authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-07-06 06:10:44+00:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-07-06 06:10:44+00:00
log8be8ebd698aac447db2babf95def4725d9ddd05f
tree9a63bcd593efed5358244bd922e7dec4b0778a92
parentad2ed457dd925c65d7d2bcac9208cee5619c523d

stage2: skeleton codegen for x64 ADD

also rework Module to take advantage of the new hash map implementation.

6 files changed, 392 insertions(+), 281 deletions(-)

src-self-hosted/Module.zig+184-205
......@@ -20,8 +20,8 @@ const ast = std.zig.ast;
2020const trace = @import("tracy.zig").trace;
2121const liveness = @import("liveness.zig");
2222
23/// General-purpose allocator.
24allocator: *Allocator,
23/// General-purpose allocator. Used for both temporary and long-term storage.
24gpa: *Allocator,
2525/// Pointer to externally managed resource.
2626root_pkg: *Package,
2727/// Module owns this resource.
......@@ -33,7 +33,7 @@ bin_file_path: []const u8,
3333/// It's rare for a decl to be exported, so we save memory by having a sparse map of
3434/// Decl pointers to details about them being exported.
3535/// The Export memory is owned by the `export_owners` table; the slice itself is owned by this table.
36decl_exports: std.AutoHashMap(*Decl, []*Export),
36decl_exports: std.AutoHashMapUnmanaged(*Decl, []*Export) = .{},
3737/// We track which export is associated with the given symbol name for quick
3838/// detection of symbol collisions.
3939symbol_exports: std.StringHashMap(*Export),
......@@ -41,9 +41,9 @@ symbol_exports: std.StringHashMap(*Export),
4141/// is modified. Note that the key of this table is not the Decl being exported, but the Decl that
4242/// is performing the export of another Decl.
4343/// This table owns the Export memory.
44export_owners: std.AutoHashMap(*Decl, []*Export),
44export_owners: std.AutoHashMapUnmanaged(*Decl, []*Export) = .{},
4545/// Maps fully qualified namespaced names to the Decl struct for them.
46decl_table: DeclTable,
46decl_table: std.HashMapUnmanaged(Scope.NameHash, *Decl, Scope.name_hash_hash, Scope.name_hash_eql, false) = .{},
4747
4848optimize_mode: std.builtin.Mode,
4949link_error_flags: link.ElfFile.ErrorFlags = .{},
......@@ -55,13 +55,13 @@ work_queue: std.fifo.LinearFifo(WorkItem, .Dynamic),
5555/// The ErrorMsg memory is owned by the decl, using Module's allocator.
5656/// Note that a Decl can succeed but the Fn it represents can fail. In this case,
5757/// a Decl can have a failed_decls entry but have analysis status of success.
58failed_decls: std.AutoHashMap(*Decl, *ErrorMsg),
58failed_decls: std.AutoHashMapUnmanaged(*Decl, *ErrorMsg) = .{},
5959/// Using a map here for consistency with the other fields here.
6060/// The ErrorMsg memory is owned by the `Scope`, using Module's allocator.
61failed_files: std.AutoHashMap(*Scope, *ErrorMsg),
61failed_files: std.AutoHashMapUnmanaged(*Scope, *ErrorMsg) = .{},
6262/// Using a map here for consistency with the other fields here.
6363/// The ErrorMsg memory is owned by the `Export`, using Module's allocator.
64failed_exports: std.AutoHashMap(*Export, *ErrorMsg),
64failed_exports: std.AutoHashMapUnmanaged(*Export, *ErrorMsg) = .{},
6565
6666/// Incrementing integer used to compare against the corresponding Decl
6767/// field to determine whether a Decl's status applies to an ongoing update, or a
......@@ -76,8 +76,6 @@ deletion_set: std.ArrayListUnmanaged(*Decl) = .{},
7676
7777keep_source_files_loaded: bool,
7878
79const DeclTable = std.HashMap(Scope.NameHash, *Decl, Scope.name_hash_hash, Scope.name_hash_eql, false);
80
8179const WorkItem = union(enum) {
8280 /// Write the machine code for a Decl to the output file.
8381 codegen_decl: *Decl,
......@@ -176,19 +174,23 @@ pub const Decl = struct {
176174
177175 /// The shallow set of other decls whose typed_value could possibly change if this Decl's
178176 /// typed_value is modified.
179 dependants: ArrayListUnmanaged(*Decl) = ArrayListUnmanaged(*Decl){},
177 dependants: DepsTable = .{},
180178 /// The shallow set of other decls whose typed_value changing indicates that this Decl's
181179 /// typed_value may need to be regenerated.
182 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);
183185
184 pub fn destroy(self: *Decl, allocator: *Allocator) void {
185 allocator.free(mem.spanZ(self.name));
186 pub fn destroy(self: *Decl, gpa: *Allocator) void {
187 gpa.free(mem.spanZ(self.name));
186188 if (self.typedValueManaged()) |tvm| {
187 tvm.deinit(allocator);
189 tvm.deinit(gpa);
188190 }
189 self.dependants.deinit(allocator);
190 self.dependencies.deinit(allocator);
191 allocator.destroy(self);
191 self.dependants.deinit(gpa);
192 self.dependencies.deinit(gpa);
193 gpa.destroy(self);
192194 }
193195
194196 pub fn src(self: Decl) usize {
......@@ -247,23 +249,11 @@ pub const Decl = struct {
247249 }
248250
249251 fn removeDependant(self: *Decl, other: *Decl) void {
250 for (self.dependants.items) |item, i| {
251 if (item == other) {
252 _ = self.dependants.swapRemove(i);
253 return;
254 }
255 }
256 unreachable;
252 self.dependants.removeAssertDiscard(other);
257253 }
258254
259255 fn removeDependency(self: *Decl, other: *Decl) void {
260 for (self.dependencies.items) |item, i| {
261 if (item == other) {
262 _ = self.dependencies.swapRemove(i);
263 return;
264 }
265 }
266 unreachable;
256 self.dependencies.removeAssertDiscard(other);
267257 }
268258};
269259
......@@ -390,10 +380,10 @@ pub const Scope = struct {
390380 }
391381 }
392382
393 pub fn unload(base: *Scope, allocator: *Allocator) void {
383 pub fn unload(base: *Scope, gpa: *Allocator) void {
394384 switch (base.tag) {
395 .file => return @fieldParentPtr(File, "base", base).unload(allocator),
396 .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),
397387 .block => unreachable,
398388 .gen_zir => unreachable,
399389 .decl => unreachable,
......@@ -422,17 +412,17 @@ pub const Scope = struct {
422412 }
423413
424414 /// Asserts the scope is a File or ZIRModule and deinitializes it, then deallocates it.
425 pub fn destroy(base: *Scope, allocator: *Allocator) void {
415 pub fn destroy(base: *Scope, gpa: *Allocator) void {
426416 switch (base.tag) {
427417 .file => {
428418 const scope_file = @fieldParentPtr(File, "base", base);
429 scope_file.deinit(allocator);
430 allocator.destroy(scope_file);
419 scope_file.deinit(gpa);
420 gpa.destroy(scope_file);
431421 },
432422 .zir_module => {
433423 const scope_zir_module = @fieldParentPtr(ZIRModule, "base", base);
434 scope_zir_module.deinit(allocator);
435 allocator.destroy(scope_zir_module);
424 scope_zir_module.deinit(gpa);
425 gpa.destroy(scope_zir_module);
436426 },
437427 .block => unreachable,
438428 .gen_zir => unreachable,
......@@ -483,7 +473,7 @@ pub const Scope = struct {
483473 /// Direct children of the file.
484474 decls: ArrayListUnmanaged(*Decl),
485475
486 pub fn unload(self: *File, allocator: *Allocator) void {
476 pub fn unload(self: *File, gpa: *Allocator) void {
487477 switch (self.status) {
488478 .never_loaded,
489479 .unloaded_parse_failure,
......@@ -497,16 +487,16 @@ pub const Scope = struct {
497487 }
498488 switch (self.source) {
499489 .bytes => |bytes| {
500 allocator.free(bytes);
490 gpa.free(bytes);
501491 self.source = .{ .unloaded = {} };
502492 },
503493 .unloaded => {},
504494 }
505495 }
506496
507 pub fn deinit(self: *File, allocator: *Allocator) void {
508 self.decls.deinit(allocator);
509 self.unload(allocator);
497 pub fn deinit(self: *File, gpa: *Allocator) void {
498 self.decls.deinit(gpa);
499 self.unload(gpa);
510500 self.* = undefined;
511501 }
512502
......@@ -528,7 +518,7 @@ pub const Scope = struct {
528518 switch (self.source) {
529519 .unloaded => {
530520 const source = try module.root_pkg.root_src_dir.readFileAllocOptions(
531 module.allocator,
521 module.gpa,
532522 self.sub_file_path,
533523 std.math.maxInt(u32),
534524 1,
......@@ -576,7 +566,7 @@ pub const Scope = struct {
576566 /// not this one.
577567 decls: ArrayListUnmanaged(*Decl),
578568
579 pub fn unload(self: *ZIRModule, allocator: *Allocator) void {
569 pub fn unload(self: *ZIRModule, gpa: *Allocator) void {
580570 switch (self.status) {
581571 .never_loaded,
582572 .unloaded_parse_failure,
......@@ -585,30 +575,30 @@ pub const Scope = struct {
585575 => {},
586576
587577 .loaded_success => {
588 self.contents.module.deinit(allocator);
589 allocator.destroy(self.contents.module);
578 self.contents.module.deinit(gpa);
579 gpa.destroy(self.contents.module);
590580 self.contents = .{ .not_available = {} };
591581 self.status = .unloaded_success;
592582 },
593583 .loaded_sema_failure => {
594 self.contents.module.deinit(allocator);
595 allocator.destroy(self.contents.module);
584 self.contents.module.deinit(gpa);
585 gpa.destroy(self.contents.module);
596586 self.contents = .{ .not_available = {} };
597587 self.status = .unloaded_sema_failure;
598588 },
599589 }
600590 switch (self.source) {
601591 .bytes => |bytes| {
602 allocator.free(bytes);
592 gpa.free(bytes);
603593 self.source = .{ .unloaded = {} };
604594 },
605595 .unloaded => {},
606596 }
607597 }
608598
609 pub fn deinit(self: *ZIRModule, allocator: *Allocator) void {
610 self.decls.deinit(allocator);
611 self.unload(allocator);
599 pub fn deinit(self: *ZIRModule, gpa: *Allocator) void {
600 self.decls.deinit(gpa);
601 self.unload(gpa);
612602 self.* = undefined;
613603 }
614604
......@@ -630,7 +620,7 @@ pub const Scope = struct {
630620 switch (self.source) {
631621 .unloaded => {
632622 const source = try module.root_pkg.root_src_dir.readFileAllocOptions(
633 module.allocator,
623 module.gpa,
634624 self.sub_file_path,
635625 std.math.maxInt(u32),
636626 1,
......@@ -701,8 +691,8 @@ pub const AllErrors = struct {
701691 msg: []const u8,
702692 };
703693
704 pub fn deinit(self: *AllErrors, allocator: *Allocator) void {
705 self.arena.promote(allocator).deinit();
694 pub fn deinit(self: *AllErrors, gpa: *Allocator) void {
695 self.arena.promote(gpa).deinit();
706696 }
707697
708698 fn add(
......@@ -772,20 +762,14 @@ pub fn init(gpa: *Allocator, options: InitOptions) !Module {
772762 };
773763
774764 return Module{
775 .allocator = gpa,
765 .gpa = gpa,
776766 .root_pkg = options.root_pkg,
777767 .root_scope = root_scope,
778768 .bin_file_dir = bin_file_dir,
779769 .bin_file_path = options.bin_file_path,
780770 .bin_file = bin_file,
781771 .optimize_mode = options.optimize_mode,
782 .decl_table = DeclTable.init(gpa),
783 .decl_exports = std.AutoHashMap(*Decl, []*Export).init(gpa),
784772 .symbol_exports = std.StringHashMap(*Export).init(gpa),
785 .export_owners = std.AutoHashMap(*Decl, []*Export).init(gpa),
786 .failed_decls = std.AutoHashMap(*Decl, *ErrorMsg).init(gpa),
787 .failed_files = std.AutoHashMap(*Scope, *ErrorMsg).init(gpa),
788 .failed_exports = std.AutoHashMap(*Export, *ErrorMsg).init(gpa),
789773 .work_queue = std.fifo.LinearFifo(WorkItem, .Dynamic).init(gpa),
790774 .keep_source_files_loaded = options.keep_source_files_loaded,
791775 };
......@@ -793,51 +777,51 @@ pub fn init(gpa: *Allocator, options: InitOptions) !Module {
793777
794778pub fn deinit(self: *Module) void {
795779 self.bin_file.deinit();
796 const allocator = self.allocator;
797 self.deletion_set.deinit(allocator);
780 const gpa = self.gpa;
781 self.deletion_set.deinit(gpa);
798782 self.work_queue.deinit();
799783
800784 for (self.decl_table.items()) |entry| {
801 entry.value.destroy(allocator);
785 entry.value.destroy(gpa);
802786 }
803 self.decl_table.deinit();
787 self.decl_table.deinit(gpa);
804788
805789 for (self.failed_decls.items()) |entry| {
806 entry.value.destroy(allocator);
790 entry.value.destroy(gpa);
807791 }
808 self.failed_decls.deinit();
792 self.failed_decls.deinit(gpa);
809793
810794 for (self.failed_files.items()) |entry| {
811 entry.value.destroy(allocator);
795 entry.value.destroy(gpa);
812796 }
813 self.failed_files.deinit();
797 self.failed_files.deinit(gpa);
814798
815799 for (self.failed_exports.items()) |entry| {
816 entry.value.destroy(allocator);
800 entry.value.destroy(gpa);
817801 }
818 self.failed_exports.deinit();
802 self.failed_exports.deinit(gpa);
819803
820804 for (self.decl_exports.items()) |entry| {
821805 const export_list = entry.value;
822 allocator.free(export_list);
806 gpa.free(export_list);
823807 }
824 self.decl_exports.deinit();
808 self.decl_exports.deinit(gpa);
825809
826810 for (self.export_owners.items()) |entry| {
827 freeExportList(allocator, entry.value);
811 freeExportList(gpa, entry.value);
828812 }
829 self.export_owners.deinit();
813 self.export_owners.deinit(gpa);
830814
831815 self.symbol_exports.deinit();
832 self.root_scope.destroy(allocator);
816 self.root_scope.destroy(gpa);
833817 self.* = undefined;
834818}
835819
836fn freeExportList(allocator: *Allocator, export_list: []*Export) void {
820fn freeExportList(gpa: *Allocator, export_list: []*Export) void {
837821 for (export_list) |exp| {
838 allocator.destroy(exp);
822 gpa.destroy(exp);
839823 }
840 allocator.free(export_list);
824 gpa.free(export_list);
841825}
842826
843827pub fn target(self: Module) std.Target {
......@@ -855,7 +839,7 @@ pub fn update(self: *Module) !void {
855839 // Until then we simulate a full cache miss. Source files could have been loaded for any reason;
856840 // to force a refresh we unload now.
857841 if (self.root_scope.cast(Scope.File)) |zig_file| {
858 zig_file.unload(self.allocator);
842 zig_file.unload(self.gpa);
859843 self.analyzeRootSrcFile(zig_file) catch |err| switch (err) {
860844 error.AnalysisFail => {
861845 assert(self.totalErrorCount() != 0);
......@@ -863,7 +847,7 @@ pub fn update(self: *Module) !void {
863847 else => |e| return e,
864848 };
865849 } else if (self.root_scope.cast(Scope.ZIRModule)) |zir_module| {
866 zir_module.unload(self.allocator);
850 zir_module.unload(self.gpa);
867851 self.analyzeRootZIRModule(zir_module) catch |err| switch (err) {
868852 error.AnalysisFail => {
869853 assert(self.totalErrorCount() != 0);
......@@ -876,7 +860,7 @@ pub fn update(self: *Module) !void {
876860
877861 // Process the deletion set.
878862 while (self.deletion_set.popOrNull()) |decl| {
879 if (decl.dependants.items.len != 0) {
863 if (decl.dependants.items().len != 0) {
880864 decl.deletion_flag = false;
881865 continue;
882866 }
......@@ -889,7 +873,7 @@ pub fn update(self: *Module) !void {
889873 // to report error messages. Otherwise we unload all source files to save memory.
890874 if (self.totalErrorCount() == 0) {
891875 if (!self.keep_source_files_loaded) {
892 self.root_scope.unload(self.allocator);
876 self.root_scope.unload(self.gpa);
893877 }
894878 try self.bin_file.flush();
895879 }
......@@ -915,10 +899,10 @@ pub fn totalErrorCount(self: *Module) usize {
915899}
916900
917901pub fn getAllErrorsAlloc(self: *Module) !AllErrors {
918 var arena = std.heap.ArenaAllocator.init(self.allocator);
902 var arena = std.heap.ArenaAllocator.init(self.gpa);
919903 errdefer arena.deinit();
920904
921 var errors = std.ArrayList(AllErrors.Message).init(self.allocator);
905 var errors = std.ArrayList(AllErrors.Message).init(self.gpa);
922906 defer errors.deinit();
923907
924908 for (self.failed_files.items()) |entry| {
......@@ -989,9 +973,9 @@ pub fn performAllTheWork(self: *Module) error{OutOfMemory}!void {
989973 }
990974 // Here we tack on additional allocations to the Decl's arena. The allocations are
991975 // lifetime annotations in the ZIR.
992 var decl_arena = decl.typed_value.most_recent.arena.?.promote(self.allocator);
976 var decl_arena = decl.typed_value.most_recent.arena.?.promote(self.gpa);
993977 defer decl.typed_value.most_recent.arena.?.* = decl_arena.state;
994 try liveness.analyze(self.allocator, &decl_arena.allocator, payload.func.analysis.success);
978 try liveness.analyze(self.gpa, &decl_arena.allocator, payload.func.analysis.success);
995979 }
996980
997981 assert(decl.typed_value.most_recent.typed_value.ty.hasCodeGenBits());
......@@ -1002,9 +986,9 @@ pub fn performAllTheWork(self: *Module) error{OutOfMemory}!void {
1002986 decl.analysis = .dependency_failure;
1003987 },
1004988 else => {
1005 try self.failed_decls.ensureCapacity(self.failed_decls.items().len + 1);
989 try self.failed_decls.ensureCapacity(self.gpa, self.failed_decls.items().len + 1);
1006990 self.failed_decls.putAssumeCapacityNoClobber(decl, try ErrorMsg.create(
1007 self.allocator,
991 self.gpa,
1008992 decl.src(),
1009993 "unable to codegen: {}",
1010994 .{@errorName(err)},
......@@ -1048,16 +1032,17 @@ fn ensureDeclAnalyzed(self: *Module, decl: *Decl) InnerError!void {
10481032 // prior to re-analysis.
10491033 self.deleteDeclExports(decl);
10501034 // Dependencies will be re-discovered, so we remove them here prior to re-analysis.
1051 for (decl.dependencies.items) |dep| {
1035 for (decl.dependencies.items()) |entry| {
1036 const dep = entry.key;
10521037 dep.removeDependant(decl);
1053 if (dep.dependants.items.len == 0 and !dep.deletion_flag) {
1038 if (dep.dependants.items().len == 0 and !dep.deletion_flag) {
10541039 // We don't perform a deletion here, because this Decl or another one
10551040 // may end up referencing it before the update is complete.
10561041 dep.deletion_flag = true;
1057 try self.deletion_set.append(self.allocator, dep);
1042 try self.deletion_set.append(self.gpa, dep);
10581043 }
10591044 }
1060 decl.dependencies.shrink(self.allocator, 0);
1045 decl.dependencies.clearRetainingCapacity();
10611046
10621047 break :blk true;
10631048 },
......@@ -1072,9 +1057,9 @@ fn ensureDeclAnalyzed(self: *Module, decl: *Decl) InnerError!void {
10721057 error.OutOfMemory => return error.OutOfMemory,
10731058 error.AnalysisFail => return error.AnalysisFail,
10741059 else => {
1075 try self.failed_decls.ensureCapacity(self.failed_decls.items().len + 1);
1060 try self.failed_decls.ensureCapacity(self.gpa, self.failed_decls.items().len + 1);
10761061 self.failed_decls.putAssumeCapacityNoClobber(decl, try ErrorMsg.create(
1077 self.allocator,
1062 self.gpa,
10781063 decl.src(),
10791064 "unable to analyze: {}",
10801065 .{@errorName(err)},
......@@ -1088,7 +1073,8 @@ fn ensureDeclAnalyzed(self: *Module, decl: *Decl) InnerError!void {
10881073 // We may need to chase the dependants and re-analyze them.
10891074 // However, if the decl is a function, and the type is the same, we do not need to.
10901075 if (type_changed or decl.typed_value.most_recent.typed_value.val.tag() != .function) {
1091 for (decl.dependants.items) |dep| {
1076 for (decl.dependants.items()) |entry| {
1077 const dep = entry.key;
10921078 switch (dep.analysis) {
10931079 .unreferenced => unreachable,
10941080 .in_progress => unreachable,
......@@ -1127,8 +1113,8 @@ fn astGenAndAnalyzeDecl(self: *Module, decl: *Decl) !bool {
11271113 // to complete the Decl analysis.
11281114 var fn_type_scope: Scope.GenZIR = .{
11291115 .decl = decl,
1130 .arena = std.heap.ArenaAllocator.init(self.allocator),
1131 .instructions = std.ArrayList(*zir.Inst).init(self.allocator),
1116 .arena = std.heap.ArenaAllocator.init(self.gpa),
1117 .instructions = std.ArrayList(*zir.Inst).init(self.gpa),
11321118 };
11331119 defer fn_type_scope.arena.deinit();
11341120 defer fn_type_scope.instructions.deinit();
......@@ -1178,7 +1164,7 @@ fn astGenAndAnalyzeDecl(self: *Module, decl: *Decl) !bool {
11781164 _ = try self.addZIRInst(&fn_type_scope.base, fn_src, zir.Inst.Return, .{ .operand = fn_type_inst }, .{});
11791165
11801166 // We need the memory for the Type to go into the arena for the Decl
1181 var decl_arena = std.heap.ArenaAllocator.init(self.allocator);
1167 var decl_arena = std.heap.ArenaAllocator.init(self.gpa);
11821168 errdefer decl_arena.deinit();
11831169 const decl_arena_state = try decl_arena.allocator.create(std.heap.ArenaAllocator.State);
11841170
......@@ -1189,7 +1175,7 @@ fn astGenAndAnalyzeDecl(self: *Module, decl: *Decl) !bool {
11891175 .instructions = .{},
11901176 .arena = &decl_arena.allocator,
11911177 };
1192 defer block_scope.instructions.deinit(self.allocator);
1178 defer block_scope.instructions.deinit(self.gpa);
11931179
11941180 const fn_type = try self.analyzeBodyValueAsType(&block_scope, .{
11951181 .instructions = fn_type_scope.instructions.items,
......@@ -1202,8 +1188,8 @@ fn astGenAndAnalyzeDecl(self: *Module, decl: *Decl) !bool {
12021188 // pass completes, and semantic analysis of it completes.
12031189 var gen_scope: Scope.GenZIR = .{
12041190 .decl = decl,
1205 .arena = std.heap.ArenaAllocator.init(self.allocator),
1206 .instructions = std.ArrayList(*zir.Inst).init(self.allocator),
1191 .arena = std.heap.ArenaAllocator.init(self.gpa),
1192 .instructions = std.ArrayList(*zir.Inst).init(self.gpa),
12071193 };
12081194 errdefer gen_scope.arena.deinit();
12091195 defer gen_scope.instructions.deinit();
......@@ -1235,7 +1221,7 @@ fn astGenAndAnalyzeDecl(self: *Module, decl: *Decl) !bool {
12351221 prev_type_has_bits = tvm.typed_value.ty.hasCodeGenBits();
12361222 type_changed = !tvm.typed_value.ty.eql(fn_type);
12371223
1238 tvm.deinit(self.allocator);
1224 tvm.deinit(self.gpa);
12391225 }
12401226
12411227 decl_arena_state.* = decl_arena.state;
......@@ -1626,40 +1612,31 @@ fn getSimplePrimitiveValue(name: []const u8) ?TypedValue {
16261612}
16271613
16281614fn declareDeclDependency(self: *Module, depender: *Decl, dependee: *Decl) !void {
1629 try depender.dependencies.ensureCapacity(self.allocator, depender.dependencies.items.len + 1);
1630 try dependee.dependants.ensureCapacity(self.allocator, dependee.dependants.items.len + 1);
1631
1632 for (depender.dependencies.items) |item| {
1633 if (item == dependee) break; // Already in the set.
1634 } else {
1635 depender.dependencies.appendAssumeCapacity(dependee);
1636 }
1615 try depender.dependencies.ensureCapacity(self.gpa, depender.dependencies.items().len + 1);
1616 try dependee.dependants.ensureCapacity(self.gpa, dependee.dependants.items().len + 1);
16371617
1638 for (dependee.dependants.items) |item| {
1639 if (item == depender) break; // Already in the set.
1640 } else {
1641 dependee.dependants.appendAssumeCapacity(depender);
1642 }
1618 depender.dependencies.putAssumeCapacity(dependee, {});
1619 dependee.dependants.putAssumeCapacity(depender, {});
16431620}
16441621
16451622fn getSrcModule(self: *Module, root_scope: *Scope.ZIRModule) !*zir.Module {
16461623 switch (root_scope.status) {
16471624 .never_loaded, .unloaded_success => {
1648 try self.failed_files.ensureCapacity(self.failed_files.items().len + 1);
1625 try self.failed_files.ensureCapacity(self.gpa, self.failed_files.items().len + 1);
16491626
16501627 const source = try root_scope.getSource(self);
16511628
16521629 var keep_zir_module = false;
1653 const zir_module = try self.allocator.create(zir.Module);
1654 defer if (!keep_zir_module) self.allocator.destroy(zir_module);
1630 const zir_module = try self.gpa.create(zir.Module);
1631 defer if (!keep_zir_module) self.gpa.destroy(zir_module);
16551632
1656 zir_module.* = try zir.parse(self.allocator, source);
1657 defer if (!keep_zir_module) zir_module.deinit(self.allocator);
1633 zir_module.* = try zir.parse(self.gpa, source);
1634 defer if (!keep_zir_module) zir_module.deinit(self.gpa);
16581635
16591636 if (zir_module.error_msg) |src_err_msg| {
16601637 self.failed_files.putAssumeCapacityNoClobber(
16611638 &root_scope.base,
1662 try ErrorMsg.create(self.allocator, src_err_msg.byte_offset, "{}", .{src_err_msg.msg}),
1639 try ErrorMsg.create(self.gpa, src_err_msg.byte_offset, "{}", .{src_err_msg.msg}),
16631640 );
16641641 root_scope.status = .unloaded_parse_failure;
16651642 return error.AnalysisFail;
......@@ -1686,22 +1663,22 @@ fn getAstTree(self: *Module, root_scope: *Scope.File) !*ast.Tree {
16861663
16871664 switch (root_scope.status) {
16881665 .never_loaded, .unloaded_success => {
1689 try self.failed_files.ensureCapacity(self.failed_files.items().len + 1);
1666 try self.failed_files.ensureCapacity(self.gpa, self.failed_files.items().len + 1);
16901667
16911668 const source = try root_scope.getSource(self);
16921669
16931670 var keep_tree = false;
1694 const tree = try std.zig.parse(self.allocator, source);
1671 const tree = try std.zig.parse(self.gpa, source);
16951672 defer if (!keep_tree) tree.deinit();
16961673
16971674 if (tree.errors.len != 0) {
16981675 const parse_err = tree.errors[0];
16991676
1700 var msg = std.ArrayList(u8).init(self.allocator);
1677 var msg = std.ArrayList(u8).init(self.gpa);
17011678 defer msg.deinit();
17021679
17031680 try parse_err.render(tree.token_ids, msg.outStream());
1704 const err_msg = try self.allocator.create(ErrorMsg);
1681 const err_msg = try self.gpa.create(ErrorMsg);
17051682 err_msg.* = .{
17061683 .msg = msg.toOwnedSlice(),
17071684 .byte_offset = tree.token_locs[parse_err.loc()].start,
......@@ -1732,11 +1709,11 @@ fn analyzeRootSrcFile(self: *Module, root_scope: *Scope.File) !void {
17321709 const decls = tree.root_node.decls();
17331710
17341711 try self.work_queue.ensureUnusedCapacity(decls.len);
1735 try root_scope.decls.ensureCapacity(self.allocator, decls.len);
1712 try root_scope.decls.ensureCapacity(self.gpa, decls.len);
17361713
17371714 // Keep track of the decls that we expect to see in this file so that
17381715 // we know which ones have been deleted.
1739 var deleted_decls = std.AutoHashMap(*Decl, void).init(self.allocator);
1716 var deleted_decls = std.AutoHashMap(*Decl, void).init(self.gpa);
17401717 defer deleted_decls.deinit();
17411718 try deleted_decls.ensureCapacity(root_scope.decls.items.len);
17421719 for (root_scope.decls.items) |file_decl| {
......@@ -1760,9 +1737,9 @@ fn analyzeRootSrcFile(self: *Module, root_scope: *Scope.File) !void {
17601737 decl.src_index = decl_i;
17611738 if (deleted_decls.remove(decl) == null) {
17621739 decl.analysis = .sema_failure;
1763 const err_msg = try ErrorMsg.create(self.allocator, tree.token_locs[name_tok].start, "redefinition of '{}'", .{decl.name});
1764 errdefer err_msg.destroy(self.allocator);
1765 try self.failed_decls.putNoClobber(decl, err_msg);
1740 const err_msg = try ErrorMsg.create(self.gpa, tree.token_locs[name_tok].start, "redefinition of '{}'", .{decl.name});
1741 errdefer err_msg.destroy(self.gpa);
1742 try self.failed_decls.putNoClobber(self.gpa, decl, err_msg);
17661743 } else {
17671744 if (!srcHashEql(decl.contents_hash, contents_hash)) {
17681745 try self.markOutdatedDecl(decl);
......@@ -1796,14 +1773,14 @@ fn analyzeRootZIRModule(self: *Module, root_scope: *Scope.ZIRModule) !void {
17961773 const src_module = try self.getSrcModule(root_scope);
17971774
17981775 try self.work_queue.ensureUnusedCapacity(src_module.decls.len);
1799 try root_scope.decls.ensureCapacity(self.allocator, src_module.decls.len);
1776 try root_scope.decls.ensureCapacity(self.gpa, src_module.decls.len);
18001777
1801 var exports_to_resolve = std.ArrayList(*zir.Decl).init(self.allocator);
1778 var exports_to_resolve = std.ArrayList(*zir.Decl).init(self.gpa);
18021779 defer exports_to_resolve.deinit();
18031780
18041781 // Keep track of the decls that we expect to see in this file so that
18051782 // we know which ones have been deleted.
1806 var deleted_decls = std.AutoHashMap(*Decl, void).init(self.allocator);
1783 var deleted_decls = std.AutoHashMap(*Decl, void).init(self.gpa);
18071784 defer deleted_decls.deinit();
18081785 try deleted_decls.ensureCapacity(self.decl_table.items().len);
18091786 for (self.decl_table.items()) |entry| {
......@@ -1845,7 +1822,7 @@ fn analyzeRootZIRModule(self: *Module, root_scope: *Scope.ZIRModule) !void {
18451822}
18461823
18471824fn deleteDecl(self: *Module, decl: *Decl) !void {
1848 try self.deletion_set.ensureCapacity(self.allocator, self.deletion_set.items.len + decl.dependencies.items.len);
1825 try self.deletion_set.ensureCapacity(self.gpa, self.deletion_set.items.len + decl.dependencies.items().len);
18491826
18501827 // Remove from the namespace it resides in. In the case of an anonymous Decl it will
18511828 // not be present in the set, and this does nothing.
......@@ -1855,9 +1832,10 @@ fn deleteDecl(self: *Module, decl: *Decl) !void {
18551832 const name_hash = decl.fullyQualifiedNameHash();
18561833 self.decl_table.removeAssertDiscard(name_hash);
18571834 // Remove itself from its dependencies, because we are about to destroy the decl pointer.
1858 for (decl.dependencies.items) |dep| {
1835 for (decl.dependencies.items()) |entry| {
1836 const dep = entry.key;
18591837 dep.removeDependant(decl);
1860 if (dep.dependants.items.len == 0 and !dep.deletion_flag) {
1838 if (dep.dependants.items().len == 0 and !dep.deletion_flag) {
18611839 // We don't recursively perform a deletion here, because during the update,
18621840 // another reference to it may turn up.
18631841 dep.deletion_flag = true;
......@@ -1865,7 +1843,8 @@ fn deleteDecl(self: *Module, decl: *Decl) !void {
18651843 }
18661844 }
18671845 // Anything that depends on this deleted decl certainly needs to be re-analyzed.
1868 for (decl.dependants.items) |dep| {
1846 for (decl.dependants.items()) |entry| {
1847 const dep = entry.key;
18691848 dep.removeDependency(decl);
18701849 if (dep.analysis != .outdated) {
18711850 // TODO Move this failure possibility to the top of the function.
......@@ -1873,11 +1852,11 @@ fn deleteDecl(self: *Module, decl: *Decl) !void {
18731852 }
18741853 }
18751854 if (self.failed_decls.remove(decl)) |entry| {
1876 entry.value.destroy(self.allocator);
1855 entry.value.destroy(self.gpa);
18771856 }
18781857 self.deleteDeclExports(decl);
18791858 self.bin_file.freeDecl(decl);
1880 decl.destroy(self.allocator);
1859 decl.destroy(self.gpa);
18811860}
18821861
18831862/// Delete all the Export objects that are caused by this Decl. Re-analysis of
......@@ -1899,7 +1878,7 @@ fn deleteDeclExports(self: *Module, decl: *Decl) void {
18991878 i += 1;
19001879 }
19011880 }
1902 decl_exports_kv.value = self.allocator.shrink(list, new_len);
1881 decl_exports_kv.value = self.gpa.shrink(list, new_len);
19031882 if (new_len == 0) {
19041883 self.decl_exports.removeAssertDiscard(exp.exported_decl);
19051884 }
......@@ -1907,12 +1886,12 @@ fn deleteDeclExports(self: *Module, decl: *Decl) void {
19071886
19081887 self.bin_file.deleteExport(exp.link);
19091888 if (self.failed_exports.remove(exp)) |entry| {
1910 entry.value.destroy(self.allocator);
1889 entry.value.destroy(self.gpa);
19111890 }
19121891 _ = self.symbol_exports.remove(exp.options.name);
1913 self.allocator.destroy(exp);
1892 self.gpa.destroy(exp);
19141893 }
1915 self.allocator.free(kv.value);
1894 self.gpa.free(kv.value);
19161895}
19171896
19181897fn analyzeFnBody(self: *Module, decl: *Decl, func: *Fn) !void {
......@@ -1920,7 +1899,7 @@ fn analyzeFnBody(self: *Module, decl: *Decl, func: *Fn) !void {
19201899 defer tracy.end();
19211900
19221901 // Use the Decl's arena for function memory.
1923 var arena = decl.typed_value.most_recent.arena.?.promote(self.allocator);
1902 var arena = decl.typed_value.most_recent.arena.?.promote(self.gpa);
19241903 defer decl.typed_value.most_recent.arena.?.* = arena.state;
19251904 var inner_block: Scope.Block = .{
19261905 .parent = null,
......@@ -1929,10 +1908,10 @@ fn analyzeFnBody(self: *Module, decl: *Decl, func: *Fn) !void {
19291908 .instructions = .{},
19301909 .arena = &arena.allocator,
19311910 };
1932 defer inner_block.instructions.deinit(self.allocator);
1911 defer inner_block.instructions.deinit(self.gpa);
19331912
19341913 const fn_zir = func.analysis.queued;
1935 defer fn_zir.arena.promote(self.allocator).deinit();
1914 defer fn_zir.arena.promote(self.gpa).deinit();
19361915 func.analysis = .{ .in_progress = {} };
19371916 //std.debug.warn("set {} to in_progress\n", .{decl.name});
19381917
......@@ -1947,7 +1926,7 @@ fn markOutdatedDecl(self: *Module, decl: *Decl) !void {
19471926 //std.debug.warn("mark {} outdated\n", .{decl.name});
19481927 try self.work_queue.writeItem(.{ .analyze_decl = decl });
19491928 if (self.failed_decls.remove(decl)) |entry| {
1950 entry.value.destroy(self.allocator);
1929 entry.value.destroy(self.gpa);
19511930 }
19521931 decl.analysis = .outdated;
19531932}
......@@ -1958,7 +1937,7 @@ fn allocateNewDecl(
19581937 src_index: usize,
19591938 contents_hash: std.zig.SrcHash,
19601939) !*Decl {
1961 const new_decl = try self.allocator.create(Decl);
1940 const new_decl = try self.gpa.create(Decl);
19621941 new_decl.* = .{
19631942 .name = "",
19641943 .scope = scope.namespace(),
......@@ -1981,10 +1960,10 @@ fn createNewDecl(
19811960 name_hash: Scope.NameHash,
19821961 contents_hash: std.zig.SrcHash,
19831962) !*Decl {
1984 try self.decl_table.ensureCapacity(self.decl_table.items().len + 1);
1963 try self.decl_table.ensureCapacity(self.gpa, self.decl_table.items().len + 1);
19851964 const new_decl = try self.allocateNewDecl(scope, src_index, contents_hash);
1986 errdefer self.allocator.destroy(new_decl);
1987 new_decl.name = try mem.dupeZ(self.allocator, u8, decl_name);
1965 errdefer self.gpa.destroy(new_decl);
1966 new_decl.name = try mem.dupeZ(self.gpa, u8, decl_name);
19881967 self.decl_table.putAssumeCapacityNoClobber(name_hash, new_decl);
19891968 return new_decl;
19901969}
......@@ -1992,7 +1971,7 @@ fn createNewDecl(
19921971fn analyzeZirDecl(self: *Module, decl: *Decl, src_decl: *zir.Decl) InnerError!bool {
19931972 var decl_scope: Scope.DeclAnalysis = .{
19941973 .decl = decl,
1995 .arena = std.heap.ArenaAllocator.init(self.allocator),
1974 .arena = std.heap.ArenaAllocator.init(self.gpa),
19961975 };
19971976 errdefer decl_scope.arena.deinit();
19981977
......@@ -2008,7 +1987,7 @@ fn analyzeZirDecl(self: *Module, decl: *Decl, src_decl: *zir.Decl) InnerError!bo
20081987 prev_type_has_bits = tvm.typed_value.ty.hasCodeGenBits();
20091988 type_changed = !tvm.typed_value.ty.eql(typed_value.ty);
20101989
2011 tvm.deinit(self.allocator);
1990 tvm.deinit(self.gpa);
20121991 }
20131992
20141993 arena_state.* = decl_scope.arena.state;
......@@ -2146,11 +2125,11 @@ fn analyzeExport(self: *Module, scope: *Scope, src: usize, symbol_name: []const
21462125 else => return self.fail(scope, src, "unable to export type '{}'", .{typed_value.ty}),
21472126 }
21482127
2149 try self.decl_exports.ensureCapacity(self.decl_exports.items().len + 1);
2150 try self.export_owners.ensureCapacity(self.export_owners.items().len + 1);
2128 try self.decl_exports.ensureCapacity(self.gpa, self.decl_exports.items().len + 1);
2129 try self.export_owners.ensureCapacity(self.gpa, self.export_owners.items().len + 1);
21512130
2152 const new_export = try self.allocator.create(Export);
2153 errdefer self.allocator.destroy(new_export);
2131 const new_export = try self.gpa.create(Export);
2132 errdefer self.gpa.destroy(new_export);
21542133
21552134 const owner_decl = scope.decl().?;
21562135
......@@ -2164,27 +2143,27 @@ fn analyzeExport(self: *Module, scope: *Scope, src: usize, symbol_name: []const
21642143 };
21652144
21662145 // Add to export_owners table.
2167 const eo_gop = self.export_owners.getOrPut(owner_decl) catch unreachable;
2146 const eo_gop = self.export_owners.getOrPut(self.gpa, owner_decl) catch unreachable;
21682147 if (!eo_gop.found_existing) {
21692148 eo_gop.entry.value = &[0]*Export{};
21702149 }
2171 eo_gop.entry.value = try self.allocator.realloc(eo_gop.entry.value, eo_gop.entry.value.len + 1);
2150 eo_gop.entry.value = try self.gpa.realloc(eo_gop.entry.value, eo_gop.entry.value.len + 1);
21722151 eo_gop.entry.value[eo_gop.entry.value.len - 1] = new_export;
2173 errdefer eo_gop.entry.value = self.allocator.shrink(eo_gop.entry.value, eo_gop.entry.value.len - 1);
2152 errdefer eo_gop.entry.value = self.gpa.shrink(eo_gop.entry.value, eo_gop.entry.value.len - 1);
21742153
21752154 // Add to exported_decl table.
2176 const de_gop = self.decl_exports.getOrPut(exported_decl) catch unreachable;
2155 const de_gop = self.decl_exports.getOrPut(self.gpa, exported_decl) catch unreachable;
21772156 if (!de_gop.found_existing) {
21782157 de_gop.entry.value = &[0]*Export{};
21792158 }
2180 de_gop.entry.value = try self.allocator.realloc(de_gop.entry.value, de_gop.entry.value.len + 1);
2159 de_gop.entry.value = try self.gpa.realloc(de_gop.entry.value, de_gop.entry.value.len + 1);
21812160 de_gop.entry.value[de_gop.entry.value.len - 1] = new_export;
2182 errdefer de_gop.entry.value = self.allocator.shrink(de_gop.entry.value, de_gop.entry.value.len - 1);
2161 errdefer de_gop.entry.value = self.gpa.shrink(de_gop.entry.value, de_gop.entry.value.len - 1);
21832162
21842163 if (self.symbol_exports.get(symbol_name)) |_| {
2185 try self.failed_exports.ensureCapacity(self.failed_exports.items().len + 1);
2164 try self.failed_exports.ensureCapacity(self.gpa, self.failed_exports.items().len + 1);
21862165 self.failed_exports.putAssumeCapacityNoClobber(new_export, try ErrorMsg.create(
2187 self.allocator,
2166 self.gpa,
21882167 src,
21892168 "exported symbol collision: {}",
21902169 .{symbol_name},
......@@ -2198,9 +2177,9 @@ fn analyzeExport(self: *Module, scope: *Scope, src: usize, symbol_name: []const
21982177 self.bin_file.updateDeclExports(self, exported_decl, de_gop.entry.value) catch |err| switch (err) {
21992178 error.OutOfMemory => return error.OutOfMemory,
22002179 else => {
2201 try self.failed_exports.ensureCapacity(self.failed_exports.items().len + 1);
2180 try self.failed_exports.ensureCapacity(self.gpa, self.failed_exports.items().len + 1);
22022181 self.failed_exports.putAssumeCapacityNoClobber(new_export, try ErrorMsg.create(
2203 self.allocator,
2182 self.gpa,
22042183 src,
22052184 "unable to export: {}",
22062185 .{@errorName(err)},
......@@ -2224,13 +2203,13 @@ fn addNewInstArgs(
22242203}
22252204
22262205fn newZIRInst(
2227 allocator: *Allocator,
2206 gpa: *Allocator,
22282207 src: usize,
22292208 comptime T: type,
22302209 positionals: std.meta.fieldInfo(T, "positionals").field_type,
22312210 kw_args: std.meta.fieldInfo(T, "kw_args").field_type,
22322211) !*zir.Inst {
2233 const inst = try allocator.create(T);
2212 const inst = try gpa.create(T);
22342213 inst.* = .{
22352214 .base = .{
22362215 .tag = T.base_tag,
......@@ -2273,7 +2252,7 @@ fn addNewInst(self: *Module, block: *Scope.Block, src: usize, ty: Type, comptime
22732252 },
22742253 .args = undefined,
22752254 };
2276 try block.instructions.append(self.allocator, &inst.base);
2255 try block.instructions.append(self.gpa, &inst.base);
22772256 return inst;
22782257}
22792258
......@@ -2433,7 +2412,7 @@ fn analyzeInst(self: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!*In
24332412fn analyzeInstStr(self: *Module, scope: *Scope, str_inst: *zir.Inst.Str) InnerError!*Inst {
24342413 // The bytes references memory inside the ZIR module, which can get deallocated
24352414 // after semantic analysis is complete. We need the memory to be in the new anonymous Decl's arena.
2436 var new_decl_arena = std.heap.ArenaAllocator.init(self.allocator);
2415 var new_decl_arena = std.heap.ArenaAllocator.init(self.gpa);
24372416 const arena_bytes = try new_decl_arena.allocator.dupe(u8, str_inst.positionals.bytes);
24382417
24392418 const ty_payload = try scope.arena().create(Type.Payload.Array_u8_Sentinel0);
......@@ -2457,8 +2436,8 @@ fn createAnonymousDecl(
24572436) !*Decl {
24582437 const name_index = self.getNextAnonNameIndex();
24592438 const scope_decl = scope.decl().?;
2460 const name = try std.fmt.allocPrint(self.allocator, "{}${}", .{ scope_decl.name, name_index });
2461 defer self.allocator.free(name);
2439 const name = try std.fmt.allocPrint(self.gpa, "{}${}", .{ scope_decl.name, name_index });
2440 defer self.gpa.free(name);
24622441 const name_hash = scope.namespace().fullyQualifiedNameHash(name);
24632442 const src_hash: std.zig.SrcHash = undefined;
24642443 const new_decl = try self.createNewDecl(scope, name, scope_decl.src_index, name_hash, src_hash);
......@@ -2554,8 +2533,8 @@ fn analyzeInstBlock(self: *Module, scope: *Scope, inst: *zir.Inst.Block) InnerEr
25542533 };
25552534 const label = &child_block.label.?;
25562535
2557 defer child_block.instructions.deinit(self.allocator);
2558 defer label.results.deinit(self.allocator);
2536 defer child_block.instructions.deinit(self.gpa);
2537 defer label.results.deinit(self.gpa);
25592538
25602539 try self.analyzeBody(&child_block.base, inst.positionals.body);
25612540
......@@ -2567,7 +2546,7 @@ fn analyzeInstBlock(self: *Module, scope: *Scope, inst: *zir.Inst.Block) InnerEr
25672546 // No need to add the Block instruction; we can add the instructions to the parent block directly.
25682547 // Blocks are terminated with a noreturn instruction which we do not want to include.
25692548 const instrs = child_block.instructions.items;
2570 try parent_block.instructions.appendSlice(self.allocator, instrs[0 .. instrs.len - 1]);
2549 try parent_block.instructions.appendSlice(self.gpa, instrs[0 .. instrs.len - 1]);
25712550 if (label.results.items.len == 1) {
25722551 return label.results.items[0];
25732552 } else {
......@@ -2577,7 +2556,7 @@ fn analyzeInstBlock(self: *Module, scope: *Scope, inst: *zir.Inst.Block) InnerEr
25772556
25782557 // Need to set the type and emit the Block instruction. This allows machine code generation
25792558 // to emit a jump instruction to after the block when it encounters the break.
2580 try parent_block.instructions.append(self.allocator, &block_inst.base);
2559 try parent_block.instructions.append(self.gpa, &block_inst.base);
25812560 block_inst.base.ty = try self.resolvePeerTypes(scope, label.results.items);
25822561 block_inst.args.body = .{ .instructions = try parent_block.arena.dupe(*Inst, child_block.instructions.items) };
25832562 return &block_inst.base;
......@@ -2596,7 +2575,7 @@ fn analyzeInstBreakVoid(self: *Module, scope: *Scope, inst: *zir.Inst.BreakVoid)
25962575 while (opt_block) |block| {
25972576 if (block.label) |*label| {
25982577 if (mem.eql(u8, label.name, label_name)) {
2599 try label.results.append(self.allocator, void_inst);
2578 try label.results.append(self.gpa, void_inst);
26002579 return self.constNoReturn(scope, inst.base.src);
26012580 }
26022581 }
......@@ -2719,8 +2698,8 @@ fn analyzeInstCall(self: *Module, scope: *Scope, inst: *zir.Inst.Call) InnerErro
27192698
27202699 // TODO handle function calls of generic functions
27212700
2722 const fn_param_types = try self.allocator.alloc(Type, fn_params_len);
2723 defer self.allocator.free(fn_param_types);
2701 const fn_param_types = try self.gpa.alloc(Type, fn_params_len);
2702 defer self.gpa.free(fn_param_types);
27242703 func.ty.fnParamTypes(fn_param_types);
27252704
27262705 const casted_args = try scope.arena().alloc(*Inst, fn_params_len);
......@@ -2739,7 +2718,7 @@ fn analyzeInstCall(self: *Module, scope: *Scope, inst: *zir.Inst.Call) InnerErro
27392718fn analyzeInstFn(self: *Module, scope: *Scope, fn_inst: *zir.Inst.Fn) InnerError!*Inst {
27402719 const fn_type = try self.resolveType(scope, fn_inst.positionals.fn_type);
27412720 const fn_zir = blk: {
2742 var fn_arena = std.heap.ArenaAllocator.init(self.allocator);
2721 var fn_arena = std.heap.ArenaAllocator.init(self.gpa);
27432722 errdefer fn_arena.deinit();
27442723
27452724 const fn_zir = try scope.arena().create(Fn.ZIR);
......@@ -3120,7 +3099,7 @@ fn analyzeInstCondBr(self: *Module, scope: *Scope, inst: *zir.Inst.CondBr) Inner
31203099 .instructions = .{},
31213100 .arena = parent_block.arena,
31223101 };
3123 defer true_block.instructions.deinit(self.allocator);
3102 defer true_block.instructions.deinit(self.gpa);
31243103 try self.analyzeBody(&true_block.base, inst.positionals.true_body);
31253104
31263105 var false_block: Scope.Block = .{
......@@ -3130,7 +3109,7 @@ fn analyzeInstCondBr(self: *Module, scope: *Scope, inst: *zir.Inst.CondBr) Inner
31303109 .instructions = .{},
31313110 .arena = parent_block.arena,
31323111 };
3133 defer false_block.instructions.deinit(self.allocator);
3112 defer false_block.instructions.deinit(self.gpa);
31343113 try self.analyzeBody(&false_block.base, inst.positionals.false_body);
31353114
31363115 return self.addNewInstArgs(parent_block, inst.base.src, Type.initTag(.void), Inst.CondBr, Inst.Args(Inst.CondBr){
......@@ -3284,7 +3263,7 @@ fn cmpNumeric(
32843263 return self.constUndef(scope, src, Type.initTag(.bool));
32853264 const is_unsigned = if (lhs_is_float) x: {
32863265 var bigint_space: Value.BigIntSpace = undefined;
3287 var bigint = try lhs_val.toBigInt(&bigint_space).toManaged(self.allocator);
3266 var bigint = try lhs_val.toBigInt(&bigint_space).toManaged(self.gpa);
32883267 defer bigint.deinit();
32893268 const zcmp = lhs_val.orderAgainstZero();
32903269 if (lhs_val.floatHasFraction()) {
......@@ -3319,7 +3298,7 @@ fn cmpNumeric(
33193298 return self.constUndef(scope, src, Type.initTag(.bool));
33203299 const is_unsigned = if (rhs_is_float) x: {
33213300 var bigint_space: Value.BigIntSpace = undefined;
3322 var bigint = try rhs_val.toBigInt(&bigint_space).toManaged(self.allocator);
3301 var bigint = try rhs_val.toBigInt(&bigint_space).toManaged(self.gpa);
33233302 defer bigint.deinit();
33243303 const zcmp = rhs_val.orderAgainstZero();
33253304 if (rhs_val.floatHasFraction()) {
......@@ -3457,7 +3436,7 @@ fn coerceArrayPtrToSlice(self: *Module, scope: *Scope, dest_type: Type, inst: *I
34573436
34583437fn fail(self: *Module, scope: *Scope, src: usize, comptime format: []const u8, args: var) InnerError {
34593438 @setCold(true);
3460 const err_msg = try ErrorMsg.create(self.allocator, src, format, args);
3439 const err_msg = try ErrorMsg.create(self.gpa, src, format, args);
34613440 return self.failWithOwnedErrorMsg(scope, src, err_msg);
34623441}
34633442
......@@ -3487,9 +3466,9 @@ fn failNode(
34873466
34883467fn failWithOwnedErrorMsg(self: *Module, scope: *Scope, src: usize, err_msg: *ErrorMsg) InnerError {
34893468 {
3490 errdefer err_msg.destroy(self.allocator);
3491 try self.failed_decls.ensureCapacity(self.failed_decls.items().len + 1);
3492 try self.failed_files.ensureCapacity(self.failed_files.items().len + 1);
3469 errdefer err_msg.destroy(self.gpa);
3470 try self.failed_decls.ensureCapacity(self.gpa, self.failed_decls.items().len + 1);
3471 try self.failed_files.ensureCapacity(self.gpa, self.failed_files.items().len + 1);
34933472 }
34943473 switch (scope.tag) {
34953474 .decl => {
......@@ -3542,28 +3521,28 @@ pub const ErrorMsg = struct {
35423521 byte_offset: usize,
35433522 msg: []const u8,
35443523
3545 pub fn create(allocator: *Allocator, byte_offset: usize, comptime format: []const u8, args: var) !*ErrorMsg {
3546 const self = try allocator.create(ErrorMsg);
3547 errdefer allocator.destroy(self);
3548 self.* = try init(allocator, byte_offset, format, args);
3524 pub fn create(gpa: *Allocator, byte_offset: usize, comptime format: []const u8, args: var) !*ErrorMsg {
3525 const self = try gpa.create(ErrorMsg);
3526 errdefer gpa.destroy(self);
3527 self.* = try init(gpa, byte_offset, format, args);
35493528 return self;
35503529 }
35513530
35523531 /// Assumes the ErrorMsg struct and msg were both allocated with allocator.
3553 pub fn destroy(self: *ErrorMsg, allocator: *Allocator) void {
3554 self.deinit(allocator);
3555 allocator.destroy(self);
3532 pub fn destroy(self: *ErrorMsg, gpa: *Allocator) void {
3533 self.deinit(gpa);
3534 gpa.destroy(self);
35563535 }
35573536
3558 pub fn init(allocator: *Allocator, byte_offset: usize, comptime format: []const u8, args: var) !ErrorMsg {
3537 pub fn init(gpa: *Allocator, byte_offset: usize, comptime format: []const u8, args: var) !ErrorMsg {
35593538 return ErrorMsg{
35603539 .byte_offset = byte_offset,
3561 .msg = try std.fmt.allocPrint(allocator, format, args),
3540 .msg = try std.fmt.allocPrint(gpa, format, args),
35623541 };
35633542 }
35643543
3565 pub fn deinit(self: *ErrorMsg, allocator: *Allocator) void {
3566 allocator.free(self.msg);
3544 pub fn deinit(self: *ErrorMsg, gpa: *Allocator) void {
3545 gpa.free(self.msg);
35673546 self.* = undefined;
35683547 }
35693548};
src-self-hosted/codegen.zig+186-65
......@@ -46,7 +46,14 @@ pub fn generateSymbol(
4646 var mc_args = try std.ArrayList(Function.MCValue).initCapacity(bin_file.allocator, param_types.len);
4747 defer mc_args.deinit();
4848
49 var next_stack_offset: u64 = 0;
49 var branch_stack = std.ArrayList(Function.Branch).init(bin_file.allocator);
50 defer {
51 assert(branch_stack.items.len == 1);
52 branch_stack.items[0].deinit(bin_file.allocator);
53 branch_stack.deinit();
54 }
55 const branch = try branch_stack.addOne();
56 branch.* = .{};
5057
5158 switch (fn_type.fnCallingConvention()) {
5259 .Naked => assert(mc_args.items.len == 0),
......@@ -61,8 +68,8 @@ pub fn generateSymbol(
6168 switch (param_type.zigTypeTag()) {
6269 .Bool, .Int => {
6370 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);
71 try mc_args.append(.{ .stack_offset = branch.next_stack_offset });
72 branch.next_stack_offset += @intCast(u32, param_type.abiSize(bin_file.options.target));
6673 } else {
6774 try mc_args.append(.{ .register = @enumToInt(integer_registers[next_int_reg]) });
6875 next_int_reg += 1;
......@@ -100,23 +107,17 @@ pub fn generateSymbol(
100107 }
101108
102109 var function = Function{
110 .gpa = bin_file.allocator,
103111 .target = &bin_file.options.target,
104112 .bin_file = bin_file,
105113 .mod_fn = module_fn,
106114 .code = code,
107115 .err_msg = null,
108116 .args = mc_args.items,
109 .branch_stack = .{},
117 .branch_stack = &branch_stack,
110118 };
111 defer {
112 assert(function.branch_stack.items.len == 1);
113 function.branch_stack.items[0].inst_table.deinit();
114 function.branch_stack.deinit(bin_file.allocator);
115 }
116 try function.branch_stack.append(bin_file.allocator, .{
117 .inst_table = std.AutoHashMap(*ir.Inst, Function.MCValue).init(bin_file.allocator),
118 });
119119
120 branch.max_end_stack = branch.next_stack_offset;
120121 function.gen() catch |err| switch (err) {
121122 error.CodegenFail => return Result{ .fail = function.err_msg.? },
122123 else => |e| return e,
......@@ -218,6 +219,7 @@ pub fn generateSymbol(
218219}
219220
220221const Function = struct {
222 gpa: *Allocator,
221223 bin_file: *link.ElfFile,
222224 target: *const std.Target,
223225 mod_fn: *const Module.Fn,
......@@ -232,10 +234,37 @@ const Function = struct {
232234 /// within different branches. Special consideration is needed when a branch
233235 /// joins with its parent, to make sure all instructions have the same MCValue
234236 /// across each runtime branch upon joining.
235 branch_stack: std.ArrayListUnmanaged(Branch),
237 branch_stack: *std.ArrayList(Branch),
236238
237239 const Branch = struct {
238 inst_table: std.AutoHashMap(*ir.Inst, MCValue),
240 inst_table: std.AutoHashMapUnmanaged(*ir.Inst, MCValue) = .{},
241
242 /// The key is an enum value of an arch-specific register.
243 registers: std.AutoHashMapUnmanaged(usize, RegisterAllocation) = .{},
244
245 /// Maps offset to what is stored there.
246 stack: std.AutoHashMapUnmanaged(usize, StackAllocation) = .{},
247 /// Offset from the stack base, representing the end of the stack frame.
248 max_end_stack: u32 = 0,
249 /// Represents the current end stack offset. If there is no existing slot
250 /// to place a new stack allocation, it goes here, and then bumps `max_end_stack`.
251 next_stack_offset: u32 = 0,
252
253 fn deinit(self: *Branch, gpa: *Allocator) void {
254 self.inst_table.deinit(gpa);
255 self.registers.deinit(gpa);
256 self.stack.deinit(gpa);
257 self.* = undefined;
258 }
259 };
260
261 const RegisterAllocation = struct {
262 inst: *ir.Inst,
263 };
264
265 const StackAllocation = struct {
266 inst: *ir.Inst,
267 size: u32,
239268 };
240269
241270 const MCValue = union(enum) {
......@@ -256,6 +285,13 @@ const Function = struct {
256285 memory: u64,
257286 /// The value is one of the stack variables.
258287 stack_offset: u64,
288
289 fn isMemory(mcv: MCValue) bool {
290 return switch (mcv) {
291 .embedded_in_code, .memory, .stack_offset => true,
292 else => false,
293 };
294 }
259295 };
260296
261297 fn gen(self: *Function) !void {
......@@ -318,7 +354,7 @@ const Function = struct {
318354 const inst_table = &self.branch_stack.items[0].inst_table;
319355 for (self.mod_fn.analysis.success.instructions) |inst| {
320356 const new_inst = try self.genFuncInst(inst, arch);
321 try inst_table.putNoClobber(inst, new_inst);
357 try inst_table.putNoClobber(self.gpa, inst, new_inst);
322358 }
323359 }
324360
......@@ -344,19 +380,99 @@ const Function = struct {
344380 }
345381
346382 fn genAdd(self: *Function, inst: *ir.Inst.Add, comptime arch: std.Target.Cpu.Arch) !MCValue {
347 const lhs = try self.resolveInst(inst.args.lhs);
348 const rhs = try self.resolveInst(inst.args.rhs);
383 // No side effects, so if it's unreferenced, do nothing.
384 if (inst.base.isUnused())
385 return MCValue.dead;
349386 switch (arch) {
350 .i386, .x86_64 => {
351 // const lhs_reg = try self.instAsReg(lhs);
352 // const rhs_reg = try self.instAsReg(rhs);
353 // const result = try self.allocateReg();
354
355 // try self.code.append(??);
387 .x86_64 => {
388 // Biggest encoding of ADD is 8 bytes.
389 try self.code.ensureCapacity(self.code.items.len + 8);
390
391 // In x86, ADD has 2 operands, destination and source.
392 // Either one, but not both, can be a memory operand.
393 // Source operand can be an immediate, 8 bits or 32 bits.
394 // So, if either one of the operands dies with this instruction, we can use it
395 // as the result MCValue.
396 var dst_mcv: MCValue = undefined;
397 var src_mcv: MCValue = undefined;
398 if (inst.base.operandDies(0)) {
399 // LHS dies; use it as the destination.
400 dst_mcv = try self.resolveInst(inst.args.lhs);
401 // Both operands cannot be memory.
402 if (dst_mcv.isMemory()) {
403 src_mcv = try self.resolveInstImmOrReg(inst.args.rhs);
404 } else {
405 src_mcv = try self.resolveInst(inst.args.rhs);
406 }
407 } else if (inst.base.operandDies(1)) {
408 // RHS dies; use it as the destination.
409 dst_mcv = try self.resolveInst(inst.args.rhs);
410 // Both operands cannot be memory.
411 if (dst_mcv.isMemory()) {
412 src_mcv = try self.resolveInstImmOrReg(inst.args.lhs);
413 } else {
414 src_mcv = try self.resolveInst(inst.args.lhs);
415 }
416 } else {
417 const lhs = try self.resolveInst(inst.args.lhs);
418 const rhs = try self.resolveInst(inst.args.rhs);
419 if (lhs.isMemory()) {
420 dst_mcv = try self.copyToNewRegister(inst.base.src, lhs);
421 src_mcv = rhs;
422 } else {
423 dst_mcv = try self.copyToNewRegister(inst.base.src, rhs);
424 src_mcv = lhs;
425 }
426 }
427 // x86 ADD supports only signed 32-bit immediates at most. If the immediate
428 // value is larger than this, we put it in a register.
429 // A potential opportunity for future optimization here would be keeping track
430 // of the fact that the instruction is available both as an immediate
431 // and as a register.
432 switch (src_mcv) {
433 .immediate => |imm| {
434 if (imm > std.math.maxInt(u31)) {
435 src_mcv = try self.copyToNewRegister(inst.base.src, src_mcv);
436 }
437 },
438 else => {},
439 }
356440
357 // lhs_reg.release();
358 // rhs_reg.release();
359 return self.fail(inst.base.src, "TODO implement register allocation", .{});
441 switch (dst_mcv) {
442 .none => unreachable,
443 .dead, .unreach, .immediate => unreachable,
444 .register => |dst_reg_usize| {
445 const dst_reg = @intToEnum(Reg(arch), @intCast(@TagType(Reg(arch)), dst_reg_usize));
446 switch (src_mcv) {
447 .none => unreachable,
448 .dead, .unreach => unreachable,
449 .register => |src_reg_usize| {
450 const src_reg = @intToEnum(Reg(arch), @intCast(@TagType(Reg(arch)), src_reg_usize));
451 self.rex(.{ .b = dst_reg.isExtended(), .r = src_reg.isExtended(), .w = dst_reg.size() == 64 });
452 self.code.appendSliceAssumeCapacity(&[_]u8{ 0x1, 0xC0 | (@as(u8, src_reg.id() & 0b111) << 3) | @as(u8, dst_reg.id() & 0b111) });
453 },
454 .immediate => |imm| {
455 const imm32 = @intCast(u31, imm); // We handle this case above.
456 // 81 /0 id
457 if (imm32 <= std.math.maxInt(u7)) {
458 self.rex(.{ .b = dst_reg.isExtended(), .w = dst_reg.size() == 64 });
459 self.code.appendSliceAssumeCapacity(&[_]u8{ 0x83, 0xC0 | @as(u8, dst_reg.id() & 0b111), @intCast(u8, imm32)});
460 } else {
461 self.rex(.{ .r = dst_reg.isExtended(), .w = dst_reg.size() == 64 });
462 self.code.appendSliceAssumeCapacity(&[_]u8{ 0x81, 0xC0 | @as(u8, dst_reg.id() & 0b111) });
463 std.mem.writeIntLittle(u32, self.code.addManyAsArrayAssumeCapacity(4), imm32);
464 }
465 },
466 .embedded_in_code, .memory, .stack_offset => {
467 return self.fail(inst.base.src, "TODO implement x86 add source memory", .{});
468 },
469 }
470 },
471 .embedded_in_code, .memory, .stack_offset => {
472 return self.fail(inst.base.src, "TODO implement x86 add destination memory", .{});
473 },
474 }
475 return dst_mcv;
360476 },
361477 else => return self.fail(inst.base.src, "TODO implement add for {}", .{self.target.cpu.arch}),
362478 }
......@@ -526,23 +642,23 @@ const Function = struct {
526642 /// resulting REX is meaningful, but will remain the same if it is not.
527643 /// * Deliberately inserting a "meaningless REX" requires explicit usage of
528644 /// 0x40, and cannot be done via this function.
529 fn REX(self: *Function, arg: struct { B: bool = false, W: bool = false, X: bool = false, R: bool = false }) !void {
645 fn rex(self: *Function, arg: struct { b: bool = false, w: bool = false, x: bool = false, r: bool = false }) void {
530646 // From section 2.2.1.2 of the manual, REX is encoded as b0100WRXB.
531647 var value: u8 = 0x40;
532 if (arg.B) {
648 if (arg.b) {
533649 value |= 0x1;
534650 }
535 if (arg.X) {
651 if (arg.x) {
536652 value |= 0x2;
537653 }
538 if (arg.R) {
654 if (arg.r) {
539655 value |= 0x4;
540656 }
541 if (arg.W) {
657 if (arg.w) {
542658 value |= 0x8;
543659 }
544660 if (value != 0x40) {
545 try self.code.append(value);
661 self.code.appendAssumeCapacity(value);
546662 }
547663 }
548664
......@@ -570,11 +686,11 @@ const Function = struct {
570686 // If we're accessing e.g. r8d, we need to use a REX prefix before the actual operation. Since
571687 // this is a 32-bit operation, the W flag is set to zero. X is also zero, as we're not using a SIB.
572688 // Both R and B are set, as we're extending, in effect, the register bits *and* the operand.
573 try self.REX(.{ .R = reg.isExtended(), .B = reg.isExtended() });
689 try self.code.ensureCapacity(self.code.items.len + 3);
690 self.rex(.{ .r = reg.isExtended(), .b = reg.isExtended() });
574691 const id = @as(u8, reg.id() & 0b111);
575 return self.code.appendSlice(&[_]u8{
576 0x31, 0xC0 | id << 3 | id,
577 });
692 self.code.appendSliceAssumeCapacity(&[_]u8{ 0x31, 0xC0 | id << 3 | id });
693 return;
578694 }
579695 if (x <= std.math.maxInt(u32)) {
580696 // Next best case: if we set the lower four bytes, the upper four will be zeroed.
......@@ -607,9 +723,9 @@ const Function = struct {
607723 // Since we always need a REX here, let's just check if we also need to set REX.B.
608724 //
609725 // In this case, the encoding of the REX byte is 0b0100100B
610
611 try self.REX(.{ .W = true, .B = reg.isExtended() });
612 try self.code.resize(self.code.items.len + 9);
726 try self.code.ensureCapacity(self.code.items.len + 10);
727 self.rex(.{ .w = true, .b = reg.isExtended() });
728 self.code.items.len += 9;
613729 self.code.items[self.code.items.len - 9] = 0xB8 | @as(u8, reg.id() & 0b111);
614730 const imm_ptr = self.code.items[self.code.items.len - 8 ..][0..8];
615731 mem.writeIntLittle(u64, imm_ptr, x);
......@@ -620,13 +736,13 @@ const Function = struct {
620736 }
621737 // We need the offset from RIP in a signed i32 twos complement.
622738 // The instruction is 7 bytes long and RIP points to the next instruction.
623 //
739 try self.code.ensureCapacity(self.code.items.len + 7);
624740 // 64-bit LEA is encoded as REX.W 8D /r. If the register is extended, the REX byte is modified,
625741 // but the operation size is unchanged. Since we're using a disp32, we want mode 0 and lower three
626742 // bits as five.
627743 // REX 0x8D 0b00RRR101, where RRR is the lower three bits of the id.
628 try self.REX(.{ .W = true, .B = reg.isExtended() });
629 try self.code.resize(self.code.items.len + 6);
744 self.rex(.{ .w = true, .b = reg.isExtended() });
745 self.code.items.len += 6;
630746 const rip = self.code.items.len;
631747 const big_offset = @intCast(i64, code_offset) - @intCast(i64, rip);
632748 const offset = @intCast(i32, big_offset);
......@@ -646,9 +762,10 @@ const Function = struct {
646762 // If the *source* is extended, the B field must be 1.
647763 // Since the register is being accessed directly, the R/M mode is three. The reg field (the middle
648764 // three bits) contain the destination, and the R/M field (the lower three bits) contain the source.
649 try self.REX(.{ .W = true, .R = reg.isExtended(), .B = src_reg.isExtended() });
765 try self.code.ensureCapacity(self.code.items.len + 3);
766 self.rex(.{ .w = true, .r = reg.isExtended(), .b = src_reg.isExtended() });
650767 const R = 0xC0 | (@as(u8, reg.id() & 0b111) << 3) | @as(u8, src_reg.id() & 0b111);
651 try self.code.appendSlice(&[_]u8{ 0x8B, R });
768 self.code.appendSliceAssumeCapacity(&[_]u8{ 0x8B, R });
652769 },
653770 .memory => |x| {
654771 if (reg.size() != 64) {
......@@ -662,14 +779,14 @@ const Function = struct {
662779 // The SIB must be 0x25, to indicate a disp32 with no scaled index.
663780 // 0b00RRR100, where RRR is the lower three bits of the register ID.
664781 // The instruction is thus eight bytes; REX 0x8B 0b00RRR100 0x25 followed by a four-byte disp32.
665 try self.REX(.{ .W = true, .B = reg.isExtended() });
666 try self.code.resize(self.code.items.len + 7);
667 const r = 0x04 | (@as(u8, reg.id() & 0b111) << 3);
668 self.code.items[self.code.items.len - 7] = 0x8B;
669 self.code.items[self.code.items.len - 6] = r;
670 self.code.items[self.code.items.len - 5] = 0x25;
671 const imm_ptr = self.code.items[self.code.items.len - 4 ..][0..4];
672 mem.writeIntLittle(u32, imm_ptr, @intCast(u32, x));
782 try self.code.ensureCapacity(self.code.items.len + 8);
783 self.rex(.{ .w = true, .b = reg.isExtended() });
784 self.code.appendSliceAssumeCapacity(&[_]u8{
785 0x8B,
786 0x04 | (@as(u8, reg.id() & 0b111) << 3), // R
787 0x25,
788 });
789 mem.writeIntLittle(u32, self.code.addManyAsArrayAssumeCapacity(4), @intCast(u32, x));
673790 } else {
674791 // If this is RAX, we can use a direct load; otherwise, we need to load the address, then indirectly load
675792 // the value.
......@@ -700,15 +817,15 @@ const Function = struct {
700817 // Currently, we're only allowing 64-bit registers, so we need the `REX.W 8B /r` variant.
701818 // TODO: determine whether to allow other sized registers, and if so, handle them properly.
702819 // This operation requires three bytes: REX 0x8B R/M
703 //
820 try self.code.ensureCapacity(self.code.items.len + 3);
704821 // For this operation, we want R/M mode *zero* (use register indirectly), and the two register
705822 // values must match. Thus, it's 00ABCABC where ABC is the lower three bits of the register ID.
706823 //
707824 // Furthermore, if this is an extended register, both B and R must be set in the REX byte, as *both*
708825 // register operands need to be marked as extended.
709 try self.REX(.{ .W = true, .B = reg.isExtended(), .R = reg.isExtended() });
826 self.rex(.{ .w = true, .b = reg.isExtended(), .r = reg.isExtended() });
710827 const RM = (@as(u8, reg.id() & 0b111) << 3) | @truncate(u3, reg.id());
711 try self.code.appendSlice(&[_]u8{ 0x8B, RM });
828 self.code.appendSliceAssumeCapacity(&[_]u8{ 0x8B, RM });
712829 }
713830 }
714831 },
......@@ -731,36 +848,40 @@ const Function = struct {
731848 }
732849
733850 fn resolveInst(self: *Function, inst: *ir.Inst) !MCValue {
734 if (self.inst_table.get(inst)) |mcv| {
735 return mcv;
736 }
737851 // Constants have static lifetimes, so they are always memoized in the outer most table.
738852 if (inst.cast(ir.Inst.Constant)) |const_inst| {
739853 const branch = &self.branch_stack.items[0];
740 const gop = try branch.inst_table.getOrPut(inst);
854 const gop = try branch.inst_table.getOrPut(self.gpa, inst);
741855 if (!gop.found_existing) {
742856 const mcv = try self.genTypedValue(inst.src, .{ .ty = inst.ty, .val = const_inst.val });
743 try branch.inst_table.putNoClobber(inst, mcv);
744 gop.kv.value = mcv;
857 try branch.inst_table.putNoClobber(self.gpa, inst, mcv);
858 gop.entry.value = mcv;
745859 return mcv;
746860 }
747 return gop.kv.value;
861 return gop.entry.value;
748862 }
749863
750864 // Treat each stack item as a "layer" on top of the previous one.
751865 var i: usize = self.branch_stack.items.len;
752866 while (true) {
753867 i -= 1;
754 if (self.branch_stack.items[i].inst_table.getValue(inst)) |mcv| {
868 if (self.branch_stack.items[i].inst_table.get(inst)) |mcv| {
755869 return mcv;
756870 }
757871 }
758872 }
759873
874 fn resolveInstImmOrReg(self: *Function, inst: *ir.Inst) !MCValue {
875 return self.fail(inst.src, "TODO implement resolveInstImmOrReg", .{});
876 }
877
878 fn copyToNewRegister(self: *Function, src: usize, mcv: MCValue) !MCValue {
879 return self.fail(src, "TODO implement copyToNewRegister", .{});
880 }
881
760882 fn genTypedValue(self: *Function, src: usize, typed_value: TypedValue) !MCValue {
761883 const ptr_bits = self.target.cpu.arch.ptrBitWidth();
762884 const ptr_bytes: u64 = @divExact(ptr_bits, 8);
763 const allocator = self.code.allocator;
764885 switch (typed_value.ty.zigTypeTag()) {
765886 .Pointer => {
766887 if (typed_value.val.cast(Value.Payload.DeclRef)) |payload| {
......@@ -787,7 +908,7 @@ const Function = struct {
787908 fn fail(self: *Function, src: usize, comptime format: []const u8, args: var) error{ CodegenFail, OutOfMemory } {
788909 @setCold(true);
789910 assert(self.err_msg == null);
790 self.err_msg = try ErrorMsg.create(self.code.allocator, src, format, args);
911 self.err_msg = try ErrorMsg.create(self.bin_file.allocator, src, format, args);
791912 return error.CodegenFail;
792913 }
793914};
src-self-hosted/ir.zig+16-5
......@@ -2,6 +2,7 @@ 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;
56
67/// These are in-memory, analyzed instructions. See `zir.Inst` for the representation
78/// of instructions that correspond to the ZIR text format.
......@@ -12,18 +13,28 @@ pub const Inst = struct {
1213 tag: Tag,
1314 /// Each bit represents the index of an `Inst` parameter in the `args` field.
1415 /// If a bit is set, it marks the end of the lifetime of the corresponding
15 /// instruction parameter. For example, 0b00000101 means that the first and
16 /// instruction parameter. For example, 0b000_00101 means that the first and
1617 /// third `Inst` parameters' lifetimes end after this instruction, and will
1718 /// not have any more following references.
1819 /// The most significant bit being set means that the instruction itself is
1920 /// never referenced, in other words its lifetime ends as soon as it finishes.
20 /// If the byte is `0xff`, it means this is a special case and this data is
21 /// encoded elsewhere.
22 deaths: u8 = 0xff,
21 /// If bit 7 (0b1xxx_xxxx) is set, it means this instruction itself is unreferenced.
22 /// If bit 6 (0bx1xx_xxxx) is set, it means this is a special case and the
23 /// lifetimes of operands are encoded elsewhere.
24 deaths: u8 = undefined,
2325 ty: Type,
2426 /// Byte offset into the source.
2527 src: usize,
2628
29 pub fn isUnused(self: Inst) bool {
30 return (self.deaths & 0b1000_0000) != 0;
31 }
32
33 pub fn operandDies(self: Inst, index: u3) bool {
34 assert(index < 6);
35 return @truncate(u1, self.deaths << index) != 0;
36 }
37
2738 pub const Tag = enum {
2839 add,
2940 arg,
......@@ -240,4 +251,4 @@ pub const Inst = struct {
240251
241252pub const Body = struct {
242253 instructions: []*Inst,
243};
\ No newline at end of file
254};
src-self-hosted/link.zig+3-3
......@@ -1007,7 +1007,7 @@ pub const ElfFile = struct {
10071007 .appended => code_buffer.items,
10081008 .fail => |em| {
10091009 decl.analysis = .codegen_failure;
1010 _ = try module.failed_decls.put(decl, em);
1010 _ = try module.failed_decls.put(module.gpa, decl, em);
10111011 return;
10121012 },
10131013 };
......@@ -1093,7 +1093,7 @@ pub const ElfFile = struct {
10931093 for (exports) |exp| {
10941094 if (exp.options.section) |section_name| {
10951095 if (!mem.eql(u8, section_name, ".text")) {
1096 try module.failed_exports.ensureCapacity(module.failed_exports.items().len + 1);
1096 try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.items().len + 1);
10971097 module.failed_exports.putAssumeCapacityNoClobber(
10981098 exp,
10991099 try Module.ErrorMsg.create(self.allocator, 0, "Unimplemented: ExportOptions.section", .{}),
......@@ -1111,7 +1111,7 @@ pub const ElfFile = struct {
11111111 },
11121112 .Weak => elf.STB_WEAK,
11131113 .LinkOnce => {
1114 try module.failed_exports.ensureCapacity(module.failed_exports.items().len + 1);
1114 try module.failed_exports.ensureCapacity(module.gpa, module.failed_exports.items().len + 1);
11151115 module.failed_exports.putAssumeCapacityNoClobber(
11161116 exp,
11171117 try Module.ErrorMsg.create(self.allocator, 0, "Unimplemented: GlobalLinkage.LinkOnce", .{}),
src-self-hosted/liveness.zig+2-2
......@@ -123,7 +123,7 @@ fn analyzeInst(arena: *std.mem.Allocator, table: *std.AutoHashMap(*ir.Inst, void
123123 if (arg_index >= 6) {
124124 @compileError("out of bits to mark deaths of operands");
125125 }
126 const prev = try table.put(@field(inst.args, field.name), {});
126 const prev = try table.fetchPut(@field(inst.args, field.name), {});
127127 if (prev == null) {
128128 // Death.
129129 inst.base.deaths |= 1 << arg_index;
......@@ -131,4 +131,4 @@ fn analyzeInst(arena: *std.mem.Allocator, table: *std.AutoHashMap(*ir.Inst, void
131131 arg_index += 1;
132132 }
133133 }
134}
\ No newline at end of file
134}
src-self-hosted/main.zig+1-1
......@@ -502,7 +502,7 @@ fn updateModule(gpa: *Allocator, module: *Module, zir_out_path: ?[]const u8) !vo
502502 const update_nanos = timer.read();
503503
504504 var errors = try module.getAllErrorsAlloc();
505 defer errors.deinit(module.allocator);
505 defer errors.deinit(module.gpa);
506506
507507 if (errors.list.len != 0) {
508508 for (errors.list) |full_err_msg| {