authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2024-07-08 16:00:28-04:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2024-07-08 16:00:28-04:00
logab4eeb770a0af411d525616dcdbfa4a8491f8ac0
treed19b6b0cdb71a7e0f6bc65379441992753979a4a
parent8f20e81b8816aadd8ceb1b04bd3727cc1d124464
parent65ced4a33436fa762de75e22a986ae08a8c0d9cc
signaturebadge-check Signed by PGP key B5690EEEBB952194

Merge pull request #20528 from jacobly0/tsip

InternPool: begin conversion to thread-safe data structure

61 files changed, 15011 insertions(+), 12550 deletions(-)

CMakeLists.txt+1
......@@ -525,6 +525,7 @@ set(ZIG_STAGE2_SOURCES
525525 src/Type.zig
526526 src/Value.zig
527527 src/Zcu.zig
528 src/Zcu/PerThread.zig
528529 src/arch/aarch64/CodeGen.zig
529530 src/arch/aarch64/Emit.zig
530531 src/arch/aarch64/Mir.zig
lib/std/Progress.zig+1-1
......@@ -282,7 +282,7 @@ pub const Node = struct {
282282 }
283283
284284 fn init(free_index: Index, parent: Parent, name: []const u8, estimated_total_items: usize) Node {
285 assert(parent != .unused);
285 assert(parent == .none or @intFromEnum(parent) < node_storage_buffer_len);
286286
287287 const storage = storageByIndex(free_index);
288288 storage.* = .{
lib/std/Thread.zig+6-1
......@@ -280,12 +280,13 @@ pub fn getCurrentId() Id {
280280pub const CpuCountError = error{
281281 PermissionDenied,
282282 SystemResources,
283 Unsupported,
283284 Unexpected,
284285};
285286
286287/// Returns the platforms view on the number of logical CPU cores available.
287288pub fn getCpuCount() CpuCountError!usize {
288 return Impl.getCpuCount();
289 return try Impl.getCpuCount();
289290}
290291
291292/// Configuration options for hints on how to spawn threads.
......@@ -782,6 +783,10 @@ const WasiThreadImpl = struct {
782783 return tls_thread_id;
783784 }
784785
786 fn getCpuCount() error{Unsupported}!noreturn {
787 return error.Unsupported;
788 }
789
785790 fn getHandle(self: Impl) ThreadHandle {
786791 return self.thread.tid.load(.seq_cst);
787792 }
lib/std/Thread/Pool.zig+98-13
......@@ -8,18 +8,25 @@ cond: std.Thread.Condition = .{},
88run_queue: RunQueue = .{},
99is_running: bool = true,
1010allocator: std.mem.Allocator,
11threads: []std.Thread,
11threads: if (builtin.single_threaded) [0]std.Thread else []std.Thread,
12ids: if (builtin.single_threaded) struct {
13 inline fn deinit(_: @This(), _: std.mem.Allocator) void {}
14 fn getIndex(_: @This(), _: std.Thread.Id) usize {
15 return 0;
16 }
17} else std.AutoArrayHashMapUnmanaged(std.Thread.Id, void),
1218
1319const RunQueue = std.SinglyLinkedList(Runnable);
1420const Runnable = struct {
1521 runFn: RunProto,
1622};
1723
18const RunProto = *const fn (*Runnable) void;
24const RunProto = *const fn (*Runnable, id: ?usize) void;
1925
2026pub const Options = struct {
2127 allocator: std.mem.Allocator,
22 n_jobs: ?u32 = null,
28 n_jobs: ?usize = null,
29 track_ids: bool = false,
2330};
2431
2532pub fn init(pool: *Pool, options: Options) !void {
......@@ -27,7 +34,8 @@ pub fn init(pool: *Pool, options: Options) !void {
2734
2835 pool.* = .{
2936 .allocator = allocator,
30 .threads = &[_]std.Thread{},
37 .threads = if (builtin.single_threaded) .{} else &.{},
38 .ids = .{},
3139 };
3240
3341 if (builtin.single_threaded) {
......@@ -35,6 +43,10 @@ pub fn init(pool: *Pool, options: Options) !void {
3543 }
3644
3745 const thread_count = options.n_jobs orelse @max(1, std.Thread.getCpuCount() catch 1);
46 if (options.track_ids) {
47 try pool.ids.ensureTotalCapacity(allocator, 1 + thread_count);
48 pool.ids.putAssumeCapacityNoClobber(std.Thread.getCurrentId(), {});
49 }
3850
3951 // kill and join any threads we spawned and free memory on error.
4052 pool.threads = try allocator.alloc(std.Thread, thread_count);
......@@ -49,6 +61,7 @@ pub fn init(pool: *Pool, options: Options) !void {
4961
5062pub fn deinit(pool: *Pool) void {
5163 pool.join(pool.threads.len); // kill and join all threads.
64 pool.ids.deinit(pool.allocator);
5265 pool.* = undefined;
5366}
5467
......@@ -96,7 +109,7 @@ pub fn spawnWg(pool: *Pool, wait_group: *WaitGroup, comptime func: anytype, args
96109 run_node: RunQueue.Node = .{ .data = .{ .runFn = runFn } },
97110 wait_group: *WaitGroup,
98111
99 fn runFn(runnable: *Runnable) void {
112 fn runFn(runnable: *Runnable, _: ?usize) void {
100113 const run_node: *RunQueue.Node = @fieldParentPtr("data", runnable);
101114 const closure: *@This() = @alignCast(@fieldParentPtr("run_node", run_node));
102115 @call(.auto, func, closure.arguments);
......@@ -134,6 +147,70 @@ pub fn spawnWg(pool: *Pool, wait_group: *WaitGroup, comptime func: anytype, args
134147 pool.cond.signal();
135148}
136149
150/// Runs `func` in the thread pool, calling `WaitGroup.start` beforehand, and
151/// `WaitGroup.finish` after it returns.
152///
153/// The first argument passed to `func` is a dense `usize` thread id, the rest
154/// of the arguments are passed from `args`. Requires the pool to have been
155/// initialized with `.track_ids = true`.
156///
157/// In the case that queuing the function call fails to allocate memory, or the
158/// target is single-threaded, the function is called directly.
159pub fn spawnWgId(pool: *Pool, wait_group: *WaitGroup, comptime func: anytype, args: anytype) void {
160 wait_group.start();
161
162 if (builtin.single_threaded) {
163 @call(.auto, func, .{0} ++ args);
164 wait_group.finish();
165 return;
166 }
167
168 const Args = @TypeOf(args);
169 const Closure = struct {
170 arguments: Args,
171 pool: *Pool,
172 run_node: RunQueue.Node = .{ .data = .{ .runFn = runFn } },
173 wait_group: *WaitGroup,
174
175 fn runFn(runnable: *Runnable, id: ?usize) void {
176 const run_node: *RunQueue.Node = @fieldParentPtr("data", runnable);
177 const closure: *@This() = @alignCast(@fieldParentPtr("run_node", run_node));
178 @call(.auto, func, .{id.?} ++ closure.arguments);
179 closure.wait_group.finish();
180
181 // The thread pool's allocator is protected by the mutex.
182 const mutex = &closure.pool.mutex;
183 mutex.lock();
184 defer mutex.unlock();
185
186 closure.pool.allocator.destroy(closure);
187 }
188 };
189
190 {
191 pool.mutex.lock();
192
193 const closure = pool.allocator.create(Closure) catch {
194 const id: ?usize = pool.ids.getIndex(std.Thread.getCurrentId());
195 pool.mutex.unlock();
196 @call(.auto, func, .{id.?} ++ args);
197 wait_group.finish();
198 return;
199 };
200 closure.* = .{
201 .arguments = args,
202 .pool = pool,
203 .wait_group = wait_group,
204 };
205
206 pool.run_queue.prepend(&closure.run_node);
207 pool.mutex.unlock();
208 }
209
210 // Notify waiting threads outside the lock to try and keep the critical section small.
211 pool.cond.signal();
212}
213
137214pub fn spawn(pool: *Pool, comptime func: anytype, args: anytype) !void {
138215 if (builtin.single_threaded) {
139216 @call(.auto, func, args);
......@@ -181,14 +258,16 @@ fn worker(pool: *Pool) void {
181258 pool.mutex.lock();
182259 defer pool.mutex.unlock();
183260
261 const id: ?usize = if (pool.ids.count() > 0) @intCast(pool.ids.count()) else null;
262 if (id) |_| pool.ids.putAssumeCapacityNoClobber(std.Thread.getCurrentId(), {});
263
184264 while (true) {
185265 while (pool.run_queue.popFirst()) |run_node| {
186266 // Temporarily unlock the mutex in order to execute the run_node
187267 pool.mutex.unlock();
188268 defer pool.mutex.lock();
189269
190 const runFn = run_node.data.runFn;
191 runFn(&run_node.data);
270 run_node.data.runFn(&run_node.data, id);
192271 }
193272
194273 // Stop executing instead of waiting if the thread pool is no longer running.
......@@ -201,17 +280,23 @@ fn worker(pool: *Pool) void {
201280}
202281
203282pub fn waitAndWork(pool: *Pool, wait_group: *WaitGroup) void {
283 var id: ?usize = null;
284
204285 while (!wait_group.isDone()) {
205 if (blk: {
206 pool.mutex.lock();
207 defer pool.mutex.unlock();
208 break :blk pool.run_queue.popFirst();
209 }) |run_node| {
210 run_node.data.runFn(&run_node.data);
286 pool.mutex.lock();
287 if (pool.run_queue.popFirst()) |run_node| {
288 id = id orelse pool.ids.getIndex(std.Thread.getCurrentId());
289 pool.mutex.unlock();
290 run_node.data.runFn(&run_node.data, id);
211291 continue;
212292 }
213293
294 pool.mutex.unlock();
214295 wait_group.wait();
215296 return;
216297 }
217298}
299
300pub fn getIdCount(pool: *Pool) usize {
301 return @intCast(1 + pool.threads.len);
302}
lib/std/multi_array_list.zig+1-1
......@@ -534,7 +534,7 @@ pub fn MultiArrayList(comptime T: type) type {
534534 self.sortInternal(a, b, ctx, .unstable);
535535 }
536536
537 fn capacityInBytes(capacity: usize) usize {
537 pub fn capacityInBytes(capacity: usize) usize {
538538 comptime var elem_bytes: usize = 0;
539539 inline for (sizes.bytes) |size| elem_bytes += size;
540540 return elem_bytes * capacity;
src/Air.zig+2-2
......@@ -1563,12 +1563,12 @@ pub fn internedToRef(ip_index: InternPool.Index) Inst.Ref {
15631563}
15641564
15651565/// Returns `null` if runtime-known.
1566pub fn value(air: Air, inst: Inst.Ref, mod: *Module) !?Value {
1566pub fn value(air: Air, inst: Inst.Ref, pt: Zcu.PerThread) !?Value {
15671567 if (inst.toInterned()) |ip_index| {
15681568 return Value.fromInterned(ip_index);
15691569 }
15701570 const index = inst.toIndex().?;
1571 return air.typeOfIndex(index, &mod.intern_pool).onePossibleValue(mod);
1571 return air.typeOfIndex(index, &pt.zcu.intern_pool).onePossibleValue(pt);
15721572}
15731573
15741574pub fn nullTerminatedString(air: Air, index: usize) [:0]const u8 {
src/Compilation.zig+198-104
......@@ -29,8 +29,6 @@ const wasi_libc = @import("wasi_libc.zig");
2929const fatal = @import("main.zig").fatal;
3030const clangMain = @import("main.zig").clangMain;
3131const Zcu = @import("Zcu.zig");
32/// Deprecated; use `Zcu`.
33const Module = Zcu;
3432const Sema = @import("Sema.zig");
3533const InternPool = @import("InternPool.zig");
3634const Cache = std.Build.Cache;
......@@ -50,7 +48,7 @@ gpa: Allocator,
5048arena: Allocator,
5149/// Not every Compilation compiles .zig code! For example you could do `zig build-exe foo.o`.
5250/// TODO: rename to zcu: ?*Zcu
53module: ?*Module,
51module: ?*Zcu,
5452/// Contains different state depending on whether the Compilation uses
5553/// incremental or whole cache mode.
5654cache_use: CacheUse,
......@@ -105,6 +103,14 @@ lld_errors: std.ArrayListUnmanaged(LldError) = .{},
105103
106104work_queue: std.fifo.LinearFifo(Job, .Dynamic),
107105
106codegen_work: if (InternPool.single_threaded) void else struct {
107 mutex: std.Thread.Mutex,
108 cond: std.Thread.Condition,
109 queue: std.fifo.LinearFifo(CodegenJob, .Dynamic),
110 job_error: ?JobError,
111 done: bool,
112},
113
108114/// These jobs are to invoke the Clang compiler to create an object file, which
109115/// gets linked with the Compilation.
110116c_object_work_queue: std.fifo.LinearFifo(*CObject, .Dynamic),
......@@ -120,7 +126,7 @@ astgen_work_queue: std.fifo.LinearFifo(Zcu.File.Index, .Dynamic),
120126/// These jobs are to inspect the file system stat() and if the embedded file has changed
121127/// on disk, mark the corresponding Decl outdated and queue up an `analyze_decl`
122128/// task for it.
123embed_file_work_queue: std.fifo.LinearFifo(*Module.EmbedFile, .Dynamic),
129embed_file_work_queue: std.fifo.LinearFifo(*Zcu.EmbedFile, .Dynamic),
124130
125131/// The ErrorMsg memory is owned by the `CObject`, using Compilation's general purpose allocator.
126132/// This data is accessed by multiple threads and is protected by `mutex`.
......@@ -252,7 +258,7 @@ pub const Emit = struct {
252258};
253259
254260pub const default_stack_protector_buffer_size = target_util.default_stack_protector_buffer_size;
255pub const SemaError = Module.SemaError;
261pub const SemaError = Zcu.SemaError;
256262
257263pub const CRTFile = struct {
258264 lock: Cache.Lock,
......@@ -364,6 +370,16 @@ const Job = union(enum) {
364370 windows_import_lib: usize,
365371};
366372
373const CodegenJob = union(enum) {
374 decl: InternPool.DeclIndex,
375 func: struct {
376 func: InternPool.Index,
377 /// This `Air` is owned by the `Job` and allocated with `gpa`.
378 /// It must be deinited when the job is processed.
379 air: Air,
380 },
381};
382
367383pub const CObject = struct {
368384 /// Relative to cwd. Owned by arena.
369385 src: CSourceFile,
......@@ -1138,7 +1154,7 @@ pub const CreateOptions = struct {
11381154 pdb_source_path: ?[]const u8 = null,
11391155 /// (Windows) PDB output path
11401156 pdb_out_path: ?[]const u8 = null,
1141 error_limit: ?Compilation.Module.ErrorInt = null,
1157 error_limit: ?Zcu.ErrorInt = null,
11421158 global_cc_argv: []const []const u8 = &.{},
11431159
11441160 pub const Entry = link.File.OpenOptions.Entry;
......@@ -1344,7 +1360,7 @@ pub fn create(gpa: Allocator, arena: Allocator, options: CreateOptions) !*Compil
13441360
13451361 const main_mod = options.main_mod orelse options.root_mod;
13461362 const comp = try arena.create(Compilation);
1347 const opt_zcu: ?*Module = if (have_zcu) blk: {
1363 const opt_zcu: ?*Zcu = if (have_zcu) blk: {
13481364 // Pre-open the directory handles for cached ZIR code so that it does not need
13491365 // to redundantly happen for each AstGen operation.
13501366 const zir_sub_dir = "z";
......@@ -1362,8 +1378,8 @@ pub fn create(gpa: Allocator, arena: Allocator, options: CreateOptions) !*Compil
13621378 .path = try options.global_cache_directory.join(arena, &[_][]const u8{zir_sub_dir}),
13631379 };
13641380
1365 const emit_h: ?*Module.GlobalEmitH = if (options.emit_h) |loc| eh: {
1366 const eh = try arena.create(Module.GlobalEmitH);
1381 const emit_h: ?*Zcu.GlobalEmitH = if (options.emit_h) |loc| eh: {
1382 const eh = try arena.create(Zcu.GlobalEmitH);
13671383 eh.* = .{ .loc = loc };
13681384 break :eh eh;
13691385 } else null;
......@@ -1386,7 +1402,7 @@ pub fn create(gpa: Allocator, arena: Allocator, options: CreateOptions) !*Compil
13861402 .builtin_modules = null, // `builtin_mod` is set
13871403 });
13881404
1389 const zcu = try arena.create(Module);
1405 const zcu = try arena.create(Zcu);
13901406 zcu.* = .{
13911407 .gpa = gpa,
13921408 .comp = comp,
......@@ -1399,7 +1415,7 @@ pub fn create(gpa: Allocator, arena: Allocator, options: CreateOptions) !*Compil
13991415 .error_limit = error_limit,
14001416 .llvm_object = null,
14011417 };
1402 try zcu.init();
1418 try zcu.init(options.thread_pool.getIdCount());
14031419 break :blk zcu;
14041420 } else blk: {
14051421 if (options.emit_h != null) return error.NoZigModuleForCHeader;
......@@ -1431,10 +1447,17 @@ pub fn create(gpa: Allocator, arena: Allocator, options: CreateOptions) !*Compil
14311447 .emit_llvm_ir = options.emit_llvm_ir,
14321448 .emit_llvm_bc = options.emit_llvm_bc,
14331449 .work_queue = std.fifo.LinearFifo(Job, .Dynamic).init(gpa),
1450 .codegen_work = if (InternPool.single_threaded) {} else .{
1451 .mutex = .{},
1452 .cond = .{},
1453 .queue = std.fifo.LinearFifo(CodegenJob, .Dynamic).init(gpa),
1454 .job_error = null,
1455 .done = false,
1456 },
14341457 .c_object_work_queue = std.fifo.LinearFifo(*CObject, .Dynamic).init(gpa),
14351458 .win32_resource_work_queue = if (build_options.only_core_functionality) {} else std.fifo.LinearFifo(*Win32Resource, .Dynamic).init(gpa),
14361459 .astgen_work_queue = std.fifo.LinearFifo(Zcu.File.Index, .Dynamic).init(gpa),
1437 .embed_file_work_queue = std.fifo.LinearFifo(*Module.EmbedFile, .Dynamic).init(gpa),
1460 .embed_file_work_queue = std.fifo.LinearFifo(*Zcu.EmbedFile, .Dynamic).init(gpa),
14381461 .c_source_files = options.c_source_files,
14391462 .rc_source_files = options.rc_source_files,
14401463 .cache_parent = cache,
......@@ -2146,6 +2169,8 @@ pub fn update(comp: *Compilation, main_progress_node: std.Progress.Node) !void {
21462169 try comp.performAllTheWork(main_progress_node);
21472170
21482171 if (comp.module) |zcu| {
2172 const pt: Zcu.PerThread = .{ .zcu = zcu, .tid = .main };
2173
21492174 if (build_options.enable_debug_extensions and comp.verbose_intern_pool) {
21502175 std.debug.print("intern pool stats for '{s}':\n", .{
21512176 comp.root_name,
......@@ -2156,7 +2181,7 @@ pub fn update(comp: *Compilation, main_progress_node: std.Progress.Node) !void {
21562181 if (build_options.enable_debug_extensions and comp.verbose_generic_instances) {
21572182 std.debug.print("generic instances for '{s}:0x{x}':\n", .{
21582183 comp.root_name,
2159 @as(usize, @intFromPtr(zcu)),
2184 @intFromPtr(zcu),
21602185 });
21612186 zcu.intern_pool.dumpGenericInstances(gpa);
21622187 }
......@@ -2165,10 +2190,10 @@ pub fn update(comp: *Compilation, main_progress_node: std.Progress.Node) !void {
21652190 // The `test_functions` decl has been intentionally postponed until now,
21662191 // at which point we must populate it with the list of test functions that
21672192 // have been discovered and not filtered out.
2168 try zcu.populateTestFunctions(main_progress_node);
2193 try pt.populateTestFunctions(main_progress_node);
21692194 }
21702195
2171 try zcu.processExports();
2196 try pt.processExports();
21722197 }
21732198
21742199 if (comp.totalErrorCount() != 0) {
......@@ -2247,7 +2272,7 @@ pub fn update(comp: *Compilation, main_progress_node: std.Progress.Node) !void {
22472272 }
22482273 }
22492274
2250 try flush(comp, arena, main_progress_node);
2275 try flush(comp, arena, .main, main_progress_node);
22512276 if (comp.totalErrorCount() != 0) return;
22522277
22532278 // Failure here only means an unnecessary cache miss.
......@@ -2264,16 +2289,16 @@ pub fn update(comp: *Compilation, main_progress_node: std.Progress.Node) !void {
22642289 whole.lock = man.toOwnedLock();
22652290 },
22662291 .incremental => {
2267 try flush(comp, arena, main_progress_node);
2292 try flush(comp, arena, .main, main_progress_node);
22682293 if (comp.totalErrorCount() != 0) return;
22692294 },
22702295 }
22712296}
22722297
2273fn flush(comp: *Compilation, arena: Allocator, prog_node: std.Progress.Node) !void {
2298fn flush(comp: *Compilation, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) !void {
22742299 if (comp.bin_file) |lf| {
22752300 // This is needed before reading the error flags.
2276 lf.flush(arena, prog_node) catch |err| switch (err) {
2301 lf.flush(arena, tid, prog_node) catch |err| switch (err) {
22772302 error.FlushFailure => {}, // error reported through link_error_flags
22782303 error.LLDReportedFailure => {}, // error reported via lockAndParseLldStderr
22792304 else => |e| return e,
......@@ -2624,7 +2649,7 @@ fn reportMultiModuleErrors(zcu: *Zcu) !void {
26242649 var num_errors: u32 = 0;
26252650 const max_errors = 5;
26262651 // Attach the "some omitted" note to the final error message
2627 var last_err: ?*Module.ErrorMsg = null;
2652 var last_err: ?*Zcu.ErrorMsg = null;
26282653
26292654 for (zcu.import_table.values(), 0..) |file, file_index_usize| {
26302655 if (!file.multi_pkg) continue;
......@@ -2640,13 +2665,13 @@ fn reportMultiModuleErrors(zcu: *Zcu) !void {
26402665 const omitted = file.references.items.len -| max_notes;
26412666 const num_notes = file.references.items.len - omitted;
26422667
2643 const notes = try gpa.alloc(Module.ErrorMsg, if (omitted > 0) num_notes + 1 else num_notes);
2668 const notes = try gpa.alloc(Zcu.ErrorMsg, if (omitted > 0) num_notes + 1 else num_notes);
26442669 errdefer gpa.free(notes);
26452670
26462671 for (notes[0..num_notes], file.references.items[0..num_notes], 0..) |*note, ref, i| {
26472672 errdefer for (notes[0..i]) |*n| n.deinit(gpa);
26482673 note.* = switch (ref) {
2649 .import => |import| try Module.ErrorMsg.init(
2674 .import => |import| try Zcu.ErrorMsg.init(
26502675 gpa,
26512676 .{
26522677 .base_node_inst = try ip.trackZir(gpa, import.file, .main_struct_inst),
......@@ -2655,7 +2680,7 @@ fn reportMultiModuleErrors(zcu: *Zcu) !void {
26552680 "imported from module {s}",
26562681 .{zcu.fileByIndex(import.file).mod.fully_qualified_name},
26572682 ),
2658 .root => |pkg| try Module.ErrorMsg.init(
2683 .root => |pkg| try Zcu.ErrorMsg.init(
26592684 gpa,
26602685 .{
26612686 .base_node_inst = try ip.trackZir(gpa, file_index, .main_struct_inst),
......@@ -2669,7 +2694,7 @@ fn reportMultiModuleErrors(zcu: *Zcu) !void {
26692694 errdefer for (notes[0..num_notes]) |*n| n.deinit(gpa);
26702695
26712696 if (omitted > 0) {
2672 notes[num_notes] = try Module.ErrorMsg.init(
2697 notes[num_notes] = try Zcu.ErrorMsg.init(
26732698 gpa,
26742699 .{
26752700 .base_node_inst = try ip.trackZir(gpa, file_index, .main_struct_inst),
......@@ -2681,7 +2706,7 @@ fn reportMultiModuleErrors(zcu: *Zcu) !void {
26812706 }
26822707 errdefer if (omitted > 0) notes[num_notes].deinit(gpa);
26832708
2684 const err = try Module.ErrorMsg.create(
2709 const err = try Zcu.ErrorMsg.create(
26852710 gpa,
26862711 .{
26872712 .base_node_inst = try ip.trackZir(gpa, file_index, .main_struct_inst),
......@@ -2704,7 +2729,7 @@ fn reportMultiModuleErrors(zcu: *Zcu) !void {
27042729
27052730 // There isn't really any meaningful place to put this note, so just attach it to the
27062731 // last failed file
2707 var note = try Module.ErrorMsg.init(
2732 var note = try Zcu.ErrorMsg.init(
27082733 gpa,
27092734 err.src_loc,
27102735 "{} more errors omitted",
......@@ -2745,10 +2770,10 @@ pub fn makeBinFileWritable(comp: *Compilation) !void {
27452770
27462771const Header = extern struct {
27472772 intern_pool: extern struct {
2748 items_len: u32,
2749 extra_len: u32,
2750 limbs_len: u32,
2751 string_bytes_len: u32,
2773 //items_len: u32,
2774 //extra_len: u32,
2775 //limbs_len: u32,
2776 //string_bytes_len: u32,
27522777 tracked_insts_len: u32,
27532778 src_hash_deps_len: u32,
27542779 decl_val_deps_len: u32,
......@@ -2774,10 +2799,10 @@ pub fn saveState(comp: *Compilation) !void {
27742799 const ip = &zcu.intern_pool;
27752800 const header: Header = .{
27762801 .intern_pool = .{
2777 .items_len = @intCast(ip.items.len),
2778 .extra_len = @intCast(ip.extra.items.len),
2779 .limbs_len = @intCast(ip.limbs.items.len),
2780 .string_bytes_len = @intCast(ip.string_bytes.items.len),
2802 //.items_len = @intCast(ip.items.len),
2803 //.extra_len = @intCast(ip.extra.items.len),
2804 //.limbs_len = @intCast(ip.limbs.items.len),
2805 //.string_bytes_len = @intCast(ip.string_bytes.items.len),
27812806 .tracked_insts_len = @intCast(ip.tracked_insts.count()),
27822807 .src_hash_deps_len = @intCast(ip.src_hash_deps.count()),
27832808 .decl_val_deps_len = @intCast(ip.decl_val_deps.count()),
......@@ -2790,11 +2815,11 @@ pub fn saveState(comp: *Compilation) !void {
27902815 },
27912816 };
27922817 addBuf(&bufs_list, &bufs_len, mem.asBytes(&header));
2793 addBuf(&bufs_list, &bufs_len, mem.sliceAsBytes(ip.limbs.items));
2794 addBuf(&bufs_list, &bufs_len, mem.sliceAsBytes(ip.extra.items));
2795 addBuf(&bufs_list, &bufs_len, mem.sliceAsBytes(ip.items.items(.data)));
2796 addBuf(&bufs_list, &bufs_len, mem.sliceAsBytes(ip.items.items(.tag)));
2797 addBuf(&bufs_list, &bufs_len, ip.string_bytes.items);
2818 //addBuf(&bufs_list, &bufs_len, mem.sliceAsBytes(ip.limbs.items));
2819 //addBuf(&bufs_list, &bufs_len, mem.sliceAsBytes(ip.extra.items));
2820 //addBuf(&bufs_list, &bufs_len, mem.sliceAsBytes(ip.items.items(.data)));
2821 //addBuf(&bufs_list, &bufs_len, mem.sliceAsBytes(ip.items.items(.tag)));
2822 //addBuf(&bufs_list, &bufs_len, ip.string_bytes.items);
27982823 addBuf(&bufs_list, &bufs_len, mem.sliceAsBytes(ip.tracked_insts.keys()));
27992824
28002825 addBuf(&bufs_list, &bufs_len, mem.sliceAsBytes(ip.src_hash_deps.keys()));
......@@ -3093,10 +3118,10 @@ pub fn getAllErrorsAlloc(comp: *Compilation) !ErrorBundle {
30933118 const values = zcu.compile_log_sources.values();
30943119 // First one will be the error; subsequent ones will be notes.
30953120 const src_loc = values[0].src();
3096 const err_msg: Module.ErrorMsg = .{
3121 const err_msg: Zcu.ErrorMsg = .{
30973122 .src_loc = src_loc,
30983123 .msg = "found compile log statement",
3099 .notes = try gpa.alloc(Module.ErrorMsg, zcu.compile_log_sources.count() - 1),
3124 .notes = try gpa.alloc(Zcu.ErrorMsg, zcu.compile_log_sources.count() - 1),
31003125 };
31013126 defer gpa.free(err_msg.notes);
31023127
......@@ -3164,9 +3189,9 @@ pub const ErrorNoteHashContext = struct {
31643189};
31653190
31663191pub fn addModuleErrorMsg(
3167 mod: *Module,
3192 mod: *Zcu,
31683193 eb: *ErrorBundle.Wip,
3169 module_err_msg: Module.ErrorMsg,
3194 module_err_msg: Zcu.ErrorMsg,
31703195 all_references: *const std.AutoHashMapUnmanaged(InternPool.AnalUnit, Zcu.ResolvedReference),
31713196) !void {
31723197 const gpa = eb.gpa;
......@@ -3297,7 +3322,7 @@ pub fn addModuleErrorMsg(
32973322 }
32983323}
32993324
3300pub fn addZirErrorMessages(eb: *ErrorBundle.Wip, file: *Module.File) !void {
3325pub fn addZirErrorMessages(eb: *ErrorBundle.Wip, file: *Zcu.File) !void {
33013326 assert(file.zir_loaded);
33023327 assert(file.tree_loaded);
33033328 assert(file.source_loaded);
......@@ -3310,7 +3335,21 @@ pub fn addZirErrorMessages(eb: *ErrorBundle.Wip, file: *Module.File) !void {
33103335pub fn performAllTheWork(
33113336 comp: *Compilation,
33123337 main_progress_node: std.Progress.Node,
3313) error{ TimerUnsupported, OutOfMemory }!void {
3338) JobError!void {
3339 defer if (comp.module) |mod| {
3340 mod.sema_prog_node.end();
3341 mod.sema_prog_node = std.Progress.Node.none;
3342 mod.codegen_prog_node.end();
3343 mod.codegen_prog_node = std.Progress.Node.none;
3344 };
3345 try comp.performAllTheWorkInner(main_progress_node);
3346 if (!InternPool.single_threaded) if (comp.codegen_work.job_error) |job_error| return job_error;
3347}
3348
3349fn performAllTheWorkInner(
3350 comp: *Compilation,
3351 main_progress_node: std.Progress.Node,
3352) JobError!void {
33143353 // Here we queue up all the AstGen tasks first, followed by C object compilation.
33153354 // We wait until the AstGen tasks are all completed before proceeding to the
33163355 // (at least for now) single-threaded main work queue. However, C object compilation
......@@ -3376,7 +3415,7 @@ pub fn performAllTheWork(
33763415 const path_digest = zcu.filePathDigest(file_index);
33773416 const root_decl = zcu.fileRootDecl(file_index);
33783417 const file = zcu.fileByIndex(file_index);
3379 comp.thread_pool.spawnWg(&comp.astgen_wait_group, workerAstGenFile, .{
3418 comp.thread_pool.spawnWgId(&comp.astgen_wait_group, workerAstGenFile, .{
33803419 comp, file, file_index, path_digest, root_decl, zir_prog_node, &comp.astgen_wait_group, .root,
33813420 });
33823421 }
......@@ -3410,16 +3449,20 @@ pub fn performAllTheWork(
34103449 mod.sema_prog_node = main_progress_node.start("Semantic Analysis", 0);
34113450 mod.codegen_prog_node = main_progress_node.start("Code Generation", 0);
34123451 }
3413 defer if (comp.module) |mod| {
3414 mod.sema_prog_node.end();
3415 mod.sema_prog_node = undefined;
3416 mod.codegen_prog_node.end();
3417 mod.codegen_prog_node = undefined;
3452
3453 if (!InternPool.single_threaded) comp.thread_pool.spawnWgId(&comp.work_queue_wait_group, codegenThread, .{comp});
3454 defer if (!InternPool.single_threaded) {
3455 {
3456 comp.codegen_work.mutex.lock();
3457 defer comp.codegen_work.mutex.unlock();
3458 comp.codegen_work.done = true;
3459 }
3460 comp.codegen_work.cond.signal();
34183461 };
34193462
34203463 while (true) {
34213464 if (comp.work_queue.readItem()) |work_item| {
3422 try processOneJob(comp, work_item, main_progress_node);
3465 try processOneJob(@intFromEnum(Zcu.PerThread.Id.main), comp, work_item, main_progress_node);
34233466 continue;
34243467 }
34253468 if (comp.module) |zcu| {
......@@ -3447,11 +3490,12 @@ pub fn performAllTheWork(
34473490 }
34483491}
34493492
3450fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !void {
3493const JobError = Allocator.Error;
3494
3495fn processOneJob(tid: usize, comp: *Compilation, job: Job, prog_node: std.Progress.Node) JobError!void {
34513496 switch (job) {
34523497 .codegen_decl => |decl_index| {
3453 const zcu = comp.module.?;
3454 const decl = zcu.declPtr(decl_index);
3498 const decl = comp.module.?.declPtr(decl_index);
34553499
34563500 switch (decl.analysis) {
34573501 .unreferenced => unreachable,
......@@ -3461,33 +3505,27 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
34613505 .sema_failure,
34623506 .codegen_failure,
34633507 .dependency_failure,
3464 => return,
3508 => {},
34653509
34663510 .complete => {
3467 const named_frame = tracy.namedFrame("codegen_decl");
3468 defer named_frame.end();
3469
34703511 assert(decl.has_tv);
3471
3472 try zcu.linkerUpdateDecl(decl_index);
3473 return;
3512 try comp.queueCodegenJob(tid, .{ .decl = decl_index });
34743513 },
34753514 }
34763515 },
34773516 .codegen_func => |func| {
3478 const named_frame = tracy.namedFrame("codegen_func");
3479 defer named_frame.end();
3480
3481 const zcu = comp.module.?;
34823517 // This call takes ownership of `func.air`.
3483 try zcu.linkerUpdateFunc(func.func, func.air);
3518 try comp.queueCodegenJob(tid, .{ .func = .{
3519 .func = func.func,
3520 .air = func.air,
3521 } });
34843522 },
34853523 .analyze_func => |func| {
34863524 const named_frame = tracy.namedFrame("analyze_func");
34873525 defer named_frame.end();
34883526
3489 const zcu = comp.module.?;
3490 zcu.ensureFuncBodyAnalyzed(func) catch |err| switch (err) {
3527 const pt: Zcu.PerThread = .{ .zcu = comp.module.?, .tid = @enumFromInt(tid) };
3528 pt.ensureFuncBodyAnalyzed(func) catch |err| switch (err) {
34913529 error.OutOfMemory => return error.OutOfMemory,
34923530 error.AnalysisFail => return,
34933531 };
......@@ -3496,8 +3534,8 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
34963534 if (true) @panic("regressed compiler feature: emit-h should hook into updateExports, " ++
34973535 "not decl analysis, which is too early to know about @export calls");
34983536
3499 const zcu = comp.module.?;
3500 const decl = zcu.declPtr(decl_index);
3537 const pt: Zcu.PerThread = .{ .zcu = comp.module.?, .tid = @enumFromInt(tid) };
3538 const decl = pt.zcu.declPtr(decl_index);
35013539
35023540 switch (decl.analysis) {
35033541 .unreferenced => unreachable,
......@@ -3515,7 +3553,7 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
35153553 defer named_frame.end();
35163554
35173555 const gpa = comp.gpa;
3518 const emit_h = zcu.emit_h.?;
3556 const emit_h = pt.zcu.emit_h.?;
35193557 _ = try emit_h.decl_table.getOrPut(gpa, decl_index);
35203558 const decl_emit_h = emit_h.declPtr(decl_index);
35213559 const fwd_decl = &decl_emit_h.fwd_decl;
......@@ -3523,11 +3561,11 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
35233561 var ctypes_arena = std.heap.ArenaAllocator.init(gpa);
35243562 defer ctypes_arena.deinit();
35253563
3526 const file_scope = zcu.namespacePtr(decl.src_namespace).fileScope(zcu);
3564 const file_scope = pt.zcu.namespacePtr(decl.src_namespace).fileScope(pt.zcu);
35273565
35283566 var dg: c_codegen.DeclGen = .{
35293567 .gpa = gpa,
3530 .zcu = zcu,
3568 .pt = pt,
35313569 .mod = file_scope.mod,
35323570 .error_msg = null,
35333571 .pass = .{ .decl = decl_index },
......@@ -3557,25 +3595,25 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
35573595 }
35583596 },
35593597 .analyze_decl => |decl_index| {
3560 const zcu = comp.module.?;
3561 zcu.ensureDeclAnalyzed(decl_index) catch |err| switch (err) {
3598 const pt: Zcu.PerThread = .{ .zcu = comp.module.?, .tid = @enumFromInt(tid) };
3599 pt.ensureDeclAnalyzed(decl_index) catch |err| switch (err) {
35623600 error.OutOfMemory => return error.OutOfMemory,
35633601 error.AnalysisFail => return,
35643602 };
3565 const decl = zcu.declPtr(decl_index);
3603 const decl = pt.zcu.declPtr(decl_index);
35663604 if (decl.kind == .@"test" and comp.config.is_test) {
35673605 // Tests are always emitted in test binaries. The decl_refs are created by
35683606 // Zcu.populateTestFunctions, but this will not queue body analysis, so do
35693607 // that now.
3570 try zcu.ensureFuncBodyAnalysisQueued(decl.val.toIntern());
3608 try pt.zcu.ensureFuncBodyAnalysisQueued(decl.val.toIntern());
35713609 }
35723610 },
35733611 .resolve_type_fully => |ty| {
35743612 const named_frame = tracy.namedFrame("resolve_type_fully");
35753613 defer named_frame.end();
35763614
3577 const zcu = comp.module.?;
3578 Type.fromInterned(ty).resolveFully(zcu) catch |err| switch (err) {
3615 const pt: Zcu.PerThread = .{ .zcu = comp.module.?, .tid = @enumFromInt(tid) };
3616 Type.fromInterned(ty).resolveFully(pt) catch |err| switch (err) {
35793617 error.OutOfMemory => return error.OutOfMemory,
35803618 error.AnalysisFail => return,
35813619 };
......@@ -3585,30 +3623,30 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
35853623 defer named_frame.end();
35863624
35873625 const gpa = comp.gpa;
3588 const zcu = comp.module.?;
3589 const decl = zcu.declPtr(decl_index);
3626 const pt: Zcu.PerThread = .{ .zcu = comp.module.?, .tid = @enumFromInt(tid) };
3627 const decl = pt.zcu.declPtr(decl_index);
35903628 const lf = comp.bin_file.?;
3591 lf.updateDeclLineNumber(zcu, decl_index) catch |err| {
3592 try zcu.failed_analysis.ensureUnusedCapacity(gpa, 1);
3593 zcu.failed_analysis.putAssumeCapacityNoClobber(
3629 lf.updateDeclLineNumber(pt, decl_index) catch |err| {
3630 try pt.zcu.failed_analysis.ensureUnusedCapacity(gpa, 1);
3631 pt.zcu.failed_analysis.putAssumeCapacityNoClobber(
35943632 InternPool.AnalUnit.wrap(.{ .decl = decl_index }),
35953633 try Zcu.ErrorMsg.create(
35963634 gpa,
3597 decl.navSrcLoc(zcu),
3635 decl.navSrcLoc(pt.zcu),
35983636 "unable to update line number: {s}",
35993637 .{@errorName(err)},
36003638 ),
36013639 );
36023640 decl.analysis = .codegen_failure;
3603 try zcu.retryable_failures.append(gpa, InternPool.AnalUnit.wrap(.{ .decl = decl_index }));
3641 try pt.zcu.retryable_failures.append(gpa, InternPool.AnalUnit.wrap(.{ .decl = decl_index }));
36043642 };
36053643 },
3606 .analyze_mod => |pkg| {
3644 .analyze_mod => |mod| {
36073645 const named_frame = tracy.namedFrame("analyze_mod");
36083646 defer named_frame.end();
36093647
3610 const zcu = comp.module.?;
3611 zcu.semaPkg(pkg) catch |err| switch (err) {
3648 const pt: Zcu.PerThread = .{ .zcu = comp.module.?, .tid = @enumFromInt(tid) };
3649 pt.semaPkg(mod) catch |err| switch (err) {
36123650 error.OutOfMemory => return error.OutOfMemory,
36133651 error.AnalysisFail => return,
36143652 };
......@@ -3772,6 +3810,61 @@ fn processOneJob(comp: *Compilation, job: Job, prog_node: std.Progress.Node) !vo
37723810 }
37733811}
37743812
3813fn queueCodegenJob(comp: *Compilation, tid: usize, codegen_job: CodegenJob) !void {
3814 if (InternPool.single_threaded or
3815 !comp.module.?.backendSupportsFeature(.separate_thread))
3816 return processOneCodegenJob(tid, comp, codegen_job);
3817
3818 {
3819 comp.codegen_work.mutex.lock();
3820 defer comp.codegen_work.mutex.unlock();
3821 try comp.codegen_work.queue.writeItem(codegen_job);
3822 }
3823 comp.codegen_work.cond.signal();
3824}
3825
3826fn codegenThread(tid: usize, comp: *Compilation) void {
3827 comp.codegen_work.mutex.lock();
3828 defer comp.codegen_work.mutex.unlock();
3829
3830 while (true) {
3831 if (comp.codegen_work.queue.readItem()) |codegen_job| {
3832 comp.codegen_work.mutex.unlock();
3833 defer comp.codegen_work.mutex.lock();
3834
3835 processOneCodegenJob(tid, comp, codegen_job) catch |job_error| {
3836 comp.codegen_work.job_error = job_error;
3837 break;
3838 };
3839 continue;
3840 }
3841
3842 if (comp.codegen_work.done) break;
3843
3844 comp.codegen_work.cond.wait(&comp.codegen_work.mutex);
3845 }
3846}
3847
3848fn processOneCodegenJob(tid: usize, comp: *Compilation, codegen_job: CodegenJob) JobError!void {
3849 switch (codegen_job) {
3850 .decl => |decl_index| {
3851 const named_frame = tracy.namedFrame("codegen_decl");
3852 defer named_frame.end();
3853
3854 const pt: Zcu.PerThread = .{ .zcu = comp.module.?, .tid = @enumFromInt(tid) };
3855 try pt.linkerUpdateDecl(decl_index);
3856 },
3857 .func => |func| {
3858 const named_frame = tracy.namedFrame("codegen_func");
3859 defer named_frame.end();
3860
3861 const pt: Zcu.PerThread = .{ .zcu = comp.module.?, .tid = @enumFromInt(tid) };
3862 // This call takes ownership of `func.air`.
3863 try pt.linkerUpdateFunc(func.func, func.air);
3864 },
3865 }
3866}
3867
37753868fn workerDocsCopy(comp: *Compilation) void {
37763869 docsCopyFallible(comp) catch |err| {
37773870 return comp.lockAndSetMiscFailure(
......@@ -4047,6 +4140,7 @@ const AstGenSrc = union(enum) {
40474140};
40484141
40494142fn workerAstGenFile(
4143 tid: usize,
40504144 comp: *Compilation,
40514145 file: *Zcu.File,
40524146 file_index: Zcu.File.Index,
......@@ -4059,8 +4153,8 @@ fn workerAstGenFile(
40594153 const child_prog_node = prog_node.start(file.sub_file_path, 0);
40604154 defer child_prog_node.end();
40614155
4062 const zcu = comp.module.?;
4063 zcu.astGenFile(file, file_index, path_digest, root_decl) catch |err| switch (err) {
4156 const pt: Zcu.PerThread = .{ .zcu = comp.module.?, .tid = @enumFromInt(tid) };
4157 pt.astGenFile(file, file_index, path_digest, root_decl) catch |err| switch (err) {
40644158 error.AnalysisFail => return,
40654159 else => {
40664160 file.status = .retryable_failure;
......@@ -4095,15 +4189,15 @@ fn workerAstGenFile(
40954189 comp.mutex.lock();
40964190 defer comp.mutex.unlock();
40974191
4098 const res = zcu.importFile(file, import_path) catch continue;
4192 const res = pt.zcu.importFile(file, import_path) catch continue;
40994193 if (!res.is_pkg) {
4100 res.file.addReference(zcu.*, .{ .import = .{
4194 res.file.addReference(pt.zcu.*, .{ .import = .{
41014195 .file = file_index,
41024196 .token = item.data.token,
41034197 } }) catch continue;
41044198 }
4105 const imported_path_digest = zcu.filePathDigest(res.file_index);
4106 const imported_root_decl = zcu.fileRootDecl(res.file_index);
4199 const imported_path_digest = pt.zcu.filePathDigest(res.file_index);
4200 const imported_root_decl = pt.zcu.fileRootDecl(res.file_index);
41074201 break :blk .{ res, imported_path_digest, imported_root_decl };
41084202 };
41094203 if (import_result.is_new) {
......@@ -4114,7 +4208,7 @@ fn workerAstGenFile(
41144208 .importing_file = file_index,
41154209 .import_tok = item.data.token,
41164210 } };
4117 comp.thread_pool.spawnWg(wg, workerAstGenFile, .{
4211 comp.thread_pool.spawnWgId(wg, workerAstGenFile, .{
41184212 comp, import_result.file, import_result.file_index, imported_path_digest, imported_root_decl, prog_node, wg, sub_src,
41194213 });
41204214 }
......@@ -4125,7 +4219,7 @@ fn workerAstGenFile(
41254219fn workerUpdateBuiltinZigFile(
41264220 comp: *Compilation,
41274221 mod: *Package.Module,
4128 file: *Module.File,
4222 file: *Zcu.File,
41294223) void {
41304224 Builtin.populateFile(comp, mod, file) catch |err| {
41314225 comp.mutex.lock();
......@@ -4137,7 +4231,7 @@ fn workerUpdateBuiltinZigFile(
41374231 };
41384232}
41394233
4140fn workerCheckEmbedFile(comp: *Compilation, embed_file: *Module.EmbedFile) void {
4234fn workerCheckEmbedFile(comp: *Compilation, embed_file: *Zcu.EmbedFile) void {
41414235 comp.detectEmbedFileUpdate(embed_file) catch |err| {
41424236 comp.reportRetryableEmbedFileError(embed_file, err) catch |oom| switch (oom) {
41434237 // Swallowing this error is OK because it's implied to be OOM when
......@@ -4148,7 +4242,7 @@ fn workerCheckEmbedFile(comp: *Compilation, embed_file: *Module.EmbedFile) void
41484242 };
41494243}
41504244
4151fn detectEmbedFileUpdate(comp: *Compilation, embed_file: *Module.EmbedFile) !void {
4245fn detectEmbedFileUpdate(comp: *Compilation, embed_file: *Zcu.EmbedFile) !void {
41524246 const mod = comp.module.?;
41534247 const ip = &mod.intern_pool;
41544248 var file = try embed_file.owner.root.openFile(embed_file.sub_file_path.toSlice(ip), .{});
......@@ -4475,7 +4569,7 @@ fn reportRetryableAstGenError(
44754569 const file = zcu.fileByIndex(file_index);
44764570 file.status = .retryable_failure;
44774571
4478 const src_loc: Module.LazySrcLoc = switch (src) {
4572 const src_loc: Zcu.LazySrcLoc = switch (src) {
44794573 .root => .{
44804574 .base_node_inst = try zcu.intern_pool.trackZir(gpa, file_index, .main_struct_inst),
44814575 .offset = .entire_file,
......@@ -4486,7 +4580,7 @@ fn reportRetryableAstGenError(
44864580 },
44874581 };
44884582
4489 const err_msg = try Module.ErrorMsg.create(gpa, src_loc, "unable to load '{}{s}': {s}", .{
4583 const err_msg = try Zcu.ErrorMsg.create(gpa, src_loc, "unable to load '{}{s}': {s}", .{
44904584 file.mod.root, file.sub_file_path, @errorName(err),
44914585 });
44924586 errdefer err_msg.destroy(gpa);
......@@ -4500,14 +4594,14 @@ fn reportRetryableAstGenError(
45004594
45014595fn reportRetryableEmbedFileError(
45024596 comp: *Compilation,
4503 embed_file: *Module.EmbedFile,
4597 embed_file: *Zcu.EmbedFile,
45044598 err: anyerror,
45054599) error{OutOfMemory}!void {
45064600 const mod = comp.module.?;
45074601 const gpa = mod.gpa;
45084602 const src_loc = embed_file.src_loc;
45094603 const ip = &mod.intern_pool;
4510 const err_msg = try Module.ErrorMsg.create(gpa, src_loc, "unable to load '{}{s}': {s}", .{
4604 const err_msg = try Zcu.ErrorMsg.create(gpa, src_loc, "unable to load '{}{s}': {s}", .{
45114605 embed_file.owner.root,
45124606 embed_file.sub_file_path.toSlice(ip),
45134607 @errorName(err),
src/Compilation/Config.zig+2-6
......@@ -440,12 +440,8 @@ pub fn resolve(options: Options) ResolveError!Config {
440440 };
441441 };
442442
443 const backend_supports_error_tracing = target_util.backendSupportsFeature(
444 target.cpu.arch,
445 target.ofmt,
446 use_llvm,
447 .error_return_trace,
448 );
443 const backend = target_util.zigBackend(target, use_llvm);
444 const backend_supports_error_tracing = target_util.backendSupportsFeature(backend, .error_return_trace);
449445
450446 const root_error_tracing = b: {
451447 if (options.root_error_tracing) |x| break :b x;
src/InternPool.zig+2634-1638
......@@ -2,22 +2,17 @@
22//! This data structure is self-contained, with the following exceptions:
33//! * Module.Namespace has a pointer to Module.File
44
5/// Maps `Key` to `Index`. `Key` objects are not stored anywhere; they are
6/// constructed lazily.
7map: std.AutoArrayHashMapUnmanaged(void, void) = .{},
8items: std.MultiArrayList(Item) = .{},
9extra: std.ArrayListUnmanaged(u32) = .{},
10/// On 32-bit systems, this array is ignored and extra is used for everything.
11/// On 64-bit systems, this array is used for big integers and associated metadata.
12/// Use the helper methods instead of accessing this directly in order to not
13/// violate the above mechanism.
14limbs: std.ArrayListUnmanaged(u64) = .{},
15/// In order to store references to strings in fewer bytes, we copy all
16/// string bytes into here. String bytes can be null. It is up to whomever
17/// is referencing the data here whether they want to store both index and length,
18/// thus allowing null bytes, or store only index, and use null-termination. The
19/// `string_bytes` array is agnostic to either usage.
20string_bytes: std.ArrayListUnmanaged(u8) = .{},
5/// One item per thread, indexed by `tid`, which is dense and unique per thread.
6locals: []Local = &.{},
7/// Length must be a power of two and represents the number of simultaneous
8/// writers that can mutate any single sharded data structure.
9shards: []Shard = &.{},
10/// Cached number of active bits in a `tid`.
11tid_width: if (single_threaded) u0 else std.math.Log2Int(u32) = 0,
12/// Cached shift amount to put a `tid` in the top bits of a 31-bit value.
13tid_shift_31: if (single_threaded) u0 else std.math.Log2Int(u32) = if (single_threaded) 0 else 31,
14/// Cached shift amount to put a `tid` in the top bits of a 32-bit value.
15tid_shift_32: if (single_threaded) u0 else std.math.Log2Int(u32) = if (single_threaded) 0 else 31,
2116
2217/// Rather than allocating Decl objects with an Allocator, we instead allocate
2318/// them with this SegmentedList. This provides four advantages:
......@@ -45,14 +40,6 @@ namespaces_free_list: std.ArrayListUnmanaged(NamespaceIndex) = .{},
4540/// These are not serialized; it is computed upon deserialization.
4641maps: std.ArrayListUnmanaged(FieldMap) = .{},
4742
48/// Used for finding the index inside `string_bytes`.
49string_table: std.HashMapUnmanaged(
50 u32,
51 void,
52 std.hash_map.StringIndexContext,
53 std.hash_map.default_max_load_percentage,
54) = .{},
55
5643/// An index into `tracked_insts` gives a reference to a single ZIR instruction which
5744/// persists across incremental updates.
5845tracked_insts: std.AutoArrayHashMapUnmanaged(TrackedInst, void) = .{},
......@@ -103,6 +90,14 @@ free_dep_entries: std.ArrayListUnmanaged(DepEntry.Index) = .{},
10390/// Value is the `Decl` of the struct that represents this `File`.
10491files: std.AutoArrayHashMapUnmanaged(Cache.BinDigest, OptionalDeclIndex) = .{},
10592
93/// Whether a multi-threaded intern pool is useful.
94/// Currently `false` until the intern pool is actually accessed
95/// from multiple threads to reduce the cost of this data structure.
96const want_multi_threaded = false;
97
98/// Whether a single-threaded intern pool impl is in use.
99pub const single_threaded = builtin.single_threaded or !want_multi_threaded;
100
106101pub const FileIndex = enum(u32) {
107102 _,
108103};
......@@ -351,6 +346,417 @@ pub const DepEntry = extern struct {
351346 };
352347};
353348
349const Local = struct {
350 /// These fields can be accessed from any thread by calling `acquire`.
351 /// They are only modified by the owning thread.
352 shared: Shared align(std.atomic.cache_line),
353 /// This state is fully local to the owning thread and does not require any
354 /// atomic access.
355 mutate: struct {
356 arena: std.heap.ArenaAllocator.State,
357 items: Mutate,
358 extra: Mutate,
359 limbs: Mutate,
360 strings: Mutate,
361 } align(std.atomic.cache_line),
362
363 const Shared = struct {
364 items: List(Item),
365 extra: Extra,
366 limbs: Limbs,
367 strings: Strings,
368
369 pub fn getLimbs(shared: *const Local.Shared) Limbs {
370 return switch (@sizeOf(Limb)) {
371 @sizeOf(u32) => shared.extra,
372 @sizeOf(u64) => shared.limbs,
373 else => @compileError("unsupported host"),
374 }.acquire();
375 }
376 };
377
378 const Extra = List(struct { u32 });
379 const Limbs = switch (@sizeOf(Limb)) {
380 @sizeOf(u32) => Extra,
381 @sizeOf(u64) => List(struct { u64 }),
382 else => @compileError("unsupported host"),
383 };
384 const Strings = List(struct { u8 });
385
386 const Mutate = struct {
387 len: u32,
388
389 const empty: Mutate = .{
390 .len = 0,
391 };
392 };
393
394 fn List(comptime Elem: type) type {
395 assert(@typeInfo(Elem) == .Struct);
396 return struct {
397 bytes: [*]align(@alignOf(Elem)) u8,
398
399 const ListSelf = @This();
400 const Mutable = struct {
401 gpa: std.mem.Allocator,
402 arena: *std.heap.ArenaAllocator.State,
403 mutate: *Mutate,
404 list: *ListSelf,
405
406 const fields = std.enums.values(std.meta.FieldEnum(Elem));
407
408 fn PtrArrayElem(comptime len: usize) type {
409 const elem_info = @typeInfo(Elem).Struct;
410 const elem_fields = elem_info.fields;
411 var new_fields: [elem_fields.len]std.builtin.Type.StructField = undefined;
412 for (&new_fields, elem_fields) |*new_field, elem_field| new_field.* = .{
413 .name = elem_field.name,
414 .type = *[len]elem_field.type,
415 .default_value = null,
416 .is_comptime = false,
417 .alignment = 0,
418 };
419 return @Type(.{ .Struct = .{
420 .layout = .auto,
421 .fields = &new_fields,
422 .decls = &.{},
423 .is_tuple = elem_info.is_tuple,
424 } });
425 }
426 fn SliceElem(comptime opts: struct { is_const: bool = false }) type {
427 const elem_info = @typeInfo(Elem).Struct;
428 const elem_fields = elem_info.fields;
429 var new_fields: [elem_fields.len]std.builtin.Type.StructField = undefined;
430 for (&new_fields, elem_fields) |*new_field, elem_field| new_field.* = .{
431 .name = elem_field.name,
432 .type = @Type(.{ .Pointer = .{
433 .size = .Slice,
434 .is_const = opts.is_const,
435 .is_volatile = false,
436 .alignment = 0,
437 .address_space = .generic,
438 .child = elem_field.type,
439 .is_allowzero = false,
440 .sentinel = null,
441 } }),
442 .default_value = null,
443 .is_comptime = false,
444 .alignment = 0,
445 };
446 return @Type(.{ .Struct = .{
447 .layout = .auto,
448 .fields = &new_fields,
449 .decls = &.{},
450 .is_tuple = elem_info.is_tuple,
451 } });
452 }
453
454 pub fn append(mutable: Mutable, elem: Elem) Allocator.Error!void {
455 try mutable.ensureUnusedCapacity(1);
456 mutable.appendAssumeCapacity(elem);
457 }
458
459 pub fn appendAssumeCapacity(mutable: Mutable, elem: Elem) void {
460 var mutable_view = mutable.view();
461 defer mutable.mutate.len = @intCast(mutable_view.len);
462 mutable_view.appendAssumeCapacity(elem);
463 }
464
465 pub fn appendSliceAssumeCapacity(
466 mutable: Mutable,
467 slice: SliceElem(.{ .is_const = true }),
468 ) void {
469 if (fields.len == 0) return;
470 const start = mutable.mutate.len;
471 const slice_len = @field(slice, @tagName(fields[0])).len;
472 assert(slice_len <= mutable.list.header().capacity - start);
473 mutable.mutate.len = @intCast(start + slice_len);
474 const mutable_view = mutable.view();
475 inline for (fields) |field| {
476 const field_slice = @field(slice, @tagName(field));
477 assert(field_slice.len == slice_len);
478 @memcpy(mutable_view.items(field)[start..][0..slice_len], field_slice);
479 }
480 }
481
482 pub fn appendNTimes(mutable: Mutable, elem: Elem, len: usize) Allocator.Error!void {
483 try mutable.ensureUnusedCapacity(len);
484 mutable.appendNTimesAssumeCapacity(elem, len);
485 }
486
487 pub fn appendNTimesAssumeCapacity(mutable: Mutable, elem: Elem, len: usize) void {
488 const start = mutable.mutate.len;
489 assert(len <= mutable.list.header().capacity - start);
490 mutable.mutate.len = @intCast(start + len);
491 const mutable_view = mutable.view();
492 inline for (fields) |field| {
493 @memset(mutable_view.items(field)[start..][0..len], @field(elem, @tagName(field)));
494 }
495 }
496
497 pub fn addManyAsArray(mutable: Mutable, comptime len: usize) Allocator.Error!PtrArrayElem(len) {
498 try mutable.ensureUnusedCapacity(len);
499 return mutable.addManyAsArrayAssumeCapacity(len);
500 }
501
502 pub fn addManyAsArrayAssumeCapacity(mutable: Mutable, comptime len: usize) PtrArrayElem(len) {
503 const start = mutable.mutate.len;
504 assert(len <= mutable.list.header().capacity - start);
505 mutable.mutate.len = @intCast(start + len);
506 const mutable_view = mutable.view();
507 var ptr_array: PtrArrayElem(len) = undefined;
508 inline for (fields) |field| {
509 @field(ptr_array, @tagName(field)) = mutable_view.items(field)[start..][0..len];
510 }
511 return ptr_array;
512 }
513
514 pub fn addManyAsSlice(mutable: Mutable, len: usize) Allocator.Error!SliceElem(.{}) {
515 try mutable.ensureUnusedCapacity(len);
516 return mutable.addManyAsSliceAssumeCapacity(len);
517 }
518
519 pub fn addManyAsSliceAssumeCapacity(mutable: Mutable, len: usize) SliceElem(.{}) {
520 const start = mutable.mutate.len;
521 assert(len <= mutable.list.header().capacity - start);
522 mutable.mutate.len = @intCast(start + len);
523 const mutable_view = mutable.view();
524 var slice: SliceElem(.{}) = undefined;
525 inline for (fields) |field| {
526 @field(slice, @tagName(field)) = mutable_view.items(field)[start..][0..len];
527 }
528 return slice;
529 }
530
531 pub fn shrinkRetainingCapacity(mutable: Mutable, len: usize) void {
532 assert(len <= mutable.mutate.len);
533 mutable.mutate.len = @intCast(len);
534 }
535
536 pub fn ensureUnusedCapacity(mutable: Mutable, unused_capacity: usize) Allocator.Error!void {
537 try mutable.ensureTotalCapacity(@intCast(mutable.mutate.len + unused_capacity));
538 }
539
540 pub fn ensureTotalCapacity(mutable: Mutable, total_capacity: usize) Allocator.Error!void {
541 const old_capacity = mutable.list.header().capacity;
542 if (old_capacity >= total_capacity) return;
543 var new_capacity = old_capacity;
544 while (new_capacity < total_capacity) new_capacity = (new_capacity + 10) * 2;
545 try mutable.setCapacity(new_capacity);
546 }
547
548 fn setCapacity(mutable: Mutable, capacity: u32) Allocator.Error!void {
549 var arena = mutable.arena.promote(mutable.gpa);
550 defer mutable.arena.* = arena.state;
551 const buf = try arena.allocator().alignedAlloc(
552 u8,
553 alignment,
554 bytes_offset + View.capacityInBytes(capacity),
555 );
556 var new_list: ListSelf = .{ .bytes = @ptrCast(buf[bytes_offset..].ptr) };
557 new_list.header().* = .{ .capacity = capacity };
558 const len = mutable.mutate.len;
559 // this cold, quickly predictable, condition enables
560 // the `MultiArrayList` optimization in `view`
561 if (len > 0) {
562 const old_slice = mutable.list.view().slice();
563 const new_slice = new_list.view().slice();
564 inline for (fields) |field| @memcpy(new_slice.items(field)[0..len], old_slice.items(field)[0..len]);
565 }
566 mutable.list.release(new_list);
567 }
568
569 fn view(mutable: Mutable) View {
570 const capacity = mutable.list.header().capacity;
571 assert(capacity > 0); // optimizes `MultiArrayList.Slice.items`
572 return .{
573 .bytes = mutable.list.bytes,
574 .len = mutable.mutate.len,
575 .capacity = capacity,
576 };
577 }
578 };
579
580 const empty: ListSelf = .{ .bytes = @constCast(&(extern struct {
581 header: Header,
582 bytes: [0]u8 align(@alignOf(Elem)),
583 }{
584 .header = .{ .capacity = 0 },
585 .bytes = .{},
586 }).bytes) };
587
588 const alignment = @max(@alignOf(Header), @alignOf(Elem));
589 const bytes_offset = std.mem.alignForward(usize, @sizeOf(Header), @alignOf(Elem));
590 const View = std.MultiArrayList(Elem);
591
592 /// Must be called when accessing from another thread.
593 fn acquire(list: *const ListSelf) ListSelf {
594 return .{ .bytes = @atomicLoad([*]align(@alignOf(Elem)) u8, &list.bytes, .acquire) };
595 }
596 fn release(list: *ListSelf, new_list: ListSelf) void {
597 @atomicStore([*]align(@alignOf(Elem)) u8, &list.bytes, new_list.bytes, .release);
598 }
599
600 const Header = extern struct {
601 capacity: u32,
602 };
603 fn header(list: ListSelf) *Header {
604 return @ptrFromInt(@intFromPtr(list.bytes) - bytes_offset);
605 }
606
607 fn view(list: ListSelf) View {
608 const capacity = list.header().capacity;
609 assert(capacity > 0); // optimizes `MultiArrayList.Slice.items`
610 return .{
611 .bytes = list.bytes,
612 .len = capacity,
613 .capacity = capacity,
614 };
615 }
616 };
617 }
618
619 pub fn getMutableItems(local: *Local, gpa: std.mem.Allocator) List(Item).Mutable {
620 return .{
621 .gpa = gpa,
622 .arena = &local.mutate.arena,
623 .mutate = &local.mutate.items,
624 .list = &local.shared.items,
625 };
626 }
627
628 pub fn getMutableExtra(local: *Local, gpa: std.mem.Allocator) Extra.Mutable {
629 return .{
630 .gpa = gpa,
631 .arena = &local.mutate.arena,
632 .mutate = &local.mutate.extra,
633 .list = &local.shared.extra,
634 };
635 }
636
637 /// On 32-bit systems, this array is ignored and extra is used for everything.
638 /// On 64-bit systems, this array is used for big integers and associated metadata.
639 /// Use the helper methods instead of accessing this directly in order to not
640 /// violate the above mechanism.
641 pub fn getMutableLimbs(local: *Local, gpa: std.mem.Allocator) Limbs.Mutable {
642 return switch (@sizeOf(Limb)) {
643 @sizeOf(u32) => local.getMutableExtra(gpa),
644 @sizeOf(u64) => .{
645 .gpa = gpa,
646 .arena = &local.mutate.arena,
647 .mutate = &local.mutate.limbs,
648 .list = &local.shared.limbs,
649 },
650 else => @compileError("unsupported host"),
651 };
652 }
653
654 /// In order to store references to strings in fewer bytes, we copy all
655 /// string bytes into here. String bytes can be null. It is up to whomever
656 /// is referencing the data here whether they want to store both index and length,
657 /// thus allowing null bytes, or store only index, and use null-termination. The
658 /// `strings` array is agnostic to either usage.
659 pub fn getMutableStrings(local: *Local, gpa: std.mem.Allocator) Strings.Mutable {
660 return .{
661 .gpa = gpa,
662 .arena = &local.mutate.arena,
663 .mutate = &local.mutate.strings,
664 .list = &local.shared.strings,
665 };
666 }
667};
668
669pub fn getLocal(ip: *InternPool, tid: Zcu.PerThread.Id) *Local {
670 return &ip.locals[@intFromEnum(tid)];
671}
672
673pub fn getLocalShared(ip: *const InternPool, tid: Zcu.PerThread.Id) *const Local.Shared {
674 return &ip.locals[@intFromEnum(tid)].shared;
675}
676
677const Shard = struct {
678 shared: struct {
679 map: Map(Index),
680 string_map: Map(OptionalNullTerminatedString),
681 } align(std.atomic.cache_line),
682 mutate: struct {
683 // TODO: measure cost of sharing unrelated mutate state
684 map: Mutate align(std.atomic.cache_line),
685 string_map: Mutate align(std.atomic.cache_line),
686 },
687
688 const Mutate = struct {
689 mutex: std.Thread.Mutex.Recursive,
690 len: u32,
691
692 const empty: Mutate = .{
693 .mutex = std.Thread.Mutex.Recursive.init,
694 .len = 0,
695 };
696 };
697
698 fn Map(comptime Value: type) type {
699 comptime assert(@typeInfo(Value).Enum.tag_type == u32);
700 _ = @as(Value, .none); // expected .none key
701 return struct {
702 /// header: Header,
703 /// entries: [header.capacity]Entry,
704 entries: [*]Entry,
705
706 const empty: @This() = .{ .entries = @constCast(&(extern struct {
707 header: Header,
708 entries: [1]Entry,
709 }{
710 .header = .{ .capacity = 1 },
711 .entries = .{.{ .value = .none, .hash = undefined }},
712 }).entries) };
713
714 const alignment = @max(@alignOf(Header), @alignOf(Entry));
715 const entries_offset = std.mem.alignForward(usize, @sizeOf(Header), @alignOf(Entry));
716
717 /// Must be called unless the mutate mutex is locked.
718 fn acquire(map: *const @This()) @This() {
719 return .{ .entries = @atomicLoad([*]Entry, &map.entries, .acquire) };
720 }
721 fn release(map: *@This(), new_map: @This()) void {
722 @atomicStore([*]Entry, &map.entries, new_map.entries, .release);
723 }
724
725 const Header = extern struct {
726 capacity: u32,
727
728 fn mask(head: *const Header) u32 {
729 assert(std.math.isPowerOfTwo(head.capacity));
730 return head.capacity - 1;
731 }
732 };
733 fn header(map: @This()) *Header {
734 return @ptrFromInt(@intFromPtr(map.entries) - entries_offset);
735 }
736
737 const Entry = extern struct {
738 value: Value,
739 hash: u32,
740
741 fn acquire(entry: *const Entry) Value {
742 return @atomicLoad(Value, &entry.value, .acquire);
743 }
744 fn release(entry: *Entry, value: Value) void {
745 @atomicStore(Value, &entry.value, value, .release);
746 }
747 };
748 };
749 }
750};
751
752fn getTidMask(ip: *const InternPool) u32 {
753 return (@as(u32, 1) << ip.tid_width) - 1;
754}
755
756fn getIndexMask(ip: *const InternPool, comptime BackingInt: type) u32 {
757 return @as(u32, std.math.maxInt(BackingInt)) >> ip.tid_width;
758}
759
354760const FieldMap = std.ArrayHashMapUnmanaged(void, void, std.array_hash_map.AutoContext(void), false);
355761
356762const builtin = @import("builtin");
......@@ -369,20 +775,6 @@ const Zcu = @import("Zcu.zig");
369775const Module = Zcu;
370776const Zir = std.zig.Zir;
371777
372const KeyAdapter = struct {
373 intern_pool: *const InternPool,
374
375 pub fn eql(ctx: @This(), a: Key, b_void: void, b_map_index: usize) bool {
376 _ = b_void;
377 if (ctx.intern_pool.items.items(.tag)[b_map_index] == .removed) return false;
378 return ctx.intern_pool.indexToKey(@enumFromInt(b_map_index)).eql(a, ctx.intern_pool);
379 }
380
381 pub fn hash(ctx: @This(), a: Key) u32 {
382 return a.hash32(ctx.intern_pool);
383 }
384};
385
386778/// An index into `maps` which might be `none`.
387779pub const OptionalMapIndex = enum(u32) {
388780 none = std.math.maxInt(u32),
......@@ -459,18 +851,18 @@ pub const OptionalNamespaceIndex = enum(u32) {
459851 }
460852};
461853
462/// An index into `string_bytes`.
854/// An index into `strings`.
463855pub const String = enum(u32) {
464856 /// An empty string.
465857 empty = 0,
466858 _,
467859
468860 pub fn toSlice(string: String, len: u64, ip: *const InternPool) []const u8 {
469 return ip.string_bytes.items[@intFromEnum(string)..][0..@intCast(len)];
861 return string.toOverlongSlice(ip)[0..@intCast(len)];
470862 }
471863
472864 pub fn at(string: String, index: u64, ip: *const InternPool) u8 {
473 return ip.string_bytes.items[@intCast(@intFromEnum(string) + index)];
865 return string.toOverlongSlice(ip)[@intCast(index)];
474866 }
475867
476868 pub fn toNullTerminatedString(string: String, len: u64, ip: *const InternPool) NullTerminatedString {
......@@ -478,9 +870,32 @@ pub const String = enum(u32) {
478870 assert(string.at(len, ip) == 0);
479871 return @enumFromInt(@intFromEnum(string));
480872 }
873
874 const Unwrapped = struct {
875 tid: Zcu.PerThread.Id,
876 index: u32,
877
878 fn wrap(unwrapped: Unwrapped, ip: *const InternPool) String {
879 assert(@intFromEnum(unwrapped.tid) <= ip.getTidMask());
880 assert(unwrapped.index <= ip.getIndexMask(u32));
881 return @enumFromInt(@as(u32, @intFromEnum(unwrapped.tid)) << ip.tid_shift_32 | unwrapped.index);
882 }
883 };
884 fn unwrap(string: String, ip: *const InternPool) Unwrapped {
885 return .{
886 .tid = @enumFromInt(@intFromEnum(string) >> ip.tid_shift_32 & ip.getTidMask()),
887 .index = @intFromEnum(string) & ip.getIndexMask(u32),
888 };
889 }
890
891 fn toOverlongSlice(string: String, ip: *const InternPool) []const u8 {
892 const unwrapped_string = string.unwrap(ip);
893 const strings = ip.getLocalShared(unwrapped_string.tid).strings.acquire();
894 return strings.view().items(.@"0")[unwrapped_string.index..];
895 }
481896};
482897
483/// An index into `string_bytes` which might be `none`.
898/// An index into `strings` which might be `none`.
484899pub const OptionalString = enum(u32) {
485900 /// This is distinct from `none` - it is a valid index that represents empty string.
486901 empty = 0,
......@@ -496,7 +911,7 @@ pub const OptionalString = enum(u32) {
496911 }
497912};
498913
499/// An index into `string_bytes`.
914/// An index into `strings`.
500915pub const NullTerminatedString = enum(u32) {
501916 /// An empty string.
502917 empty = 0,
......@@ -506,11 +921,15 @@ pub const NullTerminatedString = enum(u32) {
506921 /// This type exists to provide a struct with lifetime that is
507922 /// not invalidated when items are added to the `InternPool`.
508923 pub const Slice = struct {
924 tid: Zcu.PerThread.Id,
509925 start: u32,
510926 len: u32,
511927
928 pub const empty: Slice = .{ .tid = .main, .start = 0, .len = 0 };
929
512930 pub fn get(slice: Slice, ip: *const InternPool) []NullTerminatedString {
513 return @ptrCast(ip.extra.items[slice.start..][0..slice.len]);
931 const extra = ip.getLocalShared(slice.tid).extra.acquire();
932 return @ptrCast(extra.view().items(.@"0")[slice.start..][0..slice.len]);
514933 }
515934 };
516935
......@@ -523,8 +942,8 @@ pub const NullTerminatedString = enum(u32) {
523942 }
524943
525944 pub fn toSlice(string: NullTerminatedString, ip: *const InternPool) [:0]const u8 {
526 const slice = ip.string_bytes.items[@intFromEnum(string)..];
527 return slice[0..std.mem.indexOfScalar(u8, slice, 0).? :0];
945 const overlong_slice = string.toString().toOverlongSlice(ip);
946 return overlong_slice[0..std.mem.indexOfScalar(u8, overlong_slice, 0).? :0];
528947 }
529948
530949 pub fn length(string: NullTerminatedString, ip: *const InternPool) u32 {
......@@ -532,7 +951,10 @@ pub const NullTerminatedString = enum(u32) {
532951 }
533952
534953 pub fn eqlSlice(string: NullTerminatedString, slice: []const u8, ip: *const InternPool) bool {
535 return std.mem.eql(u8, string.toSlice(ip), slice);
954 const overlong_slice = string.toString().toOverlongSlice(ip);
955 return overlong_slice.len > slice.len and
956 std.mem.eql(u8, overlong_slice[0..slice.len], slice) and
957 overlong_slice[slice.len] == 0;
536958 }
537959
538960 const Adapter = struct {
......@@ -580,12 +1002,12 @@ pub const NullTerminatedString = enum(u32) {
5801002 } else @compileError("invalid format string '" ++ specifier ++ "' for '" ++ @typeName(NullTerminatedString) ++ "'");
5811003 }
5821004
583 pub fn fmt(self: NullTerminatedString, ip: *const InternPool) std.fmt.Formatter(format) {
584 return .{ .data = .{ .string = self, .ip = ip } };
1005 pub fn fmt(string: NullTerminatedString, ip: *const InternPool) std.fmt.Formatter(format) {
1006 return .{ .data = .{ .string = string, .ip = ip } };
5851007 }
5861008};
5871009
588/// An index into `string_bytes` which might be `none`.
1010/// An index into `strings` which might be `none`.
5891011pub const OptionalNullTerminatedString = enum(u32) {
5901012 /// This is distinct from `none` - it is a valid index that represents empty string.
5911013 empty = 0,
......@@ -638,10 +1060,15 @@ pub const CaptureValue = packed struct(u32) {
6381060 };
6391061
6401062 pub const Slice = struct {
1063 tid: Zcu.PerThread.Id,
6411064 start: u32,
6421065 len: u32,
1066
1067 pub const empty: Slice = .{ .tid = .main, .start = 0, .len = 0 };
1068
6431069 pub fn get(slice: Slice, ip: *const InternPool) []CaptureValue {
644 return @ptrCast(ip.extra.items[slice.start..][0..slice.len]);
1070 const extra = ip.getLocalShared(slice.tid).extra.acquire();
1071 return @ptrCast(extra.view().items(.@"0")[slice.start..][0..slice.len]);
6451072 }
6461073 };
6471074};
......@@ -927,6 +1354,7 @@ pub const Key = union(enum) {
9271354 };
9281355
9291356 pub const Func = struct {
1357 tid: Zcu.PerThread.Id,
9301358 /// In the case of a generic function, this type will potentially have fewer parameters
9311359 /// than the generic owner's type, because the comptime parameters will be deleted.
9321360 ty: Index,
......@@ -982,23 +1410,27 @@ pub const Key = union(enum) {
9821410
9831411 /// Returns a pointer that becomes invalid after any additions to the `InternPool`.
9841412 pub fn analysis(func: *const Func, ip: *const InternPool) *FuncAnalysis {
985 return @ptrCast(&ip.extra.items[func.analysis_extra_index]);
1413 const extra = ip.getLocalShared(func.tid).extra.acquire();
1414 return @ptrCast(&extra.view().items(.@"0")[func.analysis_extra_index]);
9861415 }
9871416
9881417 /// Returns a pointer that becomes invalid after any additions to the `InternPool`.
9891418 pub fn zirBodyInst(func: *const Func, ip: *const InternPool) *TrackedInst.Index {
990 return @ptrCast(&ip.extra.items[func.zir_body_inst_extra_index]);
1419 const extra = ip.getLocalShared(func.tid).extra.acquire();
1420 return @ptrCast(&extra.view().items(.@"0")[func.zir_body_inst_extra_index]);
9911421 }
9921422
9931423 /// Returns a pointer that becomes invalid after any additions to the `InternPool`.
9941424 pub fn branchQuota(func: *const Func, ip: *const InternPool) *u32 {
995 return &ip.extra.items[func.branch_quota_extra_index];
1425 const extra = ip.getLocalShared(func.tid).extra.acquire();
1426 return &extra.view().items(.@"0")[func.branch_quota_extra_index];
9961427 }
9971428
9981429 /// Returns a pointer that becomes invalid after any additions to the `InternPool`.
9991430 pub fn resolvedErrorSet(func: *const Func, ip: *const InternPool) *Index {
1431 const extra = ip.getLocalShared(func.tid).extra.acquire();
10001432 assert(func.analysis(ip).inferred_error_set);
1001 return @ptrCast(&ip.extra.items[func.resolved_error_set_extra_index]);
1433 return @ptrCast(&extra.view().items(.@"0")[func.resolved_error_set_extra_index]);
10021434 }
10031435 };
10041436
......@@ -1841,6 +2273,7 @@ pub const RequiresComptime = enum(u2) { no, yes, unknown, wip };
18412273// minimal hashmap key, this type is a convenience type that contains info
18422274// needed by semantic analysis.
18432275pub const LoadedUnionType = struct {
2276 tid: Zcu.PerThread.Id,
18442277 /// The index of the `Tag.TypeUnion` payload.
18452278 extra_index: u32,
18462279 /// The Decl that corresponds to the union itself.
......@@ -1913,7 +2346,7 @@ pub const LoadedUnionType = struct {
19132346 }
19142347 };
19152348
1916 pub fn loadTagType(self: LoadedUnionType, ip: *InternPool) LoadedEnumType {
2349 pub fn loadTagType(self: LoadedUnionType, ip: *const InternPool) LoadedEnumType {
19172350 return ip.loadEnumType(self.enum_tag_ty);
19182351 }
19192352
......@@ -1926,26 +2359,30 @@ pub const LoadedUnionType = struct {
19262359 /// when it is mutated, the mutations are observed.
19272360 /// The returned pointer expires with any addition to the `InternPool`.
19282361 pub fn tagTypePtr(self: LoadedUnionType, ip: *const InternPool) *Index {
2362 const extra = ip.getLocalShared(self.tid).extra.acquire();
19292363 const field_index = std.meta.fieldIndex(Tag.TypeUnion, "tag_ty").?;
1930 return @ptrCast(&ip.extra.items[self.extra_index + field_index]);
2364 return @ptrCast(&extra.view().items(.@"0")[self.extra_index + field_index]);
19312365 }
19322366
19332367 /// The returned pointer expires with any addition to the `InternPool`.
19342368 pub fn flagsPtr(self: LoadedUnionType, ip: *const InternPool) *Tag.TypeUnion.Flags {
2369 const extra = ip.getLocalShared(self.tid).extra.acquire();
19352370 const field_index = std.meta.fieldIndex(Tag.TypeUnion, "flags").?;
1936 return @ptrCast(&ip.extra.items[self.extra_index + field_index]);
2371 return @ptrCast(&extra.view().items(.@"0")[self.extra_index + field_index]);
19372372 }
19382373
19392374 /// The returned pointer expires with any addition to the `InternPool`.
19402375 pub fn size(self: LoadedUnionType, ip: *const InternPool) *u32 {
2376 const extra = ip.getLocalShared(self.tid).extra.acquire();
19412377 const field_index = std.meta.fieldIndex(Tag.TypeUnion, "size").?;
1942 return &ip.extra.items[self.extra_index + field_index];
2378 return &extra.view().items(.@"0")[self.extra_index + field_index];
19432379 }
19442380
19452381 /// The returned pointer expires with any addition to the `InternPool`.
19462382 pub fn padding(self: LoadedUnionType, ip: *const InternPool) *u32 {
2383 const extra = ip.getLocalShared(self.tid).extra.acquire();
19472384 const field_index = std.meta.fieldIndex(Tag.TypeUnion, "padding").?;
1948 return &ip.extra.items[self.extra_index + field_index];
2385 return &extra.view().items(.@"0")[self.extra_index + field_index];
19492386 }
19502387
19512388 pub fn hasTag(self: LoadedUnionType, ip: *const InternPool) bool {
......@@ -1974,7 +2411,7 @@ pub const LoadedUnionType = struct {
19742411 const flags_field_index = std.meta.fieldIndex(Tag.TypeUnion, "flags").?;
19752412 const zir_index_field_index = std.meta.fieldIndex(Tag.TypeUnion, "zir_index").?;
19762413 const ptr: *TrackedInst.Index.Optional =
1977 @ptrCast(&ip.extra.items[self.flags_index - flags_field_index + zir_index_field_index]);
2414 @ptrCast(&ip.extra_.items[self.flags_index - flags_field_index + zir_index_field_index]);
19782415 ptr.* = new_zir_index;
19792416 }
19802417
......@@ -1990,18 +2427,21 @@ pub const LoadedUnionType = struct {
19902427};
19912428
19922429pub fn loadUnionType(ip: *const InternPool, index: Index) LoadedUnionType {
1993 const data = ip.items.items(.data)[@intFromEnum(index)];
1994 const type_union = ip.extraDataTrail(Tag.TypeUnion, data);
2430 const unwrapped_index = index.unwrap(ip);
2431 const extra_list = unwrapped_index.getExtra(ip);
2432 const data = unwrapped_index.getData(ip);
2433 const type_union = extraDataTrail(extra_list, Tag.TypeUnion, data);
19952434 const fields_len = type_union.data.fields_len;
19962435
19972436 var extra_index = type_union.end;
19982437 const captures_len = if (type_union.data.flags.any_captures) c: {
1999 const len = ip.extra.items[extra_index];
2438 const len = extra_list.view().items(.@"0")[extra_index];
20002439 extra_index += 1;
20012440 break :c len;
20022441 } else 0;
20032442
20042443 const captures: CaptureValue.Slice = .{
2444 .tid = unwrapped_index.tid,
20052445 .start = extra_index,
20062446 .len = captures_len,
20072447 };
......@@ -2011,21 +2451,24 @@ pub fn loadUnionType(ip: *const InternPool, index: Index) LoadedUnionType {
20112451 }
20122452
20132453 const field_types: Index.Slice = .{
2454 .tid = unwrapped_index.tid,
20142455 .start = extra_index,
20152456 .len = fields_len,
20162457 };
20172458 extra_index += fields_len;
20182459
2019 const field_aligns: Alignment.Slice = if (type_union.data.flags.any_aligned_fields) a: {
2460 const field_aligns = if (type_union.data.flags.any_aligned_fields) a: {
20202461 const a: Alignment.Slice = .{
2462 .tid = unwrapped_index.tid,
20212463 .start = extra_index,
20222464 .len = fields_len,
20232465 };
20242466 extra_index += std.math.divCeil(u32, fields_len, 4) catch unreachable;
20252467 break :a a;
2026 } else .{ .start = 0, .len = 0 };
2468 } else Alignment.Slice.empty;
20272469
20282470 return .{
2471 .tid = unwrapped_index.tid,
20292472 .extra_index = data,
20302473 .decl = type_union.data.decl,
20312474 .namespace = type_union.data.namespace,
......@@ -2038,6 +2481,7 @@ pub fn loadUnionType(ip: *const InternPool, index: Index) LoadedUnionType {
20382481}
20392482
20402483pub const LoadedStructType = struct {
2484 tid: Zcu.PerThread.Id,
20412485 /// The index of the `Tag.TypeStruct` or `Tag.TypeStructPacked` payload.
20422486 extra_index: u32,
20432487 /// The struct's owner Decl. `none` when the struct is `@TypeOf(.{})`.
......@@ -2059,12 +2503,16 @@ pub const LoadedStructType = struct {
20592503 captures: CaptureValue.Slice,
20602504
20612505 pub const ComptimeBits = struct {
2506 tid: Zcu.PerThread.Id,
20622507 start: u32,
20632508 /// This is the number of u32 elements, not the number of struct fields.
20642509 len: u32,
20652510
2511 pub const empty: ComptimeBits = .{ .tid = .main, .start = 0, .len = 0 };
2512
20662513 pub fn get(this: ComptimeBits, ip: *const InternPool) []u32 {
2067 return ip.extra.items[this.start..][0..this.len];
2514 const extra = ip.getLocalShared(this.tid).extra.acquire();
2515 return extra.view().items(.@"0")[this.start..][0..this.len];
20682516 }
20692517
20702518 pub fn getBit(this: ComptimeBits, ip: *const InternPool, i: usize) bool {
......@@ -2082,11 +2530,15 @@ pub const LoadedStructType = struct {
20822530 };
20832531
20842532 pub const Offsets = struct {
2533 tid: Zcu.PerThread.Id,
20852534 start: u32,
20862535 len: u32,
20872536
2537 pub const empty: Offsets = .{ .tid = .main, .start = 0, .len = 0 };
2538
20882539 pub fn get(this: Offsets, ip: *const InternPool) []u32 {
2089 return @ptrCast(ip.extra.items[this.start..][0..this.len]);
2540 const extra = ip.getLocalShared(this.tid).extra.acquire();
2541 return @ptrCast(extra.view().items(.@"0")[this.start..][0..this.len]);
20902542 }
20912543 };
20922544
......@@ -2098,11 +2550,15 @@ pub const LoadedStructType = struct {
20982550 _,
20992551
21002552 pub const Slice = struct {
2553 tid: Zcu.PerThread.Id,
21012554 start: u32,
21022555 len: u32,
21032556
2557 pub const empty: Slice = .{ .tid = .main, .start = 0, .len = 0 };
2558
21042559 pub fn get(slice: RuntimeOrder.Slice, ip: *const InternPool) []RuntimeOrder {
2105 return @ptrCast(ip.extra.items[slice.start..][0..slice.len]);
2560 const extra = ip.getLocalShared(slice.tid).extra.acquire();
2561 return @ptrCast(extra.view().items(.@"0")[slice.start..][0..slice.len]);
21062562 }
21072563 };
21082564
......@@ -2134,7 +2590,8 @@ pub const LoadedStructType = struct {
21342590 ip: *InternPool,
21352591 name: NullTerminatedString,
21362592 ) ?u32 {
2137 return ip.addFieldName(self.names_map.unwrap().?, self.field_names.start, name);
2593 const extra = ip.getLocalShared(self.tid).extra.acquire();
2594 return ip.addFieldName(extra, self.names_map.unwrap().?, self.field_names.start, name);
21382595 }
21392596
21402597 pub fn fieldAlign(s: LoadedStructType, ip: *const InternPool, i: usize) Alignment {
......@@ -2142,7 +2599,7 @@ pub const LoadedStructType = struct {
21422599 return s.field_aligns.get(ip)[i];
21432600 }
21442601
2145 pub fn fieldInit(s: LoadedStructType, ip: *const InternPool, i: usize) Index {
2602 pub fn fieldInit(s: LoadedStructType, ip: *InternPool, i: usize) Index {
21462603 if (s.field_inits.len == 0) return .none;
21472604 assert(s.haveFieldInits(ip));
21482605 return s.field_inits.get(ip)[i];
......@@ -2173,18 +2630,20 @@ pub const LoadedStructType = struct {
21732630
21742631 /// The returned pointer expires with any addition to the `InternPool`.
21752632 /// Asserts the struct is not packed.
2176 pub fn flagsPtr(self: LoadedStructType, ip: *const InternPool) *Tag.TypeStruct.Flags {
2633 pub fn flagsPtr(self: LoadedStructType, ip: *InternPool) *Tag.TypeStruct.Flags {
21772634 assert(self.layout != .@"packed");
2635 const extra = ip.getLocalShared(self.tid).extra.acquire();
21782636 const flags_field_index = std.meta.fieldIndex(Tag.TypeStruct, "flags").?;
2179 return @ptrCast(&ip.extra.items[self.extra_index + flags_field_index]);
2637 return @ptrCast(&extra.view().items(.@"0")[self.extra_index + flags_field_index]);
21802638 }
21812639
21822640 /// The returned pointer expires with any addition to the `InternPool`.
21832641 /// Asserts that the struct is packed.
2184 pub fn packedFlagsPtr(self: LoadedStructType, ip: *const InternPool) *Tag.TypeStructPacked.Flags {
2642 pub fn packedFlagsPtr(self: LoadedStructType, ip: *InternPool) *Tag.TypeStructPacked.Flags {
21852643 assert(self.layout == .@"packed");
2644 const extra = ip.getLocalShared(self.tid).extra.acquire();
21862645 const flags_field_index = std.meta.fieldIndex(Tag.TypeStructPacked, "flags").?;
2187 return @ptrCast(&ip.extra.items[self.extra_index + flags_field_index]);
2646 return @ptrCast(&extra.view().items(.@"0")[self.extra_index + flags_field_index]);
21882647 }
21892648
21902649 pub fn assumeRuntimeBitsIfFieldTypesWip(s: LoadedStructType, ip: *InternPool) bool {
......@@ -2276,25 +2735,27 @@ pub const LoadedStructType = struct {
22762735 /// Asserts the struct is not packed.
22772736 pub fn size(self: LoadedStructType, ip: *InternPool) *u32 {
22782737 assert(self.layout != .@"packed");
2738 const extra = ip.getLocalShared(self.tid).extra.acquire();
22792739 const size_field_index = std.meta.fieldIndex(Tag.TypeStruct, "size").?;
2280 return @ptrCast(&ip.extra.items[self.extra_index + size_field_index]);
2740 return @ptrCast(&extra.view().items(.@"0")[self.extra_index + size_field_index]);
22812741 }
22822742
22832743 /// The backing integer type of the packed struct. Whether zig chooses
22842744 /// this type or the user specifies it, it is stored here. This will be
22852745 /// set to `none` until the layout is resolved.
22862746 /// Asserts the struct is packed.
2287 pub fn backingIntType(s: LoadedStructType, ip: *const InternPool) *Index {
2747 pub fn backingIntType(s: LoadedStructType, ip: *InternPool) *Index {
22882748 assert(s.layout == .@"packed");
2749 const extra = ip.getLocalShared(s.tid).extra.acquire();
22892750 const field_index = std.meta.fieldIndex(Tag.TypeStructPacked, "backing_int_ty").?;
2290 return @ptrCast(&ip.extra.items[s.extra_index + field_index]);
2751 return @ptrCast(&extra.view().items(.@"0")[s.extra_index + field_index]);
22912752 }
22922753
22932754 /// Asserts the struct is not packed.
22942755 pub fn setZirIndex(s: LoadedStructType, ip: *InternPool, new_zir_index: TrackedInst.Index.Optional) void {
22952756 assert(s.layout != .@"packed");
22962757 const field_index = std.meta.fieldIndex(Tag.TypeStruct, "zir_index").?;
2297 ip.extra.items[s.extra_index + field_index] = @intFromEnum(new_zir_index);
2758 ip.extra_.items[s.extra_index + field_index] = @intFromEnum(new_zir_index);
22982759 }
22992760
23002761 pub fn haveFieldTypes(s: LoadedStructType, ip: *const InternPool) bool {
......@@ -2302,7 +2763,7 @@ pub const LoadedStructType = struct {
23022763 return types.len == 0 or types[0] != .none;
23032764 }
23042765
2305 pub fn haveFieldInits(s: LoadedStructType, ip: *const InternPool) bool {
2766 pub fn haveFieldInits(s: LoadedStructType, ip: *InternPool) bool {
23062767 return switch (s.layout) {
23072768 .@"packed" => s.packedFlagsPtr(ip).inits_resolved,
23082769 .auto, .@"extern" => s.flagsPtr(ip).inits_resolved,
......@@ -2412,34 +2873,38 @@ pub const LoadedStructType = struct {
24122873};
24132874
24142875pub fn loadStructType(ip: *const InternPool, index: Index) LoadedStructType {
2415 const item = ip.items.get(@intFromEnum(index));
2876 const unwrapped_index = index.unwrap(ip);
2877 const extra_list = unwrapped_index.getExtra(ip);
2878 const item = unwrapped_index.getItem(ip);
24162879 switch (item.tag) {
24172880 .type_struct => {
24182881 if (item.data == 0) return .{
2882 .tid = .main,
24192883 .extra_index = 0,
24202884 .decl = .none,
24212885 .namespace = .none,
24222886 .zir_index = .none,
24232887 .layout = .auto,
2424 .field_names = .{ .start = 0, .len = 0 },
2425 .field_types = .{ .start = 0, .len = 0 },
2426 .field_inits = .{ .start = 0, .len = 0 },
2427 .field_aligns = .{ .start = 0, .len = 0 },
2428 .runtime_order = .{ .start = 0, .len = 0 },
2429 .comptime_bits = .{ .start = 0, .len = 0 },
2430 .offsets = .{ .start = 0, .len = 0 },
2888 .field_names = NullTerminatedString.Slice.empty,
2889 .field_types = Index.Slice.empty,
2890 .field_inits = Index.Slice.empty,
2891 .field_aligns = Alignment.Slice.empty,
2892 .runtime_order = LoadedStructType.RuntimeOrder.Slice.empty,
2893 .comptime_bits = LoadedStructType.ComptimeBits.empty,
2894 .offsets = LoadedStructType.Offsets.empty,
24312895 .names_map = .none,
2432 .captures = .{ .start = 0, .len = 0 },
2896 .captures = CaptureValue.Slice.empty,
24332897 };
2434 const extra = ip.extraDataTrail(Tag.TypeStruct, item.data);
2898 const extra = extraDataTrail(extra_list, Tag.TypeStruct, item.data);
24352899 const fields_len = extra.data.fields_len;
24362900 var extra_index = extra.end;
24372901 const captures_len = if (extra.data.flags.any_captures) c: {
2438 const len = ip.extra.items[extra_index];
2902 const len = extra_list.view().items(.@"0")[extra_index];
24392903 extra_index += 1;
24402904 break :c len;
24412905 } else 0;
24422906 const captures: CaptureValue.Slice = .{
2907 .tid = unwrapped_index.tid,
24432908 .start = extra_index,
24442909 .len = captures_len,
24452910 };
......@@ -2448,49 +2913,75 @@ pub fn loadStructType(ip: *const InternPool, index: Index) LoadedStructType {
24482913 extra_index += 2; // PackedU64
24492914 }
24502915 const field_types: Index.Slice = .{
2916 .tid = unwrapped_index.tid,
24512917 .start = extra_index,
24522918 .len = fields_len,
24532919 };
24542920 extra_index += fields_len;
2455 const names_map: OptionalMapIndex, const names: NullTerminatedString.Slice = if (!extra.data.flags.is_tuple) n: {
2456 const names_map: OptionalMapIndex = @enumFromInt(ip.extra.items[extra_index]);
2921 const names_map: OptionalMapIndex, const names = if (!extra.data.flags.is_tuple) n: {
2922 const names_map: OptionalMapIndex = @enumFromInt(extra_list.view().items(.@"0")[extra_index]);
24572923 extra_index += 1;
2458 const names: NullTerminatedString.Slice = .{ .start = extra_index, .len = fields_len };
2924 const names: NullTerminatedString.Slice = .{
2925 .tid = unwrapped_index.tid,
2926 .start = extra_index,
2927 .len = fields_len,
2928 };
24592929 extra_index += fields_len;
24602930 break :n .{ names_map, names };
2461 } else .{ .none, .{ .start = 0, .len = 0 } };
2931 } else .{ .none, NullTerminatedString.Slice.empty };
24622932 const inits: Index.Slice = if (extra.data.flags.any_default_inits) i: {
2463 const inits: Index.Slice = .{ .start = extra_index, .len = fields_len };
2933 const inits: Index.Slice = .{
2934 .tid = unwrapped_index.tid,
2935 .start = extra_index,
2936 .len = fields_len,
2937 };
24642938 extra_index += fields_len;
24652939 break :i inits;
2466 } else .{ .start = 0, .len = 0 };
2940 } else Index.Slice.empty;
24672941 const namespace: OptionalNamespaceIndex = if (extra.data.flags.has_namespace) n: {
2468 const n: NamespaceIndex = @enumFromInt(ip.extra.items[extra_index]);
2942 const n: NamespaceIndex = @enumFromInt(extra_list.view().items(.@"0")[extra_index]);
24692943 extra_index += 1;
24702944 break :n n.toOptional();
24712945 } else .none;
24722946 const aligns: Alignment.Slice = if (extra.data.flags.any_aligned_fields) a: {
2473 const a: Alignment.Slice = .{ .start = extra_index, .len = fields_len };
2947 const a: Alignment.Slice = .{
2948 .tid = unwrapped_index.tid,
2949 .start = extra_index,
2950 .len = fields_len,
2951 };
24742952 extra_index += std.math.divCeil(u32, fields_len, 4) catch unreachable;
24752953 break :a a;
2476 } else .{ .start = 0, .len = 0 };
2954 } else Alignment.Slice.empty;
24772955 const comptime_bits: LoadedStructType.ComptimeBits = if (extra.data.flags.any_comptime_fields) c: {
24782956 const len = std.math.divCeil(u32, fields_len, 32) catch unreachable;
2479 const c: LoadedStructType.ComptimeBits = .{ .start = extra_index, .len = len };
2957 const c: LoadedStructType.ComptimeBits = .{
2958 .tid = unwrapped_index.tid,
2959 .start = extra_index,
2960 .len = len,
2961 };
24802962 extra_index += len;
24812963 break :c c;
2482 } else .{ .start = 0, .len = 0 };
2964 } else LoadedStructType.ComptimeBits.empty;
24832965 const runtime_order: LoadedStructType.RuntimeOrder.Slice = if (!extra.data.flags.is_extern) ro: {
2484 const ro: LoadedStructType.RuntimeOrder.Slice = .{ .start = extra_index, .len = fields_len };
2966 const ro: LoadedStructType.RuntimeOrder.Slice = .{
2967 .tid = unwrapped_index.tid,
2968 .start = extra_index,
2969 .len = fields_len,
2970 };
24852971 extra_index += fields_len;
24862972 break :ro ro;
2487 } else .{ .start = 0, .len = 0 };
2973 } else LoadedStructType.RuntimeOrder.Slice.empty;
24882974 const offsets: LoadedStructType.Offsets = o: {
2489 const o: LoadedStructType.Offsets = .{ .start = extra_index, .len = fields_len };
2975 const o: LoadedStructType.Offsets = .{
2976 .tid = unwrapped_index.tid,
2977 .start = extra_index,
2978 .len = fields_len,
2979 };
24902980 extra_index += fields_len;
24912981 break :o o;
24922982 };
24932983 return .{
2984 .tid = unwrapped_index.tid,
24942985 .extra_index = item.data,
24952986 .decl = extra.data.decl.toOptional(),
24962987 .namespace = namespace,
......@@ -2508,16 +2999,17 @@ pub fn loadStructType(ip: *const InternPool, index: Index) LoadedStructType {
25082999 };
25093000 },
25103001 .type_struct_packed, .type_struct_packed_inits => {
2511 const extra = ip.extraDataTrail(Tag.TypeStructPacked, item.data);
3002 const extra = extraDataTrail(extra_list, Tag.TypeStructPacked, item.data);
25123003 const has_inits = item.tag == .type_struct_packed_inits;
25133004 const fields_len = extra.data.fields_len;
25143005 var extra_index = extra.end;
25153006 const captures_len = if (extra.data.flags.any_captures) c: {
2516 const len = ip.extra.items[extra_index];
3007 const len = extra_list.view().items(.@"0")[extra_index];
25173008 extra_index += 1;
25183009 break :c len;
25193010 } else 0;
25203011 const captures: CaptureValue.Slice = .{
3012 .tid = unwrapped_index.tid,
25213013 .start = extra_index,
25223014 .len = captures_len,
25233015 };
......@@ -2526,24 +3018,28 @@ pub fn loadStructType(ip: *const InternPool, index: Index) LoadedStructType {
25263018 extra_index += 2; // PackedU64
25273019 }
25283020 const field_types: Index.Slice = .{
3021 .tid = unwrapped_index.tid,
25293022 .start = extra_index,
25303023 .len = fields_len,
25313024 };
25323025 extra_index += fields_len;
25333026 const field_names: NullTerminatedString.Slice = .{
3027 .tid = unwrapped_index.tid,
25343028 .start = extra_index,
25353029 .len = fields_len,
25363030 };
25373031 extra_index += fields_len;
25383032 const field_inits: Index.Slice = if (has_inits) inits: {
25393033 const i: Index.Slice = .{
3034 .tid = unwrapped_index.tid,
25403035 .start = extra_index,
25413036 .len = fields_len,
25423037 };
25433038 extra_index += fields_len;
25443039 break :inits i;
2545 } else .{ .start = 0, .len = 0 };
3040 } else Index.Slice.empty;
25463041 return .{
3042 .tid = unwrapped_index.tid,
25473043 .extra_index = item.data,
25483044 .decl = extra.data.decl.toOptional(),
25493045 .namespace = extra.data.namespace,
......@@ -2552,10 +3048,10 @@ pub fn loadStructType(ip: *const InternPool, index: Index) LoadedStructType {
25523048 .field_names = field_names,
25533049 .field_types = field_types,
25543050 .field_inits = field_inits,
2555 .field_aligns = .{ .start = 0, .len = 0 },
2556 .runtime_order = .{ .start = 0, .len = 0 },
2557 .comptime_bits = .{ .start = 0, .len = 0 },
2558 .offsets = .{ .start = 0, .len = 0 },
3051 .field_aligns = Alignment.Slice.empty,
3052 .runtime_order = LoadedStructType.RuntimeOrder.Slice.empty,
3053 .comptime_bits = LoadedStructType.ComptimeBits.empty,
3054 .offsets = LoadedStructType.Offsets.empty,
25593055 .names_map = extra.data.names_map.toOptional(),
25603056 .captures = captures,
25613057 };
......@@ -2636,10 +3132,12 @@ const LoadedEnumType = struct {
26363132};
26373133
26383134pub fn loadEnumType(ip: *const InternPool, index: Index) LoadedEnumType {
2639 const item = ip.items.get(@intFromEnum(index));
3135 const unwrapped_index = index.unwrap(ip);
3136 const extra_list = unwrapped_index.getExtra(ip);
3137 const item = unwrapped_index.getItem(ip);
26403138 const tag_mode: LoadedEnumType.TagMode = switch (item.tag) {
26413139 .type_enum_auto => {
2642 const extra = ip.extraDataTrail(EnumAuto, item.data);
3140 const extra = extraDataTrail(extra_list, EnumAuto, item.data);
26433141 var extra_index: u32 = @intCast(extra.end);
26443142 if (extra.data.zir_index == .none) {
26453143 extra_index += 1; // owner_union
......@@ -2653,15 +3151,17 @@ pub fn loadEnumType(ip: *const InternPool, index: Index) LoadedEnumType {
26533151 .namespace = extra.data.namespace,
26543152 .tag_ty = extra.data.int_tag_type,
26553153 .names = .{
3154 .tid = unwrapped_index.tid,
26563155 .start = extra_index + captures_len,
26573156 .len = extra.data.fields_len,
26583157 },
2659 .values = .{ .start = 0, .len = 0 },
3158 .values = Index.Slice.empty,
26603159 .tag_mode = .auto,
26613160 .names_map = extra.data.names_map,
26623161 .values_map = .none,
26633162 .zir_index = extra.data.zir_index,
26643163 .captures = .{
3164 .tid = unwrapped_index.tid,
26653165 .start = extra_index,
26663166 .len = captures_len,
26673167 },
......@@ -2671,7 +3171,7 @@ pub fn loadEnumType(ip: *const InternPool, index: Index) LoadedEnumType {
26713171 .type_enum_nonexhaustive => .nonexhaustive,
26723172 else => unreachable,
26733173 };
2674 const extra = ip.extraDataTrail(EnumExplicit, item.data);
3174 const extra = extraDataTrail(extra_list, EnumExplicit, item.data);
26753175 var extra_index: u32 = @intCast(extra.end);
26763176 if (extra.data.zir_index == .none) {
26773177 extra_index += 1; // owner_union
......@@ -2685,10 +3185,12 @@ pub fn loadEnumType(ip: *const InternPool, index: Index) LoadedEnumType {
26853185 .namespace = extra.data.namespace,
26863186 .tag_ty = extra.data.int_tag_type,
26873187 .names = .{
3188 .tid = unwrapped_index.tid,
26883189 .start = extra_index + captures_len,
26893190 .len = extra.data.fields_len,
26903191 },
26913192 .values = .{
3193 .tid = unwrapped_index.tid,
26923194 .start = extra_index + captures_len + extra.data.fields_len,
26933195 .len = if (extra.data.values_map != .none) extra.data.fields_len else 0,
26943196 },
......@@ -2697,6 +3199,7 @@ pub fn loadEnumType(ip: *const InternPool, index: Index) LoadedEnumType {
26973199 .values_map = extra.data.values_map,
26983200 .zir_index = extra.data.zir_index,
26993201 .captures = .{
3202 .tid = unwrapped_index.tid,
27003203 .start = extra_index,
27013204 .len = captures_len,
27023205 },
......@@ -2715,9 +3218,10 @@ pub const LoadedOpaqueType = struct {
27153218};
27163219
27173220pub fn loadOpaqueType(ip: *const InternPool, index: Index) LoadedOpaqueType {
2718 assert(ip.items.items(.tag)[@intFromEnum(index)] == .type_opaque);
2719 const extra_index = ip.items.items(.data)[@intFromEnum(index)];
2720 const extra = ip.extraDataTrail(Tag.TypeOpaque, extra_index);
3221 const unwrapped_index = index.unwrap(ip);
3222 const item = unwrapped_index.getItem(ip);
3223 assert(item.tag == .type_opaque);
3224 const extra = extraDataTrail(unwrapped_index.getExtra(ip), Tag.TypeOpaque, item.data);
27213225 const captures_len = if (extra.data.captures_len == std.math.maxInt(u32))
27223226 0
27233227 else
......@@ -2727,6 +3231,7 @@ pub fn loadOpaqueType(ip: *const InternPool, index: Index) LoadedOpaqueType {
27273231 .namespace = extra.data.namespace,
27283232 .zir_index = extra.data.zir_index,
27293233 .captures = .{
3234 .tid = unwrapped_index.tid,
27303235 .start = extra.end,
27313236 .len = captures_len,
27323237 },
......@@ -2869,11 +3374,15 @@ pub const Index = enum(u32) {
28693374 /// This type exists to provide a struct with lifetime that is
28703375 /// not invalidated when items are added to the `InternPool`.
28713376 pub const Slice = struct {
3377 tid: Zcu.PerThread.Id,
28723378 start: u32,
28733379 len: u32,
28743380
3381 pub const empty: Slice = .{ .tid = .main, .start = 0, .len = 0 };
3382
28753383 pub fn get(slice: Slice, ip: *const InternPool) []Index {
2876 return @ptrCast(ip.extra.items[slice.start..][0..slice.len]);
3384 const extra = ip.getLocalShared(slice.tid).extra.acquire();
3385 return @ptrCast(extra.view().items(.@"0")[slice.start..][0..slice.len]);
28773386 }
28783387 };
28793388
......@@ -2892,6 +3401,57 @@ pub const Index = enum(u32) {
28923401 }
28933402 };
28943403
3404 const Unwrapped = struct {
3405 tid: Zcu.PerThread.Id,
3406 index: u32,
3407
3408 fn wrap(unwrapped: Unwrapped, ip: *const InternPool) Index {
3409 assert(@intFromEnum(unwrapped.tid) <= ip.getTidMask());
3410 assert(unwrapped.index <= ip.getIndexMask(u31));
3411 return @enumFromInt(@as(u32, @intFromEnum(unwrapped.tid)) << ip.tid_shift_31 | unwrapped.index);
3412 }
3413
3414 pub fn getExtra(unwrapped: Unwrapped, ip: *const InternPool) Local.Extra {
3415 return ip.getLocalShared(unwrapped.tid).extra.acquire();
3416 }
3417
3418 pub fn getItem(unwrapped: Unwrapped, ip: *const InternPool) Item {
3419 const item_ptr = unwrapped.itemPtr(ip);
3420 const tag = @atomicLoad(Tag, item_ptr.tag_ptr, .acquire);
3421 return .{ .tag = tag, .data = item_ptr.data_ptr.* };
3422 }
3423
3424 pub fn getTag(unwrapped: Unwrapped, ip: *const InternPool) Tag {
3425 const item_ptr = unwrapped.itemPtr(ip);
3426 return @atomicLoad(Tag, item_ptr.tag_ptr, .acquire);
3427 }
3428
3429 pub fn getData(unwrapped: Unwrapped, ip: *const InternPool) u32 {
3430 return unwrapped.getItem(ip).data;
3431 }
3432
3433 const ItemPtr = struct {
3434 tag_ptr: *Tag,
3435 data_ptr: *u32,
3436 };
3437 fn itemPtr(unwrapped: Unwrapped, ip: *const InternPool) ItemPtr {
3438 const slice = ip.getLocalShared(unwrapped.tid).items.acquire().view().slice();
3439 return .{
3440 .tag_ptr = &slice.items(.tag)[unwrapped.index],
3441 .data_ptr = &slice.items(.data)[unwrapped.index],
3442 };
3443 }
3444 };
3445 pub fn unwrap(index: Index, ip: *const InternPool) Unwrapped {
3446 return if (single_threaded) .{
3447 .tid = .main,
3448 .index = @intFromEnum(index),
3449 } else .{
3450 .tid = @enumFromInt(@intFromEnum(index) >> ip.tid_shift_31 & ip.getTidMask()),
3451 .index = @intFromEnum(index) & ip.getIndexMask(u31),
3452 };
3453 }
3454
28953455 /// This function is used in the debugger pretty formatters in tools/ to fetch the
28963456 /// Tag to encoding mapping to facilitate fancy debug printing for this type.
28973457 /// TODO merge this with `Tag.Payload`.
......@@ -2947,7 +3507,7 @@ pub const Index = enum(u32) {
29473507 },
29483508 type_enum_explicit: DataIsExtraIndexOfEnumExplicit,
29493509 type_enum_nonexhaustive: DataIsExtraIndexOfEnumExplicit,
2950 simple_type: struct { data: SimpleType },
3510 simple_type: void,
29513511 type_opaque: struct { data: *Tag.TypeOpaque },
29523512 type_struct: struct { data: *Tag.TypeStruct },
29533513 type_struct_anon: DataIsExtraIndexOfTypeStructAnon,
......@@ -2967,7 +3527,7 @@ pub const Index = enum(u32) {
29673527 },
29683528
29693529 undef: DataIsIndex,
2970 simple_value: struct { data: SimpleValue },
3530 simple_value: void,
29713531 ptr_decl: struct { data: *PtrDecl },
29723532 ptr_comptime_alloc: struct { data: *PtrComptimeAlloc },
29733533 ptr_anon_decl: struct { data: *PtrAnonDecl },
......@@ -3250,9 +3810,9 @@ pub const static_keys = [_]Key{
32503810
32513811 // empty_struct_type
32523812 .{ .anon_struct_type = .{
3253 .types = .{ .start = 0, .len = 0 },
3254 .names = .{ .start = 0, .len = 0 },
3255 .values = .{ .start = 0, .len = 0 },
3813 .types = Index.Slice.empty,
3814 .names = NullTerminatedString.Slice.empty,
3815 .values = Index.Slice.empty,
32563816 } },
32573817
32583818 .{ .simple_value = .undefined },
......@@ -3969,7 +4529,7 @@ pub const FuncAnalysis = packed struct(u32) {
39694529pub const Bytes = struct {
39704530 /// The type of the aggregate
39714531 ty: Index,
3972 /// Index into string_bytes, of len ip.aggregateTypeLen(ty)
4532 /// Index into strings, of len ip.aggregateTypeLen(ty)
39734533 bytes: String,
39744534};
39754535
......@@ -3993,64 +4553,64 @@ pub const TypeStructAnon = struct {
39934553/// implement logic that only wants to deal with types because the logic can
39944554/// ignore all simple values. Note that technically, types are values.
39954555pub const SimpleType = enum(u32) {
3996 f16,
3997 f32,
3998 f64,
3999 f80,
4000 f128,
4001 usize,
4002 isize,
4003 c_char,
4004 c_short,
4005 c_ushort,
4006 c_int,
4007 c_uint,
4008 c_long,
4009 c_ulong,
4010 c_longlong,
4011 c_ulonglong,
4012 c_longdouble,
4013 anyopaque,
4014 bool,
4015 void,
4016 type,
4017 anyerror,
4018 comptime_int,
4019 comptime_float,
4020 noreturn,
4021 null,
4022 undefined,
4023 enum_literal,
4024
4025 atomic_order,
4026 atomic_rmw_op,
4027 calling_convention,
4028 address_space,
4029 float_mode,
4030 reduce_op,
4031 call_modifier,
4032 prefetch_options,
4033 export_options,
4034 extern_options,
4035 type_info,
4036
4037 adhoc_inferred_error_set,
4038 generic_poison,
4556 f16 = @intFromEnum(Index.f16_type),
4557 f32 = @intFromEnum(Index.f32_type),
4558 f64 = @intFromEnum(Index.f64_type),
4559 f80 = @intFromEnum(Index.f80_type),
4560 f128 = @intFromEnum(Index.f128_type),
4561 usize = @intFromEnum(Index.usize_type),
4562 isize = @intFromEnum(Index.isize_type),
4563 c_char = @intFromEnum(Index.c_char_type),
4564 c_short = @intFromEnum(Index.c_short_type),
4565 c_ushort = @intFromEnum(Index.c_ushort_type),
4566 c_int = @intFromEnum(Index.c_int_type),
4567 c_uint = @intFromEnum(Index.c_uint_type),
4568 c_long = @intFromEnum(Index.c_long_type),
4569 c_ulong = @intFromEnum(Index.c_ulong_type),
4570 c_longlong = @intFromEnum(Index.c_longlong_type),
4571 c_ulonglong = @intFromEnum(Index.c_ulonglong_type),
4572 c_longdouble = @intFromEnum(Index.c_longdouble_type),
4573 anyopaque = @intFromEnum(Index.anyopaque_type),
4574 bool = @intFromEnum(Index.bool_type),
4575 void = @intFromEnum(Index.void_type),
4576 type = @intFromEnum(Index.type_type),
4577 anyerror = @intFromEnum(Index.anyerror_type),
4578 comptime_int = @intFromEnum(Index.comptime_int_type),
4579 comptime_float = @intFromEnum(Index.comptime_float_type),
4580 noreturn = @intFromEnum(Index.noreturn_type),
4581 null = @intFromEnum(Index.null_type),
4582 undefined = @intFromEnum(Index.undefined_type),
4583 enum_literal = @intFromEnum(Index.enum_literal_type),
4584
4585 atomic_order = @intFromEnum(Index.atomic_order_type),
4586 atomic_rmw_op = @intFromEnum(Index.atomic_rmw_op_type),
4587 calling_convention = @intFromEnum(Index.calling_convention_type),
4588 address_space = @intFromEnum(Index.address_space_type),
4589 float_mode = @intFromEnum(Index.float_mode_type),
4590 reduce_op = @intFromEnum(Index.reduce_op_type),
4591 call_modifier = @intFromEnum(Index.call_modifier_type),
4592 prefetch_options = @intFromEnum(Index.prefetch_options_type),
4593 export_options = @intFromEnum(Index.export_options_type),
4594 extern_options = @intFromEnum(Index.extern_options_type),
4595 type_info = @intFromEnum(Index.type_info_type),
4596
4597 adhoc_inferred_error_set = @intFromEnum(Index.adhoc_inferred_error_set_type),
4598 generic_poison = @intFromEnum(Index.generic_poison_type),
40394599};
40404600
40414601pub const SimpleValue = enum(u32) {
40424602 /// This is untyped `undefined`.
4043 undefined,
4044 void,
4603 undefined = @intFromEnum(Index.undef),
4604 void = @intFromEnum(Index.void_value),
40454605 /// This is untyped `null`.
4046 null,
4606 null = @intFromEnum(Index.null_value),
40474607 /// This is the untyped empty struct literal: `.{}`
4048 empty_struct,
4049 true,
4050 false,
4051 @"unreachable",
4608 empty_struct = @intFromEnum(Index.empty_struct),
4609 true = @intFromEnum(Index.bool_true),
4610 false = @intFromEnum(Index.bool_false),
4611 @"unreachable" = @intFromEnum(Index.unreachable_value),
40524612
4053 generic_poison,
4613 generic_poison = @intFromEnum(Index.generic_poison),
40544614};
40554615
40564616/// Stored as a power-of-two, with one special value to indicate none.
......@@ -4170,14 +4730,18 @@ pub const Alignment = enum(u6) {
41704730 /// This type exists to provide a struct with lifetime that is
41714731 /// not invalidated when items are added to the `InternPool`.
41724732 pub const Slice = struct {
4733 tid: Zcu.PerThread.Id,
41734734 start: u32,
41744735 /// This is the number of alignment values, not the number of u32 elements.
41754736 len: u32,
41764737
4738 pub const empty: Slice = .{ .tid = .main, .start = 0, .len = 0 };
4739
41774740 pub fn get(slice: Slice, ip: *const InternPool) []Alignment {
41784741 // TODO: implement @ptrCast between slices changing the length
4179 //const bytes: []u8 = @ptrCast(ip.extra.items[slice.start..]);
4180 const bytes: []u8 = std.mem.sliceAsBytes(ip.extra.items[slice.start..]);
4742 const extra = ip.getLocalShared(slice.tid).extra.acquire();
4743 //const bytes: []u8 = @ptrCast(extra.view().items(.@"0")[slice.start..]);
4744 const bytes: []u8 = std.mem.sliceAsBytes(extra.view().items(.@"0")[slice.start..]);
41814745 return @ptrCast(bytes[0..slice.len]);
41824746 }
41834747 };
......@@ -4444,9 +5008,11 @@ pub const PtrSlice = struct {
44445008};
44455009
44465010/// Trailing: Limb for every limbs_len
4447pub const Int = struct {
5011pub const Int = packed struct {
44485012 ty: Index,
44495013 limbs_len: u32,
5014
5015 const limbs_items_len = @divExact(@sizeOf(Int), @sizeOf(Limb));
44505016};
44515017
44525018pub const IntSmall = struct {
......@@ -4535,30 +5101,57 @@ pub const MemoizedCall = struct {
45355101 result: Index,
45365102};
45375103
4538pub fn init(ip: *InternPool, gpa: Allocator) !void {
4539 assert(ip.items.len == 0);
5104pub fn init(ip: *InternPool, gpa: Allocator, available_threads: usize) !void {
5105 errdefer ip.deinit(gpa);
5106 assert(ip.locals.len == 0 and ip.shards.len == 0);
5107 assert(available_threads > 0 and available_threads <= std.math.maxInt(u8));
5108
5109 const used_threads = if (single_threaded) 1 else available_threads;
5110 ip.locals = try gpa.alloc(Local, used_threads);
5111 @memset(ip.locals, .{
5112 .shared = .{
5113 .items = Local.List(Item).empty,
5114 .extra = Local.Extra.empty,
5115 .limbs = Local.Limbs.empty,
5116 .strings = Local.Strings.empty,
5117 },
5118 .mutate = .{
5119 .arena = .{},
5120 .items = Local.Mutate.empty,
5121 .extra = Local.Mutate.empty,
5122 .limbs = Local.Mutate.empty,
5123 .strings = Local.Mutate.empty,
5124 },
5125 });
45405126
4541 // Reserve string index 0 for an empty string.
4542 assert((try ip.getOrPutString(gpa, "", .no_embedded_nulls)) == .empty);
5127 ip.tid_width = @intCast(std.math.log2_int_ceil(usize, used_threads));
5128 ip.tid_shift_31 = if (single_threaded) 0 else 31 - ip.tid_width;
5129 ip.tid_shift_32 = if (single_threaded) 0 else ip.tid_shift_31 +| 1;
5130 ip.shards = try gpa.alloc(Shard, @as(usize, 1) << ip.tid_width);
5131 @memset(ip.shards, .{
5132 .shared = .{
5133 .map = Shard.Map(Index).empty,
5134 .string_map = Shard.Map(OptionalNullTerminatedString).empty,
5135 },
5136 .mutate = .{
5137 .map = Shard.Mutate.empty,
5138 .string_map = Shard.Mutate.empty,
5139 },
5140 });
45435141
4544 // So that we can use `catch unreachable` below.
4545 try ip.items.ensureUnusedCapacity(gpa, static_keys.len);
4546 try ip.map.ensureUnusedCapacity(gpa, static_keys.len);
4547 try ip.extra.ensureUnusedCapacity(gpa, static_keys.len);
5142 // Reserve string index 0 for an empty string.
5143 assert((try ip.getOrPutString(gpa, .main, "", .no_embedded_nulls)) == .empty);
45485144
45495145 // This inserts all the statically-known values into the intern pool in the
45505146 // order expected.
4551 for (static_keys[0..@intFromEnum(Index.empty_struct_type)]) |key| {
4552 _ = ip.get(gpa, key) catch unreachable;
4553 }
4554 _ = ip.getAnonStructType(gpa, .{
4555 .types = &.{},
4556 .names = &.{},
4557 .values = &.{},
4558 }) catch unreachable;
4559 for (static_keys[@intFromEnum(Index.empty_struct_type) + 1 ..]) |key| {
4560 _ = ip.get(gpa, key) catch unreachable;
4561 }
5147 for (&static_keys, 0..) |key, key_index| switch (@as(Index, @enumFromInt(key_index))) {
5148 .empty_struct_type => assert(try ip.getAnonStructType(gpa, .main, .{
5149 .types = &.{},
5150 .names = &.{},
5151 .values = &.{},
5152 }) == .empty_struct_type),
5153 else => |expected_index| assert(try ip.get(gpa, .main, key) == expected_index),
5154 };
45625155
45635156 if (std.debug.runtime_safety) {
45645157 // Sanity check.
......@@ -4577,17 +5170,9 @@ pub fn init(ip: *InternPool, gpa: Allocator) !void {
45775170 assert(ip.indexToKey(ip.typeOf(cc_inline)).int_type.bits ==
45785171 @typeInfo(@typeInfo(std.builtin.CallingConvention).Enum.tag_type).Int.bits);
45795172 }
4580
4581 assert(ip.items.len == static_keys.len);
45825173}
45835174
45845175pub fn deinit(ip: *InternPool, gpa: Allocator) void {
4585 ip.map.deinit(gpa);
4586 ip.items.deinit(gpa);
4587 ip.extra.deinit(gpa);
4588 ip.limbs.deinit(gpa);
4589 ip.string_bytes.deinit(gpa);
4590
45915176 ip.decls_free_list.deinit(gpa);
45925177 ip.allocated_decls.deinit(gpa);
45935178
......@@ -4597,8 +5182,6 @@ pub fn deinit(ip: *InternPool, gpa: Allocator) void {
45975182 for (ip.maps.items) |*map| map.deinit(gpa);
45985183 ip.maps.deinit(gpa);
45995184
4600 ip.string_table.deinit(gpa);
4601
46025185 ip.tracked_insts.deinit(gpa);
46035186
46045187 ip.src_hash_deps.deinit(gpa);
......@@ -4614,12 +5197,17 @@ pub fn deinit(ip: *InternPool, gpa: Allocator) void {
46145197
46155198 ip.files.deinit(gpa);
46165199
5200 gpa.free(ip.shards);
5201 for (ip.locals) |*local| local.mutate.arena.promote(gpa).deinit();
5202 gpa.free(ip.locals);
5203
46175204 ip.* = undefined;
46185205}
46195206
46205207pub fn indexToKey(ip: *const InternPool, index: Index) Key {
46215208 assert(index != .none);
4622 const item = ip.items.get(@intFromEnum(index));
5209 const unwrapped_index = index.unwrap(ip);
5210 const item = unwrapped_index.getItem(ip);
46235211 const data = item.data;
46245212 return switch (item.tag) {
46255213 .removed => unreachable,
......@@ -4636,7 +5224,7 @@ pub fn indexToKey(ip: *const InternPool, index: Index) Key {
46365224 },
46375225 },
46385226 .type_array_big => {
4639 const array_info = ip.extraData(Array, data);
5227 const array_info = extraData(unwrapped_index.getExtra(ip), Array, data);
46405228 return .{ .array_type = .{
46415229 .len = array_info.getLength(),
46425230 .child = array_info.child,
......@@ -4644,29 +5232,32 @@ pub fn indexToKey(ip: *const InternPool, index: Index) Key {
46445232 } };
46455233 },
46465234 .type_array_small => {
4647 const array_info = ip.extraData(Vector, data);
5235 const array_info = extraData(unwrapped_index.getExtra(ip), Vector, data);
46485236 return .{ .array_type = .{
46495237 .len = array_info.len,
46505238 .child = array_info.child,
46515239 .sentinel = .none,
46525240 } };
46535241 },
4654 .simple_type => .{ .simple_type = @enumFromInt(data) },
4655 .simple_value => .{ .simple_value = @enumFromInt(data) },
5242 .simple_type => .{ .simple_type = @enumFromInt(@intFromEnum(index)) },
5243 .simple_value => .{ .simple_value = @enumFromInt(@intFromEnum(index)) },
46565244
46575245 .type_vector => {
4658 const vector_info = ip.extraData(Vector, data);
5246 const vector_info = extraData(unwrapped_index.getExtra(ip), Vector, data);
46595247 return .{ .vector_type = .{
46605248 .len = vector_info.len,
46615249 .child = vector_info.child,
46625250 } };
46635251 },
46645252
4665 .type_pointer => .{ .ptr_type = ip.extraData(Tag.TypePointer, data) },
5253 .type_pointer => .{ .ptr_type = extraData(unwrapped_index.getExtra(ip), Tag.TypePointer, data) },
46665254
46675255 .type_slice => {
4668 assert(ip.items.items(.tag)[data] == .type_pointer);
4669 var ptr_info = ip.extraData(Tag.TypePointer, ip.items.items(.data)[data]);
5256 const many_ptr_index: Index = @enumFromInt(data);
5257 const many_ptr_unwrapped = many_ptr_index.unwrap(ip);
5258 const many_ptr_item = many_ptr_unwrapped.getItem(ip);
5259 assert(many_ptr_item.tag == .type_pointer);
5260 var ptr_info = extraData(many_ptr_unwrapped.getExtra(ip), Tag.TypePointer, many_ptr_item.data);
46705261 ptr_info.flags.size = .Slice;
46715262 return .{ .ptr_type = ptr_info };
46725263 },
......@@ -4674,18 +5265,18 @@ pub fn indexToKey(ip: *const InternPool, index: Index) Key {
46745265 .type_optional => .{ .opt_type = @enumFromInt(data) },
46755266 .type_anyframe => .{ .anyframe_type = @enumFromInt(data) },
46765267
4677 .type_error_union => .{ .error_union_type = ip.extraData(Key.ErrorUnionType, data) },
5268 .type_error_union => .{ .error_union_type = extraData(unwrapped_index.getExtra(ip), Key.ErrorUnionType, data) },
46785269 .type_anyerror_union => .{ .error_union_type = .{
46795270 .error_set_type = .anyerror_type,
46805271 .payload_type = @enumFromInt(data),
46815272 } },
4682 .type_error_set => .{ .error_set_type = ip.extraErrorSet(data) },
5273 .type_error_set => .{ .error_set_type = extraErrorSet(unwrapped_index.tid, unwrapped_index.getExtra(ip), data) },
46835274 .type_inferred_error_set => .{
46845275 .inferred_error_set_type = @enumFromInt(data),
46855276 },
46865277
46875278 .type_opaque => .{ .opaque_type = ns: {
4688 const extra = ip.extraDataTrail(Tag.TypeOpaque, data);
5279 const extra = extraDataTrail(unwrapped_index.getExtra(ip), Tag.TypeOpaque, data);
46895280 if (extra.data.captures_len == std.math.maxInt(u32)) {
46905281 break :ns .{ .reified = .{
46915282 .zir_index = extra.data.zir_index,
......@@ -4695,6 +5286,7 @@ pub fn indexToKey(ip: *const InternPool, index: Index) Key {
46955286 break :ns .{ .declared = .{
46965287 .zir_index = extra.data.zir_index,
46975288 .captures = .{ .owned = .{
5289 .tid = unwrapped_index.tid,
46985290 .start = extra.end,
46995291 .len = extra.data.captures_len,
47005292 } },
......@@ -4703,105 +5295,115 @@ pub fn indexToKey(ip: *const InternPool, index: Index) Key {
47035295
47045296 .type_struct => .{ .struct_type = ns: {
47055297 if (data == 0) break :ns .empty_struct;
4706 const extra = ip.extraDataTrail(Tag.TypeStruct, data);
5298 const extra_list = unwrapped_index.getExtra(ip);
5299 const extra = extraDataTrail(extra_list, Tag.TypeStruct, data);
47075300 if (extra.data.flags.is_reified) {
47085301 assert(!extra.data.flags.any_captures);
47095302 break :ns .{ .reified = .{
47105303 .zir_index = extra.data.zir_index,
4711 .type_hash = ip.extraData(PackedU64, extra.end).get(),
5304 .type_hash = extraData(extra_list, PackedU64, extra.end).get(),
47125305 } };
47135306 }
47145307 break :ns .{ .declared = .{
47155308 .zir_index = extra.data.zir_index,
47165309 .captures = .{ .owned = if (extra.data.flags.any_captures) .{
5310 .tid = unwrapped_index.tid,
47175311 .start = extra.end + 1,
4718 .len = ip.extra.items[extra.end],
4719 } else .{ .start = 0, .len = 0 } },
5312 .len = extra_list.view().items(.@"0")[extra.end],
5313 } else CaptureValue.Slice.empty },
47205314 } };
47215315 } },
47225316
47235317 .type_struct_packed, .type_struct_packed_inits => .{ .struct_type = ns: {
4724 const extra = ip.extraDataTrail(Tag.TypeStructPacked, data);
5318 const extra_list = unwrapped_index.getExtra(ip);
5319 const extra = extraDataTrail(extra_list, Tag.TypeStructPacked, data);
47255320 if (extra.data.flags.is_reified) {
47265321 assert(!extra.data.flags.any_captures);
47275322 break :ns .{ .reified = .{
47285323 .zir_index = extra.data.zir_index,
4729 .type_hash = ip.extraData(PackedU64, extra.end).get(),
5324 .type_hash = extraData(extra_list, PackedU64, extra.end).get(),
47305325 } };
47315326 }
47325327 break :ns .{ .declared = .{
47335328 .zir_index = extra.data.zir_index,
47345329 .captures = .{ .owned = if (extra.data.flags.any_captures) .{
5330 .tid = unwrapped_index.tid,
47355331 .start = extra.end + 1,
4736 .len = ip.extra.items[extra.end],
4737 } else .{ .start = 0, .len = 0 } },
5332 .len = extra_list.view().items(.@"0")[extra.end],
5333 } else CaptureValue.Slice.empty },
47385334 } };
47395335 } },
4740 .type_struct_anon => .{ .anon_struct_type = extraTypeStructAnon(ip, data) },
4741 .type_tuple_anon => .{ .anon_struct_type = extraTypeTupleAnon(ip, data) },
5336 .type_struct_anon => .{ .anon_struct_type = extraTypeStructAnon(unwrapped_index.tid, unwrapped_index.getExtra(ip), data) },
5337 .type_tuple_anon => .{ .anon_struct_type = extraTypeTupleAnon(unwrapped_index.tid, unwrapped_index.getExtra(ip), data) },
47425338 .type_union => .{ .union_type = ns: {
4743 const extra = ip.extraDataTrail(Tag.TypeUnion, data);
5339 const extra_list = unwrapped_index.getExtra(ip);
5340 const extra = extraDataTrail(extra_list, Tag.TypeUnion, data);
47445341 if (extra.data.flags.is_reified) {
47455342 assert(!extra.data.flags.any_captures);
47465343 break :ns .{ .reified = .{
47475344 .zir_index = extra.data.zir_index,
4748 .type_hash = ip.extraData(PackedU64, extra.end).get(),
5345 .type_hash = extraData(extra_list, PackedU64, extra.end).get(),
47495346 } };
47505347 }
47515348 break :ns .{ .declared = .{
47525349 .zir_index = extra.data.zir_index,
47535350 .captures = .{ .owned = if (extra.data.flags.any_captures) .{
5351 .tid = unwrapped_index.tid,
47545352 .start = extra.end + 1,
4755 .len = ip.extra.items[extra.end],
4756 } else .{ .start = 0, .len = 0 } },
5353 .len = extra_list.view().items(.@"0")[extra.end],
5354 } else CaptureValue.Slice.empty },
47575355 } };
47585356 } },
47595357
47605358 .type_enum_auto => .{ .enum_type = ns: {
4761 const extra = ip.extraDataTrail(EnumAuto, data);
5359 const extra_list = unwrapped_index.getExtra(ip);
5360 const extra = extraDataTrail(extra_list, EnumAuto, data);
47625361 const zir_index = extra.data.zir_index.unwrap() orelse {
47635362 assert(extra.data.captures_len == 0);
47645363 break :ns .{ .generated_tag = .{
4765 .union_type = @enumFromInt(ip.extra.items[extra.end]),
5364 .union_type = @enumFromInt(extra_list.view().items(.@"0")[extra.end]),
47665365 } };
47675366 };
47685367 if (extra.data.captures_len == std.math.maxInt(u32)) {
47695368 break :ns .{ .reified = .{
47705369 .zir_index = zir_index,
4771 .type_hash = ip.extraData(PackedU64, extra.end).get(),
5370 .type_hash = extraData(extra_list, PackedU64, extra.end).get(),
47725371 } };
47735372 }
47745373 break :ns .{ .declared = .{
47755374 .zir_index = zir_index,
47765375 .captures = .{ .owned = .{
5376 .tid = unwrapped_index.tid,
47775377 .start = extra.end,
47785378 .len = extra.data.captures_len,
47795379 } },
47805380 } };
47815381 } },
47825382 .type_enum_explicit, .type_enum_nonexhaustive => .{ .enum_type = ns: {
4783 const extra = ip.extraDataTrail(EnumExplicit, data);
5383 const extra_list = unwrapped_index.getExtra(ip);
5384 const extra = extraDataTrail(extra_list, EnumExplicit, data);
47845385 const zir_index = extra.data.zir_index.unwrap() orelse {
47855386 assert(extra.data.captures_len == 0);
47865387 break :ns .{ .generated_tag = .{
4787 .union_type = @enumFromInt(ip.extra.items[extra.end]),
5388 .union_type = @enumFromInt(extra_list.view().items(.@"0")[extra.end]),
47885389 } };
47895390 };
47905391 if (extra.data.captures_len == std.math.maxInt(u32)) {
47915392 break :ns .{ .reified = .{
47925393 .zir_index = zir_index,
4793 .type_hash = ip.extraData(PackedU64, extra.end).get(),
5394 .type_hash = extraData(extra_list, PackedU64, extra.end).get(),
47945395 } };
47955396 }
47965397 break :ns .{ .declared = .{
47975398 .zir_index = zir_index,
47985399 .captures = .{ .owned = .{
5400 .tid = unwrapped_index.tid,
47995401 .start = extra.end,
48005402 .len = extra.data.captures_len,
48015403 } },
48025404 } };
48035405 } },
4804 .type_function => .{ .func_type = ip.extraFuncType(data) },
5406 .type_function => .{ .func_type = extraFuncType(unwrapped_index.tid, unwrapped_index.getExtra(ip), data) },
48055407
48065408 .undef => .{ .undef = @enumFromInt(data) },
48075409 .opt_null => .{ .opt = .{
......@@ -4809,40 +5411,40 @@ pub fn indexToKey(ip: *const InternPool, index: Index) Key {
48095411 .val = .none,
48105412 } },
48115413 .opt_payload => {
4812 const extra = ip.extraData(Tag.TypeValue, data);
5414 const extra = extraData(unwrapped_index.getExtra(ip), Tag.TypeValue, data);
48135415 return .{ .opt = .{
48145416 .ty = extra.ty,
48155417 .val = extra.val,
48165418 } };
48175419 },
48185420 .ptr_decl => {
4819 const info = ip.extraData(PtrDecl, data);
5421 const info = extraData(unwrapped_index.getExtra(ip), PtrDecl, data);
48205422 return .{ .ptr = .{ .ty = info.ty, .base_addr = .{ .decl = info.decl }, .byte_offset = info.byteOffset() } };
48215423 },
48225424 .ptr_comptime_alloc => {
4823 const info = ip.extraData(PtrComptimeAlloc, data);
5425 const info = extraData(unwrapped_index.getExtra(ip), PtrComptimeAlloc, data);
48245426 return .{ .ptr = .{ .ty = info.ty, .base_addr = .{ .comptime_alloc = info.index }, .byte_offset = info.byteOffset() } };
48255427 },
48265428 .ptr_anon_decl => {
4827 const info = ip.extraData(PtrAnonDecl, data);
5429 const info = extraData(unwrapped_index.getExtra(ip), PtrAnonDecl, data);
48285430 return .{ .ptr = .{ .ty = info.ty, .base_addr = .{ .anon_decl = .{
48295431 .val = info.val,
48305432 .orig_ty = info.ty,
48315433 } }, .byte_offset = info.byteOffset() } };
48325434 },
48335435 .ptr_anon_decl_aligned => {
4834 const info = ip.extraData(PtrAnonDeclAligned, data);
5436 const info = extraData(unwrapped_index.getExtra(ip), PtrAnonDeclAligned, data);
48355437 return .{ .ptr = .{ .ty = info.ty, .base_addr = .{ .anon_decl = .{
48365438 .val = info.val,
48375439 .orig_ty = info.orig_ty,
48385440 } }, .byte_offset = info.byteOffset() } };
48395441 },
48405442 .ptr_comptime_field => {
4841 const info = ip.extraData(PtrComptimeField, data);
5443 const info = extraData(unwrapped_index.getExtra(ip), PtrComptimeField, data);
48425444 return .{ .ptr = .{ .ty = info.ty, .base_addr = .{ .comptime_field = info.field_val }, .byte_offset = info.byteOffset() } };
48435445 },
48445446 .ptr_int => {
4845 const info = ip.extraData(PtrInt, data);
5447 const info = extraData(unwrapped_index.getExtra(ip), PtrInt, data);
48465448 return .{ .ptr = .{
48475449 .ty = info.ty,
48485450 .base_addr = .int,
......@@ -4850,17 +5452,17 @@ pub fn indexToKey(ip: *const InternPool, index: Index) Key {
48505452 } };
48515453 },
48525454 .ptr_eu_payload => {
4853 const info = ip.extraData(PtrBase, data);
5455 const info = extraData(unwrapped_index.getExtra(ip), PtrBase, data);
48545456 return .{ .ptr = .{ .ty = info.ty, .base_addr = .{ .eu_payload = info.base }, .byte_offset = info.byteOffset() } };
48555457 },
48565458 .ptr_opt_payload => {
4857 const info = ip.extraData(PtrBase, data);
5459 const info = extraData(unwrapped_index.getExtra(ip), PtrBase, data);
48585460 return .{ .ptr = .{ .ty = info.ty, .base_addr = .{ .opt_payload = info.base }, .byte_offset = info.byteOffset() } };
48595461 },
48605462 .ptr_elem => {
48615463 // Avoid `indexToKey` recursion by asserting the tag encoding.
4862 const info = ip.extraData(PtrBaseIndex, data);
4863 const index_item = ip.items.get(@intFromEnum(info.index));
5464 const info = extraData(unwrapped_index.getExtra(ip), PtrBaseIndex, data);
5465 const index_item = info.index.unwrap(ip).getItem(ip);
48645466 return switch (index_item.tag) {
48655467 .int_usize => .{ .ptr = .{ .ty = info.ty, .base_addr = .{ .arr_elem = .{
48665468 .base = info.base,
......@@ -4872,8 +5474,8 @@ pub fn indexToKey(ip: *const InternPool, index: Index) Key {
48725474 },
48735475 .ptr_field => {
48745476 // Avoid `indexToKey` recursion by asserting the tag encoding.
4875 const info = ip.extraData(PtrBaseIndex, data);
4876 const index_item = ip.items.get(@intFromEnum(info.index));
5477 const info = extraData(unwrapped_index.getExtra(ip), PtrBaseIndex, data);
5478 const index_item = info.index.unwrap(ip).getItem(ip);
48775479 return switch (index_item.tag) {
48785480 .int_usize => .{ .ptr = .{ .ty = info.ty, .base_addr = .{ .field = .{
48795481 .base = info.base,
......@@ -4884,7 +5486,7 @@ pub fn indexToKey(ip: *const InternPool, index: Index) Key {
48845486 };
48855487 },
48865488 .ptr_slice => {
4887 const info = ip.extraData(PtrSlice, data);
5489 const info = extraData(unwrapped_index.getExtra(ip), PtrSlice, data);
48885490 return .{ .slice = .{
48895491 .ty = info.ty,
48905492 .ptr = info.ptr,
......@@ -4919,17 +5521,17 @@ pub fn indexToKey(ip: *const InternPool, index: Index) Key {
49195521 .ty = .comptime_int_type,
49205522 .storage = .{ .i64 = @as(i32, @bitCast(data)) },
49215523 } },
4922 .int_positive => ip.indexToKeyBigInt(data, true),
4923 .int_negative => ip.indexToKeyBigInt(data, false),
5524 .int_positive => ip.indexToKeyBigInt(unwrapped_index.tid, data, true),
5525 .int_negative => ip.indexToKeyBigInt(unwrapped_index.tid, data, false),
49245526 .int_small => {
4925 const info = ip.extraData(IntSmall, data);
5527 const info = extraData(unwrapped_index.getExtra(ip), IntSmall, data);
49265528 return .{ .int = .{
49275529 .ty = info.ty,
49285530 .storage = .{ .u64 = info.value },
49295531 } };
49305532 },
49315533 .int_lazy_align, .int_lazy_size => |tag| {
4932 const info = ip.extraData(IntLazy, data);
5534 const info = extraData(unwrapped_index.getExtra(ip), IntLazy, data);
49335535 return .{ .int = .{
49345536 .ty = info.ty,
49355537 .storage = switch (tag) {
......@@ -4949,30 +5551,30 @@ pub fn indexToKey(ip: *const InternPool, index: Index) Key {
49495551 } },
49505552 .float_f64 => .{ .float = .{
49515553 .ty = .f64_type,
4952 .storage = .{ .f64 = ip.extraData(Float64, data).get() },
5554 .storage = .{ .f64 = extraData(unwrapped_index.getExtra(ip), Float64, data).get() },
49535555 } },
49545556 .float_f80 => .{ .float = .{
49555557 .ty = .f80_type,
4956 .storage = .{ .f80 = ip.extraData(Float80, data).get() },
5558 .storage = .{ .f80 = extraData(unwrapped_index.getExtra(ip), Float80, data).get() },
49575559 } },
49585560 .float_f128 => .{ .float = .{
49595561 .ty = .f128_type,
4960 .storage = .{ .f128 = ip.extraData(Float128, data).get() },
5562 .storage = .{ .f128 = extraData(unwrapped_index.getExtra(ip), Float128, data).get() },
49615563 } },
49625564 .float_c_longdouble_f80 => .{ .float = .{
49635565 .ty = .c_longdouble_type,
4964 .storage = .{ .f80 = ip.extraData(Float80, data).get() },
5566 .storage = .{ .f80 = extraData(unwrapped_index.getExtra(ip), Float80, data).get() },
49655567 } },
49665568 .float_c_longdouble_f128 => .{ .float = .{
49675569 .ty = .c_longdouble_type,
4968 .storage = .{ .f128 = ip.extraData(Float128, data).get() },
5570 .storage = .{ .f128 = extraData(unwrapped_index.getExtra(ip), Float128, data).get() },
49695571 } },
49705572 .float_comptime_float => .{ .float = .{
49715573 .ty = .comptime_float_type,
4972 .storage = .{ .f128 = ip.extraData(Float128, data).get() },
5574 .storage = .{ .f128 = extraData(unwrapped_index.getExtra(ip), Float128, data).get() },
49735575 } },
49745576 .variable => {
4975 const extra = ip.extraData(Tag.Variable, data);
5577 const extra = extraData(unwrapped_index.getExtra(ip), Tag.Variable, data);
49765578 return .{ .variable = .{
49775579 .ty = extra.ty,
49785580 .init = extra.init,
......@@ -4984,18 +5586,20 @@ pub fn indexToKey(ip: *const InternPool, index: Index) Key {
49845586 .is_weak_linkage = extra.flags.is_weak_linkage,
49855587 } };
49865588 },
4987 .extern_func => .{ .extern_func = ip.extraData(Tag.ExternFunc, data) },
4988 .func_instance => .{ .func = ip.extraFuncInstance(data) },
4989 .func_decl => .{ .func = ip.extraFuncDecl(data) },
4990 .func_coerced => .{ .func = ip.extraFuncCoerced(data) },
5589 .extern_func => .{ .extern_func = extraData(unwrapped_index.getExtra(ip), Tag.ExternFunc, data) },
5590 .func_instance => .{ .func = ip.extraFuncInstance(unwrapped_index.tid, unwrapped_index.getExtra(ip), data) },
5591 .func_decl => .{ .func = extraFuncDecl(unwrapped_index.tid, unwrapped_index.getExtra(ip), data) },
5592 .func_coerced => .{ .func = ip.extraFuncCoerced(unwrapped_index.getExtra(ip), data) },
49915593 .only_possible_value => {
49925594 const ty: Index = @enumFromInt(data);
4993 const ty_item = ip.items.get(@intFromEnum(ty));
5595 const ty_unwrapped = ty.unwrap(ip);
5596 const ty_extra = ty_unwrapped.getExtra(ip);
5597 const ty_item = ty_unwrapped.getItem(ip);
49945598 return switch (ty_item.tag) {
49955599 .type_array_big => {
49965600 const sentinel = @as(
49975601 *const [1]Index,
4998 @ptrCast(&ip.extra.items[ty_item.data + std.meta.fieldIndex(Array, "sentinel").?]),
5602 @ptrCast(&ty_extra.view().items(.@"0")[ty_item.data + std.meta.fieldIndex(Array, "sentinel").?]),
49995603 );
50005604 return .{ .aggregate = .{
50015605 .ty = ty,
......@@ -5023,9 +5627,9 @@ pub fn indexToKey(ip: *const InternPool, index: Index) Key {
50235627 // There is only one possible value precisely due to the
50245628 // fact that this values slice is fully populated!
50255629 .type_struct_anon, .type_tuple_anon => {
5026 const type_struct_anon = ip.extraDataTrail(TypeStructAnon, ty_item.data);
5630 const type_struct_anon = extraDataTrail(ty_extra, TypeStructAnon, ty_item.data);
50275631 const fields_len = type_struct_anon.data.fields_len;
5028 const values = ip.extra.items[type_struct_anon.end + fields_len ..][0..fields_len];
5632 const values = ty_extra.view().items(.@"0")[type_struct_anon.end + fields_len ..][0..fields_len];
50295633 return .{ .aggregate = .{
50305634 .ty = ty,
50315635 .storage = .{ .elems = @ptrCast(values) },
......@@ -5041,62 +5645,65 @@ pub fn indexToKey(ip: *const InternPool, index: Index) Key {
50415645 };
50425646 },
50435647 .bytes => {
5044 const extra = ip.extraData(Bytes, data);
5648 const extra = extraData(unwrapped_index.getExtra(ip), Bytes, data);
50455649 return .{ .aggregate = .{
50465650 .ty = extra.ty,
50475651 .storage = .{ .bytes = extra.bytes },
50485652 } };
50495653 },
50505654 .aggregate => {
5051 const extra = ip.extraDataTrail(Tag.Aggregate, data);
5655 const extra_list = unwrapped_index.getExtra(ip);
5656 const extra = extraDataTrail(extra_list, Tag.Aggregate, data);
50525657 const len: u32 = @intCast(ip.aggregateTypeLenIncludingSentinel(extra.data.ty));
5053 const fields: []const Index = @ptrCast(ip.extra.items[extra.end..][0..len]);
5658 const fields: []const Index = @ptrCast(extra_list.view().items(.@"0")[extra.end..][0..len]);
50545659 return .{ .aggregate = .{
50555660 .ty = extra.data.ty,
50565661 .storage = .{ .elems = fields },
50575662 } };
50585663 },
50595664 .repeated => {
5060 const extra = ip.extraData(Repeated, data);
5665 const extra = extraData(unwrapped_index.getExtra(ip), Repeated, data);
50615666 return .{ .aggregate = .{
50625667 .ty = extra.ty,
50635668 .storage = .{ .repeated_elem = extra.elem_val },
50645669 } };
50655670 },
5066 .union_value => .{ .un = ip.extraData(Key.Union, data) },
5067 .error_set_error => .{ .err = ip.extraData(Key.Error, data) },
5671 .union_value => .{ .un = extraData(unwrapped_index.getExtra(ip), Key.Union, data) },
5672 .error_set_error => .{ .err = extraData(unwrapped_index.getExtra(ip), Key.Error, data) },
50685673 .error_union_error => {
5069 const extra = ip.extraData(Key.Error, data);
5674 const extra = extraData(unwrapped_index.getExtra(ip), Key.Error, data);
50705675 return .{ .error_union = .{
50715676 .ty = extra.ty,
50725677 .val = .{ .err_name = extra.name },
50735678 } };
50745679 },
50755680 .error_union_payload => {
5076 const extra = ip.extraData(Tag.TypeValue, data);
5681 const extra = extraData(unwrapped_index.getExtra(ip), Tag.TypeValue, data);
50775682 return .{ .error_union = .{
50785683 .ty = extra.ty,
50795684 .val = .{ .payload = extra.val },
50805685 } };
50815686 },
50825687 .enum_literal => .{ .enum_literal = @enumFromInt(data) },
5083 .enum_tag => .{ .enum_tag = ip.extraData(Tag.EnumTag, data) },
5688 .enum_tag => .{ .enum_tag = extraData(unwrapped_index.getExtra(ip), Tag.EnumTag, data) },
50845689
50855690 .memoized_call => {
5086 const extra = ip.extraDataTrail(MemoizedCall, data);
5691 const extra_list = unwrapped_index.getExtra(ip);
5692 const extra = extraDataTrail(extra_list, MemoizedCall, data);
50875693 return .{ .memoized_call = .{
50885694 .func = extra.data.func,
5089 .arg_values = @ptrCast(ip.extra.items[extra.end..][0..extra.data.args_len]),
5695 .arg_values = @ptrCast(extra_list.view().items(.@"0")[extra.end..][0..extra.data.args_len]),
50905696 .result = extra.data.result,
50915697 } };
50925698 },
50935699 };
50945700}
50955701
5096fn extraErrorSet(ip: *const InternPool, extra_index: u32) Key.ErrorSetType {
5097 const error_set = ip.extraDataTrail(Tag.ErrorSet, extra_index);
5702fn extraErrorSet(tid: Zcu.PerThread.Id, extra: Local.Extra, extra_index: u32) Key.ErrorSetType {
5703 const error_set = extraDataTrail(extra, Tag.ErrorSet, extra_index);
50985704 return .{
50995705 .names = .{
5706 .tid = tid,
51005707 .start = @intCast(error_set.end),
51015708 .len = error_set.data.names_len,
51025709 },
......@@ -5104,60 +5711,67 @@ fn extraErrorSet(ip: *const InternPool, extra_index: u32) Key.ErrorSetType {
51045711 };
51055712}
51065713
5107fn extraTypeStructAnon(ip: *const InternPool, extra_index: u32) Key.AnonStructType {
5108 const type_struct_anon = ip.extraDataTrail(TypeStructAnon, extra_index);
5714fn extraTypeStructAnon(tid: Zcu.PerThread.Id, extra: Local.Extra, extra_index: u32) Key.AnonStructType {
5715 const type_struct_anon = extraDataTrail(extra, TypeStructAnon, extra_index);
51095716 const fields_len = type_struct_anon.data.fields_len;
51105717 return .{
51115718 .types = .{
5719 .tid = tid,
51125720 .start = type_struct_anon.end,
51135721 .len = fields_len,
51145722 },
51155723 .values = .{
5724 .tid = tid,
51165725 .start = type_struct_anon.end + fields_len,
51175726 .len = fields_len,
51185727 },
51195728 .names = .{
5729 .tid = tid,
51205730 .start = type_struct_anon.end + fields_len + fields_len,
51215731 .len = fields_len,
51225732 },
51235733 };
51245734}
51255735
5126fn extraTypeTupleAnon(ip: *const InternPool, extra_index: u32) Key.AnonStructType {
5127 const type_struct_anon = ip.extraDataTrail(TypeStructAnon, extra_index);
5736fn extraTypeTupleAnon(tid: Zcu.PerThread.Id, extra: Local.Extra, extra_index: u32) Key.AnonStructType {
5737 const type_struct_anon = extraDataTrail(extra, TypeStructAnon, extra_index);
51285738 const fields_len = type_struct_anon.data.fields_len;
51295739 return .{
51305740 .types = .{
5741 .tid = tid,
51315742 .start = type_struct_anon.end,
51325743 .len = fields_len,
51335744 },
51345745 .values = .{
5746 .tid = tid,
51355747 .start = type_struct_anon.end + fields_len,
51365748 .len = fields_len,
51375749 },
51385750 .names = .{
5751 .tid = tid,
51395752 .start = 0,
51405753 .len = 0,
51415754 },
51425755 };
51435756}
51445757
5145fn extraFuncType(ip: *const InternPool, extra_index: u32) Key.FuncType {
5146 const type_function = ip.extraDataTrail(Tag.TypeFunction, extra_index);
5147 var index: usize = type_function.end;
5758fn extraFuncType(tid: Zcu.PerThread.Id, extra: Local.Extra, extra_index: u32) Key.FuncType {
5759 const type_function = extraDataTrail(extra, Tag.TypeFunction, extra_index);
5760 var trail_index: usize = type_function.end;
51485761 const comptime_bits: u32 = if (!type_function.data.flags.has_comptime_bits) 0 else b: {
5149 const x = ip.extra.items[index];
5150 index += 1;
5762 const x = extra.view().items(.@"0")[trail_index];
5763 trail_index += 1;
51515764 break :b x;
51525765 };
51535766 const noalias_bits: u32 = if (!type_function.data.flags.has_noalias_bits) 0 else b: {
5154 const x = ip.extra.items[index];
5155 index += 1;
5767 const x = extra.view().items(.@"0")[trail_index];
5768 trail_index += 1;
51565769 break :b x;
51575770 };
51585771 return .{
51595772 .param_types = .{
5160 .start = @intCast(index),
5773 .tid = tid,
5774 .start = @intCast(trail_index),
51615775 .len = type_function.data.params_len,
51625776 },
51635777 .return_type = type_function.data.return_type,
......@@ -5173,10 +5787,11 @@ fn extraFuncType(ip: *const InternPool, extra_index: u32) Key.FuncType {
51735787 };
51745788}
51755789
5176fn extraFuncDecl(ip: *const InternPool, extra_index: u32) Key.Func {
5790fn extraFuncDecl(tid: Zcu.PerThread.Id, extra: Local.Extra, extra_index: u32) Key.Func {
51775791 const P = Tag.FuncDecl;
5178 const func_decl = ip.extraDataTrail(P, extra_index);
5792 const func_decl = extraDataTrail(extra, P, extra_index);
51795793 return .{
5794 .tid = tid,
51805795 .ty = func_decl.data.ty,
51815796 .uncoerced_ty = func_decl.data.ty,
51825797 .analysis_extra_index = extra_index + std.meta.fieldIndex(P, "analysis").?,
......@@ -5190,15 +5805,16 @@ fn extraFuncDecl(ip: *const InternPool, extra_index: u32) Key.Func {
51905805 .lbrace_column = func_decl.data.lbrace_column,
51915806 .rbrace_column = func_decl.data.rbrace_column,
51925807 .generic_owner = .none,
5193 .comptime_args = .{ .start = 0, .len = 0 },
5808 .comptime_args = Index.Slice.empty,
51945809 };
51955810}
51965811
5197fn extraFuncInstance(ip: *const InternPool, extra_index: u32) Key.Func {
5812fn extraFuncInstance(ip: *const InternPool, tid: Zcu.PerThread.Id, extra: Local.Extra, extra_index: u32) Key.Func {
51985813 const P = Tag.FuncInstance;
5199 const fi = ip.extraDataTrail(P, extra_index);
5814 const fi = extraDataTrail(extra, P, extra_index);
52005815 const func_decl = ip.funcDeclInfo(fi.data.generic_owner);
52015816 return .{
5817 .tid = tid,
52025818 .ty = fi.data.ty,
52035819 .uncoerced_ty = fi.data.ty,
52045820 .analysis_extra_index = extra_index + std.meta.fieldIndex(P, "analysis").?,
......@@ -5213,47 +5829,185 @@ fn extraFuncInstance(ip: *const InternPool, extra_index: u32) Key.Func {
52135829 .rbrace_column = func_decl.rbrace_column,
52145830 .generic_owner = fi.data.generic_owner,
52155831 .comptime_args = .{
5832 .tid = tid,
52165833 .start = fi.end + @intFromBool(fi.data.analysis.inferred_error_set),
52175834 .len = ip.funcTypeParamsLen(func_decl.ty),
52185835 },
52195836 };
52205837}
52215838
5222fn extraFuncCoerced(ip: *const InternPool, extra_index: u32) Key.Func {
5223 const func_coerced = ip.extraData(Tag.FuncCoerced, extra_index);
5224 const sub_item = ip.items.get(@intFromEnum(func_coerced.func));
5839fn extraFuncCoerced(ip: *const InternPool, extra: Local.Extra, extra_index: u32) Key.Func {
5840 const func_coerced = extraData(extra, Tag.FuncCoerced, extra_index);
5841 const func_unwrapped = func_coerced.func.unwrap(ip);
5842 const sub_item = func_unwrapped.getItem(ip);
5843 const func_extra = func_unwrapped.getExtra(ip);
52255844 var func: Key.Func = switch (sub_item.tag) {
5226 .func_instance => ip.extraFuncInstance(sub_item.data),
5227 .func_decl => ip.extraFuncDecl(sub_item.data),
5845 .func_instance => ip.extraFuncInstance(func_unwrapped.tid, func_extra, sub_item.data),
5846 .func_decl => extraFuncDecl(func_unwrapped.tid, func_extra, sub_item.data),
52285847 else => unreachable,
52295848 };
52305849 func.ty = func_coerced.ty;
52315850 return func;
52325851}
52335852
5234fn indexToKeyBigInt(ip: *const InternPool, limb_index: u32, positive: bool) Key {
5235 const int_info = ip.limbData(Int, limb_index);
5853fn indexToKeyBigInt(ip: *const InternPool, tid: Zcu.PerThread.Id, limb_index: u32, positive: bool) Key {
5854 const limbs_items = ip.getLocalShared(tid).getLimbs().view().items(.@"0");
5855 const int: Int = @bitCast(limbs_items[limb_index..][0..Int.limbs_items_len].*);
52365856 return .{ .int = .{
5237 .ty = int_info.ty,
5857 .ty = int.ty,
52385858 .storage = .{ .big_int = .{
5239 .limbs = ip.limbSlice(Int, limb_index, int_info.limbs_len),
5859 .limbs = limbs_items[limb_index + Int.limbs_items_len ..][0..int.limbs_len],
52405860 .positive = positive,
52415861 } },
52425862 } };
52435863}
52445864
5245pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
5246 const adapter: KeyAdapter = .{ .intern_pool = ip };
5247 const gop = try ip.map.getOrPutAdapted(gpa, key, adapter);
5248 if (gop.found_existing) return @enumFromInt(gop.index);
5249 try ip.items.ensureUnusedCapacity(gpa, 1);
5865const GetOrPutKey = union(enum) {
5866 existing: Index,
5867 new: struct {
5868 ip: *InternPool,
5869 tid: Zcu.PerThread.Id,
5870 shard: *Shard,
5871 map_index: u32,
5872 },
5873
5874 fn put(gop: *GetOrPutKey) Index {
5875 return gop.putAt(0);
5876 }
5877 fn putAt(gop: *GetOrPutKey, offset: u32) Index {
5878 switch (gop.*) {
5879 .existing => unreachable,
5880 .new => |info| {
5881 const index = Index.Unwrapped.wrap(.{
5882 .tid = info.tid,
5883 .index = info.ip.getLocal(info.tid).mutate.items.len - 1 - offset,
5884 }, info.ip);
5885 info.shard.shared.map.entries[info.map_index].release(index);
5886 info.shard.mutate.map.len += 1;
5887 info.shard.mutate.map.mutex.unlock();
5888 gop.* = .{ .existing = index };
5889 return index;
5890 },
5891 }
5892 }
5893
5894 fn assign(gop: *GetOrPutKey, new_gop: GetOrPutKey) void {
5895 gop.deinit();
5896 gop.* = new_gop;
5897 }
5898
5899 fn deinit(gop: *GetOrPutKey) void {
5900 switch (gop.*) {
5901 .existing => {},
5902 .new => |info| info.shard.mutate.map.mutex.unlock(),
5903 }
5904 gop.* = undefined;
5905 }
5906};
5907fn getOrPutKey(
5908 ip: *InternPool,
5909 gpa: Allocator,
5910 tid: Zcu.PerThread.Id,
5911 key: Key,
5912) Allocator.Error!GetOrPutKey {
5913 const full_hash = key.hash64(ip);
5914 const hash: u32 = @truncate(full_hash >> 32);
5915 const shard = &ip.shards[@intCast(full_hash & (ip.shards.len - 1))];
5916 var map = shard.shared.map.acquire();
5917 const Map = @TypeOf(map);
5918 var map_mask = map.header().mask();
5919 var map_index = hash;
5920 while (true) : (map_index += 1) {
5921 map_index &= map_mask;
5922 const entry = &map.entries[map_index];
5923 const index = entry.acquire();
5924 if (index == .none) break;
5925 if (entry.hash != hash) continue;
5926 if (ip.indexToKey(index).eql(key, ip)) return .{ .existing = index };
5927 }
5928 shard.mutate.map.mutex.lock();
5929 errdefer shard.mutate.map.mutex.unlock();
5930 if (map.entries != shard.shared.map.entries) {
5931 map = shard.shared.map;
5932 map_mask = map.header().mask();
5933 map_index = hash;
5934 }
5935 while (true) : (map_index += 1) {
5936 map_index &= map_mask;
5937 const entry = &map.entries[map_index];
5938 const index = entry.value;
5939 if (index == .none) break;
5940 if (entry.hash != hash) continue;
5941 if (ip.indexToKey(index).eql(key, ip)) {
5942 defer shard.mutate.map.mutex.unlock();
5943 return .{ .existing = index };
5944 }
5945 }
5946 const map_header = map.header().*;
5947 if (shard.mutate.map.len >= map_header.capacity * 3 / 5) {
5948 const arena_state = &ip.getLocal(tid).mutate.arena;
5949 var arena = arena_state.promote(gpa);
5950 defer arena_state.* = arena.state;
5951 const new_map_capacity = map_header.capacity * 2;
5952 const new_map_buf = try arena.allocator().alignedAlloc(
5953 u8,
5954 Map.alignment,
5955 Map.entries_offset + new_map_capacity * @sizeOf(Map.Entry),
5956 );
5957 const new_map: Map = .{ .entries = @ptrCast(new_map_buf[Map.entries_offset..].ptr) };
5958 new_map.header().* = .{ .capacity = new_map_capacity };
5959 @memset(new_map.entries[0..new_map_capacity], .{ .value = .none, .hash = undefined });
5960 const new_map_mask = new_map.header().mask();
5961 map_index = 0;
5962 while (map_index < map_header.capacity) : (map_index += 1) {
5963 const entry = &map.entries[map_index];
5964 const index = entry.value;
5965 if (index == .none) continue;
5966 const item_hash = entry.hash;
5967 var new_map_index = item_hash;
5968 while (true) : (new_map_index += 1) {
5969 new_map_index &= new_map_mask;
5970 const new_entry = &new_map.entries[new_map_index];
5971 if (new_entry.value != .none) continue;
5972 new_entry.* = .{
5973 .value = index,
5974 .hash = item_hash,
5975 };
5976 break;
5977 }
5978 }
5979 map = new_map;
5980 map_index = hash;
5981 while (true) : (map_index += 1) {
5982 map_index &= new_map_mask;
5983 if (map.entries[map_index].value == .none) break;
5984 }
5985 shard.shared.map.release(new_map);
5986 }
5987 map.entries[map_index].hash = hash;
5988 return .{ .new = .{
5989 .ip = ip,
5990 .tid = tid,
5991 .shard = shard,
5992 .map_index = map_index,
5993 } };
5994}
5995
5996pub fn get(ip: *InternPool, gpa: Allocator, tid: Zcu.PerThread.Id, key: Key) Allocator.Error!Index {
5997 var gop = try ip.getOrPutKey(gpa, tid, key);
5998 defer gop.deinit();
5999 if (gop == .existing) return gop.existing;
6000 const local = ip.getLocal(tid);
6001 const items = local.getMutableItems(gpa);
6002 const extra = local.getMutableExtra(gpa);
6003 try items.ensureUnusedCapacity(1);
52506004 switch (key) {
52516005 .int_type => |int_type| {
52526006 const t: Tag = switch (int_type.signedness) {
52536007 .signed => .type_int_signed,
52546008 .unsigned => .type_int_unsigned,
52556009 };
5256 ip.items.appendAssumeCapacity(.{
6010 items.appendAssumeCapacity(.{
52576011 .tag = t,
52586012 .data = int_type.bits,
52596013 });
......@@ -5263,25 +6017,25 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
52636017 assert(ptr_type.sentinel == .none or ip.typeOf(ptr_type.sentinel) == ptr_type.child);
52646018
52656019 if (ptr_type.flags.size == .Slice) {
5266 _ = ip.map.pop();
52676020 var new_key = key;
52686021 new_key.ptr_type.flags.size = .Many;
5269 const ptr_type_index = try ip.get(gpa, new_key);
5270 assert(!(try ip.map.getOrPutAdapted(gpa, key, adapter)).found_existing);
5271 try ip.items.ensureUnusedCapacity(gpa, 1);
5272 ip.items.appendAssumeCapacity(.{
6022 const ptr_type_index = try ip.get(gpa, tid, new_key);
6023 gop.assign(try ip.getOrPutKey(gpa, tid, key));
6024
6025 try items.ensureUnusedCapacity(1);
6026 items.appendAssumeCapacity(.{
52736027 .tag = .type_slice,
52746028 .data = @intFromEnum(ptr_type_index),
52756029 });
5276 return @enumFromInt(ip.items.len - 1);
6030 return gop.put();
52776031 }
52786032
52796033 var ptr_type_adjusted = ptr_type;
52806034 if (ptr_type.flags.size == .C) ptr_type_adjusted.flags.is_allowzero = true;
52816035
5282 ip.items.appendAssumeCapacity(.{
6036 items.appendAssumeCapacity(.{
52836037 .tag = .type_pointer,
5284 .data = try ip.addExtra(gpa, ptr_type_adjusted),
6038 .data = try addExtra(extra, ptr_type_adjusted),
52856039 });
52866040 },
52876041 .array_type => |array_type| {
......@@ -5290,21 +6044,21 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
52906044
52916045 if (std.math.cast(u32, array_type.len)) |len| {
52926046 if (array_type.sentinel == .none) {
5293 ip.items.appendAssumeCapacity(.{
6047 items.appendAssumeCapacity(.{
52946048 .tag = .type_array_small,
5295 .data = try ip.addExtra(gpa, Vector{
6049 .data = try addExtra(extra, Vector{
52966050 .len = len,
52976051 .child = array_type.child,
52986052 }),
52996053 });
5300 return @enumFromInt(ip.items.len - 1);
6054 return gop.put();
53016055 }
53026056 }
53036057
53046058 const length = Array.Length.init(array_type.len);
5305 ip.items.appendAssumeCapacity(.{
6059 items.appendAssumeCapacity(.{
53066060 .tag = .type_array_big,
5307 .data = try ip.addExtra(gpa, Array{
6061 .data = try addExtra(extra, Array{
53086062 .len0 = length.a,
53096063 .len1 = length.b,
53106064 .child = array_type.child,
......@@ -5313,9 +6067,9 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
53136067 });
53146068 },
53156069 .vector_type => |vector_type| {
5316 ip.items.appendAssumeCapacity(.{
6070 items.appendAssumeCapacity(.{
53176071 .tag = .type_vector,
5318 .data = try ip.addExtra(gpa, Vector{
6072 .data = try addExtra(extra, Vector{
53196073 .len = vector_type.len,
53206074 .child = vector_type.child,
53216075 }),
......@@ -5323,25 +6077,25 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
53236077 },
53246078 .opt_type => |payload_type| {
53256079 assert(payload_type != .none);
5326 ip.items.appendAssumeCapacity(.{
6080 items.appendAssumeCapacity(.{
53276081 .tag = .type_optional,
53286082 .data = @intFromEnum(payload_type),
53296083 });
53306084 },
53316085 .anyframe_type => |payload_type| {
53326086 // payload_type might be none, indicating the type is `anyframe`.
5333 ip.items.appendAssumeCapacity(.{
6087 items.appendAssumeCapacity(.{
53346088 .tag = .type_anyframe,
53356089 .data = @intFromEnum(payload_type),
53366090 });
53376091 },
53386092 .error_union_type => |error_union_type| {
5339 ip.items.appendAssumeCapacity(if (error_union_type.error_set_type == .anyerror_type) .{
6093 items.appendAssumeCapacity(if (error_union_type.error_set_type == .anyerror_type) .{
53406094 .tag = .type_anyerror_union,
53416095 .data = @intFromEnum(error_union_type.payload_type),
53426096 } else .{
53436097 .tag = .type_error_union,
5344 .data = try ip.addExtra(gpa, error_union_type),
6098 .data = try addExtra(extra, error_union_type),
53456099 });
53466100 },
53476101 .error_set_type => |error_set_type| {
......@@ -5351,37 +6105,39 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
53516105 const names_map = try ip.addMap(gpa, names.len);
53526106 addStringsToMap(ip, names_map, names);
53536107 const names_len = error_set_type.names.len;
5354 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(Tag.ErrorSet).Struct.fields.len + names_len);
5355 ip.items.appendAssumeCapacity(.{
6108 try extra.ensureUnusedCapacity(@typeInfo(Tag.ErrorSet).Struct.fields.len + names_len);
6109 items.appendAssumeCapacity(.{
53566110 .tag = .type_error_set,
5357 .data = ip.addExtraAssumeCapacity(Tag.ErrorSet{
6111 .data = addExtraAssumeCapacity(extra, Tag.ErrorSet{
53586112 .names_len = names_len,
53596113 .names_map = names_map,
53606114 }),
53616115 });
5362 ip.extra.appendSliceAssumeCapacity(@ptrCast(error_set_type.names.get(ip)));
6116 extra.appendSliceAssumeCapacity(.{@ptrCast(error_set_type.names.get(ip))});
53636117 },
53646118 .inferred_error_set_type => |ies_index| {
5365 ip.items.appendAssumeCapacity(.{
6119 items.appendAssumeCapacity(.{
53666120 .tag = .type_inferred_error_set,
53676121 .data = @intFromEnum(ies_index),
53686122 });
53696123 },
53706124 .simple_type => |simple_type| {
5371 ip.items.appendAssumeCapacity(.{
6125 assert(@intFromEnum(simple_type) == items.mutate.len);
6126 items.appendAssumeCapacity(.{
53726127 .tag = .simple_type,
5373 .data = @intFromEnum(simple_type),
6128 .data = 0, // avoid writing `undefined` bits to a file
53746129 });
53756130 },
53766131 .simple_value => |simple_value| {
5377 ip.items.appendAssumeCapacity(.{
6132 assert(@intFromEnum(simple_value) == items.mutate.len);
6133 items.appendAssumeCapacity(.{
53786134 .tag = .simple_value,
5379 .data = @intFromEnum(simple_value),
6135 .data = 0, // avoid writing `undefined` bits to a file
53806136 });
53816137 },
53826138 .undef => |ty| {
53836139 assert(ty != .none);
5384 ip.items.appendAssumeCapacity(.{
6140 items.appendAssumeCapacity(.{
53856141 .tag = .undef,
53866142 .data = @intFromEnum(ty),
53876143 });
......@@ -5400,9 +6156,9 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
54006156 .variable => |variable| {
54016157 const has_init = variable.init != .none;
54026158 if (has_init) assert(variable.ty == ip.typeOf(variable.init));
5403 ip.items.appendAssumeCapacity(.{
6159 items.appendAssumeCapacity(.{
54046160 .tag = .variable,
5405 .data = try ip.addExtra(gpa, Tag.Variable{
6161 .data = try addExtra(extra, Tag.Variable{
54066162 .ty = variable.ty,
54076163 .init = variable.init,
54086164 .decl = variable.decl,
......@@ -5420,9 +6176,9 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
54206176 .slice => |slice| {
54216177 assert(ip.indexToKey(slice.ty).ptr_type.flags.size == .Slice);
54226178 assert(ip.indexToKey(ip.typeOf(slice.ptr)).ptr_type.flags.size == .Many);
5423 ip.items.appendAssumeCapacity(.{
6179 items.appendAssumeCapacity(.{
54246180 .tag = .ptr_slice,
5425 .data = try ip.addExtra(gpa, PtrSlice{
6181 .data = try addExtra(extra, PtrSlice{
54266182 .ty = slice.ty,
54276183 .ptr = slice.ptr,
54286184 .len = slice.len,
......@@ -5433,36 +6189,35 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
54336189 .ptr => |ptr| {
54346190 const ptr_type = ip.indexToKey(ptr.ty).ptr_type;
54356191 assert(ptr_type.flags.size != .Slice);
5436 ip.items.appendAssumeCapacity(switch (ptr.base_addr) {
6192 items.appendAssumeCapacity(switch (ptr.base_addr) {
54376193 .decl => |decl| .{
54386194 .tag = .ptr_decl,
5439 .data = try ip.addExtra(gpa, PtrDecl.init(ptr.ty, decl, ptr.byte_offset)),
6195 .data = try addExtra(extra, PtrDecl.init(ptr.ty, decl, ptr.byte_offset)),
54406196 },
54416197 .comptime_alloc => |alloc_index| .{
54426198 .tag = .ptr_comptime_alloc,
5443 .data = try ip.addExtra(gpa, PtrComptimeAlloc.init(ptr.ty, alloc_index, ptr.byte_offset)),
6199 .data = try addExtra(extra, PtrComptimeAlloc.init(ptr.ty, alloc_index, ptr.byte_offset)),
54446200 },
54456201 .anon_decl => |anon_decl| if (ptrsHaveSameAlignment(ip, ptr.ty, ptr_type, anon_decl.orig_ty)) item: {
54466202 if (ptr.ty != anon_decl.orig_ty) {
5447 _ = ip.map.pop();
54486203 var new_key = key;
54496204 new_key.ptr.base_addr.anon_decl.orig_ty = ptr.ty;
5450 const new_gop = try ip.map.getOrPutAdapted(gpa, new_key, adapter);
5451 if (new_gop.found_existing) return @enumFromInt(new_gop.index);
6205 gop.assign(try ip.getOrPutKey(gpa, tid, new_key));
6206 if (gop == .existing) return gop.existing;
54526207 }
54536208 break :item .{
54546209 .tag = .ptr_anon_decl,
5455 .data = try ip.addExtra(gpa, PtrAnonDecl.init(ptr.ty, anon_decl.val, ptr.byte_offset)),
6210 .data = try addExtra(extra, PtrAnonDecl.init(ptr.ty, anon_decl.val, ptr.byte_offset)),
54566211 };
54576212 } else .{
54586213 .tag = .ptr_anon_decl_aligned,
5459 .data = try ip.addExtra(gpa, PtrAnonDeclAligned.init(ptr.ty, anon_decl.val, anon_decl.orig_ty, ptr.byte_offset)),
6214 .data = try addExtra(extra, PtrAnonDeclAligned.init(ptr.ty, anon_decl.val, anon_decl.orig_ty, ptr.byte_offset)),
54606215 },
54616216 .comptime_field => |field_val| item: {
54626217 assert(field_val != .none);
54636218 break :item .{
54646219 .tag = .ptr_comptime_field,
5465 .data = try ip.addExtra(gpa, PtrComptimeField.init(ptr.ty, field_val, ptr.byte_offset)),
6220 .data = try addExtra(extra, PtrComptimeField.init(ptr.ty, field_val, ptr.byte_offset)),
54666221 };
54676222 },
54686223 .eu_payload, .opt_payload => |base| item: {
......@@ -5481,14 +6236,14 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
54816236 .opt_payload => .ptr_opt_payload,
54826237 else => unreachable,
54836238 },
5484 .data = try ip.addExtra(gpa, PtrBase.init(ptr.ty, base, ptr.byte_offset)),
6239 .data = try addExtra(extra, PtrBase.init(ptr.ty, base, ptr.byte_offset)),
54856240 };
54866241 },
54876242 .int => .{
54886243 .tag = .ptr_int,
5489 .data = try ip.addExtra(gpa, PtrInt.init(ptr.ty, ptr.byte_offset)),
6244 .data = try addExtra(extra, PtrInt.init(ptr.ty, ptr.byte_offset)),
54906245 },
5491 .arr_elem, .field => |base_index| item: {
6246 .arr_elem, .field => |base_index| {
54926247 const base_ptr_type = ip.indexToKey(ip.typeOf(base_index.base)).ptr_type;
54936248 switch (ptr.base_addr) {
54946249 .arr_elem => assert(base_ptr_type.flags.size == .Many),
......@@ -5518,21 +6273,21 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
55186273 },
55196274 else => unreachable,
55206275 }
5521 _ = ip.map.pop();
5522 const index_index = try ip.get(gpa, .{ .int = .{
6276 const index_index = try ip.get(gpa, tid, .{ .int = .{
55236277 .ty = .usize_type,
55246278 .storage = .{ .u64 = base_index.index },
55256279 } });
5526 assert(!(try ip.map.getOrPutAdapted(gpa, key, adapter)).found_existing);
5527 try ip.items.ensureUnusedCapacity(gpa, 1);
5528 break :item .{
6280 gop.assign(try ip.getOrPutKey(gpa, tid, key));
6281 try items.ensureUnusedCapacity(1);
6282 items.appendAssumeCapacity(.{
55296283 .tag = switch (ptr.base_addr) {
55306284 .arr_elem => .ptr_elem,
55316285 .field => .ptr_field,
55326286 else => unreachable,
55336287 },
5534 .data = try ip.addExtra(gpa, PtrBaseIndex.init(ptr.ty, base_index.base, index_index, ptr.byte_offset)),
5535 };
6288 .data = try addExtra(extra, PtrBaseIndex.init(ptr.ty, base_index.base, index_index, ptr.byte_offset)),
6289 });
6290 return gop.put();
55366291 },
55376292 });
55386293 },
......@@ -5540,12 +6295,12 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
55406295 .opt => |opt| {
55416296 assert(ip.isOptionalType(opt.ty));
55426297 assert(opt.val == .none or ip.indexToKey(opt.ty).opt_type == ip.typeOf(opt.val));
5543 ip.items.appendAssumeCapacity(if (opt.val == .none) .{
6298 items.appendAssumeCapacity(if (opt.val == .none) .{
55446299 .tag = .opt_null,
55456300 .data = @intFromEnum(opt.ty),
55466301 } else .{
55476302 .tag = .opt_payload,
5548 .data = try ip.addExtra(gpa, Tag.TypeValue{
6303 .data = try addExtra(extra, Tag.TypeValue{
55496304 .ty = opt.ty,
55506305 .val = opt.val,
55516306 }),
......@@ -5557,31 +6312,31 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
55576312 switch (int.storage) {
55586313 .u64, .i64, .big_int => {},
55596314 .lazy_align, .lazy_size => |lazy_ty| {
5560 ip.items.appendAssumeCapacity(.{
6315 items.appendAssumeCapacity(.{
55616316 .tag = switch (int.storage) {
55626317 else => unreachable,
55636318 .lazy_align => .int_lazy_align,
55646319 .lazy_size => .int_lazy_size,
55656320 },
5566 .data = try ip.addExtra(gpa, IntLazy{
6321 .data = try addExtra(extra, IntLazy{
55676322 .ty = int.ty,
55686323 .lazy_ty = lazy_ty,
55696324 }),
55706325 });
5571 return @enumFromInt(ip.items.len - 1);
6326 return gop.put();
55726327 },
55736328 }
55746329 switch (int.ty) {
55756330 .u8_type => switch (int.storage) {
55766331 .big_int => |big_int| {
5577 ip.items.appendAssumeCapacity(.{
6332 items.appendAssumeCapacity(.{
55786333 .tag = .int_u8,
55796334 .data = big_int.to(u8) catch unreachable,
55806335 });
55816336 break :b;
55826337 },
55836338 inline .u64, .i64 => |x| {
5584 ip.items.appendAssumeCapacity(.{
6339 items.appendAssumeCapacity(.{
55856340 .tag = .int_u8,
55866341 .data = @as(u8, @intCast(x)),
55876342 });
......@@ -5591,14 +6346,14 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
55916346 },
55926347 .u16_type => switch (int.storage) {
55936348 .big_int => |big_int| {
5594 ip.items.appendAssumeCapacity(.{
6349 items.appendAssumeCapacity(.{
55956350 .tag = .int_u16,
55966351 .data = big_int.to(u16) catch unreachable,
55976352 });
55986353 break :b;
55996354 },
56006355 inline .u64, .i64 => |x| {
5601 ip.items.appendAssumeCapacity(.{
6356 items.appendAssumeCapacity(.{
56026357 .tag = .int_u16,
56036358 .data = @as(u16, @intCast(x)),
56046359 });
......@@ -5608,14 +6363,14 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
56086363 },
56096364 .u32_type => switch (int.storage) {
56106365 .big_int => |big_int| {
5611 ip.items.appendAssumeCapacity(.{
6366 items.appendAssumeCapacity(.{
56126367 .tag = .int_u32,
56136368 .data = big_int.to(u32) catch unreachable,
56146369 });
56156370 break :b;
56166371 },
56176372 inline .u64, .i64 => |x| {
5618 ip.items.appendAssumeCapacity(.{
6373 items.appendAssumeCapacity(.{
56196374 .tag = .int_u32,
56206375 .data = @as(u32, @intCast(x)),
56216376 });
......@@ -5626,14 +6381,14 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
56266381 .i32_type => switch (int.storage) {
56276382 .big_int => |big_int| {
56286383 const casted = big_int.to(i32) catch unreachable;
5629 ip.items.appendAssumeCapacity(.{
6384 items.appendAssumeCapacity(.{
56306385 .tag = .int_i32,
56316386 .data = @as(u32, @bitCast(casted)),
56326387 });
56336388 break :b;
56346389 },
56356390 inline .u64, .i64 => |x| {
5636 ip.items.appendAssumeCapacity(.{
6391 items.appendAssumeCapacity(.{
56376392 .tag = .int_i32,
56386393 .data = @as(u32, @bitCast(@as(i32, @intCast(x)))),
56396394 });
......@@ -5644,7 +6399,7 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
56446399 .usize_type => switch (int.storage) {
56456400 .big_int => |big_int| {
56466401 if (big_int.to(u32)) |casted| {
5647 ip.items.appendAssumeCapacity(.{
6402 items.appendAssumeCapacity(.{
56486403 .tag = .int_usize,
56496404 .data = casted,
56506405 });
......@@ -5653,7 +6408,7 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
56536408 },
56546409 inline .u64, .i64 => |x| {
56556410 if (std.math.cast(u32, x)) |casted| {
5656 ip.items.appendAssumeCapacity(.{
6411 items.appendAssumeCapacity(.{
56576412 .tag = .int_usize,
56586413 .data = casted,
56596414 });
......@@ -5665,14 +6420,14 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
56656420 .comptime_int_type => switch (int.storage) {
56666421 .big_int => |big_int| {
56676422 if (big_int.to(u32)) |casted| {
5668 ip.items.appendAssumeCapacity(.{
6423 items.appendAssumeCapacity(.{
56696424 .tag = .int_comptime_int_u32,
56706425 .data = casted,
56716426 });
56726427 break :b;
56736428 } else |_| {}
56746429 if (big_int.to(i32)) |casted| {
5675 ip.items.appendAssumeCapacity(.{
6430 items.appendAssumeCapacity(.{
56766431 .tag = .int_comptime_int_i32,
56776432 .data = @as(u32, @bitCast(casted)),
56786433 });
......@@ -5681,14 +6436,14 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
56816436 },
56826437 inline .u64, .i64 => |x| {
56836438 if (std.math.cast(u32, x)) |casted| {
5684 ip.items.appendAssumeCapacity(.{
6439 items.appendAssumeCapacity(.{
56856440 .tag = .int_comptime_int_u32,
56866441 .data = casted,
56876442 });
56886443 break :b;
56896444 }
56906445 if (std.math.cast(i32, x)) |casted| {
5691 ip.items.appendAssumeCapacity(.{
6446 items.appendAssumeCapacity(.{
56926447 .tag = .int_comptime_int_i32,
56936448 .data = @as(u32, @bitCast(casted)),
56946449 });
......@@ -5702,35 +6457,35 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
57026457 switch (int.storage) {
57036458 .big_int => |big_int| {
57046459 if (big_int.to(u32)) |casted| {
5705 ip.items.appendAssumeCapacity(.{
6460 items.appendAssumeCapacity(.{
57066461 .tag = .int_small,
5707 .data = try ip.addExtra(gpa, IntSmall{
6462 .data = try addExtra(extra, IntSmall{
57086463 .ty = int.ty,
57096464 .value = casted,
57106465 }),
57116466 });
5712 return @enumFromInt(ip.items.len - 1);
6467 return gop.put();
57136468 } else |_| {}
57146469
57156470 const tag: Tag = if (big_int.positive) .int_positive else .int_negative;
5716 try addInt(ip, gpa, int.ty, tag, big_int.limbs);
6471 try addInt(ip, gpa, tid, int.ty, tag, big_int.limbs);
57176472 },
57186473 inline .u64, .i64 => |x| {
57196474 if (std.math.cast(u32, x)) |casted| {
5720 ip.items.appendAssumeCapacity(.{
6475 items.appendAssumeCapacity(.{
57216476 .tag = .int_small,
5722 .data = try ip.addExtra(gpa, IntSmall{
6477 .data = try addExtra(extra, IntSmall{
57236478 .ty = int.ty,
57246479 .value = casted,
57256480 }),
57266481 });
5727 return @enumFromInt(ip.items.len - 1);
6482 return gop.put();
57286483 }
57296484
57306485 var buf: [2]Limb = undefined;
57316486 const big_int = BigIntMutable.init(&buf, x).toConst();
57326487 const tag: Tag = if (big_int.positive) .int_positive else .int_negative;
5733 try addInt(ip, gpa, int.ty, tag, big_int.limbs);
6488 try addInt(ip, gpa, tid, int.ty, tag, big_int.limbs);
57346489 },
57356490 .lazy_align, .lazy_size => unreachable,
57366491 }
......@@ -5738,25 +6493,25 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
57386493
57396494 .err => |err| {
57406495 assert(ip.isErrorSetType(err.ty));
5741 ip.items.appendAssumeCapacity(.{
6496 items.appendAssumeCapacity(.{
57426497 .tag = .error_set_error,
5743 .data = try ip.addExtra(gpa, err),
6498 .data = try addExtra(extra, err),
57446499 });
57456500 },
57466501
57476502 .error_union => |error_union| {
57486503 assert(ip.isErrorUnionType(error_union.ty));
5749 ip.items.appendAssumeCapacity(switch (error_union.val) {
6504 items.appendAssumeCapacity(switch (error_union.val) {
57506505 .err_name => |err_name| .{
57516506 .tag = .error_union_error,
5752 .data = try ip.addExtra(gpa, Key.Error{
6507 .data = try addExtra(extra, Key.Error{
57536508 .ty = error_union.ty,
57546509 .name = err_name,
57556510 }),
57566511 },
57576512 .payload => |payload| .{
57586513 .tag = .error_union_payload,
5759 .data = try ip.addExtra(gpa, Tag.TypeValue{
6514 .data = try addExtra(extra, Tag.TypeValue{
57606515 .ty = error_union.ty,
57616516 .val = payload,
57626517 }),
......@@ -5764,7 +6519,7 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
57646519 });
57656520 },
57666521
5767 .enum_literal => |enum_literal| ip.items.appendAssumeCapacity(.{
6522 .enum_literal => |enum_literal| items.appendAssumeCapacity(.{
57686523 .tag = .enum_literal,
57696524 .data = @intFromEnum(enum_literal),
57706525 }),
......@@ -5776,52 +6531,52 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
57766531 .enum_type => assert(ip.typeOf(enum_tag.int) == ip.loadEnumType(enum_tag.ty).tag_ty),
57776532 else => unreachable,
57786533 }
5779 ip.items.appendAssumeCapacity(.{
6534 items.appendAssumeCapacity(.{
57806535 .tag = .enum_tag,
5781 .data = try ip.addExtra(gpa, enum_tag),
6536 .data = try addExtra(extra, enum_tag),
57826537 });
57836538 },
57846539
5785 .empty_enum_value => |enum_or_union_ty| ip.items.appendAssumeCapacity(.{
6540 .empty_enum_value => |enum_or_union_ty| items.appendAssumeCapacity(.{
57866541 .tag = .only_possible_value,
57876542 .data = @intFromEnum(enum_or_union_ty),
57886543 }),
57896544
57906545 .float => |float| {
57916546 switch (float.ty) {
5792 .f16_type => ip.items.appendAssumeCapacity(.{
6547 .f16_type => items.appendAssumeCapacity(.{
57936548 .tag = .float_f16,
57946549 .data = @as(u16, @bitCast(float.storage.f16)),
57956550 }),
5796 .f32_type => ip.items.appendAssumeCapacity(.{
6551 .f32_type => items.appendAssumeCapacity(.{
57976552 .tag = .float_f32,
57986553 .data = @as(u32, @bitCast(float.storage.f32)),
57996554 }),
5800 .f64_type => ip.items.appendAssumeCapacity(.{
6555 .f64_type => items.appendAssumeCapacity(.{
58016556 .tag = .float_f64,
5802 .data = try ip.addExtra(gpa, Float64.pack(float.storage.f64)),
6557 .data = try addExtra(extra, Float64.pack(float.storage.f64)),
58036558 }),
5804 .f80_type => ip.items.appendAssumeCapacity(.{
6559 .f80_type => items.appendAssumeCapacity(.{
58056560 .tag = .float_f80,
5806 .data = try ip.addExtra(gpa, Float80.pack(float.storage.f80)),
6561 .data = try addExtra(extra, Float80.pack(float.storage.f80)),
58076562 }),
5808 .f128_type => ip.items.appendAssumeCapacity(.{
6563 .f128_type => items.appendAssumeCapacity(.{
58096564 .tag = .float_f128,
5810 .data = try ip.addExtra(gpa, Float128.pack(float.storage.f128)),
6565 .data = try addExtra(extra, Float128.pack(float.storage.f128)),
58116566 }),
58126567 .c_longdouble_type => switch (float.storage) {
5813 .f80 => |x| ip.items.appendAssumeCapacity(.{
6568 .f80 => |x| items.appendAssumeCapacity(.{
58146569 .tag = .float_c_longdouble_f80,
5815 .data = try ip.addExtra(gpa, Float80.pack(x)),
6570 .data = try addExtra(extra, Float80.pack(x)),
58166571 }),
5817 inline .f16, .f32, .f64, .f128 => |x| ip.items.appendAssumeCapacity(.{
6572 inline .f16, .f32, .f64, .f128 => |x| items.appendAssumeCapacity(.{
58186573 .tag = .float_c_longdouble_f128,
5819 .data = try ip.addExtra(gpa, Float128.pack(x)),
6574 .data = try addExtra(extra, Float128.pack(x)),
58206575 }),
58216576 },
5822 .comptime_float_type => ip.items.appendAssumeCapacity(.{
6577 .comptime_float_type => items.appendAssumeCapacity(.{
58236578 .tag = .float_comptime_float,
5824 .data = try ip.addExtra(gpa, Float128.pack(float.storage.f128)),
6579 .data = try addExtra(extra, Float128.pack(float.storage.f128)),
58256580 }),
58266581 else => unreachable,
58276582 }
......@@ -5879,11 +6634,11 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
58796634 }
58806635
58816636 if (len == 0) {
5882 ip.items.appendAssumeCapacity(.{
6637 items.appendAssumeCapacity(.{
58836638 .tag = .only_possible_value,
58846639 .data = @intFromEnum(aggregate.ty),
58856640 });
5886 return @enumFromInt(ip.items.len - 1);
6641 return gop.put();
58876642 }
58886643
58896644 switch (ty_key) {
......@@ -5912,11 +6667,11 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
59126667 // This encoding works thanks to the fact that, as we just verified,
59136668 // the type itself contains a slice of values that can be provided
59146669 // in the aggregate fields.
5915 ip.items.appendAssumeCapacity(.{
6670 items.appendAssumeCapacity(.{
59166671 .tag = .only_possible_value,
59176672 .data = @intFromEnum(aggregate.ty),
59186673 });
5919 return @enumFromInt(ip.items.len - 1);
6674 return gop.put();
59206675 },
59216676 else => {},
59226677 }
......@@ -5931,115 +6686,110 @@ pub fn get(ip: *InternPool, gpa: Allocator, key: Key) Allocator.Error!Index {
59316686 }
59326687 const elem = switch (aggregate.storage) {
59336688 .bytes => |bytes| elem: {
5934 _ = ip.map.pop();
5935 const elem = try ip.get(gpa, .{ .int = .{
6689 const elem = try ip.get(gpa, tid, .{ .int = .{
59366690 .ty = .u8_type,
59376691 .storage = .{ .u64 = bytes.at(0, ip) },
59386692 } });
5939 assert(!(try ip.map.getOrPutAdapted(gpa, key, adapter)).found_existing);
5940 try ip.items.ensureUnusedCapacity(gpa, 1);
6693 gop.assign(try ip.getOrPutKey(gpa, tid, key));
6694 try items.ensureUnusedCapacity(1);
59416695 break :elem elem;
59426696 },
59436697 .elems => |elems| elems[0],
59446698 .repeated_elem => |elem| elem,
59456699 };
59466700
5947 try ip.extra.ensureUnusedCapacity(
5948 gpa,
5949 @typeInfo(Repeated).Struct.fields.len,
5950 );
5951 ip.items.appendAssumeCapacity(.{
6701 try extra.ensureUnusedCapacity(@typeInfo(Repeated).Struct.fields.len);
6702 items.appendAssumeCapacity(.{
59526703 .tag = .repeated,
5953 .data = ip.addExtraAssumeCapacity(Repeated{
6704 .data = addExtraAssumeCapacity(extra, Repeated{
59546705 .ty = aggregate.ty,
59556706 .elem_val = elem,
59566707 }),
59576708 });
5958 return @enumFromInt(ip.items.len - 1);
6709 return gop.put();
59596710 }
59606711
59616712 if (child == .u8_type) bytes: {
5962 const string_bytes_index = ip.string_bytes.items.len;
5963 try ip.string_bytes.ensureUnusedCapacity(gpa, @intCast(len_including_sentinel + 1));
5964 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(Bytes).Struct.fields.len);
6713 const strings = ip.getLocal(tid).getMutableStrings(gpa);
6714 const start = strings.mutate.len;
6715 try strings.ensureUnusedCapacity(@intCast(len_including_sentinel + 1));
6716 try extra.ensureUnusedCapacity(@typeInfo(Bytes).Struct.fields.len);
59656717 switch (aggregate.storage) {
5966 .bytes => |bytes| ip.string_bytes.appendSliceAssumeCapacity(bytes.toSlice(len, ip)),
6718 .bytes => |bytes| strings.appendSliceAssumeCapacity(.{bytes.toSlice(len, ip)}),
59676719 .elems => |elems| for (elems[0..@intCast(len)]) |elem| switch (ip.indexToKey(elem)) {
59686720 .undef => {
5969 ip.string_bytes.shrinkRetainingCapacity(string_bytes_index);
6721 strings.shrinkRetainingCapacity(start);
59706722 break :bytes;
59716723 },
5972 .int => |int| ip.string_bytes.appendAssumeCapacity(
5973 @intCast(int.storage.u64),
5974 ),
6724 .int => |int| strings.appendAssumeCapacity(.{@intCast(int.storage.u64)}),
59756725 else => unreachable,
59766726 },
59776727 .repeated_elem => |elem| switch (ip.indexToKey(elem)) {
59786728 .undef => break :bytes,
59796729 .int => |int| @memset(
5980 ip.string_bytes.addManyAsSliceAssumeCapacity(@intCast(len)),
6730 strings.addManyAsSliceAssumeCapacity(@intCast(len))[0],
59816731 @intCast(int.storage.u64),
59826732 ),
59836733 else => unreachable,
59846734 },
59856735 }
5986 if (sentinel != .none) ip.string_bytes.appendAssumeCapacity(
6736 if (sentinel != .none) strings.appendAssumeCapacity(.{
59876737 @intCast(ip.indexToKey(sentinel).int.storage.u64),
5988 );
6738 });
59896739 const string = try ip.getOrPutTrailingString(
59906740 gpa,
6741 tid,
59916742 @intCast(len_including_sentinel),
59926743 .maybe_embedded_nulls,
59936744 );
5994 ip.items.appendAssumeCapacity(.{
6745 items.appendAssumeCapacity(.{
59956746 .tag = .bytes,
5996 .data = ip.addExtraAssumeCapacity(Bytes{
6747 .data = addExtraAssumeCapacity(extra, Bytes{
59976748 .ty = aggregate.ty,
59986749 .bytes = string,
59996750 }),
60006751 });
6001 return @enumFromInt(ip.items.len - 1);
6752 return gop.put();
60026753 }
60036754
6004 try ip.extra.ensureUnusedCapacity(
6005 gpa,
6755 try extra.ensureUnusedCapacity(
60066756 @typeInfo(Tag.Aggregate).Struct.fields.len + @as(usize, @intCast(len_including_sentinel + 1)),
60076757 );
6008 ip.items.appendAssumeCapacity(.{
6758 items.appendAssumeCapacity(.{
60096759 .tag = .aggregate,
6010 .data = ip.addExtraAssumeCapacity(Tag.Aggregate{
6760 .data = addExtraAssumeCapacity(extra, Tag.Aggregate{
60116761 .ty = aggregate.ty,
60126762 }),
60136763 });
6014 ip.extra.appendSliceAssumeCapacity(@ptrCast(aggregate.storage.elems));
6015 if (sentinel != .none) ip.extra.appendAssumeCapacity(@intFromEnum(sentinel));
6764 extra.appendSliceAssumeCapacity(.{@ptrCast(aggregate.storage.elems)});
6765 if (sentinel != .none) extra.appendAssumeCapacity(.{@intFromEnum(sentinel)});
60166766 },
60176767
60186768 .un => |un| {
60196769 assert(un.ty != .none);
60206770 assert(un.val != .none);
6021 ip.items.appendAssumeCapacity(.{
6771 items.appendAssumeCapacity(.{
60226772 .tag = .union_value,
6023 .data = try ip.addExtra(gpa, un),
6773 .data = try addExtra(extra, un),
60246774 });
60256775 },
60266776
60276777 .memoized_call => |memoized_call| {
60286778 for (memoized_call.arg_values) |arg| assert(arg != .none);
6029 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(MemoizedCall).Struct.fields.len +
6779 try extra.ensureUnusedCapacity(@typeInfo(MemoizedCall).Struct.fields.len +
60306780 memoized_call.arg_values.len);
6031 ip.items.appendAssumeCapacity(.{
6781 items.appendAssumeCapacity(.{
60326782 .tag = .memoized_call,
6033 .data = ip.addExtraAssumeCapacity(MemoizedCall{
6783 .data = addExtraAssumeCapacity(extra, MemoizedCall{
60346784 .func = memoized_call.func,
60356785 .args_len = @intCast(memoized_call.arg_values.len),
60366786 .result = memoized_call.result,
60376787 }),
60386788 });
6039 ip.extra.appendSliceAssumeCapacity(@ptrCast(memoized_call.arg_values));
6789 extra.appendSliceAssumeCapacity(.{@ptrCast(memoized_call.arg_values)});
60406790 },
60416791 }
6042 return @enumFromInt(ip.items.len - 1);
6792 return gop.put();
60436793}
60446794
60456795pub const UnionTypeInit = struct {
......@@ -6074,9 +6824,13 @@ pub const UnionTypeInit = struct {
60746824 },
60756825};
60766826
6077pub fn getUnionType(ip: *InternPool, gpa: Allocator, ini: UnionTypeInit) Allocator.Error!WipNamespaceType.Result {
6078 const adapter: KeyAdapter = .{ .intern_pool = ip };
6079 const gop = try ip.map.getOrPutAdapted(gpa, Key{ .union_type = switch (ini.key) {
6827pub fn getUnionType(
6828 ip: *InternPool,
6829 gpa: Allocator,
6830 tid: Zcu.PerThread.Id,
6831 ini: UnionTypeInit,
6832) Allocator.Error!WipNamespaceType.Result {
6833 var gop = try ip.getOrPutKey(gpa, tid, .{ .union_type = switch (ini.key) {
60806834 .declared => |d| .{ .declared = .{
60816835 .zir_index = d.zir_index,
60826836 .captures = .{ .external = d.captures },
......@@ -6085,13 +6839,18 @@ pub fn getUnionType(ip: *InternPool, gpa: Allocator, ini: UnionTypeInit) Allocat
60856839 .zir_index = r.zir_index,
60866840 .type_hash = r.type_hash,
60876841 } },
6088 } }, adapter);
6089 if (gop.found_existing) return .{ .existing = @enumFromInt(gop.index) };
6090 errdefer _ = ip.map.pop();
6842 } });
6843 defer gop.deinit();
6844 if (gop == .existing) return .{ .existing = gop.existing };
6845
6846 const local = ip.getLocal(tid);
6847 const items = local.getMutableItems(gpa);
6848 try items.ensureUnusedCapacity(1);
6849 const extra = local.getMutableExtra(gpa);
60916850
60926851 const align_elements_len = if (ini.flags.any_aligned_fields) (ini.fields_len + 3) / 4 else 0;
60936852 const align_element: u32 = @bitCast([1]u8{@intFromEnum(Alignment.none)} ** 4);
6094 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(Tag.TypeUnion).Struct.fields.len +
6853 try extra.ensureUnusedCapacity(@typeInfo(Tag.TypeUnion).Struct.fields.len +
60956854 // TODO: fmt bug
60966855 // zig fmt: off
60976856 switch (ini.key) {
......@@ -6101,9 +6860,8 @@ pub fn getUnionType(ip: *InternPool, gpa: Allocator, ini: UnionTypeInit) Allocat
61016860 // zig fmt: on
61026861 ini.fields_len + // field types
61036862 align_elements_len);
6104 try ip.items.ensureUnusedCapacity(gpa, 1);
61056863
6106 const extra_index = ip.addExtraAssumeCapacity(Tag.TypeUnion{
6864 const extra_index = addExtraAssumeCapacity(extra, Tag.TypeUnion{
61076865 .flags = .{
61086866 .any_captures = ini.key == .declared and ini.key.declared.captures.len != 0,
61096867 .runtime_tag = ini.flags.runtime_tag,
......@@ -6127,34 +6885,35 @@ pub fn getUnionType(ip: *InternPool, gpa: Allocator, ini: UnionTypeInit) Allocat
61276885 },
61286886 });
61296887
6130 ip.items.appendAssumeCapacity(.{
6888 items.appendAssumeCapacity(.{
61316889 .tag = .type_union,
61326890 .data = extra_index,
61336891 });
61346892
61356893 switch (ini.key) {
61366894 .declared => |d| if (d.captures.len != 0) {
6137 ip.extra.appendAssumeCapacity(@intCast(d.captures.len));
6138 ip.extra.appendSliceAssumeCapacity(@ptrCast(d.captures));
6895 extra.appendAssumeCapacity(.{@intCast(d.captures.len)});
6896 extra.appendSliceAssumeCapacity(.{@ptrCast(d.captures)});
61396897 },
6140 .reified => |r| _ = ip.addExtraAssumeCapacity(PackedU64.init(r.type_hash)),
6898 .reified => |r| _ = addExtraAssumeCapacity(extra, PackedU64.init(r.type_hash)),
61416899 }
61426900
61436901 // field types
61446902 if (ini.field_types.len > 0) {
61456903 assert(ini.field_types.len == ini.fields_len);
6146 ip.extra.appendSliceAssumeCapacity(@ptrCast(ini.field_types));
6904 extra.appendSliceAssumeCapacity(.{@ptrCast(ini.field_types)});
61476905 } else {
6148 ip.extra.appendNTimesAssumeCapacity(@intFromEnum(Index.none), ini.fields_len);
6906 extra.appendNTimesAssumeCapacity(.{@intFromEnum(Index.none)}, ini.fields_len);
61496907 }
61506908
61516909 // field alignments
61526910 if (ini.flags.any_aligned_fields) {
6153 ip.extra.appendNTimesAssumeCapacity(align_element, align_elements_len);
6911 extra.appendNTimesAssumeCapacity(.{align_element}, align_elements_len);
61546912 if (ini.field_aligns.len > 0) {
61556913 assert(ini.field_aligns.len == ini.fields_len);
61566914 @memcpy((Alignment.Slice{
6157 .start = @intCast(ip.extra.items.len - align_elements_len),
6915 .tid = tid,
6916 .start = @intCast(extra.mutate.len - align_elements_len),
61586917 .len = @intCast(ini.field_aligns.len),
61596918 }).get(ip), ini.field_aligns);
61606919 }
......@@ -6163,7 +6922,8 @@ pub fn getUnionType(ip: *InternPool, gpa: Allocator, ini: UnionTypeInit) Allocat
61636922 }
61646923
61656924 return .{ .wip = .{
6166 .index = @enumFromInt(ip.items.len - 1),
6925 .tid = tid,
6926 .index = gop.put(),
61676927 .decl_extra_index = extra_index + std.meta.fieldIndex(Tag.TypeUnion, "decl").?,
61686928 .namespace_extra_index = if (ini.has_namespace)
61696929 extra_index + std.meta.fieldIndex(Tag.TypeUnion, "namespace").?
......@@ -6173,20 +6933,22 @@ pub fn getUnionType(ip: *InternPool, gpa: Allocator, ini: UnionTypeInit) Allocat
61736933}
61746934
61756935pub const WipNamespaceType = struct {
6936 tid: Zcu.PerThread.Id,
61766937 index: Index,
61776938 decl_extra_index: u32,
61786939 namespace_extra_index: ?u32,
61796940 pub fn finish(wip: WipNamespaceType, ip: *InternPool, decl: DeclIndex, namespace: OptionalNamespaceIndex) Index {
6180 ip.extra.items[wip.decl_extra_index] = @intFromEnum(decl);
6941 const extra_items = ip.getLocalShared(wip.tid).extra.acquire().view().items(.@"0");
6942 extra_items[wip.decl_extra_index] = @intFromEnum(decl);
61816943 if (wip.namespace_extra_index) |i| {
6182 ip.extra.items[i] = @intFromEnum(namespace.unwrap().?);
6944 extra_items[i] = @intFromEnum(namespace.unwrap().?);
61836945 } else {
61846946 assert(namespace == .none);
61856947 }
61866948 return wip.index;
61876949 }
6188 pub fn cancel(wip: WipNamespaceType, ip: *InternPool) void {
6189 ip.remove(wip.index);
6950 pub fn cancel(wip: WipNamespaceType, ip: *InternPool, tid: Zcu.PerThread.Id) void {
6951 ip.remove(tid, wip.index);
61906952 }
61916953
61926954 pub const Result = union(enum) {
......@@ -6221,10 +6983,10 @@ pub const StructTypeInit = struct {
62216983pub fn getStructType(
62226984 ip: *InternPool,
62236985 gpa: Allocator,
6986 tid: Zcu.PerThread.Id,
62246987 ini: StructTypeInit,
62256988) Allocator.Error!WipNamespaceType.Result {
6226 const adapter: KeyAdapter = .{ .intern_pool = ip };
6227 const key: Key = .{ .struct_type = switch (ini.key) {
6989 var gop = try ip.getOrPutKey(gpa, tid, .{ .struct_type = switch (ini.key) {
62286990 .declared => |d| .{ .declared = .{
62296991 .zir_index = d.zir_index,
62306992 .captures = .{ .external = d.captures },
......@@ -6233,10 +6995,13 @@ pub fn getStructType(
62336995 .zir_index = r.zir_index,
62346996 .type_hash = r.type_hash,
62356997 } },
6236 } };
6237 const gop = try ip.map.getOrPutAdapted(gpa, key, adapter);
6238 if (gop.found_existing) return .{ .existing = @enumFromInt(gop.index) };
6239 errdefer _ = ip.map.pop();
6998 } });
6999 defer gop.deinit();
7000 if (gop == .existing) return .{ .existing = gop.existing };
7001
7002 const local = ip.getLocal(tid);
7003 const items = local.getMutableItems(gpa);
7004 const extra = local.getMutableExtra(gpa);
62407005
62417006 const names_map = try ip.addMap(gpa, ini.fields_len);
62427007 errdefer _ = ip.maps.pop();
......@@ -6249,7 +7014,7 @@ pub fn getStructType(
62497014 .auto => false,
62507015 .@"extern" => true,
62517016 .@"packed" => {
6252 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(Tag.TypeStructPacked).Struct.fields.len +
7017 try extra.ensureUnusedCapacity(@typeInfo(Tag.TypeStructPacked).Struct.fields.len +
62537018 // TODO: fmt bug
62547019 // zig fmt: off
62557020 switch (ini.key) {
......@@ -6260,7 +7025,7 @@ pub fn getStructType(
62607025 ini.fields_len + // types
62617026 ini.fields_len + // names
62627027 ini.fields_len); // inits
6263 const extra_index = ip.addExtraAssumeCapacity(Tag.TypeStructPacked{
7028 const extra_index = addExtraAssumeCapacity(extra, Tag.TypeStructPacked{
62647029 .decl = undefined, // set by `finish`
62657030 .zir_index = zir_index,
62667031 .fields_len = ini.fields_len,
......@@ -6274,26 +7039,27 @@ pub fn getStructType(
62747039 .is_reified = ini.key == .reified,
62757040 },
62767041 });
6277 try ip.items.append(gpa, .{
7042 try items.append(.{
62787043 .tag = if (ini.any_default_inits) .type_struct_packed_inits else .type_struct_packed,
62797044 .data = extra_index,
62807045 });
62817046 switch (ini.key) {
62827047 .declared => |d| if (d.captures.len != 0) {
6283 ip.extra.appendAssumeCapacity(@intCast(d.captures.len));
6284 ip.extra.appendSliceAssumeCapacity(@ptrCast(d.captures));
7048 extra.appendAssumeCapacity(.{@intCast(d.captures.len)});
7049 extra.appendSliceAssumeCapacity(.{@ptrCast(d.captures)});
62857050 },
62867051 .reified => |r| {
6287 _ = ip.addExtraAssumeCapacity(PackedU64.init(r.type_hash));
7052 _ = addExtraAssumeCapacity(extra, PackedU64.init(r.type_hash));
62887053 },
62897054 }
6290 ip.extra.appendNTimesAssumeCapacity(@intFromEnum(Index.none), ini.fields_len);
6291 ip.extra.appendNTimesAssumeCapacity(@intFromEnum(OptionalNullTerminatedString.none), ini.fields_len);
7055 extra.appendNTimesAssumeCapacity(.{@intFromEnum(Index.none)}, ini.fields_len);
7056 extra.appendNTimesAssumeCapacity(.{@intFromEnum(OptionalNullTerminatedString.none)}, ini.fields_len);
62927057 if (ini.any_default_inits) {
6293 ip.extra.appendNTimesAssumeCapacity(@intFromEnum(Index.none), ini.fields_len);
7058 extra.appendNTimesAssumeCapacity(.{@intFromEnum(Index.none)}, ini.fields_len);
62947059 }
62957060 return .{ .wip = .{
6296 .index = @enumFromInt(ip.items.len - 1),
7061 .tid = tid,
7062 .index = gop.put(),
62977063 .decl_extra_index = extra_index + std.meta.fieldIndex(Tag.TypeStructPacked, "decl").?,
62987064 .namespace_extra_index = if (ini.has_namespace)
62997065 extra_index + std.meta.fieldIndex(Tag.TypeStructPacked, "namespace").?
......@@ -6307,7 +7073,7 @@ pub fn getStructType(
63077073 const align_element: u32 = @bitCast([1]u8{@intFromEnum(Alignment.none)} ** 4);
63087074 const comptime_elements_len = if (ini.any_comptime_fields) (ini.fields_len + 31) / 32 else 0;
63097075
6310 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(Tag.TypeStruct).Struct.fields.len +
7076 try extra.ensureUnusedCapacity(@typeInfo(Tag.TypeStruct).Struct.fields.len +
63117077 // TODO: fmt bug
63127078 // zig fmt: off
63137079 switch (ini.key) {
......@@ -6318,7 +7084,7 @@ pub fn getStructType(
63187084 (ini.fields_len * 5) + // types, names, inits, runtime order, offsets
63197085 align_elements_len + comptime_elements_len +
63207086 2); // names_map + namespace
6321 const extra_index = ip.addExtraAssumeCapacity(Tag.TypeStruct{
7087 const extra_index = addExtraAssumeCapacity(extra, Tag.TypeStruct{
63227088 .decl = undefined, // set by `finish`
63237089 .zir_index = zir_index,
63247090 .fields_len = ini.fields_len,
......@@ -6346,43 +7112,44 @@ pub fn getStructType(
63467112 .is_reified = ini.key == .reified,
63477113 },
63487114 });
6349 try ip.items.append(gpa, .{
7115 try items.append(.{
63507116 .tag = .type_struct,
63517117 .data = extra_index,
63527118 });
63537119 switch (ini.key) {
63547120 .declared => |d| if (d.captures.len != 0) {
6355 ip.extra.appendAssumeCapacity(@intCast(d.captures.len));
6356 ip.extra.appendSliceAssumeCapacity(@ptrCast(d.captures));
7121 extra.appendAssumeCapacity(.{@intCast(d.captures.len)});
7122 extra.appendSliceAssumeCapacity(.{@ptrCast(d.captures)});
63577123 },
63587124 .reified => |r| {
6359 _ = ip.addExtraAssumeCapacity(PackedU64.init(r.type_hash));
7125 _ = addExtraAssumeCapacity(extra, PackedU64.init(r.type_hash));
63607126 },
63617127 }
6362 ip.extra.appendNTimesAssumeCapacity(@intFromEnum(Index.none), ini.fields_len);
7128 extra.appendNTimesAssumeCapacity(.{@intFromEnum(Index.none)}, ini.fields_len);
63637129 if (!ini.is_tuple) {
6364 ip.extra.appendAssumeCapacity(@intFromEnum(names_map));
6365 ip.extra.appendNTimesAssumeCapacity(@intFromEnum(OptionalNullTerminatedString.none), ini.fields_len);
7130 extra.appendAssumeCapacity(.{@intFromEnum(names_map)});
7131 extra.appendNTimesAssumeCapacity(.{@intFromEnum(OptionalNullTerminatedString.none)}, ini.fields_len);
63667132 }
63677133 if (ini.any_default_inits) {
6368 ip.extra.appendNTimesAssumeCapacity(@intFromEnum(Index.none), ini.fields_len);
7134 extra.appendNTimesAssumeCapacity(.{@intFromEnum(Index.none)}, ini.fields_len);
63697135 }
63707136 const namespace_extra_index: ?u32 = if (ini.has_namespace) i: {
6371 ip.extra.appendAssumeCapacity(undefined); // set by `finish`
6372 break :i @intCast(ip.extra.items.len - 1);
7137 extra.appendAssumeCapacity(undefined); // set by `finish`
7138 break :i @intCast(extra.mutate.len - 1);
63737139 } else null;
63747140 if (ini.any_aligned_fields) {
6375 ip.extra.appendNTimesAssumeCapacity(align_element, align_elements_len);
7141 extra.appendNTimesAssumeCapacity(.{align_element}, align_elements_len);
63767142 }
63777143 if (ini.any_comptime_fields) {
6378 ip.extra.appendNTimesAssumeCapacity(0, comptime_elements_len);
7144 extra.appendNTimesAssumeCapacity(.{0}, comptime_elements_len);
63797145 }
63807146 if (ini.layout == .auto) {
6381 ip.extra.appendNTimesAssumeCapacity(@intFromEnum(LoadedStructType.RuntimeOrder.unresolved), ini.fields_len);
7147 extra.appendNTimesAssumeCapacity(.{@intFromEnum(LoadedStructType.RuntimeOrder.unresolved)}, ini.fields_len);
63827148 }
6383 ip.extra.appendNTimesAssumeCapacity(std.math.maxInt(u32), ini.fields_len);
7149 extra.appendNTimesAssumeCapacity(.{std.math.maxInt(u32)}, ini.fields_len);
63847150 return .{ .wip = .{
6385 .index = @enumFromInt(ip.items.len - 1),
7151 .tid = tid,
7152 .index = gop.put(),
63867153 .decl_extra_index = extra_index + std.meta.fieldIndex(Tag.TypeStruct, "decl").?,
63877154 .namespace_extra_index = namespace_extra_index,
63887155 } };
......@@ -6396,43 +7163,52 @@ pub const AnonStructTypeInit = struct {
63967163 values: []const Index,
63977164};
63987165
6399pub fn getAnonStructType(ip: *InternPool, gpa: Allocator, ini: AnonStructTypeInit) Allocator.Error!Index {
7166pub fn getAnonStructType(
7167 ip: *InternPool,
7168 gpa: Allocator,
7169 tid: Zcu.PerThread.Id,
7170 ini: AnonStructTypeInit,
7171) Allocator.Error!Index {
64007172 assert(ini.types.len == ini.values.len);
64017173 for (ini.types) |elem| assert(elem != .none);
64027174
6403 const prev_extra_len = ip.extra.items.len;
7175 const local = ip.getLocal(tid);
7176 const items = local.getMutableItems(gpa);
7177 const extra = local.getMutableExtra(gpa);
7178
7179 const prev_extra_len = extra.mutate.len;
64047180 const fields_len: u32 = @intCast(ini.types.len);
64057181
6406 try ip.extra.ensureUnusedCapacity(
6407 gpa,
7182 try items.ensureUnusedCapacity(1);
7183 try extra.ensureUnusedCapacity(
64087184 @typeInfo(TypeStructAnon).Struct.fields.len + (fields_len * 3),
64097185 );
6410 try ip.items.ensureUnusedCapacity(gpa, 1);
64117186
6412 const extra_index = ip.addExtraAssumeCapacity(TypeStructAnon{
7187 const extra_index = addExtraAssumeCapacity(extra, TypeStructAnon{
64137188 .fields_len = fields_len,
64147189 });
6415 ip.extra.appendSliceAssumeCapacity(@ptrCast(ini.types));
6416 ip.extra.appendSliceAssumeCapacity(@ptrCast(ini.values));
7190 extra.appendSliceAssumeCapacity(.{@ptrCast(ini.types)});
7191 extra.appendSliceAssumeCapacity(.{@ptrCast(ini.values)});
7192 errdefer extra.mutate.len = prev_extra_len;
64177193
6418 const adapter: KeyAdapter = .{ .intern_pool = ip };
6419 const key: Key = .{
6420 .anon_struct_type = if (ini.names.len == 0) extraTypeTupleAnon(ip, extra_index) else k: {
7194 var gop = try ip.getOrPutKey(gpa, tid, .{
7195 .anon_struct_type = if (ini.names.len == 0) extraTypeTupleAnon(tid, extra.list.*, extra_index) else k: {
64217196 assert(ini.names.len == ini.types.len);
6422 ip.extra.appendSliceAssumeCapacity(@ptrCast(ini.names));
6423 break :k extraTypeStructAnon(ip, extra_index);
7197 extra.appendSliceAssumeCapacity(.{@ptrCast(ini.names)});
7198 break :k extraTypeStructAnon(tid, extra.list.*, extra_index);
64247199 },
6425 };
6426 const gop = try ip.map.getOrPutAdapted(gpa, key, adapter);
6427 if (gop.found_existing) {
6428 ip.extra.items.len = prev_extra_len;
6429 return @enumFromInt(gop.index);
7200 });
7201 defer gop.deinit();
7202 if (gop == .existing) {
7203 extra.mutate.len = prev_extra_len;
7204 return gop.existing;
64307205 }
6431 ip.items.appendAssumeCapacity(.{
7206
7207 items.appendAssumeCapacity(.{
64327208 .tag = if (ini.names.len == 0) .type_tuple_anon else .type_struct_anon,
64337209 .data = extra_index,
64347210 });
6435 return @enumFromInt(ip.items.len - 1);
7211 return gop.put();
64367212}
64377213
64387214/// This is equivalent to `Key.FuncType` but adjusted to have a slice for `param_types`.
......@@ -6450,24 +7226,33 @@ pub const GetFuncTypeKey = struct {
64507226 addrspace_is_generic: bool = false,
64517227};
64527228
6453pub fn getFuncType(ip: *InternPool, gpa: Allocator, key: GetFuncTypeKey) Allocator.Error!Index {
7229pub fn getFuncType(
7230 ip: *InternPool,
7231 gpa: Allocator,
7232 tid: Zcu.PerThread.Id,
7233 key: GetFuncTypeKey,
7234) Allocator.Error!Index {
64547235 // Validate input parameters.
64557236 assert(key.return_type != .none);
64567237 for (key.param_types) |param_type| assert(param_type != .none);
64577238
7239 const local = ip.getLocal(tid);
7240 const items = local.getMutableItems(gpa);
7241 try items.ensureUnusedCapacity(1);
7242 const extra = local.getMutableExtra(gpa);
7243
64587244 // The strategy here is to add the function type unconditionally, then to
64597245 // ask if it already exists, and if so, revert the lengths of the mutated
64607246 // arrays. This is similar to what `getOrPutTrailingString` does.
6461 const prev_extra_len = ip.extra.items.len;
7247 const prev_extra_len = extra.mutate.len;
64627248 const params_len: u32 = @intCast(key.param_types.len);
64637249
6464 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(Tag.TypeFunction).Struct.fields.len +
7250 try extra.ensureUnusedCapacity(@typeInfo(Tag.TypeFunction).Struct.fields.len +
64657251 @intFromBool(key.comptime_bits != 0) +
64667252 @intFromBool(key.noalias_bits != 0) +
64677253 params_len);
6468 try ip.items.ensureUnusedCapacity(gpa, 1);
64697254
6470 const func_type_extra_index = ip.addExtraAssumeCapacity(Tag.TypeFunction{
7255 const func_type_extra_index = addExtraAssumeCapacity(extra, Tag.TypeFunction{
64717256 .params_len = params_len,
64727257 .return_type = key.return_type,
64737258 .flags = .{
......@@ -6483,40 +7268,51 @@ pub fn getFuncType(ip: *InternPool, gpa: Allocator, key: GetFuncTypeKey) Allocat
64837268 },
64847269 });
64857270
6486 if (key.comptime_bits != 0) ip.extra.appendAssumeCapacity(key.comptime_bits);
6487 if (key.noalias_bits != 0) ip.extra.appendAssumeCapacity(key.noalias_bits);
6488 ip.extra.appendSliceAssumeCapacity(@ptrCast(key.param_types));
7271 if (key.comptime_bits != 0) extra.appendAssumeCapacity(.{key.comptime_bits});
7272 if (key.noalias_bits != 0) extra.appendAssumeCapacity(.{key.noalias_bits});
7273 extra.appendSliceAssumeCapacity(.{@ptrCast(key.param_types)});
7274 errdefer extra.mutate.len = prev_extra_len;
64897275
6490 const adapter: KeyAdapter = .{ .intern_pool = ip };
6491 const gop = try ip.map.getOrPutAdapted(gpa, Key{
6492 .func_type = extraFuncType(ip, func_type_extra_index),
6493 }, adapter);
6494 if (gop.found_existing) {
6495 ip.extra.items.len = prev_extra_len;
6496 return @enumFromInt(gop.index);
7276 var gop = try ip.getOrPutKey(gpa, tid, .{
7277 .func_type = extraFuncType(tid, extra.list.*, func_type_extra_index),
7278 });
7279 defer gop.deinit();
7280 if (gop == .existing) {
7281 extra.mutate.len = prev_extra_len;
7282 return gop.existing;
64977283 }
64987284
6499 ip.items.appendAssumeCapacity(.{
7285 items.appendAssumeCapacity(.{
65007286 .tag = .type_function,
65017287 .data = func_type_extra_index,
65027288 });
6503 return @enumFromInt(ip.items.len - 1);
7289 return gop.put();
65047290}
65057291
6506pub fn getExternFunc(ip: *InternPool, gpa: Allocator, key: Key.ExternFunc) Allocator.Error!Index {
6507 const adapter: KeyAdapter = .{ .intern_pool = ip };
6508 const gop = try ip.map.getOrPutAdapted(gpa, Key{ .extern_func = key }, adapter);
6509 if (gop.found_existing) return @enumFromInt(gop.index);
6510 errdefer _ = ip.map.pop();
6511 const prev_extra_len = ip.extra.items.len;
6512 const extra_index = try ip.addExtra(gpa, @as(Tag.ExternFunc, key));
6513 errdefer ip.extra.items.len = prev_extra_len;
6514 try ip.items.append(gpa, .{
6515 .tag = .extern_func,
6516 .data = extra_index,
7292pub fn getExternFunc(
7293 ip: *InternPool,
7294 gpa: Allocator,
7295 tid: Zcu.PerThread.Id,
7296 key: Key.ExternFunc,
7297) Allocator.Error!Index {
7298 var gop = try ip.getOrPutKey(gpa, tid, .{ .extern_func = key });
7299 defer gop.deinit();
7300 if (gop == .existing) return gop.existing;
7301
7302 const local = ip.getLocal(tid);
7303 const items = local.getMutableItems(gpa);
7304 try items.ensureUnusedCapacity(1);
7305 const extra = local.getMutableExtra(gpa);
7306
7307 const prev_extra_len = extra.mutate.len;
7308 const extra_index = try addExtra(extra, @as(Tag.ExternFunc, key));
7309 errdefer extra.mutate.len = prev_extra_len;
7310 items.appendAssumeCapacity(.{
7311 .tag = .extern_func,
7312 .data = extra_index,
65177313 });
6518 errdefer ip.items.len -= 1;
6519 return @enumFromInt(ip.items.len - 1);
7314 errdefer items.mutate.len -= 1;
7315 return gop.put();
65207316}
65217317
65227318pub const GetFuncDeclKey = struct {
......@@ -6531,17 +7327,25 @@ pub const GetFuncDeclKey = struct {
65317327 is_noinline: bool,
65327328};
65337329
6534pub fn getFuncDecl(ip: *InternPool, gpa: Allocator, key: GetFuncDeclKey) Allocator.Error!Index {
7330pub fn getFuncDecl(
7331 ip: *InternPool,
7332 gpa: Allocator,
7333 tid: Zcu.PerThread.Id,
7334 key: GetFuncDeclKey,
7335) Allocator.Error!Index {
7336 const local = ip.getLocal(tid);
7337 const items = local.getMutableItems(gpa);
7338 try items.ensureUnusedCapacity(1);
7339 const extra = local.getMutableExtra(gpa);
7340
65357341 // The strategy here is to add the function type unconditionally, then to
65367342 // ask if it already exists, and if so, revert the lengths of the mutated
65377343 // arrays. This is similar to what `getOrPutTrailingString` does.
6538 const prev_extra_len = ip.extra.items.len;
7344 const prev_extra_len = extra.mutate.len;
65397345
6540 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(Tag.FuncDecl).Struct.fields.len);
6541 try ip.items.ensureUnusedCapacity(gpa, 1);
6542 try ip.map.ensureUnusedCapacity(gpa, 1);
7346 try extra.ensureUnusedCapacity(@typeInfo(Tag.FuncDecl).Struct.fields.len);
65437347
6544 const func_decl_extra_index = ip.addExtraAssumeCapacity(Tag.FuncDecl{
7348 const func_decl_extra_index = addExtraAssumeCapacity(extra, Tag.FuncDecl{
65457349 .analysis = .{
65467350 .state = if (key.cc == .Inline) .inline_only else .none,
65477351 .is_cold = false,
......@@ -6558,22 +7362,22 @@ pub fn getFuncDecl(ip: *InternPool, gpa: Allocator, key: GetFuncDeclKey) Allocat
65587362 .lbrace_column = key.lbrace_column,
65597363 .rbrace_column = key.rbrace_column,
65607364 });
7365 errdefer extra.mutate.len = prev_extra_len;
65617366
6562 const adapter: KeyAdapter = .{ .intern_pool = ip };
6563 const gop = ip.map.getOrPutAssumeCapacityAdapted(Key{
6564 .func = extraFuncDecl(ip, func_decl_extra_index),
6565 }, adapter);
6566
6567 if (gop.found_existing) {
6568 ip.extra.items.len = prev_extra_len;
6569 return @enumFromInt(gop.index);
7367 var gop = try ip.getOrPutKey(gpa, tid, .{
7368 .func = extraFuncDecl(tid, extra.list.*, func_decl_extra_index),
7369 });
7370 defer gop.deinit();
7371 if (gop == .existing) {
7372 extra.mutate.len = prev_extra_len;
7373 return gop.existing;
65707374 }
65717375
6572 ip.items.appendAssumeCapacity(.{
7376 items.appendAssumeCapacity(.{
65737377 .tag = .func_decl,
65747378 .data = func_decl_extra_index,
65757379 });
6576 return @enumFromInt(ip.items.len - 1);
7380 return gop.put();
65777381}
65787382
65797383pub const GetFuncDeclIesKey = struct {
......@@ -6598,28 +7402,53 @@ pub const GetFuncDeclIesKey = struct {
65987402 rbrace_column: u32,
65997403};
66007404
6601pub fn getFuncDeclIes(ip: *InternPool, gpa: Allocator, key: GetFuncDeclIesKey) Allocator.Error!Index {
7405pub fn getFuncDeclIes(
7406 ip: *InternPool,
7407 gpa: Allocator,
7408 tid: Zcu.PerThread.Id,
7409 key: GetFuncDeclIesKey,
7410) Allocator.Error!Index {
66027411 // Validate input parameters.
66037412 assert(key.bare_return_type != .none);
66047413 for (key.param_types) |param_type| assert(param_type != .none);
66057414
7415 const local = ip.getLocal(tid);
7416 const items = local.getMutableItems(gpa);
7417 try items.ensureUnusedCapacity(4);
7418 const extra = local.getMutableExtra(gpa);
7419
66067420 // The strategy here is to add the function decl unconditionally, then to
66077421 // ask if it already exists, and if so, revert the lengths of the mutated
66087422 // arrays. This is similar to what `getOrPutTrailingString` does.
6609 const prev_extra_len = ip.extra.items.len;
7423 const prev_extra_len = extra.mutate.len;
66107424 const params_len: u32 = @intCast(key.param_types.len);
66117425
6612 try ip.map.ensureUnusedCapacity(gpa, 4);
6613 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(Tag.FuncDecl).Struct.fields.len +
7426 try extra.ensureUnusedCapacity(@typeInfo(Tag.FuncDecl).Struct.fields.len +
66147427 1 + // inferred_error_set
66157428 @typeInfo(Tag.ErrorUnionType).Struct.fields.len +
66167429 @typeInfo(Tag.TypeFunction).Struct.fields.len +
66177430 @intFromBool(key.comptime_bits != 0) +
66187431 @intFromBool(key.noalias_bits != 0) +
66197432 params_len);
6620 try ip.items.ensureUnusedCapacity(gpa, 4);
66217433
6622 const func_decl_extra_index = ip.addExtraAssumeCapacity(Tag.FuncDecl{
7434 const func_index = Index.Unwrapped.wrap(.{
7435 .tid = tid,
7436 .index = items.mutate.len + 0,
7437 }, ip);
7438 const error_union_type = Index.Unwrapped.wrap(.{
7439 .tid = tid,
7440 .index = items.mutate.len + 1,
7441 }, ip);
7442 const error_set_type = Index.Unwrapped.wrap(.{
7443 .tid = tid,
7444 .index = items.mutate.len + 2,
7445 }, ip);
7446 const func_ty = Index.Unwrapped.wrap(.{
7447 .tid = tid,
7448 .index = items.mutate.len + 3,
7449 }, ip);
7450
7451 const func_decl_extra_index = addExtraAssumeCapacity(extra, Tag.FuncDecl{
66237452 .analysis = .{
66247453 .state = if (key.cc == .Inline) .inline_only else .none,
66257454 .is_cold = false,
......@@ -6629,36 +7458,18 @@ pub fn getFuncDeclIes(ip: *InternPool, gpa: Allocator, key: GetFuncDeclIesKey) A
66297458 .inferred_error_set = true,
66307459 },
66317460 .owner_decl = key.owner_decl,
6632 .ty = @enumFromInt(ip.items.len + 3),
7461 .ty = func_ty,
66337462 .zir_body_inst = key.zir_body_inst,
66347463 .lbrace_line = key.lbrace_line,
66357464 .rbrace_line = key.rbrace_line,
66367465 .lbrace_column = key.lbrace_column,
66377466 .rbrace_column = key.rbrace_column,
66387467 });
7468 extra.appendAssumeCapacity(.{@intFromEnum(Index.none)});
66397469
6640 ip.items.appendAssumeCapacity(.{
6641 .tag = .func_decl,
6642 .data = func_decl_extra_index,
6643 });
6644 ip.extra.appendAssumeCapacity(@intFromEnum(Index.none));
6645
6646 ip.items.appendAssumeCapacity(.{
6647 .tag = .type_error_union,
6648 .data = ip.addExtraAssumeCapacity(Tag.ErrorUnionType{
6649 .error_set_type = @enumFromInt(ip.items.len + 1),
6650 .payload_type = key.bare_return_type,
6651 }),
6652 });
6653
6654 ip.items.appendAssumeCapacity(.{
6655 .tag = .type_inferred_error_set,
6656 .data = @intCast(ip.items.len - 2),
6657 });
6658
6659 const func_type_extra_index = ip.addExtraAssumeCapacity(Tag.TypeFunction{
7470 const func_type_extra_index = addExtraAssumeCapacity(extra, Tag.TypeFunction{
66607471 .params_len = params_len,
6661 .return_type = @enumFromInt(ip.items.len - 2),
7472 .return_type = error_union_type,
66627473 .flags = .{
66637474 .cc = key.cc orelse .Unspecified,
66647475 .is_var_args = key.is_var_args,
......@@ -6671,78 +7482,104 @@ pub fn getFuncDeclIes(ip: *InternPool, gpa: Allocator, key: GetFuncDeclIesKey) A
66717482 .addrspace_is_generic = key.addrspace_is_generic,
66727483 },
66737484 });
6674 if (key.comptime_bits != 0) ip.extra.appendAssumeCapacity(key.comptime_bits);
6675 if (key.noalias_bits != 0) ip.extra.appendAssumeCapacity(key.noalias_bits);
6676 ip.extra.appendSliceAssumeCapacity(@ptrCast(key.param_types));
7485 if (key.comptime_bits != 0) extra.appendAssumeCapacity(.{key.comptime_bits});
7486 if (key.noalias_bits != 0) extra.appendAssumeCapacity(.{key.noalias_bits});
7487 extra.appendSliceAssumeCapacity(.{@ptrCast(key.param_types)});
66777488
6678 ip.items.appendAssumeCapacity(.{
6679 .tag = .type_function,
6680 .data = func_type_extra_index,
7489 items.appendSliceAssumeCapacity(.{
7490 .tag = &.{
7491 .func_decl,
7492 .type_error_union,
7493 .type_inferred_error_set,
7494 .type_function,
7495 },
7496 .data = &.{
7497 func_decl_extra_index,
7498 addExtraAssumeCapacity(extra, Tag.ErrorUnionType{
7499 .error_set_type = error_set_type,
7500 .payload_type = key.bare_return_type,
7501 }),
7502 @intFromEnum(func_index),
7503 func_type_extra_index,
7504 },
66817505 });
7506 errdefer {
7507 items.mutate.len -= 4;
7508 extra.mutate.len = prev_extra_len;
7509 }
66827510
6683 const adapter: KeyAdapter = .{ .intern_pool = ip };
6684 const gop = ip.map.getOrPutAssumeCapacityAdapted(Key{
6685 .func = extraFuncDecl(ip, func_decl_extra_index),
6686 }, adapter);
6687 if (!gop.found_existing) {
6688 assert(!ip.map.getOrPutAssumeCapacityAdapted(Key{ .error_union_type = .{
6689 .error_set_type = @enumFromInt(ip.items.len - 2),
6690 .payload_type = key.bare_return_type,
6691 } }, adapter).found_existing);
6692 assert(!ip.map.getOrPutAssumeCapacityAdapted(Key{
6693 .inferred_error_set_type = @enumFromInt(ip.items.len - 4),
6694 }, adapter).found_existing);
6695 assert(!ip.map.getOrPutAssumeCapacityAdapted(Key{
6696 .func_type = extraFuncType(ip, func_type_extra_index),
6697 }, adapter).found_existing);
6698 return @enumFromInt(ip.items.len - 4);
6699 }
6700
6701 // An existing function type was found; undo the additions to our two arrays.
6702 ip.items.len -= 4;
6703 ip.extra.items.len = prev_extra_len;
6704 return @enumFromInt(gop.index);
7511 var func_gop = try ip.getOrPutKey(gpa, tid, .{
7512 .func = extraFuncDecl(tid, extra.list.*, func_decl_extra_index),
7513 });
7514 defer func_gop.deinit();
7515 if (func_gop == .existing) {
7516 // An existing function type was found; undo the additions to our two arrays.
7517 items.mutate.len -= 4;
7518 extra.mutate.len = prev_extra_len;
7519 return func_gop.existing;
7520 }
7521 var error_union_type_gop = try ip.getOrPutKey(gpa, tid, .{ .error_union_type = .{
7522 .error_set_type = error_set_type,
7523 .payload_type = key.bare_return_type,
7524 } });
7525 defer error_union_type_gop.deinit();
7526 var error_set_type_gop = try ip.getOrPutKey(gpa, tid, .{
7527 .inferred_error_set_type = func_index,
7528 });
7529 defer error_set_type_gop.deinit();
7530 var func_ty_gop = try ip.getOrPutKey(gpa, tid, .{
7531 .func_type = extraFuncType(tid, extra.list.*, func_type_extra_index),
7532 });
7533 defer func_ty_gop.deinit();
7534 assert(func_gop.putAt(3) == func_index);
7535 assert(error_union_type_gop.putAt(2) == error_union_type);
7536 assert(error_set_type_gop.putAt(1) == error_set_type);
7537 assert(func_ty_gop.putAt(0) == func_ty);
7538 return func_index;
67057539}
67067540
67077541pub fn getErrorSetType(
67087542 ip: *InternPool,
67097543 gpa: Allocator,
7544 tid: Zcu.PerThread.Id,
67107545 names: []const NullTerminatedString,
67117546) Allocator.Error!Index {
67127547 assert(std.sort.isSorted(NullTerminatedString, names, {}, NullTerminatedString.indexLessThan));
67137548
7549 const local = ip.getLocal(tid);
7550 const items = local.getMutableItems(gpa);
7551 const extra = local.getMutableExtra(gpa);
7552 try extra.ensureUnusedCapacity(@typeInfo(Tag.ErrorSet).Struct.fields.len + names.len);
7553
67147554 // The strategy here is to add the type unconditionally, then to ask if it
67157555 // already exists, and if so, revert the lengths of the mutated arrays.
67167556 // This is similar to what `getOrPutTrailingString` does.
6717 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(Tag.ErrorSet).Struct.fields.len + names.len);
6718
6719 const prev_extra_len = ip.extra.items.len;
6720 errdefer ip.extra.items.len = prev_extra_len;
7557 const prev_extra_len = extra.mutate.len;
7558 errdefer extra.mutate.len = prev_extra_len;
67217559
67227560 const predicted_names_map: MapIndex = @enumFromInt(ip.maps.items.len);
67237561
6724 const error_set_extra_index = ip.addExtraAssumeCapacity(Tag.ErrorSet{
7562 const error_set_extra_index = addExtraAssumeCapacity(extra, Tag.ErrorSet{
67257563 .names_len = @intCast(names.len),
67267564 .names_map = predicted_names_map,
67277565 });
6728 ip.extra.appendSliceAssumeCapacity(@ptrCast(names));
6729
6730 const adapter: KeyAdapter = .{ .intern_pool = ip };
6731 const gop = try ip.map.getOrPutAdapted(gpa, Key{
6732 .error_set_type = extraErrorSet(ip, error_set_extra_index),
6733 }, adapter);
6734 errdefer _ = ip.map.pop();
7566 extra.appendSliceAssumeCapacity(.{@ptrCast(names)});
7567 errdefer extra.mutate.len = prev_extra_len;
67357568
6736 if (gop.found_existing) {
6737 ip.extra.items.len = prev_extra_len;
6738 return @enumFromInt(gop.index);
7569 var gop = try ip.getOrPutKey(gpa, tid, .{
7570 .error_set_type = extraErrorSet(tid, extra.list.*, error_set_extra_index),
7571 });
7572 defer gop.deinit();
7573 if (gop == .existing) {
7574 extra.mutate.len = prev_extra_len;
7575 return gop.existing;
67397576 }
67407577
6741 try ip.items.append(gpa, .{
7578 try items.append(.{
67427579 .tag = .type_error_set,
67437580 .data = error_set_extra_index,
67447581 });
6745 errdefer ip.items.len -= 1;
7582 errdefer items.mutate.len -= 1;
67467583
67477584 const names_map = try ip.addMap(gpa, names.len);
67487585 assert(names_map == predicted_names_map);
......@@ -6750,7 +7587,7 @@ pub fn getErrorSetType(
67507587
67517588 addStringsToMap(ip, names_map, names);
67527589
6753 return @enumFromInt(ip.items.len - 1);
7590 return gop.put();
67547591}
67557592
67567593pub const GetFuncInstanceKey = struct {
......@@ -6770,11 +7607,16 @@ pub const GetFuncInstanceKey = struct {
67707607 inferred_error_set: bool,
67717608};
67727609
6773pub fn getFuncInstance(ip: *InternPool, gpa: Allocator, arg: GetFuncInstanceKey) Allocator.Error!Index {
7610pub fn getFuncInstance(
7611 ip: *InternPool,
7612 gpa: Allocator,
7613 tid: Zcu.PerThread.Id,
7614 arg: GetFuncInstanceKey,
7615) Allocator.Error!Index {
67747616 if (arg.inferred_error_set)
6775 return getFuncInstanceIes(ip, gpa, arg);
7617 return getFuncInstanceIes(ip, gpa, tid, arg);
67767618
6777 const func_ty = try ip.getFuncType(gpa, .{
7619 const func_ty = try ip.getFuncType(gpa, tid, .{
67787620 .param_types = arg.param_types,
67797621 .return_type = arg.bare_return_type,
67807622 .noalias_bits = arg.noalias_bits,
......@@ -6782,16 +7624,20 @@ pub fn getFuncInstance(ip: *InternPool, gpa: Allocator, arg: GetFuncInstanceKey)
67827624 .is_noinline = arg.is_noinline,
67837625 });
67847626
7627 const local = ip.getLocal(tid);
7628 const items = local.getMutableItems(gpa);
7629 const extra = local.getMutableExtra(gpa);
7630 try extra.ensureUnusedCapacity(@typeInfo(Tag.FuncInstance).Struct.fields.len +
7631 arg.comptime_args.len);
7632
67857633 const generic_owner = unwrapCoercedFunc(ip, arg.generic_owner);
67867634
67877635 assert(arg.comptime_args.len == ip.funcTypeParamsLen(ip.typeOf(generic_owner)));
67887636
6789 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(Tag.FuncInstance).Struct.fields.len +
6790 arg.comptime_args.len);
6791 const prev_extra_len = ip.extra.items.len;
6792 errdefer ip.extra.items.len = prev_extra_len;
7637 const prev_extra_len = extra.mutate.len;
7638 errdefer extra.mutate.len = prev_extra_len;
67937639
6794 const func_extra_index = ip.addExtraAssumeCapacity(Tag.FuncInstance{
7640 const func_extra_index = addExtraAssumeCapacity(extra, Tag.FuncInstance{
67957641 .analysis = .{
67967642 .state = if (arg.cc == .Inline) .inline_only else .none,
67977643 .is_cold = false,
......@@ -6807,35 +7653,35 @@ pub fn getFuncInstance(ip: *InternPool, gpa: Allocator, arg: GetFuncInstanceKey)
68077653 .branch_quota = 0,
68087654 .generic_owner = generic_owner,
68097655 });
6810 ip.extra.appendSliceAssumeCapacity(@ptrCast(arg.comptime_args));
6811
6812 const gop = try ip.map.getOrPutAdapted(gpa, Key{
6813 .func = extraFuncInstance(ip, func_extra_index),
6814 }, KeyAdapter{ .intern_pool = ip });
6815 errdefer _ = ip.map.pop();
7656 extra.appendSliceAssumeCapacity(.{@ptrCast(arg.comptime_args)});
68167657
6817 if (gop.found_existing) {
6818 ip.extra.items.len = prev_extra_len;
6819 return @enumFromInt(gop.index);
7658 var gop = try ip.getOrPutKey(gpa, tid, .{
7659 .func = ip.extraFuncInstance(tid, extra.list.*, func_extra_index),
7660 });
7661 defer gop.deinit();
7662 if (gop == .existing) {
7663 extra.mutate.len = prev_extra_len;
7664 return gop.existing;
68207665 }
68217666
6822 const func_index: Index = @enumFromInt(ip.items.len);
6823
6824 try ip.items.append(gpa, .{
7667 const func_index = Index.Unwrapped.wrap(.{ .tid = tid, .index = items.mutate.len }, ip);
7668 try items.append(.{
68257669 .tag = .func_instance,
68267670 .data = func_extra_index,
68277671 });
6828 errdefer ip.items.len -= 1;
6829
6830 return finishFuncInstance(
7672 errdefer items.mutate.len -= 1;
7673 try finishFuncInstance(
68317674 ip,
68327675 gpa,
7676 tid,
7677 extra,
68337678 generic_owner,
68347679 func_index,
68357680 func_extra_index,
68367681 arg.alignment,
68377682 arg.section,
68387683 );
7684 return gop.put();
68397685}
68407686
68417687/// This function exists separately than `getFuncInstance` because it needs to
......@@ -6844,6 +7690,7 @@ pub fn getFuncInstance(ip: *InternPool, gpa: Allocator, arg: GetFuncInstanceKey)
68447690pub fn getFuncInstanceIes(
68457691 ip: *InternPool,
68467692 gpa: Allocator,
7693 tid: Zcu.PerThread.Id,
68477694 arg: GetFuncInstanceKey,
68487695) Allocator.Error!Index {
68497696 // Validate input parameters.
......@@ -6851,30 +7698,45 @@ pub fn getFuncInstanceIes(
68517698 assert(arg.bare_return_type != .none);
68527699 for (arg.param_types) |param_type| assert(param_type != .none);
68537700
7701 const local = ip.getLocal(tid);
7702 const items = local.getMutableItems(gpa);
7703 const extra = local.getMutableExtra(gpa);
7704 try items.ensureUnusedCapacity(4);
7705
68547706 const generic_owner = unwrapCoercedFunc(ip, arg.generic_owner);
68557707
68567708 // The strategy here is to add the function decl unconditionally, then to
68577709 // ask if it already exists, and if so, revert the lengths of the mutated
68587710 // arrays. This is similar to what `getOrPutTrailingString` does.
6859 const prev_extra_len = ip.extra.items.len;
7711 const prev_extra_len = extra.mutate.len;
68607712 const params_len: u32 = @intCast(arg.param_types.len);
68617713
6862 try ip.map.ensureUnusedCapacity(gpa, 4);
6863 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(Tag.FuncInstance).Struct.fields.len +
7714 try extra.ensureUnusedCapacity(@typeInfo(Tag.FuncInstance).Struct.fields.len +
68647715 1 + // inferred_error_set
68657716 arg.comptime_args.len +
68667717 @typeInfo(Tag.ErrorUnionType).Struct.fields.len +
68677718 @typeInfo(Tag.TypeFunction).Struct.fields.len +
68687719 @intFromBool(arg.noalias_bits != 0) +
68697720 params_len);
6870 try ip.items.ensureUnusedCapacity(gpa, 4);
6871
6872 const func_index: Index = @enumFromInt(ip.items.len);
6873 const error_union_type: Index = @enumFromInt(ip.items.len + 1);
6874 const error_set_type: Index = @enumFromInt(ip.items.len + 2);
6875 const func_ty: Index = @enumFromInt(ip.items.len + 3);
68767721
6877 const func_extra_index = ip.addExtraAssumeCapacity(Tag.FuncInstance{
7722 const func_index = Index.Unwrapped.wrap(.{
7723 .tid = tid,
7724 .index = items.mutate.len + 0,
7725 }, ip);
7726 const error_union_type = Index.Unwrapped.wrap(.{
7727 .tid = tid,
7728 .index = items.mutate.len + 1,
7729 }, ip);
7730 const error_set_type = Index.Unwrapped.wrap(.{
7731 .tid = tid,
7732 .index = items.mutate.len + 2,
7733 }, ip);
7734 const func_ty = Index.Unwrapped.wrap(.{
7735 .tid = tid,
7736 .index = items.mutate.len + 3,
7737 }, ip);
7738
7739 const func_extra_index = addExtraAssumeCapacity(extra, Tag.FuncInstance{
68787740 .analysis = .{
68797741 .state = if (arg.cc == .Inline) .inline_only else .none,
68807742 .is_cold = false,
......@@ -6890,10 +7752,10 @@ pub fn getFuncInstanceIes(
68907752 .branch_quota = 0,
68917753 .generic_owner = generic_owner,
68927754 });
6893 ip.extra.appendAssumeCapacity(@intFromEnum(Index.none)); // resolved error set
6894 ip.extra.appendSliceAssumeCapacity(@ptrCast(arg.comptime_args));
7755 extra.appendAssumeCapacity(.{@intFromEnum(Index.none)}); // resolved error set
7756 extra.appendSliceAssumeCapacity(.{@ptrCast(arg.comptime_args)});
68957757
6896 const func_type_extra_index = ip.addExtraAssumeCapacity(Tag.TypeFunction{
7758 const func_type_extra_index = addExtraAssumeCapacity(extra, Tag.TypeFunction{
68977759 .params_len = params_len,
68987760 .return_type = error_union_type,
68997761 .flags = .{
......@@ -6909,73 +7771,83 @@ pub fn getFuncInstanceIes(
69097771 },
69107772 });
69117773 // no comptime_bits because has_comptime_bits is false
6912 if (arg.noalias_bits != 0) ip.extra.appendAssumeCapacity(arg.noalias_bits);
6913 ip.extra.appendSliceAssumeCapacity(@ptrCast(arg.param_types));
7774 if (arg.noalias_bits != 0) extra.appendAssumeCapacity(.{arg.noalias_bits});
7775 extra.appendSliceAssumeCapacity(.{@ptrCast(arg.param_types)});
69147776
6915 // TODO: add appendSliceAssumeCapacity to MultiArrayList.
6916 ip.items.appendAssumeCapacity(.{
6917 .tag = .func_instance,
6918 .data = func_extra_index,
6919 });
6920 ip.items.appendAssumeCapacity(.{
6921 .tag = .type_error_union,
6922 .data = ip.addExtraAssumeCapacity(Tag.ErrorUnionType{
6923 .error_set_type = error_set_type,
6924 .payload_type = arg.bare_return_type,
6925 }),
6926 });
6927 ip.items.appendAssumeCapacity(.{
6928 .tag = .type_inferred_error_set,
6929 .data = @intFromEnum(func_index),
6930 });
6931 ip.items.appendAssumeCapacity(.{
6932 .tag = .type_function,
6933 .data = func_type_extra_index,
7777 items.appendSliceAssumeCapacity(.{
7778 .tag = &.{
7779 .func_instance,
7780 .type_error_union,
7781 .type_inferred_error_set,
7782 .type_function,
7783 },
7784 .data = &.{
7785 func_extra_index,
7786 addExtraAssumeCapacity(extra, Tag.ErrorUnionType{
7787 .error_set_type = error_set_type,
7788 .payload_type = arg.bare_return_type,
7789 }),
7790 @intFromEnum(func_index),
7791 func_type_extra_index,
7792 },
69347793 });
7794 errdefer {
7795 items.mutate.len -= 4;
7796 extra.mutate.len = prev_extra_len;
7797 }
69357798
6936 const adapter: KeyAdapter = .{ .intern_pool = ip };
6937 const gop = ip.map.getOrPutAssumeCapacityAdapted(Key{
6938 .func = extraFuncInstance(ip, func_extra_index),
6939 }, adapter);
6940 if (gop.found_existing) {
7799 var func_gop = try ip.getOrPutKey(gpa, tid, .{
7800 .func = ip.extraFuncInstance(tid, extra.list.*, func_extra_index),
7801 });
7802 defer func_gop.deinit();
7803 if (func_gop == .existing) {
69417804 // Hot path: undo the additions to our two arrays.
6942 ip.items.len -= 4;
6943 ip.extra.items.len = prev_extra_len;
6944 return @enumFromInt(gop.index);
7805 items.mutate.len -= 4;
7806 extra.mutate.len = prev_extra_len;
7807 return func_gop.existing;
69457808 }
6946
6947 // Synchronize the map with items.
6948 assert(!ip.map.getOrPutAssumeCapacityAdapted(Key{ .error_union_type = .{
7809 var error_union_type_gop = try ip.getOrPutKey(gpa, tid, .{ .error_union_type = .{
69497810 .error_set_type = error_set_type,
69507811 .payload_type = arg.bare_return_type,
6951 } }, adapter).found_existing);
6952 assert(!ip.map.getOrPutAssumeCapacityAdapted(Key{
7812 } });
7813 defer error_union_type_gop.deinit();
7814 var error_set_type_gop = try ip.getOrPutKey(gpa, tid, .{
69537815 .inferred_error_set_type = func_index,
6954 }, adapter).found_existing);
6955 assert(!ip.map.getOrPutAssumeCapacityAdapted(Key{
6956 .func_type = extraFuncType(ip, func_type_extra_index),
6957 }, adapter).found_existing);
6958
6959 return finishFuncInstance(
7816 });
7817 defer error_set_type_gop.deinit();
7818 var func_ty_gop = try ip.getOrPutKey(gpa, tid, .{
7819 .func_type = extraFuncType(tid, extra.list.*, func_type_extra_index),
7820 });
7821 defer func_ty_gop.deinit();
7822 try finishFuncInstance(
69607823 ip,
69617824 gpa,
7825 tid,
7826 extra,
69627827 generic_owner,
69637828 func_index,
69647829 func_extra_index,
69657830 arg.alignment,
69667831 arg.section,
69677832 );
7833 assert(func_gop.putAt(3) == func_index);
7834 assert(error_union_type_gop.putAt(2) == error_union_type);
7835 assert(error_set_type_gop.putAt(1) == error_set_type);
7836 assert(func_ty_gop.putAt(0) == func_ty);
7837 return func_index;
69687838}
69697839
69707840fn finishFuncInstance(
69717841 ip: *InternPool,
69727842 gpa: Allocator,
7843 tid: Zcu.PerThread.Id,
7844 extra: Local.Extra.Mutable,
69737845 generic_owner: Index,
69747846 func_index: Index,
69757847 func_extra_index: u32,
69767848 alignment: Alignment,
69777849 section: OptionalNullTerminatedString,
6978) Allocator.Error!Index {
7850) Allocator.Error!void {
69797851 const fn_owner_decl = ip.declPtr(ip.funcDeclOwner(generic_owner));
69807852 const decl_index = try ip.createDecl(gpa, .{
69817853 .name = undefined,
......@@ -6995,17 +7867,15 @@ fn finishFuncInstance(
69957867 errdefer ip.destroyDecl(gpa, decl_index);
69967868
69977869 // Populate the owner_decl field which was left undefined until now.
6998 ip.extra.items[
7870 extra.view().items(.@"0")[
69997871 func_extra_index + std.meta.fieldIndex(Tag.FuncInstance, "owner_decl").?
70007872 ] = @intFromEnum(decl_index);
70017873
70027874 // TODO: improve this name
70037875 const decl = ip.declPtr(decl_index);
7004 decl.name = try ip.getOrPutStringFmt(gpa, "{}__anon_{d}", .{
7876 decl.name = try ip.getOrPutStringFmt(gpa, tid, "{}__anon_{d}", .{
70057877 fn_owner_decl.name.fmt(ip), @intFromEnum(decl_index),
70067878 }, .no_embedded_nulls);
7007
7008 return func_index;
70097879}
70107880
70117881pub const EnumTypeInit = struct {
......@@ -7026,6 +7896,7 @@ pub const EnumTypeInit = struct {
70267896};
70277897
70287898pub const WipEnumType = struct {
7899 tid: Zcu.PerThread.Id,
70297900 index: Index,
70307901 tag_ty_index: u32,
70317902 decl_index: u32,
......@@ -7041,9 +7912,11 @@ pub const WipEnumType = struct {
70417912 decl: DeclIndex,
70427913 namespace: OptionalNamespaceIndex,
70437914 ) void {
7044 ip.extra.items[wip.decl_index] = @intFromEnum(decl);
7915 const extra = ip.getLocalShared(wip.tid).extra.acquire();
7916 const extra_items = extra.view().items(.@"0");
7917 extra_items[wip.decl_index] = @intFromEnum(decl);
70457918 if (wip.namespace_index) |i| {
7046 ip.extra.items[i] = @intFromEnum(namespace.unwrap().?);
7919 extra_items[i] = @intFromEnum(namespace.unwrap().?);
70477920 } else {
70487921 assert(namespace == .none);
70497922 }
......@@ -7051,7 +7924,8 @@ pub const WipEnumType = struct {
70517924
70527925 pub fn setTagTy(wip: WipEnumType, ip: *InternPool, tag_ty: Index) void {
70537926 assert(ip.isIntegerType(tag_ty));
7054 ip.extra.items[wip.tag_ty_index] = @intFromEnum(tag_ty);
7927 const extra = ip.getLocalShared(wip.tid).extra.acquire();
7928 extra.view().items(.@"0")[wip.tag_ty_index] = @intFromEnum(tag_ty);
70557929 }
70567930
70577931 pub const FieldConflict = struct {
......@@ -7063,28 +7937,31 @@ pub const WipEnumType = struct {
70637937 /// If the enum is automatially numbered, `value` must be `.none`.
70647938 /// Otherwise, the type of `value` must be the integer tag type of the enum.
70657939 pub fn nextField(wip: WipEnumType, ip: *InternPool, name: NullTerminatedString, value: Index) ?FieldConflict {
7066 if (ip.addFieldName(wip.names_map, wip.names_start, name)) |conflict| {
7940 const unwrapped_index = wip.index.unwrap(ip);
7941 const extra_list = ip.getLocalShared(unwrapped_index.tid).extra.acquire();
7942 const extra_items = extra_list.view().items(.@"0");
7943 if (ip.addFieldName(extra_list, wip.names_map, wip.names_start, name)) |conflict| {
70677944 return .{ .kind = .name, .prev_field_idx = conflict };
70687945 }
70697946 if (value == .none) {
70707947 assert(wip.values_map == .none);
70717948 return null;
70727949 }
7073 assert(ip.typeOf(value) == @as(Index, @enumFromInt(ip.extra.items[wip.tag_ty_index])));
7950 assert(ip.typeOf(value) == @as(Index, @enumFromInt(extra_items[wip.tag_ty_index])));
70747951 const map = &ip.maps.items[@intFromEnum(wip.values_map.unwrap().?)];
70757952 const field_index = map.count();
7076 const indexes = ip.extra.items[wip.values_start..][0..field_index];
7953 const indexes = extra_items[wip.values_start..][0..field_index];
70777954 const adapter: Index.Adapter = .{ .indexes = @ptrCast(indexes) };
70787955 const gop = map.getOrPutAssumeCapacityAdapted(value, adapter);
70797956 if (gop.found_existing) {
70807957 return .{ .kind = .value, .prev_field_idx = @intCast(gop.index) };
70817958 }
7082 ip.extra.items[wip.values_start + field_index] = @intFromEnum(value);
7959 extra_items[wip.values_start + field_index] = @intFromEnum(value);
70837960 return null;
70847961 }
70857962
7086 pub fn cancel(wip: WipEnumType, ip: *InternPool) void {
7087 ip.remove(wip.index);
7963 pub fn cancel(wip: WipEnumType, ip: *InternPool, tid: Zcu.PerThread.Id) void {
7964 ip.remove(tid, wip.index);
70887965 }
70897966
70907967 pub const Result = union(enum) {
......@@ -7096,10 +7973,10 @@ pub const WipEnumType = struct {
70967973pub fn getEnumType(
70977974 ip: *InternPool,
70987975 gpa: Allocator,
7976 tid: Zcu.PerThread.Id,
70997977 ini: EnumTypeInit,
71007978) Allocator.Error!WipEnumType.Result {
7101 const adapter: KeyAdapter = .{ .intern_pool = ip };
7102 const gop = try ip.map.getOrPutAdapted(gpa, Key{ .enum_type = switch (ini.key) {
7979 var gop = try ip.getOrPutKey(gpa, tid, .{ .enum_type = switch (ini.key) {
71037980 .declared => |d| .{ .declared = .{
71047981 .zir_index = d.zir_index,
71057982 .captures = .{ .external = d.captures },
......@@ -7108,12 +7985,14 @@ pub fn getEnumType(
71087985 .zir_index = r.zir_index,
71097986 .type_hash = r.type_hash,
71107987 } },
7111 } }, adapter);
7112 if (gop.found_existing) return .{ .existing = @enumFromInt(gop.index) };
7113 assert(gop.index == ip.items.len);
7114 errdefer _ = ip.map.pop();
7988 } });
7989 defer gop.deinit();
7990 if (gop == .existing) return .{ .existing = gop.existing };
71157991
7116 try ip.items.ensureUnusedCapacity(gpa, 1);
7992 const local = ip.getLocal(tid);
7993 const items = local.getMutableItems(gpa);
7994 try items.ensureUnusedCapacity(1);
7995 const extra = local.getMutableExtra(gpa);
71177996
71187997 const names_map = try ip.addMap(gpa, ini.fields_len);
71197998 errdefer _ = ip.maps.pop();
......@@ -7121,7 +8000,7 @@ pub fn getEnumType(
71218000 switch (ini.tag_mode) {
71228001 .auto => {
71238002 assert(!ini.has_values);
7124 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(EnumAuto).Struct.fields.len +
8003 try extra.ensureUnusedCapacity(@typeInfo(EnumAuto).Struct.fields.len +
71258004 // TODO: fmt bug
71268005 // zig fmt: off
71278006 switch (ini.key) {
......@@ -7131,7 +8010,7 @@ pub fn getEnumType(
71318010 // zig fmt: on
71328011 ini.fields_len); // field types
71338012
7134 const extra_index = ip.addExtraAssumeCapacity(EnumAuto{
8013 const extra_index = addExtraAssumeCapacity(extra, EnumAuto{
71358014 .decl = undefined, // set by `prepare`
71368015 .captures_len = switch (ini.key) {
71378016 .declared => |d| @intCast(d.captures.len),
......@@ -7145,18 +8024,19 @@ pub fn getEnumType(
71458024 inline else => |x| x.zir_index,
71468025 }.toOptional(),
71478026 });
7148 ip.items.appendAssumeCapacity(.{
8027 items.appendAssumeCapacity(.{
71498028 .tag = .type_enum_auto,
71508029 .data = extra_index,
71518030 });
71528031 switch (ini.key) {
7153 .declared => |d| ip.extra.appendSliceAssumeCapacity(@ptrCast(d.captures)),
7154 .reified => |r| _ = ip.addExtraAssumeCapacity(PackedU64.init(r.type_hash)),
8032 .declared => |d| extra.appendSliceAssumeCapacity(.{@ptrCast(d.captures)}),
8033 .reified => |r| _ = addExtraAssumeCapacity(extra, PackedU64.init(r.type_hash)),
71558034 }
7156 const names_start = ip.extra.items.len;
7157 ip.extra.appendNTimesAssumeCapacity(undefined, ini.fields_len);
8035 const names_start = extra.mutate.len;
8036 _ = extra.addManyAsSliceAssumeCapacity(ini.fields_len);
71588037 return .{ .wip = .{
7159 .index = @enumFromInt(gop.index),
8038 .tid = tid,
8039 .index = gop.put(),
71608040 .tag_ty_index = extra_index + std.meta.fieldIndex(EnumAuto, "int_tag_type").?,
71618041 .decl_index = extra_index + std.meta.fieldIndex(EnumAuto, "decl").?,
71628042 .namespace_index = if (ini.has_namespace) extra_index + std.meta.fieldIndex(EnumAuto, "namespace").? else null,
......@@ -7172,10 +8052,10 @@ pub fn getEnumType(
71728052 break :m values_map.toOptional();
71738053 };
71748054 errdefer if (ini.has_values) {
7175 _ = ip.map.pop();
8055 _ = ip.maps.pop();
71768056 };
71778057
7178 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(EnumExplicit).Struct.fields.len +
8058 try extra.ensureUnusedCapacity(@typeInfo(EnumExplicit).Struct.fields.len +
71798059 // TODO: fmt bug
71808060 // zig fmt: off
71818061 switch (ini.key) {
......@@ -7186,7 +8066,7 @@ pub fn getEnumType(
71868066 ini.fields_len + // field types
71878067 ini.fields_len * @intFromBool(ini.has_values)); // field values
71888068
7189 const extra_index = ip.addExtraAssumeCapacity(EnumExplicit{
8069 const extra_index = addExtraAssumeCapacity(extra, EnumExplicit{
71908070 .decl = undefined, // set by `prepare`
71918071 .captures_len = switch (ini.key) {
71928072 .declared => |d| @intCast(d.captures.len),
......@@ -7201,7 +8081,7 @@ pub fn getEnumType(
72018081 inline else => |x| x.zir_index,
72028082 }.toOptional(),
72038083 });
7204 ip.items.appendAssumeCapacity(.{
8084 items.appendAssumeCapacity(.{
72058085 .tag = switch (ini.tag_mode) {
72068086 .auto => unreachable,
72078087 .explicit => .type_enum_explicit,
......@@ -7210,17 +8090,18 @@ pub fn getEnumType(
72108090 .data = extra_index,
72118091 });
72128092 switch (ini.key) {
7213 .declared => |d| ip.extra.appendSliceAssumeCapacity(@ptrCast(d.captures)),
7214 .reified => |r| _ = ip.addExtraAssumeCapacity(PackedU64.init(r.type_hash)),
8093 .declared => |d| extra.appendSliceAssumeCapacity(.{@ptrCast(d.captures)}),
8094 .reified => |r| _ = addExtraAssumeCapacity(extra, PackedU64.init(r.type_hash)),
72158095 }
7216 const names_start = ip.extra.items.len;
7217 ip.extra.appendNTimesAssumeCapacity(undefined, ini.fields_len);
7218 const values_start = ip.extra.items.len;
8096 const names_start = extra.mutate.len;
8097 _ = extra.addManyAsSliceAssumeCapacity(ini.fields_len);
8098 const values_start = extra.mutate.len;
72198099 if (ini.has_values) {
7220 ip.extra.appendNTimesAssumeCapacity(undefined, ini.fields_len);
8100 _ = extra.addManyAsSliceAssumeCapacity(ini.fields_len);
72218101 }
72228102 return .{ .wip = .{
7223 .index = @enumFromInt(gop.index),
8103 .tid = tid,
8104 .index = gop.put(),
72248105 .tag_ty_index = extra_index + std.meta.fieldIndex(EnumAuto, "int_tag_type").?,
72258106 .decl_index = extra_index + std.meta.fieldIndex(EnumAuto, "decl").?,
72268107 .namespace_index = if (ini.has_namespace) extra_index + std.meta.fieldIndex(EnumAuto, "namespace").? else null,
......@@ -7245,13 +8126,20 @@ const GeneratedTagEnumTypeInit = struct {
72458126/// Creates an enum type which was automatically-generated as the tag type of a
72468127/// `union` with no explicit tag type. Since this is only called once per union
72478128/// type, it asserts that no matching type yet exists.
7248pub fn getGeneratedTagEnumType(ip: *InternPool, gpa: Allocator, ini: GeneratedTagEnumTypeInit) Allocator.Error!Index {
8129pub fn getGeneratedTagEnumType(
8130 ip: *InternPool,
8131 gpa: Allocator,
8132 tid: Zcu.PerThread.Id,
8133 ini: GeneratedTagEnumTypeInit,
8134) Allocator.Error!Index {
72498135 assert(ip.isUnion(ini.owner_union_ty));
72508136 assert(ip.isIntegerType(ini.tag_ty));
72518137 for (ini.values) |val| assert(ip.typeOf(val) == ini.tag_ty);
72528138
7253 try ip.map.ensureUnusedCapacity(gpa, 1);
7254 try ip.items.ensureUnusedCapacity(gpa, 1);
8139 const local = ip.getLocal(tid);
8140 const items = local.getMutableItems(gpa);
8141 try items.ensureUnusedCapacity(1);
8142 const extra = local.getMutableExtra(gpa);
72558143
72568144 const names_map = try ip.addMap(gpa, ini.names.len);
72578145 errdefer _ = ip.maps.pop();
......@@ -7259,14 +8147,15 @@ pub fn getGeneratedTagEnumType(ip: *InternPool, gpa: Allocator, ini: GeneratedTa
72598147
72608148 const fields_len: u32 = @intCast(ini.names.len);
72618149
8150 const prev_extra_len = extra.mutate.len;
72628151 switch (ini.tag_mode) {
72638152 .auto => {
7264 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(EnumAuto).Struct.fields.len +
8153 try extra.ensureUnusedCapacity(@typeInfo(EnumAuto).Struct.fields.len +
72658154 1 + // owner_union
72668155 fields_len); // field names
7267 ip.items.appendAssumeCapacity(.{
8156 items.appendAssumeCapacity(.{
72688157 .tag = .type_enum_auto,
7269 .data = ip.addExtraAssumeCapacity(EnumAuto{
8158 .data = addExtraAssumeCapacity(extra, EnumAuto{
72708159 .decl = ini.decl,
72718160 .captures_len = 0,
72728161 .namespace = .none,
......@@ -7276,11 +8165,11 @@ pub fn getGeneratedTagEnumType(ip: *InternPool, gpa: Allocator, ini: GeneratedTa
72768165 .zir_index = .none,
72778166 }),
72788167 });
7279 ip.extra.appendAssumeCapacity(@intFromEnum(ini.owner_union_ty));
7280 ip.extra.appendSliceAssumeCapacity(@ptrCast(ini.names));
8168 extra.appendAssumeCapacity(.{@intFromEnum(ini.owner_union_ty)});
8169 extra.appendSliceAssumeCapacity(.{@ptrCast(ini.names)});
72818170 },
72828171 .explicit, .nonexhaustive => {
7283 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(EnumExplicit).Struct.fields.len +
8172 try extra.ensureUnusedCapacity(@typeInfo(EnumExplicit).Struct.fields.len +
72848173 1 + // owner_union
72858174 fields_len + // field names
72868175 ini.values.len); // field values
......@@ -7293,13 +8182,13 @@ pub fn getGeneratedTagEnumType(ip: *InternPool, gpa: Allocator, ini: GeneratedTa
72938182 // We don't clean up the values map on error!
72948183 errdefer @compileError("error path leaks values_map");
72958184
7296 ip.items.appendAssumeCapacity(.{
8185 items.appendAssumeCapacity(.{
72978186 .tag = switch (ini.tag_mode) {
72988187 .explicit => .type_enum_explicit,
72998188 .nonexhaustive => .type_enum_nonexhaustive,
73008189 .auto => unreachable,
73018190 },
7302 .data = ip.addExtraAssumeCapacity(EnumExplicit{
8191 .data = addExtraAssumeCapacity(extra, EnumExplicit{
73038192 .decl = ini.decl,
73048193 .captures_len = 0,
73058194 .namespace = .none,
......@@ -7310,22 +8199,22 @@ pub fn getGeneratedTagEnumType(ip: *InternPool, gpa: Allocator, ini: GeneratedTa
73108199 .zir_index = .none,
73118200 }),
73128201 });
7313 ip.extra.appendAssumeCapacity(@intFromEnum(ini.owner_union_ty));
7314 ip.extra.appendSliceAssumeCapacity(@ptrCast(ini.names));
7315 ip.extra.appendSliceAssumeCapacity(@ptrCast(ini.values));
8202 extra.appendAssumeCapacity(.{@intFromEnum(ini.owner_union_ty)});
8203 extra.appendSliceAssumeCapacity(.{@ptrCast(ini.names)});
8204 extra.appendSliceAssumeCapacity(.{@ptrCast(ini.values)});
73168205 },
73178206 }
7318 // Same as above
7319 errdefer @compileError("error path leaks values_map and extra data");
8207 errdefer extra.mutate.len = prev_extra_len;
8208 errdefer switch (ini.tag_mode) {
8209 .auto => {},
8210 .explicit, .nonexhaustive => _ = if (ini.values.len != 0) ip.maps.pop(),
8211 };
73208212
7321 // Capacity for this was ensured earlier
7322 const adapter: KeyAdapter = .{ .intern_pool = ip };
7323 const gop = ip.map.getOrPutAssumeCapacityAdapted(Key{ .enum_type = .{
8213 var gop = try ip.getOrPutKey(gpa, tid, .{ .enum_type = .{
73248214 .generated_tag = .{ .union_type = ini.owner_union_ty },
7325 } }, adapter);
7326 assert(!gop.found_existing);
7327 assert(gop.index == ip.items.len - 1);
7328 return @enumFromInt(gop.index);
8215 } });
8216 defer gop.deinit();
8217 return gop.put();
73298218}
73308219
73318220pub const OpaqueTypeInit = struct {
......@@ -7342,9 +8231,13 @@ pub const OpaqueTypeInit = struct {
73428231 },
73438232};
73448233
7345pub fn getOpaqueType(ip: *InternPool, gpa: Allocator, ini: OpaqueTypeInit) Allocator.Error!WipNamespaceType.Result {
7346 const adapter: KeyAdapter = .{ .intern_pool = ip };
7347 const gop = try ip.map.getOrPutAdapted(gpa, Key{ .opaque_type = switch (ini.key) {
8234pub fn getOpaqueType(
8235 ip: *InternPool,
8236 gpa: Allocator,
8237 tid: Zcu.PerThread.Id,
8238 ini: OpaqueTypeInit,
8239) Allocator.Error!WipNamespaceType.Result {
8240 var gop = try ip.getOrPutKey(gpa, tid, .{ .opaque_type = switch (ini.key) {
73488241 .declared => |d| .{ .declared = .{
73498242 .zir_index = d.zir_index,
73508243 .captures = .{ .external = d.captures },
......@@ -7353,15 +8246,20 @@ pub fn getOpaqueType(ip: *InternPool, gpa: Allocator, ini: OpaqueTypeInit) Alloc
73538246 .zir_index = r.zir_index,
73548247 .type_hash = 0,
73558248 } },
7356 } }, adapter);
7357 if (gop.found_existing) return .{ .existing = @enumFromInt(gop.index) };
7358 errdefer _ = ip.map.pop();
7359 try ip.items.ensureUnusedCapacity(gpa, 1);
7360 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(Tag.TypeOpaque).Struct.fields.len + switch (ini.key) {
8249 } });
8250 defer gop.deinit();
8251 if (gop == .existing) return .{ .existing = gop.existing };
8252
8253 const local = ip.getLocal(tid);
8254 const items = local.getMutableItems(gpa);
8255 const extra = local.getMutableExtra(gpa);
8256 try items.ensureUnusedCapacity(1);
8257
8258 try extra.ensureUnusedCapacity(@typeInfo(Tag.TypeOpaque).Struct.fields.len + switch (ini.key) {
73618259 .declared => |d| d.captures.len,
73628260 .reified => 0,
73638261 });
7364 const extra_index = ip.addExtraAssumeCapacity(Tag.TypeOpaque{
8262 const extra_index = addExtraAssumeCapacity(extra, Tag.TypeOpaque{
73658263 .decl = undefined, // set by `finish`
73668264 .namespace = .none,
73678265 .zir_index = switch (ini.key) {
......@@ -7372,16 +8270,17 @@ pub fn getOpaqueType(ip: *InternPool, gpa: Allocator, ini: OpaqueTypeInit) Alloc
73728270 .reified => std.math.maxInt(u32),
73738271 },
73748272 });
7375 ip.items.appendAssumeCapacity(.{
8273 items.appendAssumeCapacity(.{
73768274 .tag = .type_opaque,
73778275 .data = extra_index,
73788276 });
73798277 switch (ini.key) {
7380 .declared => |d| ip.extra.appendSliceAssumeCapacity(@ptrCast(d.captures)),
8278 .declared => |d| extra.appendSliceAssumeCapacity(.{@ptrCast(d.captures)}),
73818279 .reified => {},
73828280 }
73838281 return .{ .wip = .{
7384 .index = @enumFromInt(gop.index),
8282 .tid = tid,
8283 .index = gop.put(),
73858284 .decl_extra_index = extra_index + std.meta.fieldIndex(Tag.TypeOpaque, "decl").?,
73868285 .namespace_extra_index = if (ini.has_namespace)
73878286 extra_index + std.meta.fieldIndex(Tag.TypeOpaque, "namespace").?
......@@ -7391,13 +8290,20 @@ pub fn getOpaqueType(ip: *InternPool, gpa: Allocator, ini: OpaqueTypeInit) Alloc
73918290}
73928291
73938292pub fn getIfExists(ip: *const InternPool, key: Key) ?Index {
7394 const adapter: KeyAdapter = .{ .intern_pool = ip };
7395 const index = ip.map.getIndexAdapted(key, adapter) orelse return null;
7396 return @enumFromInt(index);
7397}
7398
7399pub fn getAssumeExists(ip: *const InternPool, key: Key) Index {
7400 return ip.getIfExists(key).?;
8293 const full_hash = key.hash64(ip);
8294 const hash: u32 = @truncate(full_hash >> 32);
8295 const shard = &ip.shards[@intCast(full_hash & (ip.shards.len - 1))];
8296 const map = shard.shared.map.acquire();
8297 const map_mask = map.header().mask();
8298 var map_index = hash;
8299 while (true) : (map_index += 1) {
8300 map_index &= map_mask;
8301 const entry = &map.entries[map_index];
8302 const index = entry.acquire();
8303 if (index == .none) return null;
8304 if (entry.hash != hash) continue;
8305 if (ip.indexToKey(index).eql(key, ip)) return index;
8306 }
74018307}
74028308
74038309fn addStringsToMap(
......@@ -7437,57 +8343,67 @@ fn addMap(ip: *InternPool, gpa: Allocator, cap: usize) Allocator.Error!MapIndex
74378343/// This operation only happens under compile error conditions.
74388344/// Leak the index until the next garbage collection.
74398345/// Invalidates all references to this index.
7440pub fn remove(ip: *InternPool, index: Index) void {
8346pub fn remove(ip: *InternPool, tid: Zcu.PerThread.Id, index: Index) void {
8347 const unwrapped_index = index.unwrap(ip);
74418348 if (@intFromEnum(index) < static_keys.len) {
74428349 // The item being removed replaced a special index via `InternPool.resolveBuiltinType`.
74438350 // Restore the original item at this index.
7444 switch (static_keys[@intFromEnum(index)]) {
7445 .simple_type => |s| {
7446 ip.items.set(@intFromEnum(index), .{
7447 .tag = .simple_type,
7448 .data = @intFromEnum(s),
7449 });
7450 },
7451 else => unreachable,
7452 }
8351 assert(static_keys[@intFromEnum(index)] == .simple_type);
8352 const items = ip.getLocalShared(unwrapped_index.tid).items.acquire().view();
8353 @atomicStore(Tag, &items.items(.tag)[unwrapped_index.index], .simple_type, .monotonic);
74538354 return;
74548355 }
74558356
7456 if (@intFromEnum(index) == ip.items.len - 1) {
7457 // Happy case - we can just drop the item without affecting any other indices.
7458 ip.items.len -= 1;
7459 _ = ip.map.pop();
7460 } else {
7461 // We must preserve the item so that indices following it remain valid.
7462 // Thus, we will rewrite the tag to `removed`, leaking the item until
7463 // next GC but causing `KeyAdapter` to ignore it.
7464 ip.items.set(@intFromEnum(index), .{ .tag = .removed, .data = undefined });
8357 if (unwrapped_index.tid == tid) {
8358 const items_len = &ip.getLocal(unwrapped_index.tid).mutate.items.len;
8359 if (unwrapped_index.index == items_len.* - 1) {
8360 // Happy case - we can just drop the item without affecting any other indices.
8361 items_len.* -= 1;
8362 return;
8363 }
74658364 }
8365
8366 // We must preserve the item so that indices following it remain valid.
8367 // Thus, we will rewrite the tag to `removed`, leaking the item until
8368 // next GC but causing `KeyAdapter` to ignore it.
8369 const items = ip.getLocalShared(unwrapped_index.tid).items.acquire().view();
8370 @atomicStore(Tag, &items.items(.tag)[unwrapped_index.index], .removed, .monotonic);
74668371}
74678372
7468fn addInt(ip: *InternPool, gpa: Allocator, ty: Index, tag: Tag, limbs: []const Limb) !void {
8373fn addInt(
8374 ip: *InternPool,
8375 gpa: Allocator,
8376 tid: Zcu.PerThread.Id,
8377 ty: Index,
8378 tag: Tag,
8379 limbs: []const Limb,
8380) !void {
8381 const local = ip.getLocal(tid);
8382 const items_list = local.getMutableItems(gpa);
8383 const limbs_list = local.getMutableLimbs(gpa);
74698384 const limbs_len: u32 = @intCast(limbs.len);
7470 try ip.reserveLimbs(gpa, @typeInfo(Int).Struct.fields.len + limbs_len);
7471 ip.items.appendAssumeCapacity(.{
8385 try limbs_list.ensureUnusedCapacity(Int.limbs_items_len + limbs_len);
8386 items_list.appendAssumeCapacity(.{
74728387 .tag = tag,
7473 .data = ip.addLimbsExtraAssumeCapacity(Int{
7474 .ty = ty,
7475 .limbs_len = limbs_len,
7476 }),
8388 .data = limbs_list.mutate.len,
8389 });
8390 limbs_list.addManyAsArrayAssumeCapacity(Int.limbs_items_len)[0].* = @bitCast(Int{
8391 .ty = ty,
8392 .limbs_len = limbs_len,
74778393 });
7478 ip.addLimbsAssumeCapacity(limbs);
8394 limbs_list.appendSliceAssumeCapacity(.{limbs});
74798395}
74808396
7481fn addExtra(ip: *InternPool, gpa: Allocator, extra: anytype) Allocator.Error!u32 {
7482 const fields = @typeInfo(@TypeOf(extra)).Struct.fields;
7483 try ip.extra.ensureUnusedCapacity(gpa, fields.len);
7484 return ip.addExtraAssumeCapacity(extra);
8397fn addExtra(extra: Local.Extra.Mutable, item: anytype) Allocator.Error!u32 {
8398 const fields = @typeInfo(@TypeOf(item)).Struct.fields;
8399 try extra.ensureUnusedCapacity(fields.len);
8400 return addExtraAssumeCapacity(extra, item);
74858401}
74868402
7487fn addExtraAssumeCapacity(ip: *InternPool, extra: anytype) u32 {
7488 const result: u32 = @intCast(ip.extra.items.len);
7489 inline for (@typeInfo(@TypeOf(extra)).Struct.fields) |field| {
7490 ip.extra.appendAssumeCapacity(switch (field.type) {
8403fn addExtraAssumeCapacity(extra: Local.Extra.Mutable, item: anytype) u32 {
8404 const result: u32 = extra.mutate.len;
8405 inline for (@typeInfo(@TypeOf(item)).Struct.fields) |field| {
8406 extra.appendAssumeCapacity(.{switch (field.type) {
74918407 Index,
74928408 DeclIndex,
74938409 NamespaceIndex,
......@@ -7502,7 +8418,7 @@ fn addExtraAssumeCapacity(ip: *InternPool, extra: anytype) u32 {
75028418 TrackedInst.Index,
75038419 TrackedInst.Index.Optional,
75048420 ComptimeAllocIndex,
7505 => @intFromEnum(@field(extra, field.name)),
8421 => @intFromEnum(@field(item, field.name)),
75068422
75078423 u32,
75088424 i32,
......@@ -7514,22 +8430,14 @@ fn addExtraAssumeCapacity(ip: *InternPool, extra: anytype) u32 {
75148430 Tag.TypeStruct.Flags,
75158431 Tag.TypeStructPacked.Flags,
75168432 Tag.Variable.Flags,
7517 => @bitCast(@field(extra, field.name)),
8433 => @bitCast(@field(item, field.name)),
75188434
75198435 else => @compileError("bad field type: " ++ @typeName(field.type)),
7520 });
8436 }});
75218437 }
75228438 return result;
75238439}
75248440
7525fn reserveLimbs(ip: *InternPool, gpa: Allocator, n: usize) !void {
7526 switch (@sizeOf(Limb)) {
7527 @sizeOf(u32) => try ip.extra.ensureUnusedCapacity(gpa, n),
7528 @sizeOf(u64) => try ip.limbs.ensureUnusedCapacity(gpa, n),
7529 else => @compileError("unsupported host"),
7530 }
7531}
7532
75338441fn addLimbsExtraAssumeCapacity(ip: *InternPool, extra: anytype) u32 {
75348442 switch (@sizeOf(Limb)) {
75358443 @sizeOf(u32) => return addExtraAssumeCapacity(ip, extra),
......@@ -7552,19 +8460,12 @@ fn addLimbsExtraAssumeCapacity(ip: *InternPool, extra: anytype) u32 {
75528460 return result;
75538461}
75548462
7555fn addLimbsAssumeCapacity(ip: *InternPool, limbs: []const Limb) void {
7556 switch (@sizeOf(Limb)) {
7557 @sizeOf(u32) => ip.extra.appendSliceAssumeCapacity(limbs),
7558 @sizeOf(u64) => ip.limbs.appendSliceAssumeCapacity(limbs),
7559 else => @compileError("unsupported host"),
7560 }
7561}
7562
7563fn extraDataTrail(ip: *const InternPool, comptime T: type, index: usize) struct { data: T, end: u32 } {
8463fn extraDataTrail(extra: Local.Extra, comptime T: type, index: u32) struct { data: T, end: u32 } {
8464 const extra_items = extra.view().items(.@"0");
75648465 var result: T = undefined;
75658466 const fields = @typeInfo(T).Struct.fields;
7566 inline for (fields, 0..) |field, i| {
7567 const int32 = ip.extra.items[i + index];
8467 inline for (fields, index..) |field, extra_index| {
8468 const extra_item = extra_items[extra_index];
75688469 @field(result, field.name) = switch (field.type) {
75698470 Index,
75708471 DeclIndex,
......@@ -7580,7 +8481,7 @@ fn extraDataTrail(ip: *const InternPool, comptime T: type, index: usize) struct
75808481 TrackedInst.Index,
75818482 TrackedInst.Index.Optional,
75828483 ComptimeAllocIndex,
7583 => @enumFromInt(int32),
8484 => @enumFromInt(extra_item),
75848485
75858486 u32,
75868487 i32,
......@@ -7592,7 +8493,7 @@ fn extraDataTrail(ip: *const InternPool, comptime T: type, index: usize) struct
75928493 Tag.TypeStructPacked.Flags,
75938494 Tag.Variable.Flags,
75948495 FuncAnalysis,
7595 => @bitCast(int32),
8496 => @bitCast(extra_item),
75968497
75978498 else => @compileError("bad field type: " ++ @typeName(field.type)),
75988499 };
......@@ -7603,75 +8504,8 @@ fn extraDataTrail(ip: *const InternPool, comptime T: type, index: usize) struct
76038504 };
76048505}
76058506
7606fn extraData(ip: *const InternPool, comptime T: type, index: usize) T {
7607 return extraDataTrail(ip, T, index).data;
7608}
7609
7610/// Asserts the struct has 32-bit fields and the number of fields is evenly divisible by 2.
7611fn limbData(ip: *const InternPool, comptime T: type, index: usize) T {
7612 switch (@sizeOf(Limb)) {
7613 @sizeOf(u32) => return extraData(ip, T, index),
7614 @sizeOf(u64) => {},
7615 else => @compileError("unsupported host"),
7616 }
7617 var result: T = undefined;
7618 inline for (@typeInfo(T).Struct.fields, 0..) |field, i| {
7619 const host_int = ip.limbs.items[index + i / 2];
7620 const int32 = if (i % 2 == 0)
7621 @as(u32, @truncate(host_int))
7622 else
7623 @as(u32, @truncate(host_int >> 32));
7624
7625 @field(result, field.name) = switch (field.type) {
7626 u32 => int32,
7627 Index => @enumFromInt(int32),
7628 else => @compileError("bad field type: " ++ @typeName(field.type)),
7629 };
7630 }
7631 return result;
7632}
7633
7634/// This function returns the Limb slice that is trailing data after a payload.
7635fn limbSlice(ip: *const InternPool, comptime S: type, limb_index: u32, len: u32) []const Limb {
7636 const field_count = @typeInfo(S).Struct.fields.len;
7637 switch (@sizeOf(Limb)) {
7638 @sizeOf(u32) => {
7639 const start = limb_index + field_count;
7640 return ip.extra.items[start..][0..len];
7641 },
7642 @sizeOf(u64) => {
7643 const start = limb_index + @divExact(field_count, 2);
7644 return ip.limbs.items[start..][0..len];
7645 },
7646 else => @compileError("unsupported host"),
7647 }
7648}
7649
7650const LimbsAsIndexes = struct {
7651 start: u32,
7652 len: u32,
7653};
7654
7655fn limbsSliceToIndex(ip: *const InternPool, limbs: []const Limb) LimbsAsIndexes {
7656 const host_slice = switch (@sizeOf(Limb)) {
7657 @sizeOf(u32) => ip.extra.items,
7658 @sizeOf(u64) => ip.limbs.items,
7659 else => @compileError("unsupported host"),
7660 };
7661 // TODO: https://github.com/ziglang/zig/issues/1738
7662 return .{
7663 .start = @intCast(@divExact(@intFromPtr(limbs.ptr) - @intFromPtr(host_slice.ptr), @sizeOf(Limb))),
7664 .len = @intCast(limbs.len),
7665 };
7666}
7667
7668/// This function converts Limb array indexes to a primitive slice type.
7669fn limbsIndexToSlice(ip: *const InternPool, limbs: LimbsAsIndexes) []const Limb {
7670 return switch (@sizeOf(Limb)) {
7671 @sizeOf(u32) => ip.extra.items[limbs.start..][0..limbs.len],
7672 @sizeOf(u64) => ip.limbs.items[limbs.start..][0..limbs.len],
7673 else => @compileError("unsupported host"),
7674 };
8507fn extraData(extra: Local.Extra, comptime T: type, index: u32) T {
8508 return extraDataTrail(extra, T, index).data;
76758509}
76768510
76778511test "basic usage" {
......@@ -7680,23 +8514,23 @@ test "basic usage" {
76808514 var ip: InternPool = .{};
76818515 defer ip.deinit(gpa);
76828516
7683 const i32_type = try ip.get(gpa, .{ .int_type = .{
8517 const i32_type = try ip.get(gpa, .main, .{ .int_type = .{
76848518 .signedness = .signed,
76858519 .bits = 32,
76868520 } });
7687 const array_i32 = try ip.get(gpa, .{ .array_type = .{
8521 const array_i32 = try ip.get(gpa, .main, .{ .array_type = .{
76888522 .len = 10,
76898523 .child = i32_type,
76908524 .sentinel = .none,
76918525 } });
76928526
7693 const another_i32_type = try ip.get(gpa, .{ .int_type = .{
8527 const another_i32_type = try ip.get(gpa, .main, .{ .int_type = .{
76948528 .signedness = .signed,
76958529 .bits = 32,
76968530 } });
76978531 try std.testing.expect(another_i32_type == i32_type);
76988532
7699 const another_array_i32 = try ip.get(gpa, .{ .array_type = .{
8533 const another_array_i32 = try ip.get(gpa, .main, .{ .array_type = .{
77008534 .len = 10,
77018535 .child = i32_type,
77028536 .sentinel = .none,
......@@ -7715,13 +8549,13 @@ pub fn childType(ip: *const InternPool, i: Index) Index {
77158549}
77168550
77178551/// Given a slice type, returns the type of the ptr field.
7718pub fn slicePtrType(ip: *const InternPool, i: Index) Index {
7719 switch (i) {
8552pub fn slicePtrType(ip: *const InternPool, index: Index) Index {
8553 switch (index) {
77208554 .slice_const_u8_type => return .manyptr_const_u8_type,
77218555 .slice_const_u8_sentinel_0_type => return .manyptr_const_u8_sentinel_0_type,
77228556 else => {},
77238557 }
7724 const item = ip.items.get(@intFromEnum(i));
8558 const item = index.unwrap(ip).getItem(ip);
77258559 switch (item.tag) {
77268560 .type_slice => return @enumFromInt(item.data),
77278561 else => unreachable, // not a slice type
......@@ -7729,19 +8563,21 @@ pub fn slicePtrType(ip: *const InternPool, i: Index) Index {
77298563}
77308564
77318565/// Given a slice value, returns the value of the ptr field.
7732pub fn slicePtr(ip: *const InternPool, i: Index) Index {
7733 const item = ip.items.get(@intFromEnum(i));
8566pub fn slicePtr(ip: *const InternPool, index: Index) Index {
8567 const unwrapped_index = index.unwrap(ip);
8568 const item = unwrapped_index.getItem(ip);
77348569 switch (item.tag) {
7735 .ptr_slice => return ip.extraData(PtrSlice, item.data).ptr,
8570 .ptr_slice => return extraData(unwrapped_index.getExtra(ip), PtrSlice, item.data).ptr,
77368571 else => unreachable, // not a slice value
77378572 }
77388573}
77398574
77408575/// Given a slice value, returns the value of the len field.
7741pub fn sliceLen(ip: *const InternPool, i: Index) Index {
7742 const item = ip.items.get(@intFromEnum(i));
8576pub fn sliceLen(ip: *const InternPool, index: Index) Index {
8577 const unwrapped_index = index.unwrap(ip);
8578 const item = unwrapped_index.getItem(ip);
77438579 switch (item.tag) {
7744 .ptr_slice => return ip.extraData(PtrSlice, item.data).len,
8580 .ptr_slice => return extraData(unwrapped_index.getExtra(ip), PtrSlice, item.data).len,
77458581 else => unreachable, // not a slice value
77468582 }
77478583}
......@@ -7766,59 +8602,66 @@ pub fn sliceLen(ip: *const InternPool, i: Index) Index {
77668602/// * payload => error union
77678603/// * fn <=> fn
77688604/// * aggregate <=> aggregate (where children can also be coerced)
7769pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Allocator.Error!Index {
8605pub fn getCoerced(
8606 ip: *InternPool,
8607 gpa: Allocator,
8608 tid: Zcu.PerThread.Id,
8609 val: Index,
8610 new_ty: Index,
8611) Allocator.Error!Index {
77708612 const old_ty = ip.typeOf(val);
77718613 if (old_ty == new_ty) return val;
77728614
7773 const tags = ip.items.items(.tag);
7774
77758615 switch (val) {
7776 .undef => return ip.get(gpa, .{ .undef = new_ty }),
8616 .undef => return ip.get(gpa, tid, .{ .undef = new_ty }),
77778617 .null_value => {
7778 if (ip.isOptionalType(new_ty)) return ip.get(gpa, .{ .opt = .{
8618 if (ip.isOptionalType(new_ty)) return ip.get(gpa, tid, .{ .opt = .{
77798619 .ty = new_ty,
77808620 .val = .none,
77818621 } });
77828622
77838623 if (ip.isPointerType(new_ty)) switch (ip.indexToKey(new_ty).ptr_type.flags.size) {
7784 .One, .Many, .C => return ip.get(gpa, .{ .ptr = .{
8624 .One, .Many, .C => return ip.get(gpa, tid, .{ .ptr = .{
77858625 .ty = new_ty,
77868626 .base_addr = .int,
77878627 .byte_offset = 0,
77888628 } }),
7789 .Slice => return ip.get(gpa, .{ .slice = .{
8629 .Slice => return ip.get(gpa, tid, .{ .slice = .{
77908630 .ty = new_ty,
7791 .ptr = try ip.get(gpa, .{ .ptr = .{
8631 .ptr = try ip.get(gpa, tid, .{ .ptr = .{
77928632 .ty = ip.slicePtrType(new_ty),
77938633 .base_addr = .int,
77948634 .byte_offset = 0,
77958635 } }),
7796 .len = try ip.get(gpa, .{ .undef = .usize_type }),
8636 .len = try ip.get(gpa, tid, .{ .undef = .usize_type }),
77978637 } }),
77988638 };
77998639 },
7800 else => switch (tags[@intFromEnum(val)]) {
7801 .func_decl => return getCoercedFuncDecl(ip, gpa, val, new_ty),
7802 .func_instance => return getCoercedFuncInstance(ip, gpa, val, new_ty),
7803 .func_coerced => {
7804 const extra_index = ip.items.items(.data)[@intFromEnum(val)];
7805 const func: Index = @enumFromInt(
7806 ip.extra.items[extra_index + std.meta.fieldIndex(Tag.FuncCoerced, "func").?],
7807 );
7808 switch (tags[@intFromEnum(func)]) {
7809 .func_decl => return getCoercedFuncDecl(ip, gpa, val, new_ty),
7810 .func_instance => return getCoercedFuncInstance(ip, gpa, val, new_ty),
7811 else => unreachable,
7812 }
7813 },
7814 else => {},
8640 else => {
8641 const unwrapped_val = val.unwrap(ip);
8642 const val_item = unwrapped_val.getItem(ip);
8643 switch (val_item.tag) {
8644 .func_decl => return getCoercedFuncDecl(ip, gpa, tid, val, new_ty),
8645 .func_instance => return getCoercedFuncInstance(ip, gpa, tid, val, new_ty),
8646 .func_coerced => {
8647 const func: Index = @enumFromInt(unwrapped_val.getExtra(ip).view().items(.@"0")[
8648 val_item.data + std.meta.fieldIndex(Tag.FuncCoerced, "func").?
8649 ]);
8650 switch (func.unwrap(ip).getTag(ip)) {
8651 .func_decl => return getCoercedFuncDecl(ip, gpa, tid, val, new_ty),
8652 .func_instance => return getCoercedFuncInstance(ip, gpa, tid, val, new_ty),
8653 else => unreachable,
8654 }
8655 },
8656 else => {},
8657 }
78158658 },
78168659 }
78178660
78188661 switch (ip.indexToKey(val)) {
7819 .undef => return ip.get(gpa, .{ .undef = new_ty }),
8662 .undef => return ip.get(gpa, tid, .{ .undef = new_ty }),
78208663 .extern_func => |extern_func| if (ip.isFunctionType(new_ty))
7821 return ip.get(gpa, .{ .extern_func = .{
8664 return ip.get(gpa, tid, .{ .extern_func = .{
78228665 .ty = new_ty,
78238666 .decl = extern_func.decl,
78248667 .lib_name = extern_func.lib_name,
......@@ -7827,12 +8670,12 @@ pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Al
78278670 .func => unreachable,
78288671
78298672 .int => |int| switch (ip.indexToKey(new_ty)) {
7830 .enum_type => return ip.get(gpa, .{ .enum_tag = .{
8673 .enum_type => return ip.get(gpa, tid, .{ .enum_tag = .{
78318674 .ty = new_ty,
7832 .int = try ip.getCoerced(gpa, val, ip.loadEnumType(new_ty).tag_ty),
8675 .int = try ip.getCoerced(gpa, tid, val, ip.loadEnumType(new_ty).tag_ty),
78338676 } }),
78348677 .ptr_type => switch (int.storage) {
7835 inline .u64, .i64 => |int_val| return ip.get(gpa, .{ .ptr = .{
8678 inline .u64, .i64 => |int_val| return ip.get(gpa, tid, .{ .ptr = .{
78368679 .ty = new_ty,
78378680 .base_addr = .int,
78388681 .byte_offset = @intCast(int_val),
......@@ -7841,7 +8684,7 @@ pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Al
78418684 .lazy_align, .lazy_size => {},
78428685 },
78438686 else => if (ip.isIntegerType(new_ty))
7844 return getCoercedInts(ip, gpa, int, new_ty),
8687 return ip.getCoercedInts(gpa, tid, int, new_ty),
78458688 },
78468689 .float => |float| switch (ip.indexToKey(new_ty)) {
78478690 .simple_type => |simple| switch (simple) {
......@@ -7852,7 +8695,7 @@ pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Al
78528695 .f128,
78538696 .c_longdouble,
78548697 .comptime_float,
7855 => return ip.get(gpa, .{ .float = .{
8698 => return ip.get(gpa, tid, .{ .float = .{
78568699 .ty = new_ty,
78578700 .storage = float.storage,
78588701 } }),
......@@ -7861,17 +8704,17 @@ pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Al
78618704 else => {},
78628705 },
78638706 .enum_tag => |enum_tag| if (ip.isIntegerType(new_ty))
7864 return getCoercedInts(ip, gpa, ip.indexToKey(enum_tag.int).int, new_ty),
8707 return ip.getCoercedInts(gpa, tid, ip.indexToKey(enum_tag.int).int, new_ty),
78658708 .enum_literal => |enum_literal| switch (ip.indexToKey(new_ty)) {
78668709 .enum_type => {
78678710 const enum_type = ip.loadEnumType(new_ty);
78688711 const index = enum_type.nameIndex(ip, enum_literal).?;
7869 return ip.get(gpa, .{ .enum_tag = .{
8712 return ip.get(gpa, tid, .{ .enum_tag = .{
78708713 .ty = new_ty,
78718714 .int = if (enum_type.values.len != 0)
78728715 enum_type.values.get(ip)[index]
78738716 else
7874 try ip.get(gpa, .{ .int = .{
8717 try ip.get(gpa, tid, .{ .int = .{
78758718 .ty = enum_type.tag_ty,
78768719 .storage = .{ .u64 = index },
78778720 } }),
......@@ -7880,22 +8723,22 @@ pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Al
78808723 else => {},
78818724 },
78828725 .slice => |slice| if (ip.isPointerType(new_ty) and ip.indexToKey(new_ty).ptr_type.flags.size == .Slice)
7883 return ip.get(gpa, .{ .slice = .{
8726 return ip.get(gpa, tid, .{ .slice = .{
78848727 .ty = new_ty,
7885 .ptr = try ip.getCoerced(gpa, slice.ptr, ip.slicePtrType(new_ty)),
8728 .ptr = try ip.getCoerced(gpa, tid, slice.ptr, ip.slicePtrType(new_ty)),
78868729 .len = slice.len,
78878730 } })
78888731 else if (ip.isIntegerType(new_ty))
7889 return ip.getCoerced(gpa, slice.ptr, new_ty),
8732 return ip.getCoerced(gpa, tid, slice.ptr, new_ty),
78908733 .ptr => |ptr| if (ip.isPointerType(new_ty) and ip.indexToKey(new_ty).ptr_type.flags.size != .Slice)
7891 return ip.get(gpa, .{ .ptr = .{
8734 return ip.get(gpa, tid, .{ .ptr = .{
78928735 .ty = new_ty,
78938736 .base_addr = ptr.base_addr,
78948737 .byte_offset = ptr.byte_offset,
78958738 } })
78968739 else if (ip.isIntegerType(new_ty))
78978740 switch (ptr.base_addr) {
7898 .int => return ip.get(gpa, .{ .int = .{
8741 .int => return ip.get(gpa, tid, .{ .int = .{
78998742 .ty = .usize_type,
79008743 .storage = .{ .u64 = @intCast(ptr.byte_offset) },
79018744 } }),
......@@ -7904,44 +8747,44 @@ pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Al
79048747 .opt => |opt| switch (ip.indexToKey(new_ty)) {
79058748 .ptr_type => |ptr_type| return switch (opt.val) {
79068749 .none => switch (ptr_type.flags.size) {
7907 .One, .Many, .C => try ip.get(gpa, .{ .ptr = .{
8750 .One, .Many, .C => try ip.get(gpa, tid, .{ .ptr = .{
79088751 .ty = new_ty,
79098752 .base_addr = .int,
79108753 .byte_offset = 0,
79118754 } }),
7912 .Slice => try ip.get(gpa, .{ .slice = .{
8755 .Slice => try ip.get(gpa, tid, .{ .slice = .{
79138756 .ty = new_ty,
7914 .ptr = try ip.get(gpa, .{ .ptr = .{
8757 .ptr = try ip.get(gpa, tid, .{ .ptr = .{
79158758 .ty = ip.slicePtrType(new_ty),
79168759 .base_addr = .int,
79178760 .byte_offset = 0,
79188761 } }),
7919 .len = try ip.get(gpa, .{ .undef = .usize_type }),
8762 .len = try ip.get(gpa, tid, .{ .undef = .usize_type }),
79208763 } }),
79218764 },
7922 else => |payload| try ip.getCoerced(gpa, payload, new_ty),
8765 else => |payload| try ip.getCoerced(gpa, tid, payload, new_ty),
79238766 },
7924 .opt_type => |child_type| return try ip.get(gpa, .{ .opt = .{
8767 .opt_type => |child_type| return try ip.get(gpa, tid, .{ .opt = .{
79258768 .ty = new_ty,
79268769 .val = switch (opt.val) {
79278770 .none => .none,
7928 else => try ip.getCoerced(gpa, opt.val, child_type),
8771 else => try ip.getCoerced(gpa, tid, opt.val, child_type),
79298772 },
79308773 } }),
79318774 else => {},
79328775 },
79338776 .err => |err| if (ip.isErrorSetType(new_ty))
7934 return ip.get(gpa, .{ .err = .{
8777 return ip.get(gpa, tid, .{ .err = .{
79358778 .ty = new_ty,
79368779 .name = err.name,
79378780 } })
79388781 else if (ip.isErrorUnionType(new_ty))
7939 return ip.get(gpa, .{ .error_union = .{
8782 return ip.get(gpa, tid, .{ .error_union = .{
79408783 .ty = new_ty,
79418784 .val = .{ .err_name = err.name },
79428785 } }),
79438786 .error_union => |error_union| if (ip.isErrorUnionType(new_ty))
7944 return ip.get(gpa, .{ .error_union = .{
8787 return ip.get(gpa, tid, .{ .error_union = .{
79458788 .ty = new_ty,
79468789 .val = error_union.val,
79478790 } }),
......@@ -7960,20 +8803,20 @@ pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Al
79608803 };
79618804 if (old_ty_child != new_ty_child) break :direct;
79628805 switch (aggregate.storage) {
7963 .bytes => |bytes| return ip.get(gpa, .{ .aggregate = .{
8806 .bytes => |bytes| return ip.get(gpa, tid, .{ .aggregate = .{
79648807 .ty = new_ty,
79658808 .storage = .{ .bytes = bytes },
79668809 } }),
79678810 .elems => |elems| {
79688811 const elems_copy = try gpa.dupe(Index, elems[0..new_len]);
79698812 defer gpa.free(elems_copy);
7970 return ip.get(gpa, .{ .aggregate = .{
8813 return ip.get(gpa, tid, .{ .aggregate = .{
79718814 .ty = new_ty,
79728815 .storage = .{ .elems = elems_copy },
79738816 } });
79748817 },
79758818 .repeated_elem => |elem| {
7976 return ip.get(gpa, .{ .aggregate = .{
8819 return ip.get(gpa, tid, .{ .aggregate = .{
79778820 .ty = new_ty,
79788821 .storage = .{ .repeated_elem = elem },
79798822 } });
......@@ -7991,7 +8834,7 @@ pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Al
79918834 // We have to intern each value here, so unfortunately we can't easily avoid
79928835 // the repeated indexToKey calls.
79938836 for (agg_elems, 0..) |*elem, index| {
7994 elem.* = try ip.get(gpa, .{ .int = .{
8837 elem.* = try ip.get(gpa, tid, .{ .int = .{
79958838 .ty = .u8_type,
79968839 .storage = .{ .u64 = bytes.at(index, ip) },
79978840 } });
......@@ -8008,27 +8851,27 @@ pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Al
80088851 .struct_type => ip.loadStructType(new_ty).field_types.get(ip)[i],
80098852 else => unreachable,
80108853 };
8011 elem.* = try ip.getCoerced(gpa, elem.*, new_elem_ty);
8854 elem.* = try ip.getCoerced(gpa, tid, elem.*, new_elem_ty);
80128855 }
8013 return ip.get(gpa, .{ .aggregate = .{ .ty = new_ty, .storage = .{ .elems = agg_elems } } });
8856 return ip.get(gpa, tid, .{ .aggregate = .{ .ty = new_ty, .storage = .{ .elems = agg_elems } } });
80148857 },
80158858 else => {},
80168859 }
80178860
80188861 switch (ip.indexToKey(new_ty)) {
80198862 .opt_type => |child_type| switch (val) {
8020 .null_value => return ip.get(gpa, .{ .opt = .{
8863 .null_value => return ip.get(gpa, tid, .{ .opt = .{
80218864 .ty = new_ty,
80228865 .val = .none,
80238866 } }),
8024 else => return ip.get(gpa, .{ .opt = .{
8867 else => return ip.get(gpa, tid, .{ .opt = .{
80258868 .ty = new_ty,
8026 .val = try ip.getCoerced(gpa, val, child_type),
8869 .val = try ip.getCoerced(gpa, tid, val, child_type),
80278870 } }),
80288871 },
8029 .error_union_type => |error_union_type| return ip.get(gpa, .{ .error_union = .{
8872 .error_union_type => |error_union_type| return ip.get(gpa, tid, .{ .error_union = .{
80308873 .ty = new_ty,
8031 .val = .{ .payload = try ip.getCoerced(gpa, val, error_union_type.payload_type) },
8874 .val = .{ .payload = try ip.getCoerced(gpa, tid, val, error_union_type.payload_type) },
80328875 } }),
80338876 else => {},
80348877 }
......@@ -8042,87 +8885,87 @@ pub fn getCoerced(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Al
80428885 unreachable;
80438886}
80448887
8045fn getCoercedFuncDecl(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Allocator.Error!Index {
8046 const datas = ip.items.items(.data);
8047 const extra_index = datas[@intFromEnum(val)];
8048 const prev_ty: Index = @enumFromInt(
8049 ip.extra.items[extra_index + std.meta.fieldIndex(Tag.FuncDecl, "ty").?],
8050 );
8888fn getCoercedFuncDecl(
8889 ip: *InternPool,
8890 gpa: Allocator,
8891 tid: Zcu.PerThread.Id,
8892 val: Index,
8893 new_ty: Index,
8894) Allocator.Error!Index {
8895 const unwrapped_val = val.unwrap(ip);
8896 const prev_ty: Index = @enumFromInt(unwrapped_val.getExtra(ip).view().items(.@"0")[
8897 unwrapped_val.getData(ip) + std.meta.fieldIndex(Tag.FuncDecl, "ty").?
8898 ]);
80518899 if (new_ty == prev_ty) return val;
8052 return getCoercedFunc(ip, gpa, val, new_ty);
8900 return getCoercedFunc(ip, gpa, tid, val, new_ty);
80538901}
80548902
8055fn getCoercedFuncInstance(ip: *InternPool, gpa: Allocator, val: Index, new_ty: Index) Allocator.Error!Index {
8056 const datas = ip.items.items(.data);
8057 const extra_index = datas[@intFromEnum(val)];
8058 const prev_ty: Index = @enumFromInt(
8059 ip.extra.items[extra_index + std.meta.fieldIndex(Tag.FuncInstance, "ty").?],
8060 );
8903fn getCoercedFuncInstance(
8904 ip: *InternPool,
8905 gpa: Allocator,
8906 tid: Zcu.PerThread.Id,
8907 val: Index,
8908 new_ty: Index,
8909) Allocator.Error!Index {
8910 const unwrapped_val = val.unwrap(ip);
8911 const prev_ty: Index = @enumFromInt(unwrapped_val.getExtra(ip).view().items(.@"0")[
8912 unwrapped_val.getData(ip) + std.meta.fieldIndex(Tag.FuncInstance, "ty").?
8913 ]);
80618914 if (new_ty == prev_ty) return val;
8062 return getCoercedFunc(ip, gpa, val, new_ty);
8915 return getCoercedFunc(ip, gpa, tid, val, new_ty);
80638916}
80648917
8065fn getCoercedFunc(ip: *InternPool, gpa: Allocator, func: Index, ty: Index) Allocator.Error!Index {
8066 const prev_extra_len = ip.extra.items.len;
8067 try ip.extra.ensureUnusedCapacity(gpa, @typeInfo(Tag.FuncCoerced).Struct.fields.len);
8068 try ip.items.ensureUnusedCapacity(gpa, 1);
8069 try ip.map.ensureUnusedCapacity(gpa, 1);
8918fn getCoercedFunc(
8919 ip: *InternPool,
8920 gpa: Allocator,
8921 tid: Zcu.PerThread.Id,
8922 func: Index,
8923 ty: Index,
8924) Allocator.Error!Index {
8925 const local = ip.getLocal(tid);
8926 const items = local.getMutableItems(gpa);
8927 try items.ensureUnusedCapacity(1);
8928 const extra = local.getMutableExtra(gpa);
80708929
8071 const extra_index = ip.addExtraAssumeCapacity(Tag.FuncCoerced{
8930 const prev_extra_len = extra.mutate.len;
8931 try extra.ensureUnusedCapacity(@typeInfo(Tag.FuncCoerced).Struct.fields.len);
8932
8933 const extra_index = addExtraAssumeCapacity(extra, Tag.FuncCoerced{
80728934 .ty = ty,
80738935 .func = func,
80748936 });
8937 errdefer extra.mutate.len = prev_extra_len;
80758938
8076 const adapter: KeyAdapter = .{ .intern_pool = ip };
8077 const gop = ip.map.getOrPutAssumeCapacityAdapted(Key{
8078 .func = extraFuncCoerced(ip, extra_index),
8079 }, adapter);
8080
8081 if (gop.found_existing) {
8082 ip.extra.items.len = prev_extra_len;
8083 return @enumFromInt(gop.index);
8939 var gop = try ip.getOrPutKey(gpa, tid, .{
8940 .func = ip.extraFuncCoerced(extra.list.*, extra_index),
8941 });
8942 defer gop.deinit();
8943 if (gop == .existing) {
8944 extra.mutate.len = prev_extra_len;
8945 return gop.existing;
80848946 }
80858947
8086 ip.items.appendAssumeCapacity(.{
8948 items.appendAssumeCapacity(.{
80878949 .tag = .func_coerced,
80888950 .data = extra_index,
80898951 });
8090 return @enumFromInt(ip.items.len - 1);
8952 return gop.put();
80918953}
80928954
80938955/// Asserts `val` has an integer type.
80948956/// Assumes `new_ty` is an integer type.
8095pub fn getCoercedInts(ip: *InternPool, gpa: Allocator, int: Key.Int, new_ty: Index) Allocator.Error!Index {
8096 // The key cannot be passed directly to `get`, otherwise in the case of
8097 // big_int storage, the limbs would be invalidated before they are read.
8098 // Here we pre-reserve the limbs to ensure that the logic in `addInt` will
8099 // not use an invalidated limbs pointer.
8100 const new_storage: Key.Int.Storage = switch (int.storage) {
8101 .u64, .i64, .lazy_align, .lazy_size => int.storage,
8102 .big_int => |big_int| storage: {
8103 const positive = big_int.positive;
8104 const limbs = ip.limbsSliceToIndex(big_int.limbs);
8105 // This line invalidates the limbs slice, but the indexes computed in the
8106 // previous line are still correct.
8107 try reserveLimbs(ip, gpa, @typeInfo(Int).Struct.fields.len + big_int.limbs.len);
8108 break :storage .{ .big_int = .{
8109 .limbs = ip.limbsIndexToSlice(limbs),
8110 .positive = positive,
8111 } };
8112 },
8113 };
8114 return ip.get(gpa, .{ .int = .{
8957pub fn getCoercedInts(ip: *InternPool, gpa: Allocator, tid: Zcu.PerThread.Id, int: Key.Int, new_ty: Index) Allocator.Error!Index {
8958 return ip.get(gpa, tid, .{ .int = .{
81158959 .ty = new_ty,
8116 .storage = new_storage,
8960 .storage = int.storage,
81178961 } });
81188962}
81198963
81208964pub fn indexToFuncType(ip: *const InternPool, val: Index) ?Key.FuncType {
8121 assert(val != .none);
8122 const tags = ip.items.items(.tag);
8123 const datas = ip.items.items(.data);
8124 switch (tags[@intFromEnum(val)]) {
8125 .type_function => return extraFuncType(ip, datas[@intFromEnum(val)]),
8965 const unwrapped_val = val.unwrap(ip);
8966 const item = unwrapped_val.getItem(ip);
8967 switch (item.tag) {
8968 .type_function => return extraFuncType(unwrapped_val.tid, unwrapped_val.getExtra(ip), item.data),
81268969 else => return null,
81278970 }
81288971}
......@@ -8143,7 +8986,7 @@ pub fn isIntegerType(ip: *const InternPool, ty: Index) bool {
81438986 .c_ulonglong_type,
81448987 .comptime_int_type,
81458988 => true,
8146 else => switch (ip.items.items(.tag)[@intFromEnum(ty)]) {
8989 else => switch (ty.unwrap(ip).getTag(ip)) {
81478990 .type_int_signed,
81488991 .type_int_unsigned,
81498992 => true,
......@@ -8219,9 +9062,11 @@ pub fn errorUnionPayload(ip: *const InternPool, ty: Index) Index {
82199062
82209063/// The is only legal because the initializer is not part of the hash.
82219064pub fn mutateVarInit(ip: *InternPool, index: Index, init_index: Index) void {
8222 const item = ip.items.get(@intFromEnum(index));
9065 const unwrapped_index = index.unwrap(ip);
9066 const extra_list = unwrapped_index.getExtra(ip);
9067 const item = unwrapped_index.getItem(ip);
82239068 assert(item.tag == .variable);
8224 ip.extra.items[item.data + std.meta.fieldIndex(Tag.Variable, "init").?] = @intFromEnum(init_index);
9069 @atomicStore(u32, &extra_list.view().items(.@"0")[item.data + std.meta.fieldIndex(Tag.Variable, "init").?], @intFromEnum(init_index), .release);
82259070}
82269071
82279072pub fn dump(ip: *const InternPool) void {
......@@ -8230,9 +9075,17 @@ pub fn dump(ip: *const InternPool) void {
82309075}
82319076
82329077fn dumpStatsFallible(ip: *const InternPool, arena: Allocator) anyerror!void {
8233 const items_size = (1 + 4) * ip.items.len;
8234 const extra_size = 4 * ip.extra.items.len;
8235 const limbs_size = 8 * ip.limbs.items.len;
9078 var items_len: usize = 0;
9079 var extra_len: usize = 0;
9080 var limbs_len: usize = 0;
9081 for (ip.locals) |*local| {
9082 items_len += local.mutate.items.len;
9083 extra_len += local.mutate.extra.len;
9084 limbs_len += local.mutate.limbs.len;
9085 }
9086 const items_size = (1 + 4) * items_len;
9087 const extra_size = 4 * extra_len;
9088 const limbs_size = 8 * limbs_len;
82369089 const decls_size = ip.allocated_decls.len * @sizeOf(Module.Decl);
82379090
82389091 // TODO: map overhead size is not taken into account
......@@ -8247,221 +9100,234 @@ fn dumpStatsFallible(ip: *const InternPool, arena: Allocator) anyerror!void {
82479100 \\
82489101 , .{
82499102 total_size,
8250 ip.items.len,
9103 items_len,
82519104 items_size,
8252 ip.extra.items.len,
9105 extra_len,
82539106 extra_size,
8254 ip.limbs.items.len,
9107 limbs_len,
82559108 limbs_size,
82569109 ip.allocated_decls.len,
82579110 decls_size,
82589111 });
82599112
8260 const tags = ip.items.items(.tag);
8261 const datas = ip.items.items(.data);
82629113 const TagStats = struct {
82639114 count: usize = 0,
82649115 bytes: usize = 0,
82659116 };
82669117 var counts = std.AutoArrayHashMap(Tag, TagStats).init(arena);
8267 for (tags, datas) |tag, data| {
8268 const gop = try counts.getOrPut(tag);
8269 if (!gop.found_existing) gop.value_ptr.* = .{};
8270 gop.value_ptr.count += 1;
8271 gop.value_ptr.bytes += 1 + 4 + @as(usize, switch (tag) {
8272 // Note that in this case, we have technically leaked some extra data
8273 // bytes which we do not account for here.
8274 .removed => 0,
8275
8276 .type_int_signed => 0,
8277 .type_int_unsigned => 0,
8278 .type_array_small => @sizeOf(Vector),
8279 .type_array_big => @sizeOf(Array),
8280 .type_vector => @sizeOf(Vector),
8281 .type_pointer => @sizeOf(Tag.TypePointer),
8282 .type_slice => 0,
8283 .type_optional => 0,
8284 .type_anyframe => 0,
8285 .type_error_union => @sizeOf(Key.ErrorUnionType),
8286 .type_anyerror_union => 0,
8287 .type_error_set => b: {
8288 const info = ip.extraData(Tag.ErrorSet, data);
8289 break :b @sizeOf(Tag.ErrorSet) + (@sizeOf(u32) * info.names_len);
8290 },
8291 .type_inferred_error_set => 0,
8292 .type_enum_explicit, .type_enum_nonexhaustive => b: {
8293 const info = ip.extraData(EnumExplicit, data);
8294 var ints = @typeInfo(EnumExplicit).Struct.fields.len + info.captures_len + info.fields_len;
8295 if (info.values_map != .none) ints += info.fields_len;
8296 break :b @sizeOf(u32) * ints;
8297 },
8298 .type_enum_auto => b: {
8299 const info = ip.extraData(EnumAuto, data);
8300 const ints = @typeInfo(EnumAuto).Struct.fields.len + info.captures_len + info.fields_len;
8301 break :b @sizeOf(u32) * ints;
8302 },
8303 .type_opaque => b: {
8304 const info = ip.extraData(Tag.TypeOpaque, data);
8305 const ints = @typeInfo(Tag.TypeOpaque).Struct.fields.len + info.captures_len;
8306 break :b @sizeOf(u32) * ints;
8307 },
8308 .type_struct => b: {
8309 if (data == 0) break :b 0;
8310 const extra = ip.extraDataTrail(Tag.TypeStruct, data);
8311 const info = extra.data;
8312 var ints: usize = @typeInfo(Tag.TypeStruct).Struct.fields.len;
8313 if (info.flags.any_captures) {
8314 const captures_len = ip.extra.items[extra.end];
8315 ints += 1 + captures_len;
8316 }
8317 ints += info.fields_len; // types
8318 if (!info.flags.is_tuple) {
8319 ints += 1; // names_map
8320 ints += info.fields_len; // names
8321 }
8322 if (info.flags.any_default_inits)
8323 ints += info.fields_len; // inits
8324 ints += @intFromBool(info.flags.has_namespace); // namespace
8325 if (info.flags.any_aligned_fields)
8326 ints += (info.fields_len + 3) / 4; // aligns
8327 if (info.flags.any_comptime_fields)
8328 ints += (info.fields_len + 31) / 32; // comptime bits
8329 if (!info.flags.is_extern)
8330 ints += info.fields_len; // runtime order
8331 ints += info.fields_len; // offsets
8332 break :b @sizeOf(u32) * ints;
8333 },
8334 .type_struct_anon => b: {
8335 const info = ip.extraData(TypeStructAnon, data);
8336 break :b @sizeOf(TypeStructAnon) + (@sizeOf(u32) * 3 * info.fields_len);
8337 },
8338 .type_struct_packed => b: {
8339 const extra = ip.extraDataTrail(Tag.TypeStructPacked, data);
8340 const captures_len = if (extra.data.flags.any_captures)
8341 ip.extra.items[extra.end]
8342 else
8343 0;
8344 break :b @sizeOf(u32) * (@typeInfo(Tag.TypeStructPacked).Struct.fields.len +
8345 @intFromBool(extra.data.flags.any_captures) + captures_len +
8346 extra.data.fields_len * 2);
8347 },
8348 .type_struct_packed_inits => b: {
8349 const extra = ip.extraDataTrail(Tag.TypeStructPacked, data);
8350 const captures_len = if (extra.data.flags.any_captures)
8351 ip.extra.items[extra.end]
8352 else
8353 0;
8354 break :b @sizeOf(u32) * (@typeInfo(Tag.TypeStructPacked).Struct.fields.len +
8355 @intFromBool(extra.data.flags.any_captures) + captures_len +
8356 extra.data.fields_len * 3);
8357 },
8358 .type_tuple_anon => b: {
8359 const info = ip.extraData(TypeStructAnon, data);
8360 break :b @sizeOf(TypeStructAnon) + (@sizeOf(u32) * 2 * info.fields_len);
8361 },
8362
8363 .type_union => b: {
8364 const extra = ip.extraDataTrail(Tag.TypeUnion, data);
8365 const captures_len = if (extra.data.flags.any_captures)
8366 ip.extra.items[extra.end]
8367 else
8368 0;
8369 const per_field = @sizeOf(u32); // field type
8370 // 1 byte per field for alignment, rounded up to the nearest 4 bytes
8371 const alignments = if (extra.data.flags.any_aligned_fields)
8372 ((extra.data.fields_len + 3) / 4) * 4
8373 else
8374 0;
8375 break :b @sizeOf(Tag.TypeUnion) +
8376 4 * (@intFromBool(extra.data.flags.any_captures) + captures_len) +
8377 (extra.data.fields_len * per_field) + alignments;
8378 },
9118 for (ip.locals) |*local| {
9119 const items = local.shared.items.view().slice();
9120 const extra_list = local.shared.extra;
9121 const extra_items = extra_list.view().items(.@"0");
9122 for (
9123 items.items(.tag)[0..local.mutate.items.len],
9124 items.items(.data)[0..local.mutate.items.len],
9125 ) |tag, data| {
9126 const gop = try counts.getOrPut(tag);
9127 if (!gop.found_existing) gop.value_ptr.* = .{};
9128 gop.value_ptr.count += 1;
9129 gop.value_ptr.bytes += 1 + 4 + @as(usize, switch (tag) {
9130 // Note that in this case, we have technically leaked some extra data
9131 // bytes which we do not account for here.
9132 .removed => 0,
9133
9134 .type_int_signed => 0,
9135 .type_int_unsigned => 0,
9136 .type_array_small => @sizeOf(Vector),
9137 .type_array_big => @sizeOf(Array),
9138 .type_vector => @sizeOf(Vector),
9139 .type_pointer => @sizeOf(Tag.TypePointer),
9140 .type_slice => 0,
9141 .type_optional => 0,
9142 .type_anyframe => 0,
9143 .type_error_union => @sizeOf(Key.ErrorUnionType),
9144 .type_anyerror_union => 0,
9145 .type_error_set => b: {
9146 const info = extraData(extra_list, Tag.ErrorSet, data);
9147 break :b @sizeOf(Tag.ErrorSet) + (@sizeOf(u32) * info.names_len);
9148 },
9149 .type_inferred_error_set => 0,
9150 .type_enum_explicit, .type_enum_nonexhaustive => b: {
9151 const info = extraData(extra_list, EnumExplicit, data);
9152 var ints = @typeInfo(EnumExplicit).Struct.fields.len;
9153 if (info.zir_index == .none) ints += 1;
9154 ints += if (info.captures_len != std.math.maxInt(u32))
9155 info.captures_len
9156 else
9157 @typeInfo(PackedU64).Struct.fields.len;
9158 ints += info.fields_len;
9159 if (info.values_map != .none) ints += info.fields_len;
9160 break :b @sizeOf(u32) * ints;
9161 },
9162 .type_enum_auto => b: {
9163 const info = extraData(extra_list, EnumAuto, data);
9164 const ints = @typeInfo(EnumAuto).Struct.fields.len + info.captures_len + info.fields_len;
9165 break :b @sizeOf(u32) * ints;
9166 },
9167 .type_opaque => b: {
9168 const info = extraData(extra_list, Tag.TypeOpaque, data);
9169 const ints = @typeInfo(Tag.TypeOpaque).Struct.fields.len + info.captures_len;
9170 break :b @sizeOf(u32) * ints;
9171 },
9172 .type_struct => b: {
9173 if (data == 0) break :b 0;
9174 const extra = extraDataTrail(extra_list, Tag.TypeStruct, data);
9175 const info = extra.data;
9176 var ints: usize = @typeInfo(Tag.TypeStruct).Struct.fields.len;
9177 if (info.flags.any_captures) {
9178 const captures_len = extra_items[extra.end];
9179 ints += 1 + captures_len;
9180 }
9181 ints += info.fields_len; // types
9182 if (!info.flags.is_tuple) {
9183 ints += 1; // names_map
9184 ints += info.fields_len; // names
9185 }
9186 if (info.flags.any_default_inits)
9187 ints += info.fields_len; // inits
9188 ints += @intFromBool(info.flags.has_namespace); // namespace
9189 if (info.flags.any_aligned_fields)
9190 ints += (info.fields_len + 3) / 4; // aligns
9191 if (info.flags.any_comptime_fields)
9192 ints += (info.fields_len + 31) / 32; // comptime bits
9193 if (!info.flags.is_extern)
9194 ints += info.fields_len; // runtime order
9195 ints += info.fields_len; // offsets
9196 break :b @sizeOf(u32) * ints;
9197 },
9198 .type_struct_anon => b: {
9199 const info = extraData(extra_list, TypeStructAnon, data);
9200 break :b @sizeOf(TypeStructAnon) + (@sizeOf(u32) * 3 * info.fields_len);
9201 },
9202 .type_struct_packed => b: {
9203 const extra = extraDataTrail(extra_list, Tag.TypeStructPacked, data);
9204 const captures_len = if (extra.data.flags.any_captures)
9205 extra_items[extra.end]
9206 else
9207 0;
9208 break :b @sizeOf(u32) * (@typeInfo(Tag.TypeStructPacked).Struct.fields.len +
9209 @intFromBool(extra.data.flags.any_captures) + captures_len +
9210 extra.data.fields_len * 2);
9211 },
9212 .type_struct_packed_inits => b: {
9213 const extra = extraDataTrail(extra_list, Tag.TypeStructPacked, data);
9214 const captures_len = if (extra.data.flags.any_captures)
9215 extra_items[extra.end]
9216 else
9217 0;
9218 break :b @sizeOf(u32) * (@typeInfo(Tag.TypeStructPacked).Struct.fields.len +
9219 @intFromBool(extra.data.flags.any_captures) + captures_len +
9220 extra.data.fields_len * 3);
9221 },
9222 .type_tuple_anon => b: {
9223 const info = extraData(extra_list, TypeStructAnon, data);
9224 break :b @sizeOf(TypeStructAnon) + (@sizeOf(u32) * 2 * info.fields_len);
9225 },
83799226
8380 .type_function => b: {
8381 const info = ip.extraData(Tag.TypeFunction, data);
8382 break :b @sizeOf(Tag.TypeFunction) +
8383 (@sizeOf(Index) * info.params_len) +
8384 (@as(u32, 4) * @intFromBool(info.flags.has_comptime_bits)) +
8385 (@as(u32, 4) * @intFromBool(info.flags.has_noalias_bits));
8386 },
9227 .type_union => b: {
9228 const extra = extraDataTrail(extra_list, Tag.TypeUnion, data);
9229 const captures_len = if (extra.data.flags.any_captures)
9230 extra_items[extra.end]
9231 else
9232 0;
9233 const per_field = @sizeOf(u32); // field type
9234 // 1 byte per field for alignment, rounded up to the nearest 4 bytes
9235 const alignments = if (extra.data.flags.any_aligned_fields)
9236 ((extra.data.fields_len + 3) / 4) * 4
9237 else
9238 0;
9239 break :b @sizeOf(Tag.TypeUnion) +
9240 4 * (@intFromBool(extra.data.flags.any_captures) + captures_len) +
9241 (extra.data.fields_len * per_field) + alignments;
9242 },
83879243
8388 .undef => 0,
8389 .simple_type => 0,
8390 .simple_value => 0,
8391 .ptr_decl => @sizeOf(PtrDecl),
8392 .ptr_comptime_alloc => @sizeOf(PtrComptimeAlloc),
8393 .ptr_anon_decl => @sizeOf(PtrAnonDecl),
8394 .ptr_anon_decl_aligned => @sizeOf(PtrAnonDeclAligned),
8395 .ptr_comptime_field => @sizeOf(PtrComptimeField),
8396 .ptr_int => @sizeOf(PtrInt),
8397 .ptr_eu_payload => @sizeOf(PtrBase),
8398 .ptr_opt_payload => @sizeOf(PtrBase),
8399 .ptr_elem => @sizeOf(PtrBaseIndex),
8400 .ptr_field => @sizeOf(PtrBaseIndex),
8401 .ptr_slice => @sizeOf(PtrSlice),
8402 .opt_null => 0,
8403 .opt_payload => @sizeOf(Tag.TypeValue),
8404 .int_u8 => 0,
8405 .int_u16 => 0,
8406 .int_u32 => 0,
8407 .int_i32 => 0,
8408 .int_usize => 0,
8409 .int_comptime_int_u32 => 0,
8410 .int_comptime_int_i32 => 0,
8411 .int_small => @sizeOf(IntSmall),
9244 .type_function => b: {
9245 const info = extraData(extra_list, Tag.TypeFunction, data);
9246 break :b @sizeOf(Tag.TypeFunction) +
9247 (@sizeOf(Index) * info.params_len) +
9248 (@as(u32, 4) * @intFromBool(info.flags.has_comptime_bits)) +
9249 (@as(u32, 4) * @intFromBool(info.flags.has_noalias_bits));
9250 },
84129251
8413 .int_positive,
8414 .int_negative,
8415 => b: {
8416 const int = ip.limbData(Int, data);
8417 break :b @sizeOf(Int) + int.limbs_len * 8;
8418 },
9252 .undef => 0,
9253 .simple_type => 0,
9254 .simple_value => 0,
9255 .ptr_decl => @sizeOf(PtrDecl),
9256 .ptr_comptime_alloc => @sizeOf(PtrComptimeAlloc),
9257 .ptr_anon_decl => @sizeOf(PtrAnonDecl),
9258 .ptr_anon_decl_aligned => @sizeOf(PtrAnonDeclAligned),
9259 .ptr_comptime_field => @sizeOf(PtrComptimeField),
9260 .ptr_int => @sizeOf(PtrInt),
9261 .ptr_eu_payload => @sizeOf(PtrBase),
9262 .ptr_opt_payload => @sizeOf(PtrBase),
9263 .ptr_elem => @sizeOf(PtrBaseIndex),
9264 .ptr_field => @sizeOf(PtrBaseIndex),
9265 .ptr_slice => @sizeOf(PtrSlice),
9266 .opt_null => 0,
9267 .opt_payload => @sizeOf(Tag.TypeValue),
9268 .int_u8 => 0,
9269 .int_u16 => 0,
9270 .int_u32 => 0,
9271 .int_i32 => 0,
9272 .int_usize => 0,
9273 .int_comptime_int_u32 => 0,
9274 .int_comptime_int_i32 => 0,
9275 .int_small => @sizeOf(IntSmall),
9276
9277 .int_positive,
9278 .int_negative,
9279 => b: {
9280 const limbs_list = local.shared.getLimbs();
9281 const int: Int = @bitCast(limbs_list.view().items(.@"0")[data..][0..Int.limbs_items_len].*);
9282 break :b @sizeOf(Int) + int.limbs_len * @sizeOf(Limb);
9283 },
84199284
8420 .int_lazy_align, .int_lazy_size => @sizeOf(IntLazy),
9285 .int_lazy_align, .int_lazy_size => @sizeOf(IntLazy),
84219286
8422 .error_set_error, .error_union_error => @sizeOf(Key.Error),
8423 .error_union_payload => @sizeOf(Tag.TypeValue),
8424 .enum_literal => 0,
8425 .enum_tag => @sizeOf(Tag.EnumTag),
9287 .error_set_error, .error_union_error => @sizeOf(Key.Error),
9288 .error_union_payload => @sizeOf(Tag.TypeValue),
9289 .enum_literal => 0,
9290 .enum_tag => @sizeOf(Tag.EnumTag),
84269291
8427 .bytes => b: {
8428 const info = ip.extraData(Bytes, data);
8429 const len: usize = @intCast(ip.aggregateTypeLenIncludingSentinel(info.ty));
8430 break :b @sizeOf(Bytes) + len + @intFromBool(info.bytes.at(len - 1, ip) != 0);
8431 },
8432 .aggregate => b: {
8433 const info = ip.extraData(Tag.Aggregate, data);
8434 const fields_len: u32 = @intCast(ip.aggregateTypeLenIncludingSentinel(info.ty));
8435 break :b @sizeOf(Tag.Aggregate) + (@sizeOf(Index) * fields_len);
8436 },
8437 .repeated => @sizeOf(Repeated),
8438
8439 .float_f16 => 0,
8440 .float_f32 => 0,
8441 .float_f64 => @sizeOf(Float64),
8442 .float_f80 => @sizeOf(Float80),
8443 .float_f128 => @sizeOf(Float128),
8444 .float_c_longdouble_f80 => @sizeOf(Float80),
8445 .float_c_longdouble_f128 => @sizeOf(Float128),
8446 .float_comptime_float => @sizeOf(Float128),
8447 .variable => @sizeOf(Tag.Variable),
8448 .extern_func => @sizeOf(Tag.ExternFunc),
8449 .func_decl => @sizeOf(Tag.FuncDecl),
8450 .func_instance => b: {
8451 const info = ip.extraData(Tag.FuncInstance, data);
8452 const ty = ip.typeOf(info.generic_owner);
8453 const params_len = ip.indexToKey(ty).func_type.param_types.len;
8454 break :b @sizeOf(Tag.FuncInstance) + @sizeOf(Index) * params_len;
8455 },
8456 .func_coerced => @sizeOf(Tag.FuncCoerced),
8457 .only_possible_value => 0,
8458 .union_value => @sizeOf(Key.Union),
9292 .bytes => b: {
9293 const info = extraData(extra_list, Bytes, data);
9294 const len: usize = @intCast(ip.aggregateTypeLenIncludingSentinel(info.ty));
9295 break :b @sizeOf(Bytes) + len + @intFromBool(info.bytes.at(len - 1, ip) != 0);
9296 },
9297 .aggregate => b: {
9298 const info = extraData(extra_list, Tag.Aggregate, data);
9299 const fields_len: u32 = @intCast(ip.aggregateTypeLenIncludingSentinel(info.ty));
9300 break :b @sizeOf(Tag.Aggregate) + (@sizeOf(Index) * fields_len);
9301 },
9302 .repeated => @sizeOf(Repeated),
9303
9304 .float_f16 => 0,
9305 .float_f32 => 0,
9306 .float_f64 => @sizeOf(Float64),
9307 .float_f80 => @sizeOf(Float80),
9308 .float_f128 => @sizeOf(Float128),
9309 .float_c_longdouble_f80 => @sizeOf(Float80),
9310 .float_c_longdouble_f128 => @sizeOf(Float128),
9311 .float_comptime_float => @sizeOf(Float128),
9312 .variable => @sizeOf(Tag.Variable),
9313 .extern_func => @sizeOf(Tag.ExternFunc),
9314 .func_decl => @sizeOf(Tag.FuncDecl),
9315 .func_instance => b: {
9316 const info = extraData(extra_list, Tag.FuncInstance, data);
9317 const ty = ip.typeOf(info.generic_owner);
9318 const params_len = ip.indexToKey(ty).func_type.param_types.len;
9319 break :b @sizeOf(Tag.FuncInstance) + @sizeOf(Index) * params_len;
9320 },
9321 .func_coerced => @sizeOf(Tag.FuncCoerced),
9322 .only_possible_value => 0,
9323 .union_value => @sizeOf(Key.Union),
84599324
8460 .memoized_call => b: {
8461 const info = ip.extraData(MemoizedCall, data);
8462 break :b @sizeOf(MemoizedCall) + (@sizeOf(Index) * info.args_len);
8463 },
8464 });
9325 .memoized_call => b: {
9326 const info = extraData(extra_list, MemoizedCall, data);
9327 break :b @sizeOf(MemoizedCall) + (@sizeOf(Index) * info.args_len);
9328 },
9329 });
9330 }
84659331 }
84669332 const SortContext = struct {
84679333 map: *std.AutoArrayHashMap(Tag, TagStats),
......@@ -8482,97 +9348,103 @@ fn dumpStatsFallible(ip: *const InternPool, arena: Allocator) anyerror!void {
84829348}
84839349
84849350fn dumpAllFallible(ip: *const InternPool) anyerror!void {
8485 const tags = ip.items.items(.tag);
8486 const datas = ip.items.items(.data);
84879351 var bw = std.io.bufferedWriter(std.io.getStdErr().writer());
84889352 const w = bw.writer();
8489 for (tags, datas, 0..) |tag, data, i| {
8490 try w.print("${d} = {s}(", .{ i, @tagName(tag) });
8491 switch (tag) {
8492 .removed => {},
8493
8494 .simple_type => try w.print("{s}", .{@tagName(@as(SimpleType, @enumFromInt(data)))}),
8495 .simple_value => try w.print("{s}", .{@tagName(@as(SimpleValue, @enumFromInt(data)))}),
8496
8497 .type_int_signed,
8498 .type_int_unsigned,
8499 .type_array_small,
8500 .type_array_big,
8501 .type_vector,
8502 .type_pointer,
8503 .type_optional,
8504 .type_anyframe,
8505 .type_error_union,
8506 .type_anyerror_union,
8507 .type_error_set,
8508 .type_inferred_error_set,
8509 .type_enum_explicit,
8510 .type_enum_nonexhaustive,
8511 .type_enum_auto,
8512 .type_opaque,
8513 .type_struct,
8514 .type_struct_anon,
8515 .type_struct_packed,
8516 .type_struct_packed_inits,
8517 .type_tuple_anon,
8518 .type_union,
8519 .type_function,
8520 .undef,
8521 .ptr_decl,
8522 .ptr_comptime_alloc,
8523 .ptr_anon_decl,
8524 .ptr_anon_decl_aligned,
8525 .ptr_comptime_field,
8526 .ptr_int,
8527 .ptr_eu_payload,
8528 .ptr_opt_payload,
8529 .ptr_elem,
8530 .ptr_field,
8531 .ptr_slice,
8532 .opt_payload,
8533 .int_u8,
8534 .int_u16,
8535 .int_u32,
8536 .int_i32,
8537 .int_usize,
8538 .int_comptime_int_u32,
8539 .int_comptime_int_i32,
8540 .int_small,
8541 .int_positive,
8542 .int_negative,
8543 .int_lazy_align,
8544 .int_lazy_size,
8545 .error_set_error,
8546 .error_union_error,
8547 .error_union_payload,
8548 .enum_literal,
8549 .enum_tag,
8550 .bytes,
8551 .aggregate,
8552 .repeated,
8553 .float_f16,
8554 .float_f32,
8555 .float_f64,
8556 .float_f80,
8557 .float_f128,
8558 .float_c_longdouble_f80,
8559 .float_c_longdouble_f128,
8560 .float_comptime_float,
8561 .variable,
8562 .extern_func,
8563 .func_decl,
8564 .func_instance,
8565 .func_coerced,
8566 .union_value,
8567 .memoized_call,
8568 => try w.print("{d}", .{data}),
8569
8570 .opt_null,
8571 .type_slice,
8572 .only_possible_value,
8573 => try w.print("${d}", .{data}),
9353 for (ip.locals, 0..) |*local, tid| {
9354 const items = local.shared.items.view();
9355 for (
9356 items.items(.tag)[0..local.mutate.items.len],
9357 items.items(.data)[0..local.mutate.items.len],
9358 0..,
9359 ) |tag, data, index| {
9360 const i = Index.Unwrapped.wrap(.{ .tid = @enumFromInt(tid), .index = @intCast(index) }, ip);
9361 try w.print("${d} = {s}(", .{ i, @tagName(tag) });
9362 switch (tag) {
9363 .removed => {},
9364
9365 .simple_type => try w.print("{s}", .{@tagName(@as(SimpleType, @enumFromInt(@intFromEnum(i))))}),
9366 .simple_value => try w.print("{s}", .{@tagName(@as(SimpleValue, @enumFromInt(@intFromEnum(i))))}),
9367
9368 .type_int_signed,
9369 .type_int_unsigned,
9370 .type_array_small,
9371 .type_array_big,
9372 .type_vector,
9373 .type_pointer,
9374 .type_optional,
9375 .type_anyframe,
9376 .type_error_union,
9377 .type_anyerror_union,
9378 .type_error_set,
9379 .type_inferred_error_set,
9380 .type_enum_explicit,
9381 .type_enum_nonexhaustive,
9382 .type_enum_auto,
9383 .type_opaque,
9384 .type_struct,
9385 .type_struct_anon,
9386 .type_struct_packed,
9387 .type_struct_packed_inits,
9388 .type_tuple_anon,
9389 .type_union,
9390 .type_function,
9391 .undef,
9392 .ptr_decl,
9393 .ptr_comptime_alloc,
9394 .ptr_anon_decl,
9395 .ptr_anon_decl_aligned,
9396 .ptr_comptime_field,
9397 .ptr_int,
9398 .ptr_eu_payload,
9399 .ptr_opt_payload,
9400 .ptr_elem,
9401 .ptr_field,
9402 .ptr_slice,
9403 .opt_payload,
9404 .int_u8,
9405 .int_u16,
9406 .int_u32,
9407 .int_i32,
9408 .int_usize,
9409 .int_comptime_int_u32,
9410 .int_comptime_int_i32,
9411 .int_small,
9412 .int_positive,
9413 .int_negative,
9414 .int_lazy_align,
9415 .int_lazy_size,
9416 .error_set_error,
9417 .error_union_error,
9418 .error_union_payload,
9419 .enum_literal,
9420 .enum_tag,
9421 .bytes,
9422 .aggregate,
9423 .repeated,
9424 .float_f16,
9425 .float_f32,
9426 .float_f64,
9427 .float_f80,
9428 .float_f128,
9429 .float_c_longdouble_f80,
9430 .float_c_longdouble_f128,
9431 .float_comptime_float,
9432 .variable,
9433 .extern_func,
9434 .func_decl,
9435 .func_instance,
9436 .func_coerced,
9437 .union_value,
9438 .memoized_call,
9439 => try w.print("{d}", .{data}),
9440
9441 .opt_null,
9442 .type_slice,
9443 .only_possible_value,
9444 => try w.print("${d}", .{data}),
9445 }
9446 try w.writeAll(")\n");
85749447 }
8575 try w.writeAll(")\n");
85769448 }
85779449 try bw.flush();
85789450}
......@@ -8590,15 +9462,25 @@ pub fn dumpGenericInstancesFallible(ip: *const InternPool, allocator: Allocator)
85909462 const w = bw.writer();
85919463
85929464 var instances: std.AutoArrayHashMapUnmanaged(Index, std.ArrayListUnmanaged(Index)) = .{};
8593 const datas = ip.items.items(.data);
8594 for (ip.items.items(.tag), 0..) |tag, i| {
8595 if (tag != .func_instance) continue;
8596 const info = ip.extraData(Tag.FuncInstance, datas[i]);
8597
8598 const gop = try instances.getOrPut(arena, info.generic_owner);
8599 if (!gop.found_existing) gop.value_ptr.* = .{};
8600
8601 try gop.value_ptr.append(arena, @enumFromInt(i));
9465 for (ip.locals, 0..) |*local, tid| {
9466 const items = local.shared.items.view().slice();
9467 const extra_list = local.shared.extra;
9468 for (
9469 items.items(.tag)[0..local.mutate.items.len],
9470 items.items(.data)[0..local.mutate.items.len],
9471 0..,
9472 ) |tag, data, index| {
9473 if (tag != .func_instance) continue;
9474 const info = extraData(extra_list, Tag.FuncInstance, data);
9475
9476 const gop = try instances.getOrPut(arena, info.generic_owner);
9477 if (!gop.found_existing) gop.value_ptr.* = .{};
9478
9479 try gop.value_ptr.append(
9480 arena,
9481 Index.Unwrapped.wrap(.{ .tid = @enumFromInt(tid), .index = @intCast(index) }, ip),
9482 );
9483 }
86029484 }
86039485
86049486 const SortContext = struct {
......@@ -8614,7 +9496,8 @@ pub fn dumpGenericInstancesFallible(ip: *const InternPool, allocator: Allocator)
86149496 const generic_fn_owner_decl = ip.declPtrConst(ip.funcDeclOwner(entry.key_ptr.*));
86159497 try w.print("{} ({}): \n", .{ generic_fn_owner_decl.name.fmt(ip), entry.value_ptr.items.len });
86169498 for (entry.value_ptr.items) |index| {
8617 const func = ip.extraFuncInstance(datas[@intFromEnum(index)]);
9499 const unwrapped_index = index.unwrap(ip);
9500 const func = ip.extraFuncInstance(unwrapped_index.tid, unwrapped_index.getExtra(ip), unwrapped_index.getData(ip));
86189501 const owner_decl = ip.declPtrConst(func.owner_decl);
86199502 try w.print(" {}: (", .{owner_decl.name.fmt(ip)});
86209503 for (func.comptime_args.get(ip)) |arg| {
......@@ -8712,82 +9595,173 @@ const EmbeddedNulls = enum {
87129595pub fn getOrPutString(
87139596 ip: *InternPool,
87149597 gpa: Allocator,
9598 tid: Zcu.PerThread.Id,
87159599 slice: []const u8,
87169600 comptime embedded_nulls: EmbeddedNulls,
87179601) Allocator.Error!embedded_nulls.StringType() {
8718 try ip.string_bytes.ensureUnusedCapacity(gpa, slice.len + 1);
8719 ip.string_bytes.appendSliceAssumeCapacity(slice);
8720 ip.string_bytes.appendAssumeCapacity(0);
8721 return ip.getOrPutTrailingString(gpa, slice.len + 1, embedded_nulls);
9602 const strings = ip.getLocal(tid).getMutableStrings(gpa);
9603 try strings.ensureUnusedCapacity(slice.len + 1);
9604 strings.appendSliceAssumeCapacity(.{slice});
9605 strings.appendAssumeCapacity(.{0});
9606 return ip.getOrPutTrailingString(gpa, tid, @intCast(slice.len + 1), embedded_nulls);
87229607}
87239608
87249609pub fn getOrPutStringFmt(
87259610 ip: *InternPool,
87269611 gpa: Allocator,
9612 tid: Zcu.PerThread.Id,
87279613 comptime format: []const u8,
87289614 args: anytype,
87299615 comptime embedded_nulls: EmbeddedNulls,
87309616) Allocator.Error!embedded_nulls.StringType() {
8731 // ensure that references to string_bytes in args do not get invalidated
8732 const len: usize = @intCast(std.fmt.count(format, args) + 1);
8733 try ip.string_bytes.ensureUnusedCapacity(gpa, len);
8734 ip.string_bytes.writer(undefined).print(format, args) catch unreachable;
8735 ip.string_bytes.appendAssumeCapacity(0);
8736 return ip.getOrPutTrailingString(gpa, len, embedded_nulls);
9617 // ensure that references to strings in args do not get invalidated
9618 const format_z = format ++ .{0};
9619 const len: u32 = @intCast(std.fmt.count(format_z, args));
9620 const strings = ip.getLocal(tid).getMutableStrings(gpa);
9621 const slice = try strings.addManyAsSlice(len);
9622 assert((std.fmt.bufPrint(slice[0], format_z, args) catch unreachable).len == len);
9623 return ip.getOrPutTrailingString(gpa, tid, len, embedded_nulls);
87379624}
87389625
87399626pub fn getOrPutStringOpt(
87409627 ip: *InternPool,
87419628 gpa: Allocator,
9629 tid: Zcu.PerThread.Id,
87429630 slice: ?[]const u8,
87439631 comptime embedded_nulls: EmbeddedNulls,
87449632) Allocator.Error!embedded_nulls.OptionalStringType() {
8745 const string = try getOrPutString(ip, gpa, slice orelse return .none, embedded_nulls);
9633 const string = try getOrPutString(ip, gpa, tid, slice orelse return .none, embedded_nulls);
87469634 return string.toOptional();
87479635}
87489636
8749/// Uses the last len bytes of ip.string_bytes as the key.
9637/// Uses the last len bytes of strings as the key.
87509638pub fn getOrPutTrailingString(
87519639 ip: *InternPool,
87529640 gpa: Allocator,
8753 len: usize,
9641 tid: Zcu.PerThread.Id,
9642 len: u32,
87549643 comptime embedded_nulls: EmbeddedNulls,
87559644) Allocator.Error!embedded_nulls.StringType() {
8756 const string_bytes = &ip.string_bytes;
8757 const str_index: u32 = @intCast(string_bytes.items.len - len);
8758 if (len > 0 and string_bytes.getLast() == 0) {
8759 _ = string_bytes.pop();
9645 const strings = ip.getLocal(tid).getMutableStrings(gpa);
9646 const start: u32 = @intCast(strings.mutate.len - len);
9647 if (len > 0 and strings.view().items(.@"0")[strings.mutate.len - 1] == 0) {
9648 strings.mutate.len -= 1;
87609649 } else {
8761 try string_bytes.ensureUnusedCapacity(gpa, 1);
9650 try strings.ensureUnusedCapacity(1);
87629651 }
8763 const key: []const u8 = string_bytes.items[str_index..];
9652 const key: []const u8 = strings.view().items(.@"0")[start..];
9653 const value: embedded_nulls.StringType() =
9654 @enumFromInt(@as(u32, @intFromEnum(tid)) << ip.tid_shift_32 | start);
87649655 const has_embedded_null = std.mem.indexOfScalar(u8, key, 0) != null;
87659656 switch (embedded_nulls) {
87669657 .no_embedded_nulls => assert(!has_embedded_null),
87679658 .maybe_embedded_nulls => if (has_embedded_null) {
8768 string_bytes.appendAssumeCapacity(0);
8769 return @enumFromInt(str_index);
8770 },
9659 strings.appendAssumeCapacity(.{0});
9660 return value;
9661 },
9662 }
9663
9664 const full_hash = Hash.hash(0, key);
9665 const hash: u32 = @truncate(full_hash >> 32);
9666 const shard = &ip.shards[@intCast(full_hash & (ip.shards.len - 1))];
9667 var map = shard.shared.string_map.acquire();
9668 const Map = @TypeOf(map);
9669 var map_mask = map.header().mask();
9670 var map_index = hash;
9671 while (true) : (map_index += 1) {
9672 map_index &= map_mask;
9673 const entry = &map.entries[map_index];
9674 const index = entry.acquire().unwrap() orelse break;
9675 if (entry.hash != hash) continue;
9676 if (!index.eqlSlice(key, ip)) continue;
9677 strings.shrinkRetainingCapacity(start);
9678 return @enumFromInt(@intFromEnum(index));
9679 }
9680 shard.mutate.string_map.mutex.lock();
9681 defer shard.mutate.string_map.mutex.unlock();
9682 if (map.entries != shard.shared.string_map.entries) {
9683 shard.mutate.string_map.len += 1;
9684 map = shard.shared.string_map;
9685 map_mask = map.header().mask();
9686 map_index = hash;
9687 }
9688 while (true) : (map_index += 1) {
9689 map_index &= map_mask;
9690 const entry = &map.entries[map_index];
9691 const index = entry.acquire().unwrap() orelse break;
9692 if (entry.hash != hash) continue;
9693 if (!index.eqlSlice(key, ip)) continue;
9694 strings.shrinkRetainingCapacity(start);
9695 return @enumFromInt(@intFromEnum(index));
9696 }
9697 defer shard.mutate.string_map.len += 1;
9698 const map_header = map.header().*;
9699 if (shard.mutate.string_map.len < map_header.capacity * 3 / 5) {
9700 const entry = &map.entries[map_index];
9701 entry.hash = hash;
9702 entry.release(@enumFromInt(@intFromEnum(value)));
9703 strings.appendAssumeCapacity(.{0});
9704 return value;
9705 }
9706 const arena_state = &ip.getLocal(tid).mutate.arena;
9707 var arena = arena_state.promote(gpa);
9708 defer arena_state.* = arena.state;
9709 const new_map_capacity = map_header.capacity * 2;
9710 const new_map_buf = try arena.allocator().alignedAlloc(
9711 u8,
9712 Map.alignment,
9713 Map.entries_offset + new_map_capacity * @sizeOf(Map.Entry),
9714 );
9715 const new_map: Map = .{ .entries = @ptrCast(new_map_buf[Map.entries_offset..].ptr) };
9716 new_map.header().* = .{ .capacity = new_map_capacity };
9717 @memset(new_map.entries[0..new_map_capacity], .{ .value = .none, .hash = undefined });
9718 const new_map_mask = new_map.header().mask();
9719 map_index = 0;
9720 while (map_index < map_header.capacity) : (map_index += 1) {
9721 const entry = &map.entries[map_index];
9722 const index = entry.value.unwrap() orelse continue;
9723 const item_hash = entry.hash;
9724 var new_map_index = item_hash;
9725 while (true) : (new_map_index += 1) {
9726 new_map_index &= new_map_mask;
9727 const new_entry = &new_map.entries[new_map_index];
9728 if (new_entry.value != .none) continue;
9729 new_entry.* = .{
9730 .value = index.toOptional(),
9731 .hash = item_hash,
9732 };
9733 break;
9734 }
87719735 }
8772 const gop = try ip.string_table.getOrPutContextAdapted(gpa, key, std.hash_map.StringIndexAdapter{
8773 .bytes = string_bytes,
8774 }, std.hash_map.StringIndexContext{
8775 .bytes = string_bytes,
8776 });
8777 if (gop.found_existing) {
8778 string_bytes.shrinkRetainingCapacity(str_index);
8779 return @enumFromInt(gop.key_ptr.*);
8780 } else {
8781 gop.key_ptr.* = str_index;
8782 string_bytes.appendAssumeCapacity(0);
8783 return @enumFromInt(str_index);
9736 map = new_map;
9737 map_index = hash;
9738 while (true) : (map_index += 1) {
9739 map_index &= new_map_mask;
9740 if (map.entries[map_index].value == .none) break;
87849741 }
9742 map.entries[map_index] = .{
9743 .value = @enumFromInt(@intFromEnum(value)),
9744 .hash = hash,
9745 };
9746 shard.shared.string_map.release(new_map);
9747 strings.appendAssumeCapacity(.{0});
9748 return value;
87859749}
87869750
8787pub fn getString(ip: *InternPool, s: []const u8) OptionalNullTerminatedString {
8788 return if (ip.string_table.getKeyAdapted(s, std.hash_map.StringIndexAdapter{
8789 .bytes = &ip.string_bytes,
8790 })) |index| @enumFromInt(index) else .none;
9751pub fn getString(ip: *InternPool, key: []const u8) OptionalNullTerminatedString {
9752 const full_hash = Hash.hash(0, key);
9753 const hash: u32 = @truncate(full_hash >> 32);
9754 const shard = &ip.shards[@intCast(full_hash & (ip.shards.len - 1))];
9755 const map = shard.shared.string_map.acquire();
9756 const map_mask = map.header().mask();
9757 var map_index = hash;
9758 while (true) : (map_index += 1) {
9759 map_index &= map_mask;
9760 const entry = map.at(map_index);
9761 const index = entry.acquire().unwrap() orelse return null;
9762 if (entry.hash != hash) continue;
9763 if (index.eqlSlice(key, ip)) return index;
9764 }
87919765}
87929766
87939767pub fn typeOf(ip: *const InternPool, index: Index) Index {
......@@ -8878,106 +9852,112 @@ pub fn typeOf(ip: *const InternPool, index: Index) Index {
88789852
88799853 // This optimization on tags is needed so that indexToKey can call
88809854 // typeOf without being recursive.
8881 _ => switch (ip.items.items(.tag)[@intFromEnum(index)]) {
8882 .removed => unreachable,
8883
8884 .type_int_signed,
8885 .type_int_unsigned,
8886 .type_array_big,
8887 .type_array_small,
8888 .type_vector,
8889 .type_pointer,
8890 .type_slice,
8891 .type_optional,
8892 .type_anyframe,
8893 .type_error_union,
8894 .type_anyerror_union,
8895 .type_error_set,
8896 .type_inferred_error_set,
8897 .type_enum_auto,
8898 .type_enum_explicit,
8899 .type_enum_nonexhaustive,
8900 .simple_type,
8901 .type_opaque,
8902 .type_struct,
8903 .type_struct_anon,
8904 .type_struct_packed,
8905 .type_struct_packed_inits,
8906 .type_tuple_anon,
8907 .type_union,
8908 .type_function,
8909 => .type_type,
8910
8911 .undef,
8912 .opt_null,
8913 .only_possible_value,
8914 => @enumFromInt(ip.items.items(.data)[@intFromEnum(index)]),
8915
8916 .simple_value => unreachable, // handled via Index above
8917
8918 inline .ptr_decl,
8919 .ptr_comptime_alloc,
8920 .ptr_anon_decl,
8921 .ptr_anon_decl_aligned,
8922 .ptr_comptime_field,
8923 .ptr_int,
8924 .ptr_eu_payload,
8925 .ptr_opt_payload,
8926 .ptr_elem,
8927 .ptr_field,
8928 .ptr_slice,
8929 .opt_payload,
8930 .error_union_payload,
8931 .int_small,
8932 .int_lazy_align,
8933 .int_lazy_size,
8934 .error_set_error,
8935 .error_union_error,
8936 .enum_tag,
8937 .variable,
8938 .extern_func,
8939 .func_decl,
8940 .func_instance,
8941 .func_coerced,
8942 .union_value,
8943 .bytes,
8944 .aggregate,
8945 .repeated,
8946 => |t| {
8947 const extra_index = ip.items.items(.data)[@intFromEnum(index)];
8948 const field_index = std.meta.fieldIndex(t.Payload(), "ty").?;
8949 return @enumFromInt(ip.extra.items[extra_index + field_index]);
8950 },
8951
8952 .int_u8 => .u8_type,
8953 .int_u16 => .u16_type,
8954 .int_u32 => .u32_type,
8955 .int_i32 => .i32_type,
8956 .int_usize => .usize_type,
8957
8958 .int_comptime_int_u32,
8959 .int_comptime_int_i32,
8960 => .comptime_int_type,
9855 _ => {
9856 const unwrapped_index = index.unwrap(ip);
9857 const item = unwrapped_index.getItem(ip);
9858 return switch (item.tag) {
9859 .removed => unreachable,
9860
9861 .type_int_signed,
9862 .type_int_unsigned,
9863 .type_array_big,
9864 .type_array_small,
9865 .type_vector,
9866 .type_pointer,
9867 .type_slice,
9868 .type_optional,
9869 .type_anyframe,
9870 .type_error_union,
9871 .type_anyerror_union,
9872 .type_error_set,
9873 .type_inferred_error_set,
9874 .type_enum_auto,
9875 .type_enum_explicit,
9876 .type_enum_nonexhaustive,
9877 .type_opaque,
9878 .type_struct,
9879 .type_struct_anon,
9880 .type_struct_packed,
9881 .type_struct_packed_inits,
9882 .type_tuple_anon,
9883 .type_union,
9884 .type_function,
9885 => .type_type,
9886
9887 .undef,
9888 .opt_null,
9889 .only_possible_value,
9890 => @enumFromInt(item.data),
9891
9892 .simple_type, .simple_value => unreachable, // handled via Index above
9893
9894 inline .ptr_decl,
9895 .ptr_comptime_alloc,
9896 .ptr_anon_decl,
9897 .ptr_anon_decl_aligned,
9898 .ptr_comptime_field,
9899 .ptr_int,
9900 .ptr_eu_payload,
9901 .ptr_opt_payload,
9902 .ptr_elem,
9903 .ptr_field,
9904 .ptr_slice,
9905 .opt_payload,
9906 .error_union_payload,
9907 .int_small,
9908 .int_lazy_align,
9909 .int_lazy_size,
9910 .error_set_error,
9911 .error_union_error,
9912 .enum_tag,
9913 .variable,
9914 .extern_func,
9915 .func_decl,
9916 .func_instance,
9917 .func_coerced,
9918 .union_value,
9919 .bytes,
9920 .aggregate,
9921 .repeated,
9922 => |t| {
9923 const extra_list = unwrapped_index.getExtra(ip);
9924 return @enumFromInt(extra_list.view().items(.@"0")[item.data + std.meta.fieldIndex(t.Payload(), "ty").?]);
9925 },
89619926
8962 // Note these are stored in limbs data, not extra data.
8963 .int_positive,
8964 .int_negative,
8965 => ip.limbData(Int, ip.items.items(.data)[@intFromEnum(index)]).ty,
9927 .int_u8 => .u8_type,
9928 .int_u16 => .u16_type,
9929 .int_u32 => .u32_type,
9930 .int_i32 => .i32_type,
9931 .int_usize => .usize_type,
9932
9933 .int_comptime_int_u32,
9934 .int_comptime_int_i32,
9935 => .comptime_int_type,
9936
9937 // Note these are stored in limbs data, not extra data.
9938 .int_positive,
9939 .int_negative,
9940 => {
9941 const limbs_list = ip.getLocalShared(unwrapped_index.tid).getLimbs();
9942 const int: Int = @bitCast(limbs_list.view().items(.@"0")[item.data..][0..Int.limbs_items_len].*);
9943 return int.ty;
9944 },
89669945
8967 .enum_literal => .enum_literal_type,
8968 .float_f16 => .f16_type,
8969 .float_f32 => .f32_type,
8970 .float_f64 => .f64_type,
8971 .float_f80 => .f80_type,
8972 .float_f128 => .f128_type,
9946 .enum_literal => .enum_literal_type,
9947 .float_f16 => .f16_type,
9948 .float_f32 => .f32_type,
9949 .float_f64 => .f64_type,
9950 .float_f80 => .f80_type,
9951 .float_f128 => .f128_type,
89739952
8974 .float_c_longdouble_f80,
8975 .float_c_longdouble_f128,
8976 => .c_longdouble_type,
9953 .float_c_longdouble_f80,
9954 .float_c_longdouble_f128,
9955 => .c_longdouble_type,
89779956
8978 .float_comptime_float => .comptime_float_type,
9957 .float_comptime_float => .comptime_float_type,
89799958
8980 .memoized_call => unreachable,
9959 .memoized_call => unreachable,
9960 };
89819961 },
89829962
89839963 .none => unreachable,
......@@ -9011,64 +9991,79 @@ pub fn aggregateTypeLenIncludingSentinel(ip: *const InternPool, ty: Index) u64 {
90119991}
90129992
90139993pub fn funcTypeReturnType(ip: *const InternPool, ty: Index) Index {
9014 const item = ip.items.get(@intFromEnum(ty));
9015 const child_item = switch (item.tag) {
9016 .type_pointer => ip.items.get(ip.extra.items[
9017 item.data + std.meta.fieldIndex(Tag.TypePointer, "child").?
9018 ]),
9019 .type_function => item,
9994 const unwrapped_ty = ty.unwrap(ip);
9995 const ty_extra = unwrapped_ty.getExtra(ip);
9996 const ty_item = unwrapped_ty.getItem(ip);
9997 const child_extra, const child_item = switch (ty_item.tag) {
9998 .type_pointer => child: {
9999 const child_index: Index = @enumFromInt(ty_extra.view().items(.@"0")[
10000 ty_item.data + std.meta.fieldIndex(Tag.TypePointer, "child").?
10001 ]);
10002 const unwrapped_child = child_index.unwrap(ip);
10003 break :child .{ unwrapped_child.getExtra(ip), unwrapped_child.getItem(ip) };
10004 },
10005 .type_function => .{ ty_extra, ty_item },
902010006 else => unreachable,
902110007 };
902210008 assert(child_item.tag == .type_function);
9023 return @enumFromInt(ip.extra.items[
10009 return @enumFromInt(child_extra.view().items(.@"0")[
902410010 child_item.data + std.meta.fieldIndex(Tag.TypeFunction, "return_type").?
902510011 ]);
902610012}
902710013
902810014pub fn isNoReturn(ip: *const InternPool, ty: Index) bool {
9029 return switch (ty) {
9030 .noreturn_type => true,
9031 else => switch (ip.items.items(.tag)[@intFromEnum(ty)]) {
9032 .type_error_set => ip.extra.items[ip.items.items(.data)[@intFromEnum(ty)] + std.meta.fieldIndex(Tag.ErrorSet, "names_len").?] == 0,
9033 else => false,
10015 switch (ty) {
10016 .noreturn_type => return true,
10017 else => {
10018 const unwrapped_ty = ty.unwrap(ip);
10019 const ty_item = unwrapped_ty.getItem(ip);
10020 return switch (ty_item.tag) {
10021 .type_error_set => unwrapped_ty.getExtra(ip).view().items(.@"0")[ty_item.data + std.meta.fieldIndex(Tag.ErrorSet, "names_len").?] == 0,
10022 else => false,
10023 };
903410024 },
9035 };
10025 }
903610026}
903710027
903810028pub fn isUndef(ip: *const InternPool, val: Index) bool {
9039 return val == .undef or ip.items.items(.tag)[@intFromEnum(val)] == .undef;
10029 return val == .undef or val.unwrap(ip).getTag(ip) == .undef;
904010030}
904110031
904210032pub fn isVariable(ip: *const InternPool, val: Index) bool {
9043 return ip.items.items(.tag)[@intFromEnum(val)] == .variable;
10033 return val.unwrap(ip).getTag(ip) == .variable;
904410034}
904510035
904610036pub fn getBackingDecl(ip: *const InternPool, val: Index) OptionalDeclIndex {
9047 var base = @intFromEnum(val);
10037 var base = val;
904810038 while (true) {
9049 switch (ip.items.items(.tag)[base]) {
9050 .ptr_decl => return @enumFromInt(ip.extra.items[
9051 ip.items.items(.data)[base] + std.meta.fieldIndex(PtrDecl, "decl").?
10039 const unwrapped_base = base.unwrap(ip);
10040 const base_item = unwrapped_base.getItem(ip);
10041 const base_extra_items = unwrapped_base.getExtra(ip).view().items(.@"0");
10042 switch (base_item.tag) {
10043 .ptr_decl => return @enumFromInt(base_extra_items[
10044 base_item.data + std.meta.fieldIndex(PtrDecl, "decl").?
905210045 ]),
905310046 inline .ptr_eu_payload,
905410047 .ptr_opt_payload,
905510048 .ptr_elem,
905610049 .ptr_field,
9057 => |tag| base = ip.extra.items[
9058 ip.items.items(.data)[base] + std.meta.fieldIndex(tag.Payload(), "base").?
9059 ],
9060 .ptr_slice => base = ip.extra.items[
9061 ip.items.items(.data)[base] + std.meta.fieldIndex(PtrSlice, "ptr").?
9062 ],
10050 => |tag| base = @enumFromInt(base_extra_items[
10051 base_item.data + std.meta.fieldIndex(tag.Payload(), "base").?
10052 ]),
10053 .ptr_slice => base = @enumFromInt(base_extra_items[
10054 base_item.data + std.meta.fieldIndex(PtrSlice, "ptr").?
10055 ]),
906310056 else => return .none,
906410057 }
906510058 }
906610059}
906710060
906810061pub fn getBackingAddrTag(ip: *const InternPool, val: Index) ?Key.Ptr.BaseAddr.Tag {
9069 var base = @intFromEnum(val);
10062 var base = val;
907010063 while (true) {
9071 switch (ip.items.items(.tag)[base]) {
10064 const unwrapped_base = base.unwrap(ip);
10065 const base_item = unwrapped_base.getItem(ip);
10066 switch (base_item.tag) {
907210067 .ptr_decl => return .decl,
907310068 .ptr_comptime_alloc => return .comptime_alloc,
907410069 .ptr_anon_decl,
......@@ -9080,12 +10075,12 @@ pub fn getBackingAddrTag(ip: *const InternPool, val: Index) ?Key.Ptr.BaseAddr.Ta
908010075 .ptr_opt_payload,
908110076 .ptr_elem,
908210077 .ptr_field,
9083 => |tag| base = ip.extra.items[
9084 ip.items.items(.data)[base] + std.meta.fieldIndex(tag.Payload(), "base").?
9085 ],
9086 inline .ptr_slice => |tag| base = ip.extra.items[
9087 ip.items.items(.data)[base] + std.meta.fieldIndex(tag.Payload(), "ptr").?
9088 ],
10078 => |tag| base = @enumFromInt(unwrapped_base.getExtra(ip).view().items(.@"0")[
10079 base_item.data + std.meta.fieldIndex(tag.Payload(), "base").?
10080 ]),
10081 inline .ptr_slice => |tag| base = @enumFromInt(unwrapped_base.getExtra(ip).view().items(.@"0")[
10082 base_item.data + std.meta.fieldIndex(tag.Payload(), "ptr").?
10083 ]),
908910084 else => return null,
909010085 }
909110086 }
......@@ -9194,7 +10189,7 @@ pub fn zigTypeTagOrPoison(ip: *const InternPool, index: Index) error{GenericPois
919410189 .empty_struct => unreachable,
919510190 .generic_poison => unreachable,
919610191
9197 _ => switch (ip.items.items(.tag)[@intFromEnum(index)]) {
10192 _ => switch (index.unwrap(ip).getTag(ip)) {
919810193 .removed => unreachable,
919910194
920010195 .type_int_signed,
......@@ -9301,143 +10296,145 @@ pub fn zigTypeTagOrPoison(ip: *const InternPool, index: Index) error{GenericPois
930110296 };
930210297}
930310298
9304pub fn isFuncBody(ip: *const InternPool, i: Index) bool {
9305 assert(i != .none);
9306 return switch (ip.items.items(.tag)[@intFromEnum(i)]) {
10299pub fn isFuncBody(ip: *const InternPool, index: Index) bool {
10300 return switch (index.unwrap(ip).getTag(ip)) {
930710301 .func_decl, .func_instance, .func_coerced => true,
930810302 else => false,
930910303 };
931010304}
931110305
9312pub fn funcAnalysis(ip: *const InternPool, i: Index) *FuncAnalysis {
9313 assert(i != .none);
9314 const item = ip.items.get(@intFromEnum(i));
10306pub fn funcAnalysis(ip: *const InternPool, index: Index) *FuncAnalysis {
10307 const unwrapped_index = index.unwrap(ip);
10308 const extra = unwrapped_index.getExtra(ip);
10309 const item = unwrapped_index.getItem(ip);
931510310 const extra_index = switch (item.tag) {
931610311 .func_decl => item.data + std.meta.fieldIndex(Tag.FuncDecl, "analysis").?,
931710312 .func_instance => item.data + std.meta.fieldIndex(Tag.FuncInstance, "analysis").?,
9318 .func_coerced => i: {
10313 .func_coerced => {
931910314 const extra_index = item.data + std.meta.fieldIndex(Tag.FuncCoerced, "func").?;
9320 const func_index: Index = @enumFromInt(ip.extra.items[extra_index]);
9321 const sub_item = ip.items.get(@intFromEnum(func_index));
9322 break :i switch (sub_item.tag) {
9323 .func_decl => sub_item.data + std.meta.fieldIndex(Tag.FuncDecl, "analysis").?,
9324 .func_instance => sub_item.data + std.meta.fieldIndex(Tag.FuncInstance, "analysis").?,
9325 else => unreachable,
9326 };
10315 const func_index: Index = @enumFromInt(extra.view().items(.@"0")[extra_index]);
10316 const unwrapped_func = func_index.unwrap(ip);
10317 const func_item = unwrapped_func.getItem(ip);
10318 return @ptrCast(&unwrapped_func.getExtra(ip).view().items(.@"0")[
10319 switch (func_item.tag) {
10320 .func_decl => func_item.data + std.meta.fieldIndex(Tag.FuncDecl, "analysis").?,
10321 .func_instance => func_item.data + std.meta.fieldIndex(Tag.FuncInstance, "analysis").?,
10322 else => unreachable,
10323 }
10324 ]);
932710325 },
932810326 else => unreachable,
932910327 };
9330 return @ptrCast(&ip.extra.items[extra_index]);
10328 return @ptrCast(&extra.view().items(.@"0")[extra_index]);
933110329}
933210330
933310331pub fn funcHasInferredErrorSet(ip: *const InternPool, i: Index) bool {
933410332 return funcAnalysis(ip, i).inferred_error_set;
933510333}
933610334
9337pub fn funcZirBodyInst(ip: *const InternPool, i: Index) TrackedInst.Index {
9338 assert(i != .none);
9339 const item = ip.items.get(@intFromEnum(i));
10335pub fn funcZirBodyInst(ip: *const InternPool, index: Index) TrackedInst.Index {
10336 const unwrapped_index = index.unwrap(ip);
10337 const item = unwrapped_index.getItem(ip);
10338 const item_extra = unwrapped_index.getExtra(ip);
934010339 const zir_body_inst_field_index = std.meta.fieldIndex(Tag.FuncDecl, "zir_body_inst").?;
9341 const extra_index = switch (item.tag) {
9342 .func_decl => item.data + zir_body_inst_field_index,
9343 .func_instance => b: {
10340 switch (item.tag) {
10341 .func_decl => return @enumFromInt(item_extra.view().items(.@"0")[item.data + zir_body_inst_field_index]),
10342 .func_instance => {
934410343 const generic_owner_field_index = std.meta.fieldIndex(Tag.FuncInstance, "generic_owner").?;
9345 const func_decl_index = ip.extra.items[item.data + generic_owner_field_index];
9346 assert(ip.items.items(.tag)[func_decl_index] == .func_decl);
9347 break :b ip.items.items(.data)[func_decl_index] + zir_body_inst_field_index;
10344 const func_decl_index: Index = @enumFromInt(item_extra.view().items(.@"0")[item.data + generic_owner_field_index]);
10345 const unwrapped_func_decl = func_decl_index.unwrap(ip);
10346 const func_decl_item = unwrapped_func_decl.getItem(ip);
10347 const func_decl_extra = unwrapped_func_decl.getExtra(ip);
10348 assert(func_decl_item.tag == .func_decl);
10349 return @enumFromInt(func_decl_extra.view().items(.@"0")[func_decl_item.data + zir_body_inst_field_index]);
934810350 },
934910351 .func_coerced => {
9350 const datas = ip.items.items(.data);
9351 const uncoerced_func_index: Index = @enumFromInt(ip.extra.items[
9352 datas[@intFromEnum(i)] + std.meta.fieldIndex(Tag.FuncCoerced, "func").?
10352 const uncoerced_func_index: Index = @enumFromInt(item_extra.view().items(.@"0")[
10353 item.data + std.meta.fieldIndex(Tag.FuncCoerced, "func").?
935310354 ]);
935410355 return ip.funcZirBodyInst(uncoerced_func_index);
935510356 },
935610357 else => unreachable,
9357 };
9358 return @enumFromInt(ip.extra.items[extra_index]);
10358 }
935910359}
936010360
936110361pub fn iesFuncIndex(ip: *const InternPool, ies_index: Index) Index {
9362 assert(ies_index != .none);
9363 const tags = ip.items.items(.tag);
9364 assert(tags[@intFromEnum(ies_index)] == .type_inferred_error_set);
9365 const func_index = ip.items.items(.data)[@intFromEnum(ies_index)];
9366 switch (tags[func_index]) {
10362 const item = ies_index.unwrap(ip).getItem(ip);
10363 assert(item.tag == .type_inferred_error_set);
10364 const func_index: Index = @enumFromInt(item.data);
10365 switch (func_index.unwrap(ip).getTag(ip)) {
936710366 .func_decl, .func_instance => {},
936810367 else => unreachable, // assertion failed
936910368 }
9370 return @enumFromInt(func_index);
10369 return func_index;
937110370}
937210371
937310372/// Returns a mutable pointer to the resolved error set type of an inferred
937410373/// error set function. The returned pointer is invalidated when anything is
937510374/// added to `ip`.
937610375pub fn iesResolved(ip: *const InternPool, ies_index: Index) *Index {
9377 assert(ies_index != .none);
9378 const tags = ip.items.items(.tag);
9379 const datas = ip.items.items(.data);
9380 assert(tags[@intFromEnum(ies_index)] == .type_inferred_error_set);
9381 const func_index = datas[@intFromEnum(ies_index)];
9382 return funcIesResolved(ip, func_index);
10376 const ies_item = ies_index.getItem(ip);
10377 assert(ies_item.tag == .type_inferred_error_set);
10378 return funcIesResolved(ip, ies_item.data);
938310379}
938410380
938510381/// Returns a mutable pointer to the resolved error set type of an inferred
938610382/// error set function. The returned pointer is invalidated when anything is
938710383/// added to `ip`.
938810384pub fn funcIesResolved(ip: *const InternPool, func_index: Index) *Index {
9389 const tags = ip.items.items(.tag);
9390 const datas = ip.items.items(.data);
939110385 assert(funcHasInferredErrorSet(ip, func_index));
9392 const func_start = datas[@intFromEnum(func_index)];
9393 const extra_index = switch (tags[@intFromEnum(func_index)]) {
9394 .func_decl => func_start + @typeInfo(Tag.FuncDecl).Struct.fields.len,
9395 .func_instance => func_start + @typeInfo(Tag.FuncInstance).Struct.fields.len,
9396 .func_coerced => i: {
9397 const uncoerced_func_index: Index = @enumFromInt(ip.extra.items[
9398 func_start + std.meta.fieldIndex(Tag.FuncCoerced, "func").?
10386 const unwrapped_func = func_index.unwrap(ip);
10387 const func_extra = unwrapped_func.getExtra(ip);
10388 const func_item = unwrapped_func.getItem(ip);
10389 const extra_index = switch (func_item.tag) {
10390 .func_decl => func_item.data + @typeInfo(Tag.FuncDecl).Struct.fields.len,
10391 .func_instance => func_item.data + @typeInfo(Tag.FuncInstance).Struct.fields.len,
10392 .func_coerced => {
10393 const uncoerced_func_index: Index = @enumFromInt(func_extra.view().items(.@"0")[
10394 func_item.data + std.meta.fieldIndex(Tag.FuncCoerced, "func").?
10395 ]);
10396 const unwrapped_uncoerced_func = uncoerced_func_index.unwrap(ip);
10397 const uncoerced_func_item = unwrapped_uncoerced_func.getItem(ip);
10398 return @ptrCast(&unwrapped_uncoerced_func.getExtra(ip).view().items(.@"0")[
10399 switch (uncoerced_func_item.tag) {
10400 .func_decl => uncoerced_func_item.data + @typeInfo(Tag.FuncDecl).Struct.fields.len,
10401 .func_instance => uncoerced_func_item.data + @typeInfo(Tag.FuncInstance).Struct.fields.len,
10402 else => unreachable,
10403 }
939910404 ]);
9400 const uncoerced_func_start = datas[@intFromEnum(uncoerced_func_index)];
9401 break :i switch (tags[@intFromEnum(uncoerced_func_index)]) {
9402 .func_decl => uncoerced_func_start + @typeInfo(Tag.FuncDecl).Struct.fields.len,
9403 .func_instance => uncoerced_func_start + @typeInfo(Tag.FuncInstance).Struct.fields.len,
9404 else => unreachable,
9405 };
940610405 },
940710406 else => unreachable,
940810407 };
9409 return @ptrCast(&ip.extra.items[extra_index]);
10408 return @ptrCast(&func_extra.view().items(.@"0")[extra_index]);
941010409}
941110410
9412pub fn funcDeclInfo(ip: *const InternPool, i: Index) Key.Func {
9413 const tags = ip.items.items(.tag);
9414 const datas = ip.items.items(.data);
9415 assert(tags[@intFromEnum(i)] == .func_decl);
9416 return extraFuncDecl(ip, datas[@intFromEnum(i)]);
10411pub fn funcDeclInfo(ip: *const InternPool, index: Index) Key.Func {
10412 const unwrapped_index = index.unwrap(ip);
10413 const item = unwrapped_index.getItem(ip);
10414 assert(item.tag == .func_decl);
10415 return extraFuncDecl(unwrapped_index.tid, unwrapped_index.getExtra(ip), item.data);
941710416}
941810417
9419pub fn funcDeclOwner(ip: *const InternPool, i: Index) DeclIndex {
9420 return funcDeclInfo(ip, i).owner_decl;
10418pub fn funcDeclOwner(ip: *const InternPool, index: Index) DeclIndex {
10419 return funcDeclInfo(ip, index).owner_decl;
942110420}
942210421
9423pub fn funcTypeParamsLen(ip: *const InternPool, i: Index) u32 {
9424 const tags = ip.items.items(.tag);
9425 const datas = ip.items.items(.data);
9426 assert(tags[@intFromEnum(i)] == .type_function);
9427 const start = datas[@intFromEnum(i)];
9428 return ip.extra.items[start + std.meta.fieldIndex(Tag.TypeFunction, "params_len").?];
10422pub fn funcTypeParamsLen(ip: *const InternPool, index: Index) u32 {
10423 const unwrapped_index = index.unwrap(ip);
10424 const extra_list = unwrapped_index.getExtra(ip);
10425 const item = unwrapped_index.getItem(ip);
10426 assert(item.tag == .type_function);
10427 return extra_list.view().items(.@"0")[item.data + std.meta.fieldIndex(Tag.TypeFunction, "params_len").?];
942910428}
943010429
9431pub fn unwrapCoercedFunc(ip: *const InternPool, i: Index) Index {
9432 const tags = ip.items.items(.tag);
9433 return switch (tags[@intFromEnum(i)]) {
9434 .func_coerced => {
9435 const datas = ip.items.items(.data);
9436 return @enumFromInt(ip.extra.items[
9437 datas[@intFromEnum(i)] + std.meta.fieldIndex(Tag.FuncCoerced, "func").?
9438 ]);
9439 },
9440 .func_instance, .func_decl => i,
10430pub fn unwrapCoercedFunc(ip: *const InternPool, index: Index) Index {
10431 const unwrapped_index = index.unwrap(ip);
10432 const item = unwrapped_index.getItem(ip);
10433 return switch (item.tag) {
10434 .func_coerced => @enumFromInt(unwrapped_index.getExtra(ip).view().items(.@"0")[
10435 item.data + std.meta.fieldIndex(Tag.FuncCoerced, "func").?
10436 ]),
10437 .func_instance, .func_decl => index,
944110438 else => unreachable,
944210439 };
944310440}
......@@ -9445,7 +10442,12 @@ pub fn unwrapCoercedFunc(ip: *const InternPool, i: Index) Index {
944510442/// Having resolved a builtin type to a real struct/union/enum (which is now at `resolverd_index`),
944610443/// make `want_index` refer to this type instead. This invalidates `resolved_index`, so must be
944710444/// called only when it is guaranteed that no reference to `resolved_index` exists.
9448pub fn resolveBuiltinType(ip: *InternPool, want_index: Index, resolved_index: Index) void {
10445pub fn resolveBuiltinType(
10446 ip: *InternPool,
10447 tid: Zcu.PerThread.Id,
10448 want_index: Index,
10449 resolved_index: Index,
10450) void {
944910451 assert(@intFromEnum(want_index) >= @intFromEnum(Index.first_type));
945010452 assert(@intFromEnum(want_index) <= @intFromEnum(Index.last_type));
945110453
......@@ -9457,20 +10459,12 @@ pub fn resolveBuiltinType(ip: *InternPool, want_index: Index, resolved_index: In
945710459 (ip.zigTypeTagOrPoison(resolved_index) catch unreachable));
945810460
945910461 // Copy the data
9460 const item = ip.items.get(@intFromEnum(resolved_index));
9461 ip.items.set(@intFromEnum(want_index), item);
9462
9463 if (std.debug.runtime_safety) {
9464 // Make the value unreachable - this is a weird value which will make (incorrect) existing
9465 // references easier to spot
9466 ip.items.set(@intFromEnum(resolved_index), .{
9467 .tag = .simple_value,
9468 .data = @intFromEnum(SimpleValue.@"unreachable"),
9469 });
9470 } else {
9471 // Here we could add the index to a free-list for reuse, but since
9472 // there is so little garbage created this way it's not worth it.
9473 }
10462 const item = resolved_index.unwrap(ip).getItem(ip);
10463 const unwrapped_index = want_index.unwrap(ip);
10464 var items = ip.getLocalShared(unwrapped_index.tid).items.acquire().view().slice();
10465 items.items(.data)[unwrapped_index.index] = item.data;
10466 @atomicStore(Tag, &items.items(.tag)[unwrapped_index.index], item.tag, .release);
10467 ip.remove(tid, resolved_index);
947410468}
947510469
947610470pub fn anonStructFieldTypes(ip: *const InternPool, i: Index) []const Index {
......@@ -9492,17 +10486,19 @@ pub fn structDecl(ip: *const InternPool, i: Index) OptionalDeclIndex {
949210486/// Returns the already-existing field with the same name, if any.
949310487pub fn addFieldName(
949410488 ip: *InternPool,
10489 extra: Local.Extra,
949510490 names_map: MapIndex,
949610491 names_start: u32,
949710492 name: NullTerminatedString,
949810493) ?u32 {
10494 const extra_items = extra.view().items(.@"0");
949910495 const map = &ip.maps.items[@intFromEnum(names_map)];
950010496 const field_index = map.count();
9501 const strings = ip.extra.items[names_start..][0..field_index];
10497 const strings = extra_items[names_start..][0..field_index];
950210498 const adapter: NullTerminatedString.Adapter = .{ .strings = @ptrCast(strings) };
950310499 const gop = map.getOrPutAssumeCapacityAdapted(name, adapter);
950410500 if (gop.found_existing) return @intCast(gop.index);
9505 ip.extra.items[names_start + field_index] = @intFromEnum(name);
10501 extra_items[names_start + field_index] = @intFromEnum(name);
950610502 return null;
950710503}
950810504
src/RangeSet.zig+15-17
......@@ -6,13 +6,11 @@ const InternPool = @import("InternPool.zig");
66const Type = @import("Type.zig");
77const Value = @import("Value.zig");
88const Zcu = @import("Zcu.zig");
9/// Deprecated.
10const Module = Zcu;
119const RangeSet = @This();
1210const LazySrcLoc = Zcu.LazySrcLoc;
1311
12pt: Zcu.PerThread,
1413ranges: std.ArrayList(Range),
15module: *Module,
1614
1715pub const Range = struct {
1816 first: InternPool.Index,
......@@ -20,10 +18,10 @@ pub const Range = struct {
2018 src: LazySrcLoc,
2119};
2220
23pub fn init(allocator: std.mem.Allocator, module: *Module) RangeSet {
21pub fn init(allocator: std.mem.Allocator, pt: Zcu.PerThread) RangeSet {
2422 return .{
23 .pt = pt,
2524 .ranges = std.ArrayList(Range).init(allocator),
26 .module = module,
2725 };
2826}
2927
......@@ -37,8 +35,8 @@ pub fn add(
3735 last: InternPool.Index,
3836 src: LazySrcLoc,
3937) !?LazySrcLoc {
40 const mod = self.module;
41 const ip = &mod.intern_pool;
38 const pt = self.pt;
39 const ip = &pt.zcu.intern_pool;
4240
4341 const ty = ip.typeOf(first);
4442 assert(ty == ip.typeOf(last));
......@@ -47,8 +45,8 @@ pub fn add(
4745 assert(ty == ip.typeOf(range.first));
4846 assert(ty == ip.typeOf(range.last));
4947
50 if (Value.fromInterned(last).compareScalar(.gte, Value.fromInterned(range.first), Type.fromInterned(ty), mod) and
51 Value.fromInterned(first).compareScalar(.lte, Value.fromInterned(range.last), Type.fromInterned(ty), mod))
48 if (Value.fromInterned(last).compareScalar(.gte, Value.fromInterned(range.first), Type.fromInterned(ty), pt) and
49 Value.fromInterned(first).compareScalar(.lte, Value.fromInterned(range.last), Type.fromInterned(ty), pt))
5250 {
5351 return range.src; // They overlap.
5452 }
......@@ -63,20 +61,20 @@ pub fn add(
6361}
6462
6563/// Assumes a and b do not overlap
66fn lessThan(mod: *Module, a: Range, b: Range) bool {
67 const ty = Type.fromInterned(mod.intern_pool.typeOf(a.first));
68 return Value.fromInterned(a.first).compareScalar(.lt, Value.fromInterned(b.first), ty, mod);
64fn lessThan(pt: Zcu.PerThread, a: Range, b: Range) bool {
65 const ty = Type.fromInterned(pt.zcu.intern_pool.typeOf(a.first));
66 return Value.fromInterned(a.first).compareScalar(.lt, Value.fromInterned(b.first), ty, pt);
6967}
7068
7169pub fn spans(self: *RangeSet, first: InternPool.Index, last: InternPool.Index) !bool {
72 const mod = self.module;
73 const ip = &mod.intern_pool;
70 const pt = self.pt;
71 const ip = &pt.zcu.intern_pool;
7472 assert(ip.typeOf(first) == ip.typeOf(last));
7573
7674 if (self.ranges.items.len == 0)
7775 return false;
7876
79 std.mem.sort(Range, self.ranges.items, mod, lessThan);
77 std.mem.sort(Range, self.ranges.items, pt, lessThan);
8078
8179 if (self.ranges.items[0].first != first or
8280 self.ranges.items[self.ranges.items.len - 1].last != last)
......@@ -95,10 +93,10 @@ pub fn spans(self: *RangeSet, first: InternPool.Index, last: InternPool.Index) !
9593 const prev = self.ranges.items[i];
9694
9795 // prev.last + 1 == cur.first
98 try counter.copy(Value.fromInterned(prev.last).toBigInt(&space, mod));
96 try counter.copy(Value.fromInterned(prev.last).toBigInt(&space, pt));
9997 try counter.addScalar(&counter, 1);
10098
101 const cur_start_int = Value.fromInterned(cur.first).toBigInt(&space, mod);
99 const cur_start_int = Value.fromInterned(cur.first).toBigInt(&space, pt);
102100 if (!cur_start_int.eql(counter.toConst())) {
103101 return false;
104102 }
src/Sema.zig+2820-2425
......@@ -5,7 +5,7 @@
55//! Does type checking, comptime control flow, and safety-check generation.
66//! This is the the heart of the Zig compiler.
77
8mod: *Module,
8pt: Zcu.PerThread,
99/// Alias to `mod.gpa`.
1010gpa: Allocator,
1111/// Points to the temporary arena allocator of the Sema.
......@@ -146,7 +146,7 @@ const ComptimeAlloc = struct {
146146fn newComptimeAlloc(sema: *Sema, block: *Block, ty: Type, alignment: Alignment) !ComptimeAllocIndex {
147147 const idx = sema.comptime_allocs.items.len;
148148 try sema.comptime_allocs.append(sema.gpa, .{
149 .val = .{ .interned = try sema.mod.intern(.{ .undef = ty.toIntern() }) },
149 .val = .{ .interned = try sema.pt.intern(.{ .undef = ty.toIntern() }) },
150150 .is_const = false,
151151 .alignment = alignment,
152152 .runtime_index = block.runtime_index,
......@@ -433,7 +433,7 @@ pub const Block = struct {
433433
434434 fn explain(cr: ComptimeReason, sema: *Sema, msg: ?*Module.ErrorMsg) !void {
435435 const parent = msg orelse return;
436 const mod = sema.mod;
436 const pt = sema.pt;
437437 const prefix = "expression is evaluated at comptime because ";
438438 switch (cr) {
439439 .c_import => |ci| {
......@@ -451,7 +451,7 @@ pub const Block = struct {
451451 ret_ty_src,
452452 parent,
453453 prefix ++ "the function returns a comptime-only type '{}'",
454 .{rt.return_ty.fmt(mod)},
454 .{rt.return_ty.fmt(pt)},
455455 );
456456 try sema.explainWhyTypeIsComptime(parent, ret_ty_src, rt.return_ty);
457457 },
......@@ -538,7 +538,7 @@ pub const Block = struct {
538538 }
539539
540540 pub fn wantSafety(block: *const Block) bool {
541 return block.want_safety orelse switch (block.sema.mod.optimizeMode()) {
541 return block.want_safety orelse switch (block.sema.pt.zcu.optimizeMode()) {
542542 .Debug => true,
543543 .ReleaseSafe => true,
544544 .ReleaseFast => false,
......@@ -737,11 +737,12 @@ pub const Block = struct {
737737
738738 fn addCmpVector(block: *Block, lhs: Air.Inst.Ref, rhs: Air.Inst.Ref, cmp_op: std.math.CompareOperator) !Air.Inst.Ref {
739739 const sema = block.sema;
740 const mod = sema.mod;
740 const pt = sema.pt;
741 const mod = pt.zcu;
741742 return block.addInst(.{
742743 .tag = if (block.float_mode == .optimized) .cmp_vector_optimized else .cmp_vector,
743744 .data = .{ .ty_pl = .{
744 .ty = Air.internedToRef((try mod.vectorType(.{
745 .ty = Air.internedToRef((try pt.vectorType(.{
745746 .len = sema.typeOf(lhs).vectorLen(mod),
746747 .child = .bool_type,
747748 })).toIntern()),
......@@ -829,14 +830,14 @@ pub const Block = struct {
829830 }
830831
831832 pub fn ownerModule(block: Block) *Package.Module {
832 const zcu = block.sema.mod;
833 const zcu = block.sema.pt.zcu;
833834 return zcu.namespacePtr(block.namespace).fileScope(zcu).mod;
834835 }
835836
836837 fn trackZir(block: *Block, inst: Zir.Inst.Index) Allocator.Error!InternPool.TrackedInst.Index {
837838 const sema = block.sema;
838839 const gpa = sema.gpa;
839 const zcu = sema.mod;
840 const zcu = sema.pt.zcu;
840841 const ip = &zcu.intern_pool;
841842 const file_index = block.getFileScopeIndex(zcu);
842843 return ip.trackZir(gpa, file_index, inst);
......@@ -992,7 +993,8 @@ fn analyzeBodyInner(
992993
993994 try sema.inst_map.ensureSpaceForInstructions(sema.gpa, body);
994995
995 const zcu = sema.mod;
996 const pt = sema.pt;
997 const zcu = pt.zcu;
996998 const map = &sema.inst_map;
997999 const tags = sema.code.instructions.items(.tag);
9981000 const datas = sema.code.instructions.items(.data);
......@@ -1777,7 +1779,7 @@ fn analyzeBodyInner(
17771779 const err_union_ty = sema.typeOf(err_union);
17781780 if (err_union_ty.zigTypeTag(zcu) != .ErrorUnion) {
17791781 return sema.fail(block, operand_src, "expected error union type, found '{}'", .{
1780 err_union_ty.fmt(zcu),
1782 err_union_ty.fmt(pt),
17811783 });
17821784 }
17831785 const is_non_err = try sema.analyzeIsNonErrComptimeOnly(block, operand_src, err_union);
......@@ -1910,10 +1912,11 @@ pub fn toConstString(
19101912 air_inst: Air.Inst.Ref,
19111913 reason: NeededComptimeReason,
19121914) ![]u8 {
1915 const pt = sema.pt;
19131916 const coerced_inst = try sema.coerce(block, Type.slice_const_u8, air_inst, src);
19141917 const slice_val = try sema.resolveConstDefinedValue(block, src, coerced_inst, reason);
19151918 const arr_val = try sema.derefSliceAsArray(block, src, slice_val, reason);
1916 return arr_val.toAllocatedBytes(arr_val.typeOf(sema.mod), sema.arena, sema.mod);
1919 return arr_val.toAllocatedBytes(arr_val.typeOf(pt.zcu), sema.arena, pt);
19171920}
19181921
19191922pub fn resolveConstStringIntern(
......@@ -1945,7 +1948,8 @@ fn resolveDestType(
19451948 strat: enum { remove_eu_opt, remove_eu, remove_opt },
19461949 builtin_name: []const u8,
19471950) !Type {
1948 const mod = sema.mod;
1951 const pt = sema.pt;
1952 const mod = pt.zcu;
19491953 const remove_eu = switch (strat) {
19501954 .remove_eu_opt, .remove_eu => true,
19511955 .remove_opt => false,
......@@ -2062,7 +2066,8 @@ fn analyzeAsType(
20622066}
20632067
20642068pub fn setupErrorReturnTrace(sema: *Sema, block: *Block, last_arg_index: usize) !void {
2065 const mod = sema.mod;
2069 const pt = sema.pt;
2070 const mod = pt.zcu;
20662071 const comp = mod.comp;
20672072 const gpa = sema.gpa;
20682073 const ip = &mod.intern_pool;
......@@ -2076,24 +2081,24 @@ pub fn setupErrorReturnTrace(sema: *Sema, block: *Block, last_arg_index: usize)
20762081
20772082 // var addrs: [err_return_trace_addr_count]usize = undefined;
20782083 const err_return_trace_addr_count = 32;
2079 const addr_arr_ty = try mod.arrayType(.{
2084 const addr_arr_ty = try pt.arrayType(.{
20802085 .len = err_return_trace_addr_count,
20812086 .child = .usize_type,
20822087 });
2083 const addrs_ptr = try err_trace_block.addTy(.alloc, try mod.singleMutPtrType(addr_arr_ty));
2088 const addrs_ptr = try err_trace_block.addTy(.alloc, try pt.singleMutPtrType(addr_arr_ty));
20842089
20852090 // var st: StackTrace = undefined;
2086 const stack_trace_ty = try mod.getBuiltinType("StackTrace");
2087 try stack_trace_ty.resolveFields(mod);
2088 const st_ptr = try err_trace_block.addTy(.alloc, try mod.singleMutPtrType(stack_trace_ty));
2091 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
2092 try stack_trace_ty.resolveFields(pt);
2093 const st_ptr = try err_trace_block.addTy(.alloc, try pt.singleMutPtrType(stack_trace_ty));
20892094
20902095 // st.instruction_addresses = &addrs;
2091 const instruction_addresses_field_name = try ip.getOrPutString(gpa, "instruction_addresses", .no_embedded_nulls);
2096 const instruction_addresses_field_name = try ip.getOrPutString(gpa, pt.tid, "instruction_addresses", .no_embedded_nulls);
20922097 const addr_field_ptr = try sema.fieldPtr(&err_trace_block, src, st_ptr, instruction_addresses_field_name, src, true);
20932098 try sema.storePtr2(&err_trace_block, src, addr_field_ptr, src, addrs_ptr, src, .store);
20942099
20952100 // st.index = 0;
2096 const index_field_name = try ip.getOrPutString(gpa, "index", .no_embedded_nulls);
2101 const index_field_name = try ip.getOrPutString(gpa, pt.tid, "index", .no_embedded_nulls);
20972102 const index_field_ptr = try sema.fieldPtr(&err_trace_block, src, st_ptr, index_field_name, src, true);
20982103 try sema.storePtr2(&err_trace_block, src, index_field_ptr, src, .zero_usize, src, .store);
20992104
......@@ -2109,7 +2114,7 @@ pub fn setupErrorReturnTrace(sema: *Sema, block: *Block, last_arg_index: usize)
21092114fn resolveValue(sema: *Sema, inst: Air.Inst.Ref) CompileError!?Value {
21102115 const val = (try sema.resolveValueAllowVariables(inst)) orelse return null;
21112116 if (val.isGenericPoison()) return error.GenericPoison;
2112 if (sema.mod.intern_pool.isVariable(val.toIntern())) return null;
2117 if (sema.pt.zcu.intern_pool.isVariable(val.toIntern())) return null;
21132118 return val;
21142119}
21152120
......@@ -2133,7 +2138,8 @@ fn resolveDefinedValue(
21332138 src: LazySrcLoc,
21342139 air_ref: Air.Inst.Ref,
21352140) CompileError!?Value {
2136 const mod = sema.mod;
2141 const pt = sema.pt;
2142 const mod = pt.zcu;
21372143 const val = try sema.resolveValue(air_ref) orelse return null;
21382144 if (val.isUndef(mod)) {
21392145 return sema.failWithUseOfUndef(block, src);
......@@ -2150,7 +2156,7 @@ fn resolveConstDefinedValue(
21502156 reason: NeededComptimeReason,
21512157) CompileError!Value {
21522158 const val = try sema.resolveConstValue(block, src, air_ref, reason);
2153 if (val.isUndef(sema.mod)) return sema.failWithUseOfUndef(block, src);
2159 if (val.isUndef(sema.pt.zcu)) return sema.failWithUseOfUndef(block, src);
21542160 return val;
21552161}
21562162
......@@ -2164,7 +2170,7 @@ fn resolveValueResolveLazy(sema: *Sema, inst: Air.Inst.Ref) CompileError!?Value
21642170/// Lazy values are recursively resolved.
21652171fn resolveValueIntable(sema: *Sema, inst: Air.Inst.Ref) CompileError!?Value {
21662172 const val = (try sema.resolveValue(inst)) orelse return null;
2167 if (sema.mod.intern_pool.getBackingAddrTag(val.toIntern())) |addr| switch (addr) {
2173 if (sema.pt.zcu.intern_pool.getBackingAddrTag(val.toIntern())) |addr| switch (addr) {
21682174 .decl, .anon_decl, .comptime_alloc, .comptime_field => return null,
21692175 .int => {},
21702176 .eu_payload, .opt_payload, .arr_elem, .field => unreachable,
......@@ -2174,6 +2180,7 @@ fn resolveValueIntable(sema: *Sema, inst: Air.Inst.Ref) CompileError!?Value {
21742180
21752181/// Returns all InternPool keys representing values, including `variable`, `undef`, and `generic_poison`.
21762182fn resolveValueAllowVariables(sema: *Sema, inst: Air.Inst.Ref) CompileError!?Value {
2183 const pt = sema.pt;
21772184 assert(inst != .none);
21782185 // First section of indexes correspond to a set number of constant values.
21792186 if (@intFromEnum(inst) < InternPool.static_len) {
......@@ -2184,7 +2191,7 @@ fn resolveValueAllowVariables(sema: *Sema, inst: Air.Inst.Ref) CompileError!?Val
21842191 if (try sema.typeHasOnePossibleValue(sema.typeOf(inst))) |opv| {
21852192 if (inst.toInterned()) |ip_index| {
21862193 const val = Value.fromInterned(ip_index);
2187 if (val.getVariable(sema.mod) != null) return val;
2194 if (val.getVariable(pt.zcu) != null) return val;
21882195 }
21892196 return opv;
21902197 }
......@@ -2196,7 +2203,7 @@ fn resolveValueAllowVariables(sema: *Sema, inst: Air.Inst.Ref) CompileError!?Val
21962203 }
21972204 };
21982205 const val = Value.fromInterned(ip_index);
2199 if (val.isPtrToThreadLocal(sema.mod)) return null;
2206 if (val.isPtrToThreadLocal(pt.zcu)) return null;
22002207 return val;
22012208}
22022209
......@@ -2225,7 +2232,7 @@ pub fn resolveFinalDeclValue(
22252232 });
22262233 };
22272234 if (val.isGenericPoison()) return error.GenericPoison;
2228 if (val.canMutateComptimeVarState(sema.mod)) {
2235 if (val.canMutateComptimeVarState(sema.pt.zcu)) {
22292236 return sema.fail(block, src, "global variable contains reference to comptime var", .{});
22302237 }
22312238 return val;
......@@ -2254,19 +2261,20 @@ fn failWithDivideByZero(sema: *Sema, block: *Block, src: LazySrcLoc) CompileErro
22542261}
22552262
22562263fn failWithModRemNegative(sema: *Sema, block: *Block, src: LazySrcLoc, lhs_ty: Type, rhs_ty: Type) CompileError {
2264 const pt = sema.pt;
22572265 return sema.fail(block, src, "remainder division with '{}' and '{}': signed integers and floats must use @rem or @mod", .{
2258 lhs_ty.fmt(sema.mod), rhs_ty.fmt(sema.mod),
2266 lhs_ty.fmt(pt), rhs_ty.fmt(pt),
22592267 });
22602268}
22612269
22622270fn failWithExpectedOptionalType(sema: *Sema, block: *Block, src: LazySrcLoc, non_optional_ty: Type) CompileError {
2263 const mod = sema.mod;
2271 const pt = sema.pt;
22642272 const msg = msg: {
22652273 const msg = try sema.errMsg(src, "expected optional type, found '{}'", .{
2266 non_optional_ty.fmt(mod),
2274 non_optional_ty.fmt(pt),
22672275 });
22682276 errdefer msg.destroy(sema.gpa);
2269 if (non_optional_ty.zigTypeTag(mod) == .ErrorUnion) {
2277 if (non_optional_ty.zigTypeTag(pt.zcu) == .ErrorUnion) {
22702278 try sema.errNote(src, msg, "consider using 'try', 'catch', or 'if'", .{});
22712279 }
22722280 try addDeclaredHereNote(sema, msg, non_optional_ty);
......@@ -2276,14 +2284,14 @@ fn failWithExpectedOptionalType(sema: *Sema, block: *Block, src: LazySrcLoc, non
22762284}
22772285
22782286fn failWithArrayInitNotSupported(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError {
2279 const mod = sema.mod;
2287 const pt = sema.pt;
22802288 const msg = msg: {
22812289 const msg = try sema.errMsg(src, "type '{}' does not support array initialization syntax", .{
2282 ty.fmt(mod),
2290 ty.fmt(pt),
22832291 });
22842292 errdefer msg.destroy(sema.gpa);
2285 if (ty.isSlice(mod)) {
2286 try sema.errNote(src, msg, "inferred array length is specified with an underscore: '[_]{}'", .{ty.elemType2(mod).fmt(mod)});
2293 if (ty.isSlice(pt.zcu)) {
2294 try sema.errNote(src, msg, "inferred array length is specified with an underscore: '[_]{}'", .{ty.elemType2(pt.zcu).fmt(pt)});
22872295 }
22882296 break :msg msg;
22892297 };
......@@ -2291,8 +2299,9 @@ fn failWithArrayInitNotSupported(sema: *Sema, block: *Block, src: LazySrcLoc, ty
22912299}
22922300
22932301fn failWithStructInitNotSupported(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError {
2302 const pt = sema.pt;
22942303 return sema.fail(block, src, "type '{}' does not support struct initialization syntax", .{
2295 ty.fmt(sema.mod),
2304 ty.fmt(pt),
22962305 });
22972306}
22982307
......@@ -2303,17 +2312,19 @@ fn failWithErrorSetCodeMissing(
23032312 dest_err_set_ty: Type,
23042313 src_err_set_ty: Type,
23052314) CompileError {
2315 const pt = sema.pt;
23062316 return sema.fail(block, src, "expected type '{}', found type '{}'", .{
2307 dest_err_set_ty.fmt(sema.mod), src_err_set_ty.fmt(sema.mod),
2317 dest_err_set_ty.fmt(pt), src_err_set_ty.fmt(pt),
23082318 });
23092319}
23102320
23112321fn failWithIntegerOverflow(sema: *Sema, block: *Block, src: LazySrcLoc, int_ty: Type, val: Value, vector_index: usize) CompileError {
2312 const zcu = sema.mod;
2322 const pt = sema.pt;
2323 const zcu = pt.zcu;
23132324 if (int_ty.zigTypeTag(zcu) == .Vector) {
23142325 const msg = msg: {
23152326 const msg = try sema.errMsg(src, "overflow of vector type '{}' with value '{}'", .{
2316 int_ty.fmt(zcu), val.fmtValue(zcu, sema),
2327 int_ty.fmt(pt), val.fmtValue(pt, sema),
23172328 });
23182329 errdefer msg.destroy(sema.gpa);
23192330 try sema.errNote(src, msg, "when computing vector element at index '{d}'", .{vector_index});
......@@ -2322,12 +2333,13 @@ fn failWithIntegerOverflow(sema: *Sema, block: *Block, src: LazySrcLoc, int_ty:
23222333 return sema.failWithOwnedErrorMsg(block, msg);
23232334 }
23242335 return sema.fail(block, src, "overflow of integer type '{}' with value '{}'", .{
2325 int_ty.fmt(zcu), val.fmtValue(zcu, sema),
2336 int_ty.fmt(pt), val.fmtValue(pt, sema),
23262337 });
23272338}
23282339
23292340fn failWithInvalidComptimeFieldStore(sema: *Sema, block: *Block, init_src: LazySrcLoc, container_ty: Type, field_index: usize) CompileError {
2330 const mod = sema.mod;
2341 const pt = sema.pt;
2342 const mod = pt.zcu;
23312343 const msg = msg: {
23322344 const msg = try sema.errMsg(init_src, "value stored in comptime field does not match the default value of the field", .{});
23332345 errdefer msg.destroy(sema.gpa);
......@@ -2358,14 +2370,15 @@ fn failWithInvalidFieldAccess(
23582370 object_ty: Type,
23592371 field_name: InternPool.NullTerminatedString,
23602372) CompileError {
2361 const mod = sema.mod;
2373 const pt = sema.pt;
2374 const mod = pt.zcu;
23622375 const inner_ty = if (object_ty.isSinglePointer(mod)) object_ty.childType(mod) else object_ty;
23632376
23642377 if (inner_ty.zigTypeTag(mod) == .Optional) opt: {
23652378 const child_ty = inner_ty.optionalChild(mod);
23662379 if (!typeSupportsFieldAccess(mod, child_ty, field_name)) break :opt;
23672380 const msg = msg: {
2368 const msg = try sema.errMsg(src, "optional type '{}' does not support field access", .{object_ty.fmt(sema.mod)});
2381 const msg = try sema.errMsg(src, "optional type '{}' does not support field access", .{object_ty.fmt(pt)});
23692382 errdefer msg.destroy(sema.gpa);
23702383 try sema.errNote(src, msg, "consider using '.?', 'orelse', or 'if'", .{});
23712384 break :msg msg;
......@@ -2375,14 +2388,14 @@ fn failWithInvalidFieldAccess(
23752388 const child_ty = inner_ty.errorUnionPayload(mod);
23762389 if (!typeSupportsFieldAccess(mod, child_ty, field_name)) break :err;
23772390 const msg = msg: {
2378 const msg = try sema.errMsg(src, "error union type '{}' does not support field access", .{object_ty.fmt(sema.mod)});
2391 const msg = try sema.errMsg(src, "error union type '{}' does not support field access", .{object_ty.fmt(pt)});
23792392 errdefer msg.destroy(sema.gpa);
23802393 try sema.errNote(src, msg, "consider using 'try', 'catch', or 'if'", .{});
23812394 break :msg msg;
23822395 };
23832396 return sema.failWithOwnedErrorMsg(block, msg);
23842397 }
2385 return sema.fail(block, src, "type '{}' does not support field access", .{object_ty.fmt(sema.mod)});
2398 return sema.fail(block, src, "type '{}' does not support field access", .{object_ty.fmt(pt)});
23862399}
23872400
23882401fn typeSupportsFieldAccess(mod: *const Module, ty: Type, field_name: InternPool.NullTerminatedString) bool {
......@@ -2408,7 +2421,8 @@ fn failWithComptimeErrorRetTrace(
24082421 src: LazySrcLoc,
24092422 name: InternPool.NullTerminatedString,
24102423) CompileError {
2411 const mod = sema.mod;
2424 const pt = sema.pt;
2425 const mod = pt.zcu;
24122426 const msg = msg: {
24132427 const msg = try sema.errMsg(src, "caught unexpected error '{}'", .{name.fmt(&mod.intern_pool)});
24142428 errdefer msg.destroy(sema.gpa);
......@@ -2430,7 +2444,7 @@ pub fn errNote(
24302444 comptime format: []const u8,
24312445 args: anytype,
24322446) error{OutOfMemory}!void {
2433 return sema.mod.errNote(src, parent, format, args);
2447 return sema.pt.zcu.errNote(src, parent, format, args);
24342448}
24352449
24362450fn addFieldErrNote(
......@@ -2442,8 +2456,7 @@ fn addFieldErrNote(
24422456 args: anytype,
24432457) !void {
24442458 @setCold(true);
2445 const zcu = sema.mod;
2446 const type_src = container_ty.srcLocOrNull(zcu) orelse return;
2459 const type_src = container_ty.srcLocOrNull(sema.pt.zcu) orelse return;
24472460 const field_src: LazySrcLoc = .{
24482461 .base_node_inst = type_src.base_node_inst,
24492462 .offset = .{ .container_field_name = @intCast(field_index) },
......@@ -2480,7 +2493,7 @@ pub fn fail(
24802493pub fn failWithOwnedErrorMsg(sema: *Sema, block: ?*Block, err_msg: *Module.ErrorMsg) error{ AnalysisFail, OutOfMemory } {
24812494 @setCold(true);
24822495 const gpa = sema.gpa;
2483 const mod = sema.mod;
2496 const mod = sema.pt.zcu;
24842497 const ip = &mod.intern_pool;
24852498
24862499 if (build_options.enable_debug_extensions and mod.comp.debug_compile_errors) {
......@@ -2545,8 +2558,7 @@ fn reparentOwnedErrorMsg(
25452558 comptime format: []const u8,
25462559 args: anytype,
25472560) !void {
2548 const mod = sema.mod;
2549 const msg_str = try std.fmt.allocPrint(mod.gpa, format, args);
2561 const msg_str = try std.fmt.allocPrint(sema.gpa, format, args);
25502562
25512563 const orig_notes = msg.notes.len;
25522564 msg.notes = try sema.gpa.realloc(msg.notes, orig_notes + 1);
......@@ -2630,16 +2642,16 @@ fn analyzeAsInt(
26302642 dest_ty: Type,
26312643 reason: NeededComptimeReason,
26322644) !u64 {
2633 const mod = sema.mod;
26342645 const coerced = try sema.coerce(block, dest_ty, air_ref, src);
26352646 const val = try sema.resolveConstDefinedValue(block, src, coerced, reason);
2636 return (try val.getUnsignedIntAdvanced(mod, .sema)).?;
2647 return (try val.getUnsignedIntAdvanced(sema.pt, .sema)).?;
26372648}
26382649
26392650/// Given a ZIR extra index which points to a list of `Zir.Inst.Capture`,
26402651/// resolves this into a list of `InternPool.CaptureValue` allocated by `arena`.
26412652fn getCaptures(sema: *Sema, block: *Block, type_src: LazySrcLoc, extra_index: usize, captures_len: u32) ![]InternPool.CaptureValue {
2642 const zcu = sema.mod;
2653 const pt = sema.pt;
2654 const zcu = pt.zcu;
26432655 const ip = &zcu.intern_pool;
26442656 const parent_captures: InternPool.CaptureValue.Slice = zcu.namespacePtr(block.namespace).getType(zcu).getCaptures(zcu);
26452657
......@@ -2679,6 +2691,7 @@ fn getCaptures(sema: *Sema, block: *Block, type_src: LazySrcLoc, extra_index: us
26792691 .decl_val => |str| capture: {
26802692 const decl_name = try ip.getOrPutString(
26812693 sema.gpa,
2694 pt.tid,
26822695 sema.code.nullTerminatedString(str),
26832696 .no_embedded_nulls,
26842697 );
......@@ -2688,6 +2701,7 @@ fn getCaptures(sema: *Sema, block: *Block, type_src: LazySrcLoc, extra_index: us
26882701 .decl_ref => |str| capture: {
26892702 const decl_name = try ip.getOrPutString(
26902703 sema.gpa,
2704 pt.tid,
26912705 sema.code.nullTerminatedString(str),
26922706 .no_embedded_nulls,
26932707 );
......@@ -2703,10 +2717,11 @@ fn getCaptures(sema: *Sema, block: *Block, type_src: LazySrcLoc, extra_index: us
27032717/// Given an `InternPool.WipNamespaceType` or `InternPool.WipEnumType`, apply
27042718/// `sema.builtin_type_target_index` to it if necessary.
27052719fn wrapWipTy(sema: *Sema, wip_ty: anytype) @TypeOf(wip_ty) {
2720 const pt = sema.pt;
27062721 if (sema.builtin_type_target_index == .none) return wip_ty;
27072722 var new = wip_ty;
27082723 new.index = sema.builtin_type_target_index;
2709 sema.mod.intern_pool.resolveBuiltinType(new.index, wip_ty.index);
2724 pt.zcu.intern_pool.resolveBuiltinType(pt.tid, new.index, wip_ty.index);
27102725 return new;
27112726}
27122727
......@@ -2714,7 +2729,8 @@ fn wrapWipTy(sema: *Sema, wip_ty: anytype) @TypeOf(wip_ty) {
27142729/// considered outdated on this update. If so, remove it from the pool
27152730/// and return `true`.
27162731fn maybeRemoveOutdatedType(sema: *Sema, ty: InternPool.Index) !bool {
2717 const zcu = sema.mod;
2732 const pt = sema.pt;
2733 const zcu = pt.zcu;
27182734
27192735 if (!zcu.comp.debug_incremental) return false;
27202736
......@@ -2725,7 +2741,7 @@ fn maybeRemoveOutdatedType(sema: *Sema, ty: InternPool.Index) !bool {
27252741 if (!was_outdated) return false;
27262742 _ = zcu.outdated_ready.swapRemove(decl_as_depender);
27272743 zcu.intern_pool.removeDependenciesForDepender(zcu.gpa, AnalUnit.wrap(.{ .decl = decl_index }));
2728 zcu.intern_pool.remove(ty);
2744 zcu.intern_pool.remove(pt.tid, ty);
27292745 zcu.declPtr(decl_index).analysis = .dependency_failure;
27302746 try zcu.markDependeeOutdated(.{ .decl_val = decl_index });
27312747 return true;
......@@ -2737,7 +2753,8 @@ fn zirStructDecl(
27372753 extended: Zir.Inst.Extended.InstData,
27382754 inst: Zir.Inst.Index,
27392755) CompileError!Air.Inst.Ref {
2740 const mod = sema.mod;
2756 const pt = sema.pt;
2757 const mod = pt.zcu;
27412758 const gpa = sema.gpa;
27422759 const ip = &mod.intern_pool;
27432760 const small: Zir.Inst.StructDecl.Small = @bitCast(extended.small);
......@@ -2796,14 +2813,14 @@ fn zirStructDecl(
27962813 .captures = captures,
27972814 } },
27982815 };
2799 const wip_ty = sema.wrapWipTy(switch (try ip.getStructType(gpa, struct_init)) {
2816 const wip_ty = sema.wrapWipTy(switch (try ip.getStructType(gpa, pt.tid, struct_init)) {
28002817 .existing => |ty| wip: {
28012818 if (!try sema.maybeRemoveOutdatedType(ty)) return Air.internedToRef(ty);
2802 break :wip (try ip.getStructType(gpa, struct_init)).wip;
2819 break :wip (try ip.getStructType(gpa, pt.tid, struct_init)).wip;
28032820 },
28042821 .wip => |wip| wip,
28052822 });
2806 errdefer wip_ty.cancel(ip);
2823 errdefer wip_ty.cancel(ip, pt.tid);
28072824
28082825 const new_decl_index = try sema.createAnonymousDeclTypeNamed(
28092826 block,
......@@ -2815,7 +2832,7 @@ fn zirStructDecl(
28152832 mod.declPtr(new_decl_index).owns_tv = true;
28162833 errdefer mod.abortAnonDecl(new_decl_index);
28172834
2818 if (sema.mod.comp.debug_incremental) {
2835 if (pt.zcu.comp.debug_incremental) {
28192836 try ip.addDependency(
28202837 sema.gpa,
28212838 AnalUnit.wrap(.{ .decl = new_decl_index }),
......@@ -2833,10 +2850,10 @@ fn zirStructDecl(
28332850
28342851 if (new_namespace_index.unwrap()) |ns| {
28352852 const decls = sema.code.bodySlice(extra_index, decls_len);
2836 try mod.scanNamespace(ns, decls, mod.declPtr(new_decl_index));
2853 try pt.scanNamespace(ns, decls, mod.declPtr(new_decl_index));
28372854 }
28382855
2839 try mod.finalizeAnonDecl(new_decl_index);
2856 try pt.finalizeAnonDecl(new_decl_index);
28402857 try mod.comp.work_queue.writeItem(.{ .resolve_type_fully = wip_ty.index });
28412858 try sema.addReferenceEntry(src, AnalUnit.wrap(.{ .decl = new_decl_index }));
28422859 return Air.internedToRef(wip_ty.finish(ip, new_decl_index, new_namespace_index));
......@@ -2850,7 +2867,8 @@ fn createAnonymousDeclTypeNamed(
28502867 anon_prefix: []const u8,
28512868 inst: ?Zir.Inst.Index,
28522869) !InternPool.DeclIndex {
2853 const zcu = sema.mod;
2870 const pt = sema.pt;
2871 const zcu = pt.zcu;
28542872 const ip = &zcu.intern_pool;
28552873 const gpa = sema.gpa;
28562874 const namespace = block.namespace;
......@@ -2892,7 +2910,7 @@ fn createAnonymousDeclTypeNamed(
28922910 // some tooling may not support very long symbol names.
28932911 try writer.print("{}", .{Value.fmtValueFull(.{
28942912 .val = arg_val,
2895 .mod = zcu,
2913 .pt = pt,
28962914 .opt_sema = sema,
28972915 .depth = 1,
28982916 })});
......@@ -2904,7 +2922,7 @@ fn createAnonymousDeclTypeNamed(
29042922 };
29052923
29062924 try writer.writeByte(')');
2907 const name = try ip.getOrPutString(gpa, buf.items, .no_embedded_nulls);
2925 const name = try ip.getOrPutString(gpa, pt.tid, buf.items, .no_embedded_nulls);
29082926 try zcu.initNewAnonDecl(new_decl_index, val, name);
29092927 return new_decl_index;
29102928 },
......@@ -2916,7 +2934,7 @@ fn createAnonymousDeclTypeNamed(
29162934 .dbg_var_ptr, .dbg_var_val => {
29172935 if (zir_data[i].str_op.operand != ref) continue;
29182936
2919 const name = try ip.getOrPutStringFmt(gpa, "{}.{s}", .{
2937 const name = try ip.getOrPutStringFmt(gpa, pt.tid, "{}.{s}", .{
29202938 block.type_name_ctx.fmt(ip), zir_data[i].str_op.getStr(sema.code),
29212939 }, .no_embedded_nulls);
29222940 try zcu.initNewAnonDecl(new_decl_index, val, name);
......@@ -2937,7 +2955,7 @@ fn createAnonymousDeclTypeNamed(
29372955 // This name is also used as the key in the parent namespace so it cannot be
29382956 // renamed.
29392957
2940 const name = ip.getOrPutStringFmt(gpa, "{}__{s}_{d}", .{
2958 const name = ip.getOrPutStringFmt(gpa, pt.tid, "{}__{s}_{d}", .{
29412959 block.type_name_ctx.fmt(ip), anon_prefix, @intFromEnum(new_decl_index),
29422960 }, .no_embedded_nulls) catch unreachable;
29432961 try zcu.initNewAnonDecl(new_decl_index, val, name);
......@@ -2953,7 +2971,8 @@ fn zirEnumDecl(
29532971 const tracy = trace(@src());
29542972 defer tracy.end();
29552973
2956 const mod = sema.mod;
2974 const pt = sema.pt;
2975 const mod = pt.zcu;
29572976 const gpa = sema.gpa;
29582977 const ip = &mod.intern_pool;
29592978 const small: Zir.Inst.EnumDecl.Small = @bitCast(extended.small);
......@@ -3026,10 +3045,10 @@ fn zirEnumDecl(
30263045 .captures = captures,
30273046 } },
30283047 };
3029 const wip_ty = sema.wrapWipTy(switch (try ip.getEnumType(gpa, enum_init)) {
3048 const wip_ty = sema.wrapWipTy(switch (try ip.getEnumType(gpa, pt.tid, enum_init)) {
30303049 .existing => |ty| wip: {
30313050 if (!try sema.maybeRemoveOutdatedType(ty)) return Air.internedToRef(ty);
3032 break :wip (try ip.getEnumType(gpa, enum_init)).wip;
3051 break :wip (try ip.getEnumType(gpa, pt.tid, enum_init)).wip;
30333052 },
30343053 .wip => |wip| wip,
30353054 });
......@@ -3038,7 +3057,7 @@ fn zirEnumDecl(
30383057 // have finished constructing the type and are in the process of analyzing it.
30393058 var done = false;
30403059
3041 errdefer if (!done) wip_ty.cancel(ip);
3060 errdefer if (!done) wip_ty.cancel(ip, pt.tid);
30423061
30433062 const new_decl_index = try sema.createAnonymousDeclTypeNamed(
30443063 block,
......@@ -3051,7 +3070,7 @@ fn zirEnumDecl(
30513070 new_decl.owns_tv = true;
30523071 errdefer if (!done) mod.abortAnonDecl(new_decl_index);
30533072
3054 if (sema.mod.comp.debug_incremental) {
3073 if (pt.zcu.comp.debug_incremental) {
30553074 try mod.intern_pool.addDependency(
30563075 gpa,
30573076 AnalUnit.wrap(.{ .decl = new_decl_index }),
......@@ -3068,7 +3087,7 @@ fn zirEnumDecl(
30683087 errdefer if (!done) if (new_namespace_index.unwrap()) |ns| mod.destroyNamespace(ns);
30693088
30703089 if (new_namespace_index.unwrap()) |ns| {
3071 try mod.scanNamespace(ns, decls, new_decl);
3090 try pt.scanNamespace(ns, decls, new_decl);
30723091 }
30733092
30743093 // We've finished the initial construction of this type, and are about to perform analysis.
......@@ -3118,21 +3137,21 @@ fn zirEnumDecl(
31183137 if (tag_type_ref != .none) {
31193138 const ty = try sema.resolveType(&enum_block, tag_ty_src, tag_type_ref);
31203139 if (ty.zigTypeTag(mod) != .Int and ty.zigTypeTag(mod) != .ComptimeInt) {
3121 return sema.fail(&enum_block, tag_ty_src, "expected integer tag type, found '{}'", .{ty.fmt(sema.mod)});
3140 return sema.fail(&enum_block, tag_ty_src, "expected integer tag type, found '{}'", .{ty.fmt(pt)});
31223141 }
31233142 break :ty ty;
31243143 } else if (fields_len == 0) {
3125 break :ty try mod.intType(.unsigned, 0);
3144 break :ty try pt.intType(.unsigned, 0);
31263145 } else {
31273146 const bits = std.math.log2_int_ceil(usize, fields_len);
3128 break :ty try mod.intType(.unsigned, bits);
3147 break :ty try pt.intType(.unsigned, bits);
31293148 }
31303149 };
31313150
31323151 wip_ty.setTagTy(ip, int_tag_ty.toIntern());
31333152
31343153 if (small.nonexhaustive and int_tag_ty.toIntern() != .comptime_int_type) {
3135 if (fields_len > 1 and std.math.log2_int(u64, fields_len) == int_tag_ty.bitSize(mod)) {
3154 if (fields_len > 1 and std.math.log2_int(u64, fields_len) == int_tag_ty.bitSize(pt)) {
31363155 return sema.fail(block, src, "non-exhaustive enum specifies every value", .{});
31373156 }
31383157 }
......@@ -3153,7 +3172,7 @@ fn zirEnumDecl(
31533172 const field_name_zir = sema.code.nullTerminatedString(field_name_index);
31543173 extra_index += 2; // field name, doc comment
31553174
3156 const field_name = try mod.intern_pool.getOrPutString(gpa, field_name_zir, .no_embedded_nulls);
3175 const field_name = try mod.intern_pool.getOrPutString(gpa, pt.tid, field_name_zir, .no_embedded_nulls);
31573176
31583177 const value_src: LazySrcLoc = .{
31593178 .base_node_inst = tracked_inst,
......@@ -3171,7 +3190,7 @@ fn zirEnumDecl(
31713190 .needed_comptime_reason = "enum tag value must be comptime-known",
31723191 });
31733192 if (!(try sema.intFitsInType(last_tag_val.?, int_tag_ty, null))) break :overflow true;
3174 last_tag_val = try mod.getCoerced(last_tag_val.?, int_tag_ty);
3193 last_tag_val = try pt.getCoerced(last_tag_val.?, int_tag_ty);
31753194 if (wip_ty.nextField(&mod.intern_pool, field_name, last_tag_val.?.toIntern())) |conflict| {
31763195 assert(conflict.kind == .value); // AstGen validated names are unique
31773196 const other_field_src: LazySrcLoc = .{
......@@ -3179,7 +3198,7 @@ fn zirEnumDecl(
31793198 .offset = .{ .container_field_value = conflict.prev_field_idx },
31803199 };
31813200 const msg = msg: {
3182 const msg = try sema.errMsg(value_src, "enum tag value {} already taken", .{last_tag_val.?.fmtValue(sema.mod, sema)});
3201 const msg = try sema.errMsg(value_src, "enum tag value {} already taken", .{last_tag_val.?.fmtValue(pt, sema)});
31833202 errdefer msg.destroy(gpa);
31843203 try sema.errNote(other_field_src, msg, "other occurrence here", .{});
31853204 break :msg msg;
......@@ -3190,9 +3209,9 @@ fn zirEnumDecl(
31903209 } else if (any_values) overflow: {
31913210 var overflow: ?usize = null;
31923211 last_tag_val = if (last_tag_val) |val|
3193 try sema.intAdd(val, try mod.intValue(int_tag_ty, 1), int_tag_ty, &overflow)
3212 try sema.intAdd(val, try pt.intValue(int_tag_ty, 1), int_tag_ty, &overflow)
31943213 else
3195 try mod.intValue(int_tag_ty, 0);
3214 try pt.intValue(int_tag_ty, 0);
31963215 if (overflow != null) break :overflow true;
31973216 if (wip_ty.nextField(&mod.intern_pool, field_name, last_tag_val.?.toIntern())) |conflict| {
31983217 assert(conflict.kind == .value); // AstGen validated names are unique
......@@ -3201,7 +3220,7 @@ fn zirEnumDecl(
32013220 .offset = .{ .container_field_value = conflict.prev_field_idx },
32023221 };
32033222 const msg = msg: {
3204 const msg = try sema.errMsg(value_src, "enum tag value {} already taken", .{last_tag_val.?.fmtValue(sema.mod, sema)});
3223 const msg = try sema.errMsg(value_src, "enum tag value {} already taken", .{last_tag_val.?.fmtValue(pt, sema)});
32053224 errdefer msg.destroy(gpa);
32063225 try sema.errNote(other_field_src, msg, "other occurrence here", .{});
32073226 break :msg msg;
......@@ -3211,21 +3230,21 @@ fn zirEnumDecl(
32113230 break :overflow false;
32123231 } else overflow: {
32133232 assert(wip_ty.nextField(&mod.intern_pool, field_name, .none) == null);
3214 last_tag_val = try mod.intValue(Type.comptime_int, field_i);
3233 last_tag_val = try pt.intValue(Type.comptime_int, field_i);
32153234 if (!try sema.intFitsInType(last_tag_val.?, int_tag_ty, null)) break :overflow true;
3216 last_tag_val = try mod.getCoerced(last_tag_val.?, int_tag_ty);
3235 last_tag_val = try pt.getCoerced(last_tag_val.?, int_tag_ty);
32173236 break :overflow false;
32183237 };
32193238
32203239 if (tag_overflow) {
32213240 const msg = try sema.errMsg(value_src, "enumeration value '{}' too large for type '{}'", .{
3222 last_tag_val.?.fmtValue(mod, sema), int_tag_ty.fmt(mod),
3241 last_tag_val.?.fmtValue(pt, sema), int_tag_ty.fmt(pt),
32233242 });
32243243 return sema.failWithOwnedErrorMsg(block, msg);
32253244 }
32263245 }
32273246
3228 try mod.finalizeAnonDecl(new_decl_index);
3247 try pt.finalizeAnonDecl(new_decl_index);
32293248 return Air.internedToRef(wip_ty.index);
32303249}
32313250
......@@ -3238,7 +3257,8 @@ fn zirUnionDecl(
32383257 const tracy = trace(@src());
32393258 defer tracy.end();
32403259
3241 const mod = sema.mod;
3260 const pt = sema.pt;
3261 const mod = pt.zcu;
32423262 const gpa = sema.gpa;
32433263 const ip = &mod.intern_pool;
32443264 const small: Zir.Inst.UnionDecl.Small = @bitCast(extended.small);
......@@ -3298,14 +3318,14 @@ fn zirUnionDecl(
32983318 .captures = captures,
32993319 } },
33003320 };
3301 const wip_ty = sema.wrapWipTy(switch (try ip.getUnionType(gpa, union_init)) {
3321 const wip_ty = sema.wrapWipTy(switch (try ip.getUnionType(gpa, pt.tid, union_init)) {
33023322 .existing => |ty| wip: {
33033323 if (!try sema.maybeRemoveOutdatedType(ty)) return Air.internedToRef(ty);
3304 break :wip (try ip.getUnionType(gpa, union_init)).wip;
3324 break :wip (try ip.getUnionType(gpa, pt.tid, union_init)).wip;
33053325 },
33063326 .wip => |wip| wip,
33073327 });
3308 errdefer wip_ty.cancel(ip);
3328 errdefer wip_ty.cancel(ip, pt.tid);
33093329
33103330 const new_decl_index = try sema.createAnonymousDeclTypeNamed(
33113331 block,
......@@ -3317,7 +3337,7 @@ fn zirUnionDecl(
33173337 mod.declPtr(new_decl_index).owns_tv = true;
33183338 errdefer mod.abortAnonDecl(new_decl_index);
33193339
3320 if (sema.mod.comp.debug_incremental) {
3340 if (pt.zcu.comp.debug_incremental) {
33213341 try mod.intern_pool.addDependency(
33223342 gpa,
33233343 AnalUnit.wrap(.{ .decl = new_decl_index }),
......@@ -3335,10 +3355,10 @@ fn zirUnionDecl(
33353355
33363356 if (new_namespace_index.unwrap()) |ns| {
33373357 const decls = sema.code.bodySlice(extra_index, decls_len);
3338 try mod.scanNamespace(ns, decls, mod.declPtr(new_decl_index));
3358 try pt.scanNamespace(ns, decls, mod.declPtr(new_decl_index));
33393359 }
33403360
3341 try mod.finalizeAnonDecl(new_decl_index);
3361 try pt.finalizeAnonDecl(new_decl_index);
33423362 try mod.comp.work_queue.writeItem(.{ .resolve_type_fully = wip_ty.index });
33433363 try sema.addReferenceEntry(src, AnalUnit.wrap(.{ .decl = new_decl_index }));
33443364 return Air.internedToRef(wip_ty.finish(ip, new_decl_index, new_namespace_index));
......@@ -3353,7 +3373,8 @@ fn zirOpaqueDecl(
33533373 const tracy = trace(@src());
33543374 defer tracy.end();
33553375
3356 const mod = sema.mod;
3376 const pt = sema.pt;
3377 const mod = pt.zcu;
33573378 const gpa = sema.gpa;
33583379 const ip = &mod.intern_pool;
33593380
......@@ -3387,14 +3408,14 @@ fn zirOpaqueDecl(
33873408 } },
33883409 };
33893410 // No `wrapWipTy` needed as no std.builtin types are opaque.
3390 const wip_ty = switch (try ip.getOpaqueType(gpa, opaque_init)) {
3411 const wip_ty = switch (try ip.getOpaqueType(gpa, pt.tid, opaque_init)) {
33913412 .existing => |ty| wip: {
33923413 if (!try sema.maybeRemoveOutdatedType(ty)) return Air.internedToRef(ty);
3393 break :wip (try ip.getOpaqueType(gpa, opaque_init)).wip;
3414 break :wip (try ip.getOpaqueType(gpa, pt.tid, opaque_init)).wip;
33943415 },
33953416 .wip => |wip| wip,
33963417 };
3397 errdefer wip_ty.cancel(ip);
3418 errdefer wip_ty.cancel(ip, pt.tid);
33983419
33993420 const new_decl_index = try sema.createAnonymousDeclTypeNamed(
34003421 block,
......@@ -3406,7 +3427,7 @@ fn zirOpaqueDecl(
34063427 mod.declPtr(new_decl_index).owns_tv = true;
34073428 errdefer mod.abortAnonDecl(new_decl_index);
34083429
3409 if (sema.mod.comp.debug_incremental) {
3430 if (pt.zcu.comp.debug_incremental) {
34103431 try ip.addDependency(
34113432 gpa,
34123433 AnalUnit.wrap(.{ .decl = new_decl_index }),
......@@ -3423,10 +3444,10 @@ fn zirOpaqueDecl(
34233444
34243445 if (new_namespace_index.unwrap()) |ns| {
34253446 const decls = sema.code.bodySlice(extra_index, decls_len);
3426 try mod.scanNamespace(ns, decls, mod.declPtr(new_decl_index));
3447 try pt.scanNamespace(ns, decls, mod.declPtr(new_decl_index));
34273448 }
34283449
3429 try mod.finalizeAnonDecl(new_decl_index);
3450 try pt.finalizeAnonDecl(new_decl_index);
34303451
34313452 return Air.internedToRef(wip_ty.finish(ip, new_decl_index, new_namespace_index));
34323453}
......@@ -3438,7 +3459,8 @@ fn zirErrorSetDecl(
34383459 const tracy = trace(@src());
34393460 defer tracy.end();
34403461
3441 const mod = sema.mod;
3462 const pt = sema.pt;
3463 const mod = pt.zcu;
34423464 const gpa = sema.gpa;
34433465 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
34443466 const extra = sema.code.extraData(Zir.Inst.ErrorSetDecl, inst_data.payload_index);
......@@ -3451,26 +3473,28 @@ fn zirErrorSetDecl(
34513473 while (extra_index < extra_index_end) : (extra_index += 2) { // +2 to skip over doc_string
34523474 const name_index: Zir.NullTerminatedString = @enumFromInt(sema.code.extra[extra_index]);
34533475 const name = sema.code.nullTerminatedString(name_index);
3454 const name_ip = try mod.intern_pool.getOrPutString(gpa, name, .no_embedded_nulls);
3476 const name_ip = try mod.intern_pool.getOrPutString(gpa, pt.tid, name, .no_embedded_nulls);
34553477 _ = try mod.getErrorValue(name_ip);
34563478 const result = names.getOrPutAssumeCapacity(name_ip);
34573479 assert(!result.found_existing); // verified in AstGen
34583480 }
34593481
3460 return Air.internedToRef((try mod.errorSetFromUnsortedNames(names.keys())).toIntern());
3482 return Air.internedToRef((try pt.errorSetFromUnsortedNames(names.keys())).toIntern());
34613483}
34623484
34633485fn zirRetPtr(sema: *Sema, block: *Block) CompileError!Air.Inst.Ref {
34643486 const tracy = trace(@src());
34653487 defer tracy.end();
34663488
3489 const pt = sema.pt;
3490
34673491 if (block.is_comptime or try sema.typeRequiresComptime(sema.fn_ret_ty)) {
3468 try sema.fn_ret_ty.resolveFields(sema.mod);
3492 try sema.fn_ret_ty.resolveFields(pt);
34693493 return sema.analyzeComptimeAlloc(block, sema.fn_ret_ty, .none);
34703494 }
34713495
3472 const target = sema.mod.getTarget();
3473 const ptr_type = try sema.mod.ptrTypeSema(.{
3496 const target = pt.zcu.getTarget();
3497 const ptr_type = try pt.ptrTypeSema(.{
34743498 .child = sema.fn_ret_ty.toIntern(),
34753499 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
34763500 });
......@@ -3511,7 +3535,8 @@ fn ensureResultUsed(
35113535 ty: Type,
35123536 src: LazySrcLoc,
35133537) CompileError!void {
3514 const mod = sema.mod;
3538 const pt = sema.pt;
3539 const mod = pt.zcu;
35153540 switch (ty.zigTypeTag(mod)) {
35163541 .Void, .NoReturn => return,
35173542 .ErrorSet => return sema.fail(block, src, "error set is ignored", .{}),
......@@ -3526,7 +3551,7 @@ fn ensureResultUsed(
35263551 },
35273552 else => {
35283553 const msg = msg: {
3529 const msg = try sema.errMsg(src, "value of type '{}' ignored", .{ty.fmt(sema.mod)});
3554 const msg = try sema.errMsg(src, "value of type '{}' ignored", .{ty.fmt(pt)});
35303555 errdefer msg.destroy(sema.gpa);
35313556 try sema.errNote(src, msg, "all non-void values must be used", .{});
35323557 try sema.errNote(src, msg, "to discard the value, assign it to '_'", .{});
......@@ -3541,7 +3566,8 @@ fn zirEnsureResultNonError(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
35413566 const tracy = trace(@src());
35423567 defer tracy.end();
35433568
3544 const mod = sema.mod;
3569 const pt = sema.pt;
3570 const mod = pt.zcu;
35453571 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
35463572 const operand = try sema.resolveInst(inst_data.operand);
35473573 const src = block.nodeOffset(inst_data.src_node);
......@@ -3565,7 +3591,8 @@ fn zirEnsureErrUnionPayloadVoid(sema: *Sema, block: *Block, inst: Zir.Inst.Index
35653591 const tracy = trace(@src());
35663592 defer tracy.end();
35673593
3568 const mod = sema.mod;
3594 const pt = sema.pt;
3595 const mod = pt.zcu;
35693596 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
35703597 const src = block.nodeOffset(inst_data.src_node);
35713598 const operand = try sema.resolveInst(inst_data.operand);
......@@ -3604,12 +3631,13 @@ fn indexablePtrLen(
36043631 src: LazySrcLoc,
36053632 object: Air.Inst.Ref,
36063633) CompileError!Air.Inst.Ref {
3607 const mod = sema.mod;
3634 const pt = sema.pt;
3635 const mod = pt.zcu;
36083636 const object_ty = sema.typeOf(object);
36093637 const is_pointer_to = object_ty.isSinglePointer(mod);
36103638 const indexable_ty = if (is_pointer_to) object_ty.childType(mod) else object_ty;
36113639 try checkIndexable(sema, block, src, indexable_ty);
3612 const field_name = try mod.intern_pool.getOrPutString(sema.gpa, "len", .no_embedded_nulls);
3640 const field_name = try mod.intern_pool.getOrPutString(sema.gpa, pt.tid, "len", .no_embedded_nulls);
36133641 return sema.fieldVal(block, src, object, field_name, src);
36143642}
36153643
......@@ -3619,11 +3647,12 @@ fn indexablePtrLenOrNone(
36193647 src: LazySrcLoc,
36203648 operand: Air.Inst.Ref,
36213649) CompileError!Air.Inst.Ref {
3622 const mod = sema.mod;
3650 const pt = sema.pt;
3651 const mod = pt.zcu;
36233652 const operand_ty = sema.typeOf(operand);
36243653 try checkMemOperand(sema, block, src, operand_ty);
36253654 if (operand_ty.ptrSize(mod) == .Many) return .none;
3626 const field_name = try mod.intern_pool.getOrPutString(sema.gpa, "len", .no_embedded_nulls);
3655 const field_name = try mod.intern_pool.getOrPutString(sema.gpa, pt.tid, "len", .no_embedded_nulls);
36273656 return sema.fieldVal(block, src, operand, field_name, src);
36283657}
36293658
......@@ -3632,6 +3661,7 @@ fn zirAllocExtended(
36323661 block: *Block,
36333662 extended: Zir.Inst.Extended.InstData,
36343663) CompileError!Air.Inst.Ref {
3664 const pt = sema.pt;
36353665 const gpa = sema.gpa;
36363666 const extra = sema.code.extraData(Zir.Inst.AllocExtended, extended.operand);
36373667 const ty_src = block.src(.{ .node_offset_var_decl_ty = extra.data.src_node });
......@@ -3673,9 +3703,9 @@ fn zirAllocExtended(
36733703 if (!small.is_const) {
36743704 try sema.validateVarType(block, ty_src, var_ty, false);
36753705 }
3676 const target = sema.mod.getTarget();
3677 try var_ty.resolveLayout(sema.mod);
3678 const ptr_type = try sema.mod.ptrTypeSema(.{
3706 const target = pt.zcu.getTarget();
3707 try var_ty.resolveLayout(pt);
3708 const ptr_type = try sema.pt.ptrTypeSema(.{
36793709 .child = var_ty.toIntern(),
36803710 .flags = .{
36813711 .alignment = alignment,
......@@ -3717,7 +3747,8 @@ fn zirAllocComptime(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr
37173747}
37183748
37193749fn zirMakePtrConst(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
3720 const mod = sema.mod;
3750 const pt = sema.pt;
3751 const mod = pt.zcu;
37213752 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
37223753 const alloc = try sema.resolveInst(inst_data.operand);
37233754 const alloc_ty = sema.typeOf(alloc);
......@@ -3749,7 +3780,7 @@ fn zirMakePtrConst(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
37493780 assert(ptr.byte_offset == 0);
37503781 const alloc_index = ptr.base_addr.comptime_alloc;
37513782 const ct_alloc = sema.getComptimeAlloc(alloc_index);
3752 const interned = try ct_alloc.val.intern(mod, sema.arena);
3783 const interned = try ct_alloc.val.intern(pt, sema.arena);
37533784 if (interned.canMutateComptimeVarState(mod)) {
37543785 // Preserve the comptime alloc, just make the pointer const.
37553786 ct_alloc.val = .{ .interned = interned.toIntern() };
......@@ -3757,7 +3788,7 @@ fn zirMakePtrConst(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
37573788 return sema.makePtrConst(block, alloc);
37583789 } else {
37593790 // Promote the constant to an anon decl.
3760 const new_mut_ptr = Air.internedToRef(try mod.intern(.{ .ptr = .{
3791 const new_mut_ptr = Air.internedToRef(try pt.intern(.{ .ptr = .{
37613792 .ty = alloc_ty.toIntern(),
37623793 .base_addr = .{ .anon_decl = .{
37633794 .val = interned.toIntern(),
......@@ -3778,7 +3809,7 @@ fn zirMakePtrConst(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
37783809 // The value was initialized through RLS, so we didn't detect the runtime condition earlier.
37793810 // TODO: source location of runtime control flow
37803811 const init_src = block.src(.{ .node_offset_bin_rhs = inst_data.src_node });
3781 return sema.fail(block, init_src, "value with comptime-only type '{}' depends on runtime control flow", .{elem_ty.fmt(mod)});
3812 return sema.fail(block, init_src, "value with comptime-only type '{}' depends on runtime control flow", .{elem_ty.fmt(pt)});
37823813 }
37833814
37843815 // This is a runtime value.
......@@ -3788,7 +3819,8 @@ fn zirMakePtrConst(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
37883819/// If `alloc` is an inferred allocation, `resolved_inferred_ty` is taken to be its resolved
37893820/// type. Otherwise, it may be `null`, and the type will be inferred from `alloc`.
37903821fn resolveComptimeKnownAllocPtr(sema: *Sema, block: *Block, alloc: Air.Inst.Ref, resolved_alloc_ty: ?Type) CompileError!?InternPool.Index {
3791 const zcu = sema.mod;
3822 const pt = sema.pt;
3823 const zcu = pt.zcu;
37923824
37933825 const alloc_ty = resolved_alloc_ty orelse sema.typeOf(alloc);
37943826 const ptr_info = alloc_ty.ptrInfo(zcu);
......@@ -3831,7 +3863,7 @@ fn resolveComptimeKnownAllocPtr(sema: *Sema, block: *Block, alloc: Air.Inst.Ref,
38313863
38323864 const ct_alloc = try sema.newComptimeAlloc(block, elem_ty, ptr_info.flags.alignment);
38333865
3834 const alloc_ptr = try zcu.intern(.{ .ptr = .{
3866 const alloc_ptr = try pt.intern(.{ .ptr = .{
38353867 .ty = alloc_ty.toIntern(),
38363868 .base_addr = .{ .comptime_alloc = ct_alloc },
38373869 .byte_offset = 0,
......@@ -3909,7 +3941,7 @@ fn resolveComptimeKnownAllocPtr(sema: *Sema, block: *Block, alloc: Air.Inst.Ref,
39093941 const idx_val = (try sema.resolveValue(data.rhs)).?;
39103942 break :blk .{
39113943 data.lhs,
3912 .{ .elem = try idx_val.toUnsignedIntSema(zcu) },
3944 .{ .elem = try idx_val.toUnsignedIntSema(pt) },
39133945 };
39143946 },
39153947 .bitcast => .{
......@@ -3935,32 +3967,32 @@ fn resolveComptimeKnownAllocPtr(sema: *Sema, block: *Block, alloc: Air.Inst.Ref,
39353967 };
39363968 const new_ptr_ty = tmp_air.typeOfIndex(air_ptr, &zcu.intern_pool).toIntern();
39373969 const new_ptr = switch (method) {
3938 .same_addr => try zcu.intern_pool.getCoerced(sema.gpa, decl_parent_ptr, new_ptr_ty),
3970 .same_addr => try zcu.intern_pool.getCoerced(sema.gpa, pt.tid, decl_parent_ptr, new_ptr_ty),
39393971 .opt_payload => ptr: {
39403972 // Set the optional to non-null at comptime.
39413973 // If the payload is OPV, we must use that value instead of undef.
39423974 const opt_ty = Value.fromInterned(decl_parent_ptr).typeOf(zcu).childType(zcu);
39433975 const payload_ty = opt_ty.optionalChild(zcu);
3944 const payload_val = try sema.typeHasOnePossibleValue(payload_ty) orelse try zcu.undefValue(payload_ty);
3945 const opt_val = try zcu.intern(.{ .opt = .{
3976 const payload_val = try sema.typeHasOnePossibleValue(payload_ty) orelse try pt.undefValue(payload_ty);
3977 const opt_val = try pt.intern(.{ .opt = .{
39463978 .ty = opt_ty.toIntern(),
39473979 .val = payload_val.toIntern(),
39483980 } });
39493981 try sema.storePtrVal(block, LazySrcLoc.unneeded, Value.fromInterned(decl_parent_ptr), Value.fromInterned(opt_val), opt_ty);
3950 break :ptr (try Value.fromInterned(decl_parent_ptr).ptrOptPayload(zcu)).toIntern();
3982 break :ptr (try Value.fromInterned(decl_parent_ptr).ptrOptPayload(pt)).toIntern();
39513983 },
39523984 .eu_payload => ptr: {
39533985 // Set the error union to non-error at comptime.
39543986 // If the payload is OPV, we must use that value instead of undef.
39553987 const eu_ty = Value.fromInterned(decl_parent_ptr).typeOf(zcu).childType(zcu);
39563988 const payload_ty = eu_ty.errorUnionPayload(zcu);
3957 const payload_val = try sema.typeHasOnePossibleValue(payload_ty) orelse try zcu.undefValue(payload_ty);
3958 const eu_val = try zcu.intern(.{ .error_union = .{
3989 const payload_val = try sema.typeHasOnePossibleValue(payload_ty) orelse try pt.undefValue(payload_ty);
3990 const eu_val = try pt.intern(.{ .error_union = .{
39593991 .ty = eu_ty.toIntern(),
39603992 .val = .{ .payload = payload_val.toIntern() },
39613993 } });
39623994 try sema.storePtrVal(block, LazySrcLoc.unneeded, Value.fromInterned(decl_parent_ptr), Value.fromInterned(eu_val), eu_ty);
3963 break :ptr (try Value.fromInterned(decl_parent_ptr).ptrEuPayload(zcu)).toIntern();
3995 break :ptr (try Value.fromInterned(decl_parent_ptr).ptrEuPayload(pt)).toIntern();
39643996 },
39653997 .field => |idx| ptr: {
39663998 const maybe_union_ty = Value.fromInterned(decl_parent_ptr).typeOf(zcu).childType(zcu);
......@@ -3969,14 +4001,14 @@ fn resolveComptimeKnownAllocPtr(sema: *Sema, block: *Block, alloc: Air.Inst.Ref,
39694001 // If the payload is OPV, there will not be a payload store, so we store that value.
39704002 // Otherwise, there will be a payload store to process later, so undef will suffice.
39714003 const payload_ty = Type.fromInterned(union_obj.field_types.get(&zcu.intern_pool)[idx]);
3972 const payload_val = try sema.typeHasOnePossibleValue(payload_ty) orelse try zcu.undefValue(payload_ty);
3973 const tag_val = try zcu.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), idx);
3974 const store_val = try zcu.unionValue(maybe_union_ty, tag_val, payload_val);
4004 const payload_val = try sema.typeHasOnePossibleValue(payload_ty) orelse try pt.undefValue(payload_ty);
4005 const tag_val = try pt.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), idx);
4006 const store_val = try pt.unionValue(maybe_union_ty, tag_val, payload_val);
39754007 try sema.storePtrVal(block, LazySrcLoc.unneeded, Value.fromInterned(decl_parent_ptr), store_val, maybe_union_ty);
39764008 }
3977 break :ptr (try Value.fromInterned(decl_parent_ptr).ptrField(idx, zcu)).toIntern();
4009 break :ptr (try Value.fromInterned(decl_parent_ptr).ptrField(idx, pt)).toIntern();
39784010 },
3979 .elem => |idx| (try Value.fromInterned(decl_parent_ptr).ptrElem(idx, zcu)).toIntern(),
4011 .elem => |idx| (try Value.fromInterned(decl_parent_ptr).ptrElem(idx, pt)).toIntern(),
39804012 };
39814013 try ptr_mapping.put(air_ptr, new_ptr);
39824014 }
......@@ -4020,7 +4052,8 @@ fn finishResolveComptimeKnownAllocPtr(
40204052 alloc_inst: Air.Inst.Index,
40214053 comptime_info: MaybeComptimeAlloc,
40224054) CompileError!?InternPool.Index {
4023 const zcu = sema.mod;
4055 const pt = sema.pt;
4056 const zcu = pt.zcu;
40244057
40254058 // We're almost done - we have the resolved comptime value. We just need to
40264059 // eliminate the now-dead runtime instructions.
......@@ -4041,19 +4074,19 @@ fn finishResolveComptimeKnownAllocPtr(
40414074
40424075 if (Value.fromInterned(result_val).canMutateComptimeVarState(zcu)) {
40434076 const alloc_index = existing_comptime_alloc orelse a: {
4044 const idx = try sema.newComptimeAlloc(block, alloc_ty.childType(zcu), alloc_ty.ptrAlignment(zcu));
4077 const idx = try sema.newComptimeAlloc(block, alloc_ty.childType(zcu), alloc_ty.ptrAlignment(pt));
40454078 const alloc = sema.getComptimeAlloc(idx);
40464079 alloc.val = .{ .interned = result_val };
40474080 break :a idx;
40484081 };
40494082 sema.getComptimeAlloc(alloc_index).is_const = true;
4050 return try zcu.intern(.{ .ptr = .{
4083 return try pt.intern(.{ .ptr = .{
40514084 .ty = alloc_ty.toIntern(),
40524085 .base_addr = .{ .comptime_alloc = alloc_index },
40534086 .byte_offset = 0,
40544087 } });
40554088 } else {
4056 return try zcu.intern(.{ .ptr = .{
4089 return try pt.intern(.{ .ptr = .{
40574090 .ty = alloc_ty.toIntern(),
40584091 .base_addr = .{ .anon_decl = .{
40594092 .orig_ty = alloc_ty.toIntern(),
......@@ -4065,9 +4098,9 @@ fn finishResolveComptimeKnownAllocPtr(
40654098}
40664099
40674100fn makePtrTyConst(sema: *Sema, ptr_ty: Type) CompileError!Type {
4068 var ptr_info = ptr_ty.ptrInfo(sema.mod);
4101 var ptr_info = ptr_ty.ptrInfo(sema.pt.zcu);
40694102 ptr_info.flags.is_const = true;
4070 return sema.mod.ptrTypeSema(ptr_info);
4103 return sema.pt.ptrTypeSema(ptr_info);
40714104}
40724105
40734106fn makePtrConst(sema: *Sema, block: *Block, alloc: Air.Inst.Ref) CompileError!Air.Inst.Ref {
......@@ -4076,7 +4109,7 @@ fn makePtrConst(sema: *Sema, block: *Block, alloc: Air.Inst.Ref) CompileError!Ai
40764109
40774110 // Detect if a comptime value simply needs to have its type changed.
40784111 if (try sema.resolveValue(alloc)) |val| {
4079 return Air.internedToRef((try sema.mod.getCoerced(val, const_ptr_ty)).toIntern());
4112 return Air.internedToRef((try sema.pt.getCoerced(val, const_ptr_ty)).toIntern());
40804113 }
40814114
40824115 return block.addBitCast(const_ptr_ty, alloc);
......@@ -4103,14 +4136,16 @@ fn zirAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
41034136 const tracy = trace(@src());
41044137 defer tracy.end();
41054138
4139 const pt = sema.pt;
4140
41064141 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
41074142 const ty_src = block.src(.{ .node_offset_var_decl_ty = inst_data.src_node });
41084143 const var_ty = try sema.resolveType(block, ty_src, inst_data.operand);
41094144 if (block.is_comptime) {
41104145 return sema.analyzeComptimeAlloc(block, var_ty, .none);
41114146 }
4112 const target = sema.mod.getTarget();
4113 const ptr_type = try sema.mod.ptrTypeSema(.{
4147 const target = pt.zcu.getTarget();
4148 const ptr_type = try pt.ptrTypeSema(.{
41144149 .child = var_ty.toIntern(),
41154150 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
41164151 });
......@@ -4125,6 +4160,8 @@ fn zirAllocMut(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
41254160 const tracy = trace(@src());
41264161 defer tracy.end();
41274162
4163 const pt = sema.pt;
4164
41284165 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
41294166 const ty_src = block.src(.{ .node_offset_var_decl_ty = inst_data.src_node });
41304167 const var_ty = try sema.resolveType(block, ty_src, inst_data.operand);
......@@ -4132,8 +4169,8 @@ fn zirAllocMut(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
41324169 return sema.analyzeComptimeAlloc(block, var_ty, .none);
41334170 }
41344171 try sema.validateVarType(block, ty_src, var_ty, false);
4135 const target = sema.mod.getTarget();
4136 const ptr_type = try sema.mod.ptrTypeSema(.{
4172 const target = pt.zcu.getTarget();
4173 const ptr_type = try pt.ptrTypeSema(.{
41374174 .child = var_ty.toIntern(),
41384175 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
41394176 });
......@@ -4181,7 +4218,8 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
41814218 const tracy = trace(@src());
41824219 defer tracy.end();
41834220
4184 const mod = sema.mod;
4221 const pt = sema.pt;
4222 const mod = pt.zcu;
41854223 const gpa = sema.gpa;
41864224 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
41874225 const src = block.nodeOffset(inst_data.src_node);
......@@ -4206,7 +4244,7 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
42064244 .anon_decl => |a| a.val,
42074245 .comptime_alloc => |i| val: {
42084246 const alloc = sema.getComptimeAlloc(i);
4209 break :val (try alloc.val.intern(mod, sema.arena)).toIntern();
4247 break :val (try alloc.val.intern(pt, sema.arena)).toIntern();
42104248 },
42114249 else => unreachable,
42124250 };
......@@ -4232,7 +4270,7 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
42324270 }
42334271 const final_elem_ty = try sema.resolvePeerTypes(block, ty_src, peer_vals, .none);
42344272
4235 const final_ptr_ty = try mod.ptrTypeSema(.{
4273 const final_ptr_ty = try pt.ptrTypeSema(.{
42364274 .child = final_elem_ty.toIntern(),
42374275 .flags = .{
42384276 .alignment = ia1.alignment,
......@@ -4244,7 +4282,7 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
42444282 try sema.validateVarType(block, ty_src, final_elem_ty, false);
42454283 } else if (try sema.resolveComptimeKnownAllocPtr(block, ptr, final_ptr_ty)) |ptr_val| {
42464284 const const_ptr_ty = try sema.makePtrTyConst(final_ptr_ty);
4247 const new_const_ptr = try mod.getCoerced(Value.fromInterned(ptr_val), const_ptr_ty);
4285 const new_const_ptr = try pt.getCoerced(Value.fromInterned(ptr_val), const_ptr_ty);
42484286
42494287 // Remap the ZIR operand to the resolved pointer value
42504288 sema.inst_map.putAssumeCapacity(inst_data.operand.toIndex().?, Air.internedToRef(new_const_ptr.toIntern()));
......@@ -4252,7 +4290,7 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
42524290 // Unless the block is comptime, `alloc_inferred` always produces
42534291 // a runtime constant. The final inferred type needs to be
42544292 // fully resolved so it can be lowered in codegen.
4255 try final_elem_ty.resolveFully(mod);
4293 try final_elem_ty.resolveFully(pt);
42564294
42574295 return;
42584296 }
......@@ -4261,7 +4299,7 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
42614299 // The alloc wasn't comptime-known per the above logic, so the
42624300 // type cannot be comptime-only.
42634301 // TODO: source location of runtime control flow
4264 return sema.fail(block, src, "value with comptime-only type '{}' depends on runtime control flow", .{final_elem_ty.fmt(mod)});
4302 return sema.fail(block, src, "value with comptime-only type '{}' depends on runtime control flow", .{final_elem_ty.fmt(pt)});
42654303 }
42664304
42674305 // Change it to a normal alloc.
......@@ -4318,7 +4356,8 @@ fn zirResolveInferredAlloc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
43184356}
43194357
43204358fn zirForLen(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
4321 const mod = sema.mod;
4359 const pt = sema.pt;
4360 const mod = pt.zcu;
43224361 const gpa = sema.gpa;
43234362 const ip = &mod.intern_pool;
43244363 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
......@@ -4355,7 +4394,7 @@ fn zirForLen(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
43554394 if (!object_ty.isIndexable(mod)) {
43564395 // Instead of using checkIndexable we customize this error.
43574396 const msg = msg: {
4358 const msg = try sema.errMsg(arg_src, "type '{}' is not indexable and not a range", .{object_ty.fmt(sema.mod)});
4397 const msg = try sema.errMsg(arg_src, "type '{}' is not indexable and not a range", .{object_ty.fmt(pt)});
43594398 errdefer msg.destroy(sema.gpa);
43604399 try sema.errNote(arg_src, msg, "for loop operand must be a range, array, slice, tuple, or vector", .{});
43614400
......@@ -4369,7 +4408,7 @@ fn zirForLen(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
43694408 }
43704409 if (!object_ty.indexableHasLen(mod)) continue;
43714410
4372 break :l try sema.fieldVal(block, arg_src, object, try ip.getOrPutString(gpa, "len", .no_embedded_nulls), arg_src);
4411 break :l try sema.fieldVal(block, arg_src, object, try ip.getOrPutString(gpa, pt.tid, "len", .no_embedded_nulls), arg_src);
43734412 };
43744413 const arg_len = try sema.coerce(block, Type.usize, arg_len_uncoerced, arg_src);
43754414 if (len == .none) {
......@@ -4387,10 +4426,10 @@ fn zirForLen(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
43874426 .input_index = len_idx,
43884427 } });
43894428 try sema.errNote(a_src, msg, "length {} here", .{
4390 v.fmtValue(sema.mod, sema),
4429 v.fmtValue(pt, sema),
43914430 });
43924431 try sema.errNote(arg_src, msg, "length {} here", .{
4393 arg_val.fmtValue(sema.mod, sema),
4432 arg_val.fmtValue(pt, sema),
43944433 });
43954434 break :msg msg;
43964435 };
......@@ -4427,7 +4466,7 @@ fn zirForLen(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
44274466 .input_index = i,
44284467 } });
44294468 try sema.errNote(arg_src, msg, "type '{}' has no upper bound", .{
4430 object_ty.fmt(sema.mod),
4469 object_ty.fmt(pt),
44314470 });
44324471 }
44334472 break :msg msg;
......@@ -4453,7 +4492,8 @@ fn zirForLen(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
44534492/// Given a `*E!?T`, returns a (valid) `*T`.
44544493/// May invalidate already-stored payload data.
44554494fn optEuBasePtrInit(sema: *Sema, block: *Block, ptr: Air.Inst.Ref, src: LazySrcLoc) CompileError!Air.Inst.Ref {
4456 const mod = sema.mod;
4495 const pt = sema.pt;
4496 const mod = pt.zcu;
44574497 var base_ptr = ptr;
44584498 while (true) switch (sema.typeOf(base_ptr).childType(mod).zigTypeTag(mod)) {
44594499 .ErrorUnion => base_ptr = try sema.analyzeErrUnionPayloadPtr(block, src, base_ptr, false, true),
......@@ -4471,7 +4511,8 @@ fn zirOptEuBasePtrInit(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Compile
44714511}
44724512
44734513fn zirCoercePtrElemTy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
4474 const mod = sema.mod;
4514 const pt = sema.pt;
4515 const mod = pt.zcu;
44754516 const pl_node = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
44764517 const src = block.nodeOffset(pl_node.src_node);
44774518 const extra = sema.code.extraData(Zir.Inst.Bin, pl_node.payload_index).data;
......@@ -4503,10 +4544,10 @@ fn zirCoercePtrElemTy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileE
45034544 switch (val_ty.zigTypeTag(mod)) {
45044545 .Array, .Vector => {},
45054546 else => if (!val_ty.isTuple(mod)) {
4506 return sema.fail(block, src, "expected array of '{}', found '{}'", .{ elem_ty.fmt(mod), val_ty.fmt(mod) });
4547 return sema.fail(block, src, "expected array of '{}', found '{}'", .{ elem_ty.fmt(pt), val_ty.fmt(pt) });
45074548 },
45084549 }
4509 const want_ty = try mod.arrayType(.{
4550 const want_ty = try pt.arrayType(.{
45104551 .len = val_ty.arrayLen(mod),
45114552 .child = elem_ty.toIntern(),
45124553 .sentinel = if (ptr_ty.sentinel(mod)) |s| s.toIntern() else .none,
......@@ -4522,7 +4563,8 @@ fn zirCoercePtrElemTy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileE
45224563}
45234564
45244565fn zirValidateRefTy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
4525 const mod = sema.mod;
4566 const pt = sema.pt;
4567 const mod = pt.zcu;
45264568 const un_tok = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_tok;
45274569 const src = block.tokenOffset(un_tok.src_tok);
45284570 // In case of GenericPoison, we don't actually have a type, so this will be
......@@ -4538,7 +4580,7 @@ fn zirValidateRefTy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr
45384580 if (ty_operand.isGenericPoison()) return;
45394581 if (ty_operand.optEuBaseType(mod).zigTypeTag(mod) != .Pointer) {
45404582 return sema.failWithOwnedErrorMsg(block, msg: {
4541 const msg = try sema.errMsg(src, "expected type '{}', found pointer", .{ty_operand.fmt(mod)});
4583 const msg = try sema.errMsg(src, "expected type '{}', found pointer", .{ty_operand.fmt(pt)});
45424584 errdefer msg.destroy(sema.gpa);
45434585 try sema.errNote(src, msg, "address-of operator always returns a pointer", .{});
45444586 break :msg msg;
......@@ -4551,7 +4593,8 @@ fn zirValidateArrayInitRefTy(
45514593 block: *Block,
45524594 inst: Zir.Inst.Index,
45534595) CompileError!Air.Inst.Ref {
4554 const mod = sema.mod;
4596 const pt = sema.pt;
4597 const mod = pt.zcu;
45554598 const pl_node = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
45564599 const src = block.nodeOffset(pl_node.src_node);
45574600 const extra = sema.code.extraData(Zir.Inst.ArrayInitRefTy, pl_node.payload_index).data;
......@@ -4565,7 +4608,7 @@ fn zirValidateArrayInitRefTy(
45654608 .ptr_type => |ptr_type| switch (ptr_type.flags.size) {
45664609 .Slice, .Many => {
45674610 // Use array of correct length
4568 const arr_ty = try mod.arrayType(.{
4611 const arr_ty = try pt.arrayType(.{
45694612 .len = extra.elem_count,
45704613 .child = ptr_ty.childType(mod).toIntern(),
45714614 .sentinel = if (ptr_ty.sentinel(mod)) |s| s.toIntern() else .none,
......@@ -4593,7 +4636,8 @@ fn zirValidateArrayInitTy(
45934636 inst: Zir.Inst.Index,
45944637 is_result_ty: bool,
45954638) CompileError!void {
4596 const mod = sema.mod;
4639 const pt = sema.pt;
4640 const mod = pt.zcu;
45974641 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
45984642 const src = block.nodeOffset(inst_data.src_node);
45994643 const ty_src: LazySrcLoc = if (is_result_ty) src else block.src(.{ .node_offset_init_ty = inst_data.src_node });
......@@ -4615,7 +4659,8 @@ fn validateArrayInitTy(
46154659 init_count: u32,
46164660 ty: Type,
46174661) CompileError!void {
4618 const mod = sema.mod;
4662 const pt = sema.pt;
4663 const mod = pt.zcu;
46194664 switch (ty.zigTypeTag(mod)) {
46204665 .Array => {
46214666 const array_len = ty.arrayLen(mod);
......@@ -4636,7 +4681,7 @@ fn validateArrayInitTy(
46364681 return;
46374682 },
46384683 .Struct => if (ty.isTuple(mod)) {
4639 try ty.resolveFields(mod);
4684 try ty.resolveFields(pt);
46404685 const array_len = ty.arrayLen(mod);
46414686 if (init_count > array_len) {
46424687 return sema.fail(block, src, "expected at most {d} tuple fields; found {d}", .{
......@@ -4656,7 +4701,8 @@ fn zirValidateStructInitTy(
46564701 inst: Zir.Inst.Index,
46574702 is_result_ty: bool,
46584703) CompileError!void {
4659 const mod = sema.mod;
4704 const pt = sema.pt;
4705 const mod = pt.zcu;
46604706 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
46614707 const src = block.nodeOffset(inst_data.src_node);
46624708 const ty = sema.resolveType(block, src, inst_data.operand) catch |err| switch (err) {
......@@ -4681,7 +4727,8 @@ fn zirValidatePtrStructInit(
46814727 const tracy = trace(@src());
46824728 defer tracy.end();
46834729
4684 const mod = sema.mod;
4730 const pt = sema.pt;
4731 const mod = pt.zcu;
46854732 const validate_inst = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
46864733 const init_src = block.nodeOffset(validate_inst.src_node);
46874734 const validate_extra = sema.code.extraData(Zir.Inst.Block, validate_inst.payload_index);
......@@ -4716,7 +4763,8 @@ fn validateUnionInit(
47164763 instrs: []const Zir.Inst.Index,
47174764 union_ptr: Air.Inst.Ref,
47184765) CompileError!void {
4719 const mod = sema.mod;
4766 const pt = sema.pt;
4767 const mod = pt.zcu;
47204768 const gpa = sema.gpa;
47214769
47224770 if (instrs.len != 1) {
......@@ -4752,6 +4800,7 @@ fn validateUnionInit(
47524800 const field_ptr_extra = sema.code.extraData(Zir.Inst.Field, field_ptr_data.payload_index).data;
47534801 const field_name = try mod.intern_pool.getOrPutString(
47544802 gpa,
4803 pt.tid,
47554804 sema.code.nullTerminatedString(field_ptr_extra.field_name_start),
47564805 .no_embedded_nulls,
47574806 );
......@@ -4814,7 +4863,7 @@ fn validateUnionInit(
48144863 }
48154864
48164865 const tag_ty = union_ty.unionTagTypeHypothetical(mod);
4817 const tag_val = try mod.enumValueFieldIndex(tag_ty, field_index);
4866 const tag_val = try pt.enumValueFieldIndex(tag_ty, field_index);
48184867 const field_type = union_ty.unionFieldType(tag_val, mod).?;
48194868
48204869 if (try sema.typeHasOnePossibleValue(field_type)) |field_only_value| {
......@@ -4848,7 +4897,7 @@ fn validateUnionInit(
48484897 }
48494898 block.instructions.shrinkRetainingCapacity(block_index);
48504899
4851 const union_val = try mod.intern(.{ .un = .{
4900 const union_val = try pt.intern(.{ .un = .{
48524901 .ty = union_ty.toIntern(),
48534902 .tag = tag_val.toIntern(),
48544903 .val = val.toIntern(),
......@@ -4875,7 +4924,8 @@ fn validateStructInit(
48754924 init_src: LazySrcLoc,
48764925 instrs: []const Zir.Inst.Index,
48774926) CompileError!void {
4878 const mod = sema.mod;
4927 const pt = sema.pt;
4928 const mod = pt.zcu;
48794929 const gpa = sema.gpa;
48804930 const ip = &mod.intern_pool;
48814931
......@@ -4896,6 +4946,7 @@ fn validateStructInit(
48964946 struct_ptr_zir_ref = field_ptr_extra.lhs;
48974947 const field_name = try ip.getOrPutString(
48984948 gpa,
4949 pt.tid,
48994950 sema.code.nullTerminatedString(field_ptr_extra.field_name_start),
49004951 .no_embedded_nulls,
49014952 );
......@@ -4914,7 +4965,7 @@ fn validateStructInit(
49144965 if (block.is_comptime and
49154966 (try sema.resolveDefinedValue(block, init_src, struct_ptr)) != null)
49164967 {
4917 try struct_ty.resolveLayout(mod);
4968 try struct_ty.resolveLayout(pt);
49184969 // In this case the only thing we need to do is evaluate the implicit
49194970 // store instructions for default field values, and report any missing fields.
49204971 // Avoid the cost of the extra machinery for detecting a comptime struct init value.
......@@ -4922,7 +4973,7 @@ fn validateStructInit(
49224973 const i: u32 = @intCast(i_usize);
49234974 if (field_ptr != .none) continue;
49244975
4925 try struct_ty.resolveStructFieldInits(mod);
4976 try struct_ty.resolveStructFieldInits(pt);
49264977 const default_val = struct_ty.structFieldDefaultValue(i, mod);
49274978 if (default_val.toIntern() == .unreachable_value) {
49284979 const field_name = struct_ty.structFieldName(i, mod).unwrap() orelse {
......@@ -4971,7 +5022,7 @@ fn validateStructInit(
49715022 const air_tags = sema.air_instructions.items(.tag);
49725023 const air_datas = sema.air_instructions.items(.data);
49735024
4974 try struct_ty.resolveStructFieldInits(mod);
5025 try struct_ty.resolveStructFieldInits(pt);
49755026
49765027 // We collect the comptime field values in case the struct initialization
49775028 // ends up being comptime-known.
......@@ -5094,7 +5145,7 @@ fn validateStructInit(
50945145 for (block.instructions.items[first_block_index..]) |cur_inst| {
50955146 while (field_ptr_ref == .none and init_index < instrs.len) : (init_index += 1) {
50965147 const field_ty = struct_ty.structFieldType(field_indices[init_index], mod);
5097 if (try field_ty.onePossibleValue(mod)) |_| continue;
5148 if (try field_ty.onePossibleValue(pt)) |_| continue;
50985149 field_ptr_ref = sema.inst_map.get(instrs[init_index]).?;
50995150 }
51005151 switch (air_tags[@intFromEnum(cur_inst)]) {
......@@ -5122,7 +5173,7 @@ fn validateStructInit(
51225173 }
51235174 block.instructions.shrinkRetainingCapacity(block_index);
51245175
5125 const struct_val = try mod.intern(.{ .aggregate = .{
5176 const struct_val = try pt.intern(.{ .aggregate = .{
51265177 .ty = struct_ty.toIntern(),
51275178 .storage = .{ .elems = field_values },
51285179 } });
......@@ -5130,7 +5181,7 @@ fn validateStructInit(
51305181 try sema.storePtr2(block, init_src, struct_ptr, init_src, struct_init, init_src, .store);
51315182 return;
51325183 }
5133 try struct_ty.resolveLayout(mod);
5184 try struct_ty.resolveLayout(pt);
51345185
51355186 // Our task is to insert `store` instructions for all the default field values.
51365187 for (found_fields, 0..) |field_ptr, i| {
......@@ -5152,7 +5203,8 @@ fn zirValidatePtrArrayInit(
51525203 block: *Block,
51535204 inst: Zir.Inst.Index,
51545205) CompileError!void {
5155 const mod = sema.mod;
5206 const pt = sema.pt;
5207 const mod = pt.zcu;
51565208 const validate_inst = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
51575209 const init_src = block.nodeOffset(validate_inst.src_node);
51585210 const validate_extra = sema.code.extraData(Zir.Inst.Block, validate_inst.payload_index);
......@@ -5175,7 +5227,7 @@ fn zirValidatePtrArrayInit(
51755227 var root_msg: ?*Module.ErrorMsg = null;
51765228 errdefer if (root_msg) |msg| msg.destroy(sema.gpa);
51775229
5178 try array_ty.resolveStructFieldInits(mod);
5230 try array_ty.resolveStructFieldInits(pt);
51795231 var i = instrs.len;
51805232 while (i < array_len) : (i += 1) {
51815233 const default_val = array_ty.structFieldDefaultValue(i, mod).toIntern();
......@@ -5218,7 +5270,7 @@ fn zirValidatePtrArrayInit(
52185270 // sentinel-terminated array, the sentinel will not have been populated by
52195271 // any ZIR instructions at comptime; we need to do that here.
52205272 if (array_ty.sentinel(mod)) |sentinel_val| {
5221 const array_len_ref = try mod.intRef(Type.usize, array_len);
5273 const array_len_ref = try pt.intRef(Type.usize, array_len);
52225274 const sentinel_ptr = try sema.elemPtrArray(block, init_src, init_src, array_ptr, init_src, array_len_ref, true, true);
52235275 const sentinel = Air.internedToRef(sentinel_val.toIntern());
52245276 try sema.storePtr2(block, init_src, sentinel_ptr, init_src, sentinel, init_src, .store);
......@@ -5244,8 +5296,8 @@ fn zirValidatePtrArrayInit(
52445296
52455297 if (array_ty.isTuple(mod)) {
52465298 if (array_ty.structFieldIsComptime(i, mod))
5247 try array_ty.resolveStructFieldInits(mod);
5248 if (try array_ty.structFieldValueComptime(mod, i)) |opv| {
5299 try array_ty.resolveStructFieldInits(pt);
5300 if (try array_ty.structFieldValueComptime(pt, i)) |opv| {
52495301 element_vals[i] = opv.toIntern();
52505302 continue;
52515303 }
......@@ -5347,7 +5399,7 @@ fn zirValidatePtrArrayInit(
53475399 }
53485400 block.instructions.shrinkRetainingCapacity(block_index);
53495401
5350 const array_val = try mod.intern(.{ .aggregate = .{
5402 const array_val = try pt.intern(.{ .aggregate = .{
53515403 .ty = array_ty.toIntern(),
53525404 .storage = .{ .elems = element_vals },
53535405 } });
......@@ -5357,18 +5409,19 @@ fn zirValidatePtrArrayInit(
53575409}
53585410
53595411fn zirValidateDeref(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
5360 const mod = sema.mod;
5412 const pt = sema.pt;
5413 const mod = pt.zcu;
53615414 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
53625415 const src = block.nodeOffset(inst_data.src_node);
53635416 const operand = try sema.resolveInst(inst_data.operand);
53645417 const operand_ty = sema.typeOf(operand);
53655418
53665419 if (operand_ty.zigTypeTag(mod) != .Pointer) {
5367 return sema.fail(block, src, "cannot dereference non-pointer type '{}'", .{operand_ty.fmt(mod)});
5420 return sema.fail(block, src, "cannot dereference non-pointer type '{}'", .{operand_ty.fmt(pt)});
53685421 } else switch (operand_ty.ptrSize(mod)) {
53695422 .One, .C => {},
5370 .Many => return sema.fail(block, src, "index syntax required for unknown-length pointer type '{}'", .{operand_ty.fmt(mod)}),
5371 .Slice => return sema.fail(block, src, "index syntax required for slice type '{}'", .{operand_ty.fmt(mod)}),
5423 .Many => return sema.fail(block, src, "index syntax required for unknown-length pointer type '{}'", .{operand_ty.fmt(pt)}),
5424 .Slice => return sema.fail(block, src, "index syntax required for slice type '{}'", .{operand_ty.fmt(pt)}),
53725425 }
53735426
53745427 if ((try sema.typeHasOnePossibleValue(operand_ty.childType(mod))) != null) {
......@@ -5386,7 +5439,7 @@ fn zirValidateDeref(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr
53865439 const msg = try sema.errMsg(
53875440 src,
53885441 "values of type '{}' must be comptime-known, but operand value is runtime-known",
5389 .{elem_ty.fmt(mod)},
5442 .{elem_ty.fmt(pt)},
53905443 );
53915444 errdefer msg.destroy(sema.gpa);
53925445
......@@ -5398,7 +5451,8 @@ fn zirValidateDeref(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErr
53985451}
53995452
54005453fn zirValidateDestructure(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
5401 const mod = sema.mod;
5454 const pt = sema.pt;
5455 const mod = pt.zcu;
54025456 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
54035457 const extra = sema.code.extraData(Zir.Inst.ValidateDestructure, inst_data.payload_index).data;
54045458 const src = block.nodeOffset(inst_data.src_node);
......@@ -5414,7 +5468,7 @@ fn zirValidateDestructure(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Comp
54145468
54155469 if (!can_destructure) {
54165470 return sema.failWithOwnedErrorMsg(block, msg: {
5417 const msg = try sema.errMsg(src, "type '{}' cannot be destructured", .{operand_ty.fmt(mod)});
5471 const msg = try sema.errMsg(src, "type '{}' cannot be destructured", .{operand_ty.fmt(pt)});
54185472 errdefer msg.destroy(sema.gpa);
54195473 try sema.errNote(destructure_src, msg, "result destructured here", .{});
54205474 break :msg msg;
......@@ -5441,7 +5495,8 @@ fn failWithBadMemberAccess(
54415495 field_src: LazySrcLoc,
54425496 field_name: InternPool.NullTerminatedString,
54435497) CompileError {
5444 const mod = sema.mod;
5498 const pt = sema.pt;
5499 const mod = pt.zcu;
54455500 const kw_name = switch (agg_ty.zigTypeTag(mod)) {
54465501 .Union => "union",
54475502 .Struct => "struct",
......@@ -5451,12 +5506,12 @@ fn failWithBadMemberAccess(
54515506 };
54525507 if (agg_ty.getOwnerDeclOrNull(mod)) |some| if (mod.declIsRoot(some)) {
54535508 return sema.fail(block, field_src, "root struct of file '{}' has no member named '{}'", .{
5454 agg_ty.fmt(mod), field_name.fmt(&mod.intern_pool),
5509 agg_ty.fmt(pt), field_name.fmt(&mod.intern_pool),
54555510 });
54565511 };
54575512
54585513 return sema.fail(block, field_src, "{s} '{}' has no member named '{}'", .{
5459 kw_name, agg_ty.fmt(mod), field_name.fmt(&mod.intern_pool),
5514 kw_name, agg_ty.fmt(pt), field_name.fmt(&mod.intern_pool),
54605515 });
54615516}
54625517
......@@ -5468,18 +5523,19 @@ fn failWithBadStructFieldAccess(
54685523 field_src: LazySrcLoc,
54695524 field_name: InternPool.NullTerminatedString,
54705525) CompileError {
5471 const zcu = sema.mod;
5472 const gpa = sema.gpa;
5526 const pt = sema.pt;
5527 const zcu = pt.zcu;
5528 const ip = &zcu.intern_pool;
54735529 const decl = zcu.declPtr(struct_type.decl.unwrap().?);
5474 const fqn = try decl.fullyQualifiedName(zcu);
5530 const fqn = try decl.fullyQualifiedName(pt);
54755531
54765532 const msg = msg: {
54775533 const msg = try sema.errMsg(
54785534 field_src,
54795535 "no field named '{}' in struct '{}'",
5480 .{ field_name.fmt(&zcu.intern_pool), fqn.fmt(&zcu.intern_pool) },
5536 .{ field_name.fmt(ip), fqn.fmt(ip) },
54815537 );
5482 errdefer msg.destroy(gpa);
5538 errdefer msg.destroy(sema.gpa);
54835539 try sema.errNote(struct_ty.srcLoc(zcu), msg, "struct declared here", .{});
54845540 break :msg msg;
54855541 };
......@@ -5494,17 +5550,19 @@ fn failWithBadUnionFieldAccess(
54945550 field_src: LazySrcLoc,
54955551 field_name: InternPool.NullTerminatedString,
54965552) CompileError {
5497 const zcu = sema.mod;
5553 const pt = sema.pt;
5554 const zcu = pt.zcu;
5555 const ip = &zcu.intern_pool;
54985556 const gpa = sema.gpa;
54995557
55005558 const decl = zcu.declPtr(union_obj.decl);
5501 const fqn = try decl.fullyQualifiedName(zcu);
5559 const fqn = try decl.fullyQualifiedName(pt);
55025560
55035561 const msg = msg: {
55045562 const msg = try sema.errMsg(
55055563 field_src,
55065564 "no field named '{}' in union '{}'",
5507 .{ field_name.fmt(&zcu.intern_pool), fqn.fmt(&zcu.intern_pool) },
5565 .{ field_name.fmt(ip), fqn.fmt(ip) },
55085566 );
55095567 errdefer msg.destroy(gpa);
55105568 try sema.errNote(union_ty.srcLoc(zcu), msg, "union declared here", .{});
......@@ -5514,9 +5572,9 @@ fn failWithBadUnionFieldAccess(
55145572}
55155573
55165574fn addDeclaredHereNote(sema: *Sema, parent: *Module.ErrorMsg, decl_ty: Type) !void {
5517 const mod = sema.mod;
5518 const src_loc = decl_ty.srcLocOrNull(mod) orelse return;
5519 const category = switch (decl_ty.zigTypeTag(mod)) {
5575 const zcu = sema.pt.zcu;
5576 const src_loc = decl_ty.srcLocOrNull(zcu) orelse return;
5577 const category = switch (decl_ty.zigTypeTag(zcu)) {
55205578 .Union => "union",
55215579 .Struct => "struct",
55225580 .Enum => "enum",
......@@ -5575,7 +5633,8 @@ fn storeToInferredAllocComptime(
55755633 operand: Air.Inst.Ref,
55765634 iac: *Air.Inst.Data.InferredAllocComptime,
55775635) CompileError!void {
5578 const zcu = sema.mod;
5636 const pt = sema.pt;
5637 const zcu = pt.zcu;
55795638 const operand_ty = sema.typeOf(operand);
55805639 // There will be only one store_to_inferred_ptr because we are running at comptime.
55815640 // The alloc will turn into a Decl or a ComptimeAlloc.
......@@ -5584,7 +5643,7 @@ fn storeToInferredAllocComptime(
55845643 .needed_comptime_reason = "value being stored to a comptime variable must be comptime-known",
55855644 });
55865645 };
5587 const alloc_ty = try zcu.ptrTypeSema(.{
5646 const alloc_ty = try pt.ptrTypeSema(.{
55885647 .child = operand_ty.toIntern(),
55895648 .flags = .{
55905649 .alignment = iac.alignment,
......@@ -5592,7 +5651,7 @@ fn storeToInferredAllocComptime(
55925651 },
55935652 });
55945653 if (iac.is_const and !operand_val.canMutateComptimeVarState(zcu)) {
5595 iac.ptr = try zcu.intern(.{ .ptr = .{
5654 iac.ptr = try pt.intern(.{ .ptr = .{
55965655 .ty = alloc_ty.toIntern(),
55975656 .base_addr = .{ .anon_decl = .{
55985657 .val = operand_val.toIntern(),
......@@ -5603,7 +5662,7 @@ fn storeToInferredAllocComptime(
56035662 } else {
56045663 const alloc_index = try sema.newComptimeAlloc(block, operand_ty, iac.alignment);
56055664 sema.getComptimeAlloc(alloc_index).val = .{ .interned = operand_val.toIntern() };
5606 iac.ptr = try zcu.intern(.{ .ptr = .{
5665 iac.ptr = try pt.intern(.{ .ptr = .{
56075666 .ty = alloc_ty.toIntern(),
56085667 .base_addr = .{ .comptime_alloc = alloc_index },
56095668 .byte_offset = 0,
......@@ -5624,7 +5683,8 @@ fn zirStoreNode(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!v
56245683 const tracy = trace(@src());
56255684 defer tracy.end();
56265685
5627 const mod = sema.mod;
5686 const pt = sema.pt;
5687 const mod = pt.zcu;
56285688 const zir_tags = sema.code.instructions.items(.tag);
56295689 const zir_datas = sema.code.instructions.items(.data);
56305690 const inst_data = zir_datas[@intFromEnum(inst)].pl_node;
......@@ -5662,23 +5722,23 @@ fn zirStoreNode(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!v
56625722fn zirStr(sema: *Sema, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
56635723 const bytes = sema.code.instructions.items(.data)[@intFromEnum(inst)].str.get(sema.code);
56645724 return sema.addStrLit(
5665 try sema.mod.intern_pool.getOrPutString(sema.gpa, bytes, .maybe_embedded_nulls),
5725 try sema.pt.zcu.intern_pool.getOrPutString(sema.gpa, sema.pt.tid, bytes, .maybe_embedded_nulls),
56665726 bytes.len,
56675727 );
56685728}
56695729
56705730fn addNullTerminatedStrLit(sema: *Sema, string: InternPool.NullTerminatedString) CompileError!Air.Inst.Ref {
5671 return sema.addStrLit(string.toString(), string.length(&sema.mod.intern_pool));
5731 return sema.addStrLit(string.toString(), string.length(&sema.pt.zcu.intern_pool));
56725732}
56735733
56745734fn addStrLit(sema: *Sema, string: InternPool.String, len: u64) CompileError!Air.Inst.Ref {
5675 const mod = sema.mod;
5676 const array_ty = try mod.arrayType(.{
5735 const pt = sema.pt;
5736 const array_ty = try pt.arrayType(.{
56775737 .len = len,
56785738 .sentinel = .zero_u8,
56795739 .child = .u8_type,
56805740 });
5681 const val = try mod.intern(.{ .aggregate = .{
5741 const val = try pt.intern(.{ .aggregate = .{
56825742 .ty = array_ty.toIntern(),
56835743 .storage = .{ .bytes = string },
56845744 } });
......@@ -5690,16 +5750,16 @@ fn anonDeclRef(sema: *Sema, val: InternPool.Index) CompileError!Air.Inst.Ref {
56905750}
56915751
56925752fn refValue(sema: *Sema, val: InternPool.Index) CompileError!InternPool.Index {
5693 const mod = sema.mod;
5694 const ptr_ty = (try mod.ptrTypeSema(.{
5695 .child = mod.intern_pool.typeOf(val),
5753 const pt = sema.pt;
5754 const ptr_ty = (try pt.ptrTypeSema(.{
5755 .child = pt.zcu.intern_pool.typeOf(val),
56965756 .flags = .{
56975757 .alignment = .none,
56985758 .is_const = true,
56995759 .address_space = .generic,
57005760 },
57015761 })).toIntern();
5702 return mod.intern(.{ .ptr = .{
5762 return pt.intern(.{ .ptr = .{
57035763 .ty = ptr_ty,
57045764 .base_addr = .{ .anon_decl = .{
57055765 .val = val,
......@@ -5715,7 +5775,7 @@ fn zirInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
57155775 defer tracy.end();
57165776
57175777 const int = sema.code.instructions.items(.data)[@intFromEnum(inst)].int;
5718 return sema.mod.intRef(Type.comptime_int, int);
5778 return sema.pt.intRef(Type.comptime_int, int);
57195779}
57205780
57215781fn zirIntBig(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
......@@ -5723,7 +5783,6 @@ fn zirIntBig(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
57235783 const tracy = trace(@src());
57245784 defer tracy.end();
57255785
5726 const mod = sema.mod;
57275786 const int = sema.code.instructions.items(.data)[@intFromEnum(inst)].str;
57285787 const byte_count = int.len * @sizeOf(std.math.big.Limb);
57295788 const limb_bytes = sema.code.string_bytes[@intFromEnum(int.start)..][0..byte_count];
......@@ -5734,7 +5793,7 @@ fn zirIntBig(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
57345793 const limbs = try sema.arena.alloc(std.math.big.Limb, int.len);
57355794 @memcpy(mem.sliceAsBytes(limbs), limb_bytes);
57365795
5737 return Air.internedToRef((try mod.intValue_big(Type.comptime_int, .{
5796 return Air.internedToRef((try sema.pt.intValue_big(Type.comptime_int, .{
57385797 .limbs = limbs,
57395798 .positive = true,
57405799 })).toIntern());
......@@ -5743,7 +5802,7 @@ fn zirIntBig(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
57435802fn zirFloat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
57445803 _ = block;
57455804 const number = sema.code.instructions.items(.data)[@intFromEnum(inst)].float;
5746 return Air.internedToRef((try sema.mod.floatValue(
5805 return Air.internedToRef((try sema.pt.floatValue(
57475806 Type.comptime_float,
57485807 number,
57495808 )).toIntern());
......@@ -5754,7 +5813,7 @@ fn zirFloat128(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
57545813 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
57555814 const extra = sema.code.extraData(Zir.Inst.Float128, inst_data.payload_index).data;
57565815 const number = extra.get();
5757 return Air.internedToRef((try sema.mod.floatValue(Type.comptime_float, number)).toIntern());
5816 return Air.internedToRef((try sema.pt.floatValue(Type.comptime_float, number)).toIntern());
57585817}
57595818
57605819fn zirCompileError(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
......@@ -5775,10 +5834,11 @@ fn zirCompileLog(
57755834 block: *Block,
57765835 extended: Zir.Inst.Extended.InstData,
57775836) CompileError!Air.Inst.Ref {
5778 const mod = sema.mod;
5837 const pt = sema.pt;
5838 const mod = pt.zcu;
57795839
57805840 var managed = mod.compile_log_text.toManaged(sema.gpa);
5781 defer sema.mod.compile_log_text = managed.moveToUnmanaged();
5841 defer pt.zcu.compile_log_text = managed.moveToUnmanaged();
57825842 const writer = managed.writer();
57835843
57845844 const extra = sema.code.extraData(Zir.Inst.NodeMultiOp, extended.operand);
......@@ -5792,10 +5852,10 @@ fn zirCompileLog(
57925852 const arg_ty = sema.typeOf(arg);
57935853 if (try sema.resolveValueResolveLazy(arg)) |val| {
57945854 try writer.print("@as({}, {})", .{
5795 arg_ty.fmt(mod), val.fmtValue(mod, sema),
5855 arg_ty.fmt(pt), val.fmtValue(pt, sema),
57965856 });
57975857 } else {
5798 try writer.print("@as({}, [runtime value])", .{arg_ty.fmt(mod)});
5858 try writer.print("@as({}, [runtime value])", .{arg_ty.fmt(pt)});
57995859 }
58005860 }
58015861 try writer.print("\n", .{});
......@@ -5835,7 +5895,8 @@ fn zirLoop(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileError
58355895 const tracy = trace(@src());
58365896 defer tracy.end();
58375897
5838 const mod = sema.mod;
5898 const pt = sema.pt;
5899 const mod = pt.zcu;
58395900 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
58405901 const src = parent_block.nodeOffset(inst_data.src_node);
58415902 const extra = sema.code.extraData(Zir.Inst.Block, inst_data.payload_index);
......@@ -5906,7 +5967,8 @@ fn zirCImport(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileEr
59065967 const tracy = trace(@src());
59075968 defer tracy.end();
59085969
5909 const zcu = sema.mod;
5970 const pt = sema.pt;
5971 const zcu = pt.zcu;
59105972 const comp = zcu.comp;
59115973 const gpa = sema.gpa;
59125974 const pl_node = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
......@@ -6002,10 +6064,10 @@ fn zirCImport(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileEr
60026064
60036065 const path_digest = zcu.filePathDigest(result.file_index);
60046066 const root_decl = zcu.fileRootDecl(result.file_index);
6005 zcu.astGenFile(result.file, result.file_index, path_digest, root_decl) catch |err|
6067 pt.astGenFile(result.file, result.file_index, path_digest, root_decl) catch |err|
60066068 return sema.fail(&child_block, src, "C import failed: {s}", .{@errorName(err)});
60076069
6008 try zcu.ensureFileAnalyzed(result.file_index);
6070 try pt.ensureFileAnalyzed(result.file_index);
60096071 const file_root_decl_index = zcu.fileRootDecl(result.file_index).unwrap().?;
60106072 return sema.analyzeDeclVal(parent_block, src, file_root_decl_index);
60116073}
......@@ -6147,7 +6209,8 @@ fn resolveAnalyzedBlock(
61476209 defer tracy.end();
61486210
61496211 const gpa = sema.gpa;
6150 const mod = sema.mod;
6212 const pt = sema.pt;
6213 const mod = pt.zcu;
61516214
61526215 // Blocks must terminate with noreturn instruction.
61536216 assert(child_block.instructions.items.len != 0);
......@@ -6258,7 +6321,7 @@ fn resolveAnalyzedBlock(
62586321 const type_src = src; // TODO: better source location
62596322 if (try sema.typeRequiresComptime(resolved_ty)) {
62606323 const msg = msg: {
6261 const msg = try sema.errMsg(type_src, "value with comptime-only type '{}' depends on runtime control flow", .{resolved_ty.fmt(mod)});
6324 const msg = try sema.errMsg(type_src, "value with comptime-only type '{}' depends on runtime control flow", .{resolved_ty.fmt(pt)});
62626325 errdefer msg.destroy(sema.gpa);
62636326
62646327 const runtime_src = child_block.runtime_cond orelse child_block.runtime_loop.?;
......@@ -6353,7 +6416,8 @@ fn zirExport(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
63536416 const tracy = trace(@src());
63546417 defer tracy.end();
63556418
6356 const mod = sema.mod;
6419 const pt = sema.pt;
6420 const mod = pt.zcu;
63576421 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
63586422 const extra = sema.code.extraData(Zir.Inst.Export, inst_data.payload_index).data;
63596423 const src = block.nodeOffset(inst_data.src_node);
......@@ -6361,6 +6425,7 @@ fn zirExport(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
63616425 const options_src = block.builtinCallArgSrc(inst_data.src_node, 1);
63626426 const decl_name = try mod.intern_pool.getOrPutString(
63636427 mod.gpa,
6428 pt.tid,
63646429 sema.code.nullTerminatedString(extra.decl_name),
63656430 .no_embedded_nulls,
63666431 );
......@@ -6388,7 +6453,8 @@ fn zirExportValue(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
63886453 const tracy = trace(@src());
63896454 defer tracy.end();
63906455
6391 const mod = sema.mod;
6456 const pt = sema.pt;
6457 const mod = pt.zcu;
63926458 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
63936459 const extra = sema.code.extraData(Zir.Inst.ExportValue, inst_data.payload_index).data;
63946460 const src = block.nodeOffset(inst_data.src_node);
......@@ -6421,7 +6487,8 @@ pub fn analyzeExport(
64216487 exported_decl_index: InternPool.DeclIndex,
64226488) !void {
64236489 const gpa = sema.gpa;
6424 const mod = sema.mod;
6490 const pt = sema.pt;
6491 const mod = pt.zcu;
64256492
64266493 if (options.linkage == .internal)
64276494 return;
......@@ -6433,7 +6500,7 @@ pub fn analyzeExport(
64336500
64346501 if (!try sema.validateExternType(export_ty, .other)) {
64356502 const msg = msg: {
6436 const msg = try sema.errMsg(src, "unable to export type '{}'", .{export_ty.fmt(mod)});
6503 const msg = try sema.errMsg(src, "unable to export type '{}'", .{export_ty.fmt(pt)});
64376504 errdefer msg.destroy(gpa);
64386505
64396506 try sema.explainWhyTypeIsNotExtern(msg, src, export_ty, .other);
......@@ -6460,7 +6527,8 @@ pub fn analyzeExport(
64606527}
64616528
64626529fn zirSetAlignStack(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!void {
6463 const mod = sema.mod;
6530 const pt = sema.pt;
6531 const mod = pt.zcu;
64646532 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
64656533 const operand_src = block.builtinCallArgSrc(extra.node, 0);
64666534 const src = block.nodeOffset(extra.node);
......@@ -6502,7 +6570,8 @@ fn zirSetAlignStack(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Inst
65026570}
65036571
65046572fn zirSetCold(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!void {
6505 const mod = sema.mod;
6573 const pt = sema.pt;
6574 const mod = pt.zcu;
65066575 const ip = &mod.intern_pool;
65076576 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
65086577 const operand_src = block.builtinCallArgSrc(extra.node, 0);
......@@ -6628,7 +6697,8 @@ fn addDbgVar(
66286697) CompileError!void {
66296698 if (block.is_comptime or block.ownerModule().strip) return;
66306699
6631 const mod = sema.mod;
6700 const pt = sema.pt;
6701 const mod = pt.zcu;
66326702 const operand_ty = sema.typeOf(operand);
66336703 const val_ty = switch (air_tag) {
66346704 .dbg_var_ptr => operand_ty.childType(mod),
......@@ -6669,11 +6739,13 @@ fn addDbgVar(
66696739}
66706740
66716741fn zirDeclRef(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
6672 const mod = sema.mod;
6742 const pt = sema.pt;
6743 const mod = pt.zcu;
66736744 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].str_tok;
66746745 const src = block.tokenOffset(inst_data.src_tok);
66756746 const decl_name = try mod.intern_pool.getOrPutString(
66766747 sema.gpa,
6748 pt.tid,
66776749 inst_data.get(sema.code),
66786750 .no_embedded_nulls,
66796751 );
......@@ -6682,11 +6754,13 @@ fn zirDeclRef(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
66826754}
66836755
66846756fn zirDeclVal(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
6685 const mod = sema.mod;
6757 const pt = sema.pt;
6758 const mod = pt.zcu;
66866759 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].str_tok;
66876760 const src = block.tokenOffset(inst_data.src_tok);
66886761 const decl_name = try mod.intern_pool.getOrPutString(
66896762 sema.gpa,
6763 pt.tid,
66906764 inst_data.get(sema.code),
66916765 .no_embedded_nulls,
66926766 );
......@@ -6695,7 +6769,8 @@ fn zirDeclVal(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
66956769}
66966770
66976771fn lookupIdentifier(sema: *Sema, block: *Block, src: LazySrcLoc, name: InternPool.NullTerminatedString) !InternPool.DeclIndex {
6698 const mod = sema.mod;
6772 const pt = sema.pt;
6773 const mod = pt.zcu;
66996774 var namespace = block.namespace;
67006775 while (true) {
67016776 if (try sema.lookupInNamespace(block, src, namespace.toOptional(), name, false)) |decl_index| {
......@@ -6716,7 +6791,8 @@ fn lookupInNamespace(
67166791 ident_name: InternPool.NullTerminatedString,
67176792 observe_usingnamespace: bool,
67186793) CompileError!?InternPool.DeclIndex {
6719 const mod = sema.mod;
6794 const pt = sema.pt;
6795 const mod = pt.zcu;
67206796
67216797 const namespace_index = opt_namespace_index.unwrap() orelse return null;
67226798 const namespace = mod.namespacePtr(namespace_index);
......@@ -6811,7 +6887,8 @@ fn lookupInNamespace(
68116887}
68126888
68136889fn funcDeclSrc(sema: *Sema, func_inst: Air.Inst.Ref) !?*Decl {
6814 const mod = sema.mod;
6890 const pt = sema.pt;
6891 const mod = pt.zcu;
68156892 const func_val = (try sema.resolveValue(func_inst)) orelse return null;
68166893 if (func_val.isUndef(mod)) return null;
68176894 const owner_decl_index = switch (mod.intern_pool.indexToKey(func_val.toIntern())) {
......@@ -6827,19 +6904,20 @@ fn funcDeclSrc(sema: *Sema, func_inst: Air.Inst.Ref) !?*Decl {
68276904}
68286905
68296906pub fn analyzeSaveErrRetIndex(sema: *Sema, block: *Block) SemaError!Air.Inst.Ref {
6830 const mod = sema.mod;
6907 const pt = sema.pt;
6908 const mod = pt.zcu;
68316909 const gpa = sema.gpa;
68326910
68336911 if (block.is_comptime or block.is_typeof) {
6834 const index_val = try mod.intValue_u64(Type.usize, sema.comptime_err_ret_trace.items.len);
6912 const index_val = try pt.intValue_u64(Type.usize, sema.comptime_err_ret_trace.items.len);
68356913 return Air.internedToRef(index_val.toIntern());
68366914 }
68376915
68386916 if (!block.ownerModule().error_tracing) return .none;
68396917
6840 const stack_trace_ty = try mod.getBuiltinType("StackTrace");
6841 try stack_trace_ty.resolveFields(mod);
6842 const field_name = try mod.intern_pool.getOrPutString(gpa, "index", .no_embedded_nulls);
6918 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
6919 try stack_trace_ty.resolveFields(pt);
6920 const field_name = try mod.intern_pool.getOrPutString(gpa, pt.tid, "index", .no_embedded_nulls);
68436921 const field_index = sema.structFieldIndex(block, stack_trace_ty, field_name, LazySrcLoc.unneeded) catch |err| switch (err) {
68446922 error.AnalysisFail => @panic("std.builtin.StackTrace is corrupt"),
68456923 error.GenericPoison, error.ComptimeReturn, error.ComptimeBreak => unreachable,
......@@ -6864,7 +6942,8 @@ fn popErrorReturnTrace(
68646942 operand: Air.Inst.Ref,
68656943 saved_error_trace_index: Air.Inst.Ref,
68666944) CompileError!void {
6867 const mod = sema.mod;
6945 const pt = sema.pt;
6946 const mod = pt.zcu;
68686947 const gpa = sema.gpa;
68696948 var is_non_error: ?bool = null;
68706949 var is_non_error_inst: Air.Inst.Ref = undefined;
......@@ -6878,11 +6957,11 @@ fn popErrorReturnTrace(
68786957 // AstGen determined this result does not go to an error-handling expr (try/catch/return etc.), or
68796958 // the result is comptime-known to be a non-error. Either way, pop unconditionally.
68806959
6881 const stack_trace_ty = try mod.getBuiltinType("StackTrace");
6882 try stack_trace_ty.resolveFields(mod);
6883 const ptr_stack_trace_ty = try mod.singleMutPtrType(stack_trace_ty);
6960 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
6961 try stack_trace_ty.resolveFields(pt);
6962 const ptr_stack_trace_ty = try pt.singleMutPtrType(stack_trace_ty);
68846963 const err_return_trace = try block.addTy(.err_return_trace, ptr_stack_trace_ty);
6885 const field_name = try mod.intern_pool.getOrPutString(gpa, "index", .no_embedded_nulls);
6964 const field_name = try mod.intern_pool.getOrPutString(gpa, pt.tid, "index", .no_embedded_nulls);
68866965 const field_ptr = try sema.structFieldPtr(block, src, err_return_trace, field_name, src, stack_trace_ty, true);
68876966 try sema.storePtr2(block, src, field_ptr, src, saved_error_trace_index, src, .store);
68886967 } else if (is_non_error == null) {
......@@ -6904,11 +6983,11 @@ fn popErrorReturnTrace(
69046983 defer then_block.instructions.deinit(gpa);
69056984
69066985 // If non-error, then pop the error return trace by restoring the index.
6907 const stack_trace_ty = try mod.getBuiltinType("StackTrace");
6908 try stack_trace_ty.resolveFields(mod);
6909 const ptr_stack_trace_ty = try mod.singleMutPtrType(stack_trace_ty);
6986 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
6987 try stack_trace_ty.resolveFields(pt);
6988 const ptr_stack_trace_ty = try pt.singleMutPtrType(stack_trace_ty);
69106989 const err_return_trace = try then_block.addTy(.err_return_trace, ptr_stack_trace_ty);
6911 const field_name = try mod.intern_pool.getOrPutString(gpa, "index", .no_embedded_nulls);
6990 const field_name = try mod.intern_pool.getOrPutString(gpa, pt.tid, "index", .no_embedded_nulls);
69126991 const field_ptr = try sema.structFieldPtr(&then_block, src, err_return_trace, field_name, src, stack_trace_ty, true);
69136992 try sema.storePtr2(&then_block, src, field_ptr, src, saved_error_trace_index, src, .store);
69146993 _ = try then_block.addBr(cond_block_inst, .void_value);
......@@ -6947,7 +7026,8 @@ fn zirCall(
69477026 const tracy = trace(@src());
69487027 defer tracy.end();
69497028
6950 const mod = sema.mod;
7029 const pt = sema.pt;
7030 const mod = pt.zcu;
69517031 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
69527032 const callee_src = block.src(.{ .node_offset_call_func = inst_data.src_node });
69537033 const call_src = block.nodeOffset(inst_data.src_node);
......@@ -6968,6 +7048,7 @@ fn zirCall(
69687048 const object_ptr = try sema.resolveInst(extra.data.obj_ptr);
69697049 const field_name = try mod.intern_pool.getOrPutString(
69707050 sema.gpa,
7051 pt.tid,
69717052 sema.code.nullTerminatedString(extra.data.field_name_start),
69727053 .no_embedded_nulls,
69737054 );
......@@ -7031,9 +7112,9 @@ fn zirCall(
70317112 // If any input is an error-type, we might need to pop any trace it generated. Otherwise, we only
70327113 // need to clean-up our own trace if we were passed to a non-error-handling expression.
70337114 if (input_is_error or (pop_error_return_trace and return_ty.isError(mod))) {
7034 const stack_trace_ty = try mod.getBuiltinType("StackTrace");
7035 try stack_trace_ty.resolveFields(mod);
7036 const field_name = try mod.intern_pool.getOrPutString(sema.gpa, "index", .no_embedded_nulls);
7115 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
7116 try stack_trace_ty.resolveFields(pt);
7117 const field_name = try mod.intern_pool.getOrPutString(sema.gpa, pt.tid, "index", .no_embedded_nulls);
70377118 const field_index = try sema.structFieldIndex(block, stack_trace_ty, field_name, call_src);
70387119
70397120 // Insert a save instruction before the arg resolution + call instructions we just generated
......@@ -7065,7 +7146,8 @@ fn checkCallArgumentCount(
70657146 total_args: usize,
70667147 member_fn: bool,
70677148) !Type {
7068 const mod = sema.mod;
7149 const pt = sema.pt;
7150 const mod = pt.zcu;
70697151 const func_ty = func_ty: {
70707152 switch (callee_ty.zigTypeTag(mod)) {
70717153 .Fn => break :func_ty callee_ty,
......@@ -7082,7 +7164,7 @@ fn checkCallArgumentCount(
70827164 {
70837165 const msg = msg: {
70847166 const msg = try sema.errMsg(func_src, "cannot call optional type '{}'", .{
7085 callee_ty.fmt(mod),
7167 callee_ty.fmt(pt),
70867168 });
70877169 errdefer msg.destroy(sema.gpa);
70887170 try sema.errNote(func_src, msg, "consider using '.?', 'orelse' or 'if'", .{});
......@@ -7093,7 +7175,7 @@ fn checkCallArgumentCount(
70937175 },
70947176 else => {},
70957177 }
7096 return sema.fail(block, func_src, "type '{}' not a function", .{callee_ty.fmt(mod)});
7178 return sema.fail(block, func_src, "type '{}' not a function", .{callee_ty.fmt(pt)});
70977179 };
70987180
70997181 const func_ty_info = mod.typeToFunc(func_ty).?;
......@@ -7142,7 +7224,8 @@ fn callBuiltin(
71427224 args: []const Air.Inst.Ref,
71437225 operation: CallOperation,
71447226) !void {
7145 const mod = sema.mod;
7227 const pt = sema.pt;
7228 const mod = pt.zcu;
71467229 const callee_ty = sema.typeOf(builtin_fn);
71477230 const func_ty = func_ty: {
71487231 switch (callee_ty.zigTypeTag(mod)) {
......@@ -7155,7 +7238,7 @@ fn callBuiltin(
71557238 },
71567239 else => {},
71577240 }
7158 std.debug.panic("type '{}' is not a function calling builtin fn", .{callee_ty.fmt(mod)});
7241 std.debug.panic("type '{}' is not a function calling builtin fn", .{callee_ty.fmt(pt)});
71597242 };
71607243
71617244 const func_ty_info = mod.typeToFunc(func_ty).?;
......@@ -7261,7 +7344,8 @@ const CallArgsInfo = union(enum) {
72617344 func_ty_info: InternPool.Key.FuncType,
72627345 func_inst: Air.Inst.Ref,
72637346 ) CompileError!Air.Inst.Ref {
7264 const mod = sema.mod;
7347 const pt = sema.pt;
7348 const mod = pt.zcu;
72657349 const param_count = func_ty_info.param_types.len;
72667350 const uncoerced_arg: Air.Inst.Ref = switch (cai) {
72677351 inline .resolved, .call_builtin => |resolved| resolved.args[arg_index],
......@@ -7438,7 +7522,8 @@ fn analyzeCall(
74387522 call_dbg_node: ?Zir.Inst.Index,
74397523 operation: CallOperation,
74407524) CompileError!Air.Inst.Ref {
7441 const mod = sema.mod;
7525 const pt = sema.pt;
7526 const mod = pt.zcu;
74427527 const ip = &mod.intern_pool;
74437528
74447529 const callee_ty = sema.typeOf(func);
......@@ -7741,10 +7826,10 @@ fn analyzeCall(
77417826 const ies = try sema.arena.create(InferredErrorSet);
77427827 ies.* = .{ .func = .none };
77437828 sema.fn_ret_ty_ies = ies;
7744 sema.fn_ret_ty = Type.fromInterned((try ip.get(gpa, .{ .error_union_type = .{
7829 sema.fn_ret_ty = Type.fromInterned(try pt.intern(.{ .error_union_type = .{
77457830 .error_set_type = .adhoc_inferred_error_set_type,
77467831 .payload_type = sema.fn_ret_ty.toIntern(),
7747 } })));
7832 } }));
77487833 }
77497834
77507835 // This `res2` is here instead of directly breaking from `res` due to a stage1
......@@ -7816,7 +7901,7 @@ fn analyzeCall(
78167901 // TODO: check whether any external comptime memory was mutated by the
78177902 // comptime function call. If so, then do not memoize the call here.
78187903 if (should_memoize and !Value.fromInterned(result_interned).canMutateComptimeVarState(mod)) {
7819 _ = try mod.intern(.{ .memoized_call = .{
7904 _ = try pt.intern(.{ .memoized_call = .{
78207905 .func = module_fn_index,
78217906 .arg_values = memoized_arg_values,
78227907 .result = result_transformed,
......@@ -7921,7 +8006,8 @@ fn analyzeCall(
79218006}
79228007
79238008fn handleTailCall(sema: *Sema, block: *Block, call_src: LazySrcLoc, func_ty: Type, result: Air.Inst.Ref) !Air.Inst.Ref {
7924 const mod = sema.mod;
8009 const pt = sema.pt;
8010 const mod = pt.zcu;
79258011 const target = mod.getTarget();
79268012 const backend = mod.comp.getZigBackend();
79278013 if (!target_util.supportsTailCall(target, backend)) {
......@@ -7932,7 +8018,7 @@ fn handleTailCall(sema: *Sema, block: *Block, call_src: LazySrcLoc, func_ty: Typ
79328018 const func_decl = mod.funcOwnerDeclPtr(sema.owner_func_index);
79338019 if (!func_ty.eql(func_decl.typeOf(mod), mod)) {
79348020 return sema.fail(block, call_src, "unable to perform tail call: type of function being called '{}' does not match type of calling function '{}'", .{
7935 func_ty.fmt(mod), func_decl.typeOf(mod).fmt(mod),
8021 func_ty.fmt(pt), func_decl.typeOf(mod).fmt(pt),
79368022 });
79378023 }
79388024 _ = try block.addUnOp(.ret, result);
......@@ -7954,7 +8040,7 @@ fn analyzeInlineCallArg(
79548040 func_ty_info: InternPool.Key.FuncType,
79558041 func_inst: Air.Inst.Ref,
79568042) !?Air.Inst.Ref {
7957 const mod = ics.sema.mod;
8043 const mod = ics.sema.pt.zcu;
79588044 const ip = &mod.intern_pool;
79598045 const zir_tags = ics.callee().code.instructions.items(.tag);
79608046 switch (zir_tags[@intFromEnum(inst)]) {
......@@ -8084,7 +8170,8 @@ fn instantiateGenericCall(
80848170 call_tag: Air.Inst.Tag,
80858171 call_dbg_node: ?Zir.Inst.Index,
80868172) CompileError!Air.Inst.Ref {
8087 const zcu = sema.mod;
8173 const pt = sema.pt;
8174 const zcu = pt.zcu;
80888175 const gpa = sema.gpa;
80898176 const ip = &zcu.intern_pool;
80908177
......@@ -8127,7 +8214,7 @@ fn instantiateGenericCall(
81278214 // `param_anytype_comptime` ZIR instructions to be ignored, resulting in a
81288215 // new, monomorphized function, with the comptime parameters elided.
81298216 var child_sema: Sema = .{
8130 .mod = zcu,
8217 .pt = pt,
81318218 .gpa = gpa,
81328219 .arena = sema.arena,
81338220 .code = fn_zir,
......@@ -8358,7 +8445,8 @@ fn instantiateGenericCall(
83588445}
83598446
83608447fn resolveTupleLazyValues(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError!void {
8361 const mod = sema.mod;
8448 const pt = sema.pt;
8449 const mod = pt.zcu;
83628450 const ip = &mod.intern_pool;
83638451 const tuple = switch (ip.indexToKey(ty.toIntern())) {
83648452 .anon_struct_type => |tuple| tuple,
......@@ -8373,9 +8461,8 @@ fn resolveTupleLazyValues(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type)
83738461}
83748462
83758463fn zirIntType(sema: *Sema, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
8376 const mod = sema.mod;
83778464 const int_type = sema.code.instructions.items(.data)[@intFromEnum(inst)].int_type;
8378 const ty = try mod.intType(int_type.signedness, int_type.bit_count);
8465 const ty = try sema.pt.intType(int_type.signedness, int_type.bit_count);
83798466 return Air.internedToRef(ty.toIntern());
83808467}
83818468
......@@ -8383,22 +8470,24 @@ fn zirOptionalType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
83838470 const tracy = trace(@src());
83848471 defer tracy.end();
83858472
8386 const mod = sema.mod;
8473 const pt = sema.pt;
8474 const mod = pt.zcu;
83878475 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
83888476 const operand_src = block.src(.{ .node_offset_un_op = inst_data.src_node });
83898477 const child_type = try sema.resolveType(block, operand_src, inst_data.operand);
83908478 if (child_type.zigTypeTag(mod) == .Opaque) {
8391 return sema.fail(block, operand_src, "opaque type '{}' cannot be optional", .{child_type.fmt(mod)});
8479 return sema.fail(block, operand_src, "opaque type '{}' cannot be optional", .{child_type.fmt(pt)});
83928480 } else if (child_type.zigTypeTag(mod) == .Null) {
8393 return sema.fail(block, operand_src, "type '{}' cannot be optional", .{child_type.fmt(mod)});
8481 return sema.fail(block, operand_src, "type '{}' cannot be optional", .{child_type.fmt(pt)});
83948482 }
8395 const opt_type = try mod.optionalType(child_type.toIntern());
8483 const opt_type = try pt.optionalType(child_type.toIntern());
83968484
83978485 return Air.internedToRef(opt_type.toIntern());
83988486}
83998487
84008488fn zirArrayInitElemType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
8401 const mod = sema.mod;
8489 const pt = sema.pt;
8490 const mod = pt.zcu;
84028491 const bin = sema.code.instructions.items(.data)[@intFromEnum(inst)].bin;
84038492 const maybe_wrapped_indexable_ty = sema.resolveType(block, LazySrcLoc.unneeded, bin.lhs) catch |err| switch (err) {
84048493 // Since this is a ZIR instruction that returns a type, encountering
......@@ -8409,7 +8498,7 @@ fn zirArrayInitElemType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Compil
84098498 else => |e| return e,
84108499 };
84118500 const indexable_ty = maybe_wrapped_indexable_ty.optEuBaseType(mod);
8412 try indexable_ty.resolveFields(mod);
8501 try indexable_ty.resolveFields(pt);
84138502 assert(indexable_ty.isIndexable(mod)); // validated by a previous instruction
84148503 if (indexable_ty.zigTypeTag(mod) == .Struct) {
84158504 const elem_type = indexable_ty.structFieldType(@intFromEnum(bin.rhs), mod);
......@@ -8421,7 +8510,8 @@ fn zirArrayInitElemType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Compil
84218510}
84228511
84238512fn zirElemType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
8424 const mod = sema.mod;
8513 const pt = sema.pt;
8514 const mod = pt.zcu;
84258515 const un_node = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
84268516 const maybe_wrapped_ptr_ty = sema.resolveType(block, LazySrcLoc.unneeded, un_node.operand) catch |err| switch (err) {
84278517 error.GenericPoison => return .generic_poison_type,
......@@ -8439,7 +8529,8 @@ fn zirElemType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
84398529}
84408530
84418531fn zirIndexablePtrElemType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
8442 const mod = sema.mod;
8532 const pt = sema.pt;
8533 const mod = pt.zcu;
84438534 const un_node = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
84448535 const src = block.nodeOffset(un_node.src_node);
84458536 const ptr_ty = sema.resolveType(block, src, un_node.operand) catch |err| switch (err) {
......@@ -8455,7 +8546,8 @@ fn zirIndexablePtrElemType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Com
84558546}
84568547
84578548fn zirVectorElemType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
8458 const mod = sema.mod;
8549 const pt = sema.pt;
8550 const mod = pt.zcu;
84598551 const un_node = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
84608552 const vec_ty = sema.resolveType(block, LazySrcLoc.unneeded, un_node.operand) catch |err| switch (err) {
84618553 // Since this is a ZIR instruction that returns a type, encountering
......@@ -8466,13 +8558,12 @@ fn zirVectorElemType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileEr
84668558 else => |e| return e,
84678559 };
84688560 if (!vec_ty.isVector(mod)) {
8469 return sema.fail(block, block.nodeOffset(un_node.src_node), "expected vector type, found '{}'", .{vec_ty.fmt(mod)});
8561 return sema.fail(block, block.nodeOffset(un_node.src_node), "expected vector type, found '{}'", .{vec_ty.fmt(pt)});
84708562 }
84718563 return Air.internedToRef(vec_ty.childType(mod).toIntern());
84728564}
84738565
84748566fn zirVectorType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
8475 const mod = sema.mod;
84768567 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
84778568 const len_src = block.builtinCallArgSrc(inst_data.src_node, 0);
84788569 const elem_type_src = block.builtinCallArgSrc(inst_data.src_node, 1);
......@@ -8482,7 +8573,7 @@ fn zirVectorType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
84828573 }));
84838574 const elem_type = try sema.resolveType(block, elem_type_src, extra.rhs);
84848575 try sema.checkVectorElemType(block, elem_type_src, elem_type);
8485 const vector_type = try mod.vectorType(.{
8576 const vector_type = try sema.pt.vectorType(.{
84868577 .len = len,
84878578 .child = elem_type.toIntern(),
84888579 });
......@@ -8502,7 +8593,7 @@ fn zirArrayType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
85028593 });
85038594 const elem_type = try sema.resolveType(block, elem_src, extra.rhs);
85048595 try sema.validateArrayElemType(block, elem_type, elem_src);
8505 const array_ty = try sema.mod.arrayType(.{
8596 const array_ty = try sema.pt.arrayType(.{
85068597 .len = len,
85078598 .child = elem_type.toIntern(),
85088599 });
......@@ -8529,7 +8620,7 @@ fn zirArrayTypeSentinel(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Compil
85298620 const sentinel_val = try sema.resolveConstDefinedValue(block, sentinel_src, sentinel, .{
85308621 .needed_comptime_reason = "array sentinel value must be comptime-known",
85318622 });
8532 const array_ty = try sema.mod.arrayType(.{
8623 const array_ty = try sema.pt.arrayType(.{
85338624 .len = len,
85348625 .sentinel = sentinel_val.toIntern(),
85358626 .child = elem_type.toIntern(),
......@@ -8539,9 +8630,10 @@ fn zirArrayTypeSentinel(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Compil
85398630}
85408631
85418632fn validateArrayElemType(sema: *Sema, block: *Block, elem_type: Type, elem_src: LazySrcLoc) !void {
8542 const mod = sema.mod;
8633 const pt = sema.pt;
8634 const mod = pt.zcu;
85438635 if (elem_type.zigTypeTag(mod) == .Opaque) {
8544 return sema.fail(block, elem_src, "array of opaque type '{}' not allowed", .{elem_type.fmt(mod)});
8636 return sema.fail(block, elem_src, "array of opaque type '{}' not allowed", .{elem_type.fmt(pt)});
85458637 } else if (elem_type.zigTypeTag(mod) == .NoReturn) {
85468638 return sema.fail(block, elem_src, "array of 'noreturn' not allowed", .{});
85478639 }
......@@ -8567,7 +8659,8 @@ fn zirErrorUnionType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileEr
85678659 const tracy = trace(@src());
85688660 defer tracy.end();
85698661
8570 const mod = sema.mod;
8662 const pt = sema.pt;
8663 const mod = pt.zcu;
85718664 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
85728665 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
85738666 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -8577,40 +8670,42 @@ fn zirErrorUnionType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileEr
85778670
85788671 if (error_set.zigTypeTag(mod) != .ErrorSet) {
85798672 return sema.fail(block, lhs_src, "expected error set type, found '{}'", .{
8580 error_set.fmt(mod),
8673 error_set.fmt(pt),
85818674 });
85828675 }
85838676 try sema.validateErrorUnionPayloadType(block, payload, rhs_src);
8584 const err_union_ty = try mod.errorUnionType(error_set, payload);
8677 const err_union_ty = try pt.errorUnionType(error_set, payload);
85858678 return Air.internedToRef(err_union_ty.toIntern());
85868679}
85878680
85888681fn validateErrorUnionPayloadType(sema: *Sema, block: *Block, payload_ty: Type, payload_src: LazySrcLoc) !void {
8589 const mod = sema.mod;
8682 const pt = sema.pt;
8683 const mod = pt.zcu;
85908684 if (payload_ty.zigTypeTag(mod) == .Opaque) {
85918685 return sema.fail(block, payload_src, "error union with payload of opaque type '{}' not allowed", .{
8592 payload_ty.fmt(mod),
8686 payload_ty.fmt(pt),
85938687 });
85948688 } else if (payload_ty.zigTypeTag(mod) == .ErrorSet) {
85958689 return sema.fail(block, payload_src, "error union with payload of error set type '{}' not allowed", .{
8596 payload_ty.fmt(mod),
8690 payload_ty.fmt(pt),
85978691 });
85988692 }
85998693}
86008694
86018695fn zirErrorValue(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
86028696 _ = block;
8603 const mod = sema.mod;
8697 const pt = sema.pt;
86048698 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].str_tok;
8605 const name = try mod.intern_pool.getOrPutString(
8699 const name = try pt.zcu.intern_pool.getOrPutString(
86068700 sema.gpa,
8701 pt.tid,
86078702 inst_data.get(sema.code),
86088703 .no_embedded_nulls,
86098704 );
8610 _ = try mod.getErrorValue(name);
8705 _ = try pt.zcu.getErrorValue(name);
86118706 // Create an error set type with only this error value, and return the value.
8612 const error_set_type = try mod.singleErrorSetType(name);
8613 return Air.internedToRef((try mod.intern(.{ .err = .{
8707 const error_set_type = try pt.singleErrorSetType(name);
8708 return Air.internedToRef((try pt.intern(.{ .err = .{
86148709 .ty = error_set_type.toIntern(),
86158710 .name = name,
86168711 } })));
......@@ -8620,21 +8715,22 @@ fn zirIntFromError(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstD
86208715 const tracy = trace(@src());
86218716 defer tracy.end();
86228717
8623 const mod = sema.mod;
8718 const pt = sema.pt;
8719 const mod = pt.zcu;
86248720 const ip = &mod.intern_pool;
86258721 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
86268722 const src = block.nodeOffset(extra.node);
86278723 const operand_src = block.builtinCallArgSrc(extra.node, 0);
86288724 const uncasted_operand = try sema.resolveInst(extra.operand);
86298725 const operand = try sema.coerce(block, Type.anyerror, uncasted_operand, operand_src);
8630 const err_int_ty = try mod.errorIntType();
8726 const err_int_ty = try pt.errorIntType();
86318727
86328728 if (try sema.resolveValue(operand)) |val| {
86338729 if (val.isUndef(mod)) {
8634 return mod.undefRef(err_int_ty);
8730 return pt.undefRef(err_int_ty);
86358731 }
86368732 const err_name = ip.indexToKey(val.toIntern()).err.name;
8637 return Air.internedToRef((try mod.intValue(
8733 return Air.internedToRef((try pt.intValue(
86388734 err_int_ty,
86398735 try mod.getErrorValue(err_name),
86408736 )).toIntern());
......@@ -8646,10 +8742,10 @@ fn zirIntFromError(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstD
86468742 else => |err_set_ty_index| {
86478743 const names = ip.indexToKey(err_set_ty_index).error_set_type.names;
86488744 switch (names.len) {
8649 0 => return Air.internedToRef((try mod.intValue(err_int_ty, 0)).toIntern()),
8745 0 => return Air.internedToRef((try pt.intValue(err_int_ty, 0)).toIntern()),
86508746 1 => {
86518747 const int: Module.ErrorInt = @intCast(mod.global_error_set.getIndex(names.get(ip)[0]).?);
8652 return mod.intRef(err_int_ty, int);
8748 return pt.intRef(err_int_ty, int);
86538749 },
86548750 else => {},
86558751 }
......@@ -8664,19 +8760,20 @@ fn zirErrorFromInt(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstD
86648760 const tracy = trace(@src());
86658761 defer tracy.end();
86668762
8667 const mod = sema.mod;
8763 const pt = sema.pt;
8764 const mod = pt.zcu;
86688765 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
86698766 const src = block.nodeOffset(extra.node);
86708767 const operand_src = block.builtinCallArgSrc(extra.node, 0);
86718768 const uncasted_operand = try sema.resolveInst(extra.operand);
8672 const err_int_ty = try mod.errorIntType();
8769 const err_int_ty = try pt.errorIntType();
86738770 const operand = try sema.coerce(block, err_int_ty, uncasted_operand, operand_src);
86748771
86758772 if (try sema.resolveDefinedValue(block, operand_src, operand)) |value| {
8676 const int = try sema.usizeCast(block, operand_src, try value.toUnsignedIntSema(mod));
8773 const int = try sema.usizeCast(block, operand_src, try value.toUnsignedIntSema(pt));
86778774 if (int > mod.global_error_set.count() or int == 0)
86788775 return sema.fail(block, operand_src, "integer value '{d}' represents no error", .{int});
8679 return Air.internedToRef((try mod.intern(.{ .err = .{
8776 return Air.internedToRef((try pt.intern(.{ .err = .{
86808777 .ty = .anyerror_type,
86818778 .name = mod.global_error_set.keys()[int],
86828779 } })));
......@@ -8684,7 +8781,7 @@ fn zirErrorFromInt(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstD
86848781 try sema.requireRuntimeBlock(block, src, operand_src);
86858782 if (block.wantSafety()) {
86868783 const is_lt_len = try block.addUnOp(.cmp_lt_errors_len, operand);
8687 const zero_val = Air.internedToRef((try mod.intValue(err_int_ty, 0)).toIntern());
8784 const zero_val = Air.internedToRef((try pt.intValue(err_int_ty, 0)).toIntern());
86888785 const is_non_zero = try block.addBinOp(.cmp_neq, operand, zero_val);
86898786 const ok = try block.addBinOp(.bool_and, is_lt_len, is_non_zero);
86908787 try sema.addSafetyCheck(block, src, ok, .invalid_error_code);
......@@ -8702,7 +8799,8 @@ fn zirMergeErrorSets(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileEr
87028799 const tracy = trace(@src());
87038800 defer tracy.end();
87048801
8705 const mod = sema.mod;
8802 const pt = sema.pt;
8803 const mod = pt.zcu;
87068804 const ip = &mod.intern_pool;
87078805 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
87088806 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
......@@ -8723,9 +8821,9 @@ fn zirMergeErrorSets(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileEr
87238821 const lhs_ty = try sema.analyzeAsType(block, lhs_src, lhs);
87248822 const rhs_ty = try sema.analyzeAsType(block, rhs_src, rhs);
87258823 if (lhs_ty.zigTypeTag(mod) != .ErrorSet)
8726 return sema.fail(block, lhs_src, "expected error set type, found '{}'", .{lhs_ty.fmt(mod)});
8824 return sema.fail(block, lhs_src, "expected error set type, found '{}'", .{lhs_ty.fmt(pt)});
87278825 if (rhs_ty.zigTypeTag(mod) != .ErrorSet)
8728 return sema.fail(block, rhs_src, "expected error set type, found '{}'", .{rhs_ty.fmt(mod)});
8826 return sema.fail(block, rhs_src, "expected error set type, found '{}'", .{rhs_ty.fmt(pt)});
87298827
87308828 // Anything merged with anyerror is anyerror.
87318829 if (lhs_ty.toIntern() == .anyerror_type or rhs_ty.toIntern() == .anyerror_type) {
......@@ -8758,16 +8856,18 @@ fn zirEnumLiteral(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
87588856 const tracy = trace(@src());
87598857 defer tracy.end();
87608858
8761 const mod = sema.mod;
8859 const pt = sema.pt;
8860 const mod = pt.zcu;
87628861 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].str_tok;
87638862 const name = inst_data.get(sema.code);
8764 return Air.internedToRef((try mod.intern(.{
8765 .enum_literal = try mod.intern_pool.getOrPutString(sema.gpa, name, .no_embedded_nulls),
8863 return Air.internedToRef((try pt.intern(.{
8864 .enum_literal = try mod.intern_pool.getOrPutString(sema.gpa, pt.tid, name, .no_embedded_nulls),
87668865 })));
87678866}
87688867
87698868fn zirIntFromEnum(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
8770 const mod = sema.mod;
8869 const pt = sema.pt;
8870 const mod = pt.zcu;
87718871 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
87728872 const src = block.nodeOffset(inst_data.src_node);
87738873 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
......@@ -8777,7 +8877,7 @@ fn zirIntFromEnum(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
87778877 const enum_tag: Air.Inst.Ref = switch (operand_ty.zigTypeTag(mod)) {
87788878 .Enum => operand,
87798879 .Union => blk: {
8780 try operand_ty.resolveFields(mod);
8880 try operand_ty.resolveFields(pt);
87818881 const tag_ty = operand_ty.unionTagType(mod) orelse {
87828882 return sema.fail(
87838883 block,
......@@ -8791,7 +8891,7 @@ fn zirIntFromEnum(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
87918891 },
87928892 else => {
87938893 return sema.fail(block, operand_src, "expected enum or tagged union, found '{}'", .{
8794 operand_ty.fmt(mod),
8894 operand_ty.fmt(pt),
87958895 });
87968896 },
87978897 };
......@@ -8802,20 +8902,20 @@ fn zirIntFromEnum(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
88028902 // https://github.com/ziglang/zig/issues/15909
88038903 if (enum_tag_ty.enumFieldCount(mod) == 0 and !enum_tag_ty.isNonexhaustiveEnum(mod)) {
88048904 return sema.fail(block, operand_src, "cannot use @intFromEnum on empty enum '{}'", .{
8805 enum_tag_ty.fmt(mod),
8905 enum_tag_ty.fmt(pt),
88068906 });
88078907 }
88088908
88098909 if (try sema.typeHasOnePossibleValue(enum_tag_ty)) |opv| {
8810 return Air.internedToRef((try mod.getCoerced(opv, int_tag_ty)).toIntern());
8910 return Air.internedToRef((try pt.getCoerced(opv, int_tag_ty)).toIntern());
88118911 }
88128912
88138913 if (try sema.resolveValue(enum_tag)) |enum_tag_val| {
88148914 if (enum_tag_val.isUndef(mod)) {
8815 return mod.undefRef(int_tag_ty);
8915 return pt.undefRef(int_tag_ty);
88168916 }
88178917
8818 const val = try enum_tag_val.intFromEnum(enum_tag_ty, mod);
8918 const val = try enum_tag_val.intFromEnum(enum_tag_ty, pt);
88198919 return Air.internedToRef(val.toIntern());
88208920 }
88218921
......@@ -8824,7 +8924,8 @@ fn zirIntFromEnum(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
88248924}
88258925
88268926fn zirEnumFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
8827 const mod = sema.mod;
8927 const pt = sema.pt;
8928 const mod = pt.zcu;
88288929 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
88298930 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
88308931 const src = block.nodeOffset(inst_data.src_node);
......@@ -8833,7 +8934,7 @@ fn zirEnumFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
88338934 const operand = try sema.resolveInst(extra.rhs);
88348935
88358936 if (dest_ty.zigTypeTag(mod) != .Enum) {
8836 return sema.fail(block, src, "expected enum, found '{}'", .{dest_ty.fmt(mod)});
8937 return sema.fail(block, src, "expected enum, found '{}'", .{dest_ty.fmt(pt)});
88378938 }
88388939 _ = try sema.checkIntType(block, operand_src, sema.typeOf(operand));
88398940
......@@ -8841,10 +8942,10 @@ fn zirEnumFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
88418942 if (dest_ty.isNonexhaustiveEnum(mod)) {
88428943 const int_tag_ty = dest_ty.intTagType(mod);
88438944 if (try sema.intFitsInType(int_val, int_tag_ty, null)) {
8844 return Air.internedToRef((try mod.getCoerced(int_val, dest_ty)).toIntern());
8945 return Air.internedToRef((try pt.getCoerced(int_val, dest_ty)).toIntern());
88458946 }
88468947 return sema.fail(block, src, "int value '{}' out of range of non-exhaustive enum '{}'", .{
8847 int_val.fmtValue(mod, sema), dest_ty.fmt(mod),
8948 int_val.fmtValue(pt, sema), dest_ty.fmt(pt),
88488949 });
88498950 }
88508951 if (int_val.isUndef(mod)) {
......@@ -8852,10 +8953,10 @@ fn zirEnumFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
88528953 }
88538954 if (!(try sema.enumHasInt(dest_ty, int_val))) {
88548955 return sema.fail(block, src, "enum '{}' has no tag with value '{}'", .{
8855 dest_ty.fmt(mod), int_val.fmtValue(mod, sema),
8956 dest_ty.fmt(pt), int_val.fmtValue(pt, sema),
88568957 });
88578958 }
8858 return Air.internedToRef((try mod.getCoerced(int_val, dest_ty)).toIntern());
8959 return Air.internedToRef((try pt.getCoerced(int_val, dest_ty)).toIntern());
88598960 }
88608961
88618962 if (dest_ty.intTagType(mod).zigTypeTag(mod) == .ComptimeInt) {
......@@ -8909,7 +9010,8 @@ fn analyzeOptionalPayloadPtr(
89099010 safety_check: bool,
89109011 initializing: bool,
89119012) CompileError!Air.Inst.Ref {
8912 const zcu = sema.mod;
9013 const pt = sema.pt;
9014 const zcu = pt.zcu;
89139015 const optional_ptr_ty = sema.typeOf(optional_ptr);
89149016 assert(optional_ptr_ty.zigTypeTag(zcu) == .Pointer);
89159017
......@@ -8919,7 +9021,7 @@ fn analyzeOptionalPayloadPtr(
89199021 }
89209022
89219023 const child_type = opt_type.optionalChild(zcu);
8922 const child_pointer = try zcu.ptrTypeSema(.{
9024 const child_pointer = try pt.ptrTypeSema(.{
89239025 .child = child_type.toIntern(),
89249026 .flags = .{
89259027 .is_const = optional_ptr_ty.isConstPtr(zcu),
......@@ -8932,8 +9034,8 @@ fn analyzeOptionalPayloadPtr(
89329034 if (sema.isComptimeMutablePtr(ptr_val)) {
89339035 // Set the optional to non-null at comptime.
89349036 // If the payload is OPV, we must use that value instead of undef.
8935 const payload_val = try sema.typeHasOnePossibleValue(child_type) orelse try zcu.undefValue(child_type);
8936 const opt_val = try zcu.intern(.{ .opt = .{
9037 const payload_val = try sema.typeHasOnePossibleValue(child_type) orelse try pt.undefValue(child_type);
9038 const opt_val = try pt.intern(.{ .opt = .{
89379039 .ty = opt_type.toIntern(),
89389040 .val = payload_val.toIntern(),
89399041 } });
......@@ -8943,13 +9045,13 @@ fn analyzeOptionalPayloadPtr(
89439045 const opt_payload_ptr = try block.addTyOp(.optional_payload_ptr_set, child_pointer, optional_ptr);
89449046 try sema.checkKnownAllocPtr(block, optional_ptr, opt_payload_ptr);
89459047 }
8946 return Air.internedToRef((try ptr_val.ptrOptPayload(zcu)).toIntern());
9048 return Air.internedToRef((try ptr_val.ptrOptPayload(pt)).toIntern());
89479049 }
89489050 if (try sema.pointerDeref(block, src, ptr_val, optional_ptr_ty)) |val| {
89499051 if (val.isNull(zcu)) {
89509052 return sema.fail(block, src, "unable to unwrap null", .{});
89519053 }
8952 return Air.internedToRef((try ptr_val.ptrOptPayload(zcu)).toIntern());
9054 return Air.internedToRef((try ptr_val.ptrOptPayload(pt)).toIntern());
89539055 }
89549056 }
89559057
......@@ -8978,7 +9080,8 @@ fn zirOptionalPayload(
89789080 const tracy = trace(@src());
89799081 defer tracy.end();
89809082
8981 const mod = sema.mod;
9083 const pt = sema.pt;
9084 const mod = pt.zcu;
89829085 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
89839086 const src = block.nodeOffset(inst_data.src_node);
89849087 const operand = try sema.resolveInst(inst_data.operand);
......@@ -8992,7 +9095,7 @@ fn zirOptionalPayload(
89929095 // TODO https://github.com/ziglang/zig/issues/6597
89939096 if (true) break :t operand_ty;
89949097 const ptr_info = operand_ty.ptrInfo(mod);
8995 break :t try mod.ptrTypeSema(.{
9098 break :t try pt.ptrTypeSema(.{
89969099 .child = ptr_info.child,
89979100 .flags = .{
89989101 .alignment = ptr_info.flags.alignment,
......@@ -9030,7 +9133,8 @@ fn zirErrUnionPayload(
90309133 const tracy = trace(@src());
90319134 defer tracy.end();
90329135
9033 const mod = sema.mod;
9136 const pt = sema.pt;
9137 const mod = pt.zcu;
90349138 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
90359139 const src = block.nodeOffset(inst_data.src_node);
90369140 const operand = try sema.resolveInst(inst_data.operand);
......@@ -9038,7 +9142,7 @@ fn zirErrUnionPayload(
90389142 const err_union_ty = sema.typeOf(operand);
90399143 if (err_union_ty.zigTypeTag(mod) != .ErrorUnion) {
90409144 return sema.fail(block, operand_src, "expected error union type, found '{}'", .{
9041 err_union_ty.fmt(mod),
9145 err_union_ty.fmt(pt),
90429146 });
90439147 }
90449148 return sema.analyzeErrUnionPayload(block, src, err_union_ty, operand, operand_src, false);
......@@ -9053,7 +9157,8 @@ fn analyzeErrUnionPayload(
90539157 operand_src: LazySrcLoc,
90549158 safety_check: bool,
90559159) CompileError!Air.Inst.Ref {
9056 const mod = sema.mod;
9160 const pt = sema.pt;
9161 const mod = pt.zcu;
90579162 const payload_ty = err_union_ty.errorUnionPayload(mod);
90589163 if (try sema.resolveDefinedValue(block, operand_src, operand)) |val| {
90599164 if (val.getErrorName(mod).unwrap()) |name| {
......@@ -9098,19 +9203,20 @@ fn analyzeErrUnionPayloadPtr(
90989203 safety_check: bool,
90999204 initializing: bool,
91009205) CompileError!Air.Inst.Ref {
9101 const zcu = sema.mod;
9206 const pt = sema.pt;
9207 const zcu = pt.zcu;
91029208 const operand_ty = sema.typeOf(operand);
91039209 assert(operand_ty.zigTypeTag(zcu) == .Pointer);
91049210
91059211 if (operand_ty.childType(zcu).zigTypeTag(zcu) != .ErrorUnion) {
91069212 return sema.fail(block, src, "expected error union type, found '{}'", .{
9107 operand_ty.childType(zcu).fmt(zcu),
9213 operand_ty.childType(zcu).fmt(pt),
91089214 });
91099215 }
91109216
91119217 const err_union_ty = operand_ty.childType(zcu);
91129218 const payload_ty = err_union_ty.errorUnionPayload(zcu);
9113 const operand_pointer_ty = try zcu.ptrTypeSema(.{
9219 const operand_pointer_ty = try pt.ptrTypeSema(.{
91149220 .child = payload_ty.toIntern(),
91159221 .flags = .{
91169222 .is_const = operand_ty.isConstPtr(zcu),
......@@ -9123,8 +9229,8 @@ fn analyzeErrUnionPayloadPtr(
91239229 if (sema.isComptimeMutablePtr(ptr_val)) {
91249230 // Set the error union to non-error at comptime.
91259231 // If the payload is OPV, we must use that value instead of undef.
9126 const payload_val = try sema.typeHasOnePossibleValue(payload_ty) orelse try zcu.undefValue(payload_ty);
9127 const eu_val = try zcu.intern(.{ .error_union = .{
9232 const payload_val = try sema.typeHasOnePossibleValue(payload_ty) orelse try pt.undefValue(payload_ty);
9233 const eu_val = try pt.intern(.{ .error_union = .{
91289234 .ty = err_union_ty.toIntern(),
91299235 .val = .{ .payload = payload_val.toIntern() },
91309236 } });
......@@ -9135,13 +9241,13 @@ fn analyzeErrUnionPayloadPtr(
91359241 const eu_payload_ptr = try block.addTyOp(.errunion_payload_ptr_set, operand_pointer_ty, operand);
91369242 try sema.checkKnownAllocPtr(block, operand, eu_payload_ptr);
91379243 }
9138 return Air.internedToRef((try ptr_val.ptrEuPayload(zcu)).toIntern());
9244 return Air.internedToRef((try ptr_val.ptrEuPayload(pt)).toIntern());
91399245 }
91409246 if (try sema.pointerDeref(block, src, ptr_val, operand_ty)) |val| {
91419247 if (val.getErrorName(zcu).unwrap()) |name| {
91429248 return sema.failWithComptimeErrorRetTrace(block, src, name);
91439249 }
9144 return Air.internedToRef((try ptr_val.ptrEuPayload(zcu)).toIntern());
9250 return Air.internedToRef((try ptr_val.ptrEuPayload(pt)).toIntern());
91459251 }
91469252 }
91479253
......@@ -9175,18 +9281,19 @@ fn zirErrUnionCode(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
91759281}
91769282
91779283fn analyzeErrUnionCode(sema: *Sema, block: *Block, src: LazySrcLoc, operand: Air.Inst.Ref) CompileError!Air.Inst.Ref {
9178 const mod = sema.mod;
9284 const pt = sema.pt;
9285 const mod = pt.zcu;
91799286 const operand_ty = sema.typeOf(operand);
91809287 if (operand_ty.zigTypeTag(mod) != .ErrorUnion) {
91819288 return sema.fail(block, src, "expected error union type, found '{}'", .{
9182 operand_ty.fmt(mod),
9289 operand_ty.fmt(pt),
91839290 });
91849291 }
91859292
91869293 const result_ty = operand_ty.errorUnionSet(mod);
91879294
91889295 if (try sema.resolveDefinedValue(block, src, operand)) |val| {
9189 return Air.internedToRef((try mod.intern(.{ .err = .{
9296 return Air.internedToRef((try pt.intern(.{ .err = .{
91909297 .ty = result_ty.toIntern(),
91919298 .name = mod.intern_pool.indexToKey(val.toIntern()).error_union.val.err_name,
91929299 } })));
......@@ -9208,13 +9315,14 @@ fn zirErrUnionCodePtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileE
92089315}
92099316
92109317fn analyzeErrUnionCodePtr(sema: *Sema, block: *Block, src: LazySrcLoc, operand: Air.Inst.Ref) CompileError!Air.Inst.Ref {
9211 const mod = sema.mod;
9318 const pt = sema.pt;
9319 const mod = pt.zcu;
92129320 const operand_ty = sema.typeOf(operand);
92139321 assert(operand_ty.zigTypeTag(mod) == .Pointer);
92149322
92159323 if (operand_ty.childType(mod).zigTypeTag(mod) != .ErrorUnion) {
92169324 return sema.fail(block, src, "expected error union type, found '{}'", .{
9217 operand_ty.childType(mod).fmt(mod),
9325 operand_ty.childType(mod).fmt(pt),
92189326 });
92199327 }
92209328
......@@ -9223,7 +9331,7 @@ fn analyzeErrUnionCodePtr(sema: *Sema, block: *Block, src: LazySrcLoc, operand:
92239331 if (try sema.resolveDefinedValue(block, src, operand)) |pointer_val| {
92249332 if (try sema.pointerDeref(block, src, pointer_val, operand_ty)) |val| {
92259333 assert(val.getErrorName(mod) != .none);
9226 return Air.internedToRef((try mod.intern(.{ .err = .{
9334 return Air.internedToRef((try pt.intern(.{ .err = .{
92279335 .ty = result_ty.toIntern(),
92289336 .name = mod.intern_pool.indexToKey(val.toIntern()).error_union.val.err_name,
92299337 } })));
......@@ -9240,10 +9348,11 @@ fn zirFunc(
92409348 inst: Zir.Inst.Index,
92419349 inferred_error_set: bool,
92429350) CompileError!Air.Inst.Ref {
9243 const mod = sema.mod;
9351 const pt = sema.pt;
9352 const mod = pt.zcu;
92449353 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
92459354 const extra = sema.code.extraData(Zir.Inst.Func, inst_data.payload_index);
9246 const target = sema.mod.getTarget();
9355 const target = mod.getTarget();
92479356 const ret_ty_src = block.src(.{ .node_offset_fn_type_ret_ty = inst_data.src_node });
92489357
92499358 var extra_index = extra.end;
......@@ -9372,7 +9481,8 @@ fn handleExternLibName(
93729481 lib_name: []const u8,
93739482) CompileError!void {
93749483 blk: {
9375 const mod = sema.mod;
9484 const pt = sema.pt;
9485 const mod = pt.zcu;
93769486 const comp = mod.comp;
93779487 const target = mod.getTarget();
93789488 log.debug("extern fn symbol expected in lib '{s}'", .{lib_name});
......@@ -9485,7 +9595,8 @@ fn funcCommon(
94859595 noalias_bits: u32,
94869596 is_noinline: bool,
94879597) CompileError!Air.Inst.Ref {
9488 const mod = sema.mod;
9598 const pt = sema.pt;
9599 const mod = pt.zcu;
94899600 const gpa = sema.gpa;
94909601 const target = mod.getTarget();
94919602 const ip = &mod.intern_pool;
......@@ -9539,13 +9650,13 @@ fn funcCommon(
95399650 if (!param_ty.isValidParamType(mod)) {
95409651 const opaque_str = if (param_ty.zigTypeTag(mod) == .Opaque) "opaque " else "";
95419652 return sema.fail(block, param_src, "parameter of {s}type '{}' not allowed", .{
9542 opaque_str, param_ty.fmt(mod),
9653 opaque_str, param_ty.fmt(pt),
95439654 });
95449655 }
95459656 if (!this_generic and !target_util.fnCallConvAllowsZigTypes(target, cc_resolved) and !try sema.validateExternType(param_ty, .param_ty)) {
95469657 const msg = msg: {
95479658 const msg = try sema.errMsg(param_src, "parameter of type '{}' not allowed in function with calling convention '{s}'", .{
9548 param_ty.fmt(mod), @tagName(cc_resolved),
9659 param_ty.fmt(pt), @tagName(cc_resolved),
95499660 });
95509661 errdefer msg.destroy(sema.gpa);
95519662
......@@ -9559,7 +9670,7 @@ fn funcCommon(
95599670 if (is_source_decl and requires_comptime and !param_is_comptime and has_body and !block.is_comptime) {
95609671 const msg = msg: {
95619672 const msg = try sema.errMsg(param_src, "parameter of type '{}' must be declared comptime", .{
9562 param_ty.fmt(mod),
9673 param_ty.fmt(pt),
95639674 });
95649675 errdefer msg.destroy(sema.gpa);
95659676
......@@ -9580,7 +9691,7 @@ fn funcCommon(
95809691 const err_code_size = target.ptrBitWidth();
95819692 switch (i) {
95829693 0 => if (param_ty.zigTypeTag(mod) != .Pointer) return sema.fail(block, param_src, "first parameter of function with 'Interrupt' calling convention must be a pointer type", .{}),
9583 1 => if (param_ty.bitSize(mod) != err_code_size) return sema.fail(block, param_src, "second parameter of function with 'Interrupt' calling convention must be a {d}-bit integer", .{err_code_size}),
9694 1 => if (param_ty.bitSize(pt) != err_code_size) return sema.fail(block, param_src, "second parameter of function with 'Interrupt' calling convention must be a {d}-bit integer", .{err_code_size}),
95849695 else => return sema.fail(block, param_src, "'Interrupt' calling convention supports up to 2 parameters, found {d}", .{i + 1}),
95859696 }
95869697 } else return sema.fail(block, param_src, "parameters are not allowed with 'Interrupt' calling convention", .{}),
......@@ -9606,7 +9717,7 @@ fn funcCommon(
96069717 if (inferred_error_set) {
96079718 try sema.validateErrorUnionPayloadType(block, bare_return_type, ret_ty_src);
96089719 }
9609 const func_index = try ip.getFuncInstance(gpa, .{
9720 const func_index = try ip.getFuncInstance(gpa, pt.tid, .{
96109721 .param_types = param_types,
96119722 .noalias_bits = noalias_bits,
96129723 .bare_return_type = bare_return_type.toIntern(),
......@@ -9655,7 +9766,7 @@ fn funcCommon(
96559766 assert(has_body);
96569767 if (!ret_poison)
96579768 try sema.validateErrorUnionPayloadType(block, bare_return_type, ret_ty_src);
9658 const func_index = try ip.getFuncDeclIes(gpa, .{
9769 const func_index = try ip.getFuncDeclIes(gpa, pt.tid, .{
96599770 .owner_decl = sema.owner_decl_index,
96609771
96619772 .param_types = param_types,
......@@ -9695,7 +9806,7 @@ fn funcCommon(
96959806 );
96969807 }
96979808
9698 const func_ty = try ip.getFuncType(gpa, .{
9809 const func_ty = try ip.getFuncType(gpa, pt.tid, .{
96999810 .param_types = param_types,
97009811 .noalias_bits = noalias_bits,
97019812 .comptime_bits = comptime_bits,
......@@ -9718,10 +9829,10 @@ fn funcCommon(
97189829 if (opt_lib_name) |lib_name| try sema.handleExternLibName(block, block.src(.{
97199830 .node_offset_lib_name = src_node_offset,
97209831 }), lib_name);
9721 const func_index = try ip.getExternFunc(gpa, .{
9832 const func_index = try ip.getExternFunc(gpa, pt.tid, .{
97229833 .ty = func_ty,
97239834 .decl = sema.owner_decl_index,
9724 .lib_name = try mod.intern_pool.getOrPutStringOpt(gpa, opt_lib_name, .no_embedded_nulls),
9835 .lib_name = try mod.intern_pool.getOrPutStringOpt(gpa, pt.tid, opt_lib_name, .no_embedded_nulls),
97259836 });
97269837 return finishFunc(
97279838 sema,
......@@ -9743,7 +9854,7 @@ fn funcCommon(
97439854 }
97449855
97459856 if (has_body) {
9746 const func_index = try ip.getFuncDecl(gpa, .{
9857 const func_index = try ip.getFuncDecl(gpa, pt.tid, .{
97479858 .owner_decl = sema.owner_decl_index,
97489859 .ty = func_ty,
97499860 .cc = cc,
......@@ -9809,7 +9920,8 @@ fn finishFunc(
98099920 is_generic: bool,
98109921 final_is_generic: bool,
98119922) CompileError!Air.Inst.Ref {
9812 const mod = sema.mod;
9923 const pt = sema.pt;
9924 const mod = pt.zcu;
98139925 const ip = &mod.intern_pool;
98149926 const gpa = sema.gpa;
98159927 const target = mod.getTarget();
......@@ -9822,7 +9934,7 @@ fn finishFunc(
98229934 if (!return_type.isValidReturnType(mod)) {
98239935 const opaque_str = if (return_type.zigTypeTag(mod) == .Opaque) "opaque " else "";
98249936 return sema.fail(block, ret_ty_src, "{s}return type '{}' not allowed", .{
9825 opaque_str, return_type.fmt(mod),
9937 opaque_str, return_type.fmt(pt),
98269938 });
98279939 }
98289940 if (!ret_poison and !target_util.fnCallConvAllowsZigTypes(target, cc_resolved) and
......@@ -9830,7 +9942,7 @@ fn finishFunc(
98309942 {
98319943 const msg = msg: {
98329944 const msg = try sema.errMsg(ret_ty_src, "return type '{}' not allowed in function with calling convention '{s}'", .{
9833 return_type.fmt(mod), @tagName(cc_resolved),
9945 return_type.fmt(pt), @tagName(cc_resolved),
98349946 });
98359947 errdefer msg.destroy(gpa);
98369948
......@@ -9852,7 +9964,7 @@ fn finishFunc(
98529964 const msg = try sema.errMsg(
98539965 ret_ty_src,
98549966 "function with comptime-only return type '{}' requires all parameters to be comptime",
9855 .{return_type.fmt(mod)},
9967 .{return_type.fmt(pt)},
98569968 );
98579969 try sema.explainWhyTypeIsComptime(msg, ret_ty_src, return_type);
98589970
......@@ -9938,8 +10050,8 @@ fn finishFunc(
993810050 if (!final_is_generic and sema.wantErrorReturnTracing(return_type)) {
993910051 // Make sure that StackTrace's fields are resolved so that the backend can
994010052 // lower this fn type.
9941 const unresolved_stack_trace_ty = try mod.getBuiltinType("StackTrace");
9942 try unresolved_stack_trace_ty.resolveFields(mod);
10053 const unresolved_stack_trace_ty = try pt.getBuiltinType("StackTrace");
10054 try unresolved_stack_trace_ty.resolveFields(pt);
994310055 }
994410056
994510057 return Air.internedToRef(if (opt_func_index != .none) opt_func_index else func_ty);
......@@ -10068,7 +10180,8 @@ fn analyzeAs(
1006810180 zir_operand: Zir.Inst.Ref,
1006910181 no_cast_to_comptime_int: bool,
1007010182) CompileError!Air.Inst.Ref {
10071 const mod = sema.mod;
10183 const pt = sema.pt;
10184 const mod = pt.zcu;
1007210185 const operand = try sema.resolveInst(zir_operand);
1007310186 const operand_air_inst = sema.resolveInst(zir_dest_type) catch |err| switch (err) {
1007410187 error.GenericPoison => return operand,
......@@ -10098,7 +10211,8 @@ fn zirIntFromPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
1009810211 const tracy = trace(@src());
1009910212 defer tracy.end();
1010010213
10101 const zcu = sema.mod;
10214 const pt = sema.pt;
10215 const zcu = pt.zcu;
1010210216 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1010310217 const ptr_src = block.builtinCallArgSrc(inst_data.src_node, 0);
1010410218 const operand = try sema.resolveInst(inst_data.operand);
......@@ -10106,12 +10220,12 @@ fn zirIntFromPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
1010610220 const ptr_ty = operand_ty.scalarType(zcu);
1010710221 const is_vector = operand_ty.zigTypeTag(zcu) == .Vector;
1010810222 if (!ptr_ty.isPtrAtRuntime(zcu)) {
10109 return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ty.fmt(zcu)});
10223 return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ty.fmt(pt)});
1011010224 }
1011110225 const pointee_ty = ptr_ty.childType(zcu);
1011210226 if (try sema.typeRequiresComptime(ptr_ty)) {
1011310227 const msg = msg: {
10114 const msg = try sema.errMsg(ptr_src, "comptime-only type '{}' has no pointer address", .{pointee_ty.fmt(zcu)});
10228 const msg = try sema.errMsg(ptr_src, "comptime-only type '{}' has no pointer address", .{pointee_ty.fmt(pt)});
1011510229 errdefer msg.destroy(sema.gpa);
1011610230 try sema.explainWhyTypeIsComptime(msg, ptr_src, pointee_ty);
1011710231 break :msg msg;
......@@ -10121,32 +10235,32 @@ fn zirIntFromPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
1012110235 if (try sema.resolveValueIntable(operand)) |operand_val| ct: {
1012210236 if (!is_vector) {
1012310237 if (operand_val.isUndef(zcu)) {
10124 return Air.internedToRef((try zcu.undefValue(Type.usize)).toIntern());
10238 return Air.internedToRef((try pt.undefValue(Type.usize)).toIntern());
1012510239 }
10126 return Air.internedToRef((try zcu.intValue(
10240 return Air.internedToRef((try pt.intValue(
1012710241 Type.usize,
10128 (try operand_val.getUnsignedIntAdvanced(zcu, .sema)).?,
10242 (try operand_val.getUnsignedIntAdvanced(pt, .sema)).?,
1012910243 )).toIntern());
1013010244 }
1013110245 const len = operand_ty.vectorLen(zcu);
10132 const dest_ty = try zcu.vectorType(.{ .child = .usize_type, .len = len });
10246 const dest_ty = try pt.vectorType(.{ .child = .usize_type, .len = len });
1013310247 const new_elems = try sema.arena.alloc(InternPool.Index, len);
1013410248 for (new_elems, 0..) |*new_elem, i| {
10135 const ptr_val = try operand_val.elemValue(zcu, i);
10249 const ptr_val = try operand_val.elemValue(pt, i);
1013610250 if (ptr_val.isUndef(zcu)) {
10137 new_elem.* = (try zcu.undefValue(Type.usize)).toIntern();
10251 new_elem.* = (try pt.undefValue(Type.usize)).toIntern();
1013810252 continue;
1013910253 }
10140 const addr = try ptr_val.getUnsignedIntAdvanced(zcu, .sema) orelse {
10254 const addr = try ptr_val.getUnsignedIntAdvanced(pt, .sema) orelse {
1014110255 // A vector element wasn't an integer pointer. This is a runtime operation.
1014210256 break :ct;
1014310257 };
10144 new_elem.* = (try zcu.intValue(
10258 new_elem.* = (try pt.intValue(
1014510259 Type.usize,
1014610260 addr,
1014710261 )).toIntern();
1014810262 }
10149 return Air.internedToRef(try zcu.intern(.{ .aggregate = .{
10263 return Air.internedToRef(try pt.intern(.{ .aggregate = .{
1015010264 .ty = dest_ty.toIntern(),
1015110265 .storage = .{ .elems = new_elems },
1015210266 } }));
......@@ -10157,10 +10271,10 @@ fn zirIntFromPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
1015710271 return block.addUnOp(.int_from_ptr, operand);
1015810272 }
1015910273 const len = operand_ty.vectorLen(zcu);
10160 const dest_ty = try zcu.vectorType(.{ .child = .usize_type, .len = len });
10274 const dest_ty = try pt.vectorType(.{ .child = .usize_type, .len = len });
1016110275 const new_elems = try sema.arena.alloc(Air.Inst.Ref, len);
1016210276 for (new_elems, 0..) |*new_elem, i| {
10163 const idx_ref = try zcu.intRef(Type.usize, i);
10277 const idx_ref = try pt.intRef(Type.usize, i);
1016410278 const old_elem = try block.addBinOp(.array_elem_val, operand, idx_ref);
1016510279 new_elem.* = try block.addUnOp(.int_from_ptr, old_elem);
1016610280 }
......@@ -10171,13 +10285,15 @@ fn zirFieldVal(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1017110285 const tracy = trace(@src());
1017210286 defer tracy.end();
1017310287
10174 const mod = sema.mod;
10288 const pt = sema.pt;
10289 const mod = pt.zcu;
1017510290 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1017610291 const src = block.nodeOffset(inst_data.src_node);
1017710292 const field_name_src = block.src(.{ .node_offset_field_name = inst_data.src_node });
1017810293 const extra = sema.code.extraData(Zir.Inst.Field, inst_data.payload_index).data;
1017910294 const field_name = try mod.intern_pool.getOrPutString(
1018010295 sema.gpa,
10296 pt.tid,
1018110297 sema.code.nullTerminatedString(extra.field_name_start),
1018210298 .no_embedded_nulls,
1018310299 );
......@@ -10189,13 +10305,15 @@ fn zirFieldPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1018910305 const tracy = trace(@src());
1019010306 defer tracy.end();
1019110307
10192 const mod = sema.mod;
10308 const pt = sema.pt;
10309 const mod = pt.zcu;
1019310310 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1019410311 const src = block.nodeOffset(inst_data.src_node);
1019510312 const field_name_src = block.src(.{ .node_offset_field_name = inst_data.src_node });
1019610313 const extra = sema.code.extraData(Zir.Inst.Field, inst_data.payload_index).data;
1019710314 const field_name = try mod.intern_pool.getOrPutString(
1019810315 sema.gpa,
10316 pt.tid,
1019910317 sema.code.nullTerminatedString(extra.field_name_start),
1020010318 .no_embedded_nulls,
1020110319 );
......@@ -10207,13 +10325,15 @@ fn zirStructInitFieldPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Compi
1020710325 const tracy = trace(@src());
1020810326 defer tracy.end();
1020910327
10210 const mod = sema.mod;
10328 const pt = sema.pt;
10329 const mod = pt.zcu;
1021110330 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1021210331 const src = block.nodeOffset(inst_data.src_node);
1021310332 const field_name_src = block.src(.{ .node_offset_field_name_init = inst_data.src_node });
1021410333 const extra = sema.code.extraData(Zir.Inst.Field, inst_data.payload_index).data;
1021510334 const field_name = try mod.intern_pool.getOrPutString(
1021610335 sema.gpa,
10336 pt.tid,
1021710337 sema.code.nullTerminatedString(extra.field_name_start),
1021810338 .no_embedded_nulls,
1021910339 );
......@@ -10284,7 +10404,8 @@ fn intCast(
1028410404 operand_src: LazySrcLoc,
1028510405 runtime_safety: bool,
1028610406) CompileError!Air.Inst.Ref {
10287 const mod = sema.mod;
10407 const pt = sema.pt;
10408 const mod = pt.zcu;
1028810409 const operand_ty = sema.typeOf(operand);
1028910410 const dest_scalar_ty = try sema.checkIntOrVectorAllowComptime(block, dest_ty, dest_ty_src);
1029010411 const operand_scalar_ty = try sema.checkIntOrVectorAllowComptime(block, operand_ty, operand_src);
......@@ -10307,7 +10428,7 @@ fn intCast(
1030710428
1030810429 if (wanted_bits == 0) {
1030910430 const ok = if (is_vector) ok: {
10310 const zeros = try sema.splat(operand_ty, try mod.intValue(operand_scalar_ty, 0));
10431 const zeros = try sema.splat(operand_ty, try pt.intValue(operand_scalar_ty, 0));
1031110432 const zero_inst = Air.internedToRef(zeros.toIntern());
1031210433 const is_in_range = try block.addCmpVector(operand, zero_inst, .eq);
1031310434 const all_in_range = try block.addInst(.{
......@@ -10316,7 +10437,7 @@ fn intCast(
1031610437 });
1031710438 break :ok all_in_range;
1031810439 } else ok: {
10319 const zero_inst = Air.internedToRef((try mod.intValue(operand_ty, 0)).toIntern());
10440 const zero_inst = Air.internedToRef((try pt.intValue(operand_ty, 0)).toIntern());
1032010441 const is_in_range = try block.addBinOp(.cmp_lte, operand, zero_inst);
1032110442 break :ok is_in_range;
1032210443 };
......@@ -10339,7 +10460,7 @@ fn intCast(
1033910460 // range shrinkage
1034010461 // requirement: int value fits into target type
1034110462 if (wanted_value_bits < actual_value_bits) {
10342 const dest_max_val_scalar = try dest_scalar_ty.maxIntScalar(mod, operand_scalar_ty);
10463 const dest_max_val_scalar = try dest_scalar_ty.maxIntScalar(pt, operand_scalar_ty);
1034310464 const dest_max_val = try sema.splat(operand_ty, dest_max_val_scalar);
1034410465 const dest_max = Air.internedToRef(dest_max_val.toIntern());
1034510466
......@@ -10348,8 +10469,8 @@ fn intCast(
1034810469
1034910470 // Reinterpret the sign-bit as part of the value. This will make
1035010471 // negative differences (`operand` > `dest_max`) appear too big.
10351 const unsigned_scalar_operand_ty = try mod.intType(.unsigned, actual_bits);
10352 const unsigned_operand_ty = if (is_vector) try mod.vectorType(.{
10472 const unsigned_scalar_operand_ty = try pt.intType(.unsigned, actual_bits);
10473 const unsigned_operand_ty = if (is_vector) try pt.vectorType(.{
1035310474 .len = dest_ty.vectorLen(mod),
1035410475 .child = unsigned_scalar_operand_ty.toIntern(),
1035510476 }) else unsigned_scalar_operand_ty;
......@@ -10358,14 +10479,14 @@ fn intCast(
1035810479 // If the destination type is signed, then we need to double its
1035910480 // range to account for negative values.
1036010481 const dest_range_val = if (wanted_info.signedness == .signed) range_val: {
10361 const one_scalar = try mod.intValue(unsigned_scalar_operand_ty, 1);
10362 const one = if (is_vector) Value.fromInterned((try mod.intern(.{ .aggregate = .{
10482 const one_scalar = try pt.intValue(unsigned_scalar_operand_ty, 1);
10483 const one = if (is_vector) Value.fromInterned(try pt.intern(.{ .aggregate = .{
1036310484 .ty = unsigned_operand_ty.toIntern(),
1036410485 .storage = .{ .repeated_elem = one_scalar.toIntern() },
10365 } }))) else one_scalar;
10366 const range_minus_one = try dest_max_val.shl(one, unsigned_operand_ty, sema.arena, mod);
10486 } })) else one_scalar;
10487 const range_minus_one = try dest_max_val.shl(one, unsigned_operand_ty, sema.arena, pt);
1036710488 break :range_val try sema.intAdd(range_minus_one, one, unsigned_operand_ty, undefined);
10368 } else try mod.getCoerced(dest_max_val, unsigned_operand_ty);
10489 } else try pt.getCoerced(dest_max_val, unsigned_operand_ty);
1036910490 const dest_range = Air.internedToRef(dest_range_val.toIntern());
1037010491
1037110492 const ok = if (is_vector) ok: {
......@@ -10405,7 +10526,7 @@ fn intCast(
1040510526 // no shrinkage, yes sign loss
1040610527 // requirement: signed to unsigned >= 0
1040710528 const ok = if (is_vector) ok: {
10408 const scalar_zero = try mod.intValue(operand_scalar_ty, 0);
10529 const scalar_zero = try pt.intValue(operand_scalar_ty, 0);
1040910530 const zero_val = try sema.splat(operand_ty, scalar_zero);
1041010531 const zero_inst = Air.internedToRef(zero_val.toIntern());
1041110532 const is_in_range = try block.addCmpVector(operand, zero_inst, .gte);
......@@ -10418,7 +10539,7 @@ fn intCast(
1041810539 });
1041910540 break :ok all_in_range;
1042010541 } else ok: {
10421 const zero_inst = Air.internedToRef((try mod.intValue(operand_ty, 0)).toIntern());
10542 const zero_inst = Air.internedToRef((try pt.intValue(operand_ty, 0)).toIntern());
1042210543 const is_in_range = try block.addBinOp(.cmp_gte, operand, zero_inst);
1042310544 break :ok is_in_range;
1042410545 };
......@@ -10432,7 +10553,8 @@ fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1043210553 const tracy = trace(@src());
1043310554 defer tracy.end();
1043410555
10435 const mod = sema.mod;
10556 const pt = sema.pt;
10557 const mod = pt.zcu;
1043610558 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1043710559 const src = block.nodeOffset(inst_data.src_node);
1043810560 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
......@@ -10457,14 +10579,14 @@ fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1045710579 .Type,
1045810580 .Undefined,
1045910581 .Void,
10460 => return sema.fail(block, src, "cannot @bitCast to '{}'", .{dest_ty.fmt(mod)}),
10582 => return sema.fail(block, src, "cannot @bitCast to '{}'", .{dest_ty.fmt(pt)}),
1046110583
1046210584 .Enum => {
1046310585 const msg = msg: {
10464 const msg = try sema.errMsg(src, "cannot @bitCast to '{}'", .{dest_ty.fmt(mod)});
10586 const msg = try sema.errMsg(src, "cannot @bitCast to '{}'", .{dest_ty.fmt(pt)});
1046510587 errdefer msg.destroy(sema.gpa);
1046610588 switch (operand_ty.zigTypeTag(mod)) {
10467 .Int, .ComptimeInt => try sema.errNote(src, msg, "use @enumFromInt to cast from '{}'", .{operand_ty.fmt(mod)}),
10589 .Int, .ComptimeInt => try sema.errNote(src, msg, "use @enumFromInt to cast from '{}'", .{operand_ty.fmt(pt)}),
1046810590 else => {},
1046910591 }
1047010592
......@@ -10475,11 +10597,11 @@ fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1047510597
1047610598 .Pointer => {
1047710599 const msg = msg: {
10478 const msg = try sema.errMsg(src, "cannot @bitCast to '{}'", .{dest_ty.fmt(mod)});
10600 const msg = try sema.errMsg(src, "cannot @bitCast to '{}'", .{dest_ty.fmt(pt)});
1047910601 errdefer msg.destroy(sema.gpa);
1048010602 switch (operand_ty.zigTypeTag(mod)) {
10481 .Int, .ComptimeInt => try sema.errNote(src, msg, "use @ptrFromInt to cast from '{}'", .{operand_ty.fmt(mod)}),
10482 .Pointer => try sema.errNote(src, msg, "use @ptrCast to cast from '{}'", .{operand_ty.fmt(mod)}),
10603 .Int, .ComptimeInt => try sema.errNote(src, msg, "use @ptrFromInt to cast from '{}'", .{operand_ty.fmt(pt)}),
10604 .Pointer => try sema.errNote(src, msg, "use @ptrCast to cast from '{}'", .{operand_ty.fmt(pt)}),
1048310605 else => {},
1048410606 }
1048510607
......@@ -10494,7 +10616,7 @@ fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1049410616 else => unreachable,
1049510617 };
1049610618 return sema.fail(block, src, "cannot @bitCast to '{}'; {s} does not have a guaranteed in-memory layout", .{
10497 dest_ty.fmt(mod), container,
10619 dest_ty.fmt(pt), container,
1049810620 });
1049910621 },
1050010622
......@@ -10521,14 +10643,14 @@ fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1052110643 .Type,
1052210644 .Undefined,
1052310645 .Void,
10524 => return sema.fail(block, operand_src, "cannot @bitCast from '{}'", .{operand_ty.fmt(mod)}),
10646 => return sema.fail(block, operand_src, "cannot @bitCast from '{}'", .{operand_ty.fmt(pt)}),
1052510647
1052610648 .Enum => {
1052710649 const msg = msg: {
10528 const msg = try sema.errMsg(operand_src, "cannot @bitCast from '{}'", .{operand_ty.fmt(mod)});
10650 const msg = try sema.errMsg(operand_src, "cannot @bitCast from '{}'", .{operand_ty.fmt(pt)});
1052910651 errdefer msg.destroy(sema.gpa);
1053010652 switch (dest_ty.zigTypeTag(mod)) {
10531 .Int, .ComptimeInt => try sema.errNote(operand_src, msg, "use @intFromEnum to cast to '{}'", .{dest_ty.fmt(mod)}),
10653 .Int, .ComptimeInt => try sema.errNote(operand_src, msg, "use @intFromEnum to cast to '{}'", .{dest_ty.fmt(pt)}),
1053210654 else => {},
1053310655 }
1053410656
......@@ -10538,11 +10660,11 @@ fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1053810660 },
1053910661 .Pointer => {
1054010662 const msg = msg: {
10541 const msg = try sema.errMsg(operand_src, "cannot @bitCast from '{}'", .{operand_ty.fmt(mod)});
10663 const msg = try sema.errMsg(operand_src, "cannot @bitCast from '{}'", .{operand_ty.fmt(pt)});
1054210664 errdefer msg.destroy(sema.gpa);
1054310665 switch (dest_ty.zigTypeTag(mod)) {
10544 .Int, .ComptimeInt => try sema.errNote(operand_src, msg, "use @intFromPtr to cast to '{}'", .{dest_ty.fmt(mod)}),
10545 .Pointer => try sema.errNote(operand_src, msg, "use @ptrCast to cast to '{}'", .{dest_ty.fmt(mod)}),
10666 .Int, .ComptimeInt => try sema.errNote(operand_src, msg, "use @intFromPtr to cast to '{}'", .{dest_ty.fmt(pt)}),
10667 .Pointer => try sema.errNote(operand_src, msg, "use @ptrCast to cast to '{}'", .{dest_ty.fmt(pt)}),
1054610668 else => {},
1054710669 }
1054810670
......@@ -10557,7 +10679,7 @@ fn zirBitcast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1055710679 else => unreachable,
1055810680 };
1055910681 return sema.fail(block, operand_src, "cannot @bitCast from '{}'; {s} does not have a guaranteed in-memory layout", .{
10560 operand_ty.fmt(mod), container,
10682 operand_ty.fmt(pt), container,
1056110683 });
1056210684 },
1056310685
......@@ -10575,7 +10697,8 @@ fn zirFloatCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
1057510697 const tracy = trace(@src());
1057610698 defer tracy.end();
1057710699
10578 const mod = sema.mod;
10700 const pt = sema.pt;
10701 const mod = pt.zcu;
1057910702 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1058010703 const src = block.nodeOffset(inst_data.src_node);
1058110704 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
......@@ -10599,7 +10722,7 @@ fn zirFloatCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
1059910722 block,
1060010723 src,
1060110724 "expected float or vector type, found '{}'",
10602 .{dest_ty.fmt(mod)},
10725 .{dest_ty.fmt(pt)},
1060310726 ),
1060410727 };
1060510728
......@@ -10609,21 +10732,21 @@ fn zirFloatCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
1060910732 block,
1061010733 operand_src,
1061110734 "expected float or vector type, found '{}'",
10612 .{operand_ty.fmt(mod)},
10735 .{operand_ty.fmt(pt)},
1061310736 ),
1061410737 }
1061510738
1061610739 if (try sema.resolveValue(operand)) |operand_val| {
1061710740 if (!is_vector) {
10618 return Air.internedToRef((try operand_val.floatCast(dest_ty, mod)).toIntern());
10741 return Air.internedToRef((try operand_val.floatCast(dest_ty, pt)).toIntern());
1061910742 }
1062010743 const vec_len = operand_ty.vectorLen(mod);
1062110744 const new_elems = try sema.arena.alloc(InternPool.Index, vec_len);
1062210745 for (new_elems, 0..) |*new_elem, i| {
10623 const old_elem = try operand_val.elemValue(mod, i);
10624 new_elem.* = (try old_elem.floatCast(dest_scalar_ty, mod)).toIntern();
10746 const old_elem = try operand_val.elemValue(pt, i);
10747 new_elem.* = (try old_elem.floatCast(dest_scalar_ty, pt)).toIntern();
1062510748 }
10626 return Air.internedToRef(try mod.intern(.{ .aggregate = .{
10749 return Air.internedToRef(try pt.intern(.{ .aggregate = .{
1062710750 .ty = dest_ty.toIntern(),
1062810751 .storage = .{ .elems = new_elems },
1062910752 } }));
......@@ -10644,7 +10767,7 @@ fn zirFloatCast(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
1064410767 const vec_len = operand_ty.vectorLen(mod);
1064510768 const new_elems = try sema.arena.alloc(Air.Inst.Ref, vec_len);
1064610769 for (new_elems, 0..) |*new_elem, i| {
10647 const idx_ref = try mod.intRef(Type.usize, i);
10770 const idx_ref = try pt.intRef(Type.usize, i);
1064810771 const old_elem = try block.addBinOp(.array_elem_val, operand, idx_ref);
1064910772 new_elem.* = try block.addTyOp(.fptrunc, dest_scalar_ty, old_elem);
1065010773 }
......@@ -10681,10 +10804,9 @@ fn zirElemValImm(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
1068110804 const tracy = trace(@src());
1068210805 defer tracy.end();
1068310806
10684 const mod = sema.mod;
1068510807 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].elem_val_imm;
1068610808 const array = try sema.resolveInst(inst_data.operand);
10687 const elem_index = try mod.intRef(Type.usize, inst_data.idx);
10809 const elem_index = try sema.pt.intRef(Type.usize, inst_data.idx);
1068810810 return sema.elemVal(block, LazySrcLoc.unneeded, array, elem_index, LazySrcLoc.unneeded, false);
1068910811}
1069010812
......@@ -10692,7 +10814,8 @@ fn zirElemPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1069210814 const tracy = trace(@src());
1069310815 defer tracy.end();
1069410816
10695 const mod = sema.mod;
10817 const pt = sema.pt;
10818 const mod = pt.zcu;
1069610819 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1069710820 const src = block.nodeOffset(inst_data.src_node);
1069810821 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
......@@ -10703,7 +10826,7 @@ fn zirElemPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1070310826 const capture_src = block.src(.{ .for_capture_from_input = inst_data.src_node });
1070410827 const msg = msg: {
1070510828 const msg = try sema.errMsg(capture_src, "pointer capture of non pointer type '{}'", .{
10706 indexable_ty.fmt(mod),
10829 indexable_ty.fmt(pt),
1070710830 });
1070810831 errdefer msg.destroy(sema.gpa);
1070910832 if (indexable_ty.isIndexable(mod)) {
......@@ -10734,12 +10857,13 @@ fn zirArrayInitElemPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Compile
1073410857 const tracy = trace(@src());
1073510858 defer tracy.end();
1073610859
10737 const mod = sema.mod;
10860 const pt = sema.pt;
10861 const mod = pt.zcu;
1073810862 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1073910863 const src = block.nodeOffset(inst_data.src_node);
1074010864 const extra = sema.code.extraData(Zir.Inst.ElemPtrImm, inst_data.payload_index).data;
1074110865 const array_ptr = try sema.resolveInst(extra.ptr);
10742 const elem_index = try sema.mod.intRef(Type.usize, extra.index);
10866 const elem_index = try pt.intRef(Type.usize, extra.index);
1074310867 const array_ty = sema.typeOf(array_ptr).childType(mod);
1074410868 switch (array_ty.zigTypeTag(mod)) {
1074510869 .Array, .Vector => {},
......@@ -10892,7 +11016,7 @@ const SwitchProngAnalysis = struct {
1089211016 inline_case_capture,
1089311017 );
1089411018
10895 if (sema.typeOf(capture_ref).isNoReturn(sema.mod)) {
11019 if (sema.typeOf(capture_ref).isNoReturn(sema.pt.zcu)) {
1089611020 // This prong should be unreachable!
1089711021 return .unreachable_value;
1089811022 }
......@@ -10948,7 +11072,7 @@ const SwitchProngAnalysis = struct {
1094811072 inline_case_capture,
1094911073 );
1095011074
10951 if (sema.typeOf(capture_ref).isNoReturn(sema.mod)) {
11075 if (sema.typeOf(capture_ref).isNoReturn(sema.pt.zcu)) {
1095211076 // No need to analyze any further, the prong is unreachable
1095311077 return;
1095411078 }
......@@ -10968,7 +11092,8 @@ const SwitchProngAnalysis = struct {
1096811092 inline_case_capture: Air.Inst.Ref,
1096911093 ) CompileError!Air.Inst.Ref {
1097011094 const sema = spa.sema;
10971 const mod = sema.mod;
11095 const pt = sema.pt;
11096 const mod = pt.zcu;
1097211097 const operand_ty = sema.typeOf(spa.operand);
1097311098 if (operand_ty.zigTypeTag(mod) != .Union) {
1097411099 const tag_capture_src: LazySrcLoc = .{
......@@ -10976,7 +11101,7 @@ const SwitchProngAnalysis = struct {
1097611101 .offset = .{ .switch_tag_capture = capture_src.offset.switch_capture },
1097711102 };
1097811103 return sema.fail(block, tag_capture_src, "cannot capture tag of non-union type '{}'", .{
10979 operand_ty.fmt(mod),
11104 operand_ty.fmt(pt),
1098011105 });
1098111106 }
1098211107 assert(inline_case_capture != .none);
......@@ -10993,7 +11118,8 @@ const SwitchProngAnalysis = struct {
1099311118 inline_case_capture: Air.Inst.Ref,
1099411119 ) CompileError!Air.Inst.Ref {
1099511120 const sema = spa.sema;
10996 const zcu = sema.mod;
11121 const pt = sema.pt;
11122 const zcu = pt.zcu;
1099711123 const ip = &zcu.intern_pool;
1099811124
1099911125 const zir_datas = sema.code.instructions.items(.data);
......@@ -11010,7 +11136,7 @@ const SwitchProngAnalysis = struct {
1101011136 const union_obj = zcu.typeToUnion(operand_ty).?;
1101111137 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
1101211138 if (capture_byref) {
11013 const ptr_field_ty = try zcu.ptrTypeSema(.{
11139 const ptr_field_ty = try pt.ptrTypeSema(.{
1101411140 .child = field_ty.toIntern(),
1101511141 .flags = .{
1101611142 .is_const = !operand_ptr_ty.ptrIsMutable(zcu),
......@@ -11019,7 +11145,7 @@ const SwitchProngAnalysis = struct {
1101911145 },
1102011146 });
1102111147 if (try sema.resolveDefinedValue(block, operand_src, spa.operand_ptr)) |union_ptr| {
11022 return Air.internedToRef((try union_ptr.ptrField(field_index, zcu)).toIntern());
11148 return Air.internedToRef((try union_ptr.ptrField(field_index, pt)).toIntern());
1102311149 }
1102411150 return block.addStructFieldPtr(spa.operand_ptr, field_index, ptr_field_ty);
1102511151 } else {
......@@ -11078,7 +11204,7 @@ const SwitchProngAnalysis = struct {
1107811204 const dummy_captures = try sema.arena.alloc(Air.Inst.Ref, case_vals.len);
1107911205 for (dummy_captures, field_indices) |*dummy, field_idx| {
1108011206 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_idx]);
11081 dummy.* = try zcu.undefRef(field_ty);
11207 dummy.* = try pt.undefRef(field_ty);
1108211208 }
1108311209
1108411210 const case_srcs = try sema.arena.alloc(?LazySrcLoc, case_vals.len);
......@@ -11113,7 +11239,7 @@ const SwitchProngAnalysis = struct {
1111311239 const dummy_captures = try sema.arena.alloc(Air.Inst.Ref, case_vals.len);
1111411240 for (field_indices, dummy_captures) |field_idx, *dummy| {
1111511241 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_idx]);
11116 const field_ptr_ty = try zcu.ptrTypeSema(.{
11242 const field_ptr_ty = try pt.ptrTypeSema(.{
1111711243 .child = field_ty.toIntern(),
1111811244 .flags = .{
1111911245 .is_const = operand_ptr_info.flags.is_const,
......@@ -11122,7 +11248,7 @@ const SwitchProngAnalysis = struct {
1112211248 .alignment = union_obj.fieldAlign(ip, field_idx),
1112311249 },
1112411250 });
11125 dummy.* = try zcu.undefRef(field_ptr_ty);
11251 dummy.* = try pt.undefRef(field_ptr_ty);
1112611252 }
1112711253 const case_srcs = try sema.arena.alloc(?LazySrcLoc, case_vals.len);
1112811254 for (case_srcs, 0..) |*case_src, i| {
......@@ -11148,9 +11274,9 @@ const SwitchProngAnalysis = struct {
1114811274 };
1114911275
1115011276 if (try sema.resolveDefinedValue(block, operand_src, spa.operand_ptr)) |op_ptr_val| {
11151 if (op_ptr_val.isUndef(zcu)) return zcu.undefRef(capture_ptr_ty);
11152 const field_ptr_val = try op_ptr_val.ptrField(first_field_index, zcu);
11153 return Air.internedToRef((try zcu.getCoerced(field_ptr_val, capture_ptr_ty)).toIntern());
11277 if (op_ptr_val.isUndef(zcu)) return pt.undefRef(capture_ptr_ty);
11278 const field_ptr_val = try op_ptr_val.ptrField(first_field_index, pt);
11279 return Air.internedToRef((try pt.getCoerced(field_ptr_val, capture_ptr_ty)).toIntern());
1115411280 }
1115511281
1115611282 try sema.requireRuntimeBlock(block, operand_src, null);
......@@ -11158,9 +11284,9 @@ const SwitchProngAnalysis = struct {
1115811284 }
1115911285
1116011286 if (try sema.resolveDefinedValue(block, operand_src, spa.operand)) |operand_val| {
11161 if (operand_val.isUndef(zcu)) return zcu.undefRef(capture_ty);
11287 if (operand_val.isUndef(zcu)) return pt.undefRef(capture_ty);
1116211288 const union_val = ip.indexToKey(operand_val.toIntern()).un;
11163 if (Value.fromInterned(union_val.tag).isUndef(zcu)) return zcu.undefRef(capture_ty);
11289 if (Value.fromInterned(union_val.tag).isUndef(zcu)) return pt.undefRef(capture_ty);
1116411290 const uncoerced = Air.internedToRef(union_val.val);
1116511291 return sema.coerce(block, capture_ty, uncoerced, operand_src);
1116611292 }
......@@ -11304,7 +11430,7 @@ const SwitchProngAnalysis = struct {
1130411430
1130511431 if (case_vals.len == 1) {
1130611432 const item_val = sema.resolveConstDefinedValue(block, LazySrcLoc.unneeded, case_vals[0], undefined) catch unreachable;
11307 const item_ty = try zcu.singleErrorSetType(item_val.getErrorName(zcu).unwrap().?);
11433 const item_ty = try pt.singleErrorSetType(item_val.getErrorName(zcu).unwrap().?);
1130811434 return sema.bitCast(block, item_ty, spa.operand, operand_src, null);
1130911435 }
1131011436
......@@ -11314,7 +11440,7 @@ const SwitchProngAnalysis = struct {
1131411440 const err_val = sema.resolveConstDefinedValue(block, LazySrcLoc.unneeded, err, undefined) catch unreachable;
1131511441 names.putAssumeCapacityNoClobber(err_val.getErrorName(zcu).unwrap().?, {});
1131611442 }
11317 const error_ty = try zcu.errorSetFromUnsortedNames(names.keys());
11443 const error_ty = try pt.errorSetFromUnsortedNames(names.keys());
1131811444 return sema.bitCast(block, error_ty, spa.operand, operand_src, null);
1131911445 },
1132011446 else => {
......@@ -11336,7 +11462,8 @@ fn switchCond(
1133611462 src: LazySrcLoc,
1133711463 operand: Air.Inst.Ref,
1133811464) CompileError!Air.Inst.Ref {
11339 const mod = sema.mod;
11465 const pt = sema.pt;
11466 const mod = pt.zcu;
1134011467 const operand_ty = sema.typeOf(operand);
1134111468 switch (operand_ty.zigTypeTag(mod)) {
1134211469 .Type,
......@@ -11353,7 +11480,7 @@ fn switchCond(
1135311480 .Enum,
1135411481 => {
1135511482 if (operand_ty.isSlice(mod)) {
11356 return sema.fail(block, src, "switch on type '{}'", .{operand_ty.fmt(mod)});
11483 return sema.fail(block, src, "switch on type '{}'", .{operand_ty.fmt(pt)});
1135711484 }
1135811485 if ((try sema.typeHasOnePossibleValue(operand_ty))) |opv| {
1135911486 return Air.internedToRef(opv.toIntern());
......@@ -11362,7 +11489,7 @@ fn switchCond(
1136211489 },
1136311490
1136411491 .Union => {
11365 try operand_ty.resolveFields(mod);
11492 try operand_ty.resolveFields(pt);
1136611493 const enum_ty = operand_ty.unionTagType(mod) orelse {
1136711494 const msg = msg: {
1136811495 const msg = try sema.errMsg(src, "switch on union with no attached enum", .{});
......@@ -11388,7 +11515,7 @@ fn switchCond(
1138811515 .Vector,
1138911516 .Frame,
1139011517 .AnyFrame,
11391 => return sema.fail(block, src, "switch on type '{}'", .{operand_ty.fmt(mod)}),
11518 => return sema.fail(block, src, "switch on type '{}'", .{operand_ty.fmt(pt)}),
1139211519 }
1139311520}
1139411521
......@@ -11398,7 +11525,8 @@ fn zirSwitchBlockErrUnion(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Comp
1139811525 const tracy = trace(@src());
1139911526 defer tracy.end();
1140011527
11401 const mod = sema.mod;
11528 const pt = sema.pt;
11529 const mod = pt.zcu;
1140211530 const gpa = sema.gpa;
1140311531 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1140411532 const switch_src = block.nodeOffset(inst_data.src_node);
......@@ -11489,7 +11617,7 @@ fn zirSwitchBlockErrUnion(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Comp
1148911617
1149011618 if (operand_err_set.zigTypeTag(mod) != .ErrorUnion) {
1149111619 return sema.fail(block, switch_src, "expected error union type, found '{}'", .{
11492 operand_ty.fmt(mod),
11620 operand_ty.fmt(pt),
1149311621 });
1149411622 }
1149511623
......@@ -11571,7 +11699,7 @@ fn zirSwitchBlockErrUnion(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Comp
1157111699 if (operand_val.errorUnionIsPayload(mod)) {
1157211700 return sema.resolveBlockBody(block, main_operand_src, &child_block, non_error_case.body, inst, merges);
1157311701 } else {
11574 const err_val = Value.fromInterned(try mod.intern(.{
11702 const err_val = Value.fromInterned(try pt.intern(.{
1157511703 .err = .{
1157611704 .ty = operand_err_set_ty.toIntern(),
1157711705 .name = operand_val.getErrorName(mod).unwrap().?,
......@@ -11708,7 +11836,8 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index, operand_is_r
1170811836 const tracy = trace(@src());
1170911837 defer tracy.end();
1171011838
11711 const mod = sema.mod;
11839 const pt = sema.pt;
11840 const mod = pt.zcu;
1171211841 const gpa = sema.gpa;
1171311842 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1171411843 const src = block.nodeOffset(inst_data.src_node);
......@@ -11783,7 +11912,7 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index, operand_is_r
1178311912 // Duplicate checking variables later also used for `inline else`.
1178411913 var seen_enum_fields: []?LazySrcLoc = &.{};
1178511914 var seen_errors = SwitchErrorSet.init(gpa);
11786 var range_set = RangeSet.init(gpa, mod);
11915 var range_set = RangeSet.init(gpa, pt);
1178711916 var true_count: u8 = 0;
1178811917 var false_count: u8 = 0;
1178911918
......@@ -11924,7 +12053,7 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index, operand_is_r
1192412053 operand_ty.srcLoc(mod),
1192512054 msg,
1192612055 "enum '{}' declared here",
11927 .{operand_ty.fmt(mod)},
12056 .{operand_ty.fmt(pt)},
1192812057 );
1192912058 break :msg msg;
1193012059 };
......@@ -12030,8 +12159,8 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index, operand_is_r
1203012159
1203112160 check_range: {
1203212161 if (operand_ty.zigTypeTag(mod) == .Int) {
12033 const min_int = try operand_ty.minInt(mod, operand_ty);
12034 const max_int = try operand_ty.maxInt(mod, operand_ty);
12162 const min_int = try operand_ty.minInt(pt, operand_ty);
12163 const max_int = try operand_ty.maxInt(pt, operand_ty);
1203512164 if (try range_set.spans(min_int.toIntern(), max_int.toIntern())) {
1203612165 if (special_prong == .@"else") {
1203712166 return sema.fail(
......@@ -12136,7 +12265,7 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index, operand_is_r
1213612265 block,
1213712266 src,
1213812267 "else prong required when switching on type '{}'",
12139 .{operand_ty.fmt(mod)},
12268 .{operand_ty.fmt(pt)},
1214012269 );
1214112270 }
1214212271
......@@ -12212,7 +12341,7 @@ fn zirSwitchBlock(sema: *Sema, block: *Block, inst: Zir.Inst.Index, operand_is_r
1221212341 .ComptimeFloat,
1221312342 .Float,
1221412343 => return sema.fail(block, operand_src, "invalid switch operand type '{}'", .{
12215 operand_ty.fmt(mod),
12344 operand_ty.fmt(pt),
1221612345 }),
1221712346 }
1221812347
......@@ -12386,7 +12515,8 @@ fn analyzeSwitchRuntimeBlock(
1238612515 cond_dbg_node_index: Zir.Inst.Index,
1238712516 allow_err_code_unwrap: bool,
1238812517) CompileError!Air.Inst.Ref {
12389 const mod = sema.mod;
12518 const pt = sema.pt;
12519 const mod = pt.zcu;
1239012520 const gpa = sema.gpa;
1239112521 const ip = &mod.intern_pool;
1239212522
......@@ -12496,9 +12626,9 @@ fn analyzeSwitchRuntimeBlock(
1249612626 var item = sema.resolveConstDefinedValue(block, LazySrcLoc.unneeded, item_first_ref, undefined) catch unreachable;
1249712627 const item_last = sema.resolveConstDefinedValue(block, LazySrcLoc.unneeded, item_last_ref, undefined) catch unreachable;
1249812628
12499 while (item.compareScalar(.lte, item_last, operand_ty, mod)) : ({
12629 while (item.compareScalar(.lte, item_last, operand_ty, pt)) : ({
1250012630 // Previous validation has resolved any possible lazy values.
12501 item = sema.intAddScalar(item, try mod.intValue(operand_ty, 1), operand_ty) catch |err| switch (err) {
12631 item = sema.intAddScalar(item, try pt.intValue(operand_ty, 1), operand_ty) catch |err| switch (err) {
1250212632 error.Overflow => unreachable,
1250312633 else => |e| return e,
1250412634 };
......@@ -12537,7 +12667,7 @@ fn analyzeSwitchRuntimeBlock(
1253712667 cases_extra.appendAssumeCapacity(@intFromEnum(item_ref));
1253812668 cases_extra.appendSliceAssumeCapacity(@ptrCast(case_block.instructions.items));
1253912669
12540 if (item.compareScalar(.eq, item_last, operand_ty, mod)) break;
12670 if (item.compareScalar(.eq, item_last, operand_ty, pt)) break;
1254112671 }
1254212672 }
1254312673
......@@ -12744,14 +12874,14 @@ fn analyzeSwitchRuntimeBlock(
1274412874 .Enum => {
1274512875 if (operand_ty.isNonexhaustiveEnum(mod) and !union_originally) {
1274612876 return sema.fail(block, special_prong_src, "cannot enumerate values of type '{}' for 'inline else'", .{
12747 operand_ty.fmt(mod),
12877 operand_ty.fmt(pt),
1274812878 });
1274912879 }
1275012880 for (seen_enum_fields, 0..) |f, i| {
1275112881 if (f != null) continue;
1275212882 cases_len += 1;
1275312883
12754 const item_val = try mod.enumValueFieldIndex(operand_ty, @intCast(i));
12884 const item_val = try pt.enumValueFieldIndex(operand_ty, @intCast(i));
1275512885 const item_ref = Air.internedToRef(item_val.toIntern());
1275612886
1275712887 case_block.instructions.shrinkRetainingCapacity(0);
......@@ -12793,7 +12923,7 @@ fn analyzeSwitchRuntimeBlock(
1279312923 .ErrorSet => {
1279412924 if (operand_ty.isAnyError(mod)) {
1279512925 return sema.fail(block, special_prong_src, "cannot enumerate values of type '{}' for 'inline else'", .{
12796 operand_ty.fmt(mod),
12926 operand_ty.fmt(pt),
1279712927 });
1279812928 }
1279912929 const error_names = operand_ty.errorSetNames(mod);
......@@ -12802,7 +12932,7 @@ fn analyzeSwitchRuntimeBlock(
1280212932 if (seen_errors.contains(error_name)) continue;
1280312933 cases_len += 1;
1280412934
12805 const item_val = try mod.intern(.{ .err = .{
12935 const item_val = try pt.intern(.{ .err = .{
1280612936 .ty = operand_ty.toIntern(),
1280712937 .name = error_name,
1280812938 } });
......@@ -12930,7 +13060,7 @@ fn analyzeSwitchRuntimeBlock(
1293013060 }
1293113061 },
1293213062 else => return sema.fail(block, special_prong_src, "cannot enumerate values of type '{}' for 'inline else'", .{
12933 operand_ty.fmt(mod),
13063 operand_ty.fmt(pt),
1293413064 }),
1293513065 };
1293613066
......@@ -13051,7 +13181,7 @@ fn resolveSwitchComptime(
1305113181
1305213182 const item = case_vals.items[scalar_i];
1305313183 const item_val = sema.resolveConstDefinedValue(child_block, LazySrcLoc.unneeded, item, undefined) catch unreachable;
13054 if (operand_val.eql(item_val, operand_ty, sema.mod)) {
13184 if (operand_val.eql(item_val, operand_ty, sema.pt.zcu)) {
1305513185 if (err_set) try sema.maybeErrorUnwrapComptime(child_block, body, cond_operand);
1305613186 return spa.resolveProngComptime(
1305713187 child_block,
......@@ -13088,7 +13218,7 @@ fn resolveSwitchComptime(
1308813218 for (items) |item| {
1308913219 // Validation above ensured these will succeed.
1309013220 const item_val = sema.resolveConstDefinedValue(child_block, LazySrcLoc.unneeded, item, undefined) catch unreachable;
13091 if (operand_val.eql(item_val, operand_ty, sema.mod)) {
13221 if (operand_val.eql(item_val, operand_ty, sema.pt.zcu)) {
1309213222 if (err_set) try sema.maybeErrorUnwrapComptime(child_block, body, cond_operand);
1309313223 return spa.resolveProngComptime(
1309413224 child_block,
......@@ -13162,7 +13292,7 @@ fn resolveSwitchComptime(
1316213292}
1316313293
1316413294const RangeSetUnhandledIterator = struct {
13165 mod: *Module,
13295 pt: Zcu.PerThread,
1316613296 cur: ?InternPool.Index,
1316713297 max: InternPool.Index,
1316813298 range_i: usize,
......@@ -13172,13 +13302,13 @@ const RangeSetUnhandledIterator = struct {
1317213302 const preallocated_limbs = math.big.int.calcTwosCompLimbCount(128);
1317313303
1317413304 fn init(sema: *Sema, ty: Type, range_set: RangeSet) !RangeSetUnhandledIterator {
13175 const mod = sema.mod;
13176 const int_type = mod.intern_pool.indexToKey(ty.toIntern()).int_type;
13305 const pt = sema.pt;
13306 const int_type = pt.zcu.intern_pool.indexToKey(ty.toIntern()).int_type;
1317713307 const needed_limbs = math.big.int.calcTwosCompLimbCount(int_type.bits);
1317813308 return .{
13179 .mod = mod,
13180 .cur = (try ty.minInt(mod, ty)).toIntern(),
13181 .max = (try ty.maxInt(mod, ty)).toIntern(),
13309 .pt = pt,
13310 .cur = (try ty.minInt(pt, ty)).toIntern(),
13311 .max = (try ty.maxInt(pt, ty)).toIntern(),
1318213312 .range_i = 0,
1318313313 .ranges = range_set.ranges.items,
1318413314 .limbs = if (needed_limbs > preallocated_limbs)
......@@ -13190,13 +13320,13 @@ const RangeSetUnhandledIterator = struct {
1319013320
1319113321 fn addOne(it: *const RangeSetUnhandledIterator, val: InternPool.Index) !?InternPool.Index {
1319213322 if (val == it.max) return null;
13193 const int = it.mod.intern_pool.indexToKey(val).int;
13323 const int = it.pt.zcu.intern_pool.indexToKey(val).int;
1319413324
1319513325 switch (int.storage) {
1319613326 inline .u64, .i64 => |val_int| {
1319713327 const next_int = @addWithOverflow(val_int, 1);
1319813328 if (next_int[1] == 0)
13199 return (try it.mod.intValue(Type.fromInterned(int.ty), next_int[0])).toIntern();
13329 return (try it.pt.intValue(Type.fromInterned(int.ty), next_int[0])).toIntern();
1320013330 },
1320113331 .big_int => {},
1320213332 .lazy_align, .lazy_size => unreachable,
......@@ -13212,7 +13342,7 @@ const RangeSetUnhandledIterator = struct {
1321213342 );
1321313343
1321413344 result_bigint.addScalar(val_bigint, 1);
13215 return (try it.mod.intValue_big(Type.fromInterned(int.ty), result_bigint.toConst())).toIntern();
13345 return (try it.pt.intValue_big(Type.fromInterned(int.ty), result_bigint.toConst())).toIntern();
1321613346 }
1321713347
1321813348 fn next(it: *RangeSetUnhandledIterator) !?InternPool.Index {
......@@ -13274,7 +13404,8 @@ fn validateErrSetSwitch(
1327413404 has_else: bool,
1327513405) CompileError!?Type {
1327613406 const gpa = sema.gpa;
13277 const mod = sema.mod;
13407 const pt = sema.pt;
13408 const mod = pt.zcu;
1327813409 const ip = &mod.intern_pool;
1327913410
1328013411 const src_node_offset = inst_data.src_node;
......@@ -13426,7 +13557,7 @@ fn validateErrSetSwitch(
1342613557 }
1342713558 // No need to keep the hash map metadata correct; here we
1342813559 // extract the (sorted) keys only.
13429 return try mod.errorSetFromUnsortedNames(names.keys());
13560 return try pt.errorSetFromUnsortedNames(names.keys());
1343013561 },
1343113562 }
1343213563 return null;
......@@ -13441,7 +13572,6 @@ fn validateSwitchRange(
1344113572 operand_ty: Type,
1344213573 item_src: LazySrcLoc,
1344313574) CompileError![2]Air.Inst.Ref {
13444 const mod = sema.mod;
1344513575 const first_src: LazySrcLoc = .{
1344613576 .base_node_inst = item_src.base_node_inst,
1344713577 .offset = .{ .switch_case_item_range_first = item_src.offset.switch_case_item },
......@@ -13452,7 +13582,7 @@ fn validateSwitchRange(
1345213582 };
1345313583 const first = try sema.resolveSwitchItemVal(block, first_ref, operand_ty, first_src);
1345413584 const last = try sema.resolveSwitchItemVal(block, last_ref, operand_ty, last_src);
13455 if (try Value.fromInterned(first.val).compareAll(.gt, Value.fromInterned(last.val), operand_ty, mod)) {
13585 if (try Value.fromInterned(first.val).compareAll(.gt, Value.fromInterned(last.val), operand_ty, sema.pt)) {
1345613586 return sema.fail(block, item_src, "range start value is greater than the end value", .{});
1345713587 }
1345813588 const maybe_prev_src = try range_set.add(first.val, last.val, item_src);
......@@ -13483,7 +13613,7 @@ fn validateSwitchItemEnum(
1348313613 operand_ty: Type,
1348413614 item_src: LazySrcLoc,
1348513615) CompileError!Air.Inst.Ref {
13486 const ip = &sema.mod.intern_pool;
13616 const ip = &sema.pt.zcu.intern_pool;
1348713617 const item = try sema.resolveSwitchItemVal(block, item_ref, operand_ty, item_src);
1348813618 const int = ip.indexToKey(item.val).enum_tag.int;
1348913619 const field_index = ip.loadEnumType(ip.typeOf(item.val)).tagValueIndex(ip, int) orelse {
......@@ -13505,9 +13635,8 @@ fn validateSwitchItemError(
1350513635 operand_ty: Type,
1350613636 item_src: LazySrcLoc,
1350713637) CompileError!Air.Inst.Ref {
13508 const ip = &sema.mod.intern_pool;
1350913638 const item = try sema.resolveSwitchItemVal(block, item_ref, operand_ty, item_src);
13510 const error_name = ip.indexToKey(item.val).err.name;
13639 const error_name = sema.pt.zcu.intern_pool.indexToKey(item.val).err.name;
1351113640 const maybe_prev_src = if (try seen_errors.fetchPut(error_name, item_src)) |prev|
1351213641 prev.value
1351313642 else
......@@ -13593,7 +13722,7 @@ fn validateSwitchNoRange(
1359313722 const msg = try sema.errMsg(
1359413723 operand_src,
1359513724 "ranges not allowed when switching on type '{}'",
13596 .{operand_ty.fmt(sema.mod)},
13725 .{operand_ty.fmt(sema.pt)},
1359713726 );
1359813727 errdefer msg.destroy(sema.gpa);
1359913728 try sema.errNote(
......@@ -13615,7 +13744,8 @@ fn maybeErrorUnwrap(
1361513744 operand_src: LazySrcLoc,
1361613745 allow_err_code_inst: bool,
1361713746) !bool {
13618 const mod = sema.mod;
13747 const pt = sema.pt;
13748 const mod = pt.zcu;
1361913749 if (!mod.backendSupportsFeature(.panic_unwrap_error)) return false;
1362013750
1362113751 const tags = sema.code.instructions.items(.tag);
......@@ -13654,7 +13784,7 @@ fn maybeErrorUnwrap(
1365413784 return true;
1365513785 }
1365613786
13657 const panic_fn = try mod.getBuiltin("panicUnwrapError");
13787 const panic_fn = try pt.getBuiltin("panicUnwrapError");
1365813788 const err_return_trace = try sema.getErrorReturnTrace(block);
1365913789 const args: [2]Air.Inst.Ref = .{ err_return_trace, operand };
1366013790 try sema.callBuiltin(block, operand_src, panic_fn, .auto, &args, .@"safety check");
......@@ -13664,7 +13794,7 @@ fn maybeErrorUnwrap(
1366413794 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1366513795 const msg_inst = try sema.resolveInst(inst_data.operand);
1366613796
13667 const panic_fn = try mod.getBuiltin("panic");
13797 const panic_fn = try pt.getBuiltin("panic");
1366813798 const err_return_trace = try sema.getErrorReturnTrace(block);
1366913799 const args: [3]Air.Inst.Ref = .{ msg_inst, err_return_trace, .null_value };
1367013800 try sema.callBuiltin(block, operand_src, panic_fn, .auto, &args, .@"safety check");
......@@ -13680,7 +13810,8 @@ fn maybeErrorUnwrap(
1368013810}
1368113811
1368213812fn maybeErrorUnwrapCondbr(sema: *Sema, block: *Block, body: []const Zir.Inst.Index, cond: Zir.Inst.Ref, cond_src: LazySrcLoc) !void {
13683 const mod = sema.mod;
13813 const pt = sema.pt;
13814 const mod = pt.zcu;
1368413815 const index = cond.toIndex() orelse return;
1368513816 if (sema.code.instructions.items(.tag)[@intFromEnum(index)] != .is_non_err) return;
1368613817
......@@ -13713,14 +13844,15 @@ fn maybeErrorUnwrapComptime(sema: *Sema, block: *Block, body: []const Zir.Inst.I
1371313844 const src = block.nodeOffset(inst_data.src_node);
1371413845
1371513846 if (try sema.resolveDefinedValue(block, src, operand)) |val| {
13716 if (val.getErrorName(sema.mod).unwrap()) |name| {
13847 if (val.getErrorName(sema.pt.zcu).unwrap()) |name| {
1371713848 return sema.failWithComptimeErrorRetTrace(block, src, name);
1371813849 }
1371913850 }
1372013851}
1372113852
1372213853fn zirHasField(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
13723 const mod = sema.mod;
13854 const pt = sema.pt;
13855 const mod = pt.zcu;
1372413856 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1372513857 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
1372613858 const ty_src = block.builtinCallArgSrc(inst_data.src_node, 0);
......@@ -13729,7 +13861,7 @@ fn zirHasField(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1372913861 const field_name = try sema.resolveConstStringIntern(block, name_src, extra.rhs, .{
1373013862 .needed_comptime_reason = "field name must be comptime-known",
1373113863 });
13732 try ty.resolveFields(mod);
13864 try ty.resolveFields(pt);
1373313865 const ip = &mod.intern_pool;
1373413866
1373513867 const has_field = hf: {
......@@ -13764,14 +13896,15 @@ fn zirHasField(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1376413896 else => {},
1376513897 }
1376613898 return sema.fail(block, ty_src, "type '{}' does not support '@hasField'", .{
13767 ty.fmt(mod),
13899 ty.fmt(pt),
1376813900 });
1376913901 };
1377013902 return if (has_field) .bool_true else .bool_false;
1377113903}
1377213904
1377313905fn zirHasDecl(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
13774 const mod = sema.mod;
13906 const pt = sema.pt;
13907 const mod = pt.zcu;
1377513908 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1377613909 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
1377713910 const src = block.nodeOffset(inst_data.src_node);
......@@ -13804,7 +13937,8 @@ fn zirImport(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1380413937 const tracy = trace(@src());
1380513938 defer tracy.end();
1380613939
13807 const zcu = sema.mod;
13940 const pt = sema.pt;
13941 const zcu = pt.zcu;
1380813942 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].str_tok;
1380913943 const operand_src = block.tokenOffset(inst_data.src_tok);
1381013944 const operand = inst_data.get(sema.code);
......@@ -13824,7 +13958,7 @@ fn zirImport(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1382413958 return sema.fail(block, operand_src, "unable to open '{s}': {s}", .{ operand, @errorName(err) });
1382513959 },
1382613960 };
13827 try zcu.ensureFileAnalyzed(result.file_index);
13961 try pt.ensureFileAnalyzed(result.file_index);
1382813962 const file_root_decl_index = zcu.fileRootDecl(result.file_index).unwrap().?;
1382913963 return sema.analyzeDeclVal(block, operand_src, file_root_decl_index);
1383013964}
......@@ -13833,7 +13967,7 @@ fn zirEmbedFile(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
1383313967 const tracy = trace(@src());
1383413968 defer tracy.end();
1383513969
13836 const mod = sema.mod;
13970 const pt = sema.pt;
1383713971 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1383813972 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
1383913973 const name = try sema.resolveConstString(block, operand_src, inst_data.operand, .{
......@@ -13844,7 +13978,7 @@ fn zirEmbedFile(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
1384413978 return sema.fail(block, operand_src, "file path name cannot be empty", .{});
1384513979 }
1384613980
13847 const val = mod.embedFile(block.getFileScope(mod), name, operand_src) catch |err| switch (err) {
13981 const val = pt.embedFile(block.getFileScope(pt.zcu), name, operand_src) catch |err| switch (err) {
1384813982 error.ImportOutsideModulePath => {
1384913983 return sema.fail(block, operand_src, "embed of file outside package path: '{s}'", .{name});
1385013984 },
......@@ -13859,16 +13993,18 @@ fn zirEmbedFile(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
1385913993}
1386013994
1386113995fn zirRetErrValueCode(sema: *Sema, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
13862 const mod = sema.mod;
13996 const pt = sema.pt;
13997 const mod = pt.zcu;
1386313998 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].str_tok;
1386413999 const name = try mod.intern_pool.getOrPutString(
1386514000 sema.gpa,
14001 pt.tid,
1386614002 inst_data.get(sema.code),
1386714003 .no_embedded_nulls,
1386814004 );
1386914005 _ = try mod.getErrorValue(name);
13870 const error_set_type = try mod.singleErrorSetType(name);
13871 return Air.internedToRef((try mod.intern(.{ .err = .{
14006 const error_set_type = try pt.singleErrorSetType(name);
14007 return Air.internedToRef((try pt.intern(.{ .err = .{
1387214008 .ty = error_set_type.toIntern(),
1387314009 .name = name,
1387414010 } })));
......@@ -13883,7 +14019,8 @@ fn zirShl(
1388314019 const tracy = trace(@src());
1388414020 defer tracy.end();
1388514021
13886 const mod = sema.mod;
14022 const pt = sema.pt;
14023 const mod = pt.zcu;
1388714024 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1388814025 const src = block.nodeOffset(inst_data.src_node);
1388914026 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -13906,53 +14043,53 @@ fn zirShl(
1390614043
1390714044 if (maybe_rhs_val) |rhs_val| {
1390814045 if (rhs_val.isUndef(mod)) {
13909 return mod.undefRef(sema.typeOf(lhs));
14046 return pt.undefRef(sema.typeOf(lhs));
1391014047 }
1391114048 // If rhs is 0, return lhs without doing any calculations.
13912 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
14049 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1391314050 return lhs;
1391414051 }
1391514052 if (scalar_ty.zigTypeTag(mod) != .ComptimeInt and air_tag != .shl_sat) {
13916 const bit_value = try mod.intValue(Type.comptime_int, scalar_ty.intInfo(mod).bits);
14053 const bit_value = try pt.intValue(Type.comptime_int, scalar_ty.intInfo(mod).bits);
1391714054 if (rhs_ty.zigTypeTag(mod) == .Vector) {
1391814055 var i: usize = 0;
1391914056 while (i < rhs_ty.vectorLen(mod)) : (i += 1) {
13920 const rhs_elem = try rhs_val.elemValue(mod, i);
13921 if (rhs_elem.compareHetero(.gte, bit_value, mod)) {
14057 const rhs_elem = try rhs_val.elemValue(pt, i);
14058 if (rhs_elem.compareHetero(.gte, bit_value, pt)) {
1392214059 return sema.fail(block, rhs_src, "shift amount '{}' at index '{d}' is too large for operand type '{}'", .{
13923 rhs_elem.fmtValue(mod, sema),
14060 rhs_elem.fmtValue(pt, sema),
1392414061 i,
13925 scalar_ty.fmt(mod),
14062 scalar_ty.fmt(pt),
1392614063 });
1392714064 }
1392814065 }
13929 } else if (rhs_val.compareHetero(.gte, bit_value, mod)) {
14066 } else if (rhs_val.compareHetero(.gte, bit_value, pt)) {
1393014067 return sema.fail(block, rhs_src, "shift amount '{}' is too large for operand type '{}'", .{
13931 rhs_val.fmtValue(mod, sema),
13932 scalar_ty.fmt(mod),
14068 rhs_val.fmtValue(pt, sema),
14069 scalar_ty.fmt(pt),
1393314070 });
1393414071 }
1393514072 }
1393614073 if (rhs_ty.zigTypeTag(mod) == .Vector) {
1393714074 var i: usize = 0;
1393814075 while (i < rhs_ty.vectorLen(mod)) : (i += 1) {
13939 const rhs_elem = try rhs_val.elemValue(mod, i);
13940 if (rhs_elem.compareHetero(.lt, try mod.intValue(scalar_rhs_ty, 0), mod)) {
14076 const rhs_elem = try rhs_val.elemValue(pt, i);
14077 if (rhs_elem.compareHetero(.lt, try pt.intValue(scalar_rhs_ty, 0), pt)) {
1394114078 return sema.fail(block, rhs_src, "shift by negative amount '{}' at index '{d}'", .{
13942 rhs_elem.fmtValue(mod, sema),
14079 rhs_elem.fmtValue(pt, sema),
1394314080 i,
1394414081 });
1394514082 }
1394614083 }
13947 } else if (rhs_val.compareHetero(.lt, try mod.intValue(rhs_ty, 0), mod)) {
14084 } else if (rhs_val.compareHetero(.lt, try pt.intValue(rhs_ty, 0), pt)) {
1394814085 return sema.fail(block, rhs_src, "shift by negative amount '{}'", .{
13949 rhs_val.fmtValue(mod, sema),
14086 rhs_val.fmtValue(pt, sema),
1395014087 });
1395114088 }
1395214089 }
1395314090
1395414091 const runtime_src = if (maybe_lhs_val) |lhs_val| rs: {
13955 if (lhs_val.isUndef(mod)) return mod.undefRef(lhs_ty);
14092 if (lhs_val.isUndef(mod)) return pt.undefRef(lhs_ty);
1395614093 const rhs_val = maybe_rhs_val orelse {
1395714094 if (scalar_ty.zigTypeTag(mod) == .ComptimeInt) {
1395814095 return sema.fail(block, src, "LHS of shift must be a fixed-width integer type, or RHS must be comptime-known", .{});
......@@ -13960,17 +14097,17 @@ fn zirShl(
1396014097 break :rs rhs_src;
1396114098 };
1396214099 const val = if (scalar_ty.zigTypeTag(mod) == .ComptimeInt)
13963 try lhs_val.shl(rhs_val, lhs_ty, sema.arena, mod)
14100 try lhs_val.shl(rhs_val, lhs_ty, sema.arena, pt)
1396414101 else switch (air_tag) {
1396514102 .shl_exact => val: {
13966 const shifted = try lhs_val.shlWithOverflow(rhs_val, lhs_ty, sema.arena, mod);
13967 if (shifted.overflow_bit.compareAllWithZero(.eq, mod)) {
14103 const shifted = try lhs_val.shlWithOverflow(rhs_val, lhs_ty, sema.arena, pt);
14104 if (shifted.overflow_bit.compareAllWithZero(.eq, pt)) {
1396814105 break :val shifted.wrapped_result;
1396914106 }
1397014107 return sema.fail(block, src, "operation caused overflow", .{});
1397114108 },
13972 .shl_sat => try lhs_val.shlSat(rhs_val, lhs_ty, sema.arena, mod),
13973 .shl => try lhs_val.shlTrunc(rhs_val, lhs_ty, sema.arena, mod),
14109 .shl_sat => try lhs_val.shlSat(rhs_val, lhs_ty, sema.arena, pt),
14110 .shl => try lhs_val.shlTrunc(rhs_val, lhs_ty, sema.arena, pt),
1397414111 else => unreachable,
1397514112 };
1397614113 return Air.internedToRef(val.toIntern());
......@@ -13981,7 +14118,7 @@ fn zirShl(
1398114118 if (rhs_is_comptime_int or
1398214119 scalar_rhs_ty.intInfo(mod).bits > scalar_ty.intInfo(mod).bits)
1398314120 {
13984 const max_int = Air.internedToRef((try lhs_ty.maxInt(mod, lhs_ty)).toIntern());
14121 const max_int = Air.internedToRef((try lhs_ty.maxInt(pt, lhs_ty)).toIntern());
1398514122 const rhs_limited = try sema.analyzeMinMax(block, rhs_src, .min, &.{ rhs, max_int }, &.{ rhs_src, rhs_src });
1398614123 break :rhs try sema.intCast(block, src, lhs_ty, rhs_src, rhs_limited, rhs_src, false);
1398714124 } else {
......@@ -13993,7 +14130,7 @@ fn zirShl(
1399314130 if (block.wantSafety()) {
1399414131 const bit_count = scalar_ty.intInfo(mod).bits;
1399514132 if (!std.math.isPowerOfTwo(bit_count)) {
13996 const bit_count_val = try mod.intValue(scalar_rhs_ty, bit_count);
14133 const bit_count_val = try pt.intValue(scalar_rhs_ty, bit_count);
1399714134 const ok = if (rhs_ty.zigTypeTag(mod) == .Vector) ok: {
1399814135 const bit_count_inst = Air.internedToRef((try sema.splat(rhs_ty, bit_count_val)).toIntern());
1399914136 const lt = try block.addCmpVector(rhs, bit_count_inst, .lt);
......@@ -14034,7 +14171,7 @@ fn zirShl(
1403414171 })
1403514172 else
1403614173 ov_bit;
14037 const zero_ov = Air.internedToRef((try mod.intValue(Type.u1, 0)).toIntern());
14174 const zero_ov = Air.internedToRef((try pt.intValue(Type.u1, 0)).toIntern());
1403814175 const no_ov = try block.addBinOp(.cmp_eq, any_ov_bit, zero_ov);
1403914176
1404014177 try sema.addSafetyCheck(block, src, no_ov, .shl_overflow);
......@@ -14053,7 +14190,8 @@ fn zirShr(
1405314190 const tracy = trace(@src());
1405414191 defer tracy.end();
1405514192
14056 const mod = sema.mod;
14193 const pt = sema.pt;
14194 const mod = pt.zcu;
1405714195 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1405814196 const src = block.nodeOffset(inst_data.src_node);
1405914197 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -14071,61 +14209,61 @@ fn zirShr(
1407114209
1407214210 const runtime_src = if (maybe_rhs_val) |rhs_val| rs: {
1407314211 if (rhs_val.isUndef(mod)) {
14074 return mod.undefRef(lhs_ty);
14212 return pt.undefRef(lhs_ty);
1407514213 }
1407614214 // If rhs is 0, return lhs without doing any calculations.
14077 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
14215 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1407814216 return lhs;
1407914217 }
1408014218 if (scalar_ty.zigTypeTag(mod) != .ComptimeInt) {
14081 const bit_value = try mod.intValue(Type.comptime_int, scalar_ty.intInfo(mod).bits);
14219 const bit_value = try pt.intValue(Type.comptime_int, scalar_ty.intInfo(mod).bits);
1408214220 if (rhs_ty.zigTypeTag(mod) == .Vector) {
1408314221 var i: usize = 0;
1408414222 while (i < rhs_ty.vectorLen(mod)) : (i += 1) {
14085 const rhs_elem = try rhs_val.elemValue(mod, i);
14086 if (rhs_elem.compareHetero(.gte, bit_value, mod)) {
14223 const rhs_elem = try rhs_val.elemValue(pt, i);
14224 if (rhs_elem.compareHetero(.gte, bit_value, pt)) {
1408714225 return sema.fail(block, rhs_src, "shift amount '{}' at index '{d}' is too large for operand type '{}'", .{
14088 rhs_elem.fmtValue(mod, sema),
14226 rhs_elem.fmtValue(pt, sema),
1408914227 i,
14090 scalar_ty.fmt(mod),
14228 scalar_ty.fmt(pt),
1409114229 });
1409214230 }
1409314231 }
14094 } else if (rhs_val.compareHetero(.gte, bit_value, mod)) {
14232 } else if (rhs_val.compareHetero(.gte, bit_value, pt)) {
1409514233 return sema.fail(block, rhs_src, "shift amount '{}' is too large for operand type '{}'", .{
14096 rhs_val.fmtValue(mod, sema),
14097 scalar_ty.fmt(mod),
14234 rhs_val.fmtValue(pt, sema),
14235 scalar_ty.fmt(pt),
1409814236 });
1409914237 }
1410014238 }
1410114239 if (rhs_ty.zigTypeTag(mod) == .Vector) {
1410214240 var i: usize = 0;
1410314241 while (i < rhs_ty.vectorLen(mod)) : (i += 1) {
14104 const rhs_elem = try rhs_val.elemValue(mod, i);
14105 if (rhs_elem.compareHetero(.lt, try mod.intValue(rhs_ty.childType(mod), 0), mod)) {
14242 const rhs_elem = try rhs_val.elemValue(pt, i);
14243 if (rhs_elem.compareHetero(.lt, try pt.intValue(rhs_ty.childType(mod), 0), pt)) {
1410614244 return sema.fail(block, rhs_src, "shift by negative amount '{}' at index '{d}'", .{
14107 rhs_elem.fmtValue(mod, sema),
14245 rhs_elem.fmtValue(pt, sema),
1410814246 i,
1410914247 });
1411014248 }
1411114249 }
14112 } else if (rhs_val.compareHetero(.lt, try mod.intValue(rhs_ty, 0), mod)) {
14250 } else if (rhs_val.compareHetero(.lt, try pt.intValue(rhs_ty, 0), pt)) {
1411314251 return sema.fail(block, rhs_src, "shift by negative amount '{}'", .{
14114 rhs_val.fmtValue(mod, sema),
14252 rhs_val.fmtValue(pt, sema),
1411514253 });
1411614254 }
1411714255 if (maybe_lhs_val) |lhs_val| {
1411814256 if (lhs_val.isUndef(mod)) {
14119 return mod.undefRef(lhs_ty);
14257 return pt.undefRef(lhs_ty);
1412014258 }
1412114259 if (air_tag == .shr_exact) {
1412214260 // Detect if any ones would be shifted out.
14123 const truncated = try lhs_val.intTruncBitsAsValue(lhs_ty, sema.arena, .unsigned, rhs_val, mod);
14124 if (!(try truncated.compareAllWithZeroSema(.eq, mod))) {
14261 const truncated = try lhs_val.intTruncBitsAsValue(lhs_ty, sema.arena, .unsigned, rhs_val, pt);
14262 if (!(try truncated.compareAllWithZeroSema(.eq, pt))) {
1412514263 return sema.fail(block, src, "exact shift shifted out 1 bits", .{});
1412614264 }
1412714265 }
14128 const val = try lhs_val.shr(rhs_val, lhs_ty, sema.arena, mod);
14266 const val = try lhs_val.shr(rhs_val, lhs_ty, sema.arena, pt);
1412914267 return Air.internedToRef(val.toIntern());
1413014268 } else {
1413114269 break :rs lhs_src;
......@@ -14141,7 +14279,7 @@ fn zirShr(
1414114279 if (block.wantSafety()) {
1414214280 const bit_count = scalar_ty.intInfo(mod).bits;
1414314281 if (!std.math.isPowerOfTwo(bit_count)) {
14144 const bit_count_val = try mod.intValue(rhs_ty.scalarType(mod), bit_count);
14282 const bit_count_val = try pt.intValue(rhs_ty.scalarType(mod), bit_count);
1414514283
1414614284 const ok = if (rhs_ty.zigTypeTag(mod) == .Vector) ok: {
1414714285 const bit_count_inst = Air.internedToRef((try sema.splat(rhs_ty, bit_count_val)).toIntern());
......@@ -14188,7 +14326,8 @@ fn zirBitwise(
1418814326 const tracy = trace(@src());
1418914327 defer tracy.end();
1419014328
14191 const mod = sema.mod;
14329 const pt = sema.pt;
14330 const mod = pt.zcu;
1419214331 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1419314332 const src = block.src(.{ .node_offset_bin_op = inst_data.src_node });
1419414333 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -14220,9 +14359,9 @@ fn zirBitwise(
1422014359 if (try sema.resolveValueIntable(casted_lhs)) |lhs_val| {
1422114360 if (try sema.resolveValueIntable(casted_rhs)) |rhs_val| {
1422214361 const result_val = switch (air_tag) {
14223 .bit_and => try lhs_val.bitwiseAnd(rhs_val, resolved_type, sema.arena, mod),
14224 .bit_or => try lhs_val.bitwiseOr(rhs_val, resolved_type, sema.arena, mod),
14225 .xor => try lhs_val.bitwiseXor(rhs_val, resolved_type, sema.arena, mod),
14362 .bit_and => try lhs_val.bitwiseAnd(rhs_val, resolved_type, sema.arena, pt),
14363 .bit_or => try lhs_val.bitwiseOr(rhs_val, resolved_type, sema.arena, pt),
14364 .xor => try lhs_val.bitwiseXor(rhs_val, resolved_type, sema.arena, pt),
1422614365 else => unreachable,
1422714366 };
1422814367 return Air.internedToRef(result_val.toIntern());
......@@ -14242,7 +14381,8 @@ fn zirBitNot(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1424214381 const tracy = trace(@src());
1424314382 defer tracy.end();
1424414383
14245 const mod = sema.mod;
14384 const pt = sema.pt;
14385 const mod = pt.zcu;
1424614386 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1424714387 const src = block.nodeOffset(inst_data.src_node);
1424814388 const operand_src = block.src(.{ .node_offset_un_op = inst_data.src_node });
......@@ -14253,26 +14393,26 @@ fn zirBitNot(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1425314393
1425414394 if (scalar_type.zigTypeTag(mod) != .Int) {
1425514395 return sema.fail(block, src, "unable to perform binary not operation on type '{}'", .{
14256 operand_type.fmt(mod),
14396 operand_type.fmt(pt),
1425714397 });
1425814398 }
1425914399
1426014400 if (try sema.resolveValue(operand)) |val| {
1426114401 if (val.isUndef(mod)) {
14262 return mod.undefRef(operand_type);
14402 return pt.undefRef(operand_type);
1426314403 } else if (operand_type.zigTypeTag(mod) == .Vector) {
1426414404 const vec_len = try sema.usizeCast(block, operand_src, operand_type.vectorLen(mod));
1426514405 const elems = try sema.arena.alloc(InternPool.Index, vec_len);
1426614406 for (elems, 0..) |*elem, i| {
14267 const elem_val = try val.elemValue(mod, i);
14268 elem.* = (try elem_val.bitwiseNot(scalar_type, sema.arena, mod)).toIntern();
14407 const elem_val = try val.elemValue(pt, i);
14408 elem.* = (try elem_val.bitwiseNot(scalar_type, sema.arena, pt)).toIntern();
1426914409 }
14270 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
14410 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
1427114411 .ty = operand_type.toIntern(),
1427214412 .storage = .{ .elems = elems },
1427314413 } })));
1427414414 } else {
14275 const result_val = try val.bitwiseNot(operand_type, sema.arena, mod);
14415 const result_val = try val.bitwiseNot(operand_type, sema.arena, pt);
1427614416 return Air.internedToRef(result_val.toIntern());
1427714417 }
1427814418 }
......@@ -14288,7 +14428,8 @@ fn analyzeTupleCat(
1428814428 lhs: Air.Inst.Ref,
1428914429 rhs: Air.Inst.Ref,
1429014430) CompileError!Air.Inst.Ref {
14291 const mod = sema.mod;
14431 const pt = sema.pt;
14432 const mod = pt.zcu;
1429214433 const lhs_ty = sema.typeOf(lhs);
1429314434 const rhs_ty = sema.typeOf(rhs);
1429414435 const src = block.nodeOffset(src_node);
......@@ -14344,14 +14485,14 @@ fn analyzeTupleCat(
1434414485 break :rs runtime_src;
1434514486 };
1434614487
14347 const tuple_ty = try mod.intern_pool.getAnonStructType(mod.gpa, .{
14488 const tuple_ty = try mod.intern_pool.getAnonStructType(mod.gpa, pt.tid, .{
1434814489 .types = types,
1434914490 .values = values,
1435014491 .names = &.{},
1435114492 });
1435214493
1435314494 const runtime_src = opt_runtime_src orelse {
14354 const tuple_val = try mod.intern(.{ .aggregate = .{
14495 const tuple_val = try pt.intern(.{ .aggregate = .{
1435514496 .ty = tuple_ty,
1435614497 .storage = .{ .elems = values },
1435714498 } });
......@@ -14386,7 +14527,8 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1438614527 const tracy = trace(@src());
1438714528 defer tracy.end();
1438814529
14389 const mod = sema.mod;
14530 const pt = sema.pt;
14531 const mod = pt.zcu;
1439014532 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1439114533 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
1439214534 const lhs = try sema.resolveInst(extra.lhs);
......@@ -14406,11 +14548,11 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1440614548
1440714549 const lhs_info = try sema.getArrayCatInfo(block, lhs_src, lhs, rhs_ty) orelse lhs_info: {
1440814550 if (lhs_is_tuple) break :lhs_info @as(Type.ArrayInfo, undefined);
14409 return sema.fail(block, lhs_src, "expected indexable; found '{}'", .{lhs_ty.fmt(mod)});
14551 return sema.fail(block, lhs_src, "expected indexable; found '{}'", .{lhs_ty.fmt(pt)});
1441014552 };
1441114553 const rhs_info = try sema.getArrayCatInfo(block, rhs_src, rhs, lhs_ty) orelse {
1441214554 assert(!rhs_is_tuple);
14413 return sema.fail(block, rhs_src, "expected indexable; found '{}'", .{rhs_ty.fmt(mod)});
14555 return sema.fail(block, rhs_src, "expected indexable; found '{}'", .{rhs_ty.fmt(pt)});
1441414556 };
1441514557
1441614558 const resolved_elem_ty = t: {
......@@ -14472,7 +14614,7 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1447214614 ),
1447314615 };
1447414616
14475 const result_ty = try mod.arrayType(.{
14617 const result_ty = try pt.arrayType(.{
1447614618 .len = result_len,
1447714619 .sentinel = if (res_sent_val) |v| v.toIntern() else .none,
1447814620 .child = resolved_elem_ty.toIntern(),
......@@ -14512,7 +14654,7 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1451214654 while (elem_i < lhs_len) : (elem_i += 1) {
1451314655 const lhs_elem_i = elem_i;
1451414656 const elem_default_val = if (lhs_is_tuple) lhs_ty.structFieldDefaultValue(lhs_elem_i, mod) else Value.@"unreachable";
14515 const elem_val = if (elem_default_val.toIntern() == .unreachable_value) try lhs_sub_val.elemValue(mod, lhs_elem_i) else elem_default_val;
14657 const elem_val = if (elem_default_val.toIntern() == .unreachable_value) try lhs_sub_val.elemValue(pt, lhs_elem_i) else elem_default_val;
1451614658 const elem_val_inst = Air.internedToRef(elem_val.toIntern());
1451714659 const operand_src = block.src(.{ .array_cat_lhs = .{
1451814660 .array_cat_offset = inst_data.src_node,
......@@ -14525,7 +14667,7 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1452514667 while (elem_i < result_len) : (elem_i += 1) {
1452614668 const rhs_elem_i = elem_i - lhs_len;
1452714669 const elem_default_val = if (rhs_is_tuple) rhs_ty.structFieldDefaultValue(rhs_elem_i, mod) else Value.@"unreachable";
14528 const elem_val = if (elem_default_val.toIntern() == .unreachable_value) try rhs_sub_val.elemValue(mod, rhs_elem_i) else elem_default_val;
14670 const elem_val = if (elem_default_val.toIntern() == .unreachable_value) try rhs_sub_val.elemValue(pt, rhs_elem_i) else elem_default_val;
1452914671 const elem_val_inst = Air.internedToRef(elem_val.toIntern());
1453014672 const operand_src = block.src(.{ .array_cat_rhs = .{
1453114673 .array_cat_offset = inst_data.src_node,
......@@ -14535,7 +14677,7 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1453514677 const coerced_elem_val = try sema.resolveConstValue(block, operand_src, coerced_elem_val_inst, undefined);
1453614678 element_vals[elem_i] = coerced_elem_val.toIntern();
1453714679 }
14538 return sema.addConstantMaybeRef(try mod.intern(.{ .aggregate = .{
14680 return sema.addConstantMaybeRef(try pt.intern(.{ .aggregate = .{
1453914681 .ty = result_ty.toIntern(),
1454014682 .storage = .{ .elems = element_vals },
1454114683 } }), ptr_addrspace != null);
......@@ -14545,19 +14687,19 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1454514687 try sema.requireRuntimeBlock(block, src, runtime_src);
1454614688
1454714689 if (ptr_addrspace) |ptr_as| {
14548 const alloc_ty = try mod.ptrTypeSema(.{
14690 const alloc_ty = try pt.ptrTypeSema(.{
1454914691 .child = result_ty.toIntern(),
1455014692 .flags = .{ .address_space = ptr_as },
1455114693 });
1455214694 const alloc = try block.addTy(.alloc, alloc_ty);
14553 const elem_ptr_ty = try mod.ptrTypeSema(.{
14695 const elem_ptr_ty = try pt.ptrTypeSema(.{
1455414696 .child = resolved_elem_ty.toIntern(),
1455514697 .flags = .{ .address_space = ptr_as },
1455614698 });
1455714699
1455814700 var elem_i: u32 = 0;
1455914701 while (elem_i < lhs_len) : (elem_i += 1) {
14560 const elem_index = try mod.intRef(Type.usize, elem_i);
14702 const elem_index = try pt.intRef(Type.usize, elem_i);
1456114703 const elem_ptr = try block.addPtrElemPtr(alloc, elem_index, elem_ptr_ty);
1456214704 const operand_src = block.src(.{ .array_cat_lhs = .{
1456314705 .array_cat_offset = inst_data.src_node,
......@@ -14568,8 +14710,8 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1456814710 }
1456914711 while (elem_i < result_len) : (elem_i += 1) {
1457014712 const rhs_elem_i = elem_i - lhs_len;
14571 const elem_index = try mod.intRef(Type.usize, elem_i);
14572 const rhs_index = try mod.intRef(Type.usize, rhs_elem_i);
14713 const elem_index = try pt.intRef(Type.usize, elem_i);
14714 const rhs_index = try pt.intRef(Type.usize, rhs_elem_i);
1457314715 const elem_ptr = try block.addPtrElemPtr(alloc, elem_index, elem_ptr_ty);
1457414716 const operand_src = block.src(.{ .array_cat_rhs = .{
1457514717 .array_cat_offset = inst_data.src_node,
......@@ -14579,9 +14721,9 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1457914721 try sema.storePtr2(block, src, elem_ptr, src, init, operand_src, .store);
1458014722 }
1458114723 if (res_sent_val) |sent_val| {
14582 const elem_index = try mod.intRef(Type.usize, result_len);
14724 const elem_index = try pt.intRef(Type.usize, result_len);
1458314725 const elem_ptr = try block.addPtrElemPtr(alloc, elem_index, elem_ptr_ty);
14584 const init = Air.internedToRef((try mod.getCoerced(sent_val, lhs_info.elem_type)).toIntern());
14726 const init = Air.internedToRef((try pt.getCoerced(sent_val, lhs_info.elem_type)).toIntern());
1458514727 try sema.storePtr2(block, src, elem_ptr, src, init, lhs_src, .store);
1458614728 }
1458714729
......@@ -14592,7 +14734,7 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1459214734 {
1459314735 var elem_i: u32 = 0;
1459414736 while (elem_i < lhs_len) : (elem_i += 1) {
14595 const index = try mod.intRef(Type.usize, elem_i);
14737 const index = try pt.intRef(Type.usize, elem_i);
1459614738 const operand_src = block.src(.{ .array_cat_lhs = .{
1459714739 .array_cat_offset = inst_data.src_node,
1459814740 .elem_index = elem_i,
......@@ -14602,7 +14744,7 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1460214744 }
1460314745 while (elem_i < result_len) : (elem_i += 1) {
1460414746 const rhs_elem_i = elem_i - lhs_len;
14605 const index = try mod.intRef(Type.usize, rhs_elem_i);
14747 const index = try pt.intRef(Type.usize, rhs_elem_i);
1460614748 const operand_src = block.src(.{ .array_cat_rhs = .{
1460714749 .array_cat_offset = inst_data.src_node,
1460814750 .elem_index = @intCast(rhs_elem_i),
......@@ -14616,7 +14758,8 @@ fn zirArrayCat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1461614758}
1461714759
1461814760fn getArrayCatInfo(sema: *Sema, block: *Block, src: LazySrcLoc, operand: Air.Inst.Ref, peer_ty: Type) !?Type.ArrayInfo {
14619 const mod = sema.mod;
14761 const pt = sema.pt;
14762 const mod = pt.zcu;
1462014763 const operand_ty = sema.typeOf(operand);
1462114764 switch (operand_ty.zigTypeTag(mod)) {
1462214765 .Array => return operand_ty.arrayInfo(mod),
......@@ -14633,7 +14776,7 @@ fn getArrayCatInfo(sema: *Sema, block: *Block, src: LazySrcLoc, operand: Air.Ins
1463314776 .none => null,
1463414777 else => Value.fromInterned(ptr_info.sentinel),
1463514778 },
14636 .len = try val.sliceLen(mod),
14779 .len = try val.sliceLen(pt),
1463714780 };
1463814781 },
1463914782 .One => {
......@@ -14666,7 +14809,8 @@ fn analyzeTupleMul(
1466614809 operand: Air.Inst.Ref,
1466714810 factor: usize,
1466814811) CompileError!Air.Inst.Ref {
14669 const mod = sema.mod;
14812 const pt = sema.pt;
14813 const mod = pt.zcu;
1467014814 const operand_ty = sema.typeOf(operand);
1467114815 const src = block.nodeOffset(src_node);
1467214816 const len_src = block.src(.{ .node_offset_bin_rhs = src_node });
......@@ -14702,14 +14846,14 @@ fn analyzeTupleMul(
1470214846 break :rs runtime_src;
1470314847 };
1470414848
14705 const tuple_ty = try mod.intern_pool.getAnonStructType(mod.gpa, .{
14849 const tuple_ty = try mod.intern_pool.getAnonStructType(mod.gpa, pt.tid, .{
1470614850 .types = types,
1470714851 .values = values,
1470814852 .names = &.{},
1470914853 });
1471014854
1471114855 const runtime_src = opt_runtime_src orelse {
14712 const tuple_val = try mod.intern(.{ .aggregate = .{
14856 const tuple_val = try pt.intern(.{ .aggregate = .{
1471314857 .ty = tuple_ty,
1471414858 .storage = .{ .elems = values },
1471514859 } });
......@@ -14739,7 +14883,8 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1473914883 const tracy = trace(@src());
1474014884 defer tracy.end();
1474114885
14742 const mod = sema.mod;
14886 const pt = sema.pt;
14887 const mod = pt.zcu;
1474314888 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1474414889 const extra = sema.code.extraData(Zir.Inst.ArrayMul, inst_data.payload_index).data;
1474514890 const uncoerced_lhs = try sema.resolveInst(extra.lhs);
......@@ -14762,12 +14907,12 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1476214907 const lhs_len = uncoerced_lhs_ty.structFieldCount(mod);
1476314908 const lhs_dest_ty = switch (res_ty.zigTypeTag(mod)) {
1476414909 else => break :no_coerce,
14765 .Array => try mod.arrayType(.{
14910 .Array => try pt.arrayType(.{
1476614911 .child = res_ty.childType(mod).toIntern(),
1476714912 .len = lhs_len,
1476814913 .sentinel = if (res_ty.sentinel(mod)) |s| s.toIntern() else .none,
1476914914 }),
14770 .Vector => try mod.vectorType(.{
14915 .Vector => try pt.vectorType(.{
1477114916 .child = res_ty.childType(mod).toIntern(),
1477214917 .len = lhs_len,
1477314918 }),
......@@ -14796,7 +14941,7 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1479614941 // Analyze the lhs first, to catch the case that someone tried to do exponentiation
1479714942 const lhs_info = try sema.getArrayCatInfo(block, lhs_src, lhs, lhs_ty) orelse {
1479814943 const msg = msg: {
14799 const msg = try sema.errMsg(lhs_src, "expected indexable; found '{}'", .{lhs_ty.fmt(mod)});
14944 const msg = try sema.errMsg(lhs_src, "expected indexable; found '{}'", .{lhs_ty.fmt(pt)});
1480014945 errdefer msg.destroy(sema.gpa);
1480114946 switch (lhs_ty.zigTypeTag(mod)) {
1480214947 .Int, .Float, .ComptimeFloat, .ComptimeInt, .Vector => {
......@@ -14818,7 +14963,7 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1481814963 return sema.fail(block, rhs_src, "operation results in overflow", .{});
1481914964 const result_len = try sema.usizeCast(block, src, result_len_u64);
1482014965
14821 const result_ty = try mod.arrayType(.{
14966 const result_ty = try pt.arrayType(.{
1482214967 .len = result_len,
1482314968 .sentinel = if (lhs_info.sentinel) |s| s.toIntern() else .none,
1482414969 .child = lhs_info.elem_type.toIntern(),
......@@ -14839,8 +14984,8 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1483914984 // Optimization for the common pattern of a single element repeated N times, such
1484014985 // as zero-filling a byte array.
1484114986 if (lhs_len == 1 and lhs_info.sentinel == null) {
14842 const elem_val = try lhs_sub_val.elemValue(mod, 0);
14843 break :v try mod.intern(.{ .aggregate = .{
14987 const elem_val = try lhs_sub_val.elemValue(pt, 0);
14988 break :v try pt.intern(.{ .aggregate = .{
1484414989 .ty = result_ty.toIntern(),
1484514990 .storage = .{ .repeated_elem = elem_val.toIntern() },
1484614991 } });
......@@ -14851,12 +14996,12 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1485114996 while (elem_i < result_len) {
1485214997 var lhs_i: usize = 0;
1485314998 while (lhs_i < lhs_len) : (lhs_i += 1) {
14854 const elem_val = try lhs_sub_val.elemValue(mod, lhs_i);
14999 const elem_val = try lhs_sub_val.elemValue(pt, lhs_i);
1485515000 element_vals[elem_i] = elem_val.toIntern();
1485615001 elem_i += 1;
1485715002 }
1485815003 }
14859 break :v try mod.intern(.{ .aggregate = .{
15004 break :v try pt.intern(.{ .aggregate = .{
1486015005 .ty = result_ty.toIntern(),
1486115006 .storage = .{ .elems = element_vals },
1486215007 } });
......@@ -14870,17 +15015,17 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1487015015 // to get the same elem values.
1487115016 const lhs_vals = try sema.arena.alloc(Air.Inst.Ref, lhs_len);
1487215017 for (lhs_vals, 0..) |*lhs_val, idx| {
14873 const idx_ref = try mod.intRef(Type.usize, idx);
15018 const idx_ref = try pt.intRef(Type.usize, idx);
1487415019 lhs_val.* = try sema.elemVal(block, lhs_src, lhs, idx_ref, src, false);
1487515020 }
1487615021
1487715022 if (ptr_addrspace) |ptr_as| {
14878 const alloc_ty = try mod.ptrTypeSema(.{
15023 const alloc_ty = try pt.ptrTypeSema(.{
1487915024 .child = result_ty.toIntern(),
1488015025 .flags = .{ .address_space = ptr_as },
1488115026 });
1488215027 const alloc = try block.addTy(.alloc, alloc_ty);
14883 const elem_ptr_ty = try mod.ptrTypeSema(.{
15028 const elem_ptr_ty = try pt.ptrTypeSema(.{
1488415029 .child = lhs_info.elem_type.toIntern(),
1488515030 .flags = .{ .address_space = ptr_as },
1488615031 });
......@@ -14888,14 +15033,14 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1488815033 var elem_i: usize = 0;
1488915034 while (elem_i < result_len) {
1489015035 for (lhs_vals) |lhs_val| {
14891 const elem_index = try mod.intRef(Type.usize, elem_i);
15036 const elem_index = try pt.intRef(Type.usize, elem_i);
1489215037 const elem_ptr = try block.addPtrElemPtr(alloc, elem_index, elem_ptr_ty);
1489315038 try sema.storePtr2(block, src, elem_ptr, src, lhs_val, lhs_src, .store);
1489415039 elem_i += 1;
1489515040 }
1489615041 }
1489715042 if (lhs_info.sentinel) |sent_val| {
14898 const elem_index = try mod.intRef(Type.usize, result_len);
15043 const elem_index = try pt.intRef(Type.usize, result_len);
1489915044 const elem_ptr = try block.addPtrElemPtr(alloc, elem_index, elem_ptr_ty);
1490015045 const init = Air.internedToRef(sent_val.toIntern());
1490115046 try sema.storePtr2(block, src, elem_ptr, src, init, lhs_src, .store);
......@@ -14912,7 +15057,8 @@ fn zirArrayMul(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1491215057}
1491315058
1491415059fn zirNegate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
14915 const mod = sema.mod;
15060 const pt = sema.pt;
15061 const mod = pt.zcu;
1491615062 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1491715063 const src = block.nodeOffset(inst_data.src_node);
1491815064 const lhs_src = src;
......@@ -14926,25 +15072,26 @@ fn zirNegate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1492615072 .Int, .ComptimeInt, .Float, .ComptimeFloat => false,
1492715073 else => true,
1492815074 }) {
14929 return sema.fail(block, src, "negation of type '{}'", .{rhs_ty.fmt(mod)});
15075 return sema.fail(block, src, "negation of type '{}'", .{rhs_ty.fmt(pt)});
1493015076 }
1493115077
1493215078 if (rhs_scalar_ty.isAnyFloat()) {
1493315079 // We handle float negation here to ensure negative zero is represented in the bits.
1493415080 if (try sema.resolveValue(rhs)) |rhs_val| {
14935 if (rhs_val.isUndef(mod)) return mod.undefRef(rhs_ty);
14936 return Air.internedToRef((try rhs_val.floatNeg(rhs_ty, sema.arena, mod)).toIntern());
15081 if (rhs_val.isUndef(mod)) return pt.undefRef(rhs_ty);
15082 return Air.internedToRef((try rhs_val.floatNeg(rhs_ty, sema.arena, pt)).toIntern());
1493715083 }
1493815084 try sema.requireRuntimeBlock(block, src, null);
1493915085 return block.addUnOp(if (block.float_mode == .optimized) .neg_optimized else .neg, rhs);
1494015086 }
1494115087
14942 const lhs = Air.internedToRef((try sema.splat(rhs_ty, try mod.intValue(rhs_scalar_ty, 0))).toIntern());
15088 const lhs = Air.internedToRef((try sema.splat(rhs_ty, try pt.intValue(rhs_scalar_ty, 0))).toIntern());
1494315089 return sema.analyzeArithmetic(block, .sub, lhs, rhs, src, lhs_src, rhs_src, true);
1494415090}
1494515091
1494615092fn zirNegateWrap(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
14947 const mod = sema.mod;
15093 const pt = sema.pt;
15094 const mod = pt.zcu;
1494815095 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1494915096 const src = block.nodeOffset(inst_data.src_node);
1495015097 const lhs_src = src;
......@@ -14956,10 +15103,10 @@ fn zirNegateWrap(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
1495615103
1495715104 switch (rhs_scalar_ty.zigTypeTag(mod)) {
1495815105 .Int, .ComptimeInt, .Float, .ComptimeFloat => {},
14959 else => return sema.fail(block, src, "negation of type '{}'", .{rhs_ty.fmt(mod)}),
15106 else => return sema.fail(block, src, "negation of type '{}'", .{rhs_ty.fmt(pt)}),
1496015107 }
1496115108
14962 const lhs = Air.internedToRef((try sema.splat(rhs_ty, try mod.intValue(rhs_scalar_ty, 0))).toIntern());
15109 const lhs = Air.internedToRef((try sema.splat(rhs_ty, try pt.intValue(rhs_scalar_ty, 0))).toIntern());
1496315110 return sema.analyzeArithmetic(block, .subwrap, lhs, rhs, src, lhs_src, rhs_src, true);
1496415111}
1496515112
......@@ -14985,7 +15132,8 @@ fn zirArithmetic(
1498515132}
1498615133
1498715134fn zirDiv(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
14988 const mod = sema.mod;
15135 const pt = sema.pt;
15136 const mod = pt.zcu;
1498915137 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1499015138 const src = block.src(.{ .node_offset_bin_op = inst_data.src_node });
1499115139 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -15026,13 +15174,13 @@ fn zirDiv(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1502615174 // If lhs % rhs is 0, it doesn't matter.
1502715175 const lhs_val = maybe_lhs_val orelse unreachable;
1502815176 const rhs_val = maybe_rhs_val orelse unreachable;
15029 const rem = lhs_val.floatRem(rhs_val, resolved_type, sema.arena, mod) catch unreachable;
15030 if (!rem.compareAllWithZero(.eq, mod)) {
15177 const rem = lhs_val.floatRem(rhs_val, resolved_type, sema.arena, pt) catch unreachable;
15178 if (!rem.compareAllWithZero(.eq, pt)) {
1503115179 return sema.fail(
1503215180 block,
1503315181 src,
1503415182 "ambiguous coercion of division operands '{}' and '{}'; non-zero remainder '{}'",
15035 .{ lhs_ty.fmt(mod), rhs_ty.fmt(mod), rem.fmtValue(mod, sema) },
15183 .{ lhs_ty.fmt(pt), rhs_ty.fmt(pt), rem.fmtValue(pt, sema) },
1503615184 );
1503715185 }
1503815186 }
......@@ -15068,10 +15216,10 @@ fn zirDiv(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1506815216 .Int, .ComptimeInt, .ComptimeFloat => {
1506915217 if (maybe_lhs_val) |lhs_val| {
1507015218 if (!lhs_val.isUndef(mod)) {
15071 if (try lhs_val.compareAllWithZeroSema(.eq, mod)) {
15219 if (try lhs_val.compareAllWithZeroSema(.eq, pt)) {
1507215220 const scalar_zero = switch (scalar_tag) {
15073 .ComptimeFloat, .Float => try mod.floatValue(resolved_type.scalarType(mod), 0.0),
15074 .ComptimeInt, .Int => try mod.intValue(resolved_type.scalarType(mod), 0),
15221 .ComptimeFloat, .Float => try pt.floatValue(resolved_type.scalarType(mod), 0.0),
15222 .ComptimeInt, .Int => try pt.intValue(resolved_type.scalarType(mod), 0),
1507515223 else => unreachable,
1507615224 };
1507715225 const zero_val = try sema.splat(resolved_type, scalar_zero);
......@@ -15083,7 +15231,7 @@ fn zirDiv(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1508315231 if (rhs_val.isUndef(mod)) {
1508415232 return sema.failWithUseOfUndef(block, rhs_src);
1508515233 }
15086 if (!(try rhs_val.compareAllWithZeroSema(.neq, mod))) {
15234 if (!(try rhs_val.compareAllWithZeroSema(.neq, pt))) {
1508715235 return sema.failWithDivideByZero(block, rhs_src);
1508815236 }
1508915237 // TODO: if the RHS is one, return the LHS directly
......@@ -15097,25 +15245,25 @@ fn zirDiv(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1509715245 if (lhs_val.isUndef(mod)) {
1509815246 if (lhs_scalar_ty.isSignedInt(mod) and rhs_scalar_ty.isSignedInt(mod)) {
1509915247 if (maybe_rhs_val) |rhs_val| {
15100 if (try sema.compareAll(rhs_val, .neq, try mod.intValue(resolved_type, -1), resolved_type)) {
15101 return mod.undefRef(resolved_type);
15248 if (try sema.compareAll(rhs_val, .neq, try pt.intValue(resolved_type, -1), resolved_type)) {
15249 return pt.undefRef(resolved_type);
1510215250 }
1510315251 }
1510415252 return sema.failWithUseOfUndef(block, rhs_src);
1510515253 }
15106 return mod.undefRef(resolved_type);
15254 return pt.undefRef(resolved_type);
1510715255 }
1510815256
1510915257 if (maybe_rhs_val) |rhs_val| {
1511015258 if (is_int) {
1511115259 var overflow_idx: ?usize = null;
15112 const res = try lhs_val.intDiv(rhs_val, resolved_type, &overflow_idx, sema.arena, mod);
15260 const res = try lhs_val.intDiv(rhs_val, resolved_type, &overflow_idx, sema.arena, pt);
1511315261 if (overflow_idx) |vec_idx| {
1511415262 return sema.failWithIntegerOverflow(block, src, resolved_type, res, vec_idx);
1511515263 }
1511615264 return Air.internedToRef(res.toIntern());
1511715265 } else {
15118 return Air.internedToRef((try lhs_val.floatDiv(rhs_val, resolved_type, sema.arena, mod)).toIntern());
15266 return Air.internedToRef((try lhs_val.floatDiv(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1511915267 }
1512015268 } else {
1512115269 break :rs rhs_src;
......@@ -15138,7 +15286,7 @@ fn zirDiv(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1513815286 block,
1513915287 src,
1514015288 "division with '{}' and '{}': signed integers must use @divTrunc, @divFloor, or @divExact",
15141 .{ lhs_ty.fmt(mod), rhs_ty.fmt(mod) },
15289 .{ lhs_ty.fmt(pt), rhs_ty.fmt(pt) },
1514215290 );
1514315291 }
1514415292 break :blk Air.Inst.Tag.div_trunc;
......@@ -15150,7 +15298,8 @@ fn zirDiv(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1515015298}
1515115299
1515215300fn zirDivExact(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
15153 const mod = sema.mod;
15301 const pt = sema.pt;
15302 const mod = pt.zcu;
1515415303 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1515515304 const src = block.src(.{ .node_offset_bin_op = inst_data.src_node });
1515615305 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -15204,10 +15353,10 @@ fn zirDivExact(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1520415353 if (lhs_val.isUndef(mod)) {
1520515354 return sema.failWithUseOfUndef(block, rhs_src);
1520615355 } else {
15207 if (try lhs_val.compareAllWithZeroSema(.eq, mod)) {
15356 if (try lhs_val.compareAllWithZeroSema(.eq, pt)) {
1520815357 const scalar_zero = switch (scalar_tag) {
15209 .ComptimeFloat, .Float => try mod.floatValue(resolved_type.scalarType(mod), 0.0),
15210 .ComptimeInt, .Int => try mod.intValue(resolved_type.scalarType(mod), 0),
15358 .ComptimeFloat, .Float => try pt.floatValue(resolved_type.scalarType(mod), 0.0),
15359 .ComptimeInt, .Int => try pt.intValue(resolved_type.scalarType(mod), 0),
1521115360 else => unreachable,
1521215361 };
1521315362 const zero_val = try sema.splat(resolved_type, scalar_zero);
......@@ -15219,7 +15368,7 @@ fn zirDivExact(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1521915368 if (rhs_val.isUndef(mod)) {
1522015369 return sema.failWithUseOfUndef(block, rhs_src);
1522115370 }
15222 if (!(try rhs_val.compareAllWithZeroSema(.neq, mod))) {
15371 if (!(try rhs_val.compareAllWithZeroSema(.neq, pt))) {
1522315372 return sema.failWithDivideByZero(block, rhs_src);
1522415373 }
1522515374 // TODO: if the RHS is one, return the LHS directly
......@@ -15227,22 +15376,22 @@ fn zirDivExact(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1522715376 if (maybe_lhs_val) |lhs_val| {
1522815377 if (maybe_rhs_val) |rhs_val| {
1522915378 if (is_int) {
15230 const modulus_val = try lhs_val.intMod(rhs_val, resolved_type, sema.arena, mod);
15231 if (!(modulus_val.compareAllWithZero(.eq, mod))) {
15379 const modulus_val = try lhs_val.intMod(rhs_val, resolved_type, sema.arena, pt);
15380 if (!(modulus_val.compareAllWithZero(.eq, pt))) {
1523215381 return sema.fail(block, src, "exact division produced remainder", .{});
1523315382 }
1523415383 var overflow_idx: ?usize = null;
15235 const res = try lhs_val.intDiv(rhs_val, resolved_type, &overflow_idx, sema.arena, mod);
15384 const res = try lhs_val.intDiv(rhs_val, resolved_type, &overflow_idx, sema.arena, pt);
1523615385 if (overflow_idx) |vec_idx| {
1523715386 return sema.failWithIntegerOverflow(block, src, resolved_type, res, vec_idx);
1523815387 }
1523915388 return Air.internedToRef(res.toIntern());
1524015389 } else {
15241 const modulus_val = try lhs_val.floatMod(rhs_val, resolved_type, sema.arena, mod);
15242 if (!(modulus_val.compareAllWithZero(.eq, mod))) {
15390 const modulus_val = try lhs_val.floatMod(rhs_val, resolved_type, sema.arena, pt);
15391 if (!(modulus_val.compareAllWithZero(.eq, pt))) {
1524315392 return sema.fail(block, src, "exact division produced remainder", .{});
1524415393 }
15245 return Air.internedToRef((try lhs_val.floatDiv(rhs_val, resolved_type, sema.arena, mod)).toIntern());
15394 return Air.internedToRef((try lhs_val.floatDiv(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1524615395 }
1524715396 } else break :rs rhs_src;
1524815397 } else break :rs lhs_src;
......@@ -15286,8 +15435,8 @@ fn zirDivExact(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1528615435 const remainder = try block.addBinOp(.rem, casted_lhs, casted_rhs);
1528715436
1528815437 const scalar_zero = switch (scalar_tag) {
15289 .ComptimeFloat, .Float => try mod.floatValue(resolved_type.scalarType(mod), 0.0),
15290 .ComptimeInt, .Int => try mod.intValue(resolved_type.scalarType(mod), 0),
15438 .ComptimeFloat, .Float => try pt.floatValue(resolved_type.scalarType(mod), 0.0),
15439 .ComptimeInt, .Int => try pt.intValue(resolved_type.scalarType(mod), 0),
1529115440 else => unreachable,
1529215441 };
1529315442 if (resolved_type.zigTypeTag(mod) == .Vector) {
......@@ -15315,7 +15464,8 @@ fn zirDivExact(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1531515464}
1531615465
1531715466fn zirDivFloor(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
15318 const mod = sema.mod;
15467 const pt = sema.pt;
15468 const mod = pt.zcu;
1531915469 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1532015470 const src = block.src(.{ .node_offset_bin_op = inst_data.src_node });
1532115471 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -15371,10 +15521,10 @@ fn zirDivFloor(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1537115521 // If the lhs is undefined, result is undefined.
1537215522 if (maybe_lhs_val) |lhs_val| {
1537315523 if (!lhs_val.isUndef(mod)) {
15374 if (try lhs_val.compareAllWithZeroSema(.eq, mod)) {
15524 if (try lhs_val.compareAllWithZeroSema(.eq, pt)) {
1537515525 const scalar_zero = switch (scalar_tag) {
15376 .ComptimeFloat, .Float => try mod.floatValue(resolved_type.scalarType(mod), 0.0),
15377 .ComptimeInt, .Int => try mod.intValue(resolved_type.scalarType(mod), 0),
15526 .ComptimeFloat, .Float => try pt.floatValue(resolved_type.scalarType(mod), 0.0),
15527 .ComptimeInt, .Int => try pt.intValue(resolved_type.scalarType(mod), 0),
1537815528 else => unreachable,
1537915529 };
1538015530 const zero_val = try sema.splat(resolved_type, scalar_zero);
......@@ -15386,7 +15536,7 @@ fn zirDivFloor(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1538615536 if (rhs_val.isUndef(mod)) {
1538715537 return sema.failWithUseOfUndef(block, rhs_src);
1538815538 }
15389 if (!(try rhs_val.compareAllWithZeroSema(.neq, mod))) {
15539 if (!(try rhs_val.compareAllWithZeroSema(.neq, pt))) {
1539015540 return sema.failWithDivideByZero(block, rhs_src);
1539115541 }
1539215542 // TODO: if the RHS is one, return the LHS directly
......@@ -15395,20 +15545,20 @@ fn zirDivFloor(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1539515545 if (lhs_val.isUndef(mod)) {
1539615546 if (lhs_scalar_ty.isSignedInt(mod) and rhs_scalar_ty.isSignedInt(mod)) {
1539715547 if (maybe_rhs_val) |rhs_val| {
15398 if (try sema.compareAll(rhs_val, .neq, try mod.intValue(resolved_type, -1), resolved_type)) {
15399 return mod.undefRef(resolved_type);
15548 if (try sema.compareAll(rhs_val, .neq, try pt.intValue(resolved_type, -1), resolved_type)) {
15549 return pt.undefRef(resolved_type);
1540015550 }
1540115551 }
1540215552 return sema.failWithUseOfUndef(block, rhs_src);
1540315553 }
15404 return mod.undefRef(resolved_type);
15554 return pt.undefRef(resolved_type);
1540515555 }
1540615556
1540715557 if (maybe_rhs_val) |rhs_val| {
1540815558 if (is_int) {
15409 return Air.internedToRef((try lhs_val.intDivFloor(rhs_val, resolved_type, sema.arena, mod)).toIntern());
15559 return Air.internedToRef((try lhs_val.intDivFloor(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1541015560 } else {
15411 return Air.internedToRef((try lhs_val.floatDivFloor(rhs_val, resolved_type, sema.arena, mod)).toIntern());
15561 return Air.internedToRef((try lhs_val.floatDivFloor(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1541215562 }
1541315563 } else break :rs rhs_src;
1541415564 } else break :rs lhs_src;
......@@ -15425,7 +15575,8 @@ fn zirDivFloor(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1542515575}
1542615576
1542715577fn zirDivTrunc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
15428 const mod = sema.mod;
15578 const pt = sema.pt;
15579 const mod = pt.zcu;
1542915580 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1543015581 const src = block.src(.{ .node_offset_bin_op = inst_data.src_node });
1543115582 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -15481,10 +15632,10 @@ fn zirDivTrunc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1548115632 // If the lhs is undefined, result is undefined.
1548215633 if (maybe_lhs_val) |lhs_val| {
1548315634 if (!lhs_val.isUndef(mod)) {
15484 if (try lhs_val.compareAllWithZeroSema(.eq, mod)) {
15635 if (try lhs_val.compareAllWithZeroSema(.eq, pt)) {
1548515636 const scalar_zero = switch (scalar_tag) {
15486 .ComptimeFloat, .Float => try mod.floatValue(resolved_type.scalarType(mod), 0.0),
15487 .ComptimeInt, .Int => try mod.intValue(resolved_type.scalarType(mod), 0),
15637 .ComptimeFloat, .Float => try pt.floatValue(resolved_type.scalarType(mod), 0.0),
15638 .ComptimeInt, .Int => try pt.intValue(resolved_type.scalarType(mod), 0),
1548815639 else => unreachable,
1548915640 };
1549015641 const zero_val = try sema.splat(resolved_type, scalar_zero);
......@@ -15496,7 +15647,7 @@ fn zirDivTrunc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1549615647 if (rhs_val.isUndef(mod)) {
1549715648 return sema.failWithUseOfUndef(block, rhs_src);
1549815649 }
15499 if (!(try rhs_val.compareAllWithZeroSema(.neq, mod))) {
15650 if (!(try rhs_val.compareAllWithZeroSema(.neq, pt))) {
1550015651 return sema.failWithDivideByZero(block, rhs_src);
1550115652 }
1550215653 }
......@@ -15504,25 +15655,25 @@ fn zirDivTrunc(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1550415655 if (lhs_val.isUndef(mod)) {
1550515656 if (lhs_scalar_ty.isSignedInt(mod) and rhs_scalar_ty.isSignedInt(mod)) {
1550615657 if (maybe_rhs_val) |rhs_val| {
15507 if (try sema.compareAll(rhs_val, .neq, try mod.intValue(resolved_type, -1), resolved_type)) {
15508 return mod.undefRef(resolved_type);
15658 if (try sema.compareAll(rhs_val, .neq, try pt.intValue(resolved_type, -1), resolved_type)) {
15659 return pt.undefRef(resolved_type);
1550915660 }
1551015661 }
1551115662 return sema.failWithUseOfUndef(block, rhs_src);
1551215663 }
15513 return mod.undefRef(resolved_type);
15664 return pt.undefRef(resolved_type);
1551415665 }
1551515666
1551615667 if (maybe_rhs_val) |rhs_val| {
1551715668 if (is_int) {
1551815669 var overflow_idx: ?usize = null;
15519 const res = try lhs_val.intDiv(rhs_val, resolved_type, &overflow_idx, sema.arena, mod);
15670 const res = try lhs_val.intDiv(rhs_val, resolved_type, &overflow_idx, sema.arena, pt);
1552015671 if (overflow_idx) |vec_idx| {
1552115672 return sema.failWithIntegerOverflow(block, src, resolved_type, res, vec_idx);
1552215673 }
1552315674 return Air.internedToRef(res.toIntern());
1552415675 } else {
15525 return Air.internedToRef((try lhs_val.floatDivTrunc(rhs_val, resolved_type, sema.arena, mod)).toIntern());
15676 return Air.internedToRef((try lhs_val.floatDivTrunc(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1552615677 }
1552715678 } else break :rs rhs_src;
1552815679 } else break :rs lhs_src;
......@@ -15550,7 +15701,8 @@ fn addDivIntOverflowSafety(
1555015701 casted_rhs: Air.Inst.Ref,
1555115702 is_int: bool,
1555215703) CompileError!void {
15553 const mod = sema.mod;
15704 const pt = sema.pt;
15705 const mod = pt.zcu;
1555415706 if (!is_int) return;
1555515707
1555615708 // If the LHS is unsigned, it cannot cause overflow.
......@@ -15561,19 +15713,19 @@ fn addDivIntOverflowSafety(
1556115713 return;
1556215714 }
1556315715
15564 const min_int = try resolved_type.minInt(mod, resolved_type);
15565 const neg_one_scalar = try mod.intValue(lhs_scalar_ty, -1);
15716 const min_int = try resolved_type.minInt(pt, resolved_type);
15717 const neg_one_scalar = try pt.intValue(lhs_scalar_ty, -1);
1556615718 const neg_one = try sema.splat(resolved_type, neg_one_scalar);
1556715719
1556815720 // If the LHS is comptime-known to be not equal to the min int,
1556915721 // no overflow is possible.
1557015722 if (maybe_lhs_val) |lhs_val| {
15571 if (try lhs_val.compareAll(.neq, min_int, resolved_type, mod)) return;
15723 if (try lhs_val.compareAll(.neq, min_int, resolved_type, pt)) return;
1557215724 }
1557315725
1557415726 // If the RHS is comptime-known to not be equal to -1, no overflow is possible.
1557515727 if (maybe_rhs_val) |rhs_val| {
15576 if (try rhs_val.compareAll(.neq, neg_one, resolved_type, mod)) return;
15728 if (try rhs_val.compareAll(.neq, neg_one, resolved_type, pt)) return;
1557715729 }
1557815730
1557915731 var ok: Air.Inst.Ref = .none;
......@@ -15634,11 +15786,12 @@ fn addDivByZeroSafety(
1563415786 // emitted above.
1563515787 if (maybe_rhs_val != null) return;
1563615788
15637 const mod = sema.mod;
15789 const pt = sema.pt;
15790 const mod = pt.zcu;
1563815791 const scalar_zero = if (is_int)
15639 try mod.intValue(resolved_type.scalarType(mod), 0)
15792 try pt.intValue(resolved_type.scalarType(mod), 0)
1564015793 else
15641 try mod.floatValue(resolved_type.scalarType(mod), 0.0);
15794 try pt.floatValue(resolved_type.scalarType(mod), 0.0);
1564215795 const ok = if (resolved_type.zigTypeTag(mod) == .Vector) ok: {
1564315796 const zero_val = try sema.splat(resolved_type, scalar_zero);
1564415797 const zero = Air.internedToRef(zero_val.toIntern());
......@@ -15666,7 +15819,8 @@ fn airTag(block: *Block, is_int: bool, normal: Air.Inst.Tag, optimized: Air.Inst
1566615819}
1566715820
1566815821fn zirModRem(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
15669 const mod = sema.mod;
15822 const pt = sema.pt;
15823 const mod = pt.zcu;
1567015824 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1567115825 const src = block.src(.{ .node_offset_bin_op = inst_data.src_node });
1567215826 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -15721,16 +15875,16 @@ fn zirModRem(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1572115875 if (lhs_val.isUndef(mod)) {
1572215876 return sema.failWithUseOfUndef(block, lhs_src);
1572315877 }
15724 if (try lhs_val.compareAllWithZeroSema(.eq, mod)) {
15878 if (try lhs_val.compareAllWithZeroSema(.eq, pt)) {
1572515879 const scalar_zero = switch (scalar_tag) {
15726 .ComptimeFloat, .Float => try mod.floatValue(resolved_type.scalarType(mod), 0.0),
15727 .ComptimeInt, .Int => try mod.intValue(resolved_type.scalarType(mod), 0),
15880 .ComptimeFloat, .Float => try pt.floatValue(resolved_type.scalarType(mod), 0.0),
15881 .ComptimeInt, .Int => try pt.intValue(resolved_type.scalarType(mod), 0),
1572815882 else => unreachable,
1572915883 };
15730 const zero_val = if (is_vector) Value.fromInterned((try mod.intern(.{ .aggregate = .{
15884 const zero_val = if (is_vector) Value.fromInterned(try pt.intern(.{ .aggregate = .{
1573115885 .ty = resolved_type.toIntern(),
1573215886 .storage = .{ .repeated_elem = scalar_zero.toIntern() },
15733 } }))) else scalar_zero;
15887 } })) else scalar_zero;
1573415888 return Air.internedToRef(zero_val.toIntern());
1573515889 }
1573615890 } else if (lhs_scalar_ty.isSignedInt(mod)) {
......@@ -15740,18 +15894,18 @@ fn zirModRem(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1574015894 if (rhs_val.isUndef(mod)) {
1574115895 return sema.failWithUseOfUndef(block, rhs_src);
1574215896 }
15743 if (!(try rhs_val.compareAllWithZeroSema(.neq, mod))) {
15897 if (!(try rhs_val.compareAllWithZeroSema(.neq, pt))) {
1574415898 return sema.failWithDivideByZero(block, rhs_src);
1574515899 }
15746 if (!(try rhs_val.compareAllWithZeroSema(.gte, mod))) {
15900 if (!(try rhs_val.compareAllWithZeroSema(.gte, pt))) {
1574715901 return sema.failWithModRemNegative(block, rhs_src, lhs_ty, rhs_ty);
1574815902 }
1574915903 if (maybe_lhs_val) |lhs_val| {
1575015904 const rem_result = try sema.intRem(resolved_type, lhs_val, rhs_val);
1575115905 // If this answer could possibly be different by doing `intMod`,
1575215906 // we must emit a compile error. Otherwise, it's OK.
15753 if (!(try lhs_val.compareAllWithZeroSema(.gte, mod)) and
15754 !(try rem_result.compareAllWithZeroSema(.eq, mod)))
15907 if (!(try lhs_val.compareAllWithZeroSema(.gte, pt)) and
15908 !(try rem_result.compareAllWithZeroSema(.eq, pt)))
1575515909 {
1575615910 return sema.failWithModRemNegative(block, lhs_src, lhs_ty, rhs_ty);
1575715911 }
......@@ -15769,17 +15923,17 @@ fn zirModRem(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1576915923 if (rhs_val.isUndef(mod)) {
1577015924 return sema.failWithUseOfUndef(block, rhs_src);
1577115925 }
15772 if (!(try rhs_val.compareAllWithZeroSema(.neq, mod))) {
15926 if (!(try rhs_val.compareAllWithZeroSema(.neq, pt))) {
1577315927 return sema.failWithDivideByZero(block, rhs_src);
1577415928 }
15775 if (!(try rhs_val.compareAllWithZeroSema(.gte, mod))) {
15929 if (!(try rhs_val.compareAllWithZeroSema(.gte, pt))) {
1577615930 return sema.failWithModRemNegative(block, rhs_src, lhs_ty, rhs_ty);
1577715931 }
1577815932 if (maybe_lhs_val) |lhs_val| {
15779 if (lhs_val.isUndef(mod) or !(try lhs_val.compareAllWithZeroSema(.gte, mod))) {
15933 if (lhs_val.isUndef(mod) or !(try lhs_val.compareAllWithZeroSema(.gte, pt))) {
1578015934 return sema.failWithModRemNegative(block, lhs_src, lhs_ty, rhs_ty);
1578115935 }
15782 return Air.internedToRef((try lhs_val.floatRem(rhs_val, resolved_type, sema.arena, mod)).toIntern());
15936 return Air.internedToRef((try lhs_val.floatRem(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1578315937 } else {
1578415938 return sema.failWithModRemNegative(block, lhs_src, lhs_ty, rhs_ty);
1578515939 }
......@@ -15804,31 +15958,32 @@ fn intRem(
1580415958 lhs: Value,
1580515959 rhs: Value,
1580615960) CompileError!Value {
15807 const mod = sema.mod;
15961 const pt = sema.pt;
15962 const mod = pt.zcu;
1580815963 if (ty.zigTypeTag(mod) == .Vector) {
1580915964 const result_data = try sema.arena.alloc(InternPool.Index, ty.vectorLen(mod));
1581015965 const scalar_ty = ty.scalarType(mod);
1581115966 for (result_data, 0..) |*scalar, i| {
15812 const lhs_elem = try lhs.elemValue(mod, i);
15813 const rhs_elem = try rhs.elemValue(mod, i);
15967 const lhs_elem = try lhs.elemValue(pt, i);
15968 const rhs_elem = try rhs.elemValue(pt, i);
1581415969 scalar.* = (try sema.intRemScalar(lhs_elem, rhs_elem, scalar_ty)).toIntern();
1581515970 }
15816 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
15971 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
1581715972 .ty = ty.toIntern(),
1581815973 .storage = .{ .elems = result_data },
15819 } })));
15974 } }));
1582015975 }
1582115976 return sema.intRemScalar(lhs, rhs, ty);
1582215977}
1582315978
1582415979fn intRemScalar(sema: *Sema, lhs: Value, rhs: Value, scalar_ty: Type) CompileError!Value {
15825 const mod = sema.mod;
15980 const pt = sema.pt;
1582615981 // TODO is this a performance issue? maybe we should try the operation without
1582715982 // resorting to BigInt first.
1582815983 var lhs_space: Value.BigIntSpace = undefined;
1582915984 var rhs_space: Value.BigIntSpace = undefined;
15830 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, mod, .sema);
15831 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, mod, .sema);
15985 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, pt, .sema);
15986 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, pt, .sema);
1583215987 const limbs_q = try sema.arena.alloc(
1583315988 math.big.Limb,
1583415989 lhs_bigint.limbs.len,
......@@ -15846,11 +16001,12 @@ fn intRemScalar(sema: *Sema, lhs: Value, rhs: Value, scalar_ty: Type) CompileErr
1584616001 var result_q = math.big.int.Mutable{ .limbs = limbs_q, .positive = undefined, .len = undefined };
1584716002 var result_r = math.big.int.Mutable{ .limbs = limbs_r, .positive = undefined, .len = undefined };
1584816003 result_q.divTrunc(&result_r, lhs_bigint, rhs_bigint, limbs_buffer);
15849 return mod.intValue_big(scalar_ty, result_r.toConst());
16004 return pt.intValue_big(scalar_ty, result_r.toConst());
1585016005}
1585116006
1585216007fn zirMod(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
15853 const mod = sema.mod;
16008 const pt = sema.pt;
16009 const mod = pt.zcu;
1585416010 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1585516011 const src = block.src(.{ .node_offset_bin_op = inst_data.src_node });
1585616012 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -15904,11 +16060,11 @@ fn zirMod(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1590416060 if (rhs_val.isUndef(mod)) {
1590516061 return sema.failWithUseOfUndef(block, rhs_src);
1590616062 }
15907 if (!(try rhs_val.compareAllWithZeroSema(.neq, mod))) {
16063 if (!(try rhs_val.compareAllWithZeroSema(.neq, pt))) {
1590816064 return sema.failWithDivideByZero(block, rhs_src);
1590916065 }
1591016066 if (maybe_lhs_val) |lhs_val| {
15911 return Air.internedToRef((try lhs_val.intMod(rhs_val, resolved_type, sema.arena, mod)).toIntern());
16067 return Air.internedToRef((try lhs_val.intMod(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1591216068 }
1591316069 break :rs lhs_src;
1591416070 } else {
......@@ -15920,16 +16076,16 @@ fn zirMod(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1592016076 if (rhs_val.isUndef(mod)) {
1592116077 return sema.failWithUseOfUndef(block, rhs_src);
1592216078 }
15923 if (!(try rhs_val.compareAllWithZeroSema(.neq, mod))) {
16079 if (!(try rhs_val.compareAllWithZeroSema(.neq, pt))) {
1592416080 return sema.failWithDivideByZero(block, rhs_src);
1592516081 }
1592616082 }
1592716083 if (maybe_lhs_val) |lhs_val| {
1592816084 if (lhs_val.isUndef(mod)) {
15929 return mod.undefRef(resolved_type);
16085 return pt.undefRef(resolved_type);
1593016086 }
1593116087 if (maybe_rhs_val) |rhs_val| {
15932 return Air.internedToRef((try lhs_val.floatMod(rhs_val, resolved_type, sema.arena, mod)).toIntern());
16088 return Air.internedToRef((try lhs_val.floatMod(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1593316089 } else break :rs rhs_src;
1593416090 } else break :rs lhs_src;
1593516091 };
......@@ -15945,7 +16101,8 @@ fn zirMod(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1594516101}
1594616102
1594716103fn zirRem(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
15948 const mod = sema.mod;
16104 const pt = sema.pt;
16105 const mod = pt.zcu;
1594916106 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1595016107 const src = block.src(.{ .node_offset_bin_op = inst_data.src_node });
1595116108 const lhs_src = block.src(.{ .node_offset_bin_lhs = inst_data.src_node });
......@@ -15999,7 +16156,7 @@ fn zirRem(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1599916156 if (rhs_val.isUndef(mod)) {
1600016157 return sema.failWithUseOfUndef(block, rhs_src);
1600116158 }
16002 if (!(try rhs_val.compareAllWithZeroSema(.neq, mod))) {
16159 if (!(try rhs_val.compareAllWithZeroSema(.neq, pt))) {
1600316160 return sema.failWithDivideByZero(block, rhs_src);
1600416161 }
1600516162 if (maybe_lhs_val) |lhs_val| {
......@@ -16015,16 +16172,16 @@ fn zirRem(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Ins
1601516172 if (rhs_val.isUndef(mod)) {
1601616173 return sema.failWithUseOfUndef(block, rhs_src);
1601716174 }
16018 if (!(try rhs_val.compareAllWithZeroSema(.neq, mod))) {
16175 if (!(try rhs_val.compareAllWithZeroSema(.neq, pt))) {
1601916176 return sema.failWithDivideByZero(block, rhs_src);
1602016177 }
1602116178 }
1602216179 if (maybe_lhs_val) |lhs_val| {
1602316180 if (lhs_val.isUndef(mod)) {
16024 return mod.undefRef(resolved_type);
16181 return pt.undefRef(resolved_type);
1602516182 }
1602616183 if (maybe_rhs_val) |rhs_val| {
16027 return Air.internedToRef((try lhs_val.floatRem(rhs_val, resolved_type, sema.arena, mod)).toIntern());
16184 return Air.internedToRef((try lhs_val.floatRem(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1602816185 } else break :rs rhs_src;
1602916186 } else break :rs lhs_src;
1603016187 };
......@@ -16059,7 +16216,8 @@ fn zirOverflowArithmetic(
1605916216
1606016217 const lhs_ty = sema.typeOf(uncasted_lhs);
1606116218 const rhs_ty = sema.typeOf(uncasted_rhs);
16062 const mod = sema.mod;
16219 const pt = sema.pt;
16220 const mod = pt.zcu;
1606316221 const ip = &mod.intern_pool;
1606416222
1606516223 try sema.checkVectorizableBinaryOperands(block, src, lhs_ty, rhs_ty, lhs_src, rhs_src);
......@@ -16081,7 +16239,7 @@ fn zirOverflowArithmetic(
1608116239 const rhs = try sema.coerce(block, rhs_dest_ty, uncasted_rhs, rhs_src);
1608216240
1608316241 if (dest_ty.scalarType(mod).zigTypeTag(mod) != .Int) {
16084 return sema.fail(block, src, "expected vector of integers or integer tag type, found '{}'", .{dest_ty.fmt(mod)});
16242 return sema.fail(block, src, "expected vector of integers or integer tag type, found '{}'", .{dest_ty.fmt(pt)});
1608516243 }
1608616244
1608716245 const maybe_lhs_val = try sema.resolveValue(lhs);
......@@ -16095,19 +16253,19 @@ fn zirOverflowArithmetic(
1609516253 wrapped: Value = Value.@"unreachable",
1609616254 overflow_bit: Value,
1609716255 } = result: {
16098 const zero_bit = try mod.intValue(Type.u1, 0);
16256 const zero_bit = try pt.intValue(Type.u1, 0);
1609916257 switch (zir_tag) {
1610016258 .add_with_overflow => {
1610116259 // If either of the arguments is zero, `false` is returned and the other is stored
1610216260 // to the result, even if it is undefined..
1610316261 // Otherwise, if either of the argument is undefined, undefined is returned.
1610416262 if (maybe_lhs_val) |lhs_val| {
16105 if (!lhs_val.isUndef(mod) and (try lhs_val.compareAllWithZeroSema(.eq, mod))) {
16263 if (!lhs_val.isUndef(mod) and (try lhs_val.compareAllWithZeroSema(.eq, pt))) {
1610616264 break :result .{ .overflow_bit = try sema.splat(overflow_ty, zero_bit), .inst = rhs };
1610716265 }
1610816266 }
1610916267 if (maybe_rhs_val) |rhs_val| {
16110 if (!rhs_val.isUndef(mod) and (try rhs_val.compareAllWithZeroSema(.eq, mod))) {
16268 if (!rhs_val.isUndef(mod) and (try rhs_val.compareAllWithZeroSema(.eq, pt))) {
1611116269 break :result .{ .overflow_bit = try sema.splat(overflow_ty, zero_bit), .inst = lhs };
1611216270 }
1611316271 }
......@@ -16128,7 +16286,7 @@ fn zirOverflowArithmetic(
1612816286 if (maybe_rhs_val) |rhs_val| {
1612916287 if (rhs_val.isUndef(mod)) {
1613016288 break :result .{ .overflow_bit = Value.undef, .wrapped = Value.undef };
16131 } else if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
16289 } else if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1613216290 break :result .{ .overflow_bit = try sema.splat(overflow_ty, zero_bit), .inst = lhs };
1613316291 } else if (maybe_lhs_val) |lhs_val| {
1613416292 if (lhs_val.isUndef(mod)) {
......@@ -16144,10 +16302,10 @@ fn zirOverflowArithmetic(
1614416302 // If either of the arguments is zero, the result is zero and no overflow occured.
1614516303 // If either of the arguments is one, the result is the other and no overflow occured.
1614616304 // Otherwise, if either of the arguments is undefined, both results are undefined.
16147 const scalar_one = try mod.intValue(dest_ty.scalarType(mod), 1);
16305 const scalar_one = try pt.intValue(dest_ty.scalarType(mod), 1);
1614816306 if (maybe_lhs_val) |lhs_val| {
1614916307 if (!lhs_val.isUndef(mod)) {
16150 if (try lhs_val.compareAllWithZeroSema(.eq, mod)) {
16308 if (try lhs_val.compareAllWithZeroSema(.eq, pt)) {
1615116309 break :result .{ .overflow_bit = try sema.splat(overflow_ty, zero_bit), .inst = lhs };
1615216310 } else if (try sema.compareAll(lhs_val, .eq, try sema.splat(dest_ty, scalar_one), dest_ty)) {
1615316311 break :result .{ .overflow_bit = try sema.splat(overflow_ty, zero_bit), .inst = rhs };
......@@ -16157,7 +16315,7 @@ fn zirOverflowArithmetic(
1615716315
1615816316 if (maybe_rhs_val) |rhs_val| {
1615916317 if (!rhs_val.isUndef(mod)) {
16160 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
16318 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1616116319 break :result .{ .overflow_bit = try sema.splat(overflow_ty, zero_bit), .inst = rhs };
1616216320 } else if (try sema.compareAll(rhs_val, .eq, try sema.splat(dest_ty, scalar_one), dest_ty)) {
1616316321 break :result .{ .overflow_bit = try sema.splat(overflow_ty, zero_bit), .inst = lhs };
......@@ -16171,7 +16329,7 @@ fn zirOverflowArithmetic(
1617116329 break :result .{ .overflow_bit = Value.undef, .wrapped = Value.undef };
1617216330 }
1617316331
16174 const result = try lhs_val.intMulWithOverflow(rhs_val, dest_ty, sema.arena, mod);
16332 const result = try lhs_val.intMulWithOverflow(rhs_val, dest_ty, sema.arena, pt);
1617516333 break :result .{ .overflow_bit = result.overflow_bit, .wrapped = result.wrapped_result };
1617616334 }
1617716335 }
......@@ -16181,12 +16339,12 @@ fn zirOverflowArithmetic(
1618116339 // If rhs is zero, the result is lhs (even if undefined) and no overflow occurred.
1618216340 // Oterhwise if either of the arguments is undefined, both results are undefined.
1618316341 if (maybe_lhs_val) |lhs_val| {
16184 if (!lhs_val.isUndef(mod) and (try lhs_val.compareAllWithZeroSema(.eq, mod))) {
16342 if (!lhs_val.isUndef(mod) and (try lhs_val.compareAllWithZeroSema(.eq, pt))) {
1618516343 break :result .{ .overflow_bit = try sema.splat(overflow_ty, zero_bit), .inst = lhs };
1618616344 }
1618716345 }
1618816346 if (maybe_rhs_val) |rhs_val| {
16189 if (!rhs_val.isUndef(mod) and (try rhs_val.compareAllWithZeroSema(.eq, mod))) {
16347 if (!rhs_val.isUndef(mod) and (try rhs_val.compareAllWithZeroSema(.eq, pt))) {
1619016348 break :result .{ .overflow_bit = try sema.splat(overflow_ty, zero_bit), .inst = lhs };
1619116349 }
1619216350 }
......@@ -16196,7 +16354,7 @@ fn zirOverflowArithmetic(
1619616354 break :result .{ .overflow_bit = Value.undef, .wrapped = Value.undef };
1619716355 }
1619816356
16199 const result = try lhs_val.shlWithOverflow(rhs_val, dest_ty, sema.arena, mod);
16357 const result = try lhs_val.shlWithOverflow(rhs_val, dest_ty, sema.arena, pt);
1620016358 break :result .{ .overflow_bit = result.overflow_bit, .wrapped = result.wrapped_result };
1620116359 }
1620216360 }
......@@ -16235,7 +16393,7 @@ fn zirOverflowArithmetic(
1623516393 }
1623616394
1623716395 if (result.inst == .none) {
16238 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
16396 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
1623916397 .ty = tuple_ty.toIntern(),
1624016398 .storage = .{ .elems = &.{
1624116399 result.wrapped.toIntern(),
......@@ -16251,9 +16409,10 @@ fn zirOverflowArithmetic(
1625116409}
1625216410
1625316411fn splat(sema: *Sema, ty: Type, val: Value) !Value {
16254 const mod = sema.mod;
16412 const pt = sema.pt;
16413 const mod = pt.zcu;
1625516414 if (ty.zigTypeTag(mod) != .Vector) return val;
16256 const repeated = try mod.intern(.{ .aggregate = .{
16415 const repeated = try pt.intern(.{ .aggregate = .{
1625716416 .ty = ty.toIntern(),
1625816417 .storage = .{ .repeated_elem = val.toIntern() },
1625916418 } });
......@@ -16261,16 +16420,17 @@ fn splat(sema: *Sema, ty: Type, val: Value) !Value {
1626116420}
1626216421
1626316422fn overflowArithmeticTupleType(sema: *Sema, ty: Type) !Type {
16264 const mod = sema.mod;
16423 const pt = sema.pt;
16424 const mod = pt.zcu;
1626516425 const ip = &mod.intern_pool;
16266 const ov_ty = if (ty.zigTypeTag(mod) == .Vector) try mod.vectorType(.{
16426 const ov_ty = if (ty.zigTypeTag(mod) == .Vector) try pt.vectorType(.{
1626716427 .len = ty.vectorLen(mod),
1626816428 .child = .u1_type,
1626916429 }) else Type.u1;
1627016430
1627116431 const types = [2]InternPool.Index{ ty.toIntern(), ov_ty.toIntern() };
1627216432 const values = [2]InternPool.Index{ .none, .none };
16273 const tuple_ty = try ip.getAnonStructType(mod.gpa, .{
16433 const tuple_ty = try ip.getAnonStructType(mod.gpa, pt.tid, .{
1627416434 .types = &types,
1627516435 .values = &values,
1627616436 .names = &.{},
......@@ -16290,7 +16450,8 @@ fn analyzeArithmetic(
1629016450 rhs_src: LazySrcLoc,
1629116451 want_safety: bool,
1629216452) CompileError!Air.Inst.Ref {
16293 const mod = sema.mod;
16453 const pt = sema.pt;
16454 const mod = pt.zcu;
1629416455 const lhs_ty = sema.typeOf(lhs);
1629516456 const rhs_ty = sema.typeOf(rhs);
1629616457 const lhs_zig_ty_tag = try lhs_ty.zigTypeTagOrPoison(mod);
......@@ -16337,7 +16498,7 @@ fn analyzeArithmetic(
1633716498 // overflow (max_int), causing illegal behavior.
1633816499 // For floats: either operand being undef makes the result undef.
1633916500 if (maybe_lhs_val) |lhs_val| {
16340 if (!lhs_val.isUndef(mod) and (try lhs_val.compareAllWithZeroSema(.eq, mod))) {
16501 if (!lhs_val.isUndef(mod) and (try lhs_val.compareAllWithZeroSema(.eq, pt))) {
1634116502 return casted_rhs;
1634216503 }
1634316504 }
......@@ -16346,10 +16507,10 @@ fn analyzeArithmetic(
1634616507 if (is_int) {
1634716508 return sema.failWithUseOfUndef(block, rhs_src);
1634816509 } else {
16349 return mod.undefRef(resolved_type);
16510 return pt.undefRef(resolved_type);
1635016511 }
1635116512 }
16352 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
16513 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1635316514 return casted_lhs;
1635416515 }
1635516516 }
......@@ -16359,7 +16520,7 @@ fn analyzeArithmetic(
1635916520 if (is_int) {
1636016521 return sema.failWithUseOfUndef(block, lhs_src);
1636116522 } else {
16362 return mod.undefRef(resolved_type);
16523 return pt.undefRef(resolved_type);
1636316524 }
1636416525 }
1636516526 if (maybe_rhs_val) |rhs_val| {
......@@ -16371,7 +16532,7 @@ fn analyzeArithmetic(
1637116532 }
1637216533 return Air.internedToRef(sum.toIntern());
1637316534 } else {
16374 return Air.internedToRef((try Value.floatAdd(lhs_val, rhs_val, resolved_type, sema.arena, mod)).toIntern());
16535 return Air.internedToRef((try Value.floatAdd(lhs_val, rhs_val, resolved_type, sema.arena, pt)).toIntern());
1637516536 }
1637616537 } else break :rs .{ rhs_src, air_tag, .add_safe };
1637716538 } else break :rs .{ lhs_src, air_tag, .add_safe };
......@@ -16381,15 +16542,15 @@ fn analyzeArithmetic(
1638116542 // If either of the operands are zero, the other operand is returned.
1638216543 // If either of the operands are undefined, the result is undefined.
1638316544 if (maybe_lhs_val) |lhs_val| {
16384 if (!lhs_val.isUndef(mod) and (try lhs_val.compareAllWithZeroSema(.eq, mod))) {
16545 if (!lhs_val.isUndef(mod) and (try lhs_val.compareAllWithZeroSema(.eq, pt))) {
1638516546 return casted_rhs;
1638616547 }
1638716548 }
1638816549 if (maybe_rhs_val) |rhs_val| {
1638916550 if (rhs_val.isUndef(mod)) {
16390 return mod.undefRef(resolved_type);
16551 return pt.undefRef(resolved_type);
1639116552 }
16392 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
16553 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1639316554 return casted_lhs;
1639416555 }
1639516556 if (maybe_lhs_val) |lhs_val| {
......@@ -16402,26 +16563,26 @@ fn analyzeArithmetic(
1640216563 // If either of the operands are zero, then the other operand is returned.
1640316564 // If either of the operands are undefined, the result is undefined.
1640416565 if (maybe_lhs_val) |lhs_val| {
16405 if (!lhs_val.isUndef(mod) and (try lhs_val.compareAllWithZeroSema(.eq, mod))) {
16566 if (!lhs_val.isUndef(mod) and (try lhs_val.compareAllWithZeroSema(.eq, pt))) {
1640616567 return casted_rhs;
1640716568 }
1640816569 }
1640916570 if (maybe_rhs_val) |rhs_val| {
1641016571 if (rhs_val.isUndef(mod)) {
16411 return mod.undefRef(resolved_type);
16572 return pt.undefRef(resolved_type);
1641216573 }
16413 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
16574 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1641416575 return casted_lhs;
1641516576 }
1641616577 if (maybe_lhs_val) |lhs_val| {
1641716578 if (lhs_val.isUndef(mod)) {
16418 return mod.undefRef(resolved_type);
16579 return pt.undefRef(resolved_type);
1641916580 }
1642016581
1642116582 const val = if (scalar_tag == .ComptimeInt)
1642216583 try sema.intAdd(lhs_val, rhs_val, resolved_type, undefined)
1642316584 else
16424 try lhs_val.intAddSat(rhs_val, resolved_type, sema.arena, mod);
16585 try lhs_val.intAddSat(rhs_val, resolved_type, sema.arena, pt);
1642516586
1642616587 return Air.internedToRef(val.toIntern());
1642716588 } else break :rs .{
......@@ -16448,10 +16609,10 @@ fn analyzeArithmetic(
1644816609 if (is_int) {
1644916610 return sema.failWithUseOfUndef(block, rhs_src);
1645016611 } else {
16451 return mod.undefRef(resolved_type);
16612 return pt.undefRef(resolved_type);
1645216613 }
1645316614 }
16454 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
16615 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1645516616 return casted_lhs;
1645616617 }
1645716618 }
......@@ -16461,7 +16622,7 @@ fn analyzeArithmetic(
1646116622 if (is_int) {
1646216623 return sema.failWithUseOfUndef(block, lhs_src);
1646316624 } else {
16464 return mod.undefRef(resolved_type);
16625 return pt.undefRef(resolved_type);
1646516626 }
1646616627 }
1646716628 if (maybe_rhs_val) |rhs_val| {
......@@ -16473,7 +16634,7 @@ fn analyzeArithmetic(
1647316634 }
1647416635 return Air.internedToRef(diff.toIntern());
1647516636 } else {
16476 return Air.internedToRef((try Value.floatSub(lhs_val, rhs_val, resolved_type, sema.arena, mod)).toIntern());
16637 return Air.internedToRef((try Value.floatSub(lhs_val, rhs_val, resolved_type, sema.arena, pt)).toIntern());
1647716638 }
1647816639 } else break :rs .{ rhs_src, air_tag, .sub_safe };
1647916640 } else break :rs .{ lhs_src, air_tag, .sub_safe };
......@@ -16484,15 +16645,15 @@ fn analyzeArithmetic(
1648416645 // If either of the operands are undefined, the result is undefined.
1648516646 if (maybe_rhs_val) |rhs_val| {
1648616647 if (rhs_val.isUndef(mod)) {
16487 return mod.undefRef(resolved_type);
16648 return pt.undefRef(resolved_type);
1648816649 }
16489 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
16650 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1649016651 return casted_lhs;
1649116652 }
1649216653 }
1649316654 if (maybe_lhs_val) |lhs_val| {
1649416655 if (lhs_val.isUndef(mod)) {
16495 return mod.undefRef(resolved_type);
16656 return pt.undefRef(resolved_type);
1649616657 }
1649716658 if (maybe_rhs_val) |rhs_val| {
1649816659 return Air.internedToRef((try sema.numberSubWrapScalar(lhs_val, rhs_val, resolved_type)).toIntern());
......@@ -16505,21 +16666,21 @@ fn analyzeArithmetic(
1650516666 // If either of the operands are undefined, the result is undefined.
1650616667 if (maybe_rhs_val) |rhs_val| {
1650716668 if (rhs_val.isUndef(mod)) {
16508 return mod.undefRef(resolved_type);
16669 return pt.undefRef(resolved_type);
1650916670 }
16510 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
16671 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1651116672 return casted_lhs;
1651216673 }
1651316674 }
1651416675 if (maybe_lhs_val) |lhs_val| {
1651516676 if (lhs_val.isUndef(mod)) {
16516 return mod.undefRef(resolved_type);
16677 return pt.undefRef(resolved_type);
1651716678 }
1651816679 if (maybe_rhs_val) |rhs_val| {
1651916680 const val = if (scalar_tag == .ComptimeInt)
1652016681 try sema.intSub(lhs_val, rhs_val, resolved_type, undefined)
1652116682 else
16522 try lhs_val.intSubSat(rhs_val, resolved_type, sema.arena, mod);
16683 try lhs_val.intSubSat(rhs_val, resolved_type, sema.arena, pt);
1652316684
1652416685 return Air.internedToRef(val.toIntern());
1652516686 } else break :rs .{ rhs_src, .sub_sat, .sub_sat };
......@@ -16540,13 +16701,13 @@ fn analyzeArithmetic(
1654016701 // the result is nan.
1654116702 // If either of the operands are nan, the result is nan.
1654216703 const scalar_zero = switch (scalar_tag) {
16543 .ComptimeFloat, .Float => try mod.floatValue(scalar_type, 0.0),
16544 .ComptimeInt, .Int => try mod.intValue(scalar_type, 0),
16704 .ComptimeFloat, .Float => try pt.floatValue(scalar_type, 0.0),
16705 .ComptimeInt, .Int => try pt.intValue(scalar_type, 0),
1654516706 else => unreachable,
1654616707 };
1654716708 const scalar_one = switch (scalar_tag) {
16548 .ComptimeFloat, .Float => try mod.floatValue(scalar_type, 1.0),
16549 .ComptimeInt, .Int => try mod.intValue(scalar_type, 1),
16709 .ComptimeFloat, .Float => try pt.floatValue(scalar_type, 1.0),
16710 .ComptimeInt, .Int => try pt.intValue(scalar_type, 1),
1655016711 else => unreachable,
1655116712 };
1655216713 if (maybe_lhs_val) |lhs_val| {
......@@ -16554,13 +16715,13 @@ fn analyzeArithmetic(
1655416715 if (lhs_val.isNan(mod)) {
1655516716 return Air.internedToRef(lhs_val.toIntern());
1655616717 }
16557 if (try lhs_val.compareAllWithZeroSema(.eq, mod)) lz: {
16718 if (try lhs_val.compareAllWithZeroSema(.eq, pt)) lz: {
1655816719 if (maybe_rhs_val) |rhs_val| {
1655916720 if (rhs_val.isNan(mod)) {
1656016721 return Air.internedToRef(rhs_val.toIntern());
1656116722 }
1656216723 if (rhs_val.isInf(mod)) {
16563 return Air.internedToRef((try mod.floatValue(resolved_type, std.math.nan(f128))).toIntern());
16724 return Air.internedToRef((try pt.floatValue(resolved_type, std.math.nan(f128))).toIntern());
1656416725 }
1656516726 } else if (resolved_type.isAnyFloat()) {
1656616727 break :lz;
......@@ -16579,16 +16740,16 @@ fn analyzeArithmetic(
1657916740 if (is_int) {
1658016741 return sema.failWithUseOfUndef(block, rhs_src);
1658116742 } else {
16582 return mod.undefRef(resolved_type);
16743 return pt.undefRef(resolved_type);
1658316744 }
1658416745 }
1658516746 if (rhs_val.isNan(mod)) {
1658616747 return Air.internedToRef(rhs_val.toIntern());
1658716748 }
16588 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) rz: {
16749 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) rz: {
1658916750 if (maybe_lhs_val) |lhs_val| {
1659016751 if (lhs_val.isInf(mod)) {
16591 return Air.internedToRef((try mod.floatValue(resolved_type, std.math.nan(f128))).toIntern());
16752 return Air.internedToRef((try pt.floatValue(resolved_type, std.math.nan(f128))).toIntern());
1659216753 }
1659316754 } else if (resolved_type.isAnyFloat()) {
1659416755 break :rz;
......@@ -16604,18 +16765,18 @@ fn analyzeArithmetic(
1660416765 if (is_int) {
1660516766 return sema.failWithUseOfUndef(block, lhs_src);
1660616767 } else {
16607 return mod.undefRef(resolved_type);
16768 return pt.undefRef(resolved_type);
1660816769 }
1660916770 }
1661016771 if (is_int) {
1661116772 var overflow_idx: ?usize = null;
16612 const product = try lhs_val.intMul(rhs_val, resolved_type, &overflow_idx, sema.arena, mod);
16773 const product = try lhs_val.intMul(rhs_val, resolved_type, &overflow_idx, sema.arena, pt);
1661316774 if (overflow_idx) |vec_idx| {
1661416775 return sema.failWithIntegerOverflow(block, src, resolved_type, product, vec_idx);
1661516776 }
1661616777 return Air.internedToRef(product.toIntern());
1661716778 } else {
16618 return Air.internedToRef((try lhs_val.floatMul(rhs_val, resolved_type, sema.arena, mod)).toIntern());
16779 return Air.internedToRef((try lhs_val.floatMul(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1661916780 }
1662016781 } else break :rs .{ lhs_src, air_tag, .mul_safe };
1662116782 } else break :rs .{ rhs_src, air_tag, .mul_safe };
......@@ -16626,18 +16787,18 @@ fn analyzeArithmetic(
1662616787 // If either of the operands are one, result is the other operand.
1662716788 // If either of the operands are undefined, result is undefined.
1662816789 const scalar_zero = switch (scalar_tag) {
16629 .ComptimeFloat, .Float => try mod.floatValue(scalar_type, 0.0),
16630 .ComptimeInt, .Int => try mod.intValue(scalar_type, 0),
16790 .ComptimeFloat, .Float => try pt.floatValue(scalar_type, 0.0),
16791 .ComptimeInt, .Int => try pt.intValue(scalar_type, 0),
1663116792 else => unreachable,
1663216793 };
1663316794 const scalar_one = switch (scalar_tag) {
16634 .ComptimeFloat, .Float => try mod.floatValue(scalar_type, 1.0),
16635 .ComptimeInt, .Int => try mod.intValue(scalar_type, 1),
16795 .ComptimeFloat, .Float => try pt.floatValue(scalar_type, 1.0),
16796 .ComptimeInt, .Int => try pt.intValue(scalar_type, 1),
1663616797 else => unreachable,
1663716798 };
1663816799 if (maybe_lhs_val) |lhs_val| {
1663916800 if (!lhs_val.isUndef(mod)) {
16640 if (try lhs_val.compareAllWithZeroSema(.eq, mod)) {
16801 if (try lhs_val.compareAllWithZeroSema(.eq, pt)) {
1664116802 const zero_val = try sema.splat(resolved_type, scalar_zero);
1664216803 return Air.internedToRef(zero_val.toIntern());
1664316804 }
......@@ -16648,9 +16809,9 @@ fn analyzeArithmetic(
1664816809 }
1664916810 if (maybe_rhs_val) |rhs_val| {
1665016811 if (rhs_val.isUndef(mod)) {
16651 return mod.undefRef(resolved_type);
16812 return pt.undefRef(resolved_type);
1665216813 }
16653 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
16814 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1665416815 const zero_val = try sema.splat(resolved_type, scalar_zero);
1665516816 return Air.internedToRef(zero_val.toIntern());
1665616817 }
......@@ -16659,9 +16820,9 @@ fn analyzeArithmetic(
1665916820 }
1666016821 if (maybe_lhs_val) |lhs_val| {
1666116822 if (lhs_val.isUndef(mod)) {
16662 return mod.undefRef(resolved_type);
16823 return pt.undefRef(resolved_type);
1666316824 }
16664 return Air.internedToRef((try lhs_val.numberMulWrap(rhs_val, resolved_type, sema.arena, mod)).toIntern());
16825 return Air.internedToRef((try lhs_val.numberMulWrap(rhs_val, resolved_type, sema.arena, pt)).toIntern());
1666516826 } else break :rs .{ lhs_src, .mul_wrap, .mul_wrap };
1666616827 } else break :rs .{ rhs_src, .mul_wrap, .mul_wrap };
1666716828 },
......@@ -16671,18 +16832,18 @@ fn analyzeArithmetic(
1667116832 // If either of the operands are one, result is the other operand.
1667216833 // If either of the operands are undefined, result is undefined.
1667316834 const scalar_zero = switch (scalar_tag) {
16674 .ComptimeFloat, .Float => try mod.floatValue(scalar_type, 0.0),
16675 .ComptimeInt, .Int => try mod.intValue(scalar_type, 0),
16835 .ComptimeFloat, .Float => try pt.floatValue(scalar_type, 0.0),
16836 .ComptimeInt, .Int => try pt.intValue(scalar_type, 0),
1667616837 else => unreachable,
1667716838 };
1667816839 const scalar_one = switch (scalar_tag) {
16679 .ComptimeFloat, .Float => try mod.floatValue(scalar_type, 1.0),
16680 .ComptimeInt, .Int => try mod.intValue(scalar_type, 1),
16840 .ComptimeFloat, .Float => try pt.floatValue(scalar_type, 1.0),
16841 .ComptimeInt, .Int => try pt.intValue(scalar_type, 1),
1668116842 else => unreachable,
1668216843 };
1668316844 if (maybe_lhs_val) |lhs_val| {
1668416845 if (!lhs_val.isUndef(mod)) {
16685 if (try lhs_val.compareAllWithZeroSema(.eq, mod)) {
16846 if (try lhs_val.compareAllWithZeroSema(.eq, pt)) {
1668616847 const zero_val = try sema.splat(resolved_type, scalar_zero);
1668716848 return Air.internedToRef(zero_val.toIntern());
1668816849 }
......@@ -16693,9 +16854,9 @@ fn analyzeArithmetic(
1669316854 }
1669416855 if (maybe_rhs_val) |rhs_val| {
1669516856 if (rhs_val.isUndef(mod)) {
16696 return mod.undefRef(resolved_type);
16857 return pt.undefRef(resolved_type);
1669716858 }
16698 if (try rhs_val.compareAllWithZeroSema(.eq, mod)) {
16859 if (try rhs_val.compareAllWithZeroSema(.eq, pt)) {
1669916860 const zero_val = try sema.splat(resolved_type, scalar_zero);
1670016861 return Air.internedToRef(zero_val.toIntern());
1670116862 }
......@@ -16704,13 +16865,13 @@ fn analyzeArithmetic(
1670416865 }
1670516866 if (maybe_lhs_val) |lhs_val| {
1670616867 if (lhs_val.isUndef(mod)) {
16707 return mod.undefRef(resolved_type);
16868 return pt.undefRef(resolved_type);
1670816869 }
1670916870
1671016871 const val = if (scalar_tag == .ComptimeInt)
16711 try lhs_val.intMul(rhs_val, resolved_type, undefined, sema.arena, mod)
16872 try lhs_val.intMul(rhs_val, resolved_type, undefined, sema.arena, pt)
1671216873 else
16713 try lhs_val.intMulSat(rhs_val, resolved_type, sema.arena, mod);
16874 try lhs_val.intMulSat(rhs_val, resolved_type, sema.arena, pt);
1671416875
1671516876 return Air.internedToRef(val.toIntern());
1671616877 } else break :rs .{ lhs_src, .mul_sat, .mul_sat };
......@@ -16758,7 +16919,7 @@ fn analyzeArithmetic(
1675816919 })
1675916920 else
1676016921 ov_bit;
16761 const zero_ov = Air.internedToRef((try mod.intValue(Type.u1, 0)).toIntern());
16922 const zero_ov = Air.internedToRef((try pt.intValue(Type.u1, 0)).toIntern());
1676216923 const no_ov = try block.addBinOp(.cmp_eq, any_ov_bit, zero_ov);
1676316924
1676416925 try sema.addSafetyCheck(block, src, no_ov, .integer_overflow);
......@@ -16782,7 +16943,8 @@ fn analyzePtrArithmetic(
1678216943 // TODO if the operand is comptime-known to be negative, or is a negative int,
1678316944 // coerce to isize instead of usize.
1678416945 const offset = try sema.coerce(block, Type.usize, uncasted_offset, offset_src);
16785 const mod = sema.mod;
16946 const pt = sema.pt;
16947 const mod = pt.zcu;
1678616948 const opt_ptr_val = try sema.resolveValue(ptr);
1678716949 const opt_off_val = try sema.resolveDefinedValue(block, offset_src, offset);
1678816950 const ptr_ty = sema.typeOf(ptr);
......@@ -16800,7 +16962,7 @@ fn analyzePtrArithmetic(
1680016962 // it being a multiple of the type size.
1680116963 const elem_size = try sema.typeAbiSize(Type.fromInterned(ptr_info.child));
1680216964 const addend = if (opt_off_val) |off_val| a: {
16803 const off_int = try sema.usizeCast(block, offset_src, try off_val.toUnsignedIntSema(mod));
16965 const off_int = try sema.usizeCast(block, offset_src, try off_val.toUnsignedIntSema(pt));
1680416966 break :a elem_size * off_int;
1680516967 } else elem_size;
1680616968
......@@ -16813,7 +16975,7 @@ fn analyzePtrArithmetic(
1681316975 ));
1681416976 assert(new_align != .none);
1681516977
16816 break :t try mod.ptrTypeSema(.{
16978 break :t try pt.ptrTypeSema(.{
1681716979 .child = ptr_info.child,
1681816980 .sentinel = ptr_info.sentinel,
1681916981 .flags = .{
......@@ -16830,16 +16992,16 @@ fn analyzePtrArithmetic(
1683016992 const runtime_src = rs: {
1683116993 if (opt_ptr_val) |ptr_val| {
1683216994 if (opt_off_val) |offset_val| {
16833 if (ptr_val.isUndef(mod)) return mod.undefRef(new_ptr_ty);
16995 if (ptr_val.isUndef(mod)) return pt.undefRef(new_ptr_ty);
1683416996
16835 const offset_int = try sema.usizeCast(block, offset_src, try offset_val.toUnsignedIntSema(mod));
16997 const offset_int = try sema.usizeCast(block, offset_src, try offset_val.toUnsignedIntSema(pt));
1683616998 if (offset_int == 0) return ptr;
1683716999 if (air_tag == .ptr_sub) {
1683817000 const elem_size = try sema.typeAbiSize(Type.fromInterned(ptr_info.child));
1683917001 const new_ptr_val = try sema.ptrSubtract(block, op_src, ptr_val, offset_int * elem_size, new_ptr_ty);
1684017002 return Air.internedToRef(new_ptr_val.toIntern());
1684117003 } else {
16842 const new_ptr_val = try mod.getCoerced(try ptr_val.ptrElem(offset_int, mod), new_ptr_ty);
17004 const new_ptr_val = try pt.getCoerced(try ptr_val.ptrElem(offset_int, pt), new_ptr_ty);
1684317005 return Air.internedToRef(new_ptr_val.toIntern());
1684417006 }
1684517007 } else break :rs offset_src;
......@@ -16879,6 +17041,8 @@ fn zirAsm(
1687917041 const tracy = trace(@src());
1688017042 defer tracy.end();
1688117043
17044 const pt = sema.pt;
17045 const mod = pt.zcu;
1688217046 const extra = sema.code.extraData(Zir.Inst.Asm, extended.operand);
1688317047 const src = block.nodeOffset(extra.data.src_node);
1688417048 const ret_ty_src = block.src(.{ .node_offset_asm_ret_ty = extra.data.src_node });
......@@ -16910,7 +17074,7 @@ fn zirAsm(
1691017074 if (is_volatile) {
1691117075 return sema.fail(block, src, "volatile keyword is redundant on module-level assembly", .{});
1691217076 }
16913 try sema.mod.addGlobalAssembly(sema.owner_decl_index, asm_source);
17077 try mod.addGlobalAssembly(sema.owner_decl_index, asm_source);
1691417078 return .void_value;
1691517079 }
1691617080
......@@ -16959,7 +17123,6 @@ fn zirAsm(
1695917123
1696017124 const args = try sema.arena.alloc(Air.Inst.Ref, inputs_len);
1696117125 const inputs = try sema.arena.alloc(ConstraintName, inputs_len);
16962 const mod = sema.mod;
1696317126
1696417127 for (args, 0..) |*arg, arg_i| {
1696517128 const input = sema.code.extraData(Zir.Inst.Asm.Input, extra_i);
......@@ -17049,7 +17212,8 @@ fn zirCmpEq(
1704917212 const tracy = trace(@src());
1705017213 defer tracy.end();
1705117214
17052 const mod = sema.mod;
17215 const pt = sema.pt;
17216 const mod = pt.zcu;
1705317217 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1705417218 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
1705517219 const src: LazySrcLoc = block.nodeOffset(inst_data.src_node);
......@@ -17077,7 +17241,7 @@ fn zirCmpEq(
1707717241
1707817242 if (lhs_ty_tag == .Null or rhs_ty_tag == .Null) {
1707917243 const non_null_type = if (lhs_ty_tag == .Null) rhs_ty else lhs_ty;
17080 return sema.fail(block, src, "comparison of '{}' with null", .{non_null_type.fmt(mod)});
17244 return sema.fail(block, src, "comparison of '{}' with null", .{non_null_type.fmt(pt)});
1708117245 }
1708217246
1708317247 if (lhs_ty_tag == .Union and (rhs_ty_tag == .EnumLiteral or rhs_ty_tag == .Enum)) {
......@@ -17092,7 +17256,7 @@ fn zirCmpEq(
1709217256 if (try sema.resolveValue(lhs)) |lval| {
1709317257 if (try sema.resolveValue(rhs)) |rval| {
1709417258 if (lval.isUndef(mod) or rval.isUndef(mod)) {
17095 return mod.undefRef(Type.bool);
17259 return pt.undefRef(Type.bool);
1709617260 }
1709717261 const lkey = mod.intern_pool.indexToKey(lval.toIntern());
1709817262 const rkey = mod.intern_pool.indexToKey(rval.toIntern());
......@@ -17128,14 +17292,15 @@ fn analyzeCmpUnionTag(
1712817292 tag_src: LazySrcLoc,
1712917293 op: std.math.CompareOperator,
1713017294) CompileError!Air.Inst.Ref {
17131 const mod = sema.mod;
17295 const pt = sema.pt;
17296 const mod = pt.zcu;
1713217297 const union_ty = sema.typeOf(un);
17133 try union_ty.resolveFields(mod);
17298 try union_ty.resolveFields(pt);
1713417299 const union_tag_ty = union_ty.unionTagType(mod) orelse {
1713517300 const msg = msg: {
1713617301 const msg = try sema.errMsg(un_src, "comparison of union and enum literal is only valid for tagged union types", .{});
1713717302 errdefer msg.destroy(sema.gpa);
17138 try sema.errNote(union_ty.srcLoc(mod), msg, "union '{}' is not a tagged union", .{union_ty.fmt(mod)});
17303 try sema.errNote(union_ty.srcLoc(mod), msg, "union '{}' is not a tagged union", .{union_ty.fmt(pt)});
1713917304 break :msg msg;
1714017305 };
1714117306 return sema.failWithOwnedErrorMsg(block, msg);
......@@ -17146,7 +17311,7 @@ fn analyzeCmpUnionTag(
1714617311 const coerced_union = try sema.coerce(block, union_tag_ty, un, un_src);
1714717312
1714817313 if (try sema.resolveValue(coerced_tag)) |enum_val| {
17149 if (enum_val.isUndef(mod)) return mod.undefRef(Type.bool);
17314 if (enum_val.isUndef(mod)) return pt.undefRef(Type.bool);
1715017315 const field_ty = union_ty.unionFieldType(enum_val, mod).?;
1715117316 if (field_ty.zigTypeTag(mod) == .NoReturn) {
1715217317 return .bool_false;
......@@ -17187,7 +17352,8 @@ fn analyzeCmp(
1718717352 rhs_src: LazySrcLoc,
1718817353 is_equality_cmp: bool,
1718917354) CompileError!Air.Inst.Ref {
17190 const mod = sema.mod;
17355 const pt = sema.pt;
17356 const mod = pt.zcu;
1719117357 const lhs_ty = sema.typeOf(lhs);
1719217358 const rhs_ty = sema.typeOf(rhs);
1719317359 if (lhs_ty.zigTypeTag(mod) != .Optional and rhs_ty.zigTypeTag(mod) != .Optional) {
......@@ -17215,7 +17381,7 @@ fn analyzeCmp(
1721517381 const resolved_type = try sema.resolvePeerTypes(block, src, instructions, .{ .override = &[_]?LazySrcLoc{ lhs_src, rhs_src } });
1721617382 if (!resolved_type.isSelfComparable(mod, is_equality_cmp)) {
1721717383 return sema.fail(block, src, "operator {s} not allowed for type '{}'", .{
17218 compareOperatorName(op), resolved_type.fmt(mod),
17384 compareOperatorName(op), resolved_type.fmt(pt),
1721917385 });
1722017386 }
1722117387 const casted_lhs = try sema.coerce(block, resolved_type, lhs, lhs_src);
......@@ -17244,13 +17410,14 @@ fn cmpSelf(
1724417410 lhs_src: LazySrcLoc,
1724517411 rhs_src: LazySrcLoc,
1724617412) CompileError!Air.Inst.Ref {
17247 const mod = sema.mod;
17413 const pt = sema.pt;
17414 const mod = pt.zcu;
1724817415 const resolved_type = sema.typeOf(casted_lhs);
1724917416 const runtime_src: LazySrcLoc = src: {
1725017417 if (try sema.resolveValue(casted_lhs)) |lhs_val| {
17251 if (lhs_val.isUndef(mod)) return mod.undefRef(Type.bool);
17418 if (lhs_val.isUndef(mod)) return pt.undefRef(Type.bool);
1725217419 if (try sema.resolveValue(casted_rhs)) |rhs_val| {
17253 if (rhs_val.isUndef(mod)) return mod.undefRef(Type.bool);
17420 if (rhs_val.isUndef(mod)) return pt.undefRef(Type.bool);
1725417421
1725517422 if (resolved_type.zigTypeTag(mod) == .Vector) {
1725617423 const cmp_val = try sema.compareVector(lhs_val, op, rhs_val, resolved_type);
......@@ -17273,7 +17440,7 @@ fn cmpSelf(
1727317440 // bool eq/neq more efficiently.
1727417441 if (resolved_type.zigTypeTag(mod) == .Bool) {
1727517442 if (try sema.resolveValue(casted_rhs)) |rhs_val| {
17276 if (rhs_val.isUndef(mod)) return mod.undefRef(Type.bool);
17443 if (rhs_val.isUndef(mod)) return pt.undefRef(Type.bool);
1727717444 return sema.runtimeBoolCmp(block, src, op, casted_lhs, rhs_val.toBool(), lhs_src);
1727817445 }
1727917446 }
......@@ -17310,24 +17477,24 @@ fn runtimeBoolCmp(
1731017477}
1731117478
1731217479fn zirSizeOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
17313 const mod = sema.mod;
17480 const pt = sema.pt;
1731417481 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1731517482 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
1731617483 const ty = try sema.resolveType(block, operand_src, inst_data.operand);
17317 switch (ty.zigTypeTag(mod)) {
17484 switch (ty.zigTypeTag(pt.zcu)) {
1731817485 .Fn,
1731917486 .NoReturn,
1732017487 .Undefined,
1732117488 .Null,
1732217489 .Opaque,
17323 => return sema.fail(block, operand_src, "no size available for type '{}'", .{ty.fmt(mod)}),
17490 => return sema.fail(block, operand_src, "no size available for type '{}'", .{ty.fmt(pt)}),
1732417491
1732517492 .Type,
1732617493 .EnumLiteral,
1732717494 .ComptimeFloat,
1732817495 .ComptimeInt,
1732917496 .Void,
17330 => return mod.intRef(Type.comptime_int, 0),
17497 => return pt.intRef(Type.comptime_int, 0),
1733117498
1733217499 .Bool,
1733317500 .Int,
......@@ -17345,12 +17512,13 @@ fn zirSizeOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
1734517512 .AnyFrame,
1734617513 => {},
1734717514 }
17348 const val = try ty.lazyAbiSize(mod);
17515 const val = try ty.lazyAbiSize(pt);
1734917516 return Air.internedToRef(val.toIntern());
1735017517}
1735117518
1735217519fn zirBitSizeOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
17353 const mod = sema.mod;
17520 const pt = sema.pt;
17521 const mod = pt.zcu;
1735417522 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1735517523 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
1735617524 const operand_ty = try sema.resolveType(block, operand_src, inst_data.operand);
......@@ -17360,14 +17528,14 @@ fn zirBitSizeOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
1736017528 .Undefined,
1736117529 .Null,
1736217530 .Opaque,
17363 => return sema.fail(block, operand_src, "no size available for type '{}'", .{operand_ty.fmt(mod)}),
17531 => return sema.fail(block, operand_src, "no size available for type '{}'", .{operand_ty.fmt(pt)}),
1736417532
1736517533 .Type,
1736617534 .EnumLiteral,
1736717535 .ComptimeFloat,
1736817536 .ComptimeInt,
1736917537 .Void,
17370 => return mod.intRef(Type.comptime_int, 0),
17538 => return pt.intRef(Type.comptime_int, 0),
1737117539
1737217540 .Bool,
1737317541 .Int,
......@@ -17385,8 +17553,8 @@ fn zirBitSizeOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
1738517553 .AnyFrame,
1738617554 => {},
1738717555 }
17388 const bit_size = try operand_ty.bitSizeAdvanced(mod, .sema);
17389 return mod.intRef(Type.comptime_int, bit_size);
17556 const bit_size = try operand_ty.bitSizeAdvanced(pt, .sema);
17557 return pt.intRef(Type.comptime_int, bit_size);
1739017558}
1739117559
1739217560fn zirThis(
......@@ -17394,14 +17562,16 @@ fn zirThis(
1739417562 block: *Block,
1739517563 extended: Zir.Inst.Extended.InstData,
1739617564) CompileError!Air.Inst.Ref {
17397 const mod = sema.mod;
17565 const pt = sema.pt;
17566 const mod = pt.zcu;
1739817567 const this_decl_index = mod.namespacePtr(block.namespace).decl_index;
1739917568 const src = block.nodeOffset(@bitCast(extended.operand));
1740017569 return sema.analyzeDeclVal(block, src, this_decl_index);
1740117570}
1740217571
1740317572fn zirClosureGet(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
17404 const mod = sema.mod;
17573 const pt = sema.pt;
17574 const mod = pt.zcu;
1740517575 const ip = &mod.intern_pool;
1740617576 const captures = mod.namespacePtr(block.namespace).getType(mod).getCaptures(mod);
1740717577
......@@ -17489,7 +17659,7 @@ fn zirRetAddr(
1748917659 _ = extended;
1749017660 if (block.is_comptime) {
1749117661 // TODO: we could give a meaningful lazy value here. #14938
17492 return sema.mod.intRef(Type.usize, 0);
17662 return sema.pt.intRef(Type.usize, 0);
1749317663 } else {
1749417664 return block.addNoOp(.ret_addr);
1749517665 }
......@@ -17514,7 +17684,8 @@ fn zirBuiltinSrc(
1751417684 const tracy = trace(@src());
1751517685 defer tracy.end();
1751617686
17517 const mod = sema.mod;
17687 const pt = sema.pt;
17688 const mod = pt.zcu;
1751817689 const extra = sema.code.extraData(Zir.Inst.Src, extended.operand).data;
1751917690 const fn_owner_decl = mod.funcOwnerDeclPtr(sema.func_index);
1752017691 const ip = &mod.intern_pool;
......@@ -17522,80 +17693,81 @@ fn zirBuiltinSrc(
1752217693
1752317694 const func_name_val = v: {
1752417695 const func_name_len = fn_owner_decl.name.length(ip);
17525 const array_ty = try ip.get(gpa, .{ .array_type = .{
17696 const array_ty = try pt.intern(.{ .array_type = .{
1752617697 .len = func_name_len,
1752717698 .sentinel = .zero_u8,
1752817699 .child = .u8_type,
1752917700 } });
17530 break :v try ip.get(gpa, .{ .slice = .{
17701 break :v try pt.intern(.{ .slice = .{
1753117702 .ty = .slice_const_u8_sentinel_0_type,
17532 .ptr = try ip.get(gpa, .{ .ptr = .{
17703 .ptr = try pt.intern(.{ .ptr = .{
1753317704 .ty = .manyptr_const_u8_sentinel_0_type,
1753417705 .base_addr = .{ .anon_decl = .{
1753517706 .orig_ty = .slice_const_u8_sentinel_0_type,
17536 .val = try ip.get(gpa, .{ .aggregate = .{
17707 .val = try pt.intern(.{ .aggregate = .{
1753717708 .ty = array_ty,
1753817709 .storage = .{ .bytes = fn_owner_decl.name.toString() },
1753917710 } }),
1754017711 } },
1754117712 .byte_offset = 0,
1754217713 } }),
17543 .len = (try mod.intValue(Type.usize, func_name_len)).toIntern(),
17714 .len = (try pt.intValue(Type.usize, func_name_len)).toIntern(),
1754417715 } });
1754517716 };
1754617717
1754717718 const file_name_val = v: {
1754817719 // The compiler must not call realpath anywhere.
1754917720 const file_name = try fn_owner_decl.getFileScope(mod).fullPath(sema.arena);
17550 const array_ty = try ip.get(gpa, .{ .array_type = .{
17721 const array_ty = try pt.intern(.{ .array_type = .{
1755117722 .len = file_name.len,
1755217723 .sentinel = .zero_u8,
1755317724 .child = .u8_type,
1755417725 } });
17555 break :v try ip.get(gpa, .{ .slice = .{
17726 break :v try pt.intern(.{ .slice = .{
1755617727 .ty = .slice_const_u8_sentinel_0_type,
17557 .ptr = try ip.get(gpa, .{ .ptr = .{
17728 .ptr = try pt.intern(.{ .ptr = .{
1755817729 .ty = .manyptr_const_u8_sentinel_0_type,
1755917730 .base_addr = .{ .anon_decl = .{
1756017731 .orig_ty = .slice_const_u8_sentinel_0_type,
17561 .val = try ip.get(gpa, .{ .aggregate = .{
17732 .val = try pt.intern(.{ .aggregate = .{
1756217733 .ty = array_ty,
1756317734 .storage = .{
17564 .bytes = try ip.getOrPutString(gpa, file_name, .maybe_embedded_nulls),
17735 .bytes = try ip.getOrPutString(gpa, pt.tid, file_name, .maybe_embedded_nulls),
1756517736 },
1756617737 } }),
1756717738 } },
1756817739 .byte_offset = 0,
1756917740 } }),
17570 .len = (try mod.intValue(Type.usize, file_name.len)).toIntern(),
17741 .len = (try pt.intValue(Type.usize, file_name.len)).toIntern(),
1757117742 } });
1757217743 };
1757317744
17574 const src_loc_ty = try mod.getBuiltinType("SourceLocation");
17745 const src_loc_ty = try pt.getBuiltinType("SourceLocation");
1757517746 const fields = .{
1757617747 // file: [:0]const u8,
1757717748 file_name_val,
1757817749 // fn_name: [:0]const u8,
1757917750 func_name_val,
1758017751 // line: u32,
17581 (try mod.intValue(Type.u32, extra.line + 1)).toIntern(),
17752 (try pt.intValue(Type.u32, extra.line + 1)).toIntern(),
1758217753 // column: u32,
17583 (try mod.intValue(Type.u32, extra.column + 1)).toIntern(),
17754 (try pt.intValue(Type.u32, extra.column + 1)).toIntern(),
1758417755 };
17585 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
17756 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
1758617757 .ty = src_loc_ty.toIntern(),
1758717758 .storage = .{ .elems = &fields },
1758817759 } })));
1758917760}
1759017761
1759117762fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
17592 const mod = sema.mod;
17763 const pt = sema.pt;
17764 const mod = pt.zcu;
1759317765 const gpa = sema.gpa;
1759417766 const ip = &mod.intern_pool;
1759517767 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1759617768 const src = block.nodeOffset(inst_data.src_node);
1759717769 const ty = try sema.resolveType(block, src, inst_data.operand);
17598 const type_info_ty = try mod.getBuiltinType("Type");
17770 const type_info_ty = try pt.getBuiltinType("Type");
1759917771 const type_info_tag_ty = type_info_ty.unionTagType(mod).?;
1760017772
1760117773 if (ty.typeDeclInst(mod)) |type_decl_inst| {
......@@ -17612,9 +17784,9 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1761217784 .Undefined,
1761317785 .Null,
1761417786 .EnumLiteral,
17615 => |type_info_tag| return Air.internedToRef((try mod.intern(.{ .un = .{
17787 => |type_info_tag| return Air.internedToRef((try pt.intern(.{ .un = .{
1761617788 .ty = type_info_ty.toIntern(),
17617 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(type_info_tag))).toIntern(),
17789 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(type_info_tag))).toIntern(),
1761817790 .val = .void_value,
1761917791 } }))),
1762017792 .Fn => {
......@@ -17622,7 +17794,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1762217794 block,
1762317795 src,
1762417796 type_info_ty.getNamespaceIndex(mod),
17625 try ip.getOrPutString(gpa, "Fn", .no_embedded_nulls),
17797 try ip.getOrPutString(gpa, pt.tid, "Fn", .no_embedded_nulls),
1762617798 )).?;
1762717799 try sema.ensureDeclAnalyzed(fn_info_decl_index);
1762817800 const fn_info_decl = mod.declPtr(fn_info_decl_index);
......@@ -17632,7 +17804,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1763217804 block,
1763317805 src,
1763417806 fn_info_ty.getNamespaceIndex(mod),
17635 try ip.getOrPutString(gpa, "Param", .no_embedded_nulls),
17807 try ip.getOrPutString(gpa, pt.tid, "Param", .no_embedded_nulls),
1763617808 )).?;
1763717809 try sema.ensureDeclAnalyzed(param_info_decl_index);
1763817810 const param_info_decl = mod.declPtr(param_info_decl_index);
......@@ -17643,8 +17815,8 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1764317815 for (param_vals, 0..) |*param_val, i| {
1764417816 const param_ty = func_ty_info.param_types.get(ip)[i];
1764517817 const is_generic = param_ty == .generic_poison_type;
17646 const param_ty_val = try ip.get(gpa, .{ .opt = .{
17647 .ty = try ip.get(gpa, .{ .opt_type = .type_type }),
17818 const param_ty_val = try pt.intern(.{ .opt = .{
17819 .ty = try pt.intern(.{ .opt_type = .type_type }),
1764817820 .val = if (is_generic) .none else param_ty,
1764917821 } });
1765017822
......@@ -17661,22 +17833,22 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1766117833 // type: ?type,
1766217834 param_ty_val,
1766317835 };
17664 param_val.* = try mod.intern(.{ .aggregate = .{
17836 param_val.* = try pt.intern(.{ .aggregate = .{
1766517837 .ty = param_info_ty.toIntern(),
1766617838 .storage = .{ .elems = &param_fields },
1766717839 } });
1766817840 }
1766917841
1767017842 const args_val = v: {
17671 const new_decl_ty = try mod.arrayType(.{
17843 const new_decl_ty = try pt.arrayType(.{
1767217844 .len = param_vals.len,
1767317845 .child = param_info_ty.toIntern(),
1767417846 });
17675 const new_decl_val = try mod.intern(.{ .aggregate = .{
17847 const new_decl_val = try pt.intern(.{ .aggregate = .{
1767617848 .ty = new_decl_ty.toIntern(),
1767717849 .storage = .{ .elems = param_vals },
1767817850 } });
17679 const slice_ty = (try mod.ptrTypeSema(.{
17851 const slice_ty = (try pt.ptrTypeSema(.{
1768017852 .child = param_info_ty.toIntern(),
1768117853 .flags = .{
1768217854 .size = .Slice,
......@@ -17684,9 +17856,9 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1768417856 },
1768517857 })).toIntern();
1768617858 const manyptr_ty = Type.fromInterned(slice_ty).slicePtrFieldType(mod).toIntern();
17687 break :v try mod.intern(.{ .slice = .{
17859 break :v try pt.intern(.{ .slice = .{
1768817860 .ty = slice_ty,
17689 .ptr = try mod.intern(.{ .ptr = .{
17861 .ptr = try pt.intern(.{ .ptr = .{
1769017862 .ty = manyptr_ty,
1769117863 .base_addr = .{ .anon_decl = .{
1769217864 .orig_ty = manyptr_ty,
......@@ -17694,23 +17866,23 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1769417866 } },
1769517867 .byte_offset = 0,
1769617868 } }),
17697 .len = (try mod.intValue(Type.usize, param_vals.len)).toIntern(),
17869 .len = (try pt.intValue(Type.usize, param_vals.len)).toIntern(),
1769817870 } });
1769917871 };
1770017872
17701 const ret_ty_opt = try mod.intern(.{ .opt = .{
17702 .ty = try ip.get(gpa, .{ .opt_type = .type_type }),
17873 const ret_ty_opt = try pt.intern(.{ .opt = .{
17874 .ty = try pt.intern(.{ .opt_type = .type_type }),
1770317875 .val = if (func_ty_info.return_type == .generic_poison_type)
1770417876 .none
1770517877 else
1770617878 func_ty_info.return_type,
1770717879 } });
1770817880
17709 const callconv_ty = try mod.getBuiltinType("CallingConvention");
17881 const callconv_ty = try pt.getBuiltinType("CallingConvention");
1771017882
1771117883 const field_values = .{
1771217884 // calling_convention: CallingConvention,
17713 (try mod.enumValueFieldIndex(callconv_ty, @intFromEnum(func_ty_info.cc))).toIntern(),
17885 (try pt.enumValueFieldIndex(callconv_ty, @intFromEnum(func_ty_info.cc))).toIntern(),
1771417886 // is_generic: bool,
1771517887 Value.makeBool(func_ty_info.is_generic).toIntern(),
1771617888 // is_var_args: bool,
......@@ -17720,10 +17892,10 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1772017892 // args: []const Fn.Param,
1772117893 args_val,
1772217894 };
17723 return Air.internedToRef((try mod.intern(.{ .un = .{
17895 return Air.internedToRef((try pt.intern(.{ .un = .{
1772417896 .ty = type_info_ty.toIntern(),
17725 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Fn))).toIntern(),
17726 .val = try mod.intern(.{ .aggregate = .{
17897 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Fn))).toIntern(),
17898 .val = try pt.intern(.{ .aggregate = .{
1772717899 .ty = fn_info_ty.toIntern(),
1772817900 .storage = .{ .elems = &field_values },
1772917901 } }),
......@@ -17734,24 +17906,24 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1773417906 block,
1773517907 src,
1773617908 type_info_ty.getNamespaceIndex(mod),
17737 try ip.getOrPutString(gpa, "Int", .no_embedded_nulls),
17909 try ip.getOrPutString(gpa, pt.tid, "Int", .no_embedded_nulls),
1773817910 )).?;
1773917911 try sema.ensureDeclAnalyzed(int_info_decl_index);
1774017912 const int_info_decl = mod.declPtr(int_info_decl_index);
1774117913 const int_info_ty = int_info_decl.val.toType();
1774217914
17743 const signedness_ty = try mod.getBuiltinType("Signedness");
17915 const signedness_ty = try pt.getBuiltinType("Signedness");
1774417916 const info = ty.intInfo(mod);
1774517917 const field_values = .{
1774617918 // signedness: Signedness,
17747 (try mod.enumValueFieldIndex(signedness_ty, @intFromEnum(info.signedness))).toIntern(),
17919 (try pt.enumValueFieldIndex(signedness_ty, @intFromEnum(info.signedness))).toIntern(),
1774817920 // bits: u16,
17749 (try mod.intValue(Type.u16, info.bits)).toIntern(),
17921 (try pt.intValue(Type.u16, info.bits)).toIntern(),
1775017922 };
17751 return Air.internedToRef((try mod.intern(.{ .un = .{
17923 return Air.internedToRef((try pt.intern(.{ .un = .{
1775217924 .ty = type_info_ty.toIntern(),
17753 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Int))).toIntern(),
17754 .val = try mod.intern(.{ .aggregate = .{
17925 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Int))).toIntern(),
17926 .val = try pt.intern(.{ .aggregate = .{
1775517927 .ty = int_info_ty.toIntern(),
1775617928 .storage = .{ .elems = &field_values },
1775717929 } }),
......@@ -17762,7 +17934,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1776217934 block,
1776317935 src,
1776417936 type_info_ty.getNamespaceIndex(mod),
17765 try ip.getOrPutString(gpa, "Float", .no_embedded_nulls),
17937 try ip.getOrPutString(gpa, pt.tid, "Float", .no_embedded_nulls),
1776617938 )).?;
1776717939 try sema.ensureDeclAnalyzed(float_info_decl_index);
1776817940 const float_info_decl = mod.declPtr(float_info_decl_index);
......@@ -17770,12 +17942,12 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1777017942
1777117943 const field_vals = .{
1777217944 // bits: u16,
17773 (try mod.intValue(Type.u16, ty.bitSize(mod))).toIntern(),
17945 (try pt.intValue(Type.u16, ty.bitSize(pt))).toIntern(),
1777417946 };
17775 return Air.internedToRef((try mod.intern(.{ .un = .{
17947 return Air.internedToRef((try pt.intern(.{ .un = .{
1777617948 .ty = type_info_ty.toIntern(),
17777 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Float))).toIntern(),
17778 .val = try mod.intern(.{ .aggregate = .{
17949 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Float))).toIntern(),
17950 .val = try pt.intern(.{ .aggregate = .{
1777917951 .ty = float_info_ty.toIntern(),
1778017952 .storage = .{ .elems = &field_vals },
1778117953 } }),
......@@ -17784,17 +17956,17 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1778417956 .Pointer => {
1778517957 const info = ty.ptrInfo(mod);
1778617958 const alignment = if (info.flags.alignment.toByteUnits()) |alignment|
17787 try mod.intValue(Type.comptime_int, alignment)
17959 try pt.intValue(Type.comptime_int, alignment)
1778817960 else
17789 try Type.fromInterned(info.child).lazyAbiAlignment(mod);
17961 try Type.fromInterned(info.child).lazyAbiAlignment(pt);
1779017962
17791 const addrspace_ty = try mod.getBuiltinType("AddressSpace");
17963 const addrspace_ty = try pt.getBuiltinType("AddressSpace");
1779217964 const pointer_ty = t: {
1779317965 const decl_index = (try sema.namespaceLookup(
1779417966 block,
1779517967 src,
17796 (try mod.getBuiltinType("Type")).getNamespaceIndex(mod),
17797 try ip.getOrPutString(gpa, "Pointer", .no_embedded_nulls),
17968 (try pt.getBuiltinType("Type")).getNamespaceIndex(mod),
17969 try ip.getOrPutString(gpa, pt.tid, "Pointer", .no_embedded_nulls),
1779817970 )).?;
1779917971 try sema.ensureDeclAnalyzed(decl_index);
1780017972 const decl = mod.declPtr(decl_index);
......@@ -17805,7 +17977,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1780517977 block,
1780617978 src,
1780717979 pointer_ty.getNamespaceIndex(mod),
17808 try ip.getOrPutString(gpa, "Size", .no_embedded_nulls),
17980 try ip.getOrPutString(gpa, pt.tid, "Size", .no_embedded_nulls),
1780917981 )).?;
1781017982 try sema.ensureDeclAnalyzed(decl_index);
1781117983 const decl = mod.declPtr(decl_index);
......@@ -17814,7 +17986,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1781417986
1781517987 const field_values = .{
1781617988 // size: Size,
17817 (try mod.enumValueFieldIndex(ptr_size_ty, @intFromEnum(info.flags.size))).toIntern(),
17989 (try pt.enumValueFieldIndex(ptr_size_ty, @intFromEnum(info.flags.size))).toIntern(),
1781817990 // is_const: bool,
1781917991 Value.makeBool(info.flags.is_const).toIntern(),
1782017992 // is_volatile: bool,
......@@ -17822,7 +17994,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1782217994 // alignment: comptime_int,
1782317995 alignment.toIntern(),
1782417996 // address_space: AddressSpace
17825 (try mod.enumValueFieldIndex(addrspace_ty, @intFromEnum(info.flags.address_space))).toIntern(),
17997 (try pt.enumValueFieldIndex(addrspace_ty, @intFromEnum(info.flags.address_space))).toIntern(),
1782617998 // child: type,
1782717999 info.child,
1782818000 // is_allowzero: bool,
......@@ -17833,10 +18005,10 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1783318005 else => Value.fromInterned(info.sentinel),
1783418006 })).toIntern(),
1783518007 };
17836 return Air.internedToRef((try mod.intern(.{ .un = .{
18008 return Air.internedToRef((try pt.intern(.{ .un = .{
1783718009 .ty = type_info_ty.toIntern(),
17838 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Pointer))).toIntern(),
17839 .val = try mod.intern(.{ .aggregate = .{
18010 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Pointer))).toIntern(),
18011 .val = try pt.intern(.{ .aggregate = .{
1784018012 .ty = pointer_ty.toIntern(),
1784118013 .storage = .{ .elems = &field_values },
1784218014 } }),
......@@ -17848,7 +18020,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1784818020 block,
1784918021 src,
1785018022 type_info_ty.getNamespaceIndex(mod),
17851 try ip.getOrPutString(gpa, "Array", .no_embedded_nulls),
18023 try ip.getOrPutString(gpa, pt.tid, "Array", .no_embedded_nulls),
1785218024 )).?;
1785318025 try sema.ensureDeclAnalyzed(array_field_ty_decl_index);
1785418026 const array_field_ty_decl = mod.declPtr(array_field_ty_decl_index);
......@@ -17858,16 +18030,16 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1785818030 const info = ty.arrayInfo(mod);
1785918031 const field_values = .{
1786018032 // len: comptime_int,
17861 (try mod.intValue(Type.comptime_int, info.len)).toIntern(),
18033 (try pt.intValue(Type.comptime_int, info.len)).toIntern(),
1786218034 // child: type,
1786318035 info.elem_type.toIntern(),
1786418036 // sentinel: ?*const anyopaque,
1786518037 (try sema.optRefValue(info.sentinel)).toIntern(),
1786618038 };
17867 return Air.internedToRef((try mod.intern(.{ .un = .{
18039 return Air.internedToRef((try pt.intern(.{ .un = .{
1786818040 .ty = type_info_ty.toIntern(),
17869 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Array))).toIntern(),
17870 .val = try mod.intern(.{ .aggregate = .{
18041 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Array))).toIntern(),
18042 .val = try pt.intern(.{ .aggregate = .{
1787118043 .ty = array_field_ty.toIntern(),
1787218044 .storage = .{ .elems = &field_values },
1787318045 } }),
......@@ -17879,7 +18051,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1787918051 block,
1788018052 src,
1788118053 type_info_ty.getNamespaceIndex(mod),
17882 try ip.getOrPutString(gpa, "Vector", .no_embedded_nulls),
18054 try ip.getOrPutString(gpa, pt.tid, "Vector", .no_embedded_nulls),
1788318055 )).?;
1788418056 try sema.ensureDeclAnalyzed(vector_field_ty_decl_index);
1788518057 const vector_field_ty_decl = mod.declPtr(vector_field_ty_decl_index);
......@@ -17889,14 +18061,14 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1788918061 const info = ty.arrayInfo(mod);
1789018062 const field_values = .{
1789118063 // len: comptime_int,
17892 (try mod.intValue(Type.comptime_int, info.len)).toIntern(),
18064 (try pt.intValue(Type.comptime_int, info.len)).toIntern(),
1789318065 // child: type,
1789418066 info.elem_type.toIntern(),
1789518067 };
17896 return Air.internedToRef((try mod.intern(.{ .un = .{
18068 return Air.internedToRef((try pt.intern(.{ .un = .{
1789718069 .ty = type_info_ty.toIntern(),
17898 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Vector))).toIntern(),
17899 .val = try mod.intern(.{ .aggregate = .{
18070 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Vector))).toIntern(),
18071 .val = try pt.intern(.{ .aggregate = .{
1790018072 .ty = vector_field_ty.toIntern(),
1790118073 .storage = .{ .elems = &field_values },
1790218074 } }),
......@@ -17908,7 +18080,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1790818080 block,
1790918081 src,
1791018082 type_info_ty.getNamespaceIndex(mod),
17911 try ip.getOrPutString(gpa, "Optional", .no_embedded_nulls),
18083 try ip.getOrPutString(gpa, pt.tid, "Optional", .no_embedded_nulls),
1791218084 )).?;
1791318085 try sema.ensureDeclAnalyzed(optional_field_ty_decl_index);
1791418086 const optional_field_ty_decl = mod.declPtr(optional_field_ty_decl_index);
......@@ -17919,10 +18091,10 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1791918091 // child: type,
1792018092 ty.optionalChild(mod).toIntern(),
1792118093 };
17922 return Air.internedToRef((try mod.intern(.{ .un = .{
18094 return Air.internedToRef((try pt.intern(.{ .un = .{
1792318095 .ty = type_info_ty.toIntern(),
17924 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Optional))).toIntern(),
17925 .val = try mod.intern(.{ .aggregate = .{
18096 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Optional))).toIntern(),
18097 .val = try pt.intern(.{ .aggregate = .{
1792618098 .ty = optional_field_ty.toIntern(),
1792718099 .storage = .{ .elems = &field_values },
1792818100 } }),
......@@ -17935,7 +18107,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1793518107 block,
1793618108 src,
1793718109 type_info_ty.getNamespaceIndex(mod),
17938 try ip.getOrPutString(gpa, "Error", .no_embedded_nulls),
18110 try ip.getOrPutString(gpa, pt.tid, "Error", .no_embedded_nulls),
1793918111 )).?;
1794018112 try sema.ensureDeclAnalyzed(set_field_ty_decl_index);
1794118113 const set_field_ty_decl = mod.declPtr(set_field_ty_decl_index);
......@@ -17954,18 +18126,18 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1795418126 const error_name = names.get(ip)[error_index];
1795518127 const error_name_len = error_name.length(ip);
1795618128 const error_name_val = v: {
17957 const new_decl_ty = try mod.arrayType(.{
18129 const new_decl_ty = try pt.arrayType(.{
1795818130 .len = error_name_len,
1795918131 .sentinel = .zero_u8,
1796018132 .child = .u8_type,
1796118133 });
17962 const new_decl_val = try mod.intern(.{ .aggregate = .{
18134 const new_decl_val = try pt.intern(.{ .aggregate = .{
1796318135 .ty = new_decl_ty.toIntern(),
1796418136 .storage = .{ .bytes = error_name.toString() },
1796518137 } });
17966 break :v try mod.intern(.{ .slice = .{
18138 break :v try pt.intern(.{ .slice = .{
1796718139 .ty = .slice_const_u8_sentinel_0_type,
17968 .ptr = try mod.intern(.{ .ptr = .{
18140 .ptr = try pt.intern(.{ .ptr = .{
1796918141 .ty = .manyptr_const_u8_sentinel_0_type,
1797018142 .base_addr = .{ .anon_decl = .{
1797118143 .val = new_decl_val,
......@@ -17973,7 +18145,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1797318145 } },
1797418146 .byte_offset = 0,
1797518147 } }),
17976 .len = (try mod.intValue(Type.usize, error_name_len)).toIntern(),
18148 .len = (try pt.intValue(Type.usize, error_name_len)).toIntern(),
1797718149 } });
1797818150 };
1797918151
......@@ -17981,7 +18153,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1798118153 // name: [:0]const u8,
1798218154 error_name_val,
1798318155 };
17984 field_val.* = try mod.intern(.{ .aggregate = .{
18156 field_val.* = try pt.intern(.{ .aggregate = .{
1798518157 .ty = error_field_ty.toIntern(),
1798618158 .storage = .{ .elems = &error_field_fields },
1798718159 } });
......@@ -17992,27 +18164,27 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1799218164 };
1799318165
1799418166 // Build our ?[]const Error value
17995 const slice_errors_ty = try mod.ptrTypeSema(.{
18167 const slice_errors_ty = try pt.ptrTypeSema(.{
1799618168 .child = error_field_ty.toIntern(),
1799718169 .flags = .{
1799818170 .size = .Slice,
1799918171 .is_const = true,
1800018172 },
1800118173 });
18002 const opt_slice_errors_ty = try mod.optionalType(slice_errors_ty.toIntern());
18174 const opt_slice_errors_ty = try pt.optionalType(slice_errors_ty.toIntern());
1800318175 const errors_payload_val: InternPool.Index = if (error_field_vals) |vals| v: {
18004 const array_errors_ty = try mod.arrayType(.{
18176 const array_errors_ty = try pt.arrayType(.{
1800518177 .len = vals.len,
1800618178 .child = error_field_ty.toIntern(),
1800718179 });
18008 const new_decl_val = try mod.intern(.{ .aggregate = .{
18180 const new_decl_val = try pt.intern(.{ .aggregate = .{
1800918181 .ty = array_errors_ty.toIntern(),
1801018182 .storage = .{ .elems = vals },
1801118183 } });
1801218184 const manyptr_errors_ty = slice_errors_ty.slicePtrFieldType(mod).toIntern();
18013 break :v try mod.intern(.{ .slice = .{
18185 break :v try pt.intern(.{ .slice = .{
1801418186 .ty = slice_errors_ty.toIntern(),
18015 .ptr = try mod.intern(.{ .ptr = .{
18187 .ptr = try pt.intern(.{ .ptr = .{
1801618188 .ty = manyptr_errors_ty,
1801718189 .base_addr = .{ .anon_decl = .{
1801818190 .orig_ty = manyptr_errors_ty,
......@@ -18020,18 +18192,18 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1802018192 } },
1802118193 .byte_offset = 0,
1802218194 } }),
18023 .len = (try mod.intValue(Type.usize, vals.len)).toIntern(),
18195 .len = (try pt.intValue(Type.usize, vals.len)).toIntern(),
1802418196 } });
1802518197 } else .none;
18026 const errors_val = try mod.intern(.{ .opt = .{
18198 const errors_val = try pt.intern(.{ .opt = .{
1802718199 .ty = opt_slice_errors_ty.toIntern(),
1802818200 .val = errors_payload_val,
1802918201 } });
1803018202
1803118203 // Construct Type{ .ErrorSet = errors_val }
18032 return Air.internedToRef((try mod.intern(.{ .un = .{
18204 return Air.internedToRef((try pt.intern(.{ .un = .{
1803318205 .ty = type_info_ty.toIntern(),
18034 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.ErrorSet))).toIntern(),
18206 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.ErrorSet))).toIntern(),
1803518207 .val = errors_val,
1803618208 } })));
1803718209 },
......@@ -18041,7 +18213,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1804118213 block,
1804218214 src,
1804318215 type_info_ty.getNamespaceIndex(mod),
18044 try ip.getOrPutString(gpa, "ErrorUnion", .no_embedded_nulls),
18216 try ip.getOrPutString(gpa, pt.tid, "ErrorUnion", .no_embedded_nulls),
1804518217 )).?;
1804618218 try sema.ensureDeclAnalyzed(error_union_field_ty_decl_index);
1804718219 const error_union_field_ty_decl = mod.declPtr(error_union_field_ty_decl_index);
......@@ -18054,10 +18226,10 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1805418226 // payload: type,
1805518227 ty.errorUnionPayload(mod).toIntern(),
1805618228 };
18057 return Air.internedToRef((try mod.intern(.{ .un = .{
18229 return Air.internedToRef((try pt.intern(.{ .un = .{
1805818230 .ty = type_info_ty.toIntern(),
18059 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.ErrorUnion))).toIntern(),
18060 .val = try mod.intern(.{ .aggregate = .{
18231 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.ErrorUnion))).toIntern(),
18232 .val = try pt.intern(.{ .aggregate = .{
1806118233 .ty = error_union_field_ty.toIntern(),
1806218234 .storage = .{ .elems = &field_values },
1806318235 } }),
......@@ -18071,7 +18243,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1807118243 block,
1807218244 src,
1807318245 type_info_ty.getNamespaceIndex(mod),
18074 try ip.getOrPutString(gpa, "EnumField", .no_embedded_nulls),
18246 try ip.getOrPutString(gpa, pt.tid, "EnumField", .no_embedded_nulls),
1807518247 )).?;
1807618248 try sema.ensureDeclAnalyzed(enum_field_ty_decl_index);
1807718249 const enum_field_ty_decl = mod.declPtr(enum_field_ty_decl_index);
......@@ -18082,30 +18254,31 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1808218254 for (enum_field_vals, 0..) |*field_val, tag_index| {
1808318255 const enum_type = ip.loadEnumType(ty.toIntern());
1808418256 const value_val = if (enum_type.values.len > 0)
18085 try mod.intern_pool.getCoercedInts(
18257 try ip.getCoercedInts(
1808618258 mod.gpa,
18087 mod.intern_pool.indexToKey(enum_type.values.get(ip)[tag_index]).int,
18259 pt.tid,
18260 ip.indexToKey(enum_type.values.get(ip)[tag_index]).int,
1808818261 .comptime_int_type,
1808918262 )
1809018263 else
18091 (try mod.intValue(Type.comptime_int, tag_index)).toIntern();
18264 (try pt.intValue(Type.comptime_int, tag_index)).toIntern();
1809218265
1809318266 // TODO: write something like getCoercedInts to avoid needing to dupe
1809418267 const name_val = v: {
1809518268 const tag_name = enum_type.names.get(ip)[tag_index];
1809618269 const tag_name_len = tag_name.length(ip);
18097 const new_decl_ty = try mod.arrayType(.{
18270 const new_decl_ty = try pt.arrayType(.{
1809818271 .len = tag_name_len,
1809918272 .sentinel = .zero_u8,
1810018273 .child = .u8_type,
1810118274 });
18102 const new_decl_val = try mod.intern(.{ .aggregate = .{
18275 const new_decl_val = try pt.intern(.{ .aggregate = .{
1810318276 .ty = new_decl_ty.toIntern(),
1810418277 .storage = .{ .bytes = tag_name.toString() },
1810518278 } });
18106 break :v try mod.intern(.{ .slice = .{
18279 break :v try pt.intern(.{ .slice = .{
1810718280 .ty = .slice_const_u8_sentinel_0_type,
18108 .ptr = try mod.intern(.{ .ptr = .{
18281 .ptr = try pt.intern(.{ .ptr = .{
1810918282 .ty = .manyptr_const_u8_sentinel_0_type,
1811018283 .base_addr = .{ .anon_decl = .{
1811118284 .val = new_decl_val,
......@@ -18113,7 +18286,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1811318286 } },
1811418287 .byte_offset = 0,
1811518288 } }),
18116 .len = (try mod.intValue(Type.usize, tag_name_len)).toIntern(),
18289 .len = (try pt.intValue(Type.usize, tag_name_len)).toIntern(),
1811718290 } });
1811818291 };
1811918292
......@@ -18123,22 +18296,22 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1812318296 // value: comptime_int,
1812418297 value_val,
1812518298 };
18126 field_val.* = try mod.intern(.{ .aggregate = .{
18299 field_val.* = try pt.intern(.{ .aggregate = .{
1812718300 .ty = enum_field_ty.toIntern(),
1812818301 .storage = .{ .elems = &enum_field_fields },
1812918302 } });
1813018303 }
1813118304
1813218305 const fields_val = v: {
18133 const fields_array_ty = try mod.arrayType(.{
18306 const fields_array_ty = try pt.arrayType(.{
1813418307 .len = enum_field_vals.len,
1813518308 .child = enum_field_ty.toIntern(),
1813618309 });
18137 const new_decl_val = try mod.intern(.{ .aggregate = .{
18310 const new_decl_val = try pt.intern(.{ .aggregate = .{
1813818311 .ty = fields_array_ty.toIntern(),
1813918312 .storage = .{ .elems = enum_field_vals },
1814018313 } });
18141 const slice_ty = (try mod.ptrTypeSema(.{
18314 const slice_ty = (try pt.ptrTypeSema(.{
1814218315 .child = enum_field_ty.toIntern(),
1814318316 .flags = .{
1814418317 .size = .Slice,
......@@ -18146,9 +18319,9 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1814618319 },
1814718320 })).toIntern();
1814818321 const manyptr_ty = Type.fromInterned(slice_ty).slicePtrFieldType(mod).toIntern();
18149 break :v try mod.intern(.{ .slice = .{
18322 break :v try pt.intern(.{ .slice = .{
1815018323 .ty = slice_ty,
18151 .ptr = try mod.intern(.{ .ptr = .{
18324 .ptr = try pt.intern(.{ .ptr = .{
1815218325 .ty = manyptr_ty,
1815318326 .base_addr = .{ .anon_decl = .{
1815418327 .val = new_decl_val,
......@@ -18156,7 +18329,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1815618329 } },
1815718330 .byte_offset = 0,
1815818331 } }),
18159 .len = (try mod.intValue(Type.usize, enum_field_vals.len)).toIntern(),
18332 .len = (try pt.intValue(Type.usize, enum_field_vals.len)).toIntern(),
1816018333 } });
1816118334 };
1816218335
......@@ -18167,7 +18340,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1816718340 block,
1816818341 src,
1816918342 type_info_ty.getNamespaceIndex(mod),
18170 try ip.getOrPutString(gpa, "Enum", .no_embedded_nulls),
18343 try ip.getOrPutString(gpa, pt.tid, "Enum", .no_embedded_nulls),
1817118344 )).?;
1817218345 try sema.ensureDeclAnalyzed(type_enum_ty_decl_index);
1817318346 const type_enum_ty_decl = mod.declPtr(type_enum_ty_decl_index);
......@@ -18184,10 +18357,10 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1818418357 // is_exhaustive: bool,
1818518358 is_exhaustive.toIntern(),
1818618359 };
18187 return Air.internedToRef((try mod.intern(.{ .un = .{
18360 return Air.internedToRef((try pt.intern(.{ .un = .{
1818818361 .ty = type_info_ty.toIntern(),
18189 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Enum))).toIntern(),
18190 .val = try mod.intern(.{ .aggregate = .{
18362 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Enum))).toIntern(),
18363 .val = try pt.intern(.{ .aggregate = .{
1819118364 .ty = type_enum_ty.toIntern(),
1819218365 .storage = .{ .elems = &field_values },
1819318366 } }),
......@@ -18199,7 +18372,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1819918372 block,
1820018373 src,
1820118374 type_info_ty.getNamespaceIndex(mod),
18202 try ip.getOrPutString(gpa, "Union", .no_embedded_nulls),
18375 try ip.getOrPutString(gpa, pt.tid, "Union", .no_embedded_nulls),
1820318376 )).?;
1820418377 try sema.ensureDeclAnalyzed(type_union_ty_decl_index);
1820518378 const type_union_ty_decl = mod.declPtr(type_union_ty_decl_index);
......@@ -18211,14 +18384,14 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1821118384 block,
1821218385 src,
1821318386 type_info_ty.getNamespaceIndex(mod),
18214 try ip.getOrPutString(gpa, "UnionField", .no_embedded_nulls),
18387 try ip.getOrPutString(gpa, pt.tid, "UnionField", .no_embedded_nulls),
1821518388 )).?;
1821618389 try sema.ensureDeclAnalyzed(union_field_ty_decl_index);
1821718390 const union_field_ty_decl = mod.declPtr(union_field_ty_decl_index);
1821818391 break :t union_field_ty_decl.val.toType();
1821918392 };
1822018393
18221 try ty.resolveLayout(mod); // Getting alignment requires type layout
18394 try ty.resolveLayout(pt); // Getting alignment requires type layout
1822218395 const union_obj = mod.typeToUnion(ty).?;
1822318396 const tag_type = union_obj.loadTagType(ip);
1822418397 const layout = union_obj.getLayout(ip);
......@@ -18230,18 +18403,18 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1823018403 const name_val = v: {
1823118404 const field_name = tag_type.names.get(ip)[field_index];
1823218405 const field_name_len = field_name.length(ip);
18233 const new_decl_ty = try mod.arrayType(.{
18406 const new_decl_ty = try pt.arrayType(.{
1823418407 .len = field_name_len,
1823518408 .sentinel = .zero_u8,
1823618409 .child = .u8_type,
1823718410 });
18238 const new_decl_val = try mod.intern(.{ .aggregate = .{
18411 const new_decl_val = try pt.intern(.{ .aggregate = .{
1823918412 .ty = new_decl_ty.toIntern(),
1824018413 .storage = .{ .bytes = field_name.toString() },
1824118414 } });
18242 break :v try mod.intern(.{ .slice = .{
18415 break :v try pt.intern(.{ .slice = .{
1824318416 .ty = .slice_const_u8_sentinel_0_type,
18244 .ptr = try mod.intern(.{ .ptr = .{
18417 .ptr = try pt.intern(.{ .ptr = .{
1824518418 .ty = .manyptr_const_u8_sentinel_0_type,
1824618419 .base_addr = .{ .anon_decl = .{
1824718420 .val = new_decl_val,
......@@ -18249,12 +18422,12 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1824918422 } },
1825018423 .byte_offset = 0,
1825118424 } }),
18252 .len = (try mod.intValue(Type.usize, field_name_len)).toIntern(),
18425 .len = (try pt.intValue(Type.usize, field_name_len)).toIntern(),
1825318426 } });
1825418427 };
1825518428
1825618429 const alignment = switch (layout) {
18257 .auto, .@"extern" => try mod.unionFieldNormalAlignmentAdvanced(union_obj, @intCast(field_index), .sema),
18430 .auto, .@"extern" => try pt.unionFieldNormalAlignmentAdvanced(union_obj, @intCast(field_index), .sema),
1825818431 .@"packed" => .none,
1825918432 };
1826018433
......@@ -18265,24 +18438,24 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1826518438 // type: type,
1826618439 field_ty,
1826718440 // alignment: comptime_int,
18268 (try mod.intValue(Type.comptime_int, alignment.toByteUnits() orelse 0)).toIntern(),
18441 (try pt.intValue(Type.comptime_int, alignment.toByteUnits() orelse 0)).toIntern(),
1826918442 };
18270 field_val.* = try mod.intern(.{ .aggregate = .{
18443 field_val.* = try pt.intern(.{ .aggregate = .{
1827118444 .ty = union_field_ty.toIntern(),
1827218445 .storage = .{ .elems = &union_field_fields },
1827318446 } });
1827418447 }
1827518448
1827618449 const fields_val = v: {
18277 const array_fields_ty = try mod.arrayType(.{
18450 const array_fields_ty = try pt.arrayType(.{
1827818451 .len = union_field_vals.len,
1827918452 .child = union_field_ty.toIntern(),
1828018453 });
18281 const new_decl_val = try mod.intern(.{ .aggregate = .{
18454 const new_decl_val = try pt.intern(.{ .aggregate = .{
1828218455 .ty = array_fields_ty.toIntern(),
1828318456 .storage = .{ .elems = union_field_vals },
1828418457 } });
18285 const slice_ty = (try mod.ptrTypeSema(.{
18458 const slice_ty = (try pt.ptrTypeSema(.{
1828618459 .child = union_field_ty.toIntern(),
1828718460 .flags = .{
1828818461 .size = .Slice,
......@@ -18290,9 +18463,9 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1829018463 },
1829118464 })).toIntern();
1829218465 const manyptr_ty = Type.fromInterned(slice_ty).slicePtrFieldType(mod).toIntern();
18293 break :v try mod.intern(.{ .slice = .{
18466 break :v try pt.intern(.{ .slice = .{
1829418467 .ty = slice_ty,
18295 .ptr = try mod.intern(.{ .ptr = .{
18468 .ptr = try pt.intern(.{ .ptr = .{
1829618469 .ty = manyptr_ty,
1829718470 .base_addr = .{ .anon_decl = .{
1829818471 .orig_ty = manyptr_ty,
......@@ -18300,14 +18473,14 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1830018473 } },
1830118474 .byte_offset = 0,
1830218475 } }),
18303 .len = (try mod.intValue(Type.usize, union_field_vals.len)).toIntern(),
18476 .len = (try pt.intValue(Type.usize, union_field_vals.len)).toIntern(),
1830418477 } });
1830518478 };
1830618479
1830718480 const decls_val = try sema.typeInfoDecls(block, src, type_info_ty, ty.getNamespaceIndex(mod));
1830818481
18309 const enum_tag_ty_val = try mod.intern(.{ .opt = .{
18310 .ty = (try mod.optionalType(.type_type)).toIntern(),
18482 const enum_tag_ty_val = try pt.intern(.{ .opt = .{
18483 .ty = (try pt.optionalType(.type_type)).toIntern(),
1831118484 .val = if (ty.unionTagType(mod)) |tag_ty| tag_ty.toIntern() else .none,
1831218485 } });
1831318486
......@@ -18315,8 +18488,8 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1831518488 const decl_index = (try sema.namespaceLookup(
1831618489 block,
1831718490 src,
18318 (try mod.getBuiltinType("Type")).getNamespaceIndex(mod),
18319 try ip.getOrPutString(gpa, "ContainerLayout", .no_embedded_nulls),
18491 (try pt.getBuiltinType("Type")).getNamespaceIndex(mod),
18492 try ip.getOrPutString(gpa, pt.tid, "ContainerLayout", .no_embedded_nulls),
1832018493 )).?;
1832118494 try sema.ensureDeclAnalyzed(decl_index);
1832218495 const decl = mod.declPtr(decl_index);
......@@ -18325,7 +18498,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1832518498
1832618499 const field_values = .{
1832718500 // layout: ContainerLayout,
18328 (try mod.enumValueFieldIndex(container_layout_ty, @intFromEnum(layout))).toIntern(),
18501 (try pt.enumValueFieldIndex(container_layout_ty, @intFromEnum(layout))).toIntern(),
1832918502
1833018503 // tag_type: ?type,
1833118504 enum_tag_ty_val,
......@@ -18334,10 +18507,10 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1833418507 // decls: []const Declaration,
1833518508 decls_val,
1833618509 };
18337 return Air.internedToRef((try mod.intern(.{ .un = .{
18510 return Air.internedToRef((try pt.intern(.{ .un = .{
1833818511 .ty = type_info_ty.toIntern(),
18339 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Union))).toIntern(),
18340 .val = try mod.intern(.{ .aggregate = .{
18512 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Union))).toIntern(),
18513 .val = try pt.intern(.{ .aggregate = .{
1834118514 .ty = type_union_ty.toIntern(),
1834218515 .storage = .{ .elems = &field_values },
1834318516 } }),
......@@ -18349,7 +18522,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1834918522 block,
1835018523 src,
1835118524 type_info_ty.getNamespaceIndex(mod),
18352 try ip.getOrPutString(gpa, "Struct", .no_embedded_nulls),
18525 try ip.getOrPutString(gpa, pt.tid, "Struct", .no_embedded_nulls),
1835318526 )).?;
1835418527 try sema.ensureDeclAnalyzed(type_struct_ty_decl_index);
1835518528 const type_struct_ty_decl = mod.declPtr(type_struct_ty_decl_index);
......@@ -18361,14 +18534,14 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1836118534 block,
1836218535 src,
1836318536 type_info_ty.getNamespaceIndex(mod),
18364 try ip.getOrPutString(gpa, "StructField", .no_embedded_nulls),
18537 try ip.getOrPutString(gpa, pt.tid, "StructField", .no_embedded_nulls),
1836518538 )).?;
1836618539 try sema.ensureDeclAnalyzed(struct_field_ty_decl_index);
1836718540 const struct_field_ty_decl = mod.declPtr(struct_field_ty_decl_index);
1836818541 break :t struct_field_ty_decl.val.toType();
1836918542 };
1837018543
18371 try ty.resolveLayout(mod); // Getting alignment requires type layout
18544 try ty.resolveLayout(pt); // Getting alignment requires type layout
1837218545
1837318546 var struct_field_vals: []InternPool.Index = &.{};
1837418547 defer gpa.free(struct_field_vals);
......@@ -18383,20 +18556,20 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1838318556 const field_name = if (anon_struct_type.names.len != 0)
1838418557 anon_struct_type.names.get(ip)[field_index]
1838518558 else
18386 try ip.getOrPutStringFmt(gpa, "{d}", .{field_index}, .no_embedded_nulls);
18559 try ip.getOrPutStringFmt(gpa, pt.tid, "{d}", .{field_index}, .no_embedded_nulls);
1838718560 const field_name_len = field_name.length(ip);
18388 const new_decl_ty = try mod.arrayType(.{
18561 const new_decl_ty = try pt.arrayType(.{
1838918562 .len = field_name_len,
1839018563 .sentinel = .zero_u8,
1839118564 .child = .u8_type,
1839218565 });
18393 const new_decl_val = try mod.intern(.{ .aggregate = .{
18566 const new_decl_val = try pt.intern(.{ .aggregate = .{
1839418567 .ty = new_decl_ty.toIntern(),
1839518568 .storage = .{ .bytes = field_name.toString() },
1839618569 } });
18397 break :v try mod.intern(.{ .slice = .{
18570 break :v try pt.intern(.{ .slice = .{
1839818571 .ty = .slice_const_u8_sentinel_0_type,
18399 .ptr = try mod.intern(.{ .ptr = .{
18572 .ptr = try pt.intern(.{ .ptr = .{
1840018573 .ty = .manyptr_const_u8_sentinel_0_type,
1840118574 .base_addr = .{ .anon_decl = .{
1840218575 .val = new_decl_val,
......@@ -18404,11 +18577,11 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1840418577 } },
1840518578 .byte_offset = 0,
1840618579 } }),
18407 .len = (try mod.intValue(Type.usize, field_name_len)).toIntern(),
18580 .len = (try pt.intValue(Type.usize, field_name_len)).toIntern(),
1840818581 } });
1840918582 };
1841018583
18411 try Type.fromInterned(field_ty).resolveLayout(mod);
18584 try Type.fromInterned(field_ty).resolveLayout(pt);
1841218585
1841318586 const is_comptime = field_val != .none;
1841418587 const opt_default_val = if (is_comptime) Value.fromInterned(field_val) else null;
......@@ -18423,9 +18596,9 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1842318596 // is_comptime: bool,
1842418597 Value.makeBool(is_comptime).toIntern(),
1842518598 // alignment: comptime_int,
18426 (try mod.intValue(Type.comptime_int, Type.fromInterned(field_ty).abiAlignment(mod).toByteUnits() orelse 0)).toIntern(),
18599 (try pt.intValue(Type.comptime_int, Type.fromInterned(field_ty).abiAlignment(pt).toByteUnits() orelse 0)).toIntern(),
1842718600 };
18428 struct_field_val.* = try mod.intern(.{ .aggregate = .{
18601 struct_field_val.* = try pt.intern(.{ .aggregate = .{
1842918602 .ty = struct_field_ty.toIntern(),
1843018603 .storage = .{ .elems = &struct_field_fields },
1843118604 } });
......@@ -18437,30 +18610,30 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1843718610 };
1843818611 struct_field_vals = try gpa.alloc(InternPool.Index, struct_type.field_types.len);
1843918612
18440 try ty.resolveStructFieldInits(mod);
18613 try ty.resolveStructFieldInits(pt);
1844118614
1844218615 for (struct_field_vals, 0..) |*field_val, field_index| {
1844318616 const field_name = if (struct_type.fieldName(ip, field_index).unwrap()) |field_name|
1844418617 field_name
1844518618 else
18446 try ip.getOrPutStringFmt(gpa, "{d}", .{field_index}, .no_embedded_nulls);
18619 try ip.getOrPutStringFmt(gpa, pt.tid, "{d}", .{field_index}, .no_embedded_nulls);
1844718620 const field_name_len = field_name.length(ip);
1844818621 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
1844918622 const field_init = struct_type.fieldInit(ip, field_index);
1845018623 const field_is_comptime = struct_type.fieldIsComptime(ip, field_index);
1845118624 const name_val = v: {
18452 const new_decl_ty = try mod.arrayType(.{
18625 const new_decl_ty = try pt.arrayType(.{
1845318626 .len = field_name_len,
1845418627 .sentinel = .zero_u8,
1845518628 .child = .u8_type,
1845618629 });
18457 const new_decl_val = try mod.intern(.{ .aggregate = .{
18630 const new_decl_val = try pt.intern(.{ .aggregate = .{
1845818631 .ty = new_decl_ty.toIntern(),
1845918632 .storage = .{ .bytes = field_name.toString() },
1846018633 } });
18461 break :v try mod.intern(.{ .slice = .{
18634 break :v try pt.intern(.{ .slice = .{
1846218635 .ty = .slice_const_u8_sentinel_0_type,
18463 .ptr = try mod.intern(.{ .ptr = .{
18636 .ptr = try pt.intern(.{ .ptr = .{
1846418637 .ty = .manyptr_const_u8_sentinel_0_type,
1846518638 .base_addr = .{ .anon_decl = .{
1846618639 .val = new_decl_val,
......@@ -18468,7 +18641,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1846818641 } },
1846918642 .byte_offset = 0,
1847018643 } }),
18471 .len = (try mod.intValue(Type.usize, field_name_len)).toIntern(),
18644 .len = (try pt.intValue(Type.usize, field_name_len)).toIntern(),
1847218645 } });
1847318646 };
1847418647
......@@ -18476,7 +18649,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1847618649 const default_val_ptr = try sema.optRefValue(opt_default_val);
1847718650 const alignment = switch (struct_type.layout) {
1847818651 .@"packed" => .none,
18479 else => try mod.structFieldAlignmentAdvanced(
18652 else => try pt.structFieldAlignmentAdvanced(
1848018653 struct_type.fieldAlign(ip, field_index),
1848118654 field_ty,
1848218655 struct_type.layout,
......@@ -18494,9 +18667,9 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1849418667 // is_comptime: bool,
1849518668 Value.makeBool(field_is_comptime).toIntern(),
1849618669 // alignment: comptime_int,
18497 (try mod.intValue(Type.comptime_int, alignment.toByteUnits() orelse 0)).toIntern(),
18670 (try pt.intValue(Type.comptime_int, alignment.toByteUnits() orelse 0)).toIntern(),
1849818671 };
18499 field_val.* = try mod.intern(.{ .aggregate = .{
18672 field_val.* = try pt.intern(.{ .aggregate = .{
1850018673 .ty = struct_field_ty.toIntern(),
1850118674 .storage = .{ .elems = &struct_field_fields },
1850218675 } });
......@@ -18504,15 +18677,15 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1850418677 }
1850518678
1850618679 const fields_val = v: {
18507 const array_fields_ty = try mod.arrayType(.{
18680 const array_fields_ty = try pt.arrayType(.{
1850818681 .len = struct_field_vals.len,
1850918682 .child = struct_field_ty.toIntern(),
1851018683 });
18511 const new_decl_val = try mod.intern(.{ .aggregate = .{
18684 const new_decl_val = try pt.intern(.{ .aggregate = .{
1851218685 .ty = array_fields_ty.toIntern(),
1851318686 .storage = .{ .elems = struct_field_vals },
1851418687 } });
18515 const slice_ty = (try mod.ptrTypeSema(.{
18688 const slice_ty = (try pt.ptrTypeSema(.{
1851618689 .child = struct_field_ty.toIntern(),
1851718690 .flags = .{
1851818691 .size = .Slice,
......@@ -18520,9 +18693,9 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1852018693 },
1852118694 })).toIntern();
1852218695 const manyptr_ty = Type.fromInterned(slice_ty).slicePtrFieldType(mod).toIntern();
18523 break :v try mod.intern(.{ .slice = .{
18696 break :v try pt.intern(.{ .slice = .{
1852418697 .ty = slice_ty,
18525 .ptr = try mod.intern(.{ .ptr = .{
18698 .ptr = try pt.intern(.{ .ptr = .{
1852618699 .ty = manyptr_ty,
1852718700 .base_addr = .{ .anon_decl = .{
1852818701 .orig_ty = manyptr_ty,
......@@ -18530,14 +18703,14 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1853018703 } },
1853118704 .byte_offset = 0,
1853218705 } }),
18533 .len = (try mod.intValue(Type.usize, struct_field_vals.len)).toIntern(),
18706 .len = (try pt.intValue(Type.usize, struct_field_vals.len)).toIntern(),
1853418707 } });
1853518708 };
1853618709
1853718710 const decls_val = try sema.typeInfoDecls(block, src, type_info_ty, ty.getNamespaceIndex(mod));
1853818711
18539 const backing_integer_val = try mod.intern(.{ .opt = .{
18540 .ty = (try mod.optionalType(.type_type)).toIntern(),
18712 const backing_integer_val = try pt.intern(.{ .opt = .{
18713 .ty = (try pt.optionalType(.type_type)).toIntern(),
1854118714 .val = if (mod.typeToPackedStruct(ty)) |packed_struct| val: {
1854218715 assert(Type.fromInterned(packed_struct.backingIntType(ip).*).isInt(mod));
1854318716 break :val packed_struct.backingIntType(ip).*;
......@@ -18548,8 +18721,8 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1854818721 const decl_index = (try sema.namespaceLookup(
1854918722 block,
1855018723 src,
18551 (try mod.getBuiltinType("Type")).getNamespaceIndex(mod),
18552 try ip.getOrPutString(gpa, "ContainerLayout", .no_embedded_nulls),
18724 (try pt.getBuiltinType("Type")).getNamespaceIndex(mod),
18725 try ip.getOrPutString(gpa, pt.tid, "ContainerLayout", .no_embedded_nulls),
1855318726 )).?;
1855418727 try sema.ensureDeclAnalyzed(decl_index);
1855518728 const decl = mod.declPtr(decl_index);
......@@ -18560,7 +18733,7 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1856018733
1856118734 const field_values = [_]InternPool.Index{
1856218735 // layout: ContainerLayout,
18563 (try mod.enumValueFieldIndex(container_layout_ty, @intFromEnum(layout))).toIntern(),
18736 (try pt.enumValueFieldIndex(container_layout_ty, @intFromEnum(layout))).toIntern(),
1856418737 // backing_integer: ?type,
1856518738 backing_integer_val,
1856618739 // fields: []const StructField,
......@@ -18570,10 +18743,10 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1857018743 // is_tuple: bool,
1857118744 Value.makeBool(ty.isTuple(mod)).toIntern(),
1857218745 };
18573 return Air.internedToRef((try mod.intern(.{ .un = .{
18746 return Air.internedToRef((try pt.intern(.{ .un = .{
1857418747 .ty = type_info_ty.toIntern(),
18575 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Struct))).toIntern(),
18576 .val = try mod.intern(.{ .aggregate = .{
18748 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Struct))).toIntern(),
18749 .val = try pt.intern(.{ .aggregate = .{
1857718750 .ty = type_struct_ty.toIntern(),
1857818751 .storage = .{ .elems = &field_values },
1857918752 } }),
......@@ -18585,24 +18758,24 @@ fn zirTypeInfo(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
1858518758 block,
1858618759 src,
1858718760 type_info_ty.getNamespaceIndex(mod),
18588 try ip.getOrPutString(gpa, "Opaque", .no_embedded_nulls),
18761 try ip.getOrPutString(gpa, pt.tid, "Opaque", .no_embedded_nulls),
1858918762 )).?;
1859018763 try sema.ensureDeclAnalyzed(type_opaque_ty_decl_index);
1859118764 const type_opaque_ty_decl = mod.declPtr(type_opaque_ty_decl_index);
1859218765 break :t type_opaque_ty_decl.val.toType();
1859318766 };
1859418767
18595 try ty.resolveFields(mod);
18768 try ty.resolveFields(pt);
1859618769 const decls_val = try sema.typeInfoDecls(block, src, type_info_ty, ty.getNamespaceIndex(mod));
1859718770
1859818771 const field_values = .{
1859918772 // decls: []const Declaration,
1860018773 decls_val,
1860118774 };
18602 return Air.internedToRef((try mod.intern(.{ .un = .{
18775 return Air.internedToRef((try pt.intern(.{ .un = .{
1860318776 .ty = type_info_ty.toIntern(),
18604 .tag = (try mod.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Opaque))).toIntern(),
18605 .val = try mod.intern(.{ .aggregate = .{
18777 .tag = (try pt.enumValueFieldIndex(type_info_tag_ty, @intFromEnum(std.builtin.TypeId.Opaque))).toIntern(),
18778 .val = try pt.intern(.{ .aggregate = .{
1860618779 .ty = type_opaque_ty.toIntern(),
1860718780 .storage = .{ .elems = &field_values },
1860818781 } }),
......@@ -18620,7 +18793,8 @@ fn typeInfoDecls(
1862018793 type_info_ty: Type,
1862118794 opt_namespace: InternPool.OptionalNamespaceIndex,
1862218795) CompileError!InternPool.Index {
18623 const mod = sema.mod;
18796 const pt = sema.pt;
18797 const mod = pt.zcu;
1862418798 const gpa = sema.gpa;
1862518799
1862618800 const declaration_ty = t: {
......@@ -18628,7 +18802,7 @@ fn typeInfoDecls(
1862818802 block,
1862918803 src,
1863018804 type_info_ty.getNamespaceIndex(mod),
18631 try mod.intern_pool.getOrPutString(gpa, "Declaration", .no_embedded_nulls),
18805 try mod.intern_pool.getOrPutString(gpa, pt.tid, "Declaration", .no_embedded_nulls),
1863218806 )).?;
1863318807 try sema.ensureDeclAnalyzed(declaration_ty_decl_index);
1863418808 const declaration_ty_decl = mod.declPtr(declaration_ty_decl_index);
......@@ -18643,15 +18817,15 @@ fn typeInfoDecls(
1864318817
1864418818 try sema.typeInfoNamespaceDecls(block, opt_namespace, declaration_ty, &decl_vals, &seen_namespaces);
1864518819
18646 const array_decl_ty = try mod.arrayType(.{
18820 const array_decl_ty = try pt.arrayType(.{
1864718821 .len = decl_vals.items.len,
1864818822 .child = declaration_ty.toIntern(),
1864918823 });
18650 const new_decl_val = try mod.intern(.{ .aggregate = .{
18824 const new_decl_val = try pt.intern(.{ .aggregate = .{
1865118825 .ty = array_decl_ty.toIntern(),
1865218826 .storage = .{ .elems = decl_vals.items },
1865318827 } });
18654 const slice_ty = (try mod.ptrTypeSema(.{
18828 const slice_ty = (try pt.ptrTypeSema(.{
1865518829 .child = declaration_ty.toIntern(),
1865618830 .flags = .{
1865718831 .size = .Slice,
......@@ -18659,9 +18833,9 @@ fn typeInfoDecls(
1865918833 },
1866018834 })).toIntern();
1866118835 const manyptr_ty = Type.fromInterned(slice_ty).slicePtrFieldType(mod).toIntern();
18662 return try mod.intern(.{ .slice = .{
18836 return try pt.intern(.{ .slice = .{
1866318837 .ty = slice_ty,
18664 .ptr = try mod.intern(.{ .ptr = .{
18838 .ptr = try pt.intern(.{ .ptr = .{
1866518839 .ty = manyptr_ty,
1866618840 .base_addr = .{ .anon_decl = .{
1866718841 .orig_ty = manyptr_ty,
......@@ -18669,7 +18843,7 @@ fn typeInfoDecls(
1866918843 } },
1867018844 .byte_offset = 0,
1867118845 } }),
18672 .len = (try mod.intValue(Type.usize, decl_vals.items.len)).toIntern(),
18846 .len = (try pt.intValue(Type.usize, decl_vals.items.len)).toIntern(),
1867318847 } });
1867418848}
1867518849
......@@ -18681,7 +18855,8 @@ fn typeInfoNamespaceDecls(
1868118855 decl_vals: *std.ArrayList(InternPool.Index),
1868218856 seen_namespaces: *std.AutoHashMap(*Namespace, void),
1868318857) !void {
18684 const mod = sema.mod;
18858 const pt = sema.pt;
18859 const mod = pt.zcu;
1868518860 const ip = &mod.intern_pool;
1868618861
1868718862 const namespace_index = opt_namespace_index.unwrap() orelse return;
......@@ -18703,18 +18878,18 @@ fn typeInfoNamespaceDecls(
1870318878 if (decl.kind != .named) continue;
1870418879 const name_val = v: {
1870518880 const decl_name_len = decl.name.length(ip);
18706 const new_decl_ty = try mod.arrayType(.{
18881 const new_decl_ty = try pt.arrayType(.{
1870718882 .len = decl_name_len,
1870818883 .sentinel = .zero_u8,
1870918884 .child = .u8_type,
1871018885 });
18711 const new_decl_val = try mod.intern(.{ .aggregate = .{
18886 const new_decl_val = try pt.intern(.{ .aggregate = .{
1871218887 .ty = new_decl_ty.toIntern(),
1871318888 .storage = .{ .bytes = decl.name.toString() },
1871418889 } });
18715 break :v try mod.intern(.{ .slice = .{
18890 break :v try pt.intern(.{ .slice = .{
1871618891 .ty = .slice_const_u8_sentinel_0_type,
18717 .ptr = try mod.intern(.{ .ptr = .{
18892 .ptr = try pt.intern(.{ .ptr = .{
1871818893 .ty = .manyptr_const_u8_sentinel_0_type,
1871918894 .base_addr = .{ .anon_decl = .{
1872018895 .orig_ty = .slice_const_u8_sentinel_0_type,
......@@ -18722,7 +18897,7 @@ fn typeInfoNamespaceDecls(
1872218897 } },
1872318898 .byte_offset = 0,
1872418899 } }),
18725 .len = (try mod.intValue(Type.usize, decl_name_len)).toIntern(),
18900 .len = (try pt.intValue(Type.usize, decl_name_len)).toIntern(),
1872618901 } });
1872718902 };
1872818903
......@@ -18730,7 +18905,7 @@ fn typeInfoNamespaceDecls(
1873018905 //name: [:0]const u8,
1873118906 name_val,
1873218907 };
18733 try decl_vals.append(try mod.intern(.{ .aggregate = .{
18908 try decl_vals.append(try pt.intern(.{ .aggregate = .{
1873418909 .ty = declaration_ty.toIntern(),
1873518910 .storage = .{ .elems = &fields },
1873618911 } }));
......@@ -18782,11 +18957,12 @@ fn zirTypeofLog2IntType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Compil
1878218957}
1878318958
1878418959fn log2IntType(sema: *Sema, block: *Block, operand: Type, src: LazySrcLoc) CompileError!Type {
18785 const mod = sema.mod;
18960 const pt = sema.pt;
18961 const mod = pt.zcu;
1878618962 switch (operand.zigTypeTag(mod)) {
1878718963 .ComptimeInt => return Type.comptime_int,
1878818964 .Int => {
18789 const bits = operand.bitSize(mod);
18965 const bits = operand.bitSize(pt);
1879018966 const count = if (bits == 0)
1879118967 0
1879218968 else blk: {
......@@ -18797,12 +18973,12 @@ fn log2IntType(sema: *Sema, block: *Block, operand: Type, src: LazySrcLoc) Compi
1879718973 }
1879818974 break :blk count;
1879918975 };
18800 return mod.intType(.unsigned, count);
18976 return pt.intType(.unsigned, count);
1880118977 },
1880218978 .Vector => {
1880318979 const elem_ty = operand.elemType2(mod);
1880418980 const log2_elem_ty = try sema.log2IntType(block, elem_ty, src);
18805 return mod.vectorType(.{
18981 return pt.vectorType(.{
1880618982 .len = operand.vectorLen(mod),
1880718983 .child = log2_elem_ty.toIntern(),
1880818984 });
......@@ -18813,7 +18989,7 @@ fn log2IntType(sema: *Sema, block: *Block, operand: Type, src: LazySrcLoc) Compi
1881318989 block,
1881418990 src,
1881518991 "bit shifting operation expected integer type, found '{}'",
18816 .{operand.fmt(mod)},
18992 .{operand.fmt(pt)},
1881718993 );
1881818994}
1881918995
......@@ -18865,7 +19041,8 @@ fn zirBoolNot(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1886519041 const tracy = trace(@src());
1886619042 defer tracy.end();
1886719043
18868 const mod = sema.mod;
19044 const pt = sema.pt;
19045 const mod = pt.zcu;
1886919046 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1887019047 const src = block.nodeOffset(inst_data.src_node);
1887119048 const operand_src = block.src(.{ .node_offset_un_op = inst_data.src_node });
......@@ -18874,7 +19051,7 @@ fn zirBoolNot(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1887419051 const operand = try sema.coerce(block, Type.bool, uncasted_operand, operand_src);
1887519052 if (try sema.resolveValue(operand)) |val| {
1887619053 return if (val.isUndef(mod))
18877 mod.undefRef(Type.bool)
19054 pt.undefRef(Type.bool)
1887819055 else if (val.toBool()) .bool_false else .bool_true;
1887919056 }
1888019057 try sema.requireRuntimeBlock(block, src, null);
......@@ -18890,7 +19067,8 @@ fn zirBoolBr(
1889019067 const tracy = trace(@src());
1889119068 defer tracy.end();
1889219069
18893 const mod = sema.mod;
19070 const pt = sema.pt;
19071 const mod = pt.zcu;
1889419072 const gpa = sema.gpa;
1889519073
1889619074 const datas = sema.code.instructions.items(.data);
......@@ -19006,7 +19184,8 @@ fn finishCondBr(
1900619184}
1900719185
1900819186fn checkNullableType(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) !void {
19009 const mod = sema.mod;
19187 const pt = sema.pt;
19188 const mod = pt.zcu;
1901019189 switch (ty.zigTypeTag(mod)) {
1901119190 .Optional, .Null, .Undefined => return,
1901219191 .Pointer => if (ty.isPtrLikeOptional(mod)) return,
......@@ -19038,7 +19217,8 @@ fn zirIsNonNullPtr(
1903819217 const tracy = trace(@src());
1903919218 defer tracy.end();
1904019219
19041 const mod = sema.mod;
19220 const pt = sema.pt;
19221 const mod = pt.zcu;
1904219222 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1904319223 const src = block.nodeOffset(inst_data.src_node);
1904419224 const ptr = try sema.resolveInst(inst_data.operand);
......@@ -19051,11 +19231,12 @@ fn zirIsNonNullPtr(
1905119231}
1905219232
1905319233fn checkErrorType(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) !void {
19054 const mod = sema.mod;
19234 const pt = sema.pt;
19235 const mod = pt.zcu;
1905519236 switch (ty.zigTypeTag(mod)) {
1905619237 .ErrorSet, .ErrorUnion, .Undefined => return,
1905719238 else => return sema.fail(block, src, "expected error union type, found '{}'", .{
19058 ty.fmt(mod),
19239 ty.fmt(pt),
1905919240 }),
1906019241 }
1906119242}
......@@ -19075,7 +19256,8 @@ fn zirIsNonErrPtr(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
1907519256 const tracy = trace(@src());
1907619257 defer tracy.end();
1907719258
19078 const mod = sema.mod;
19259 const pt = sema.pt;
19260 const mod = pt.zcu;
1907919261 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1908019262 const src = block.nodeOffset(inst_data.src_node);
1908119263 const ptr = try sema.resolveInst(inst_data.operand);
......@@ -19102,7 +19284,8 @@ fn zirCondbr(
1910219284 const tracy = trace(@src());
1910319285 defer tracy.end();
1910419286
19105 const mod = sema.mod;
19287 const pt = sema.pt;
19288 const mod = pt.zcu;
1910619289 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1910719290 const cond_src = parent_block.src(.{ .node_offset_if_cond = inst_data.src_node });
1910819291 const extra = sema.code.extraData(Zir.Inst.CondBr, inst_data.payload_index);
......@@ -19177,10 +19360,11 @@ fn zirTry(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileError!
1917719360 const body = sema.code.bodySlice(extra.end, extra.data.body_len);
1917819361 const err_union = try sema.resolveInst(extra.data.operand);
1917919362 const err_union_ty = sema.typeOf(err_union);
19180 const mod = sema.mod;
19363 const pt = sema.pt;
19364 const mod = pt.zcu;
1918119365 if (err_union_ty.zigTypeTag(mod) != .ErrorUnion) {
1918219366 return sema.fail(parent_block, operand_src, "expected error union type, found '{}'", .{
19183 err_union_ty.fmt(mod),
19367 err_union_ty.fmt(pt),
1918419368 });
1918519369 }
1918619370 const is_non_err = try sema.analyzeIsNonErrComptimeOnly(parent_block, operand_src, err_union);
......@@ -19225,10 +19409,11 @@ fn zirTryPtr(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileErr
1922519409 const operand = try sema.resolveInst(extra.data.operand);
1922619410 const err_union = try sema.analyzeLoad(parent_block, src, operand, operand_src);
1922719411 const err_union_ty = sema.typeOf(err_union);
19228 const mod = sema.mod;
19412 const pt = sema.pt;
19413 const mod = pt.zcu;
1922919414 if (err_union_ty.zigTypeTag(mod) != .ErrorUnion) {
1923019415 return sema.fail(parent_block, operand_src, "expected error union type, found '{}'", .{
19231 err_union_ty.fmt(mod),
19416 err_union_ty.fmt(pt),
1923219417 });
1923319418 }
1923419419 const is_non_err = try sema.analyzeIsNonErrComptimeOnly(parent_block, operand_src, err_union);
......@@ -19251,7 +19436,7 @@ fn zirTryPtr(sema: *Sema, parent_block: *Block, inst: Zir.Inst.Index) CompileErr
1925119436
1925219437 const operand_ty = sema.typeOf(operand);
1925319438 const ptr_info = operand_ty.ptrInfo(mod);
19254 const res_ty = try mod.ptrTypeSema(.{
19439 const res_ty = try pt.ptrTypeSema(.{
1925519440 .child = err_union_ty.errorUnionPayload(mod).toIntern(),
1925619441 .flags = .{
1925719442 .is_const = ptr_info.flags.is_const,
......@@ -19366,18 +19551,20 @@ fn zirRetErrValue(
1936619551 block: *Block,
1936719552 inst: Zir.Inst.Index,
1936819553) CompileError!void {
19369 const mod = sema.mod;
19554 const pt = sema.pt;
19555 const mod = pt.zcu;
1937019556 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].str_tok;
1937119557 const src = block.tokenOffset(inst_data.src_tok);
1937219558 const err_name = try mod.intern_pool.getOrPutString(
1937319559 sema.gpa,
19560 pt.tid,
1937419561 inst_data.get(sema.code),
1937519562 .no_embedded_nulls,
1937619563 );
1937719564 _ = try mod.getErrorValue(err_name);
1937819565 // Return the error code from the function.
19379 const error_set_type = try mod.singleErrorSetType(err_name);
19380 const result_inst = Air.internedToRef((try mod.intern(.{ .err = .{
19566 const error_set_type = try pt.singleErrorSetType(err_name);
19567 const result_inst = Air.internedToRef((try pt.intern(.{ .err = .{
1938119568 .ty = error_set_type.toIntern(),
1938219569 .name = err_name,
1938319570 } })));
......@@ -19392,7 +19579,8 @@ fn zirRetImplicit(
1939219579 const tracy = trace(@src());
1939319580 defer tracy.end();
1939419581
19395 const mod = sema.mod;
19582 const pt = sema.pt;
19583 const mod = pt.zcu;
1939619584 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_tok;
1939719585 const r_brace_src = block.tokenOffset(inst_data.src_tok);
1939819586 if (block.inlining == null and sema.func_is_naked) {
......@@ -19412,7 +19600,7 @@ fn zirRetImplicit(
1941219600 if (base_tag == .NoReturn) {
1941319601 const msg = msg: {
1941419602 const msg = try sema.errMsg(ret_ty_src, "function declared '{}' implicitly returns", .{
19415 sema.fn_ret_ty.fmt(mod),
19603 sema.fn_ret_ty.fmt(pt),
1941619604 });
1941719605 errdefer msg.destroy(sema.gpa);
1941819606 try sema.errNote(r_brace_src, msg, "control flow reaches end of body here", .{});
......@@ -19422,7 +19610,7 @@ fn zirRetImplicit(
1942219610 } else if (base_tag != .Void) {
1942319611 const msg = msg: {
1942419612 const msg = try sema.errMsg(ret_ty_src, "function with non-void return type '{}' implicitly returns", .{
19425 sema.fn_ret_ty.fmt(mod),
19613 sema.fn_ret_ty.fmt(pt),
1942619614 });
1942719615 errdefer msg.destroy(sema.gpa);
1942819616 try sema.errNote(r_brace_src, msg, "control flow reaches end of body here", .{});
......@@ -19474,7 +19662,7 @@ fn retWithErrTracing(
1947419662 ret_tag: Air.Inst.Tag,
1947519663 operand: Air.Inst.Ref,
1947619664) CompileError!void {
19477 const mod = sema.mod;
19665 const pt = sema.pt;
1947819666 const need_check = switch (is_non_err) {
1947919667 .bool_true => {
1948019668 _ = try block.addUnOp(ret_tag, operand);
......@@ -19484,11 +19672,11 @@ fn retWithErrTracing(
1948419672 else => true,
1948519673 };
1948619674 const gpa = sema.gpa;
19487 const stack_trace_ty = try mod.getBuiltinType("StackTrace");
19488 try stack_trace_ty.resolveFields(mod);
19489 const ptr_stack_trace_ty = try mod.singleMutPtrType(stack_trace_ty);
19675 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
19676 try stack_trace_ty.resolveFields(pt);
19677 const ptr_stack_trace_ty = try pt.singleMutPtrType(stack_trace_ty);
1949019678 const err_return_trace = try block.addTy(.err_return_trace, ptr_stack_trace_ty);
19491 const return_err_fn = try mod.getBuiltin("returnError");
19679 const return_err_fn = try pt.getBuiltin("returnError");
1949219680 const args: [1]Air.Inst.Ref = .{err_return_trace};
1949319681
1949419682 if (!need_check) {
......@@ -19524,12 +19712,14 @@ fn retWithErrTracing(
1952419712}
1952519713
1952619714fn wantErrorReturnTracing(sema: *Sema, fn_ret_ty: Type) bool {
19527 const mod = sema.mod;
19715 const pt = sema.pt;
19716 const mod = pt.zcu;
1952819717 return fn_ret_ty.isError(mod) and mod.comp.config.any_error_tracing;
1952919718}
1953019719
1953119720fn zirSaveErrRetIndex(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
19532 const mod = sema.mod;
19721 const pt = sema.pt;
19722 const mod = pt.zcu;
1953319723 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].save_err_ret_index;
1953419724
1953519725 if (!block.ownerModule().error_tracing) return;
......@@ -19559,7 +19749,8 @@ fn restoreErrRetIndex(sema: *Sema, start_block: *Block, src: LazySrcLoc, target_
1955919749 const tracy = trace(@src());
1956019750 defer tracy.end();
1956119751
19562 const mod = sema.mod;
19752 const pt = sema.pt;
19753 const mod = pt.zcu;
1956319754
1956419755 const saved_index = if (target_block.toIndexAllowNone()) |zir_block| b: {
1956519756 var block = start_block;
......@@ -19597,7 +19788,7 @@ fn restoreErrRetIndex(sema: *Sema, start_block: *Block, src: LazySrcLoc, target_
1959719788 if (is_non_error) return;
1959819789
1959919790 const saved_index_val = try sema.resolveDefinedValue(start_block, src, saved_index);
19600 const saved_index_int = saved_index_val.?.toUnsignedInt(mod);
19791 const saved_index_int = saved_index_val.?.toUnsignedInt(pt);
1960119792 assert(saved_index_int <= sema.comptime_err_ret_trace.items.len);
1960219793 sema.comptime_err_ret_trace.items.len = @intCast(saved_index_int);
1960319794 return;
......@@ -19612,7 +19803,8 @@ fn restoreErrRetIndex(sema: *Sema, start_block: *Block, src: LazySrcLoc, target_
1961219803}
1961319804
1961419805fn addToInferredErrorSet(sema: *Sema, uncasted_operand: Air.Inst.Ref) !void {
19615 const mod = sema.mod;
19806 const pt = sema.pt;
19807 const mod = pt.zcu;
1961619808 const ip = &mod.intern_pool;
1961719809 assert(sema.fn_ret_ty.zigTypeTag(mod) == .ErrorUnion);
1961819810 const err_set_ty = sema.fn_ret_ty.errorUnionSet(mod).toIntern();
......@@ -19632,7 +19824,8 @@ fn addToInferredErrorSet(sema: *Sema, uncasted_operand: Air.Inst.Ref) !void {
1963219824
1963319825fn addToInferredErrorSetPtr(sema: *Sema, ies: *InferredErrorSet, op_ty: Type) !void {
1963419826 const arena = sema.arena;
19635 const mod = sema.mod;
19827 const pt = sema.pt;
19828 const mod = pt.zcu;
1963619829 const ip = &mod.intern_pool;
1963719830 switch (op_ty.zigTypeTag(mod)) {
1963819831 .ErrorSet => try ies.addErrorSet(op_ty, ip, arena),
......@@ -19651,7 +19844,8 @@ fn analyzeRet(
1965119844 // Special case for returning an error to an inferred error set; we need to
1965219845 // add the error tag to the inferred error set of the in-scope function, so
1965319846 // that the coercion below works correctly.
19654 const mod = sema.mod;
19847 const pt = sema.pt;
19848 const mod = pt.zcu;
1965519849 if (sema.fn_ret_ty_ies != null and sema.fn_ret_ty.zigTypeTag(mod) == .ErrorUnion) {
1965619850 try sema.addToInferredErrorSet(uncasted_operand);
1965719851 }
......@@ -19691,7 +19885,7 @@ fn analyzeRet(
1969119885 return sema.failWithOwnedErrorMsg(block, msg);
1969219886 }
1969319887
19694 try sema.fn_ret_ty.resolveLayout(mod);
19888 try sema.fn_ret_ty.resolveLayout(pt);
1969519889
1969619890 try sema.validateRuntimeValue(block, operand_src, operand);
1969719891
......@@ -19718,7 +19912,8 @@ fn zirPtrType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1971819912 const tracy = trace(@src());
1971919913 defer tracy.end();
1972019914
19721 const mod = sema.mod;
19915 const pt = sema.pt;
19916 const mod = pt.zcu;
1972219917 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].ptr_type;
1972319918 const extra = sema.code.extraData(Zir.Inst.PtrType, inst_data.payload_index);
1972419919 const elem_ty_src = block.src(.{ .node_offset_ptr_elem = extra.data.src_node });
......@@ -19773,7 +19968,7 @@ fn zirPtrType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1977319968 },
1977419969 else => {},
1977519970 }
19776 const align_bytes = (try val.getUnsignedIntAdvanced(mod, .sema)).?;
19971 const align_bytes = (try val.getUnsignedIntAdvanced(pt, .sema)).?;
1977719972 break :blk try sema.validateAlignAllowZero(block, align_src, align_bytes);
1977819973 } else .none;
1977919974
......@@ -19804,13 +19999,13 @@ fn zirPtrType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1980419999 if (host_size != 0) {
1980520000 if (bit_offset >= host_size * 8) {
1980620001 return sema.fail(block, bitoffset_src, "packed type '{}' at bit offset {} starts {} bits after the end of a {} byte host integer", .{
19807 elem_ty.fmt(mod), bit_offset, bit_offset - host_size * 8, host_size,
20002 elem_ty.fmt(pt), bit_offset, bit_offset - host_size * 8, host_size,
1980820003 });
1980920004 }
19810 const elem_bit_size = try elem_ty.bitSizeAdvanced(mod, .sema);
20005 const elem_bit_size = try elem_ty.bitSizeAdvanced(pt, .sema);
1981120006 if (elem_bit_size > host_size * 8 - bit_offset) {
1981220007 return sema.fail(block, bitoffset_src, "packed type '{}' at bit offset {} ends {} bits after the end of a {} byte host integer", .{
19813 elem_ty.fmt(mod), bit_offset, elem_bit_size - (host_size * 8 - bit_offset), host_size,
20008 elem_ty.fmt(pt), bit_offset, elem_bit_size - (host_size * 8 - bit_offset), host_size,
1981420009 });
1981520010 }
1981620011 }
......@@ -19824,7 +20019,7 @@ fn zirPtrType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1982420019 } else if (inst_data.size == .C) {
1982520020 if (!try sema.validateExternType(elem_ty, .other)) {
1982620021 const msg = msg: {
19827 const msg = try sema.errMsg(elem_ty_src, "C pointers cannot point to non-C-ABI-compatible type '{}'", .{elem_ty.fmt(mod)});
20022 const msg = try sema.errMsg(elem_ty_src, "C pointers cannot point to non-C-ABI-compatible type '{}'", .{elem_ty.fmt(pt)});
1982820023 errdefer msg.destroy(sema.gpa);
1982920024
1983020025 try sema.explainWhyTypeIsNotExtern(msg, elem_ty_src, elem_ty, .other);
......@@ -19841,14 +20036,14 @@ fn zirPtrType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
1984120036
1984220037 if (host_size != 0 and !try sema.validatePackedType(elem_ty)) {
1984320038 return sema.failWithOwnedErrorMsg(block, msg: {
19844 const msg = try sema.errMsg(elem_ty_src, "bit-pointer cannot refer to value of type '{}'", .{elem_ty.fmt(mod)});
20039 const msg = try sema.errMsg(elem_ty_src, "bit-pointer cannot refer to value of type '{}'", .{elem_ty.fmt(pt)});
1984520040 errdefer msg.destroy(sema.gpa);
1984620041 try sema.explainWhyTypeIsNotPacked(msg, elem_ty_src, elem_ty);
1984720042 break :msg msg;
1984820043 });
1984920044 }
1985020045
19851 const ty = try mod.ptrTypeSema(.{
20046 const ty = try pt.ptrTypeSema(.{
1985220047 .child = elem_ty.toIntern(),
1985320048 .sentinel = sentinel,
1985420049 .flags = .{
......@@ -19875,7 +20070,8 @@ fn zirStructInitEmpty(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileE
1987520070 const src = block.nodeOffset(inst_data.src_node);
1987620071 const ty_src = block.src(.{ .node_offset_init_ty = inst_data.src_node });
1987720072 const obj_ty = try sema.resolveType(block, ty_src, inst_data.operand);
19878 const mod = sema.mod;
20073 const pt = sema.pt;
20074 const mod = pt.zcu;
1987920075
1988020076 switch (obj_ty.zigTypeTag(mod)) {
1988120077 .Struct => return sema.structInitEmpty(block, obj_ty, src, src),
......@@ -19890,7 +20086,8 @@ fn zirStructInitEmptyResult(sema: *Sema, block: *Block, inst: Zir.Inst.Index, is
1989020086 const tracy = trace(@src());
1989120087 defer tracy.end();
1989220088
19893 const mod = sema.mod;
20089 const pt = sema.pt;
20090 const mod = pt.zcu;
1989420091 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
1989520092 const src = block.nodeOffset(inst_data.src_node);
1989620093 const ty_operand = sema.resolveType(block, src, inst_data.operand) catch |err| switch (err) {
......@@ -19905,7 +20102,7 @@ fn zirStructInitEmptyResult(sema: *Sema, block: *Block, inst: Zir.Inst.Index, is
1990520102 break :ty ptr_ty.childType(mod);
1990620103 }
1990720104 // To make `&.{}` a `[:s]T`, the init should be a `[0:s]T`.
19908 break :ty try mod.arrayType(.{
20105 break :ty try pt.arrayType(.{
1990920106 .len = 0,
1991020107 .sentinel = if (ptr_ty.sentinel(mod)) |s| s.toIntern() else .none,
1991120108 .child = ptr_ty.childType(mod).toIntern(),
......@@ -19936,10 +20133,11 @@ fn structInitEmpty(
1993620133 dest_src: LazySrcLoc,
1993720134 init_src: LazySrcLoc,
1993820135) CompileError!Air.Inst.Ref {
19939 const mod = sema.mod;
20136 const pt = sema.pt;
20137 const mod = pt.zcu;
1994020138 const gpa = sema.gpa;
1994120139 // This logic must be synchronized with that in `zirStructInit`.
19942 try struct_ty.resolveFields(mod);
20140 try struct_ty.resolveFields(pt);
1994320141
1994420142 // The init values to use for the struct instance.
1994520143 const field_inits = try gpa.alloc(Air.Inst.Ref, struct_ty.structFieldCount(mod));
......@@ -19950,7 +20148,8 @@ fn structInitEmpty(
1995020148}
1995120149
1995220150fn arrayInitEmpty(sema: *Sema, block: *Block, src: LazySrcLoc, obj_ty: Type) CompileError!Air.Inst.Ref {
19953 const mod = sema.mod;
20151 const pt = sema.pt;
20152 const mod = pt.zcu;
1995420153 const arr_len = obj_ty.arrayLen(mod);
1995520154 if (arr_len != 0) {
1995620155 if (obj_ty.zigTypeTag(mod) == .Array) {
......@@ -19959,21 +20158,22 @@ fn arrayInitEmpty(sema: *Sema, block: *Block, src: LazySrcLoc, obj_ty: Type) Com
1995920158 return sema.fail(block, src, "expected {d} vector elements; found 0", .{arr_len});
1996020159 }
1996120160 }
19962 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
20161 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
1996320162 .ty = obj_ty.toIntern(),
1996420163 .storage = .{ .elems = &.{} },
1996520164 } })));
1996620165}
1996720166
1996820167fn zirUnionInit(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
20168 const pt = sema.pt;
1996920169 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
1997020170 const ty_src = block.builtinCallArgSrc(inst_data.src_node, 0);
1997120171 const field_src = block.builtinCallArgSrc(inst_data.src_node, 1);
1997220172 const init_src = block.builtinCallArgSrc(inst_data.src_node, 2);
1997320173 const extra = sema.code.extraData(Zir.Inst.UnionInit, inst_data.payload_index).data;
1997420174 const union_ty = try sema.resolveType(block, ty_src, extra.union_type);
19975 if (union_ty.zigTypeTag(sema.mod) != .Union) {
19976 return sema.fail(block, ty_src, "expected union type, found '{}'", .{union_ty.fmt(sema.mod)});
20175 if (union_ty.zigTypeTag(pt.zcu) != .Union) {
20176 return sema.fail(block, ty_src, "expected union type, found '{}'", .{union_ty.fmt(pt)});
1997720177 }
1997820178 const field_name = try sema.resolveConstStringIntern(block, field_src, extra.field_name, .{
1997920179 .needed_comptime_reason = "name of field being initialized must be comptime-known",
......@@ -19992,7 +20192,8 @@ fn unionInit(
1999220192 field_name: InternPool.NullTerminatedString,
1999320193 field_src: LazySrcLoc,
1999420194) CompileError!Air.Inst.Ref {
19995 const mod = sema.mod;
20195 const pt = sema.pt;
20196 const mod = pt.zcu;
1999620197 const ip = &mod.intern_pool;
1999720198 const field_index = try sema.unionFieldIndex(block, union_ty, field_name, field_src);
1999820199 const field_ty = Type.fromInterned(mod.typeToUnion(union_ty).?.field_types.get(ip)[field_index]);
......@@ -20000,8 +20201,8 @@ fn unionInit(
2000020201
2000120202 if (try sema.resolveValue(init)) |init_val| {
2000220203 const tag_ty = union_ty.unionTagTypeHypothetical(mod);
20003 const tag_val = try mod.enumValueFieldIndex(tag_ty, field_index);
20004 return Air.internedToRef((try mod.intern(.{ .un = .{
20204 const tag_val = try pt.enumValueFieldIndex(tag_ty, field_index);
20205 return Air.internedToRef((try pt.intern(.{ .un = .{
2000520206 .ty = union_ty.toIntern(),
2000620207 .tag = tag_val.toIntern(),
2000720208 .val = init_val.toIntern(),
......@@ -20025,7 +20226,8 @@ fn zirStructInit(
2002520226 const extra = sema.code.extraData(Zir.Inst.StructInit, inst_data.payload_index);
2002620227 const src = block.nodeOffset(inst_data.src_node);
2002720228
20028 const mod = sema.mod;
20229 const pt = sema.pt;
20230 const mod = pt.zcu;
2002920231 const ip = &mod.intern_pool;
2003020232 const first_item = sema.code.extraData(Zir.Inst.StructInit.Item, extra.end).data;
2003120233 const first_field_type_data = zir_datas[@intFromEnum(first_item.field_type)].pl_node;
......@@ -20038,7 +20240,7 @@ fn zirStructInit(
2003820240 else => |e| return e,
2003920241 };
2004020242 const resolved_ty = result_ty.optEuBaseType(mod);
20041 try resolved_ty.resolveLayout(mod);
20243 try resolved_ty.resolveLayout(pt);
2004220244
2004320245 if (resolved_ty.zigTypeTag(mod) == .Struct) {
2004420246 // This logic must be synchronized with that in `zirStructInitEmpty`.
......@@ -20066,6 +20268,7 @@ fn zirStructInit(
2006620268 const field_type_extra = sema.code.extraData(Zir.Inst.FieldType, field_type_data.payload_index).data;
2006720269 const field_name = try ip.getOrPutString(
2006820270 gpa,
20271 pt.tid,
2006920272 sema.code.nullTerminatedString(field_type_extra.name_start),
2007020273 .no_embedded_nulls,
2007120274 );
......@@ -20079,8 +20282,8 @@ fn zirStructInit(
2007920282 const field_ty = resolved_ty.structFieldType(field_index, mod);
2008020283 field_inits[field_index] = try sema.coerce(block, field_ty, uncoerced_init, field_src);
2008120284 if (!is_packed) {
20082 try resolved_ty.resolveStructFieldInits(mod);
20083 if (try resolved_ty.structFieldValueComptime(mod, field_index)) |default_value| {
20285 try resolved_ty.resolveStructFieldInits(pt);
20286 if (try resolved_ty.structFieldValueComptime(pt, field_index)) |default_value| {
2008420287 const init_val = (try sema.resolveValue(field_inits[field_index])) orelse {
2008520288 return sema.failWithNeededComptime(block, field_src, .{
2008620289 .needed_comptime_reason = "value stored in comptime field must be comptime-known",
......@@ -20107,12 +20310,13 @@ fn zirStructInit(
2010720310 const field_type_extra = sema.code.extraData(Zir.Inst.FieldType, field_type_data.payload_index).data;
2010820311 const field_name = try ip.getOrPutString(
2010920312 gpa,
20313 pt.tid,
2011020314 sema.code.nullTerminatedString(field_type_extra.name_start),
2011120315 .no_embedded_nulls,
2011220316 );
2011320317 const field_index = try sema.unionFieldIndex(block, resolved_ty, field_name, field_src);
2011420318 const tag_ty = resolved_ty.unionTagTypeHypothetical(mod);
20115 const tag_val = try mod.enumValueFieldIndex(tag_ty, field_index);
20319 const tag_val = try pt.enumValueFieldIndex(tag_ty, field_index);
2011620320 const field_ty = Type.fromInterned(mod.typeToUnion(resolved_ty).?.field_types.get(ip)[field_index]);
2011720321
2011820322 if (field_ty.zigTypeTag(mod) == .NoReturn) {
......@@ -20132,11 +20336,11 @@ fn zirStructInit(
2013220336 const init_inst = try sema.coerce(block, field_ty, uncoerced_init_inst, field_src);
2013320337
2013420338 if (try sema.resolveValue(init_inst)) |val| {
20135 const struct_val = Value.fromInterned((try mod.intern(.{ .un = .{
20339 const struct_val = Value.fromInterned(try pt.intern(.{ .un = .{
2013620340 .ty = resolved_ty.toIntern(),
2013720341 .tag = tag_val.toIntern(),
2013820342 .val = val.toIntern(),
20139 } })));
20343 } }));
2014020344 const final_val_inst = try sema.coerce(block, result_ty, Air.internedToRef(struct_val.toIntern()), src);
2014120345 const final_val = (try sema.resolveValue(final_val_inst)).?;
2014220346 return sema.addConstantMaybeRef(final_val.toIntern(), is_ref);
......@@ -20152,7 +20356,7 @@ fn zirStructInit(
2015220356
2015320357 if (is_ref) {
2015420358 const target = mod.getTarget();
20155 const alloc_ty = try mod.ptrTypeSema(.{
20359 const alloc_ty = try pt.ptrTypeSema(.{
2015620360 .child = result_ty.toIntern(),
2015720361 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
2015820362 });
......@@ -20182,7 +20386,8 @@ fn finishStructInit(
2018220386 result_ty: Type,
2018320387 is_ref: bool,
2018420388) CompileError!Air.Inst.Ref {
20185 const mod = sema.mod;
20389 const pt = sema.pt;
20390 const mod = pt.zcu;
2018620391 const ip = &mod.intern_pool;
2018720392
2018820393 var root_msg: ?*Module.ErrorMsg = null;
......@@ -20242,7 +20447,7 @@ fn finishStructInit(
2024220447 continue;
2024320448 }
2024420449
20245 try struct_ty.resolveStructFieldInits(mod);
20450 try struct_ty.resolveStructFieldInits(pt);
2024620451
2024720452 const field_init = struct_type.fieldInit(ip, i);
2024820453 if (field_init == .none) {
......@@ -20289,7 +20494,7 @@ fn finishStructInit(
2028920494 for (elems, field_inits) |*elem, field_init| {
2029020495 elem.* = (sema.resolveValue(field_init) catch unreachable).?.toIntern();
2029120496 }
20292 const struct_val = try mod.intern(.{ .aggregate = .{
20497 const struct_val = try pt.intern(.{ .aggregate = .{
2029320498 .ty = struct_ty.toIntern(),
2029420499 .storage = .{ .elems = elems },
2029520500 } });
......@@ -20312,9 +20517,9 @@ fn finishStructInit(
2031220517 }
2031320518
2031420519 if (is_ref) {
20315 try struct_ty.resolveLayout(mod);
20316 const target = sema.mod.getTarget();
20317 const alloc_ty = try mod.ptrTypeSema(.{
20520 try struct_ty.resolveLayout(pt);
20521 const target = mod.getTarget();
20522 const alloc_ty = try pt.ptrTypeSema(.{
2031820523 .child = result_ty.toIntern(),
2031920524 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
2032020525 });
......@@ -20334,7 +20539,7 @@ fn finishStructInit(
2033420539 .init_node_offset = init_src.offset.node_offset.x,
2033520540 .elem_index = @intCast(runtime_index),
2033620541 } }));
20337 try struct_ty.resolveStructFieldInits(mod);
20542 try struct_ty.resolveStructFieldInits(pt);
2033820543 const struct_val = try block.addAggregateInit(struct_ty, field_inits);
2033920544 return sema.coerce(block, result_ty, struct_val, init_src);
2034020545}
......@@ -20364,7 +20569,8 @@ fn structInitAnon(
2036420569 extra_end: usize,
2036520570 is_ref: bool,
2036620571) CompileError!Air.Inst.Ref {
20367 const mod = sema.mod;
20572 const pt = sema.pt;
20573 const mod = pt.zcu;
2036820574 const gpa = sema.gpa;
2036920575 const ip = &mod.intern_pool;
2037020576 const zir_datas = sema.code.instructions.items(.data);
......@@ -20394,7 +20600,7 @@ fn structInitAnon(
2039420600 },
2039520601 };
2039620602
20397 field_name.* = try mod.intern_pool.getOrPutString(gpa, name, .no_embedded_nulls);
20603 field_name.* = try mod.intern_pool.getOrPutString(gpa, pt.tid, name, .no_embedded_nulls);
2039820604
2039920605 const init = try sema.resolveInst(item.data.init);
2040020606 field_ty.* = sema.typeOf(init).toIntern();
......@@ -20422,14 +20628,14 @@ fn structInitAnon(
2042220628 break :rs runtime_index;
2042320629 };
2042420630
20425 const tuple_ty = try ip.getAnonStructType(gpa, .{
20631 const tuple_ty = try ip.getAnonStructType(gpa, pt.tid, .{
2042620632 .names = names,
2042720633 .types = types,
2042820634 .values = values,
2042920635 });
2043020636
2043120637 const runtime_index = opt_runtime_index orelse {
20432 const tuple_val = try mod.intern(.{ .aggregate = .{
20638 const tuple_val = try pt.intern(.{ .aggregate = .{
2043320639 .ty = tuple_ty,
2043420640 .storage = .{ .elems = values },
2043520641 } });
......@@ -20443,7 +20649,7 @@ fn structInitAnon(
2044320649
2044420650 if (is_ref) {
2044520651 const target = mod.getTarget();
20446 const alloc_ty = try mod.ptrTypeSema(.{
20652 const alloc_ty = try pt.ptrTypeSema(.{
2044720653 .child = tuple_ty,
2044820654 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
2044920655 });
......@@ -20457,7 +20663,7 @@ fn structInitAnon(
2045720663 };
2045820664 extra_index = item.end;
2045920665
20460 const field_ptr_ty = try mod.ptrTypeSema(.{
20666 const field_ptr_ty = try pt.ptrTypeSema(.{
2046120667 .child = field_ty,
2046220668 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
2046320669 });
......@@ -20491,7 +20697,8 @@ fn zirArrayInit(
2049120697 inst: Zir.Inst.Index,
2049220698 is_ref: bool,
2049320699) CompileError!Air.Inst.Ref {
20494 const mod = sema.mod;
20700 const pt = sema.pt;
20701 const mod = pt.zcu;
2049520702 const gpa = sema.gpa;
2049620703 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2049720704 const src = block.nodeOffset(inst_data.src_node);
......@@ -20550,8 +20757,8 @@ fn zirArrayInit(
2055020757 dest.* = try sema.coerce(block, elem_ty, resolved_arg, elem_src);
2055120758 if (is_tuple) {
2055220759 if (array_ty.structFieldIsComptime(i, mod))
20553 try array_ty.resolveStructFieldInits(mod);
20554 if (try array_ty.structFieldValueComptime(mod, i)) |field_val| {
20760 try array_ty.resolveStructFieldInits(pt);
20761 if (try array_ty.structFieldValueComptime(pt, i)) |field_val| {
2055520762 const init_val = try sema.resolveValue(dest.*) orelse {
2055620763 return sema.failWithNeededComptime(block, elem_src, .{
2055720764 .needed_comptime_reason = "value stored in comptime field must be comptime-known",
......@@ -20581,7 +20788,7 @@ fn zirArrayInit(
2058120788 // We checked that all args are comptime above.
2058220789 val.* = (sema.resolveValue(arg) catch unreachable).?.toIntern();
2058320790 }
20584 const arr_val = try mod.intern(.{ .aggregate = .{
20791 const arr_val = try pt.intern(.{ .aggregate = .{
2058520792 .ty = array_ty.toIntern(),
2058620793 .storage = .{ .elems = elem_vals },
2058720794 } });
......@@ -20597,7 +20804,7 @@ fn zirArrayInit(
2059720804
2059820805 if (is_ref) {
2059920806 const target = mod.getTarget();
20600 const alloc_ty = try mod.ptrTypeSema(.{
20807 const alloc_ty = try pt.ptrTypeSema(.{
2060120808 .child = result_ty.toIntern(),
2060220809 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
2060320810 });
......@@ -20606,27 +20813,27 @@ fn zirArrayInit(
2060620813
2060720814 if (is_tuple) {
2060820815 for (resolved_args, 0..) |arg, i| {
20609 const elem_ptr_ty = try mod.ptrTypeSema(.{
20816 const elem_ptr_ty = try pt.ptrTypeSema(.{
2061020817 .child = array_ty.structFieldType(i, mod).toIntern(),
2061120818 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
2061220819 });
2061320820 const elem_ptr_ty_ref = Air.internedToRef(elem_ptr_ty.toIntern());
2061420821
20615 const index = try mod.intRef(Type.usize, i);
20822 const index = try pt.intRef(Type.usize, i);
2061620823 const elem_ptr = try block.addPtrElemPtrTypeRef(base_ptr, index, elem_ptr_ty_ref);
2061720824 _ = try block.addBinOp(.store, elem_ptr, arg);
2061820825 }
2061920826 return sema.makePtrConst(block, alloc);
2062020827 }
2062120828
20622 const elem_ptr_ty = try mod.ptrTypeSema(.{
20829 const elem_ptr_ty = try pt.ptrTypeSema(.{
2062320830 .child = array_ty.elemType2(mod).toIntern(),
2062420831 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
2062520832 });
2062620833 const elem_ptr_ty_ref = Air.internedToRef(elem_ptr_ty.toIntern());
2062720834
2062820835 for (resolved_args, 0..) |arg, i| {
20629 const index = try mod.intRef(Type.usize, i);
20836 const index = try pt.intRef(Type.usize, i);
2063020837 const elem_ptr = try block.addPtrElemPtrTypeRef(base_ptr, index, elem_ptr_ty_ref);
2063120838 _ = try block.addBinOp(.store, elem_ptr, arg);
2063220839 }
......@@ -20656,7 +20863,8 @@ fn arrayInitAnon(
2065620863 operands: []const Zir.Inst.Ref,
2065720864 is_ref: bool,
2065820865) CompileError!Air.Inst.Ref {
20659 const mod = sema.mod;
20866 const pt = sema.pt;
20867 const mod = pt.zcu;
2066020868 const gpa = sema.gpa;
2066120869 const ip = &mod.intern_pool;
2066220870
......@@ -20689,14 +20897,14 @@ fn arrayInitAnon(
2068920897 break :rs runtime_src;
2069020898 };
2069120899
20692 const tuple_ty = try ip.getAnonStructType(gpa, .{
20900 const tuple_ty = try ip.getAnonStructType(gpa, pt.tid, .{
2069320901 .types = types,
2069420902 .values = values,
2069520903 .names = &.{},
2069620904 });
2069720905
2069820906 const runtime_src = opt_runtime_src orelse {
20699 const tuple_val = try mod.intern(.{ .aggregate = .{
20907 const tuple_val = try pt.intern(.{ .aggregate = .{
2070020908 .ty = tuple_ty,
2070120909 .storage = .{ .elems = values },
2070220910 } });
......@@ -20706,15 +20914,15 @@ fn arrayInitAnon(
2070620914 try sema.requireRuntimeBlock(block, src, runtime_src);
2070720915
2070820916 if (is_ref) {
20709 const target = sema.mod.getTarget();
20710 const alloc_ty = try mod.ptrTypeSema(.{
20917 const target = sema.pt.zcu.getTarget();
20918 const alloc_ty = try pt.ptrTypeSema(.{
2071120919 .child = tuple_ty,
2071220920 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
2071320921 });
2071420922 const alloc = try block.addTy(.alloc, alloc_ty);
2071520923 for (operands, 0..) |operand, i_usize| {
2071620924 const i: u32 = @intCast(i_usize);
20717 const field_ptr_ty = try mod.ptrTypeSema(.{
20925 const field_ptr_ty = try pt.ptrTypeSema(.{
2071820926 .child = types[i],
2071920927 .flags = .{ .address_space = target_util.defaultAddressSpace(target, .local) },
2072020928 });
......@@ -20752,7 +20960,8 @@ fn zirFieldTypeRef(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
2075220960}
2075320961
2075420962fn zirStructInitFieldType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
20755 const mod = sema.mod;
20963 const pt = sema.pt;
20964 const mod = pt.zcu;
2075620965 const ip = &mod.intern_pool;
2075720966 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2075820967 const extra = sema.code.extraData(Zir.Inst.FieldType, inst_data.payload_index).data;
......@@ -20768,7 +20977,7 @@ fn zirStructInitFieldType(sema: *Sema, block: *Block, inst: Zir.Inst.Index) Comp
2076820977 };
2076920978 const aggregate_ty = wrapped_aggregate_ty.optEuBaseType(mod);
2077020979 const zir_field_name = sema.code.nullTerminatedString(extra.name_start);
20771 const field_name = try ip.getOrPutString(sema.gpa, zir_field_name, .no_embedded_nulls);
20980 const field_name = try ip.getOrPutString(sema.gpa, pt.tid, zir_field_name, .no_embedded_nulls);
2077220981 return sema.fieldType(block, aggregate_ty, field_name, field_name_src, ty_src);
2077320982}
2077420983
......@@ -20780,11 +20989,12 @@ fn fieldType(
2078020989 field_src: LazySrcLoc,
2078120990 ty_src: LazySrcLoc,
2078220991) CompileError!Air.Inst.Ref {
20783 const mod = sema.mod;
20992 const pt = sema.pt;
20993 const mod = pt.zcu;
2078420994 const ip = &mod.intern_pool;
2078520995 var cur_ty = aggregate_ty;
2078620996 while (true) {
20787 try cur_ty.resolveFields(mod);
20997 try cur_ty.resolveFields(pt);
2078820998 switch (cur_ty.zigTypeTag(mod)) {
2078920999 .Struct => switch (ip.indexToKey(cur_ty.toIntern())) {
2079021000 .anon_struct_type => |anon_struct| {
......@@ -20823,7 +21033,7 @@ fn fieldType(
2082321033 else => {},
2082421034 }
2082521035 return sema.fail(block, ty_src, "expected struct or union; found '{}'", .{
20826 cur_ty.fmt(sema.mod),
21036 cur_ty.fmt(pt),
2082721037 });
2082821038 }
2082921039}
......@@ -20833,12 +21043,13 @@ fn zirErrorReturnTrace(sema: *Sema, block: *Block) CompileError!Air.Inst.Ref {
2083321043}
2083421044
2083521045fn getErrorReturnTrace(sema: *Sema, block: *Block) CompileError!Air.Inst.Ref {
20836 const mod = sema.mod;
21046 const pt = sema.pt;
21047 const mod = pt.zcu;
2083721048 const ip = &mod.intern_pool;
20838 const stack_trace_ty = try mod.getBuiltinType("StackTrace");
20839 try stack_trace_ty.resolveFields(mod);
20840 const ptr_stack_trace_ty = try mod.singleMutPtrType(stack_trace_ty);
20841 const opt_ptr_stack_trace_ty = try mod.optionalType(ptr_stack_trace_ty.toIntern());
21049 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
21050 try stack_trace_ty.resolveFields(pt);
21051 const ptr_stack_trace_ty = try pt.singleMutPtrType(stack_trace_ty);
21052 const opt_ptr_stack_trace_ty = try pt.optionalType(ptr_stack_trace_ty.toIntern());
2084221053
2084321054 if (sema.owner_func_index != .none and
2084421055 ip.funcAnalysis(sema.owner_func_index).calls_or_awaits_errorable_fn and
......@@ -20846,7 +21057,7 @@ fn getErrorReturnTrace(sema: *Sema, block: *Block) CompileError!Air.Inst.Ref {
2084621057 {
2084721058 return block.addTy(.err_return_trace, opt_ptr_stack_trace_ty);
2084821059 }
20849 return Air.internedToRef((try mod.intern(.{ .opt = .{
21060 return Air.internedToRef((try pt.intern(.{ .opt = .{
2085021061 .ty = opt_ptr_stack_trace_ty.toIntern(),
2085121062 .val = .none,
2085221063 } })));
......@@ -20862,19 +21073,20 @@ fn zirFrame(
2086221073}
2086321074
2086421075fn zirAlignOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
20865 const mod = sema.mod;
21076 const pt = sema.pt;
2086621077 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
2086721078 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
2086821079 const ty = try sema.resolveType(block, operand_src, inst_data.operand);
20869 if (ty.isNoReturn(mod)) {
20870 return sema.fail(block, operand_src, "no align available for type '{}'", .{ty.fmt(sema.mod)});
21080 if (ty.isNoReturn(pt.zcu)) {
21081 return sema.fail(block, operand_src, "no align available for type '{}'", .{ty.fmt(pt)});
2087121082 }
20872 const val = try ty.lazyAbiAlignment(mod);
21083 const val = try ty.lazyAbiAlignment(pt);
2087321084 return Air.internedToRef(val.toIntern());
2087421085}
2087521086
2087621087fn zirIntFromBool(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
20877 const mod = sema.mod;
21088 const pt = sema.pt;
21089 const mod = pt.zcu;
2087821090 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
2087921091 const src = block.nodeOffset(inst_data.src_node);
2088021092 const operand = try sema.resolveInst(inst_data.operand);
......@@ -20886,25 +21098,25 @@ fn zirIntFromBool(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
2088621098 }
2088721099 if (try sema.resolveValue(operand)) |val| {
2088821100 if (!is_vector) {
20889 if (val.isUndef(mod)) return mod.undefRef(Type.u1);
20890 if (val.toBool()) return Air.internedToRef((try mod.intValue(Type.u1, 1)).toIntern());
20891 return Air.internedToRef((try mod.intValue(Type.u1, 0)).toIntern());
21101 if (val.isUndef(mod)) return pt.undefRef(Type.u1);
21102 if (val.toBool()) return Air.internedToRef((try pt.intValue(Type.u1, 1)).toIntern());
21103 return Air.internedToRef((try pt.intValue(Type.u1, 0)).toIntern());
2089221104 }
2089321105 const len = operand_ty.vectorLen(mod);
20894 const dest_ty = try mod.vectorType(.{ .child = .u1_type, .len = len });
20895 if (val.isUndef(mod)) return mod.undefRef(dest_ty);
21106 const dest_ty = try pt.vectorType(.{ .child = .u1_type, .len = len });
21107 if (val.isUndef(mod)) return pt.undefRef(dest_ty);
2089621108 const new_elems = try sema.arena.alloc(InternPool.Index, len);
2089721109 for (new_elems, 0..) |*new_elem, i| {
20898 const old_elem = try val.elemValue(mod, i);
21110 const old_elem = try val.elemValue(pt, i);
2089921111 const new_val = if (old_elem.isUndef(mod))
20900 try mod.undefValue(Type.u1)
21112 try pt.undefValue(Type.u1)
2090121113 else if (old_elem.toBool())
20902 try mod.intValue(Type.u1, 1)
21114 try pt.intValue(Type.u1, 1)
2090321115 else
20904 try mod.intValue(Type.u1, 0);
21116 try pt.intValue(Type.u1, 0);
2090521117 new_elem.* = new_val.toIntern();
2090621118 }
20907 return Air.internedToRef(try mod.intern(.{ .aggregate = .{
21119 return Air.internedToRef(try pt.intern(.{ .aggregate = .{
2090821120 .ty = dest_ty.toIntern(),
2090921121 .storage = .{ .elems = new_elems },
2091021122 } }));
......@@ -20913,10 +21125,10 @@ fn zirIntFromBool(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
2091321125 return block.addUnOp(.int_from_bool, operand);
2091421126 }
2091521127 const len = operand_ty.vectorLen(mod);
20916 const dest_ty = try mod.vectorType(.{ .child = .u1_type, .len = len });
21128 const dest_ty = try pt.vectorType(.{ .child = .u1_type, .len = len });
2091721129 const new_elems = try sema.arena.alloc(Air.Inst.Ref, len);
2091821130 for (new_elems, 0..) |*new_elem, i| {
20919 const idx_ref = try mod.intRef(Type.usize, i);
21131 const idx_ref = try pt.intRef(Type.usize, i);
2092021132 const old_elem = try block.addBinOp(.array_elem_val, operand, idx_ref);
2092121133 new_elem.* = try block.addUnOp(.int_from_bool, old_elem);
2092221134 }
......@@ -20930,7 +21142,7 @@ fn zirErrorName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
2093021142 const operand = try sema.coerce(block, Type.anyerror, uncoerced_operand, operand_src);
2093121143
2093221144 if (try sema.resolveDefinedValue(block, operand_src, operand)) |val| {
20933 const err_name = sema.mod.intern_pool.indexToKey(val.toIntern()).err.name;
21145 const err_name = sema.pt.zcu.intern_pool.indexToKey(val.toIntern()).err.name;
2093421146 return sema.addNullTerminatedStrLit(err_name);
2093521147 }
2093621148
......@@ -20944,7 +21156,8 @@ fn zirAbs(
2094421156 block: *Block,
2094521157 inst: Zir.Inst.Index,
2094621158) CompileError!Air.Inst.Ref {
20947 const mod = sema.mod;
21159 const pt = sema.pt;
21160 const mod = pt.zcu;
2094821161 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
2094921162 const operand = try sema.resolveInst(inst_data.operand);
2095021163 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
......@@ -20953,12 +21166,12 @@ fn zirAbs(
2095321166
2095421167 const result_ty = switch (scalar_ty.zigTypeTag(mod)) {
2095521168 .ComptimeFloat, .Float, .ComptimeInt => operand_ty,
20956 .Int => if (scalar_ty.isSignedInt(mod)) try operand_ty.toUnsigned(mod) else return operand,
21169 .Int => if (scalar_ty.isSignedInt(mod)) try operand_ty.toUnsigned(pt) else return operand,
2095721170 else => return sema.fail(
2095821171 block,
2095921172 operand_src,
2096021173 "expected integer, float, or vector of either integers or floats, found '{}'",
20961 .{operand_ty.fmt(mod)},
21174 .{operand_ty.fmt(pt)},
2096221175 ),
2096321176 };
2096421177
......@@ -20972,30 +21185,31 @@ fn maybeConstantUnaryMath(
2097221185 sema: *Sema,
2097321186 operand: Air.Inst.Ref,
2097421187 result_ty: Type,
20975 comptime eval: fn (Value, Type, Allocator, *Module) Allocator.Error!Value,
21188 comptime eval: fn (Value, Type, Allocator, Zcu.PerThread) Allocator.Error!Value,
2097621189) CompileError!?Air.Inst.Ref {
20977 const mod = sema.mod;
21190 const pt = sema.pt;
21191 const mod = pt.zcu;
2097821192 switch (result_ty.zigTypeTag(mod)) {
2097921193 .Vector => if (try sema.resolveValue(operand)) |val| {
2098021194 const scalar_ty = result_ty.scalarType(mod);
2098121195 const vec_len = result_ty.vectorLen(mod);
2098221196 if (val.isUndef(mod))
20983 return try mod.undefRef(result_ty);
21197 return try pt.undefRef(result_ty);
2098421198
2098521199 const elems = try sema.arena.alloc(InternPool.Index, vec_len);
2098621200 for (elems, 0..) |*elem, i| {
20987 const elem_val = try val.elemValue(sema.mod, i);
20988 elem.* = (try eval(elem_val, scalar_ty, sema.arena, sema.mod)).toIntern();
21201 const elem_val = try val.elemValue(pt, i);
21202 elem.* = (try eval(elem_val, scalar_ty, sema.arena, pt)).toIntern();
2098921203 }
20990 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
21204 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
2099121205 .ty = result_ty.toIntern(),
2099221206 .storage = .{ .elems = elems },
2099321207 } })));
2099421208 },
2099521209 else => if (try sema.resolveValue(operand)) |operand_val| {
2099621210 if (operand_val.isUndef(mod))
20997 return try mod.undefRef(result_ty);
20998 const result_val = try eval(operand_val, result_ty, sema.arena, sema.mod);
21211 return try pt.undefRef(result_ty);
21212 const result_val = try eval(operand_val, result_ty, sema.arena, pt);
2099921213 return Air.internedToRef(result_val.toIntern());
2100021214 },
2100121215 }
......@@ -21007,12 +21221,13 @@ fn zirUnaryMath(
2100721221 block: *Block,
2100821222 inst: Zir.Inst.Index,
2100921223 air_tag: Air.Inst.Tag,
21010 comptime eval: fn (Value, Type, Allocator, *Module) Allocator.Error!Value,
21224 comptime eval: fn (Value, Type, Allocator, Zcu.PerThread) Allocator.Error!Value,
2101121225) CompileError!Air.Inst.Ref {
2101221226 const tracy = trace(@src());
2101321227 defer tracy.end();
2101421228
21015 const mod = sema.mod;
21229 const pt = sema.pt;
21230 const mod = pt.zcu;
2101621231 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
2101721232 const operand = try sema.resolveInst(inst_data.operand);
2101821233 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
......@@ -21025,7 +21240,7 @@ fn zirUnaryMath(
2102521240 block,
2102621241 operand_src,
2102721242 "expected vector of floats or float type, found '{}'",
21028 .{operand_ty.fmt(sema.mod)},
21243 .{operand_ty.fmt(pt)},
2102921244 ),
2103021245 }
2103121246
......@@ -21041,10 +21256,11 @@ fn zirTagName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
2104121256 const src = block.nodeOffset(inst_data.src_node);
2104221257 const operand = try sema.resolveInst(inst_data.operand);
2104321258 const operand_ty = sema.typeOf(operand);
21044 const mod = sema.mod;
21259 const pt = sema.pt;
21260 const mod = pt.zcu;
2104521261 const ip = &mod.intern_pool;
2104621262
21047 try operand_ty.resolveLayout(mod);
21263 try operand_ty.resolveLayout(pt);
2104821264 const enum_ty = switch (operand_ty.zigTypeTag(mod)) {
2104921265 .EnumLiteral => {
2105021266 const val = try sema.resolveConstDefinedValue(block, LazySrcLoc.unneeded, operand, undefined);
......@@ -21053,9 +21269,9 @@ fn zirTagName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
2105321269 },
2105421270 .Enum => operand_ty,
2105521271 .Union => operand_ty.unionTagType(mod) orelse
21056 return sema.fail(block, src, "union '{}' is untagged", .{operand_ty.fmt(sema.mod)}),
21272 return sema.fail(block, src, "union '{}' is untagged", .{operand_ty.fmt(pt)}),
2105721273 else => return sema.fail(block, operand_src, "expected enum or union; found '{}'", .{
21058 operand_ty.fmt(mod),
21274 operand_ty.fmt(pt),
2105921275 }),
2106021276 };
2106121277 if (enum_ty.enumFieldCount(mod) == 0) {
......@@ -21063,7 +21279,7 @@ fn zirTagName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
2106321279 // it prevents a crash.
2106421280 // https://github.com/ziglang/zig/issues/15909
2106521281 return sema.fail(block, operand_src, "cannot get @tagName of empty enum '{}'", .{
21066 enum_ty.fmt(mod),
21282 enum_ty.fmt(pt),
2106721283 });
2106821284 }
2106921285 const enum_decl_index = enum_ty.getOwnerDecl(mod);
......@@ -21072,7 +21288,7 @@ fn zirTagName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
2107221288 const field_index = enum_ty.enumTagFieldIndex(val, mod) orelse {
2107321289 const msg = msg: {
2107421290 const msg = try sema.errMsg(src, "no field with value '{}' in enum '{}'", .{
21075 val.fmtValue(sema.mod, sema), mod.declPtr(enum_decl_index).name.fmt(ip),
21291 val.fmtValue(pt, sema), mod.declPtr(enum_decl_index).name.fmt(ip),
2107621292 });
2107721293 errdefer msg.destroy(sema.gpa);
2107821294 try sema.errNote(enum_ty.srcLoc(mod), msg, "declared here", .{});
......@@ -21085,7 +21301,7 @@ fn zirTagName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
2108521301 return sema.addNullTerminatedStrLit(field_name);
2108621302 }
2108721303 try sema.requireRuntimeBlock(block, src, operand_src);
21088 if (block.wantSafety() and sema.mod.backendSupportsFeature(.is_named_enum_value)) {
21304 if (block.wantSafety() and mod.backendSupportsFeature(.is_named_enum_value)) {
2108921305 const ok = try block.addUnOp(.is_named_enum_value, casted_operand);
2109021306 try sema.addSafetyCheck(block, src, ok, .invalid_enum_value);
2109121307 }
......@@ -21101,7 +21317,8 @@ fn zirReify(
2110121317 extended: Zir.Inst.Extended.InstData,
2110221318 inst: Zir.Inst.Index,
2110321319) CompileError!Air.Inst.Ref {
21104 const mod = sema.mod;
21320 const pt = sema.pt;
21321 const mod = pt.zcu;
2110521322 const gpa = sema.gpa;
2110621323 const ip = &mod.intern_pool;
2110721324 const name_strategy: Zir.Inst.NameStrategy = @enumFromInt(extended.small);
......@@ -21120,7 +21337,7 @@ fn zirReify(
2112021337 },
2112121338 },
2112221339 };
21123 const type_info_ty = try mod.getBuiltinType("Type");
21340 const type_info_ty = try pt.getBuiltinType("Type");
2112421341 const uncasted_operand = try sema.resolveInst(extra.operand);
2112521342 const type_info = try sema.coerce(block, type_info_ty, uncasted_operand, operand_src);
2112621343 const val = try sema.resolveConstDefinedValue(block, operand_src, type_info, .{
......@@ -21145,36 +21362,36 @@ fn zirReify(
2114521362 .Int => {
2114621363 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
2114721364 const signedness_val = try Value.fromInterned(union_val.val).fieldValue(
21148 mod,
21149 struct_type.nameIndex(ip, try ip.getOrPutString(gpa, "signedness", .no_embedded_nulls)).?,
21365 pt,
21366 struct_type.nameIndex(ip, try ip.getOrPutString(gpa, pt.tid, "signedness", .no_embedded_nulls)).?,
2115021367 );
2115121368 const bits_val = try Value.fromInterned(union_val.val).fieldValue(
21152 mod,
21153 struct_type.nameIndex(ip, try ip.getOrPutString(gpa, "bits", .no_embedded_nulls)).?,
21369 pt,
21370 struct_type.nameIndex(ip, try ip.getOrPutString(gpa, pt.tid, "bits", .no_embedded_nulls)).?,
2115421371 );
2115521372
2115621373 const signedness = mod.toEnum(std.builtin.Signedness, signedness_val);
21157 const bits: u16 = @intCast(try bits_val.toUnsignedIntSema(mod));
21158 const ty = try mod.intType(signedness, bits);
21374 const bits: u16 = @intCast(try bits_val.toUnsignedIntSema(pt));
21375 const ty = try pt.intType(signedness, bits);
2115921376 return Air.internedToRef(ty.toIntern());
2116021377 },
2116121378 .Vector => {
2116221379 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21163 const len_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21380 const len_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2116421381 ip,
21165 try ip.getOrPutString(gpa, "len", .no_embedded_nulls),
21382 try ip.getOrPutString(gpa, pt.tid, "len", .no_embedded_nulls),
2116621383 ).?);
21167 const child_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21384 const child_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2116821385 ip,
21169 try ip.getOrPutString(gpa, "child", .no_embedded_nulls),
21386 try ip.getOrPutString(gpa, pt.tid, "child", .no_embedded_nulls),
2117021387 ).?);
2117121388
21172 const len: u32 = @intCast(try len_val.toUnsignedIntSema(mod));
21389 const len: u32 = @intCast(try len_val.toUnsignedIntSema(pt));
2117321390 const child_ty = child_val.toType();
2117421391
2117521392 try sema.checkVectorElemType(block, src, child_ty);
2117621393
21177 const ty = try mod.vectorType(.{
21394 const ty = try pt.vectorType(.{
2117821395 .len = len,
2117921396 .child = child_ty.toIntern(),
2118021397 });
......@@ -21182,12 +21399,12 @@ fn zirReify(
2118221399 },
2118321400 .Float => {
2118421401 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21185 const bits_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21402 const bits_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2118621403 ip,
21187 try ip.getOrPutString(gpa, "bits", .no_embedded_nulls),
21404 try ip.getOrPutString(gpa, pt.tid, "bits", .no_embedded_nulls),
2118821405 ).?);
2118921406
21190 const bits: u16 = @intCast(try bits_val.toUnsignedIntSema(mod));
21407 const bits: u16 = @intCast(try bits_val.toUnsignedIntSema(pt));
2119121408 const ty = switch (bits) {
2119221409 16 => Type.f16,
2119321410 32 => Type.f32,
......@@ -21200,44 +21417,44 @@ fn zirReify(
2120021417 },
2120121418 .Pointer => {
2120221419 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21203 const size_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21420 const size_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2120421421 ip,
21205 try ip.getOrPutString(gpa, "size", .no_embedded_nulls),
21422 try ip.getOrPutString(gpa, pt.tid, "size", .no_embedded_nulls),
2120621423 ).?);
21207 const is_const_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21424 const is_const_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2120821425 ip,
21209 try ip.getOrPutString(gpa, "is_const", .no_embedded_nulls),
21426 try ip.getOrPutString(gpa, pt.tid, "is_const", .no_embedded_nulls),
2121021427 ).?);
21211 const is_volatile_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21428 const is_volatile_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2121221429 ip,
21213 try ip.getOrPutString(gpa, "is_volatile", .no_embedded_nulls),
21430 try ip.getOrPutString(gpa, pt.tid, "is_volatile", .no_embedded_nulls),
2121421431 ).?);
21215 const alignment_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21432 const alignment_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2121621433 ip,
21217 try ip.getOrPutString(gpa, "alignment", .no_embedded_nulls),
21434 try ip.getOrPutString(gpa, pt.tid, "alignment", .no_embedded_nulls),
2121821435 ).?);
21219 const address_space_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21436 const address_space_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2122021437 ip,
21221 try ip.getOrPutString(gpa, "address_space", .no_embedded_nulls),
21438 try ip.getOrPutString(gpa, pt.tid, "address_space", .no_embedded_nulls),
2122221439 ).?);
21223 const child_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21440 const child_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2122421441 ip,
21225 try ip.getOrPutString(gpa, "child", .no_embedded_nulls),
21442 try ip.getOrPutString(gpa, pt.tid, "child", .no_embedded_nulls),
2122621443 ).?);
21227 const is_allowzero_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21444 const is_allowzero_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2122821445 ip,
21229 try ip.getOrPutString(gpa, "is_allowzero", .no_embedded_nulls),
21446 try ip.getOrPutString(gpa, pt.tid, "is_allowzero", .no_embedded_nulls),
2123021447 ).?);
21231 const sentinel_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21448 const sentinel_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2123221449 ip,
21233 try ip.getOrPutString(gpa, "sentinel", .no_embedded_nulls),
21450 try ip.getOrPutString(gpa, pt.tid, "sentinel", .no_embedded_nulls),
2123421451 ).?);
2123521452
2123621453 if (!try sema.intFitsInType(alignment_val, Type.u32, null)) {
2123721454 return sema.fail(block, src, "alignment must fit in 'u32'", .{});
2123821455 }
2123921456
21240 const alignment_val_int = (try alignment_val.getUnsignedIntAdvanced(mod, .sema)).?;
21457 const alignment_val_int = (try alignment_val.getUnsignedIntAdvanced(pt, .sema)).?;
2124121458 if (alignment_val_int > 0 and !math.isPowerOfTwo(alignment_val_int)) {
2124221459 return sema.fail(block, src, "alignment value '{d}' is not a power of two or zero", .{alignment_val_int});
2124321460 }
......@@ -21245,7 +21462,7 @@ fn zirReify(
2124521462
2124621463 const elem_ty = child_val.toType();
2124721464 if (abi_align != .none) {
21248 try elem_ty.resolveLayout(mod);
21465 try elem_ty.resolveLayout(pt);
2124921466 }
2125021467
2125121468 const ptr_size = mod.toEnum(std.builtin.Type.Pointer.Size, size_val);
......@@ -21256,7 +21473,7 @@ fn zirReify(
2125621473 return sema.fail(block, src, "sentinels are only allowed on slices and unknown-length pointers", .{});
2125721474 }
2125821475 const sentinel_ptr_val = sentinel_val.optionalValue(mod).?;
21259 const ptr_ty = try mod.singleMutPtrType(elem_ty);
21476 const ptr_ty = try pt.singleMutPtrType(elem_ty);
2126021477 const sent_val = (try sema.pointerDeref(block, src, sentinel_ptr_val, ptr_ty)).?;
2126121478 break :s sent_val.toIntern();
2126221479 }
......@@ -21274,7 +21491,7 @@ fn zirReify(
2127421491 } else if (ptr_size == .C) {
2127521492 if (!try sema.validateExternType(elem_ty, .other)) {
2127621493 const msg = msg: {
21277 const msg = try sema.errMsg(src, "C pointers cannot point to non-C-ABI-compatible type '{}'", .{elem_ty.fmt(mod)});
21494 const msg = try sema.errMsg(src, "C pointers cannot point to non-C-ABI-compatible type '{}'", .{elem_ty.fmt(pt)});
2127821495 errdefer msg.destroy(gpa);
2127921496
2128021497 try sema.explainWhyTypeIsNotExtern(msg, src, elem_ty, .other);
......@@ -21289,7 +21506,7 @@ fn zirReify(
2128921506 }
2129021507 }
2129121508
21292 const ty = try mod.ptrTypeSema(.{
21509 const ty = try pt.ptrTypeSema(.{
2129321510 .child = elem_ty.toIntern(),
2129421511 .sentinel = actual_sentinel,
2129521512 .flags = .{
......@@ -21305,27 +21522,27 @@ fn zirReify(
2130521522 },
2130621523 .Array => {
2130721524 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21308 const len_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21525 const len_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2130921526 ip,
21310 try ip.getOrPutString(gpa, "len", .no_embedded_nulls),
21527 try ip.getOrPutString(gpa, pt.tid, "len", .no_embedded_nulls),
2131121528 ).?);
21312 const child_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21529 const child_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2131321530 ip,
21314 try ip.getOrPutString(gpa, "child", .no_embedded_nulls),
21531 try ip.getOrPutString(gpa, pt.tid, "child", .no_embedded_nulls),
2131521532 ).?);
21316 const sentinel_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21533 const sentinel_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2131721534 ip,
21318 try ip.getOrPutString(gpa, "sentinel", .no_embedded_nulls),
21535 try ip.getOrPutString(gpa, pt.tid, "sentinel", .no_embedded_nulls),
2131921536 ).?);
2132021537
21321 const len = try len_val.toUnsignedIntSema(mod);
21538 const len = try len_val.toUnsignedIntSema(pt);
2132221539 const child_ty = child_val.toType();
2132321540 const sentinel = if (sentinel_val.optionalValue(mod)) |p| blk: {
21324 const ptr_ty = try mod.singleMutPtrType(child_ty);
21541 const ptr_ty = try pt.singleMutPtrType(child_ty);
2132521542 break :blk (try sema.pointerDeref(block, src, p, ptr_ty)).?;
2132621543 } else null;
2132721544
21328 const ty = try mod.arrayType(.{
21545 const ty = try pt.arrayType(.{
2132921546 .len = len,
2133021547 .sentinel = if (sentinel) |s| s.toIntern() else .none,
2133121548 .child = child_ty.toIntern(),
......@@ -21334,25 +21551,25 @@ fn zirReify(
2133421551 },
2133521552 .Optional => {
2133621553 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21337 const child_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21554 const child_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2133821555 ip,
21339 try ip.getOrPutString(gpa, "child", .no_embedded_nulls),
21556 try ip.getOrPutString(gpa, pt.tid, "child", .no_embedded_nulls),
2134021557 ).?);
2134121558
2134221559 const child_ty = child_val.toType();
2134321560
21344 const ty = try mod.optionalType(child_ty.toIntern());
21561 const ty = try pt.optionalType(child_ty.toIntern());
2134521562 return Air.internedToRef(ty.toIntern());
2134621563 },
2134721564 .ErrorUnion => {
2134821565 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21349 const error_set_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21566 const error_set_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2135021567 ip,
21351 try ip.getOrPutString(gpa, "error_set", .no_embedded_nulls),
21568 try ip.getOrPutString(gpa, pt.tid, "error_set", .no_embedded_nulls),
2135221569 ).?);
21353 const payload_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21570 const payload_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2135421571 ip,
21355 try ip.getOrPutString(gpa, "payload", .no_embedded_nulls),
21572 try ip.getOrPutString(gpa, pt.tid, "payload", .no_embedded_nulls),
2135621573 ).?);
2135721574
2135821575 const error_set_ty = error_set_val.toType();
......@@ -21362,7 +21579,7 @@ fn zirReify(
2136221579 return sema.fail(block, src, "Type.ErrorUnion.error_set must be an error set type", .{});
2136321580 }
2136421581
21365 const ty = try mod.errorUnionType(error_set_ty, payload_ty);
21582 const ty = try pt.errorUnionType(error_set_ty, payload_ty);
2136621583 return Air.internedToRef(ty.toIntern());
2136721584 },
2136821585 .ErrorSet => {
......@@ -21377,11 +21594,11 @@ fn zirReify(
2137721594 var names: InferredErrorSet.NameMap = .{};
2137821595 try names.ensureUnusedCapacity(sema.arena, len);
2137921596 for (0..len) |i| {
21380 const elem_val = try names_val.elemValue(mod, i);
21597 const elem_val = try names_val.elemValue(pt, i);
2138121598 const elem_struct_type = ip.loadStructType(ip.typeOf(elem_val.toIntern()));
21382 const name_val = try elem_val.fieldValue(mod, elem_struct_type.nameIndex(
21599 const name_val = try elem_val.fieldValue(pt, elem_struct_type.nameIndex(
2138321600 ip,
21384 try ip.getOrPutString(gpa, "name", .no_embedded_nulls),
21601 try ip.getOrPutString(gpa, pt.tid, "name", .no_embedded_nulls),
2138521602 ).?);
2138621603
2138721604 const name = try sema.sliceToIpString(block, src, name_val, .{
......@@ -21396,36 +21613,36 @@ fn zirReify(
2139621613 }
2139721614 }
2139821615
21399 const ty = try mod.errorSetFromUnsortedNames(names.keys());
21616 const ty = try pt.errorSetFromUnsortedNames(names.keys());
2140021617 return Air.internedToRef(ty.toIntern());
2140121618 },
2140221619 .Struct => {
2140321620 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21404 const layout_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21621 const layout_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2140521622 ip,
21406 try ip.getOrPutString(gpa, "layout", .no_embedded_nulls),
21623 try ip.getOrPutString(gpa, pt.tid, "layout", .no_embedded_nulls),
2140721624 ).?);
21408 const backing_integer_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21625 const backing_integer_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2140921626 ip,
21410 try ip.getOrPutString(gpa, "backing_integer", .no_embedded_nulls),
21627 try ip.getOrPutString(gpa, pt.tid, "backing_integer", .no_embedded_nulls),
2141121628 ).?);
21412 const fields_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21629 const fields_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2141321630 ip,
21414 try ip.getOrPutString(gpa, "fields", .no_embedded_nulls),
21631 try ip.getOrPutString(gpa, pt.tid, "fields", .no_embedded_nulls),
2141521632 ).?);
21416 const decls_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21633 const decls_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2141721634 ip,
21418 try ip.getOrPutString(gpa, "decls", .no_embedded_nulls),
21635 try ip.getOrPutString(gpa, pt.tid, "decls", .no_embedded_nulls),
2141921636 ).?);
21420 const is_tuple_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21637 const is_tuple_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2142121638 ip,
21422 try ip.getOrPutString(gpa, "is_tuple", .no_embedded_nulls),
21639 try ip.getOrPutString(gpa, pt.tid, "is_tuple", .no_embedded_nulls),
2142321640 ).?);
2142421641
2142521642 const layout = mod.toEnum(std.builtin.Type.ContainerLayout, layout_val);
2142621643
2142721644 // Decls
21428 if (try decls_val.sliceLen(mod) > 0) {
21645 if (try decls_val.sliceLen(pt) > 0) {
2142921646 return sema.fail(block, src, "reified structs must have no decls", .{});
2143021647 }
2143121648
......@@ -21441,24 +21658,24 @@ fn zirReify(
2144121658 },
2144221659 .Enum => {
2144321660 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21444 const tag_type_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21661 const tag_type_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2144521662 ip,
21446 try ip.getOrPutString(gpa, "tag_type", .no_embedded_nulls),
21663 try ip.getOrPutString(gpa, pt.tid, "tag_type", .no_embedded_nulls),
2144721664 ).?);
21448 const fields_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21665 const fields_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2144921666 ip,
21450 try ip.getOrPutString(gpa, "fields", .no_embedded_nulls),
21667 try ip.getOrPutString(gpa, pt.tid, "fields", .no_embedded_nulls),
2145121668 ).?);
21452 const decls_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21669 const decls_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2145321670 ip,
21454 try ip.getOrPutString(gpa, "decls", .no_embedded_nulls),
21671 try ip.getOrPutString(gpa, pt.tid, "decls", .no_embedded_nulls),
2145521672 ).?);
21456 const is_exhaustive_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21673 const is_exhaustive_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2145721674 ip,
21458 try ip.getOrPutString(gpa, "is_exhaustive", .no_embedded_nulls),
21675 try ip.getOrPutString(gpa, pt.tid, "is_exhaustive", .no_embedded_nulls),
2145921676 ).?);
2146021677
21461 if (try decls_val.sliceLen(mod) > 0) {
21678 if (try decls_val.sliceLen(pt) > 0) {
2146221679 return sema.fail(block, src, "reified enums must have no decls", .{});
2146321680 }
2146421681
......@@ -21470,17 +21687,17 @@ fn zirReify(
2147021687 },
2147121688 .Opaque => {
2147221689 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21473 const decls_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21690 const decls_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2147421691 ip,
21475 try ip.getOrPutString(gpa, "decls", .no_embedded_nulls),
21692 try ip.getOrPutString(gpa, pt.tid, "decls", .no_embedded_nulls),
2147621693 ).?);
2147721694
2147821695 // Decls
21479 if (try decls_val.sliceLen(mod) > 0) {
21696 if (try decls_val.sliceLen(pt) > 0) {
2148021697 return sema.fail(block, src, "reified opaque must have no decls", .{});
2148121698 }
2148221699
21483 const wip_ty = switch (try ip.getOpaqueType(gpa, .{
21700 const wip_ty = switch (try ip.getOpaqueType(gpa, pt.tid, .{
2148421701 .has_namespace = false,
2148521702 .key = .{ .reified = .{
2148621703 .zir_index = try block.trackZir(inst),
......@@ -21489,7 +21706,7 @@ fn zirReify(
2148921706 .existing => |ty| return Air.internedToRef(ty),
2149021707 .wip => |wip| wip,
2149121708 };
21492 errdefer wip_ty.cancel(ip);
21709 errdefer wip_ty.cancel(ip, pt.tid);
2149321710
2149421711 const new_decl_index = try sema.createAnonymousDeclTypeNamed(
2149521712 block,
......@@ -21501,30 +21718,30 @@ fn zirReify(
2150121718 mod.declPtr(new_decl_index).owns_tv = true;
2150221719 errdefer mod.abortAnonDecl(new_decl_index);
2150321720
21504 try mod.finalizeAnonDecl(new_decl_index);
21721 try pt.finalizeAnonDecl(new_decl_index);
2150521722
2150621723 return Air.internedToRef(wip_ty.finish(ip, new_decl_index, .none));
2150721724 },
2150821725 .Union => {
2150921726 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21510 const layout_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21727 const layout_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2151121728 ip,
21512 try ip.getOrPutString(gpa, "layout", .no_embedded_nulls),
21729 try ip.getOrPutString(gpa, pt.tid, "layout", .no_embedded_nulls),
2151321730 ).?);
21514 const tag_type_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21731 const tag_type_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2151521732 ip,
21516 try ip.getOrPutString(gpa, "tag_type", .no_embedded_nulls),
21733 try ip.getOrPutString(gpa, pt.tid, "tag_type", .no_embedded_nulls),
2151721734 ).?);
21518 const fields_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21735 const fields_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2151921736 ip,
21520 try ip.getOrPutString(gpa, "fields", .no_embedded_nulls),
21737 try ip.getOrPutString(gpa, pt.tid, "fields", .no_embedded_nulls),
2152121738 ).?);
21522 const decls_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21739 const decls_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2152321740 ip,
21524 try ip.getOrPutString(gpa, "decls", .no_embedded_nulls),
21741 try ip.getOrPutString(gpa, pt.tid, "decls", .no_embedded_nulls),
2152521742 ).?);
2152621743
21527 if (try decls_val.sliceLen(mod) > 0) {
21744 if (try decls_val.sliceLen(pt) > 0) {
2152821745 return sema.fail(block, src, "reified unions must have no decls", .{});
2152921746 }
2153021747 const layout = mod.toEnum(std.builtin.Type.ContainerLayout, layout_val);
......@@ -21537,25 +21754,25 @@ fn zirReify(
2153721754 },
2153821755 .Fn => {
2153921756 const struct_type = ip.loadStructType(ip.typeOf(union_val.val));
21540 const calling_convention_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21757 const calling_convention_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2154121758 ip,
21542 try ip.getOrPutString(gpa, "calling_convention", .no_embedded_nulls),
21759 try ip.getOrPutString(gpa, pt.tid, "calling_convention", .no_embedded_nulls),
2154321760 ).?);
21544 const is_generic_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21761 const is_generic_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2154521762 ip,
21546 try ip.getOrPutString(gpa, "is_generic", .no_embedded_nulls),
21763 try ip.getOrPutString(gpa, pt.tid, "is_generic", .no_embedded_nulls),
2154721764 ).?);
21548 const is_var_args_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21765 const is_var_args_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2154921766 ip,
21550 try ip.getOrPutString(gpa, "is_var_args", .no_embedded_nulls),
21767 try ip.getOrPutString(gpa, pt.tid, "is_var_args", .no_embedded_nulls),
2155121768 ).?);
21552 const return_type_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21769 const return_type_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2155321770 ip,
21554 try ip.getOrPutString(gpa, "return_type", .no_embedded_nulls),
21771 try ip.getOrPutString(gpa, pt.tid, "return_type", .no_embedded_nulls),
2155521772 ).?);
21556 const params_slice_val = try Value.fromInterned(union_val.val).fieldValue(mod, struct_type.nameIndex(
21773 const params_slice_val = try Value.fromInterned(union_val.val).fieldValue(pt, struct_type.nameIndex(
2155721774 ip,
21558 try ip.getOrPutString(gpa, "params", .no_embedded_nulls),
21775 try ip.getOrPutString(gpa, pt.tid, "params", .no_embedded_nulls),
2155921776 ).?);
2156021777
2156121778 const is_generic = is_generic_val.toBool();
......@@ -21581,19 +21798,19 @@ fn zirReify(
2158121798
2158221799 var noalias_bits: u32 = 0;
2158321800 for (param_types, 0..) |*param_type, i| {
21584 const elem_val = try params_val.elemValue(mod, i);
21801 const elem_val = try params_val.elemValue(pt, i);
2158521802 const elem_struct_type = ip.loadStructType(ip.typeOf(elem_val.toIntern()));
21586 const param_is_generic_val = try elem_val.fieldValue(mod, elem_struct_type.nameIndex(
21803 const param_is_generic_val = try elem_val.fieldValue(pt, elem_struct_type.nameIndex(
2158721804 ip,
21588 try ip.getOrPutString(gpa, "is_generic", .no_embedded_nulls),
21805 try ip.getOrPutString(gpa, pt.tid, "is_generic", .no_embedded_nulls),
2158921806 ).?);
21590 const param_is_noalias_val = try elem_val.fieldValue(mod, elem_struct_type.nameIndex(
21807 const param_is_noalias_val = try elem_val.fieldValue(pt, elem_struct_type.nameIndex(
2159121808 ip,
21592 try ip.getOrPutString(gpa, "is_noalias", .no_embedded_nulls),
21809 try ip.getOrPutString(gpa, pt.tid, "is_noalias", .no_embedded_nulls),
2159321810 ).?);
21594 const opt_param_type_val = try elem_val.fieldValue(mod, elem_struct_type.nameIndex(
21811 const opt_param_type_val = try elem_val.fieldValue(pt, elem_struct_type.nameIndex(
2159521812 ip,
21596 try ip.getOrPutString(gpa, "type", .no_embedded_nulls),
21813 try ip.getOrPutString(gpa, pt.tid, "type", .no_embedded_nulls),
2159721814 ).?);
2159821815
2159921816 if (param_is_generic_val.toBool()) {
......@@ -21613,7 +21830,7 @@ fn zirReify(
2161321830 }
2161421831 }
2161521832
21616 const ty = try mod.funcType(.{
21833 const ty = try pt.funcType(.{
2161721834 .param_types = param_types,
2161821835 .noalias_bits = noalias_bits,
2161921836 .return_type = return_type.toIntern(),
......@@ -21636,7 +21853,8 @@ fn reifyEnum(
2163621853 fields_val: Value,
2163721854 name_strategy: Zir.Inst.NameStrategy,
2163821855) CompileError!Air.Inst.Ref {
21639 const mod = sema.mod;
21856 const pt = sema.pt;
21857 const mod = pt.zcu;
2164021858 const gpa = sema.gpa;
2164121859 const ip = &mod.intern_pool;
2164221860
......@@ -21656,10 +21874,10 @@ fn reifyEnum(
2165621874 std.hash.autoHash(&hasher, fields_len);
2165721875
2165821876 for (0..fields_len) |field_idx| {
21659 const field_info = try fields_val.elemValue(mod, field_idx);
21877 const field_info = try fields_val.elemValue(pt, field_idx);
2166021878
21661 const field_name_val = try field_info.fieldValue(mod, 0);
21662 const field_value_val = try sema.resolveLazyValue(try field_info.fieldValue(mod, 1));
21879 const field_name_val = try field_info.fieldValue(pt, 0);
21880 const field_value_val = try sema.resolveLazyValue(try field_info.fieldValue(pt, 1));
2166321881
2166421882 const field_name = try sema.sliceToIpString(block, src, field_name_val, .{
2166521883 .needed_comptime_reason = "enum field name must be comptime-known",
......@@ -21671,7 +21889,7 @@ fn reifyEnum(
2167121889 });
2167221890 }
2167321891
21674 const wip_ty = switch (try ip.getEnumType(gpa, .{
21892 const wip_ty = switch (try ip.getEnumType(gpa, pt.tid, .{
2167521893 .has_namespace = false,
2167621894 .has_values = true,
2167721895 .tag_mode = if (is_exhaustive) .explicit else .nonexhaustive,
......@@ -21684,7 +21902,7 @@ fn reifyEnum(
2168421902 .wip => |wip| wip,
2168521903 .existing => |ty| return Air.internedToRef(ty),
2168621904 };
21687 errdefer wip_ty.cancel(ip);
21905 errdefer wip_ty.cancel(ip, pt.tid);
2168821906
2168921907 if (tag_ty.zigTypeTag(mod) != .Int) {
2169021908 return sema.fail(block, src, "Type.Enum.tag_type must be an integer type", .{});
......@@ -21704,10 +21922,10 @@ fn reifyEnum(
2170421922 wip_ty.setTagTy(ip, tag_ty.toIntern());
2170521923
2170621924 for (0..fields_len) |field_idx| {
21707 const field_info = try fields_val.elemValue(mod, field_idx);
21925 const field_info = try fields_val.elemValue(pt, field_idx);
2170821926
21709 const field_name_val = try field_info.fieldValue(mod, 0);
21710 const field_value_val = try sema.resolveLazyValue(try field_info.fieldValue(mod, 1));
21927 const field_name_val = try field_info.fieldValue(pt, 0);
21928 const field_value_val = try sema.resolveLazyValue(try field_info.fieldValue(pt, 1));
2171121929
2171221930 // Don't pass a reason; first loop acts as an assertion that this is valid.
2171321931 const field_name = try sema.sliceToIpString(block, src, field_name_val, undefined);
......@@ -21716,12 +21934,12 @@ fn reifyEnum(
2171621934 // TODO: better source location
2171721935 return sema.fail(block, src, "field '{}' with enumeration value '{}' is too large for backing int type '{}'", .{
2171821936 field_name.fmt(ip),
21719 field_value_val.fmtValue(mod, sema),
21720 tag_ty.fmt(mod),
21937 field_value_val.fmtValue(pt, sema),
21938 tag_ty.fmt(pt),
2172121939 });
2172221940 }
2172321941
21724 const coerced_field_val = try mod.getCoerced(field_value_val, tag_ty);
21942 const coerced_field_val = try pt.getCoerced(field_value_val, tag_ty);
2172521943 if (wip_ty.nextField(ip, field_name, coerced_field_val.toIntern())) |conflict| {
2172621944 return sema.failWithOwnedErrorMsg(block, switch (conflict.kind) {
2172721945 .name => msg: {
......@@ -21732,7 +21950,7 @@ fn reifyEnum(
2173221950 break :msg msg;
2173321951 },
2173421952 .value => msg: {
21735 const msg = try sema.errMsg(src, "enum tag value {} already taken", .{field_value_val.fmtValue(mod, sema)});
21953 const msg = try sema.errMsg(src, "enum tag value {} already taken", .{field_value_val.fmtValue(pt, sema)});
2173621954 errdefer msg.destroy(gpa);
2173721955 _ = conflict.prev_field_idx; // TODO: this note is incorrect
2173821956 try sema.errNote(src, msg, "other enum tag value here", .{});
......@@ -21742,11 +21960,11 @@ fn reifyEnum(
2174221960 }
2174321961 }
2174421962
21745 if (!is_exhaustive and fields_len > 1 and std.math.log2_int(u64, fields_len) == tag_ty.bitSize(mod)) {
21963 if (!is_exhaustive and fields_len > 1 and std.math.log2_int(u64, fields_len) == tag_ty.bitSize(pt)) {
2174621964 return sema.fail(block, src, "non-exhaustive enum specified every value", .{});
2174721965 }
2174821966
21749 try mod.finalizeAnonDecl(new_decl_index);
21967 try pt.finalizeAnonDecl(new_decl_index);
2175021968 return Air.internedToRef(wip_ty.index);
2175121969}
2175221970
......@@ -21760,7 +21978,8 @@ fn reifyUnion(
2176021978 fields_val: Value,
2176121979 name_strategy: Zir.Inst.NameStrategy,
2176221980) CompileError!Air.Inst.Ref {
21763 const mod = sema.mod;
21981 const pt = sema.pt;
21982 const mod = pt.zcu;
2176421983 const gpa = sema.gpa;
2176521984 const ip = &mod.intern_pool;
2176621985
......@@ -21782,11 +22001,11 @@ fn reifyUnion(
2178222001 var any_aligns = false;
2178322002
2178422003 for (0..fields_len) |field_idx| {
21785 const field_info = try fields_val.elemValue(mod, field_idx);
22004 const field_info = try fields_val.elemValue(pt, field_idx);
2178622005
21787 const field_name_val = try field_info.fieldValue(mod, 0);
21788 const field_type_val = try field_info.fieldValue(mod, 1);
21789 const field_align_val = try sema.resolveLazyValue(try field_info.fieldValue(mod, 2));
22006 const field_name_val = try field_info.fieldValue(pt, 0);
22007 const field_type_val = try field_info.fieldValue(pt, 1);
22008 const field_align_val = try sema.resolveLazyValue(try field_info.fieldValue(pt, 2));
2179022009
2179122010 const field_name = try sema.sliceToIpString(block, src, field_name_val, .{
2179222011 .needed_comptime_reason = "union field name must be comptime-known",
......@@ -21798,12 +22017,12 @@ fn reifyUnion(
2179822017 field_align_val.toIntern(),
2179922018 });
2180022019
21801 if (field_align_val.toUnsignedInt(mod) != 0) {
22020 if (field_align_val.toUnsignedInt(pt) != 0) {
2180222021 any_aligns = true;
2180322022 }
2180422023 }
2180522024
21806 const wip_ty = switch (try ip.getUnionType(gpa, .{
22025 const wip_ty = switch (try ip.getUnionType(gpa, pt.tid, .{
2180722026 .flags = .{
2180822027 .layout = layout,
2180922028 .status = .none,
......@@ -21834,7 +22053,7 @@ fn reifyUnion(
2183422053 .wip => |wip| wip,
2183522054 .existing => |ty| return Air.internedToRef(ty),
2183622055 };
21837 errdefer wip_ty.cancel(ip);
22056 errdefer wip_ty.cancel(ip, pt.tid);
2183822057
2183922058 const new_decl_index = try sema.createAnonymousDeclTypeNamed(
2184022059 block,
......@@ -21861,10 +22080,10 @@ fn reifyUnion(
2186122080 var seen_tags = try std.DynamicBitSetUnmanaged.initEmpty(sema.arena, tag_ty_fields_len);
2186222081
2186322082 for (field_types, 0..) |*field_ty, field_idx| {
21864 const field_info = try fields_val.elemValue(mod, field_idx);
22083 const field_info = try fields_val.elemValue(pt, field_idx);
2186522084
21866 const field_name_val = try field_info.fieldValue(mod, 0);
21867 const field_type_val = try field_info.fieldValue(mod, 1);
22085 const field_name_val = try field_info.fieldValue(pt, 0);
22086 const field_type_val = try field_info.fieldValue(pt, 1);
2186822087
2186922088 // Don't pass a reason; first loop acts as an assertion that this is valid.
2187022089 const field_name = try sema.sliceToIpString(block, src, field_name_val, undefined);
......@@ -21872,7 +22091,7 @@ fn reifyUnion(
2187222091 const enum_index = enum_tag_ty.enumFieldIndex(field_name, mod) orelse {
2187322092 // TODO: better source location
2187422093 return sema.fail(block, src, "no field named '{}' in enum '{}'", .{
21875 field_name.fmt(ip), enum_tag_ty.fmt(mod),
22094 field_name.fmt(ip), enum_tag_ty.fmt(pt),
2187622095 });
2187722096 };
2187822097 if (seen_tags.isSet(enum_index)) {
......@@ -21883,7 +22102,7 @@ fn reifyUnion(
2188322102
2188422103 field_ty.* = field_type_val.toIntern();
2188522104 if (any_aligns) {
21886 const byte_align = try (try field_info.fieldValue(mod, 2)).toUnsignedIntSema(mod);
22105 const byte_align = try (try field_info.fieldValue(pt, 2)).toUnsignedIntSema(pt);
2188722106 if (byte_align > 0 and !math.isPowerOfTwo(byte_align)) {
2188822107 // TODO: better source location
2188922108 return sema.fail(block, src, "alignment value '{d}' is not a power of two or zero", .{byte_align});
......@@ -21913,10 +22132,10 @@ fn reifyUnion(
2191322132 try field_names.ensureTotalCapacity(sema.arena, fields_len);
2191422133
2191522134 for (field_types, 0..) |*field_ty, field_idx| {
21916 const field_info = try fields_val.elemValue(mod, field_idx);
22135 const field_info = try fields_val.elemValue(pt, field_idx);
2191722136
21918 const field_name_val = try field_info.fieldValue(mod, 0);
21919 const field_type_val = try field_info.fieldValue(mod, 1);
22137 const field_name_val = try field_info.fieldValue(pt, 0);
22138 const field_type_val = try field_info.fieldValue(pt, 1);
2192022139
2192122140 // Don't pass a reason; first loop acts as an assertion that this is valid.
2192222141 const field_name = try sema.sliceToIpString(block, src, field_name_val, undefined);
......@@ -21928,7 +22147,7 @@ fn reifyUnion(
2192822147
2192922148 field_ty.* = field_type_val.toIntern();
2193022149 if (any_aligns) {
21931 const byte_align = try (try field_info.fieldValue(mod, 2)).toUnsignedIntSema(mod);
22150 const byte_align = try (try field_info.fieldValue(pt, 2)).toUnsignedIntSema(pt);
2193222151 if (byte_align > 0 and !math.isPowerOfTwo(byte_align)) {
2193322152 // TODO: better source location
2193422153 return sema.fail(block, src, "alignment value '{d}' is not a power of two or zero", .{byte_align});
......@@ -21940,7 +22159,7 @@ fn reifyUnion(
2194022159 const enum_tag_ty = try sema.generateUnionTagTypeSimple(block, field_names.keys(), mod.declPtr(new_decl_index));
2194122160 break :tag_ty .{ enum_tag_ty, false };
2194222161 };
21943 errdefer if (!has_explicit_tag) ip.remove(enum_tag_ty); // remove generated tag type on error
22162 errdefer if (!has_explicit_tag) ip.remove(pt.tid, enum_tag_ty); // remove generated tag type on error
2194422163
2194522164 for (field_types) |field_ty_ip| {
2194622165 const field_ty = Type.fromInterned(field_ty_ip);
......@@ -21955,7 +22174,7 @@ fn reifyUnion(
2195522174 }
2195622175 if (layout == .@"extern" and !try sema.validateExternType(field_ty, .union_field)) {
2195722176 return sema.failWithOwnedErrorMsg(block, msg: {
21958 const msg = try sema.errMsg(src, "extern unions cannot contain fields of type '{}'", .{field_ty.fmt(mod)});
22177 const msg = try sema.errMsg(src, "extern unions cannot contain fields of type '{}'", .{field_ty.fmt(pt)});
2195922178 errdefer msg.destroy(gpa);
2196022179
2196122180 try sema.explainWhyTypeIsNotExtern(msg, src, field_ty, .union_field);
......@@ -21965,7 +22184,7 @@ fn reifyUnion(
2196522184 });
2196622185 } else if (layout == .@"packed" and !try sema.validatePackedType(field_ty)) {
2196722186 return sema.failWithOwnedErrorMsg(block, msg: {
21968 const msg = try sema.errMsg(src, "packed unions cannot contain fields of type '{}'", .{field_ty.fmt(mod)});
22187 const msg = try sema.errMsg(src, "packed unions cannot contain fields of type '{}'", .{field_ty.fmt(pt)});
2196922188 errdefer msg.destroy(gpa);
2197022189
2197122190 try sema.explainWhyTypeIsNotPacked(msg, src, field_ty);
......@@ -21984,7 +22203,7 @@ fn reifyUnion(
2198422203 loaded_union.tagTypePtr(ip).* = enum_tag_ty;
2198522204 loaded_union.flagsPtr(ip).status = .have_field_types;
2198622205
21987 try mod.finalizeAnonDecl(new_decl_index);
22206 try pt.finalizeAnonDecl(new_decl_index);
2198822207 try mod.comp.work_queue.writeItem(.{ .resolve_type_fully = wip_ty.index });
2198922208 try sema.addReferenceEntry(src, AnalUnit.wrap(.{ .decl = new_decl_index }));
2199022209 return Air.internedToRef(wip_ty.finish(ip, new_decl_index, .none));
......@@ -22001,7 +22220,8 @@ fn reifyStruct(
2200122220 name_strategy: Zir.Inst.NameStrategy,
2200222221 is_tuple: bool,
2200322222) CompileError!Air.Inst.Ref {
22004 const mod = sema.mod;
22223 const pt = sema.pt;
22224 const mod = pt.zcu;
2200522225 const gpa = sema.gpa;
2200622226 const ip = &mod.intern_pool;
2200722227
......@@ -22026,20 +22246,20 @@ fn reifyStruct(
2202622246 var any_aligned_fields = false;
2202722247
2202822248 for (0..fields_len) |field_idx| {
22029 const field_info = try fields_val.elemValue(mod, field_idx);
22249 const field_info = try fields_val.elemValue(pt, field_idx);
2203022250
22031 const field_name_val = try field_info.fieldValue(mod, 0);
22032 const field_type_val = try field_info.fieldValue(mod, 1);
22033 const field_default_value_val = try field_info.fieldValue(mod, 2);
22034 const field_is_comptime_val = try field_info.fieldValue(mod, 3);
22035 const field_alignment_val = try sema.resolveLazyValue(try field_info.fieldValue(mod, 4));
22251 const field_name_val = try field_info.fieldValue(pt, 0);
22252 const field_type_val = try field_info.fieldValue(pt, 1);
22253 const field_default_value_val = try field_info.fieldValue(pt, 2);
22254 const field_is_comptime_val = try field_info.fieldValue(pt, 3);
22255 const field_alignment_val = try sema.resolveLazyValue(try field_info.fieldValue(pt, 4));
2203622256
2203722257 const field_name = try sema.sliceToIpString(block, src, field_name_val, .{
2203822258 .needed_comptime_reason = "struct field name must be comptime-known",
2203922259 });
2204022260 const field_is_comptime = field_is_comptime_val.toBool();
2204122261 const field_default_value: InternPool.Index = if (field_default_value_val.optionalValue(mod)) |ptr_val| d: {
22042 const ptr_ty = try mod.singleConstPtrType(field_type_val.toType());
22262 const ptr_ty = try pt.singleConstPtrType(field_type_val.toType());
2204322263 // We need to do this deref here, so we won't check for this error case later on.
2204422264 const val = try sema.pointerDeref(block, src, ptr_val, ptr_ty) orelse return sema.failWithNeededComptime(
2204522265 block,
......@@ -22060,14 +22280,14 @@ fn reifyStruct(
2206022280
2206122281 if (field_is_comptime) any_comptime_fields = true;
2206222282 if (field_default_value != .none) any_default_inits = true;
22063 switch (try field_alignment_val.orderAgainstZeroAdvanced(mod, .sema)) {
22283 switch (try field_alignment_val.orderAgainstZeroAdvanced(pt, .sema)) {
2206422284 .eq => {},
2206522285 .gt => any_aligned_fields = true,
2206622286 .lt => unreachable,
2206722287 }
2206822288 }
2206922289
22070 const wip_ty = switch (try ip.getStructType(gpa, .{
22290 const wip_ty = switch (try ip.getStructType(gpa, pt.tid, .{
2207122291 .layout = layout,
2207222292 .fields_len = fields_len,
2207322293 .known_non_opv = false,
......@@ -22086,7 +22306,7 @@ fn reifyStruct(
2208622306 .wip => |wip| wip,
2208722307 .existing => |ty| return Air.internedToRef(ty),
2208822308 };
22089 errdefer wip_ty.cancel(ip);
22309 errdefer wip_ty.cancel(ip, pt.tid);
2209022310
2209122311 if (is_tuple) switch (layout) {
2209222312 .@"extern" => return sema.fail(block, src, "extern tuples are not supported", .{}),
......@@ -22107,13 +22327,13 @@ fn reifyStruct(
2210722327 const struct_type = ip.loadStructType(wip_ty.index);
2210822328
2210922329 for (0..fields_len) |field_idx| {
22110 const field_info = try fields_val.elemValue(mod, field_idx);
22330 const field_info = try fields_val.elemValue(pt, field_idx);
2211122331
22112 const field_name_val = try field_info.fieldValue(mod, 0);
22113 const field_type_val = try field_info.fieldValue(mod, 1);
22114 const field_default_value_val = try field_info.fieldValue(mod, 2);
22115 const field_is_comptime_val = try field_info.fieldValue(mod, 3);
22116 const field_alignment_val = try field_info.fieldValue(mod, 4);
22332 const field_name_val = try field_info.fieldValue(pt, 0);
22333 const field_type_val = try field_info.fieldValue(pt, 1);
22334 const field_default_value_val = try field_info.fieldValue(pt, 2);
22335 const field_is_comptime_val = try field_info.fieldValue(pt, 3);
22336 const field_alignment_val = try field_info.fieldValue(pt, 4);
2211722337
2211822338 const field_ty = field_type_val.toType();
2211922339 // Don't pass a reason; first loop acts as an assertion that this is valid.
......@@ -22143,7 +22363,7 @@ fn reifyStruct(
2214322363 return sema.fail(block, src, "alignment must fit in 'u32'", .{});
2214422364 }
2214522365
22146 const byte_align = try field_alignment_val.toUnsignedIntSema(mod);
22366 const byte_align = try field_alignment_val.toUnsignedIntSema(pt);
2214722367 if (byte_align == 0) {
2214822368 if (layout != .@"packed") {
2214922369 struct_type.field_aligns.get(ip)[field_idx] = .none;
......@@ -22168,7 +22388,7 @@ fn reifyStruct(
2216822388 const field_default: InternPool.Index = d: {
2216922389 if (!any_default_inits) break :d .none;
2217022390 const ptr_val = field_default_value_val.optionalValue(mod) orelse break :d .none;
22171 const ptr_ty = try mod.singleConstPtrType(field_ty);
22391 const ptr_ty = try pt.singleConstPtrType(field_ty);
2217222392 // Asserted comptime-dereferencable above.
2217322393 const val = (try sema.pointerDeref(block, src, ptr_val, ptr_ty)).?;
2217422394 // We already resolved this for deduplication, so we may as well do it now.
......@@ -22204,7 +22424,7 @@ fn reifyStruct(
2220422424 }
2220522425 if (layout == .@"extern" and !try sema.validateExternType(field_ty, .struct_field)) {
2220622426 return sema.failWithOwnedErrorMsg(block, msg: {
22207 const msg = try sema.errMsg(src, "extern structs cannot contain fields of type '{}'", .{field_ty.fmt(sema.mod)});
22427 const msg = try sema.errMsg(src, "extern structs cannot contain fields of type '{}'", .{field_ty.fmt(pt)});
2220822428 errdefer msg.destroy(gpa);
2220922429
2221022430 try sema.explainWhyTypeIsNotExtern(msg, src, field_ty, .struct_field);
......@@ -22214,7 +22434,7 @@ fn reifyStruct(
2221422434 });
2221522435 } else if (layout == .@"packed" and !try sema.validatePackedType(field_ty)) {
2221622436 return sema.failWithOwnedErrorMsg(block, msg: {
22217 const msg = try sema.errMsg(src, "packed structs cannot contain fields of type '{}'", .{field_ty.fmt(sema.mod)});
22437 const msg = try sema.errMsg(src, "packed structs cannot contain fields of type '{}'", .{field_ty.fmt(pt)});
2221822438 errdefer msg.destroy(gpa);
2221922439
2222022440 try sema.explainWhyTypeIsNotPacked(msg, src, field_ty);
......@@ -22229,7 +22449,7 @@ fn reifyStruct(
2222922449 var fields_bit_sum: u64 = 0;
2223022450 for (0..struct_type.field_types.len) |field_idx| {
2223122451 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_idx]);
22232 field_ty.resolveLayout(mod) catch |err| switch (err) {
22452 field_ty.resolveLayout(pt) catch |err| switch (err) {
2223322453 error.AnalysisFail => {
2223422454 const msg = sema.err orelse return err;
2223522455 try sema.errNote(src, msg, "while checking a field of this struct", .{});
......@@ -22237,7 +22457,7 @@ fn reifyStruct(
2223722457 },
2223822458 else => return err,
2223922459 };
22240 fields_bit_sum += field_ty.bitSize(mod);
22460 fields_bit_sum += field_ty.bitSize(pt);
2224122461 }
2224222462
2224322463 if (opt_backing_int_val.optionalValue(mod)) |backing_int_val| {
......@@ -22245,20 +22465,21 @@ fn reifyStruct(
2224522465 try sema.checkBackingIntType(block, src, backing_int_ty, fields_bit_sum);
2224622466 struct_type.backingIntType(ip).* = backing_int_ty.toIntern();
2224722467 } else {
22248 const backing_int_ty = try mod.intType(.unsigned, @intCast(fields_bit_sum));
22468 const backing_int_ty = try pt.intType(.unsigned, @intCast(fields_bit_sum));
2224922469 struct_type.backingIntType(ip).* = backing_int_ty.toIntern();
2225022470 }
2225122471 }
2225222472
22253 try mod.finalizeAnonDecl(new_decl_index);
22473 try pt.finalizeAnonDecl(new_decl_index);
2225422474 try mod.comp.work_queue.writeItem(.{ .resolve_type_fully = wip_ty.index });
2225522475 try sema.addReferenceEntry(src, AnalUnit.wrap(.{ .decl = new_decl_index }));
2225622476 return Air.internedToRef(wip_ty.finish(ip, new_decl_index, .none));
2225722477}
2225822478
2225922479fn resolveVaListRef(sema: *Sema, block: *Block, src: LazySrcLoc, zir_ref: Zir.Inst.Ref) CompileError!Air.Inst.Ref {
22260 const va_list_ty = try sema.mod.getBuiltinType("VaList");
22261 const va_list_ptr = try sema.mod.singleMutPtrType(va_list_ty);
22480 const pt = sema.pt;
22481 const va_list_ty = try pt.getBuiltinType("VaList");
22482 const va_list_ptr = try pt.singleMutPtrType(va_list_ty);
2226222483
2226322484 const inst = try sema.resolveInst(zir_ref);
2226422485 return sema.coerce(block, va_list_ptr, inst, src);
......@@ -22275,7 +22496,7 @@ fn zirCVaArg(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) C
2227522496
2227622497 if (!try sema.validateExternType(arg_ty, .param_ty)) {
2227722498 const msg = msg: {
22278 const msg = try sema.errMsg(ty_src, "cannot get '{}' from variadic argument", .{arg_ty.fmt(sema.mod)});
22499 const msg = try sema.errMsg(ty_src, "cannot get '{}' from variadic argument", .{arg_ty.fmt(sema.pt)});
2227922500 errdefer msg.destroy(sema.gpa);
2228022501
2228122502 try sema.explainWhyTypeIsNotExtern(msg, ty_src, arg_ty, .param_ty);
......@@ -22296,7 +22517,7 @@ fn zirCVaCopy(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData)
2229622517 const va_list_src = block.builtinCallArgSrc(extra.node, 0);
2229722518
2229822519 const va_list_ref = try sema.resolveVaListRef(block, va_list_src, extra.operand);
22299 const va_list_ty = try sema.mod.getBuiltinType("VaList");
22520 const va_list_ty = try sema.pt.getBuiltinType("VaList");
2230022521
2230122522 try sema.requireRuntimeBlock(block, src, null);
2230222523 return block.addTyOp(.c_va_copy, va_list_ty, va_list_ref);
......@@ -22316,7 +22537,7 @@ fn zirCVaEnd(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) C
2231622537fn zirCVaStart(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
2231722538 const src = block.nodeOffset(@bitCast(extended.operand));
2231822539
22319 const va_list_ty = try sema.mod.getBuiltinType("VaList");
22540 const va_list_ty = try sema.pt.getBuiltinType("VaList");
2232022541 try sema.requireRuntimeBlock(block, src, null);
2232122542 return block.addInst(.{
2232222543 .tag = .c_va_start,
......@@ -22325,14 +22546,15 @@ fn zirCVaStart(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData)
2232522546}
2232622547
2232722548fn zirTypeName(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
22328 const mod = sema.mod;
22549 const pt = sema.pt;
22550 const mod = pt.zcu;
2232922551 const ip = &mod.intern_pool;
2233022552
2233122553 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
2233222554 const ty_src = block.builtinCallArgSrc(inst_data.src_node, 0);
2233322555 const ty = try sema.resolveType(block, ty_src, inst_data.operand);
2233422556
22335 const type_name = try ip.getOrPutStringFmt(sema.gpa, "{}", .{ty.fmt(mod)}, .no_embedded_nulls);
22557 const type_name = try ip.getOrPutStringFmt(sema.gpa, pt.tid, "{}", .{ty.fmt(pt)}, .no_embedded_nulls);
2233622558 return sema.addNullTerminatedStrLit(type_name);
2233722559}
2233822560
......@@ -22349,7 +22571,8 @@ fn zirFrameSize(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
2234922571}
2235022572
2235122573fn zirIntFromFloat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
22352 const mod = sema.mod;
22574 const pt = sema.pt;
22575 const mod = pt.zcu;
2235322576 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2235422577 const src = block.nodeOffset(inst_data.src_node);
2235522578 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
......@@ -22380,23 +22603,23 @@ fn zirIntFromFloat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
2238022603 if (dest_scalar_ty.intInfo(mod).bits == 0) {
2238122604 if (!is_vector) {
2238222605 if (block.wantSafety()) {
22383 const ok = try block.addBinOp(if (block.float_mode == .optimized) .cmp_eq_optimized else .cmp_eq, operand, Air.internedToRef((try mod.floatValue(operand_ty, 0.0)).toIntern()));
22606 const ok = try block.addBinOp(if (block.float_mode == .optimized) .cmp_eq_optimized else .cmp_eq, operand, Air.internedToRef((try pt.floatValue(operand_ty, 0.0)).toIntern()));
2238422607 try sema.addSafetyCheck(block, src, ok, .integer_part_out_of_bounds);
2238522608 }
22386 return Air.internedToRef((try mod.intValue(dest_ty, 0)).toIntern());
22609 return Air.internedToRef((try pt.intValue(dest_ty, 0)).toIntern());
2238722610 }
2238822611 if (block.wantSafety()) {
2238922612 const len = dest_ty.vectorLen(mod);
2239022613 for (0..len) |i| {
22391 const idx_ref = try mod.intRef(Type.usize, i);
22614 const idx_ref = try pt.intRef(Type.usize, i);
2239222615 const elem_ref = try block.addBinOp(.array_elem_val, operand, idx_ref);
22393 const ok = try block.addBinOp(if (block.float_mode == .optimized) .cmp_eq_optimized else .cmp_eq, elem_ref, Air.internedToRef((try mod.floatValue(operand_scalar_ty, 0.0)).toIntern()));
22616 const ok = try block.addBinOp(if (block.float_mode == .optimized) .cmp_eq_optimized else .cmp_eq, elem_ref, Air.internedToRef((try pt.floatValue(operand_scalar_ty, 0.0)).toIntern()));
2239422617 try sema.addSafetyCheck(block, src, ok, .integer_part_out_of_bounds);
2239522618 }
2239622619 }
22397 return Air.internedToRef(try mod.intern(.{ .aggregate = .{
22620 return Air.internedToRef(try pt.intern(.{ .aggregate = .{
2239822621 .ty = dest_ty.toIntern(),
22399 .storage = .{ .repeated_elem = (try mod.intValue(dest_scalar_ty, 0)).toIntern() },
22622 .storage = .{ .repeated_elem = (try pt.intValue(dest_scalar_ty, 0)).toIntern() },
2240022623 } }));
2240122624 }
2240222625 if (!is_vector) {
......@@ -22404,8 +22627,8 @@ fn zirIntFromFloat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
2240422627 if (block.wantSafety()) {
2240522628 const back = try block.addTyOp(.float_from_int, operand_ty, result);
2240622629 const diff = try block.addBinOp(.sub, operand, back);
22407 const ok_pos = try block.addBinOp(if (block.float_mode == .optimized) .cmp_lt_optimized else .cmp_lt, diff, Air.internedToRef((try mod.floatValue(operand_ty, 1.0)).toIntern()));
22408 const ok_neg = try block.addBinOp(if (block.float_mode == .optimized) .cmp_gt_optimized else .cmp_gt, diff, Air.internedToRef((try mod.floatValue(operand_ty, -1.0)).toIntern()));
22630 const ok_pos = try block.addBinOp(if (block.float_mode == .optimized) .cmp_lt_optimized else .cmp_lt, diff, Air.internedToRef((try pt.floatValue(operand_ty, 1.0)).toIntern()));
22631 const ok_neg = try block.addBinOp(if (block.float_mode == .optimized) .cmp_gt_optimized else .cmp_gt, diff, Air.internedToRef((try pt.floatValue(operand_ty, -1.0)).toIntern()));
2240922632 const ok = try block.addBinOp(.bool_and, ok_pos, ok_neg);
2241022633 try sema.addSafetyCheck(block, src, ok, .integer_part_out_of_bounds);
2241122634 }
......@@ -22414,14 +22637,14 @@ fn zirIntFromFloat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
2241422637 const len = dest_ty.vectorLen(mod);
2241522638 const new_elems = try sema.arena.alloc(Air.Inst.Ref, len);
2241622639 for (new_elems, 0..) |*new_elem, i| {
22417 const idx_ref = try mod.intRef(Type.usize, i);
22640 const idx_ref = try pt.intRef(Type.usize, i);
2241822641 const old_elem = try block.addBinOp(.array_elem_val, operand, idx_ref);
2241922642 const result = try block.addTyOp(if (block.float_mode == .optimized) .int_from_float_optimized else .int_from_float, dest_scalar_ty, old_elem);
2242022643 if (block.wantSafety()) {
2242122644 const back = try block.addTyOp(.float_from_int, operand_scalar_ty, result);
2242222645 const diff = try block.addBinOp(.sub, old_elem, back);
22423 const ok_pos = try block.addBinOp(if (block.float_mode == .optimized) .cmp_lt_optimized else .cmp_lt, diff, Air.internedToRef((try mod.floatValue(operand_scalar_ty, 1.0)).toIntern()));
22424 const ok_neg = try block.addBinOp(if (block.float_mode == .optimized) .cmp_gt_optimized else .cmp_gt, diff, Air.internedToRef((try mod.floatValue(operand_scalar_ty, -1.0)).toIntern()));
22646 const ok_pos = try block.addBinOp(if (block.float_mode == .optimized) .cmp_lt_optimized else .cmp_lt, diff, Air.internedToRef((try pt.floatValue(operand_scalar_ty, 1.0)).toIntern()));
22647 const ok_neg = try block.addBinOp(if (block.float_mode == .optimized) .cmp_gt_optimized else .cmp_gt, diff, Air.internedToRef((try pt.floatValue(operand_scalar_ty, -1.0)).toIntern()));
2242522648 const ok = try block.addBinOp(.bool_and, ok_pos, ok_neg);
2242622649 try sema.addSafetyCheck(block, src, ok, .integer_part_out_of_bounds);
2242722650 }
......@@ -22431,7 +22654,8 @@ fn zirIntFromFloat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
2243122654}
2243222655
2243322656fn zirFloatFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
22434 const mod = sema.mod;
22657 const pt = sema.pt;
22658 const mod = pt.zcu;
2243522659 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2243622660 const src = block.nodeOffset(inst_data.src_node);
2243722661 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
......@@ -22450,7 +22674,7 @@ fn zirFloatFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
2245022674 _ = try sema.checkIntType(block, operand_src, operand_scalar_ty);
2245122675
2245222676 if (try sema.resolveValue(operand)) |operand_val| {
22453 const result_val = try operand_val.floatFromIntAdvanced(sema.arena, operand_ty, dest_ty, mod, .sema);
22677 const result_val = try operand_val.floatFromIntAdvanced(sema.arena, operand_ty, dest_ty, pt, .sema);
2245422678 return Air.internedToRef(result_val.toIntern());
2245522679 } else if (dest_scalar_ty.zigTypeTag(mod) == .ComptimeFloat) {
2245622680 return sema.failWithNeededComptime(block, operand_src, .{
......@@ -22465,7 +22689,7 @@ fn zirFloatFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
2246522689 const len = operand_ty.vectorLen(mod);
2246622690 const new_elems = try sema.arena.alloc(Air.Inst.Ref, len);
2246722691 for (new_elems, 0..) |*new_elem, i| {
22468 const idx_ref = try mod.intRef(Type.usize, i);
22692 const idx_ref = try pt.intRef(Type.usize, i);
2246922693 const old_elem = try block.addBinOp(.array_elem_val, operand, idx_ref);
2247022694 new_elem.* = try block.addTyOp(.float_from_int, dest_scalar_ty, old_elem);
2247122695 }
......@@ -22473,7 +22697,8 @@ fn zirFloatFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileErro
2247322697}
2247422698
2247522699fn zirPtrFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
22476 const mod = sema.mod;
22700 const pt = sema.pt;
22701 const mod = pt.zcu;
2247722702 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2247822703 const src = block.nodeOffset(inst_data.src_node);
2247922704
......@@ -22489,7 +22714,7 @@ fn zirPtrFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2248922714 const is_vector = dest_ty.zigTypeTag(mod) == .Vector;
2249022715 const operand_ty = if (is_vector) operand_ty: {
2249122716 const len = dest_ty.vectorLen(mod);
22492 break :operand_ty try mod.vectorType(.{ .child = .usize_type, .len = len });
22717 break :operand_ty try pt.vectorType(.{ .child = .usize_type, .len = len });
2249322718 } else Type.usize;
2249422719
2249522720 const operand_coerced = try sema.coerce(block, operand_ty, operand_res, operand_src);
......@@ -22498,11 +22723,11 @@ fn zirPtrFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2249822723 try sema.checkPtrType(block, src, ptr_ty, true);
2249922724
2250022725 const elem_ty = ptr_ty.elemType2(mod);
22501 const ptr_align = try ptr_ty.ptrAlignmentAdvanced(mod, .sema);
22726 const ptr_align = try ptr_ty.ptrAlignmentAdvanced(pt, .sema);
2250222727
2250322728 if (ptr_ty.isSlice(mod)) {
2250422729 const msg = msg: {
22505 const msg = try sema.errMsg(src, "integer cannot be converted to slice type '{}'", .{ptr_ty.fmt(sema.mod)});
22730 const msg = try sema.errMsg(src, "integer cannot be converted to slice type '{}'", .{ptr_ty.fmt(pt)});
2250622731 errdefer msg.destroy(sema.gpa);
2250722732 try sema.errNote(src, msg, "slice length cannot be inferred from address", .{});
2250822733 break :msg msg;
......@@ -22518,18 +22743,18 @@ fn zirPtrFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2251822743 const len = dest_ty.vectorLen(mod);
2251922744 const new_elems = try sema.arena.alloc(InternPool.Index, len);
2252022745 for (new_elems, 0..) |*new_elem, i| {
22521 const elem = try val.elemValue(mod, i);
22746 const elem = try val.elemValue(pt, i);
2252222747 const ptr_val = try sema.ptrFromIntVal(block, operand_src, elem, ptr_ty, ptr_align);
2252322748 new_elem.* = ptr_val.toIntern();
2252422749 }
22525 return Air.internedToRef(try mod.intern(.{ .aggregate = .{
22750 return Air.internedToRef(try pt.intern(.{ .aggregate = .{
2252622751 .ty = dest_ty.toIntern(),
2252722752 .storage = .{ .elems = new_elems },
2252822753 } }));
2252922754 }
2253022755 if (try sema.typeRequiresComptime(ptr_ty)) {
2253122756 return sema.failWithOwnedErrorMsg(block, msg: {
22532 const msg = try sema.errMsg(src, "pointer to comptime-only type '{}' must be comptime-known, but operand is runtime-known", .{ptr_ty.fmt(mod)});
22757 const msg = try sema.errMsg(src, "pointer to comptime-only type '{}' must be comptime-known, but operand is runtime-known", .{ptr_ty.fmt(pt)});
2253322758 errdefer msg.destroy(sema.gpa);
2253422759
2253522760 try sema.explainWhyTypeIsComptime(msg, src, ptr_ty);
......@@ -22545,7 +22770,7 @@ fn zirPtrFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2254522770 }
2254622771 if (ptr_align.compare(.gt, .@"1")) {
2254722772 const align_bytes_minus_1 = ptr_align.toByteUnits().? - 1;
22548 const align_minus_1 = Air.internedToRef((try mod.intValue(Type.usize, align_bytes_minus_1)).toIntern());
22773 const align_minus_1 = Air.internedToRef((try pt.intValue(Type.usize, align_bytes_minus_1)).toIntern());
2254922774 const remainder = try block.addBinOp(.bit_and, operand_coerced, align_minus_1);
2255022775 const is_aligned = try block.addBinOp(.cmp_eq, remainder, .zero_usize);
2255122776 try sema.addSafetyCheck(block, src, is_aligned, .incorrect_alignment);
......@@ -22557,7 +22782,7 @@ fn zirPtrFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2255722782 const len = dest_ty.vectorLen(mod);
2255822783 if (block.wantSafety() and (try sema.typeHasRuntimeBits(elem_ty) or elem_ty.zigTypeTag(mod) == .Fn)) {
2255922784 for (0..len) |i| {
22560 const idx_ref = try mod.intRef(Type.usize, i);
22785 const idx_ref = try pt.intRef(Type.usize, i);
2256122786 const elem_coerced = try block.addBinOp(.array_elem_val, operand_coerced, idx_ref);
2256222787 if (!ptr_ty.isAllowzeroPtr(mod)) {
2256322788 const is_non_zero = try block.addBinOp(.cmp_neq, elem_coerced, .zero_usize);
......@@ -22565,7 +22790,7 @@ fn zirPtrFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2256522790 }
2256622791 if (ptr_align.compare(.gt, .@"1")) {
2256722792 const align_bytes_minus_1 = ptr_align.toByteUnits().? - 1;
22568 const align_minus_1 = Air.internedToRef((try mod.intValue(Type.usize, align_bytes_minus_1)).toIntern());
22793 const align_minus_1 = Air.internedToRef((try pt.intValue(Type.usize, align_bytes_minus_1)).toIntern());
2256922794 const remainder = try block.addBinOp(.bit_and, elem_coerced, align_minus_1);
2257022795 const is_aligned = try block.addBinOp(.cmp_eq, remainder, .zero_usize);
2257122796 try sema.addSafetyCheck(block, src, is_aligned, .incorrect_alignment);
......@@ -22575,7 +22800,7 @@ fn zirPtrFromInt(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2257522800
2257622801 const new_elems = try sema.arena.alloc(Air.Inst.Ref, len);
2257722802 for (new_elems, 0..) |*new_elem, i| {
22578 const idx_ref = try mod.intRef(Type.usize, i);
22803 const idx_ref = try pt.intRef(Type.usize, i);
2257922804 const old_elem = try block.addBinOp(.array_elem_val, operand_coerced, idx_ref);
2258022805 new_elem.* = try block.addBitCast(ptr_ty, old_elem);
2258122806 }
......@@ -22590,31 +22815,33 @@ fn ptrFromIntVal(
2259022815 ptr_ty: Type,
2259122816 ptr_align: Alignment,
2259222817) !Value {
22593 const zcu = sema.mod;
22818 const pt = sema.pt;
22819 const zcu = pt.zcu;
2259422820 if (operand_val.isUndef(zcu)) {
2259522821 if (ptr_ty.isAllowzeroPtr(zcu) and ptr_align == .@"1") {
22596 return zcu.undefValue(ptr_ty);
22822 return pt.undefValue(ptr_ty);
2259722823 }
2259822824 return sema.failWithUseOfUndef(block, operand_src);
2259922825 }
22600 const addr = try operand_val.toUnsignedIntSema(zcu);
22826 const addr = try operand_val.toUnsignedIntSema(pt);
2260122827 if (!ptr_ty.isAllowzeroPtr(zcu) and addr == 0)
22602 return sema.fail(block, operand_src, "pointer type '{}' does not allow address zero", .{ptr_ty.fmt(zcu)});
22828 return sema.fail(block, operand_src, "pointer type '{}' does not allow address zero", .{ptr_ty.fmt(pt)});
2260322829 if (addr != 0 and ptr_align != .none and !ptr_align.check(addr))
22604 return sema.fail(block, operand_src, "pointer type '{}' requires aligned address", .{ptr_ty.fmt(zcu)});
22830 return sema.fail(block, operand_src, "pointer type '{}' requires aligned address", .{ptr_ty.fmt(pt)});
2260522831
2260622832 return switch (ptr_ty.zigTypeTag(zcu)) {
22607 .Optional => Value.fromInterned((try zcu.intern(.{ .opt = .{
22833 .Optional => Value.fromInterned(try pt.intern(.{ .opt = .{
2260822834 .ty = ptr_ty.toIntern(),
22609 .val = if (addr == 0) .none else (try zcu.ptrIntValue(ptr_ty.childType(zcu), addr)).toIntern(),
22610 } }))),
22611 .Pointer => try zcu.ptrIntValue(ptr_ty, addr),
22835 .val = if (addr == 0) .none else (try pt.ptrIntValue(ptr_ty.childType(zcu), addr)).toIntern(),
22836 } })),
22837 .Pointer => try pt.ptrIntValue(ptr_ty, addr),
2261222838 else => unreachable,
2261322839 };
2261422840}
2261522841
2261622842fn zirErrorCast(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
22617 const mod = sema.mod;
22843 const pt = sema.pt;
22844 const mod = pt.zcu;
2261822845 const ip = &mod.intern_pool;
2261922846 const extra = sema.code.extraData(Zir.Inst.BinNode, extended.operand).data;
2262022847 const src = block.nodeOffset(extra.node);
......@@ -22642,8 +22869,8 @@ fn zirErrorCast(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData
2264222869 errdefer msg.destroy(sema.gpa);
2264322870 const dest_ty = base_dest_ty.errorUnionPayload(mod);
2264422871 const operand_ty = base_operand_ty.errorUnionPayload(mod);
22645 try sema.errNote(src, msg, "destination payload is '{}'", .{dest_ty.fmt(mod)});
22646 try sema.errNote(src, msg, "operand payload is '{}'", .{operand_ty.fmt(mod)});
22872 try sema.errNote(src, msg, "destination payload is '{}'", .{dest_ty.fmt(pt)});
22873 try sema.errNote(src, msg, "operand payload is '{}'", .{operand_ty.fmt(pt)});
2264722874 try addDeclaredHereNote(sema, msg, dest_ty);
2264822875 try addDeclaredHereNote(sema, msg, operand_ty);
2264922876 break :msg msg;
......@@ -22684,7 +22911,7 @@ fn zirErrorCast(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData
2268422911 };
2268522912 if (disjoint and dest_tag != .ErrorUnion) {
2268622913 return sema.fail(block, src, "error sets '{}' and '{}' have no common errors", .{
22687 operand_ty.fmt(sema.mod), dest_ty.fmt(sema.mod),
22914 operand_ty.fmt(pt), dest_ty.fmt(pt),
2268822915 });
2268922916 }
2269022917
......@@ -22700,24 +22927,24 @@ fn zirErrorCast(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData
2270022927 }
2270122928 if (!Type.errorSetHasFieldIp(ip, dest_ty.toIntern(), error_name)) {
2270222929 return sema.fail(block, src, "'error.{}' not a member of error set '{}'", .{
22703 error_name.fmt(ip), dest_ty.fmt(sema.mod),
22930 error_name.fmt(ip), dest_ty.fmt(pt),
2270422931 });
2270522932 }
2270622933 }
2270722934
22708 return Air.internedToRef((try mod.getCoerced(val, base_dest_ty)).toIntern());
22935 return Air.internedToRef((try pt.getCoerced(val, base_dest_ty)).toIntern());
2270922936 }
2271022937
2271122938 try sema.requireRuntimeBlock(block, src, operand_src);
22712 const err_int_ty = try mod.errorIntType();
22939 const err_int_ty = try pt.errorIntType();
2271322940 if (block.wantSafety() and !dest_ty.isAnyError(mod) and
2271422941 dest_ty.toIntern() != .adhoc_inferred_error_set_type and
22715 sema.mod.backendSupportsFeature(.error_set_has_value))
22942 mod.backendSupportsFeature(.error_set_has_value))
2271622943 {
2271722944 if (dest_tag == .ErrorUnion) {
2271822945 const err_code = try sema.analyzeErrUnionCode(block, operand_src, operand);
2271922946 const err_int = try block.addBitCast(err_int_ty, err_code);
22720 const zero_err = try mod.intRef(try mod.errorIntType(), 0);
22947 const zero_err = try pt.intRef(try pt.errorIntType(), 0);
2272122948
2272222949 const is_zero = try block.addBinOp(.cmp_eq, err_int, zero_err);
2272322950 if (disjoint) {
......@@ -22786,7 +23013,8 @@ fn ptrCastFull(
2278623013 dest_ty: Type,
2278723014 operation: []const u8,
2278823015) CompileError!Air.Inst.Ref {
22789 const mod = sema.mod;
23016 const pt = sema.pt;
23017 const mod = pt.zcu;
2279023018 const operand_ty = sema.typeOf(operand);
2279123019
2279223020 try sema.checkPtrType(block, src, dest_ty, true);
......@@ -22795,8 +23023,8 @@ fn ptrCastFull(
2279523023 const src_info = operand_ty.ptrInfo(mod);
2279623024 const dest_info = dest_ty.ptrInfo(mod);
2279723025
22798 try Type.fromInterned(src_info.child).resolveLayout(mod);
22799 try Type.fromInterned(dest_info.child).resolveLayout(mod);
23026 try Type.fromInterned(src_info.child).resolveLayout(pt);
23027 try Type.fromInterned(dest_info.child).resolveLayout(pt);
2280023028
2280123029 const src_slice_like = src_info.flags.size == .Slice or
2280223030 (src_info.flags.size == .One and Type.fromInterned(src_info.child).zigTypeTag(mod) == .Array);
......@@ -22810,12 +23038,12 @@ fn ptrCastFull(
2281023038
2281123039 if (dest_info.flags.size == .Slice) {
2281223040 const src_elem_size = switch (src_info.flags.size) {
22813 .Slice => Type.fromInterned(src_info.child).abiSize(mod),
23041 .Slice => Type.fromInterned(src_info.child).abiSize(pt),
2281423042 // pointer to array
22815 .One => Type.fromInterned(src_info.child).childType(mod).abiSize(mod),
23043 .One => Type.fromInterned(src_info.child).childType(mod).abiSize(pt),
2281623044 else => unreachable,
2281723045 };
22818 const dest_elem_size = Type.fromInterned(dest_info.child).abiSize(mod);
23046 const dest_elem_size = Type.fromInterned(dest_info.child).abiSize(pt);
2281923047 if (src_elem_size != dest_elem_size) {
2282023048 return sema.fail(block, src, "TODO: implement {s} between slices changing the length", .{operation});
2282123049 }
......@@ -22867,8 +23095,7 @@ fn ptrCastFull(
2286723095 if (imc_res == .ok) break :check_child;
2286823096 return sema.failWithOwnedErrorMsg(block, msg: {
2286923097 const msg = try sema.errMsg(src, "pointer element type '{}' cannot coerce into element type '{}'", .{
22870 src_child.fmt(mod),
22871 dest_child.fmt(mod),
23098 src_child.fmt(pt), dest_child.fmt(pt),
2287223099 });
2287323100 errdefer msg.destroy(sema.gpa);
2287423101 try imc_res.report(sema, src, msg);
......@@ -22881,26 +23108,26 @@ fn ptrCastFull(
2288123108 if (dest_info.sentinel == .none) break :check_sent;
2288223109 if (src_info.flags.size == .C) break :check_sent;
2288323110 if (src_info.sentinel != .none) {
22884 const coerced_sent = try mod.intern_pool.getCoerced(sema.gpa, src_info.sentinel, dest_info.child);
23111 const coerced_sent = try mod.intern_pool.getCoerced(sema.gpa, pt.tid, src_info.sentinel, dest_info.child);
2288523112 if (dest_info.sentinel == coerced_sent) break :check_sent;
2288623113 }
2288723114 if (src_slice_like and src_info.flags.size == .One and dest_info.flags.size == .Slice) {
2288823115 // [*]nT -> []T
2288923116 const arr_ty = Type.fromInterned(src_info.child);
2289023117 if (arr_ty.sentinel(mod)) |src_sentinel| {
22891 const coerced_sent = try mod.intern_pool.getCoerced(sema.gpa, src_sentinel.toIntern(), dest_info.child);
23118 const coerced_sent = try mod.intern_pool.getCoerced(sema.gpa, pt.tid, src_sentinel.toIntern(), dest_info.child);
2289223119 if (dest_info.sentinel == coerced_sent) break :check_sent;
2289323120 }
2289423121 }
2289523122 return sema.failWithOwnedErrorMsg(block, msg: {
2289623123 const msg = if (src_info.sentinel == .none) blk: {
2289723124 break :blk try sema.errMsg(src, "destination pointer requires '{}' sentinel", .{
22898 Value.fromInterned(dest_info.sentinel).fmtValue(mod, sema),
23125 Value.fromInterned(dest_info.sentinel).fmtValue(pt, sema),
2289923126 });
2290023127 } else blk: {
2290123128 break :blk try sema.errMsg(src, "pointer sentinel '{}' cannot coerce into pointer sentinel '{}'", .{
22902 Value.fromInterned(src_info.sentinel).fmtValue(mod, sema),
22903 Value.fromInterned(dest_info.sentinel).fmtValue(mod, sema),
23129 Value.fromInterned(src_info.sentinel).fmtValue(pt, sema),
23130 Value.fromInterned(dest_info.sentinel).fmtValue(pt, sema),
2290423131 });
2290523132 };
2290623133 errdefer msg.destroy(sema.gpa);
......@@ -22941,8 +23168,8 @@ fn ptrCastFull(
2294123168
2294223169 return sema.failWithOwnedErrorMsg(block, msg: {
2294323170 const msg = try sema.errMsg(src, "'{}' could have null values which are illegal in type '{}'", .{
22944 operand_ty.fmt(mod),
22945 dest_ty.fmt(mod),
23171 operand_ty.fmt(pt),
23172 dest_ty.fmt(pt),
2294623173 });
2294723174 errdefer msg.destroy(sema.gpa);
2294823175 try sema.errNote(src, msg, "use @ptrCast to assert the pointer is not null", .{});
......@@ -22956,12 +23183,12 @@ fn ptrCastFull(
2295623183 const src_align = if (src_info.flags.alignment != .none)
2295723184 src_info.flags.alignment
2295823185 else
22959 Type.fromInterned(src_info.child).abiAlignment(mod);
23186 Type.fromInterned(src_info.child).abiAlignment(pt);
2296023187
2296123188 const dest_align = if (dest_info.flags.alignment != .none)
2296223189 dest_info.flags.alignment
2296323190 else
22964 Type.fromInterned(dest_info.child).abiAlignment(mod);
23191 Type.fromInterned(dest_info.child).abiAlignment(pt);
2296523192
2296623193 if (!flags.align_cast) {
2296723194 if (dest_align.compare(.gt, src_align)) {
......@@ -22969,10 +23196,10 @@ fn ptrCastFull(
2296923196 const msg = try sema.errMsg(src, "{s} increases pointer alignment", .{operation});
2297023197 errdefer msg.destroy(sema.gpa);
2297123198 try sema.errNote(operand_src, msg, "'{}' has alignment '{d}'", .{
22972 operand_ty.fmt(mod), src_align.toByteUnits() orelse 0,
23199 operand_ty.fmt(pt), src_align.toByteUnits() orelse 0,
2297323200 });
2297423201 try sema.errNote(src, msg, "'{}' has alignment '{d}'", .{
22975 dest_ty.fmt(mod), dest_align.toByteUnits() orelse 0,
23202 dest_ty.fmt(pt), dest_align.toByteUnits() orelse 0,
2297623203 });
2297723204 try sema.errNote(src, msg, "use @alignCast to assert pointer alignment", .{});
2297823205 break :msg msg;
......@@ -22986,10 +23213,10 @@ fn ptrCastFull(
2298623213 const msg = try sema.errMsg(src, "{s} changes pointer address space", .{operation});
2298723214 errdefer msg.destroy(sema.gpa);
2298823215 try sema.errNote(operand_src, msg, "'{}' has address space '{s}'", .{
22989 operand_ty.fmt(mod), @tagName(src_info.flags.address_space),
23216 operand_ty.fmt(pt), @tagName(src_info.flags.address_space),
2299023217 });
2299123218 try sema.errNote(src, msg, "'{}' has address space '{s}'", .{
22992 dest_ty.fmt(mod), @tagName(dest_info.flags.address_space),
23219 dest_ty.fmt(pt), @tagName(dest_info.flags.address_space),
2299323220 });
2299423221 try sema.errNote(src, msg, "use @addrSpaceCast to cast pointer address space", .{});
2299523222 break :msg msg;
......@@ -23044,9 +23271,9 @@ fn ptrCastFull(
2304423271 // Only convert to a many-pointer at first
2304523272 var info = dest_info;
2304623273 info.flags.size = .Many;
23047 const ty = try mod.ptrTypeSema(info);
23274 const ty = try pt.ptrTypeSema(info);
2304823275 if (dest_ty.zigTypeTag(mod) == .Optional) {
23049 break :blk try mod.optionalType(ty.toIntern());
23276 break :blk try pt.optionalType(ty.toIntern());
2305023277 } else {
2305123278 break :blk ty;
2305223279 }
......@@ -23059,10 +23286,10 @@ fn ptrCastFull(
2305923286 return sema.failWithUseOfUndef(block, operand_src);
2306023287 }
2306123288 if (!dest_ty.ptrAllowsZero(mod) and ptr_val.isNull(mod)) {
23062 return sema.fail(block, operand_src, "null pointer casted to type '{}'", .{dest_ty.fmt(mod)});
23289 return sema.fail(block, operand_src, "null pointer casted to type '{}'", .{dest_ty.fmt(pt)});
2306323290 }
2306423291 if (dest_align.compare(.gt, src_align)) {
23065 if (try ptr_val.getUnsignedIntAdvanced(mod, .sema)) |addr| {
23292 if (try ptr_val.getUnsignedIntAdvanced(pt, .sema)) |addr| {
2306623293 if (!dest_align.check(addr)) {
2306723294 return sema.fail(block, operand_src, "pointer address 0x{X} is not aligned to {d} bytes", .{
2306823295 addr,
......@@ -23072,12 +23299,12 @@ fn ptrCastFull(
2307223299 }
2307323300 }
2307423301 if (dest_info.flags.size == .Slice and src_info.flags.size != .Slice) {
23075 if (ptr_val.isUndef(mod)) return mod.undefRef(dest_ty);
23076 const arr_len = try mod.intValue(Type.usize, Type.fromInterned(src_info.child).arrayLen(mod));
23302 if (ptr_val.isUndef(mod)) return pt.undefRef(dest_ty);
23303 const arr_len = try pt.intValue(Type.usize, Type.fromInterned(src_info.child).arrayLen(mod));
2307723304 const ptr_val_key = mod.intern_pool.indexToKey(ptr_val.toIntern()).ptr;
23078 return Air.internedToRef((try mod.intern(.{ .slice = .{
23305 return Air.internedToRef((try pt.intern(.{ .slice = .{
2307923306 .ty = dest_ty.toIntern(),
23080 .ptr = try mod.intern(.{ .ptr = .{
23307 .ptr = try pt.intern(.{ .ptr = .{
2308123308 .ty = dest_ty.slicePtrFieldType(mod).toIntern(),
2308223309 .base_addr = ptr_val_key.base_addr,
2308323310 .byte_offset = ptr_val_key.byte_offset,
......@@ -23086,7 +23313,7 @@ fn ptrCastFull(
2308623313 } })));
2308723314 } else {
2308823315 assert(dest_ptr_ty.eql(dest_ty, mod));
23089 return Air.internedToRef((try mod.getCoerced(ptr_val, dest_ty)).toIntern());
23316 return Air.internedToRef((try pt.getCoerced(ptr_val, dest_ty)).toIntern());
2309023317 }
2309123318 }
2309223319 }
......@@ -23112,7 +23339,7 @@ fn ptrCastFull(
2311223339 try sema.typeHasRuntimeBits(Type.fromInterned(dest_info.child)))
2311323340 {
2311423341 const align_bytes_minus_1 = dest_align.toByteUnits().? - 1;
23115 const align_minus_1 = Air.internedToRef((try mod.intValue(Type.usize, align_bytes_minus_1)).toIntern());
23342 const align_minus_1 = Air.internedToRef((try pt.intValue(Type.usize, align_bytes_minus_1)).toIntern());
2311623343 const ptr_int = try block.addUnOp(.int_from_ptr, ptr);
2311723344 const remainder = try block.addBinOp(.bit_and, ptr_int, align_minus_1);
2311823345 const is_aligned = try block.addBinOp(.cmp_eq, remainder, .zero_usize);
......@@ -23129,9 +23356,9 @@ fn ptrCastFull(
2312923356 // We can't change address spaces with a bitcast, so this requires two instructions
2313023357 var intermediate_info = src_info;
2313123358 intermediate_info.flags.address_space = dest_info.flags.address_space;
23132 const intermediate_ptr_ty = try mod.ptrTypeSema(intermediate_info);
23359 const intermediate_ptr_ty = try pt.ptrTypeSema(intermediate_info);
2313323360 const intermediate_ty = if (dest_ptr_ty.zigTypeTag(mod) == .Optional) blk: {
23134 break :blk try mod.optionalType(intermediate_ptr_ty.toIntern());
23361 break :blk try pt.optionalType(intermediate_ptr_ty.toIntern());
2313523362 } else intermediate_ptr_ty;
2313623363 const intermediate = try block.addInst(.{
2313723364 .tag = .addrspace_cast,
......@@ -23152,7 +23379,7 @@ fn ptrCastFull(
2315223379 if (dest_info.flags.size == .Slice and src_info.flags.size != .Slice) {
2315323380 // We have to construct a slice using the operand's child's array length
2315423381 // Note that we know from the check at the start of the function that operand_ty is slice-like
23155 const arr_len = Air.internedToRef((try mod.intValue(Type.usize, Type.fromInterned(src_info.child).arrayLen(mod))).toIntern());
23382 const arr_len = Air.internedToRef((try pt.intValue(Type.usize, Type.fromInterned(src_info.child).arrayLen(mod))).toIntern());
2315623383 return block.addInst(.{
2315723384 .tag = .slice,
2315823385 .data = .{ .ty_pl = .{
......@@ -23171,7 +23398,8 @@ fn ptrCastFull(
2317123398}
2317223399
2317323400fn zirPtrCastNoDest(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
23174 const mod = sema.mod;
23401 const pt = sema.pt;
23402 const mod = pt.zcu;
2317523403 const FlagsInt = @typeInfo(Zir.Inst.FullPtrCastFlags).Struct.backing_integer.?;
2317623404 const flags: Zir.Inst.FullPtrCastFlags = @bitCast(@as(FlagsInt, @truncate(extended.small)));
2317723405 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
......@@ -23186,15 +23414,15 @@ fn zirPtrCastNoDest(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Inst
2318623414 if (flags.volatile_cast) ptr_info.flags.is_volatile = false;
2318723415
2318823416 const dest_ty = blk: {
23189 const dest_ty = try mod.ptrTypeSema(ptr_info);
23417 const dest_ty = try pt.ptrTypeSema(ptr_info);
2319023418 if (operand_ty.zigTypeTag(mod) == .Optional) {
23191 break :blk try mod.optionalType(dest_ty.toIntern());
23419 break :blk try pt.optionalType(dest_ty.toIntern());
2319223420 }
2319323421 break :blk dest_ty;
2319423422 };
2319523423
2319623424 if (try sema.resolveValue(operand)) |operand_val| {
23197 return Air.internedToRef((try mod.getCoerced(operand_val, dest_ty)).toIntern());
23425 return Air.internedToRef((try pt.getCoerced(operand_val, dest_ty)).toIntern());
2319823426 }
2319923427
2320023428 try sema.requireRuntimeBlock(block, src, null);
......@@ -23204,7 +23432,8 @@ fn zirPtrCastNoDest(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Inst
2320423432}
2320523433
2320623434fn zirTruncate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
23207 const mod = sema.mod;
23435 const pt = sema.pt;
23436 const mod = pt.zcu;
2320823437 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2320923438 const src = block.nodeOffset(inst_data.src_node);
2321023439 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
......@@ -23218,7 +23447,7 @@ fn zirTruncate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
2321823447 const operand_is_vector = operand_ty.zigTypeTag(mod) == .Vector;
2321923448 const dest_is_vector = dest_ty.zigTypeTag(mod) == .Vector;
2322023449 if (operand_is_vector != dest_is_vector) {
23221 return sema.fail(block, operand_src, "expected type '{}', found '{}'", .{ dest_ty.fmt(mod), operand_ty.fmt(mod) });
23450 return sema.fail(block, operand_src, "expected type '{}', found '{}'", .{ dest_ty.fmt(pt), operand_ty.fmt(pt) });
2322223451 }
2322323452
2322423453 if (dest_scalar_ty.zigTypeTag(mod) == .ComptimeInt) {
......@@ -23239,7 +23468,7 @@ fn zirTruncate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
2323923468
2324023469 if (operand_info.signedness != dest_info.signedness) {
2324123470 return sema.fail(block, operand_src, "expected {s} integer type, found '{}'", .{
23242 @tagName(dest_info.signedness), operand_ty.fmt(mod),
23471 @tagName(dest_info.signedness), operand_ty.fmt(pt),
2324323472 });
2324423473 }
2324523474 if (operand_info.bits < dest_info.bits) {
......@@ -23247,7 +23476,7 @@ fn zirTruncate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
2324723476 const msg = try sema.errMsg(
2324823477 src,
2324923478 "destination type '{}' has more bits than source type '{}'",
23250 .{ dest_ty.fmt(mod), operand_ty.fmt(mod) },
23479 .{ dest_ty.fmt(pt), operand_ty.fmt(pt) },
2325123480 );
2325223481 errdefer msg.destroy(sema.gpa);
2325323482 try sema.errNote(src, msg, "destination type has {d} bits", .{
......@@ -23263,20 +23492,20 @@ fn zirTruncate(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
2326323492 }
2326423493
2326523494 if (try sema.resolveValueIntable(operand)) |val| {
23266 if (val.isUndef(mod)) return mod.undefRef(dest_ty);
23495 if (val.isUndef(mod)) return pt.undefRef(dest_ty);
2326723496 if (!dest_is_vector) {
23268 return Air.internedToRef((try mod.getCoerced(
23269 try val.intTrunc(operand_ty, sema.arena, dest_info.signedness, dest_info.bits, mod),
23497 return Air.internedToRef((try pt.getCoerced(
23498 try val.intTrunc(operand_ty, sema.arena, dest_info.signedness, dest_info.bits, pt),
2327023499 dest_ty,
2327123500 )).toIntern());
2327223501 }
2327323502 const elems = try sema.arena.alloc(InternPool.Index, operand_ty.vectorLen(mod));
2327423503 for (elems, 0..) |*elem, i| {
23275 const elem_val = try val.elemValue(mod, i);
23276 const uncoerced_elem = try elem_val.intTrunc(operand_scalar_ty, sema.arena, dest_info.signedness, dest_info.bits, mod);
23277 elem.* = (try mod.getCoerced(uncoerced_elem, dest_scalar_ty)).toIntern();
23504 const elem_val = try val.elemValue(pt, i);
23505 const uncoerced_elem = try elem_val.intTrunc(operand_scalar_ty, sema.arena, dest_info.signedness, dest_info.bits, pt);
23506 elem.* = (try pt.getCoerced(uncoerced_elem, dest_scalar_ty)).toIntern();
2327823507 }
23279 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
23508 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
2328023509 .ty = dest_ty.toIntern(),
2328123510 .storage = .{ .elems = elems },
2328223511 } })));
......@@ -23291,9 +23520,10 @@ fn zirBitCount(
2329123520 block: *Block,
2329223521 inst: Zir.Inst.Index,
2329323522 air_tag: Air.Inst.Tag,
23294 comptime comptimeOp: fn (val: Value, ty: Type, mod: *Module) u64,
23523 comptime comptimeOp: fn (val: Value, ty: Type, pt: Zcu.PerThread) u64,
2329523524) CompileError!Air.Inst.Ref {
23296 const mod = sema.mod;
23525 const pt = sema.pt;
23526 const mod = pt.zcu;
2329723527 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
2329823528 const src = block.nodeOffset(inst_data.src_node);
2329923529 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
......@@ -23306,25 +23536,25 @@ fn zirBitCount(
2330623536 return Air.internedToRef(val.toIntern());
2330723537 }
2330823538
23309 const result_scalar_ty = try mod.smallestUnsignedInt(bits);
23539 const result_scalar_ty = try pt.smallestUnsignedInt(bits);
2331023540 switch (operand_ty.zigTypeTag(mod)) {
2331123541 .Vector => {
2331223542 const vec_len = operand_ty.vectorLen(mod);
23313 const result_ty = try mod.vectorType(.{
23543 const result_ty = try pt.vectorType(.{
2331423544 .len = vec_len,
2331523545 .child = result_scalar_ty.toIntern(),
2331623546 });
2331723547 if (try sema.resolveValue(operand)) |val| {
23318 if (val.isUndef(mod)) return mod.undefRef(result_ty);
23548 if (val.isUndef(mod)) return pt.undefRef(result_ty);
2331923549
2332023550 const elems = try sema.arena.alloc(InternPool.Index, vec_len);
2332123551 const scalar_ty = operand_ty.scalarType(mod);
2332223552 for (elems, 0..) |*elem, i| {
23323 const elem_val = try val.elemValue(mod, i);
23324 const count = comptimeOp(elem_val, scalar_ty, mod);
23325 elem.* = (try mod.intValue(result_scalar_ty, count)).toIntern();
23553 const elem_val = try val.elemValue(pt, i);
23554 const count = comptimeOp(elem_val, scalar_ty, pt);
23555 elem.* = (try pt.intValue(result_scalar_ty, count)).toIntern();
2332623556 }
23327 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
23557 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
2332823558 .ty = result_ty.toIntern(),
2332923559 .storage = .{ .elems = elems },
2333023560 } })));
......@@ -23335,8 +23565,8 @@ fn zirBitCount(
2333523565 },
2333623566 .Int => {
2333723567 if (try sema.resolveValueResolveLazy(operand)) |val| {
23338 if (val.isUndef(mod)) return mod.undefRef(result_scalar_ty);
23339 return mod.intRef(result_scalar_ty, comptimeOp(val, operand_ty, mod));
23568 if (val.isUndef(mod)) return pt.undefRef(result_scalar_ty);
23569 return pt.intRef(result_scalar_ty, comptimeOp(val, operand_ty, pt));
2334023570 } else {
2334123571 try sema.requireRuntimeBlock(block, src, operand_src);
2334223572 return block.addTyOp(air_tag, result_scalar_ty, operand);
......@@ -23347,7 +23577,8 @@ fn zirBitCount(
2334723577}
2334823578
2334923579fn zirByteSwap(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
23350 const mod = sema.mod;
23580 const pt = sema.pt;
23581 const mod = pt.zcu;
2335123582 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].un_node;
2335223583 const src = block.nodeOffset(inst_data.src_node);
2335323584 const operand_src = block.builtinCallArgSrc(inst_data.src_node, 0);
......@@ -23360,7 +23591,7 @@ fn zirByteSwap(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
2336023591 block,
2336123592 operand_src,
2336223593 "@byteSwap requires the number of bits to be evenly divisible by 8, but {} has {} bits",
23363 .{ scalar_ty.fmt(mod), bits },
23594 .{ scalar_ty.fmt(pt), bits },
2336423595 );
2336523596 }
2336623597
......@@ -23371,8 +23602,8 @@ fn zirByteSwap(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
2337123602 switch (operand_ty.zigTypeTag(mod)) {
2337223603 .Int => {
2337323604 const runtime_src = if (try sema.resolveValue(operand)) |val| {
23374 if (val.isUndef(mod)) return mod.undefRef(operand_ty);
23375 const result_val = try val.byteSwap(operand_ty, mod, sema.arena);
23605 if (val.isUndef(mod)) return pt.undefRef(operand_ty);
23606 const result_val = try val.byteSwap(operand_ty, pt, sema.arena);
2337623607 return Air.internedToRef(result_val.toIntern());
2337723608 } else operand_src;
2337823609
......@@ -23382,15 +23613,15 @@ fn zirByteSwap(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Ai
2338223613 .Vector => {
2338323614 const runtime_src = if (try sema.resolveValue(operand)) |val| {
2338423615 if (val.isUndef(mod))
23385 return mod.undefRef(operand_ty);
23616 return pt.undefRef(operand_ty);
2338623617
2338723618 const vec_len = operand_ty.vectorLen(mod);
2338823619 const elems = try sema.arena.alloc(InternPool.Index, vec_len);
2338923620 for (elems, 0..) |*elem, i| {
23390 const elem_val = try val.elemValue(mod, i);
23391 elem.* = (try elem_val.byteSwap(scalar_ty, mod, sema.arena)).toIntern();
23621 const elem_val = try val.elemValue(pt, i);
23622 elem.* = (try elem_val.byteSwap(scalar_ty, pt, sema.arena)).toIntern();
2339223623 }
23393 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
23624 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
2339423625 .ty = operand_ty.toIntern(),
2339523626 .storage = .{ .elems = elems },
2339623627 } })));
......@@ -23415,12 +23646,13 @@ fn zirBitReverse(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2341523646 return Air.internedToRef(val.toIntern());
2341623647 }
2341723648
23418 const mod = sema.mod;
23649 const pt = sema.pt;
23650 const mod = pt.zcu;
2341923651 switch (operand_ty.zigTypeTag(mod)) {
2342023652 .Int => {
2342123653 const runtime_src = if (try sema.resolveValue(operand)) |val| {
23422 if (val.isUndef(mod)) return mod.undefRef(operand_ty);
23423 const result_val = try val.bitReverse(operand_ty, mod, sema.arena);
23654 if (val.isUndef(mod)) return pt.undefRef(operand_ty);
23655 const result_val = try val.bitReverse(operand_ty, pt, sema.arena);
2342423656 return Air.internedToRef(result_val.toIntern());
2342523657 } else operand_src;
2342623658
......@@ -23430,15 +23662,15 @@ fn zirBitReverse(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2343023662 .Vector => {
2343123663 const runtime_src = if (try sema.resolveValue(operand)) |val| {
2343223664 if (val.isUndef(mod))
23433 return mod.undefRef(operand_ty);
23665 return pt.undefRef(operand_ty);
2343423666
2343523667 const vec_len = operand_ty.vectorLen(mod);
2343623668 const elems = try sema.arena.alloc(InternPool.Index, vec_len);
2343723669 for (elems, 0..) |*elem, i| {
23438 const elem_val = try val.elemValue(mod, i);
23439 elem.* = (try elem_val.bitReverse(scalar_ty, mod, sema.arena)).toIntern();
23670 const elem_val = try val.elemValue(pt, i);
23671 elem.* = (try elem_val.bitReverse(scalar_ty, pt, sema.arena)).toIntern();
2344023672 }
23441 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
23673 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
2344223674 .ty = operand_ty.toIntern(),
2344323675 .storage = .{ .elems = elems },
2344423676 } })));
......@@ -23453,13 +23685,13 @@ fn zirBitReverse(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2345323685
2345423686fn zirBitOffsetOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
2345523687 const offset = try sema.bitOffsetOf(block, inst);
23456 return sema.mod.intRef(Type.comptime_int, offset);
23688 return sema.pt.intRef(Type.comptime_int, offset);
2345723689}
2345823690
2345923691fn zirOffsetOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
2346023692 const offset = try sema.bitOffsetOf(block, inst);
2346123693 // TODO reminder to make this a compile error for packed structs
23462 return sema.mod.intRef(Type.comptime_int, offset / 8);
23694 return sema.pt.intRef(Type.comptime_int, offset / 8);
2346323695}
2346423696
2346523697fn bitOffsetOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!u64 {
......@@ -23474,12 +23706,13 @@ fn bitOffsetOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!u6
2347423706 .needed_comptime_reason = "name of field must be comptime-known",
2347523707 });
2347623708
23477 const mod = sema.mod;
23709 const pt = sema.pt;
23710 const mod = pt.zcu;
2347823711 const ip = &mod.intern_pool;
23479 try ty.resolveLayout(mod);
23712 try ty.resolveLayout(pt);
2348023713 switch (ty.zigTypeTag(mod)) {
2348123714 .Struct => {},
23482 else => return sema.fail(block, lhs_src, "expected struct type, found '{}'", .{ty.fmt(mod)}),
23715 else => return sema.fail(block, lhs_src, "expected struct type, found '{}'", .{ty.fmt(pt)}),
2348323716 }
2348423717
2348523718 const field_index = if (ty.isTuple(mod)) blk: {
......@@ -23502,28 +23735,30 @@ fn bitOffsetOf(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!u6
2350223735 return bit_sum;
2350323736 }
2350423737 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
23505 bit_sum += field_ty.bitSize(mod);
23738 bit_sum += field_ty.bitSize(pt);
2350623739 } else unreachable;
2350723740 },
23508 else => return ty.structFieldOffset(field_index, mod) * 8,
23741 else => return ty.structFieldOffset(field_index, pt) * 8,
2350923742 }
2351023743}
2351123744
2351223745fn checkNamespaceType(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError!void {
23513 const mod = sema.mod;
23746 const pt = sema.pt;
23747 const mod = pt.zcu;
2351423748 switch (ty.zigTypeTag(mod)) {
2351523749 .Struct, .Enum, .Union, .Opaque => return,
23516 else => return sema.fail(block, src, "expected struct, enum, union, or opaque; found '{}'", .{ty.fmt(mod)}),
23750 else => return sema.fail(block, src, "expected struct, enum, union, or opaque; found '{}'", .{ty.fmt(pt)}),
2351723751 }
2351823752}
2351923753
2352023754/// Returns `true` if the type was a comptime_int.
2352123755fn checkIntType(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) CompileError!bool {
23522 const mod = sema.mod;
23756 const pt = sema.pt;
23757 const mod = pt.zcu;
2352323758 switch (try ty.zigTypeTagOrPoison(mod)) {
2352423759 .ComptimeInt => return true,
2352523760 .Int => return false,
23526 else => return sema.fail(block, src, "expected integer type, found '{}'", .{ty.fmt(mod)}),
23761 else => return sema.fail(block, src, "expected integer type, found '{}'", .{ty.fmt(pt)}),
2352723762 }
2352823763}
2352923764
......@@ -23533,7 +23768,8 @@ fn checkInvalidPtrArithmetic(
2353323768 src: LazySrcLoc,
2353423769 ty: Type,
2353523770) CompileError!void {
23536 const mod = sema.mod;
23771 const pt = sema.pt;
23772 const mod = pt.zcu;
2353723773 switch (try ty.zigTypeTagOrPoison(mod)) {
2353823774 .Pointer => switch (ty.ptrSize(mod)) {
2353923775 .One, .Slice => return,
......@@ -23573,7 +23809,8 @@ fn checkPtrOperand(
2357323809 ty_src: LazySrcLoc,
2357423810 ty: Type,
2357523811) CompileError!void {
23576 const mod = sema.mod;
23812 const pt = sema.pt;
23813 const mod = pt.zcu;
2357723814 switch (ty.zigTypeTag(mod)) {
2357823815 .Pointer => return,
2357923816 .Fn => {
......@@ -23581,7 +23818,7 @@ fn checkPtrOperand(
2358123818 const msg = try sema.errMsg(
2358223819 ty_src,
2358323820 "expected pointer, found '{}'",
23584 .{ty.fmt(mod)},
23821 .{ty.fmt(pt)},
2358523822 );
2358623823 errdefer msg.destroy(sema.gpa);
2358723824
......@@ -23594,7 +23831,7 @@ fn checkPtrOperand(
2359423831 .Optional => if (ty.childType(mod).zigTypeTag(mod) == .Pointer) return,
2359523832 else => {},
2359623833 }
23597 return sema.fail(block, ty_src, "expected pointer type, found '{}'", .{ty.fmt(mod)});
23834 return sema.fail(block, ty_src, "expected pointer type, found '{}'", .{ty.fmt(pt)});
2359823835}
2359923836
2360023837fn checkPtrType(
......@@ -23604,7 +23841,8 @@ fn checkPtrType(
2360423841 ty: Type,
2360523842 allow_slice: bool,
2360623843) CompileError!void {
23607 const mod = sema.mod;
23844 const pt = sema.pt;
23845 const mod = pt.zcu;
2360823846 switch (ty.zigTypeTag(mod)) {
2360923847 .Pointer => if (allow_slice or !ty.isSlice(mod)) return,
2361023848 .Fn => {
......@@ -23612,7 +23850,7 @@ fn checkPtrType(
2361223850 const msg = try sema.errMsg(
2361323851 ty_src,
2361423852 "expected pointer type, found '{}'",
23615 .{ty.fmt(mod)},
23853 .{ty.fmt(pt)},
2361623854 );
2361723855 errdefer msg.destroy(sema.gpa);
2361823856
......@@ -23625,7 +23863,7 @@ fn checkPtrType(
2362523863 .Optional => if (ty.childType(mod).zigTypeTag(mod) == .Pointer) return,
2362623864 else => {},
2362723865 }
23628 return sema.fail(block, ty_src, "expected pointer type, found '{}'", .{ty.fmt(mod)});
23866 return sema.fail(block, ty_src, "expected pointer type, found '{}'", .{ty.fmt(pt)});
2362923867}
2363023868
2363123869fn checkVectorElemType(
......@@ -23634,13 +23872,14 @@ fn checkVectorElemType(
2363423872 ty_src: LazySrcLoc,
2363523873 ty: Type,
2363623874) CompileError!void {
23637 const mod = sema.mod;
23875 const pt = sema.pt;
23876 const mod = pt.zcu;
2363823877 switch (ty.zigTypeTag(mod)) {
2363923878 .Int, .Float, .Bool => return,
2364023879 .Optional, .Pointer => if (ty.isPtrAtRuntime(mod)) return,
2364123880 else => {},
2364223881 }
23643 return sema.fail(block, ty_src, "expected integer, float, bool, or pointer for the vector element type; found '{}'", .{ty.fmt(mod)});
23882 return sema.fail(block, ty_src, "expected integer, float, bool, or pointer for the vector element type; found '{}'", .{ty.fmt(pt)});
2364423883}
2364523884
2364623885fn checkFloatType(
......@@ -23649,10 +23888,11 @@ fn checkFloatType(
2364923888 ty_src: LazySrcLoc,
2365023889 ty: Type,
2365123890) CompileError!void {
23652 const mod = sema.mod;
23891 const pt = sema.pt;
23892 const mod = pt.zcu;
2365323893 switch (ty.zigTypeTag(mod)) {
2365423894 .ComptimeInt, .ComptimeFloat, .Float => {},
23655 else => return sema.fail(block, ty_src, "expected float type, found '{}'", .{ty.fmt(mod)}),
23895 else => return sema.fail(block, ty_src, "expected float type, found '{}'", .{ty.fmt(pt)}),
2365623896 }
2365723897}
2365823898
......@@ -23662,14 +23902,15 @@ fn checkNumericType(
2366223902 ty_src: LazySrcLoc,
2366323903 ty: Type,
2366423904) CompileError!void {
23665 const mod = sema.mod;
23905 const pt = sema.pt;
23906 const mod = pt.zcu;
2366623907 switch (ty.zigTypeTag(mod)) {
2366723908 .ComptimeFloat, .Float, .ComptimeInt, .Int => {},
2366823909 .Vector => switch (ty.childType(mod).zigTypeTag(mod)) {
2366923910 .ComptimeFloat, .Float, .ComptimeInt, .Int => {},
2367023911 else => |t| return sema.fail(block, ty_src, "expected number, found '{}'", .{t}),
2367123912 },
23672 else => return sema.fail(block, ty_src, "expected number, found '{}'", .{ty.fmt(mod)}),
23913 else => return sema.fail(block, ty_src, "expected number, found '{}'", .{ty.fmt(pt)}),
2367323914 }
2367423915}
2367523916
......@@ -23683,7 +23924,8 @@ fn checkAtomicPtrOperand(
2368323924 ptr_src: LazySrcLoc,
2368423925 ptr_const: bool,
2368523926) CompileError!Air.Inst.Ref {
23686 const mod = sema.mod;
23927 const pt = sema.pt;
23928 const mod = pt.zcu;
2368723929 var diag: Module.AtomicPtrAlignmentDiagnostics = .{};
2368823930 const alignment = mod.atomicPtrAlignment(elem_ty, &diag) catch |err| switch (err) {
2368923931 error.OutOfMemory => return error.OutOfMemory,
......@@ -23703,7 +23945,7 @@ fn checkAtomicPtrOperand(
2370323945 block,
2370423946 elem_ty_src,
2370523947 "expected bool, integer, float, enum, or pointer type; found '{}'",
23706 .{elem_ty.fmt(mod)},
23948 .{elem_ty.fmt(pt)},
2370723949 ),
2370823950 };
2370923951
......@@ -23719,7 +23961,7 @@ fn checkAtomicPtrOperand(
2371923961 const ptr_data = switch (try ptr_ty.zigTypeTagOrPoison(mod)) {
2372023962 .Pointer => ptr_ty.ptrInfo(mod),
2372123963 else => {
23722 const wanted_ptr_ty = try mod.ptrTypeSema(wanted_ptr_data);
23964 const wanted_ptr_ty = try pt.ptrTypeSema(wanted_ptr_data);
2372323965 _ = try sema.coerce(block, wanted_ptr_ty, ptr, ptr_src);
2372423966 unreachable;
2372523967 },
......@@ -23729,7 +23971,7 @@ fn checkAtomicPtrOperand(
2372923971 wanted_ptr_data.flags.is_allowzero = ptr_data.flags.is_allowzero;
2373023972 wanted_ptr_data.flags.is_volatile = ptr_data.flags.is_volatile;
2373123973
23732 const wanted_ptr_ty = try mod.ptrTypeSema(wanted_ptr_data);
23974 const wanted_ptr_ty = try pt.ptrTypeSema(wanted_ptr_data);
2373323975 const casted_ptr = try sema.coerce(block, wanted_ptr_ty, ptr, ptr_src);
2373423976
2373523977 return casted_ptr;
......@@ -23754,7 +23996,8 @@ fn checkIntOrVector(
2375423996 operand: Air.Inst.Ref,
2375523997 operand_src: LazySrcLoc,
2375623998) CompileError!Type {
23757 const mod = sema.mod;
23999 const pt = sema.pt;
24000 const mod = pt.zcu;
2375824001 const operand_ty = sema.typeOf(operand);
2375924002 switch (try operand_ty.zigTypeTagOrPoison(mod)) {
2376024003 .Int => return operand_ty,
......@@ -23763,12 +24006,12 @@ fn checkIntOrVector(
2376324006 switch (try elem_ty.zigTypeTagOrPoison(mod)) {
2376424007 .Int => return elem_ty,
2376524008 else => return sema.fail(block, operand_src, "expected vector of integers; found vector of '{}'", .{
23766 elem_ty.fmt(mod),
24009 elem_ty.fmt(pt),
2376724010 }),
2376824011 }
2376924012 },
2377024013 else => return sema.fail(block, operand_src, "expected integer or vector, found '{}'", .{
23771 operand_ty.fmt(mod),
24014 operand_ty.fmt(pt),
2377224015 }),
2377324016 }
2377424017}
......@@ -23779,7 +24022,8 @@ fn checkIntOrVectorAllowComptime(
2377924022 operand_ty: Type,
2378024023 operand_src: LazySrcLoc,
2378124024) CompileError!Type {
23782 const mod = sema.mod;
24025 const pt = sema.pt;
24026 const mod = pt.zcu;
2378324027 switch (try operand_ty.zigTypeTagOrPoison(mod)) {
2378424028 .Int, .ComptimeInt => return operand_ty,
2378524029 .Vector => {
......@@ -23787,12 +24031,12 @@ fn checkIntOrVectorAllowComptime(
2378724031 switch (try elem_ty.zigTypeTagOrPoison(mod)) {
2378824032 .Int, .ComptimeInt => return elem_ty,
2378924033 else => return sema.fail(block, operand_src, "expected vector of integers; found vector of '{}'", .{
23790 elem_ty.fmt(mod),
24034 elem_ty.fmt(pt),
2379124035 }),
2379224036 }
2379324037 },
2379424038 else => return sema.fail(block, operand_src, "expected integer or vector, found '{}'", .{
23795 operand_ty.fmt(mod),
24039 operand_ty.fmt(pt),
2379624040 }),
2379724041 }
2379824042}
......@@ -23819,7 +24063,8 @@ fn checkSimdBinOp(
2381924063 lhs_src: LazySrcLoc,
2382024064 rhs_src: LazySrcLoc,
2382124065) CompileError!SimdBinOp {
23822 const mod = sema.mod;
24066 const pt = sema.pt;
24067 const mod = pt.zcu;
2382324068 const lhs_ty = sema.typeOf(uncasted_lhs);
2382424069 const rhs_ty = sema.typeOf(uncasted_rhs);
2382524070
......@@ -23851,7 +24096,8 @@ fn checkVectorizableBinaryOperands(
2385124096 lhs_src: LazySrcLoc,
2385224097 rhs_src: LazySrcLoc,
2385324098) CompileError!void {
23854 const mod = sema.mod;
24099 const pt = sema.pt;
24100 const mod = pt.zcu;
2385524101 const lhs_zig_ty_tag = try lhs_ty.zigTypeTagOrPoison(mod);
2385624102 const rhs_zig_ty_tag = try rhs_ty.zigTypeTagOrPoison(mod);
2385724103 if (lhs_zig_ty_tag != .Vector and rhs_zig_ty_tag != .Vector) return;
......@@ -23881,7 +24127,7 @@ fn checkVectorizableBinaryOperands(
2388124127 } else {
2388224128 const msg = msg: {
2388324129 const msg = try sema.errMsg(src, "mixed scalar and vector operands: '{}' and '{}'", .{
23884 lhs_ty.fmt(mod), rhs_ty.fmt(mod),
24130 lhs_ty.fmt(pt), rhs_ty.fmt(pt),
2388524131 });
2388624132 errdefer msg.destroy(sema.gpa);
2388724133 if (lhs_is_vector) {
......@@ -23903,10 +24149,11 @@ fn resolveExportOptions(
2390324149 src: LazySrcLoc,
2390424150 zir_ref: Zir.Inst.Ref,
2390524151) CompileError!Module.Export.Options {
23906 const mod = sema.mod;
24152 const pt = sema.pt;
24153 const mod = pt.zcu;
2390724154 const gpa = sema.gpa;
2390824155 const ip = &mod.intern_pool;
23909 const export_options_ty = try mod.getBuiltinType("ExportOptions");
24156 const export_options_ty = try pt.getBuiltinType("ExportOptions");
2391024157 const air_ref = try sema.resolveInst(zir_ref);
2391124158 const options = try sema.coerce(block, export_options_ty, air_ref, src);
2391224159
......@@ -23915,18 +24162,18 @@ fn resolveExportOptions(
2391524162 const section_src = block.src(.{ .init_field_section = src.offset.node_offset_builtin_call_arg.builtin_call_node });
2391624163 const visibility_src = block.src(.{ .init_field_visibility = src.offset.node_offset_builtin_call_arg.builtin_call_node });
2391724164
23918 const name_operand = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, "name", .no_embedded_nulls), name_src);
24165 const name_operand = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "name", .no_embedded_nulls), name_src);
2391924166 const name = try sema.toConstString(block, name_src, name_operand, .{
2392024167 .needed_comptime_reason = "name of exported value must be comptime-known",
2392124168 });
2392224169
23923 const linkage_operand = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, "linkage", .no_embedded_nulls), linkage_src);
24170 const linkage_operand = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "linkage", .no_embedded_nulls), linkage_src);
2392424171 const linkage_val = try sema.resolveConstDefinedValue(block, linkage_src, linkage_operand, .{
2392524172 .needed_comptime_reason = "linkage of exported value must be comptime-known",
2392624173 });
2392724174 const linkage = mod.toEnum(std.builtin.GlobalLinkage, linkage_val);
2392824175
23929 const section_operand = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, "section", .no_embedded_nulls), section_src);
24176 const section_operand = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "section", .no_embedded_nulls), section_src);
2393024177 const section_opt_val = try sema.resolveConstDefinedValue(block, section_src, section_operand, .{
2393124178 .needed_comptime_reason = "linksection of exported value must be comptime-known",
2393224179 });
......@@ -23937,7 +24184,7 @@ fn resolveExportOptions(
2393724184 else
2393824185 null;
2393924186
23940 const visibility_operand = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, "visibility", .no_embedded_nulls), visibility_src);
24187 const visibility_operand = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "visibility", .no_embedded_nulls), visibility_src);
2394124188 const visibility_val = try sema.resolveConstDefinedValue(block, visibility_src, visibility_operand, .{
2394224189 .needed_comptime_reason = "visibility of exported value must be comptime-known",
2394324190 });
......@@ -23954,9 +24201,9 @@ fn resolveExportOptions(
2395424201 }
2395524202
2395624203 return .{
23957 .name = try ip.getOrPutString(gpa, name, .no_embedded_nulls),
24204 .name = try ip.getOrPutString(gpa, pt.tid, name, .no_embedded_nulls),
2395824205 .linkage = linkage,
23959 .section = try ip.getOrPutStringOpt(gpa, section, .no_embedded_nulls),
24206 .section = try ip.getOrPutStringOpt(gpa, pt.tid, section, .no_embedded_nulls),
2396024207 .visibility = visibility,
2396124208 };
2396224209}
......@@ -23969,12 +24216,12 @@ fn resolveBuiltinEnum(
2396924216 comptime name: []const u8,
2397024217 reason: NeededComptimeReason,
2397124218) CompileError!@field(std.builtin, name) {
23972 const mod = sema.mod;
23973 const ty = try mod.getBuiltinType(name);
24219 const pt = sema.pt;
24220 const ty = try pt.getBuiltinType(name);
2397424221 const air_ref = try sema.resolveInst(zir_ref);
2397524222 const coerced = try sema.coerce(block, ty, air_ref, src);
2397624223 const val = try sema.resolveConstDefinedValue(block, src, coerced, reason);
23977 return mod.toEnum(@field(std.builtin, name), val);
24224 return pt.zcu.toEnum(@field(std.builtin, name), val);
2397824225}
2397924226
2398024227fn resolveAtomicOrder(
......@@ -24003,7 +24250,8 @@ fn zirCmpxchg(
2400324250 block: *Block,
2400424251 extended: Zir.Inst.Extended.InstData,
2400524252) CompileError!Air.Inst.Ref {
24006 const mod = sema.mod;
24253 const pt = sema.pt;
24254 const mod = pt.zcu;
2400724255 const extra = sema.code.extraData(Zir.Inst.Cmpxchg, extended.operand).data;
2400824256 const air_tag: Air.Inst.Tag = switch (extended.small) {
2400924257 0 => .cmpxchg_weak,
......@@ -24026,7 +24274,7 @@ fn zirCmpxchg(
2402624274 block,
2402724275 elem_ty_src,
2402824276 "expected bool, integer, enum, or pointer type; found '{}'",
24029 .{elem_ty.fmt(mod)},
24277 .{elem_ty.fmt(pt)},
2403024278 );
2403124279 }
2403224280 const uncasted_ptr = try sema.resolveInst(extra.ptr);
......@@ -24052,11 +24300,11 @@ fn zirCmpxchg(
2405224300 return sema.fail(block, failure_order_src, "failure atomic ordering must not be release or acq_rel", .{});
2405324301 }
2405424302
24055 const result_ty = try mod.optionalType(elem_ty.toIntern());
24303 const result_ty = try pt.optionalType(elem_ty.toIntern());
2405624304
2405724305 // special case zero bit types
2405824306 if ((try sema.typeHasOnePossibleValue(elem_ty)) != null) {
24059 return Air.internedToRef((try mod.intern(.{ .opt = .{
24307 return Air.internedToRef((try pt.intern(.{ .opt = .{
2406024308 .ty = result_ty.toIntern(),
2406124309 .val = .none,
2406224310 } })));
......@@ -24068,11 +24316,11 @@ fn zirCmpxchg(
2406824316 if (expected_val.isUndef(mod) or new_val.isUndef(mod)) {
2406924317 // TODO: this should probably cause the memory stored at the pointer
2407024318 // to become undef as well
24071 return mod.undefRef(result_ty);
24319 return pt.undefRef(result_ty);
2407224320 }
2407324321 const ptr_ty = sema.typeOf(ptr);
2407424322 const stored_val = (try sema.pointerDeref(block, ptr_src, ptr_val, ptr_ty)) orelse break :rs ptr_src;
24075 const result_val = try mod.intern(.{ .opt = .{
24323 const result_val = try pt.intern(.{ .opt = .{
2407624324 .ty = result_ty.toIntern(),
2407724325 .val = if (stored_val.eql(expected_val, elem_ty, mod)) blk: {
2407824326 try sema.storePtr(block, src, ptr, new_value);
......@@ -24103,17 +24351,18 @@ fn zirCmpxchg(
2410324351}
2410424352
2410524353fn zirSplat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
24106 const mod = sema.mod;
24354 const pt = sema.pt;
24355 const mod = pt.zcu;
2410724356 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2410824357 const extra = sema.code.extraData(Zir.Inst.Bin, inst_data.payload_index).data;
2410924358 const src = block.nodeOffset(inst_data.src_node);
2411024359 const scalar_src = block.builtinCallArgSrc(inst_data.src_node, 0);
2411124360 const dest_ty = try sema.resolveDestType(block, src, extra.lhs, .remove_eu_opt, "@splat");
2411224361
24113 if (!dest_ty.isVector(mod)) return sema.fail(block, src, "expected vector type, found '{}'", .{dest_ty.fmt(mod)});
24362 if (!dest_ty.isVector(mod)) return sema.fail(block, src, "expected vector type, found '{}'", .{dest_ty.fmt(pt)});
2411424363
24115 if (!dest_ty.hasRuntimeBits(mod)) {
24116 const empty_aggregate = try mod.intern(.{ .aggregate = .{
24364 if (!dest_ty.hasRuntimeBits(pt)) {
24365 const empty_aggregate = try pt.intern(.{ .aggregate = .{
2411724366 .ty = dest_ty.toIntern(),
2411824367 .storage = .{ .elems = &[_]InternPool.Index{} },
2411924368 } });
......@@ -24124,7 +24373,7 @@ fn zirSplat(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.I
2412424373 const scalar_ty = dest_ty.childType(mod);
2412524374 const scalar = try sema.coerce(block, scalar_ty, operand, scalar_src);
2412624375 if (try sema.resolveValue(scalar)) |scalar_val| {
24127 if (scalar_val.isUndef(mod)) return mod.undefRef(dest_ty);
24376 if (scalar_val.isUndef(mod)) return pt.undefRef(dest_ty);
2412824377 return Air.internedToRef((try sema.splat(dest_ty, scalar_val)).toIntern());
2412924378 }
2413024379
......@@ -24142,10 +24391,11 @@ fn zirReduce(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
2414224391 });
2414324392 const operand = try sema.resolveInst(extra.rhs);
2414424393 const operand_ty = sema.typeOf(operand);
24145 const mod = sema.mod;
24394 const pt = sema.pt;
24395 const mod = pt.zcu;
2414624396
2414724397 if (operand_ty.zigTypeTag(mod) != .Vector) {
24148 return sema.fail(block, operand_src, "expected vector, found '{}'", .{operand_ty.fmt(mod)});
24398 return sema.fail(block, operand_src, "expected vector, found '{}'", .{operand_ty.fmt(pt)});
2414924399 }
2415024400
2415124401 const scalar_ty = operand_ty.childType(mod);
......@@ -24155,13 +24405,13 @@ fn zirReduce(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
2415524405 .And, .Or, .Xor => switch (scalar_ty.zigTypeTag(mod)) {
2415624406 .Int, .Bool => {},
2415724407 else => return sema.fail(block, operand_src, "@reduce operation '{s}' requires integer or boolean operand; found '{}'", .{
24158 @tagName(operation), operand_ty.fmt(mod),
24408 @tagName(operation), operand_ty.fmt(pt),
2415924409 }),
2416024410 },
2416124411 .Min, .Max, .Add, .Mul => switch (scalar_ty.zigTypeTag(mod)) {
2416224412 .Int, .Float => {},
2416324413 else => return sema.fail(block, operand_src, "@reduce operation '{s}' requires integer or float operand; found '{}'", .{
24164 @tagName(operation), operand_ty.fmt(mod),
24414 @tagName(operation), operand_ty.fmt(pt),
2416524415 }),
2416624416 },
2416724417 }
......@@ -24174,20 +24424,20 @@ fn zirReduce(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
2417424424 }
2417524425
2417624426 if (try sema.resolveValue(operand)) |operand_val| {
24177 if (operand_val.isUndef(mod)) return mod.undefRef(scalar_ty);
24427 if (operand_val.isUndef(mod)) return pt.undefRef(scalar_ty);
2417824428
24179 var accum: Value = try operand_val.elemValue(mod, 0);
24429 var accum: Value = try operand_val.elemValue(pt, 0);
2418024430 var i: u32 = 1;
2418124431 while (i < vec_len) : (i += 1) {
24182 const elem_val = try operand_val.elemValue(mod, i);
24432 const elem_val = try operand_val.elemValue(pt, i);
2418324433 switch (operation) {
24184 .And => accum = try accum.bitwiseAnd(elem_val, scalar_ty, sema.arena, mod),
24185 .Or => accum = try accum.bitwiseOr(elem_val, scalar_ty, sema.arena, mod),
24186 .Xor => accum = try accum.bitwiseXor(elem_val, scalar_ty, sema.arena, mod),
24187 .Min => accum = accum.numberMin(elem_val, mod),
24188 .Max => accum = accum.numberMax(elem_val, mod),
24434 .And => accum = try accum.bitwiseAnd(elem_val, scalar_ty, sema.arena, pt),
24435 .Or => accum = try accum.bitwiseOr(elem_val, scalar_ty, sema.arena, pt),
24436 .Xor => accum = try accum.bitwiseXor(elem_val, scalar_ty, sema.arena, pt),
24437 .Min => accum = accum.numberMin(elem_val, pt),
24438 .Max => accum = accum.numberMax(elem_val, pt),
2418924439 .Add => accum = try sema.numberAddWrapScalar(accum, elem_val, scalar_ty),
24190 .Mul => accum = try accum.numberMulWrap(elem_val, scalar_ty, sema.arena, mod),
24440 .Mul => accum = try accum.numberMulWrap(elem_val, scalar_ty, sema.arena, pt),
2419124441 }
2419224442 }
2419324443 return Air.internedToRef(accum.toIntern());
......@@ -24204,7 +24454,8 @@ fn zirReduce(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
2420424454}
2420524455
2420624456fn zirShuffle(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
24207 const mod = sema.mod;
24457 const pt = sema.pt;
24458 const mod = pt.zcu;
2420824459 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2420924460 const extra = sema.code.extraData(Zir.Inst.Shuffle, inst_data.payload_index).data;
2421024461 const elem_ty_src = block.builtinCallArgSrc(inst_data.src_node, 0);
......@@ -24219,9 +24470,9 @@ fn zirShuffle(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air
2421924470
2422024471 const mask_len = switch (sema.typeOf(mask).zigTypeTag(mod)) {
2422124472 .Array, .Vector => sema.typeOf(mask).arrayLen(mod),
24222 else => return sema.fail(block, mask_src, "expected vector or array, found '{}'", .{sema.typeOf(mask).fmt(sema.mod)}),
24473 else => return sema.fail(block, mask_src, "expected vector or array, found '{}'", .{sema.typeOf(mask).fmt(pt)}),
2422324474 };
24224 mask_ty = try mod.vectorType(.{
24475 mask_ty = try pt.vectorType(.{
2422524476 .len = @intCast(mask_len),
2422624477 .child = .i32_type,
2422724478 });
......@@ -24242,51 +24493,51 @@ fn analyzeShuffle(
2424224493 mask: Value,
2424324494 mask_len: u32,
2424424495) CompileError!Air.Inst.Ref {
24245 const mod = sema.mod;
24496 const pt = sema.pt;
2424624497 const a_src = block.builtinCallArgSrc(src_node, 1);
2424724498 const b_src = block.builtinCallArgSrc(src_node, 2);
2424824499 const mask_src = block.builtinCallArgSrc(src_node, 3);
2424924500 var a = a_arg;
2425024501 var b = b_arg;
2425124502
24252 const res_ty = try mod.vectorType(.{
24503 const res_ty = try pt.vectorType(.{
2425324504 .len = mask_len,
2425424505 .child = elem_ty.toIntern(),
2425524506 });
2425624507
24257 const maybe_a_len = switch (sema.typeOf(a).zigTypeTag(mod)) {
24258 .Array, .Vector => sema.typeOf(a).arrayLen(mod),
24508 const maybe_a_len = switch (sema.typeOf(a).zigTypeTag(pt.zcu)) {
24509 .Array, .Vector => sema.typeOf(a).arrayLen(pt.zcu),
2425924510 .Undefined => null,
2426024511 else => return sema.fail(block, a_src, "expected vector or array with element type '{}', found '{}'", .{
24261 elem_ty.fmt(sema.mod),
24262 sema.typeOf(a).fmt(sema.mod),
24512 elem_ty.fmt(pt),
24513 sema.typeOf(a).fmt(pt),
2426324514 }),
2426424515 };
24265 const maybe_b_len = switch (sema.typeOf(b).zigTypeTag(mod)) {
24266 .Array, .Vector => sema.typeOf(b).arrayLen(mod),
24516 const maybe_b_len = switch (sema.typeOf(b).zigTypeTag(pt.zcu)) {
24517 .Array, .Vector => sema.typeOf(b).arrayLen(pt.zcu),
2426724518 .Undefined => null,
2426824519 else => return sema.fail(block, b_src, "expected vector or array with element type '{}', found '{}'", .{
24269 elem_ty.fmt(sema.mod),
24270 sema.typeOf(b).fmt(sema.mod),
24520 elem_ty.fmt(pt),
24521 sema.typeOf(b).fmt(pt),
2427124522 }),
2427224523 };
2427324524 if (maybe_a_len == null and maybe_b_len == null) {
24274 return mod.undefRef(res_ty);
24525 return pt.undefRef(res_ty);
2427524526 }
2427624527 const a_len: u32 = @intCast(maybe_a_len orelse maybe_b_len.?);
2427724528 const b_len: u32 = @intCast(maybe_b_len orelse a_len);
2427824529
24279 const a_ty = try mod.vectorType(.{
24530 const a_ty = try pt.vectorType(.{
2428024531 .len = a_len,
2428124532 .child = elem_ty.toIntern(),
2428224533 });
24283 const b_ty = try mod.vectorType(.{
24534 const b_ty = try pt.vectorType(.{
2428424535 .len = b_len,
2428524536 .child = elem_ty.toIntern(),
2428624537 });
2428724538
24288 if (maybe_a_len == null) a = try mod.undefRef(a_ty) else a = try sema.coerce(block, a_ty, a, a_src);
24289 if (maybe_b_len == null) b = try mod.undefRef(b_ty) else b = try sema.coerce(block, b_ty, b, b_src);
24539 if (maybe_a_len == null) a = try pt.undefRef(a_ty) else a = try sema.coerce(block, a_ty, a, a_src);
24540 if (maybe_b_len == null) b = try pt.undefRef(b_ty) else b = try sema.coerce(block, b_ty, b, b_src);
2429024541
2429124542 const operand_info = [2]std.meta.Tuple(&.{ u64, LazySrcLoc, Type }){
2429224543 .{ a_len, a_src, a_ty },
......@@ -24294,10 +24545,10 @@ fn analyzeShuffle(
2429424545 };
2429524546
2429624547 for (0..@intCast(mask_len)) |i| {
24297 const elem = try mask.elemValue(sema.mod, i);
24298 if (elem.isUndef(mod)) continue;
24548 const elem = try mask.elemValue(pt, i);
24549 if (elem.isUndef(pt.zcu)) continue;
2429924550 const elem_resolved = try sema.resolveLazyValue(elem);
24300 const int = elem_resolved.toSignedInt(mod);
24551 const int = elem_resolved.toSignedInt(pt);
2430124552 var unsigned: u32 = undefined;
2430224553 var chosen: u32 = undefined;
2430324554 if (int >= 0) {
......@@ -24314,7 +24565,7 @@ fn analyzeShuffle(
2431424565
2431524566 try sema.errNote(operand_info[chosen][1], msg, "selected index '{d}' out of bounds of '{}'", .{
2431624567 unsigned,
24317 operand_info[chosen][2].fmt(sema.mod),
24568 operand_info[chosen][2].fmt(pt),
2431824569 });
2431924570
2432024571 if (chosen == 0) {
......@@ -24331,16 +24582,16 @@ fn analyzeShuffle(
2433124582 if (try sema.resolveValue(b)) |b_val| {
2433224583 const values = try sema.arena.alloc(InternPool.Index, mask_len);
2433324584 for (values, 0..) |*value, i| {
24334 const mask_elem_val = try mask.elemValue(sema.mod, i);
24335 if (mask_elem_val.isUndef(mod)) {
24336 value.* = try mod.intern(.{ .undef = elem_ty.toIntern() });
24585 const mask_elem_val = try mask.elemValue(pt, i);
24586 if (mask_elem_val.isUndef(pt.zcu)) {
24587 value.* = try pt.intern(.{ .undef = elem_ty.toIntern() });
2433724588 continue;
2433824589 }
24339 const int = mask_elem_val.toSignedInt(mod);
24590 const int = mask_elem_val.toSignedInt(pt);
2434024591 const unsigned: u32 = @intCast(if (int >= 0) int else ~int);
24341 values[i] = (try (if (int >= 0) a_val else b_val).elemValue(mod, unsigned)).toIntern();
24592 values[i] = (try (if (int >= 0) a_val else b_val).elemValue(pt, unsigned)).toIntern();
2434224593 }
24343 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
24594 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
2434424595 .ty = res_ty.toIntern(),
2434524596 .storage = .{ .elems = values },
2434624597 } })));
......@@ -24359,21 +24610,21 @@ fn analyzeShuffle(
2435924610
2436024611 const expand_mask_values = try sema.arena.alloc(InternPool.Index, max_len);
2436124612 for (@intCast(0)..@intCast(min_len)) |i| {
24362 expand_mask_values[i] = (try mod.intValue(Type.comptime_int, i)).toIntern();
24613 expand_mask_values[i] = (try pt.intValue(Type.comptime_int, i)).toIntern();
2436324614 }
2436424615 for (@intCast(min_len)..@intCast(max_len)) |i| {
24365 expand_mask_values[i] = (try mod.intValue(Type.comptime_int, -1)).toIntern();
24616 expand_mask_values[i] = (try pt.intValue(Type.comptime_int, -1)).toIntern();
2436624617 }
24367 const expand_mask = try mod.intern(.{ .aggregate = .{
24368 .ty = (try mod.vectorType(.{ .len = @intCast(max_len), .child = .comptime_int_type })).toIntern(),
24618 const expand_mask = try pt.intern(.{ .aggregate = .{
24619 .ty = (try pt.vectorType(.{ .len = @intCast(max_len), .child = .comptime_int_type })).toIntern(),
2436924620 .storage = .{ .elems = expand_mask_values },
2437024621 } });
2437124622
2437224623 if (a_len < b_len) {
24373 const undef = try mod.undefRef(a_ty);
24624 const undef = try pt.undefRef(a_ty);
2437424625 a = try sema.analyzeShuffle(block, src_node, elem_ty, a, undef, Value.fromInterned(expand_mask), @intCast(max_len));
2437524626 } else {
24376 const undef = try mod.undefRef(b_ty);
24627 const undef = try pt.undefRef(b_ty);
2437724628 b = try sema.analyzeShuffle(block, src_node, elem_ty, b, undef, Value.fromInterned(expand_mask), @intCast(max_len));
2437824629 }
2437924630 }
......@@ -24393,7 +24644,8 @@ fn analyzeShuffle(
2439324644}
2439424645
2439524646fn zirSelect(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
24396 const mod = sema.mod;
24647 const pt = sema.pt;
24648 const mod = pt.zcu;
2439724649 const extra = sema.code.extraData(Zir.Inst.Select, extended.operand).data;
2439824650
2439924651 const src = block.nodeOffset(extra.node);
......@@ -24409,17 +24661,17 @@ fn zirSelect(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) C
2440924661
2441024662 const vec_len_u64 = switch (try pred_ty.zigTypeTagOrPoison(mod)) {
2441124663 .Vector, .Array => pred_ty.arrayLen(mod),
24412 else => return sema.fail(block, pred_src, "expected vector or array, found '{}'", .{pred_ty.fmt(mod)}),
24664 else => return sema.fail(block, pred_src, "expected vector or array, found '{}'", .{pred_ty.fmt(pt)}),
2441324665 };
2441424666 const vec_len: u32 = @intCast(try sema.usizeCast(block, pred_src, vec_len_u64));
2441524667
24416 const bool_vec_ty = try mod.vectorType(.{
24668 const bool_vec_ty = try pt.vectorType(.{
2441724669 .len = vec_len,
2441824670 .child = .bool_type,
2441924671 });
2442024672 const pred = try sema.coerce(block, bool_vec_ty, pred_uncoerced, pred_src);
2442124673
24422 const vec_ty = try mod.vectorType(.{
24674 const vec_ty = try pt.vectorType(.{
2442324675 .len = vec_len,
2442424676 .child = elem_ty.toIntern(),
2442524677 });
......@@ -24431,23 +24683,23 @@ fn zirSelect(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) C
2443124683 const maybe_b = try sema.resolveValue(b);
2443224684
2443324685 const runtime_src = if (maybe_pred) |pred_val| rs: {
24434 if (pred_val.isUndef(mod)) return mod.undefRef(vec_ty);
24686 if (pred_val.isUndef(mod)) return pt.undefRef(vec_ty);
2443524687
2443624688 if (maybe_a) |a_val| {
24437 if (a_val.isUndef(mod)) return mod.undefRef(vec_ty);
24689 if (a_val.isUndef(mod)) return pt.undefRef(vec_ty);
2443824690
2443924691 if (maybe_b) |b_val| {
24440 if (b_val.isUndef(mod)) return mod.undefRef(vec_ty);
24692 if (b_val.isUndef(mod)) return pt.undefRef(vec_ty);
2444124693
2444224694 const elems = try sema.gpa.alloc(InternPool.Index, vec_len);
2444324695 defer sema.gpa.free(elems);
2444424696 for (elems, 0..) |*elem, i| {
24445 const pred_elem_val = try pred_val.elemValue(mod, i);
24697 const pred_elem_val = try pred_val.elemValue(pt, i);
2444624698 const should_choose_a = pred_elem_val.toBool();
24447 elem.* = (try (if (should_choose_a) a_val else b_val).elemValue(mod, i)).toIntern();
24699 elem.* = (try (if (should_choose_a) a_val else b_val).elemValue(pt, i)).toIntern();
2444824700 }
2444924701
24450 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
24702 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
2445124703 .ty = vec_ty.toIntern(),
2445224704 .storage = .{ .elems = elems },
2445324705 } })));
......@@ -24456,16 +24708,16 @@ fn zirSelect(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) C
2445624708 }
2445724709 } else {
2445824710 if (maybe_b) |b_val| {
24459 if (b_val.isUndef(mod)) return mod.undefRef(vec_ty);
24711 if (b_val.isUndef(mod)) return pt.undefRef(vec_ty);
2446024712 }
2446124713 break :rs a_src;
2446224714 }
2446324715 } else rs: {
2446424716 if (maybe_a) |a_val| {
24465 if (a_val.isUndef(mod)) return mod.undefRef(vec_ty);
24717 if (a_val.isUndef(mod)) return pt.undefRef(vec_ty);
2446624718 }
2446724719 if (maybe_b) |b_val| {
24468 if (b_val.isUndef(mod)) return mod.undefRef(vec_ty);
24720 if (b_val.isUndef(mod)) return pt.undefRef(vec_ty);
2446924721 }
2447024722 break :rs pred_src;
2447124723 };
......@@ -24531,7 +24783,8 @@ fn zirAtomicLoad(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!
2453124783}
2453224784
2453324785fn zirAtomicRmw(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.Inst.Ref {
24534 const mod = sema.mod;
24786 const pt = sema.pt;
24787 const mod = pt.zcu;
2453524788 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2453624789 const extra = sema.code.extraData(Zir.Inst.AtomicRmw, inst_data.payload_index).data;
2453724790 const src = block.nodeOffset(inst_data.src_node);
......@@ -24588,12 +24841,12 @@ fn zirAtomicRmw(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
2458824841 .Xchg => operand_val,
2458924842 .Add => try sema.numberAddWrapScalar(stored_val, operand_val, elem_ty),
2459024843 .Sub => try sema.numberSubWrapScalar(stored_val, operand_val, elem_ty),
24591 .And => try stored_val.bitwiseAnd (operand_val, elem_ty, sema.arena, mod),
24592 .Nand => try stored_val.bitwiseNand (operand_val, elem_ty, sema.arena, mod),
24593 .Or => try stored_val.bitwiseOr (operand_val, elem_ty, sema.arena, mod),
24594 .Xor => try stored_val.bitwiseXor (operand_val, elem_ty, sema.arena, mod),
24595 .Max => stored_val.numberMax (operand_val, mod),
24596 .Min => stored_val.numberMin (operand_val, mod),
24844 .And => try stored_val.bitwiseAnd (operand_val, elem_ty, sema.arena, pt),
24845 .Nand => try stored_val.bitwiseNand (operand_val, elem_ty, sema.arena, pt),
24846 .Or => try stored_val.bitwiseOr (operand_val, elem_ty, sema.arena, pt),
24847 .Xor => try stored_val.bitwiseXor (operand_val, elem_ty, sema.arena, pt),
24848 .Max => stored_val.numberMax (operand_val, pt),
24849 .Min => stored_val.numberMin (operand_val, pt),
2459724850 // zig fmt: on
2459824851 };
2459924852 try sema.storePtrVal(block, src, ptr_val, new_val, elem_ty);
......@@ -24669,36 +24922,37 @@ fn zirMulAdd(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!Air.
2466924922 const maybe_mulend1 = try sema.resolveValue(mulend1);
2467024923 const maybe_mulend2 = try sema.resolveValue(mulend2);
2467124924 const maybe_addend = try sema.resolveValue(addend);
24672 const mod = sema.mod;
24925 const pt = sema.pt;
24926 const mod = pt.zcu;
2467324927
2467424928 switch (ty.scalarType(mod).zigTypeTag(mod)) {
2467524929 .ComptimeFloat, .Float => {},
24676 else => return sema.fail(block, src, "expected vector of floats or float type, found '{}'", .{ty.fmt(sema.mod)}),
24930 else => return sema.fail(block, src, "expected vector of floats or float type, found '{}'", .{ty.fmt(pt)}),
2467724931 }
2467824932
2467924933 const runtime_src = if (maybe_mulend1) |mulend1_val| rs: {
2468024934 if (maybe_mulend2) |mulend2_val| {
24681 if (mulend2_val.isUndef(mod)) return mod.undefRef(ty);
24935 if (mulend2_val.isUndef(mod)) return pt.undefRef(ty);
2468224936
2468324937 if (maybe_addend) |addend_val| {
24684 if (addend_val.isUndef(mod)) return mod.undefRef(ty);
24685 const result_val = try Value.mulAdd(ty, mulend1_val, mulend2_val, addend_val, sema.arena, sema.mod);
24938 if (addend_val.isUndef(mod)) return pt.undefRef(ty);
24939 const result_val = try Value.mulAdd(ty, mulend1_val, mulend2_val, addend_val, sema.arena, pt);
2468624940 return Air.internedToRef(result_val.toIntern());
2468724941 } else {
2468824942 break :rs addend_src;
2468924943 }
2469024944 } else {
2469124945 if (maybe_addend) |addend_val| {
24692 if (addend_val.isUndef(mod)) return mod.undefRef(ty);
24946 if (addend_val.isUndef(mod)) return pt.undefRef(ty);
2469324947 }
2469424948 break :rs mulend2_src;
2469524949 }
2469624950 } else rs: {
2469724951 if (maybe_mulend2) |mulend2_val| {
24698 if (mulend2_val.isUndef(mod)) return mod.undefRef(ty);
24952 if (mulend2_val.isUndef(mod)) return pt.undefRef(ty);
2469924953 }
2470024954 if (maybe_addend) |addend_val| {
24701 if (addend_val.isUndef(mod)) return mod.undefRef(ty);
24955 if (addend_val.isUndef(mod)) return pt.undefRef(ty);
2470224956 }
2470324957 break :rs mulend1_src;
2470424958 };
......@@ -24720,7 +24974,8 @@ fn zirBuiltinCall(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
2472024974 const tracy = trace(@src());
2472124975 defer tracy.end();
2472224976
24723 const mod = sema.mod;
24977 const pt = sema.pt;
24978 const mod = pt.zcu;
2472424979 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2472524980 const modifier_src = block.builtinCallArgSrc(inst_data.src_node, 0);
2472624981 const func_src = block.builtinCallArgSrc(inst_data.src_node, 1);
......@@ -24730,7 +24985,7 @@ fn zirBuiltinCall(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
2473024985 const extra = sema.code.extraData(Zir.Inst.BuiltinCall, inst_data.payload_index).data;
2473124986 const func = try sema.resolveInst(extra.callee);
2473224987
24733 const modifier_ty = try mod.getBuiltinType("CallModifier");
24988 const modifier_ty = try pt.getBuiltinType("CallModifier");
2473424989 const air_ref = try sema.resolveInst(extra.modifier);
2473524990 const modifier_ref = try sema.coerce(block, modifier_ty, air_ref, modifier_src);
2473624991 const modifier_val = try sema.resolveConstDefinedValue(block, modifier_src, modifier_ref, .{
......@@ -24783,7 +25038,7 @@ fn zirBuiltinCall(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
2478325038
2478425039 const args_ty = sema.typeOf(args);
2478525040 if (!args_ty.isTuple(mod) and args_ty.toIntern() != .empty_struct_type) {
24786 return sema.fail(block, args_src, "expected a tuple, found '{}'", .{args_ty.fmt(sema.mod)});
25041 return sema.fail(block, args_src, "expected a tuple, found '{}'", .{args_ty.fmt(pt)});
2478725042 }
2478825043
2478925044 const resolved_args: []Air.Inst.Ref = try sema.arena.alloc(Air.Inst.Ref, args_ty.structFieldCount(mod));
......@@ -24812,7 +25067,8 @@ fn zirBuiltinCall(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError
2481225067}
2481325068
2481425069fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.InstData) CompileError!Air.Inst.Ref {
24815 const zcu = sema.mod;
25070 const pt = sema.pt;
25071 const zcu = pt.zcu;
2481625072 const ip = &zcu.intern_pool;
2481725073
2481825074 const extra = sema.code.extraData(Zir.Inst.FieldParentPtr, extended.operand).data;
......@@ -24827,14 +25083,14 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2482725083 try sema.checkPtrType(block, inst_src, parent_ptr_ty, true);
2482825084 const parent_ptr_info = parent_ptr_ty.ptrInfo(zcu);
2482925085 if (parent_ptr_info.flags.size != .One) {
24830 return sema.fail(block, inst_src, "expected single pointer type, found '{}'", .{parent_ptr_ty.fmt(zcu)});
25086 return sema.fail(block, inst_src, "expected single pointer type, found '{}'", .{parent_ptr_ty.fmt(pt)});
2483125087 }
2483225088 const parent_ty = Type.fromInterned(parent_ptr_info.child);
2483325089 switch (parent_ty.zigTypeTag(zcu)) {
2483425090 .Struct, .Union => {},
24835 else => return sema.fail(block, inst_src, "expected pointer to struct or union type, found '{}'", .{parent_ptr_ty.fmt(zcu)}),
25091 else => return sema.fail(block, inst_src, "expected pointer to struct or union type, found '{}'", .{parent_ptr_ty.fmt(pt)}),
2483625092 }
24837 try parent_ty.resolveLayout(zcu);
25093 try parent_ty.resolveLayout(pt);
2483825094
2483925095 const field_name = try sema.resolveConstStringIntern(block, field_name_src, extra.field_name, .{
2484025096 .needed_comptime_reason = "field name must be comptime-known",
......@@ -24865,7 +25121,7 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2486525121 var actual_parent_ptr_info: InternPool.Key.PtrType = .{
2486625122 .child = parent_ty.toIntern(),
2486725123 .flags = .{
24868 .alignment = try parent_ptr_ty.ptrAlignmentAdvanced(zcu, .sema),
25124 .alignment = try parent_ptr_ty.ptrAlignmentAdvanced(pt, .sema),
2486925125 .is_const = field_ptr_info.flags.is_const,
2487025126 .is_volatile = field_ptr_info.flags.is_volatile,
2487125127 .is_allowzero = field_ptr_info.flags.is_allowzero,
......@@ -24877,7 +25133,7 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2487725133 var actual_field_ptr_info: InternPool.Key.PtrType = .{
2487825134 .child = field_ty.toIntern(),
2487925135 .flags = .{
24880 .alignment = try field_ptr_ty.ptrAlignmentAdvanced(zcu, .sema),
25136 .alignment = try field_ptr_ty.ptrAlignmentAdvanced(pt, .sema),
2488125137 .is_const = field_ptr_info.flags.is_const,
2488225138 .is_volatile = field_ptr_info.flags.is_volatile,
2488325139 .is_allowzero = field_ptr_info.flags.is_allowzero,
......@@ -24888,13 +25144,13 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2488825144 switch (parent_ty.containerLayout(zcu)) {
2488925145 .auto => {
2489025146 actual_parent_ptr_info.flags.alignment = actual_field_ptr_info.flags.alignment.minStrict(
24891 if (zcu.typeToStruct(parent_ty)) |struct_obj| try zcu.structFieldAlignmentAdvanced(
25147 if (zcu.typeToStruct(parent_ty)) |struct_obj| try pt.structFieldAlignmentAdvanced(
2489225148 struct_obj.fieldAlign(ip, field_index),
2489325149 field_ty,
2489425150 struct_obj.layout,
2489525151 .sema,
2489625152 ) else if (zcu.typeToUnion(parent_ty)) |union_obj|
24897 try zcu.unionFieldNormalAlignmentAdvanced(union_obj, field_index, .sema)
25153 try pt.unionFieldNormalAlignmentAdvanced(union_obj, field_index, .sema)
2489825154 else
2489925155 actual_field_ptr_info.flags.alignment,
2490025156 );
......@@ -24903,7 +25159,7 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2490325159 actual_field_ptr_info.packed_offset = .{ .bit_offset = 0, .host_size = 0 };
2490425160 },
2490525161 .@"extern" => {
24906 const field_offset = parent_ty.structFieldOffset(field_index, zcu);
25162 const field_offset = parent_ty.structFieldOffset(field_index, pt);
2490725163 actual_parent_ptr_info.flags.alignment = actual_field_ptr_info.flags.alignment.minStrict(if (field_offset > 0)
2490825164 Alignment.fromLog2Units(@ctz(field_offset))
2490925165 else
......@@ -24914,7 +25170,7 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2491425170 },
2491525171 .@"packed" => {
2491625172 const byte_offset = std.math.divExact(u32, @abs(@as(i32, actual_parent_ptr_info.packed_offset.bit_offset) +
24917 (if (zcu.typeToStruct(parent_ty)) |struct_obj| zcu.structPackedFieldBitOffset(struct_obj, field_index) else 0) -
25173 (if (zcu.typeToStruct(parent_ty)) |struct_obj| pt.structPackedFieldBitOffset(struct_obj, field_index) else 0) -
2491825174 actual_field_ptr_info.packed_offset.bit_offset), 8) catch
2491925175 return sema.fail(block, inst_src, "pointer bit-offset mismatch", .{});
2492025176 actual_parent_ptr_info.flags.alignment = actual_field_ptr_info.flags.alignment.minStrict(if (byte_offset > 0)
......@@ -24924,16 +25180,16 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2492425180 },
2492525181 }
2492625182
24927 const actual_field_ptr_ty = try zcu.ptrTypeSema(actual_field_ptr_info);
25183 const actual_field_ptr_ty = try pt.ptrTypeSema(actual_field_ptr_info);
2492825184 const casted_field_ptr = try sema.coerce(block, actual_field_ptr_ty, field_ptr, field_ptr_src);
24929 const actual_parent_ptr_ty = try zcu.ptrTypeSema(actual_parent_ptr_info);
25185 const actual_parent_ptr_ty = try pt.ptrTypeSema(actual_parent_ptr_info);
2493025186
2493125187 const result = if (try sema.resolveDefinedValue(block, field_ptr_src, casted_field_ptr)) |field_ptr_val| result: {
2493225188 switch (parent_ty.zigTypeTag(zcu)) {
2493325189 .Struct => switch (parent_ty.containerLayout(zcu)) {
2493425190 .auto => {},
2493525191 .@"extern" => {
24936 const byte_offset = parent_ty.structFieldOffset(field_index, zcu);
25192 const byte_offset = parent_ty.structFieldOffset(field_index, pt);
2493725193 const parent_ptr_val = try sema.ptrSubtract(block, field_ptr_src, field_ptr_val, byte_offset, actual_parent_ptr_ty);
2493825194 break :result Air.internedToRef(parent_ptr_val.toIntern());
2493925195 },
......@@ -24941,7 +25197,7 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2494125197 // Logic lifted from type computation above - I'm just assuming it's correct.
2494225198 // `catch unreachable` since error case handled above.
2494325199 const byte_offset = std.math.divExact(u32, @abs(@as(i32, actual_parent_ptr_info.packed_offset.bit_offset) +
24944 zcu.structPackedFieldBitOffset(zcu.typeToStruct(parent_ty).?, field_index) -
25200 pt.structPackedFieldBitOffset(zcu.typeToStruct(parent_ty).?, field_index) -
2494525201 actual_field_ptr_info.packed_offset.bit_offset), 8) catch unreachable;
2494625202 const parent_ptr_val = try sema.ptrSubtract(block, field_ptr_src, field_ptr_val, byte_offset, actual_parent_ptr_ty);
2494725203 break :result Air.internedToRef(parent_ptr_val.toIntern());
......@@ -24951,7 +25207,7 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2495125207 .auto => {},
2495225208 .@"extern", .@"packed" => {
2495325209 // For an extern or packed union, just coerce the pointer.
24954 const parent_ptr_val = try zcu.getCoerced(field_ptr_val, actual_parent_ptr_ty);
25210 const parent_ptr_val = try pt.getCoerced(field_ptr_val, actual_parent_ptr_ty);
2495525211 break :result Air.internedToRef(parent_ptr_val.toIntern());
2495625212 },
2495725213 },
......@@ -24980,7 +25236,7 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2498025236
2498125237 if (field.index != field_index) {
2498225238 return sema.fail(block, inst_src, "field '{}' has index '{d}' but pointer value is index '{d}' of struct '{}'", .{
24983 field_name.fmt(ip), field_index, field.index, parent_ty.fmt(zcu),
25239 field_name.fmt(ip), field_index, field.index, parent_ty.fmt(pt),
2498425240 });
2498525241 }
2498625242 break :result try sema.coerce(block, actual_parent_ptr_ty, Air.internedToRef(field.base), inst_src);
......@@ -25001,8 +25257,9 @@ fn zirFieldParentPtr(sema: *Sema, block: *Block, extended: Zir.Inst.Extended.Ins
2500125257}
2500225258
2500325259fn ptrSubtract(sema: *Sema, block: *Block, src: LazySrcLoc, ptr_val: Value, byte_subtract: u64, new_ty: Type) !Value {
25004 const zcu = sema.mod;
25005 if (byte_subtract == 0) return zcu.getCoerced(ptr_val, new_ty);
25260 const pt = sema.pt;
25261 const zcu = pt.zcu;
25262 if (byte_subtract == 0) return pt.getCoerced(ptr_val, new_ty);
2500625263 var ptr = switch (zcu.intern_pool.indexToKey(ptr_val.toIntern())) {
2500725264 .undef => return sema.failWithUseOfUndef(block, src),
2500825265 .ptr => |ptr| ptr,
......@@ -25018,7 +25275,7 @@ fn ptrSubtract(sema: *Sema, block: *Block, src: LazySrcLoc, ptr_val: Value, byte
2501825275 }
2501925276 ptr.byte_offset -= byte_subtract;
2502025277 ptr.ty = new_ty.toIntern();
25021 return Value.fromInterned(try zcu.intern(.{ .ptr = ptr }));
25278 return Value.fromInterned(try pt.intern(.{ .ptr = ptr }));
2502225279}
2502325280
2502425281fn zirMinMax(
......@@ -25072,7 +25329,8 @@ fn analyzeMinMax(
2507225329) CompileError!Air.Inst.Ref {
2507325330 assert(operands.len == operand_srcs.len);
2507425331 assert(operands.len > 0);
25075 const mod = sema.mod;
25332 const pt = sema.pt;
25333 const mod = pt.zcu;
2507625334
2507725335 if (operands.len == 1) return operands[0];
2507825336
......@@ -25115,15 +25373,15 @@ fn analyzeMinMax(
2511525373 break :refine_bounds;
2511625374 }
2511725375 const scalar_bounds: ?[2]Value = bounds: {
25118 if (!ty.isVector(mod)) break :bounds try uncoerced_val.intValueBounds(mod);
25119 var cur_bounds: [2]Value = try Value.intValueBounds(try uncoerced_val.elemValue(mod, 0), mod) orelse break :bounds null;
25376 if (!ty.isVector(mod)) break :bounds try uncoerced_val.intValueBounds(pt);
25377 var cur_bounds: [2]Value = try Value.intValueBounds(try uncoerced_val.elemValue(pt, 0), pt) orelse break :bounds null;
2512025378 const len = try sema.usizeCast(block, src, ty.vectorLen(mod));
2512125379 for (1..len) |i| {
25122 const elem = try uncoerced_val.elemValue(mod, i);
25123 const elem_bounds = try elem.intValueBounds(mod) orelse break :bounds null;
25380 const elem = try uncoerced_val.elemValue(pt, i);
25381 const elem_bounds = try elem.intValueBounds(pt) orelse break :bounds null;
2512425382 cur_bounds = .{
25125 Value.numberMin(elem_bounds[0], cur_bounds[0], mod),
25126 Value.numberMax(elem_bounds[1], cur_bounds[1], mod),
25383 Value.numberMin(elem_bounds[0], cur_bounds[0], pt),
25384 Value.numberMax(elem_bounds[1], cur_bounds[1], pt),
2512725385 };
2512825386 }
2512925387 break :bounds cur_bounds;
......@@ -25134,8 +25392,8 @@ fn analyzeMinMax(
2513425392 cur_max_scalar = bounds[1];
2513525393 bounds_status = .defined;
2513625394 } else {
25137 cur_min_scalar = opFunc(cur_min_scalar, bounds[0], mod);
25138 cur_max_scalar = opFunc(cur_max_scalar, bounds[1], mod);
25395 cur_min_scalar = opFunc(cur_min_scalar, bounds[0], pt);
25396 cur_max_scalar = opFunc(cur_max_scalar, bounds[1], pt);
2513925397 }
2514025398 }
2514125399 },
......@@ -25153,18 +25411,18 @@ fn analyzeMinMax(
2515325411 const operand_val = try sema.resolveLazyValue(simd_op.rhs_val.?); // we checked the operand was resolvable above
2515425412
2515525413 const vec_len = simd_op.len orelse {
25156 const result_val = opFunc(cur_val, operand_val, mod);
25414 const result_val = opFunc(cur_val, operand_val, pt);
2515725415 cur_minmax = Air.internedToRef(result_val.toIntern());
2515825416 continue;
2515925417 };
2516025418 const elems = try sema.arena.alloc(InternPool.Index, vec_len);
2516125419 for (elems, 0..) |*elem, i| {
25162 const lhs_elem_val = try cur_val.elemValue(mod, i);
25163 const rhs_elem_val = try operand_val.elemValue(mod, i);
25164 const uncoerced_elem = opFunc(lhs_elem_val, rhs_elem_val, mod);
25165 elem.* = (try mod.getCoerced(uncoerced_elem, simd_op.scalar_ty)).toIntern();
25420 const lhs_elem_val = try cur_val.elemValue(pt, i);
25421 const rhs_elem_val = try operand_val.elemValue(pt, i);
25422 const uncoerced_elem = opFunc(lhs_elem_val, rhs_elem_val, pt);
25423 elem.* = (try pt.getCoerced(uncoerced_elem, simd_op.scalar_ty)).toIntern();
2516625424 }
25167 cur_minmax = Air.internedToRef((try mod.intern(.{ .aggregate = .{
25425 cur_minmax = Air.internedToRef((try pt.intern(.{ .aggregate = .{
2516825426 .ty = simd_op.result_ty.toIntern(),
2516925427 .storage = .{ .elems = elems },
2517025428 } })));
......@@ -25191,8 +25449,8 @@ fn analyzeMinMax(
2519125449
2519225450 assert(bounds_status == .defined); // there was a non-comptime-int integral comptime-known arg
2519325451
25194 const refined_scalar_ty = try mod.intFittingRange(cur_min_scalar, cur_max_scalar);
25195 const refined_ty = if (orig_ty.isVector(mod)) try mod.vectorType(.{
25452 const refined_scalar_ty = try pt.intFittingRange(cur_min_scalar, cur_max_scalar);
25453 const refined_ty = if (orig_ty.isVector(mod)) try pt.vectorType(.{
2519625454 .len = orig_ty.vectorLen(mod),
2519725455 .child = refined_scalar_ty.toIntern(),
2519825456 }) else refined_scalar_ty;
......@@ -25226,8 +25484,8 @@ fn analyzeMinMax(
2522625484 runtime_known.unset(0); // don't look at this operand in the loop below
2522725485 const scalar_ty = sema.typeOf(cur_minmax.?).scalarType(mod);
2522825486 if (scalar_ty.isInt(mod)) {
25229 cur_min_scalar = try scalar_ty.minInt(mod, scalar_ty);
25230 cur_max_scalar = try scalar_ty.maxInt(mod, scalar_ty);
25487 cur_min_scalar = try scalar_ty.minInt(pt, scalar_ty);
25488 cur_max_scalar = try scalar_ty.maxInt(pt, scalar_ty);
2523125489 bounds_status = .defined;
2523225490 } else {
2523325491 bounds_status = .non_integral;
......@@ -25242,7 +25500,7 @@ fn analyzeMinMax(
2524225500 const rhs_src = operand_srcs[idx];
2524325501 const simd_op = try sema.checkSimdBinOp(block, src, lhs, rhs, lhs_src, rhs_src);
2524425502 if (known_undef) {
25245 cur_minmax = try mod.undefRef(simd_op.result_ty);
25503 cur_minmax = try pt.undefRef(simd_op.result_ty);
2524625504 } else {
2524725505 cur_minmax = try block.addBinOp(air_tag, simd_op.lhs, simd_op.rhs);
2524825506 }
......@@ -25254,15 +25512,15 @@ fn analyzeMinMax(
2525425512 bounds_status = .non_integral;
2525525513 break :refine_bounds;
2525625514 }
25257 const scalar_min = try scalar_ty.minInt(mod, scalar_ty);
25258 const scalar_max = try scalar_ty.maxInt(mod, scalar_ty);
25515 const scalar_min = try scalar_ty.minInt(pt, scalar_ty);
25516 const scalar_max = try scalar_ty.maxInt(pt, scalar_ty);
2525925517 if (bounds_status == .unknown) {
2526025518 cur_min_scalar = scalar_min;
2526125519 cur_max_scalar = scalar_max;
2526225520 bounds_status = .defined;
2526325521 } else {
25264 cur_min_scalar = opFunc(cur_min_scalar, scalar_min, mod);
25265 cur_max_scalar = opFunc(cur_max_scalar, scalar_max, mod);
25522 cur_min_scalar = opFunc(cur_min_scalar, scalar_min, pt);
25523 cur_max_scalar = opFunc(cur_max_scalar, scalar_max, pt);
2526625524 }
2526725525 },
2526825526 .non_integral => {},
......@@ -25276,8 +25534,8 @@ fn analyzeMinMax(
2527625534 return cur_minmax.?;
2527725535 }
2527825536 assert(bounds_status == .defined); // there were integral runtime operands
25279 const refined_scalar_ty = try mod.intFittingRange(cur_min_scalar, cur_max_scalar);
25280 const refined_ty = if (unrefined_ty.isVector(mod)) try mod.vectorType(.{
25537 const refined_scalar_ty = try pt.intFittingRange(cur_min_scalar, cur_max_scalar);
25538 const refined_ty = if (unrefined_ty.isVector(mod)) try pt.vectorType(.{
2528125539 .len = unrefined_ty.vectorLen(mod),
2528225540 .child = refined_scalar_ty.toIntern(),
2528325541 }) else refined_scalar_ty;
......@@ -25291,15 +25549,16 @@ fn analyzeMinMax(
2529125549}
2529225550
2529325551fn upgradeToArrayPtr(sema: *Sema, block: *Block, ptr: Air.Inst.Ref, len: u64) !Air.Inst.Ref {
25294 const mod = sema.mod;
25552 const pt = sema.pt;
25553 const mod = pt.zcu;
2529525554 const ptr_ty = sema.typeOf(ptr);
2529625555 const info = ptr_ty.ptrInfo(mod);
2529725556 if (info.flags.size == .One) {
2529825557 // Already an array pointer.
2529925558 return ptr;
2530025559 }
25301 const new_ty = try mod.ptrTypeSema(.{
25302 .child = (try mod.arrayType(.{
25560 const new_ty = try pt.ptrTypeSema(.{
25561 .child = (try pt.arrayType(.{
2530325562 .len = len,
2530425563 .sentinel = info.sentinel,
2530525564 .child = info.child,
......@@ -25331,8 +25590,9 @@ fn zirMemcpy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2533125590 const src_ty = sema.typeOf(src_ptr);
2533225591 const dest_len = try indexablePtrLenOrNone(sema, block, dest_src, dest_ptr);
2533325592 const src_len = try indexablePtrLenOrNone(sema, block, src_src, src_ptr);
25334 const target = sema.mod.getTarget();
25335 const mod = sema.mod;
25593 const pt = sema.pt;
25594 const mod = pt.zcu;
25595 const target = mod.getTarget();
2533625596
2533725597 if (dest_ty.isConstPtr(mod)) {
2533825598 return sema.fail(block, dest_src, "cannot memcpy to constant pointer", .{});
......@@ -25343,10 +25603,10 @@ fn zirMemcpy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2534325603 const msg = try sema.errMsg(src, "unknown @memcpy length", .{});
2534425604 errdefer msg.destroy(sema.gpa);
2534525605 try sema.errNote(dest_src, msg, "destination type '{}' provides no length", .{
25346 dest_ty.fmt(sema.mod),
25606 dest_ty.fmt(pt),
2534725607 });
2534825608 try sema.errNote(src_src, msg, "source type '{}' provides no length", .{
25349 src_ty.fmt(sema.mod),
25609 src_ty.fmt(pt),
2535025610 });
2535125611 break :msg msg;
2535225612 };
......@@ -25365,10 +25625,10 @@ fn zirMemcpy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2536525625 const msg = try sema.errMsg(src, "non-matching @memcpy lengths", .{});
2536625626 errdefer msg.destroy(sema.gpa);
2536725627 try sema.errNote(dest_src, msg, "length {} here", .{
25368 dest_len_val.fmtValue(sema.mod, sema),
25628 dest_len_val.fmtValue(pt, sema),
2536925629 });
2537025630 try sema.errNote(src_src, msg, "length {} here", .{
25371 src_len_val.fmtValue(sema.mod, sema),
25631 src_len_val.fmtValue(pt, sema),
2537225632 });
2537325633 break :msg msg;
2537425634 };
......@@ -25397,10 +25657,10 @@ fn zirMemcpy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2539725657 const runtime_src = if (try sema.resolveDefinedValue(block, dest_src, dest_ptr)) |dest_ptr_val| rs: {
2539825658 if (!sema.isComptimeMutablePtr(dest_ptr_val)) break :rs dest_src;
2539925659 if (try sema.resolveDefinedValue(block, src_src, src_ptr)) |_| {
25400 const len_u64 = (try len_val.?.getUnsignedIntAdvanced(mod, .sema)).?;
25660 const len_u64 = (try len_val.?.getUnsignedIntAdvanced(pt, .sema)).?;
2540125661 const len = try sema.usizeCast(block, dest_src, len_u64);
2540225662 for (0..len) |i| {
25403 const elem_index = try mod.intRef(Type.usize, i);
25663 const elem_index = try pt.intRef(Type.usize, i);
2540425664 const dest_elem_ptr = try sema.elemPtrOneLayerOnly(
2540525665 block,
2540625666 src,
......@@ -25456,7 +25716,7 @@ fn zirMemcpy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2545625716 var new_dest_ptr = dest_ptr;
2545725717 var new_src_ptr = src_ptr;
2545825718 if (len_val) |val| {
25459 const len = try val.toUnsignedIntSema(mod);
25719 const len = try val.toUnsignedIntSema(pt);
2546025720 if (len == 0) {
2546125721 // This AIR instruction guarantees length > 0 if it is comptime-known.
2546225722 return;
......@@ -25503,7 +25763,7 @@ fn zirMemcpy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2550325763 assert(dest_manyptr_ty_key.flags.size == .One);
2550425764 dest_manyptr_ty_key.child = dest_elem_ty.toIntern();
2550525765 dest_manyptr_ty_key.flags.size = .Many;
25506 break :ptr try sema.coerceCompatiblePtrs(block, try mod.ptrTypeSema(dest_manyptr_ty_key), new_dest_ptr, dest_src);
25766 break :ptr try sema.coerceCompatiblePtrs(block, try pt.ptrTypeSema(dest_manyptr_ty_key), new_dest_ptr, dest_src);
2550725767 } else new_dest_ptr;
2550825768
2550925769 const new_src_ptr_ty = sema.typeOf(new_src_ptr);
......@@ -25514,7 +25774,7 @@ fn zirMemcpy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2551425774 assert(src_manyptr_ty_key.flags.size == .One);
2551525775 src_manyptr_ty_key.child = src_elem_ty.toIntern();
2551625776 src_manyptr_ty_key.flags.size = .Many;
25517 break :ptr try sema.coerceCompatiblePtrs(block, try mod.ptrTypeSema(src_manyptr_ty_key), new_src_ptr, src_src);
25777 break :ptr try sema.coerceCompatiblePtrs(block, try pt.ptrTypeSema(src_manyptr_ty_key), new_src_ptr, src_src);
2551825778 } else new_src_ptr;
2551925779
2552025780 // ok1: dest >= src + len
......@@ -25537,7 +25797,8 @@ fn zirMemcpy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2553725797}
2553825798
2553925799fn zirMemset(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void {
25540 const mod = sema.mod;
25800 const pt = sema.pt;
25801 const mod = pt.zcu;
2554125802 const gpa = sema.gpa;
2554225803 const ip = &mod.intern_pool;
2554325804 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
......@@ -25569,7 +25830,7 @@ fn zirMemset(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2556925830 const msg = try sema.errMsg(src, "unknown @memset length", .{});
2557025831 errdefer msg.destroy(sema.gpa);
2557125832 try sema.errNote(dest_src, msg, "destination type '{}' provides no length", .{
25572 dest_ptr_ty.fmt(mod),
25833 dest_ptr_ty.fmt(pt),
2557325834 });
2557425835 break :msg msg;
2557525836 });
......@@ -25579,9 +25840,9 @@ fn zirMemset(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2557925840
2558025841 const runtime_src = rs: {
2558125842 const ptr_val = try sema.resolveDefinedValue(block, dest_src, dest_ptr) orelse break :rs dest_src;
25582 const len_air_ref = try sema.fieldVal(block, src, dest_ptr, try ip.getOrPutString(gpa, "len", .no_embedded_nulls), dest_src);
25843 const len_air_ref = try sema.fieldVal(block, src, dest_ptr, try ip.getOrPutString(gpa, pt.tid, "len", .no_embedded_nulls), dest_src);
2558325844 const len_val = (try sema.resolveDefinedValue(block, dest_src, len_air_ref)) orelse break :rs dest_src;
25584 const len_u64 = (try len_val.getUnsignedIntAdvanced(mod, .sema)).?;
25845 const len_u64 = (try len_val.getUnsignedIntAdvanced(pt, .sema)).?;
2558525846 const len = try sema.usizeCast(block, dest_src, len_u64);
2558625847 if (len == 0) {
2558725848 // This AIR instruction guarantees length > 0 if it is comptime-known.
......@@ -25590,22 +25851,22 @@ fn zirMemset(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!void
2559025851
2559125852 if (!sema.isComptimeMutablePtr(ptr_val)) break :rs dest_src;
2559225853 const elem_val = try sema.resolveValue(elem) orelse break :rs value_src;
25593 const array_ty = try mod.arrayType(.{
25854 const array_ty = try pt.arrayType(.{
2559425855 .child = dest_elem_ty.toIntern(),
2559525856 .len = len_u64,
2559625857 });
25597 const array_val = Value.fromInterned((try mod.intern(.{ .aggregate = .{
25858 const array_val = Value.fromInterned(try pt.intern(.{ .aggregate = .{
2559825859 .ty = array_ty.toIntern(),
2559925860 .storage = .{ .repeated_elem = elem_val.toIntern() },
25600 } })));
25861 } }));
2560125862 const array_ptr_ty = ty: {
2560225863 var info = dest_ptr_ty.ptrInfo(mod);
2560325864 info.flags.size = .One;
2560425865 info.child = array_ty.toIntern();
25605 break :ty try mod.ptrType(info);
25866 break :ty try pt.ptrType(info);
2560625867 };
2560725868 const raw_ptr_val = if (dest_ptr_ty.isSlice(mod)) ptr_val.slicePtr(mod) else ptr_val;
25608 const array_ptr_val = try mod.getCoerced(raw_ptr_val, array_ptr_ty);
25869 const array_ptr_val = try pt.getCoerced(raw_ptr_val, array_ptr_ty);
2560925870 return sema.storePtrVal(block, src, array_ptr_val, array_val, array_ty);
2561025871 };
2561125872
......@@ -25658,7 +25919,8 @@ fn zirVarExtended(
2565825919 block: *Block,
2565925920 extended: Zir.Inst.Extended.InstData,
2566025921) CompileError!Air.Inst.Ref {
25661 const mod = sema.mod;
25922 const pt = sema.pt;
25923 const mod = pt.zcu;
2566225924 const extra = sema.code.extraData(Zir.Inst.ExtendedVar, extended.operand);
2566325925 const ty_src = block.src(.{ .node_offset_var_decl_ty = 0 });
2566425926 const init_src = block.src(.{ .node_offset_var_decl_init = 0 });
......@@ -25705,11 +25967,11 @@ fn zirVarExtended(
2570525967
2570625968 try sema.validateVarType(block, ty_src, var_ty, small.is_extern);
2570725969
25708 return Air.internedToRef((try mod.intern(.{ .variable = .{
25970 return Air.internedToRef((try pt.intern(.{ .variable = .{
2570925971 .ty = var_ty.toIntern(),
2571025972 .init = init_val,
2571125973 .decl = sema.owner_decl_index,
25712 .lib_name = try mod.intern_pool.getOrPutStringOpt(sema.gpa, lib_name, .no_embedded_nulls),
25974 .lib_name = try mod.intern_pool.getOrPutStringOpt(sema.gpa, pt.tid, lib_name, .no_embedded_nulls),
2571325975 .is_extern = small.is_extern,
2571425976 .is_const = small.is_const,
2571525977 .is_threadlocal = small.is_threadlocal,
......@@ -25721,7 +25983,8 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
2572125983 const tracy = trace(@src());
2572225984 defer tracy.end();
2572325985
25724 const mod = sema.mod;
25986 const pt = sema.pt;
25987 const mod = pt.zcu;
2572525988 const inst_data = sema.code.instructions.items(.data)[@intFromEnum(inst)].pl_node;
2572625989 const extra = sema.code.extraData(Zir.Inst.FuncFancy, inst_data.payload_index);
2572725990 const target = mod.getTarget();
......@@ -25761,7 +26024,7 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
2576126024 if (val.isGenericPoison()) {
2576226025 break :blk null;
2576326026 }
25764 const alignment = try sema.validateAlignAllowZero(block, align_src, try val.toUnsignedIntSema(mod));
26027 const alignment = try sema.validateAlignAllowZero(block, align_src, try val.toUnsignedIntSema(pt));
2576526028 const default = target_util.defaultFunctionAlignment(target);
2576626029 break :blk if (alignment == default) .none else alignment;
2576726030 } else if (extra.data.bits.has_align_ref) blk: {
......@@ -25781,7 +26044,7 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
2578126044 error.GenericPoison => break :blk null,
2578226045 else => |e| return e,
2578326046 };
25784 const alignment = try sema.validateAlignAllowZero(block, align_src, try align_val.toUnsignedIntSema(mod));
26047 const alignment = try sema.validateAlignAllowZero(block, align_src, try align_val.toUnsignedIntSema(pt));
2578526048 const default = target_util.defaultFunctionAlignment(target);
2578626049 break :blk if (alignment == default) .none else alignment;
2578726050 } else .none;
......@@ -25857,7 +26120,7 @@ fn zirFuncFancy(sema: *Sema, block: *Block, inst: Zir.Inst.Index) CompileError!A
2585726120 const body = sema.code.bodySlice(extra_index, body_len);
2585826121 extra_index += body.len;
2585926122
25860 const cc_ty = try mod.getBuiltinType("CallingConvention");
26123 const cc_ty = try pt.getBuiltinType("CallingConvention");
2586126124 const val = try sema.resolveGenericBody(block, cc_src, body, inst, cc_ty, .{
2586226125 .needed_comptime_reason = "calling convention must be comptime-known",
2586326126 });
......@@ -25986,7 +26249,8 @@ fn zirCDefine(
2598626249 block: *Block,
2598726250 extended: Zir.Inst.Extended.InstData,
2598826251) CompileError!Air.Inst.Ref {
25989 const mod = sema.mod;
26252 const pt = sema.pt;
26253 const mod = pt.zcu;
2599026254 const extra = sema.code.extraData(Zir.Inst.BinNode, extended.operand).data;
2599126255 const name_src = block.builtinCallArgSrc(extra.node, 0);
2599226256 const val_src = block.builtinCallArgSrc(extra.node, 1);
......@@ -26014,7 +26278,7 @@ fn zirWasmMemorySize(
2601426278 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
2601526279 const index_src = block.builtinCallArgSrc(extra.node, 0);
2601626280 const builtin_src = block.nodeOffset(extra.node);
26017 const target = sema.mod.getTarget();
26281 const target = sema.pt.zcu.getTarget();
2601826282 if (!target.isWasm()) {
2601926283 return sema.fail(block, builtin_src, "builtin @wasmMemorySize is available when targeting WebAssembly; targeted CPU architecture is {s}", .{@tagName(target.cpu.arch)});
2602026284 }
......@@ -26041,7 +26305,7 @@ fn zirWasmMemoryGrow(
2604126305 const builtin_src = block.nodeOffset(extra.node);
2604226306 const index_src = block.builtinCallArgSrc(extra.node, 0);
2604326307 const delta_src = block.builtinCallArgSrc(extra.node, 1);
26044 const target = sema.mod.getTarget();
26308 const target = sema.pt.zcu.getTarget();
2604526309 if (!target.isWasm()) {
2604626310 return sema.fail(block, builtin_src, "builtin @wasmMemoryGrow is available when targeting WebAssembly; targeted CPU architecture is {s}", .{@tagName(target.cpu.arch)});
2604726311 }
......@@ -26067,34 +26331,35 @@ fn resolvePrefetchOptions(
2606726331 src: LazySrcLoc,
2606826332 zir_ref: Zir.Inst.Ref,
2606926333) CompileError!std.builtin.PrefetchOptions {
26070 const mod = sema.mod;
26334 const pt = sema.pt;
26335 const mod = pt.zcu;
2607126336 const gpa = sema.gpa;
2607226337 const ip = &mod.intern_pool;
26073 const options_ty = try mod.getBuiltinType("PrefetchOptions");
26338 const options_ty = try pt.getBuiltinType("PrefetchOptions");
2607426339 const options = try sema.coerce(block, options_ty, try sema.resolveInst(zir_ref), src);
2607526340
2607626341 const rw_src = block.src(.{ .init_field_rw = src.offset.node_offset_builtin_call_arg.builtin_call_node });
2607726342 const locality_src = block.src(.{ .init_field_locality = src.offset.node_offset_builtin_call_arg.builtin_call_node });
2607826343 const cache_src = block.src(.{ .init_field_cache = src.offset.node_offset_builtin_call_arg.builtin_call_node });
2607926344
26080 const rw = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, "rw", .no_embedded_nulls), rw_src);
26345 const rw = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "rw", .no_embedded_nulls), rw_src);
2608126346 const rw_val = try sema.resolveConstDefinedValue(block, rw_src, rw, .{
2608226347 .needed_comptime_reason = "prefetch read/write must be comptime-known",
2608326348 });
2608426349
26085 const locality = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, "locality", .no_embedded_nulls), locality_src);
26350 const locality = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "locality", .no_embedded_nulls), locality_src);
2608626351 const locality_val = try sema.resolveConstDefinedValue(block, locality_src, locality, .{
2608726352 .needed_comptime_reason = "prefetch locality must be comptime-known",
2608826353 });
2608926354
26090 const cache = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, "cache", .no_embedded_nulls), cache_src);
26355 const cache = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "cache", .no_embedded_nulls), cache_src);
2609126356 const cache_val = try sema.resolveConstDefinedValue(block, cache_src, cache, .{
2609226357 .needed_comptime_reason = "prefetch cache must be comptime-known",
2609326358 });
2609426359
2609526360 return std.builtin.PrefetchOptions{
2609626361 .rw = mod.toEnum(std.builtin.PrefetchOptions.Rw, rw_val),
26097 .locality = @intCast(try locality_val.toUnsignedIntSema(mod)),
26362 .locality = @intCast(try locality_val.toUnsignedIntSema(pt)),
2609826363 .cache = mod.toEnum(std.builtin.PrefetchOptions.Cache, cache_val),
2609926364 };
2610026365}
......@@ -26138,11 +26403,12 @@ fn resolveExternOptions(
2613826403 linkage: std.builtin.GlobalLinkage = .strong,
2613926404 is_thread_local: bool = false,
2614026405} {
26141 const mod = sema.mod;
26406 const pt = sema.pt;
26407 const mod = pt.zcu;
2614226408 const gpa = sema.gpa;
2614326409 const ip = &mod.intern_pool;
2614426410 const options_inst = try sema.resolveInst(zir_ref);
26145 const extern_options_ty = try mod.getBuiltinType("ExternOptions");
26411 const extern_options_ty = try pt.getBuiltinType("ExternOptions");
2614626412 const options = try sema.coerce(block, extern_options_ty, options_inst, src);
2614726413
2614826414 const name_src = block.src(.{ .init_field_name = src.offset.node_offset_builtin_call_arg.builtin_call_node });
......@@ -26150,23 +26416,23 @@ fn resolveExternOptions(
2615026416 const linkage_src = block.src(.{ .init_field_linkage = src.offset.node_offset_builtin_call_arg.builtin_call_node });
2615126417 const thread_local_src = block.src(.{ .init_field_thread_local = src.offset.node_offset_builtin_call_arg.builtin_call_node });
2615226418
26153 const name_ref = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, "name", .no_embedded_nulls), name_src);
26419 const name_ref = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "name", .no_embedded_nulls), name_src);
2615426420 const name = try sema.toConstString(block, name_src, name_ref, .{
2615526421 .needed_comptime_reason = "name of the extern symbol must be comptime-known",
2615626422 });
2615726423
26158 const library_name_inst = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, "library_name", .no_embedded_nulls), library_src);
26424 const library_name_inst = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "library_name", .no_embedded_nulls), library_src);
2615926425 const library_name_val = try sema.resolveConstDefinedValue(block, library_src, library_name_inst, .{
2616026426 .needed_comptime_reason = "library in which extern symbol is must be comptime-known",
2616126427 });
2616226428
26163 const linkage_ref = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, "linkage", .no_embedded_nulls), linkage_src);
26429 const linkage_ref = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "linkage", .no_embedded_nulls), linkage_src);
2616426430 const linkage_val = try sema.resolveConstDefinedValue(block, linkage_src, linkage_ref, .{
2616526431 .needed_comptime_reason = "linkage of the extern symbol must be comptime-known",
2616626432 });
2616726433 const linkage = mod.toEnum(std.builtin.GlobalLinkage, linkage_val);
2616826434
26169 const is_thread_local = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, "is_thread_local", .no_embedded_nulls), thread_local_src);
26435 const is_thread_local = try sema.fieldVal(block, src, options, try ip.getOrPutString(gpa, pt.tid, "is_thread_local", .no_embedded_nulls), thread_local_src);
2617026436 const is_thread_local_val = try sema.resolveConstDefinedValue(block, thread_local_src, is_thread_local, .{
2617126437 .needed_comptime_reason = "threadlocality of the extern symbol must be comptime-known",
2617226438 });
......@@ -26191,8 +26457,8 @@ fn resolveExternOptions(
2619126457 }
2619226458
2619326459 return .{
26194 .name = try ip.getOrPutString(gpa, name, .no_embedded_nulls),
26195 .library_name = try ip.getOrPutStringOpt(gpa, library_name, .no_embedded_nulls),
26460 .name = try ip.getOrPutString(gpa, pt.tid, name, .no_embedded_nulls),
26461 .library_name = try ip.getOrPutStringOpt(gpa, pt.tid, library_name, .no_embedded_nulls),
2619626462 .linkage = linkage,
2619726463 .is_thread_local = is_thread_local_val.toBool(),
2619826464 };
......@@ -26203,7 +26469,8 @@ fn zirBuiltinExtern(
2620326469 block: *Block,
2620426470 extended: Zir.Inst.Extended.InstData,
2620526471) CompileError!Air.Inst.Ref {
26206 const mod = sema.mod;
26472 const pt = sema.pt;
26473 const mod = pt.zcu;
2620726474 const ip = &mod.intern_pool;
2620826475 const extra = sema.code.extraData(Zir.Inst.BinNode, extended.operand).data;
2620926476 const ty_src = block.builtinCallArgSrc(extra.node, 0);
......@@ -26215,7 +26482,7 @@ fn zirBuiltinExtern(
2621526482 }
2621626483 if (!try sema.validateExternType(ty, .other)) {
2621726484 const msg = msg: {
26218 const msg = try sema.errMsg(ty_src, "extern symbol cannot have type '{}'", .{ty.fmt(mod)});
26485 const msg = try sema.errMsg(ty_src, "extern symbol cannot have type '{}'", .{ty.fmt(pt)});
2621926486 errdefer msg.destroy(sema.gpa);
2622026487 try sema.explainWhyTypeIsNotExtern(msg, ty_src, ty, .other);
2622126488 break :msg msg;
......@@ -26226,7 +26493,7 @@ fn zirBuiltinExtern(
2622626493 const options = try sema.resolveExternOptions(block, options_src, extra.rhs);
2622726494
2622826495 if (options.linkage == .weak and !ty.ptrAllowsZero(mod)) {
26229 ty = try mod.optionalType(ty.toIntern());
26496 ty = try pt.optionalType(ty.toIntern());
2623026497 }
2623126498 const ptr_info = ty.ptrInfo(mod);
2623226499
......@@ -26237,13 +26504,13 @@ fn zirBuiltinExtern(
2623726504 new_decl_index,
2623826505 Value.fromInterned(
2623926506 if (Type.fromInterned(ptr_info.child).zigTypeTag(mod) == .Fn)
26240 try ip.getExternFunc(sema.gpa, .{
26507 try ip.getExternFunc(sema.gpa, pt.tid, .{
2624126508 .ty = ptr_info.child,
2624226509 .decl = new_decl_index,
2624326510 .lib_name = options.library_name,
2624426511 })
2624526512 else
26246 try mod.intern(.{ .variable = .{
26513 try pt.intern(.{ .variable = .{
2624726514 .ty = ptr_info.child,
2624826515 .init = .none,
2624926516 .decl = new_decl_index,
......@@ -26259,9 +26526,9 @@ fn zirBuiltinExtern(
2625926526 new_decl.owns_tv = true;
2626026527 // Note that this will queue the anon decl for codegen, so that the backend can
2626126528 // correctly handle the extern, including duplicate detection.
26262 try mod.finalizeAnonDecl(new_decl_index);
26529 try pt.finalizeAnonDecl(new_decl_index);
2626326530
26264 return Air.internedToRef((try mod.getCoerced(Value.fromInterned((try mod.intern(.{ .ptr = .{
26531 return Air.internedToRef((try pt.getCoerced(Value.fromInterned(try pt.intern(.{ .ptr = .{
2626526532 .ty = switch (ip.indexToKey(ty.toIntern())) {
2626626533 .ptr_type => ty.toIntern(),
2626726534 .opt_type => |child_type| child_type,
......@@ -26269,7 +26536,7 @@ fn zirBuiltinExtern(
2626926536 },
2627026537 .base_addr = .{ .decl = new_decl_index },
2627126538 .byte_offset = 0,
26272 } }))), ty)).toIntern());
26539 } })), ty)).toIntern());
2627326540}
2627426541
2627526542fn zirWorkItem(
......@@ -26281,7 +26548,7 @@ fn zirWorkItem(
2628126548 const extra = sema.code.extraData(Zir.Inst.UnNode, extended.operand).data;
2628226549 const dimension_src = block.builtinCallArgSrc(extra.node, 0);
2628326550 const builtin_src = block.nodeOffset(extra.node);
26284 const target = sema.mod.getTarget();
26551 const target = sema.pt.zcu.getTarget();
2628526552
2628626553 switch (target.cpu.arch) {
2628726554 // TODO: Allow for other GPU targets.
......@@ -26344,11 +26611,12 @@ fn validateVarType(
2634426611 var_ty: Type,
2634526612 is_extern: bool,
2634626613) CompileError!void {
26347 const mod = sema.mod;
26614 const pt = sema.pt;
26615 const mod = pt.zcu;
2634826616 if (is_extern) {
2634926617 if (!try sema.validateExternType(var_ty, .other)) {
2635026618 const msg = msg: {
26351 const msg = try sema.errMsg(src, "extern variable cannot have type '{}'", .{var_ty.fmt(mod)});
26619 const msg = try sema.errMsg(src, "extern variable cannot have type '{}'", .{var_ty.fmt(pt)});
2635226620 errdefer msg.destroy(sema.gpa);
2635326621 try sema.explainWhyTypeIsNotExtern(msg, src, var_ty, .other);
2635426622 break :msg msg;
......@@ -26361,7 +26629,7 @@ fn validateVarType(
2636126629 block,
2636226630 src,
2636326631 "non-extern variable with opaque type '{}'",
26364 .{var_ty.fmt(mod)},
26632 .{var_ty.fmt(pt)},
2636526633 );
2636626634 }
2636726635 }
......@@ -26369,7 +26637,7 @@ fn validateVarType(
2636926637 if (!try sema.typeRequiresComptime(var_ty)) return;
2637026638
2637126639 const msg = msg: {
26372 const msg = try sema.errMsg(src, "variable of type '{}' must be const or comptime", .{var_ty.fmt(mod)});
26640 const msg = try sema.errMsg(src, "variable of type '{}' must be const or comptime", .{var_ty.fmt(pt)});
2637326641 errdefer msg.destroy(sema.gpa);
2637426642
2637526643 try sema.explainWhyTypeIsComptime(msg, src, var_ty);
......@@ -26393,7 +26661,7 @@ fn explainWhyTypeIsComptime(
2639326661 var type_set = TypeSet{};
2639426662 defer type_set.deinit(sema.gpa);
2639526663
26396 try ty.resolveFully(sema.mod);
26664 try ty.resolveFully(sema.pt);
2639726665 return sema.explainWhyTypeIsComptimeInner(msg, src_loc, ty, &type_set);
2639826666}
2639926667
......@@ -26404,7 +26672,8 @@ fn explainWhyTypeIsComptimeInner(
2640426672 ty: Type,
2640526673 type_set: *TypeSet,
2640626674) CompileError!void {
26407 const mod = sema.mod;
26675 const pt = sema.pt;
26676 const mod = pt.zcu;
2640826677 const ip = &mod.intern_pool;
2640926678 switch (ty.zigTypeTag(mod)) {
2641026679 .Bool,
......@@ -26418,9 +26687,7 @@ fn explainWhyTypeIsComptimeInner(
2641826687 => return,
2641926688
2642026689 .Fn => {
26421 try sema.errNote(src_loc, msg, "use '*const {}' for a function pointer type", .{
26422 ty.fmt(sema.mod),
26423 });
26690 try sema.errNote(src_loc, msg, "use '*const {}' for a function pointer type", .{ty.fmt(pt)});
2642426691 },
2642526692
2642626693 .Type => {
......@@ -26436,7 +26703,7 @@ fn explainWhyTypeIsComptimeInner(
2643626703 => return,
2643726704
2643826705 .Opaque => {
26439 try sema.errNote(src_loc, msg, "opaque type '{}' has undefined size", .{ty.fmt(sema.mod)});
26706 try sema.errNote(src_loc, msg, "opaque type '{}' has undefined size", .{ty.fmt(pt)});
2644026707 },
2644126708
2644226709 .Array, .Vector => {
......@@ -26453,7 +26720,7 @@ fn explainWhyTypeIsComptimeInner(
2645326720 .Inline => try sema.errNote(src_loc, msg, "function has inline calling convention", .{}),
2645426721 else => {},
2645526722 }
26456 if (Type.fromInterned(fn_info.return_type).comptimeOnly(mod)) {
26723 if (Type.fromInterned(fn_info.return_type).comptimeOnly(pt)) {
2645726724 try sema.errNote(src_loc, msg, "function has a comptime-only return type", .{});
2645826725 }
2645926726 return;
......@@ -26526,7 +26793,8 @@ fn validateExternType(
2652626793 ty: Type,
2652726794 position: ExternPosition,
2652826795) !bool {
26529 const mod = sema.mod;
26796 const pt = sema.pt;
26797 const mod = pt.zcu;
2653026798 switch (ty.zigTypeTag(mod)) {
2653126799 .Type,
2653226800 .ComptimeFloat,
......@@ -26557,7 +26825,7 @@ fn validateExternType(
2655726825 },
2655826826 .Fn => {
2655926827 if (position != .other) return false;
26560 const target = sema.mod.getTarget();
26828 const target = mod.getTarget();
2656126829 // For now we want to authorize PTX kernel to use zig objects, even if we end up exposing the ABI.
2656226830 // The goal is to experiment with more integrated CPU/GPU code.
2656326831 if (ty.fnCallingConvention(mod) == .Kernel and (target.cpu.arch == .nvptx or target.cpu.arch == .nvptx64)) {
......@@ -26571,7 +26839,7 @@ fn validateExternType(
2657126839 .Struct, .Union => switch (ty.containerLayout(mod)) {
2657226840 .@"extern" => return true,
2657326841 .@"packed" => {
26574 const bit_size = try ty.bitSizeAdvanced(mod, .sema);
26842 const bit_size = try ty.bitSizeAdvanced(pt, .sema);
2657526843 switch (bit_size) {
2657626844 0, 8, 16, 32, 64, 128 => return true,
2657726845 else => return false,
......@@ -26595,7 +26863,8 @@ fn explainWhyTypeIsNotExtern(
2659526863 ty: Type,
2659626864 position: ExternPosition,
2659726865) CompileError!void {
26598 const mod = sema.mod;
26866 const pt = sema.pt;
26867 const mod = pt.zcu;
2659926868 switch (ty.zigTypeTag(mod)) {
2660026869 .Opaque,
2660126870 .Bool,
......@@ -26622,7 +26891,7 @@ fn explainWhyTypeIsNotExtern(
2662226891 if (!ty.isConstPtr(mod) and pointee_ty.zigTypeTag(mod) == .Fn) {
2662326892 try sema.errNote(src_loc, msg, "pointer to extern function must be 'const'", .{});
2662426893 } else if (try sema.typeRequiresComptime(ty)) {
26625 try sema.errNote(src_loc, msg, "pointer to comptime-only type '{}'", .{pointee_ty.fmt(sema.mod)});
26894 try sema.errNote(src_loc, msg, "pointer to comptime-only type '{}'", .{pointee_ty.fmt(pt)});
2662626895 try sema.explainWhyTypeIsComptime(msg, src_loc, ty);
2662726896 }
2662826897 try sema.explainWhyTypeIsNotExtern(msg, src_loc, pointee_ty, .other);
......@@ -26650,7 +26919,7 @@ fn explainWhyTypeIsNotExtern(
2665026919 },
2665126920 .Enum => {
2665226921 const tag_ty = ty.intTagType(mod);
26653 try sema.errNote(src_loc, msg, "enum tag type '{}' is not extern compatible", .{tag_ty.fmt(sema.mod)});
26922 try sema.errNote(src_loc, msg, "enum tag type '{}' is not extern compatible", .{tag_ty.fmt(pt)});
2665426923 try sema.explainWhyTypeIsNotExtern(msg, src_loc, tag_ty, position);
2665526924 },
2665626925 .Struct => try sema.errNote(src_loc, msg, "only extern structs and ABI sized packed structs are extern compatible", .{}),
......@@ -26671,7 +26940,8 @@ fn explainWhyTypeIsNotExtern(
2667126940/// Returns true if `ty` is allowed in packed types.
2667226941/// Does not require `ty` to be resolved in any way, but may resolve whether it is comptime-only.
2667326942fn validatePackedType(sema: *Sema, ty: Type) !bool {
26674 const zcu = sema.mod;
26943 const pt = sema.pt;
26944 const zcu = pt.zcu;
2667526945 return switch (ty.zigTypeTag(zcu)) {
2667626946 .Type,
2667726947 .ComptimeFloat,
......@@ -26710,7 +26980,8 @@ fn explainWhyTypeIsNotPacked(
2671026980 src_loc: LazySrcLoc,
2671126981 ty: Type,
2671226982) CompileError!void {
26713 const mod = sema.mod;
26983 const pt = sema.pt;
26984 const mod = pt.zcu;
2671426985 switch (ty.zigTypeTag(mod)) {
2671526986 .Void,
2671626987 .Bool,
......@@ -26750,10 +27021,11 @@ fn explainWhyTypeIsNotPacked(
2675027021}
2675127022
2675227023fn prepareSimplePanic(sema: *Sema) !void {
26753 const mod = sema.mod;
27024 const pt = sema.pt;
27025 const mod = pt.zcu;
2675427026
2675527027 if (mod.panic_func_index == .none) {
26756 const decl_index = (try mod.getBuiltinDecl("panic"));
27028 const decl_index = (try pt.getBuiltinDecl("panic"));
2675727029 // decl_index may be an alias; we must find the decl that actually
2675827030 // owns the function.
2675927031 try sema.ensureDeclAnalyzed(decl_index);
......@@ -26766,17 +27038,17 @@ fn prepareSimplePanic(sema: *Sema) !void {
2676627038 }
2676727039
2676827040 if (mod.null_stack_trace == .none) {
26769 const stack_trace_ty = try mod.getBuiltinType("StackTrace");
26770 try stack_trace_ty.resolveFields(mod);
27041 const stack_trace_ty = try pt.getBuiltinType("StackTrace");
27042 try stack_trace_ty.resolveFields(pt);
2677127043 const target = mod.getTarget();
26772 const ptr_stack_trace_ty = try mod.ptrTypeSema(.{
27044 const ptr_stack_trace_ty = try pt.ptrTypeSema(.{
2677327045 .child = stack_trace_ty.toIntern(),
2677427046 .flags = .{
2677527047 .address_space = target_util.defaultAddressSpace(target, .global_constant),
2677627048 },
2677727049 });
26778 const opt_ptr_stack_trace_ty = try mod.optionalType(ptr_stack_trace_ty.toIntern());
26779 mod.null_stack_trace = try mod.intern(.{ .opt = .{
27050 const opt_ptr_stack_trace_ty = try pt.optionalType(ptr_stack_trace_ty.toIntern());
27051 mod.null_stack_trace = try pt.intern(.{ .opt = .{
2678027052 .ty = opt_ptr_stack_trace_ty.toIntern(),
2678127053 .val = .none,
2678227054 } });
......@@ -26787,18 +27059,19 @@ fn prepareSimplePanic(sema: *Sema) !void {
2678727059/// instructions. This function ensures the panic function will be available to
2678827060/// be called during that time.
2678927061fn preparePanicId(sema: *Sema, block: *Block, panic_id: Module.PanicId) !InternPool.DeclIndex {
26790 const mod = sema.mod;
27062 const pt = sema.pt;
27063 const mod = pt.zcu;
2679127064 const gpa = sema.gpa;
2679227065 if (mod.panic_messages[@intFromEnum(panic_id)].unwrap()) |x| return x;
2679327066
2679427067 try sema.prepareSimplePanic();
2679527068
26796 const panic_messages_ty = try mod.getBuiltinType("panic_messages");
27069 const panic_messages_ty = try pt.getBuiltinType("panic_messages");
2679727070 const msg_decl_index = (sema.namespaceLookup(
2679827071 block,
2679927072 LazySrcLoc.unneeded,
2680027073 panic_messages_ty.getNamespaceIndex(mod),
26801 try mod.intern_pool.getOrPutString(gpa, @tagName(panic_id), .no_embedded_nulls),
27074 try mod.intern_pool.getOrPutString(gpa, pt.tid, @tagName(panic_id), .no_embedded_nulls),
2680227075 ) catch |err| switch (err) {
2680327076 error.AnalysisFail => @panic("std.builtin.panic_messages is corrupt"),
2680427077 error.GenericPoison, error.ComptimeReturn, error.ComptimeBreak => unreachable,
......@@ -26892,7 +27165,8 @@ fn addSafetyCheckExtra(
2689227165}
2689327166
2689427167fn panicWithMsg(sema: *Sema, block: *Block, src: LazySrcLoc, msg_inst: Air.Inst.Ref, operation: CallOperation) !void {
26895 const mod = sema.mod;
27168 const pt = sema.pt;
27169 const mod = pt.zcu;
2689627170
2689727171 if (!mod.backendSupportsFeature(.panic_fn)) {
2689827172 _ = try block.addNoOp(.trap);
......@@ -26905,8 +27179,8 @@ fn panicWithMsg(sema: *Sema, block: *Block, src: LazySrcLoc, msg_inst: Air.Inst.
2690527179 const panic_fn = try sema.analyzeDeclVal(block, src, panic_func.owner_decl);
2690627180 const null_stack_trace = Air.internedToRef(mod.null_stack_trace);
2690727181
26908 const opt_usize_ty = try mod.optionalType(.usize_type);
26909 const null_ret_addr = Air.internedToRef((try mod.intern(.{ .opt = .{
27182 const opt_usize_ty = try pt.optionalType(.usize_type);
27183 const null_ret_addr = Air.internedToRef((try pt.intern(.{ .opt = .{
2691027184 .ty = opt_usize_ty.toIntern(),
2691127185 .val = .none,
2691227186 } })));
......@@ -26921,9 +27195,10 @@ fn panicUnwrapError(
2692127195 unwrap_err_tag: Air.Inst.Tag,
2692227196 is_non_err_tag: Air.Inst.Tag,
2692327197) !void {
27198 const pt = sema.pt;
2692427199 assert(!parent_block.is_comptime);
2692527200 const ok = try parent_block.addUnOp(is_non_err_tag, operand);
26926 if (!sema.mod.comp.formatted_panics) {
27201 if (!pt.zcu.comp.formatted_panics) {
2692727202 return sema.addSafetyCheck(parent_block, src, ok, .unwrap_error);
2692827203 }
2692927204 const gpa = sema.gpa;
......@@ -26942,10 +27217,10 @@ fn panicUnwrapError(
2694227217 defer fail_block.instructions.deinit(gpa);
2694327218
2694427219 {
26945 if (!sema.mod.backendSupportsFeature(.panic_unwrap_error)) {
27220 if (!pt.zcu.backendSupportsFeature(.panic_unwrap_error)) {
2694627221 _ = try fail_block.addNoOp(.trap);
2694727222 } else {
26948 const panic_fn = try sema.mod.getBuiltin("panicUnwrapError");
27223 const panic_fn = try sema.pt.getBuiltin("panicUnwrapError");
2694927224 const err = try fail_block.addTyOp(unwrap_err_tag, Type.anyerror, operand);
2695027225 const err_return_trace = try sema.getErrorReturnTrace(&fail_block);
2695127226 const args: [2]Air.Inst.Ref = .{ err_return_trace, err };
......@@ -26965,7 +27240,7 @@ fn panicIndexOutOfBounds(
2696527240) !void {
2696627241 assert(!parent_block.is_comptime);
2696727242 const ok = try parent_block.addBinOp(cmp_op, index, len);
26968 if (!sema.mod.comp.formatted_panics) {
27243 if (!sema.pt.zcu.comp.formatted_panics) {
2696927244 return sema.addSafetyCheck(parent_block, src, ok, .index_out_of_bounds);
2697027245 }
2697127246 try sema.safetyCheckFormatted(parent_block, src, ok, "panicOutOfBounds", &.{ index, len });
......@@ -26980,7 +27255,7 @@ fn panicInactiveUnionField(
2698027255) !void {
2698127256 assert(!parent_block.is_comptime);
2698227257 const ok = try parent_block.addBinOp(.cmp_eq, active_tag, wanted_tag);
26983 if (!sema.mod.comp.formatted_panics) {
27258 if (!sema.pt.zcu.comp.formatted_panics) {
2698427259 return sema.addSafetyCheck(parent_block, src, ok, .inactive_union_field);
2698527260 }
2698627261 try sema.safetyCheckFormatted(parent_block, src, ok, "panicInactiveUnionField", &.{ active_tag, wanted_tag });
......@@ -26996,7 +27271,8 @@ fn panicSentinelMismatch(
2699627271 sentinel_index: Air.Inst.Ref,
2699727272) !void {
2699827273 assert(!parent_block.is_comptime);
26999 const mod = sema.mod;
27274 const pt = sema.pt;
27275 const mod = pt.zcu;
2700027276 const expected_sentinel_val = maybe_sentinel orelse return;
2700127277 const expected_sentinel = Air.internedToRef(expected_sentinel_val.toIntern());
2700227278
......@@ -27004,7 +27280,7 @@ fn panicSentinelMismatch(
2700427280 const actual_sentinel = if (ptr_ty.isSlice(mod))
2700527281 try parent_block.addBinOp(.slice_elem_val, ptr, sentinel_index)
2700627282 else blk: {
27007 const elem_ptr_ty = try ptr_ty.elemPtrType(null, mod);
27283 const elem_ptr_ty = try ptr_ty.elemPtrType(null, pt);
2700827284 const sentinel_ptr = try parent_block.addPtrElemPtr(ptr, sentinel_index, elem_ptr_ty);
2700927285 break :blk try parent_block.addTyOp(.load, sentinel_ty, sentinel_ptr);
2701027286 };
......@@ -27022,13 +27298,13 @@ fn panicSentinelMismatch(
2702227298 } else if (sentinel_ty.isSelfComparable(mod, true))
2702327299 try parent_block.addBinOp(.cmp_eq, expected_sentinel, actual_sentinel)
2702427300 else {
27025 const panic_fn = try mod.getBuiltin("checkNonScalarSentinel");
27301 const panic_fn = try pt.getBuiltin("checkNonScalarSentinel");
2702627302 const args: [2]Air.Inst.Ref = .{ expected_sentinel, actual_sentinel };
2702727303 try sema.callBuiltin(parent_block, src, panic_fn, .auto, &args, .@"safety check");
2702827304 return;
2702927305 };
2703027306
27031 if (!sema.mod.comp.formatted_panics) {
27307 if (!pt.zcu.comp.formatted_panics) {
2703227308 return sema.addSafetyCheck(parent_block, src, ok, .sentinel_mismatch);
2703327309 }
2703427310 try sema.safetyCheckFormatted(parent_block, src, ok, "panicSentinelMismatch", &.{ expected_sentinel, actual_sentinel });
......@@ -27042,7 +27318,9 @@ fn safetyCheckFormatted(
2704227318 func: []const u8,
2704327319 args: []const Air.Inst.Ref,
2704427320) CompileError!void {
27045 assert(sema.mod.comp.formatted_panics);
27321 const pt = sema.pt;
27322 const zcu = pt.zcu;
27323 assert(zcu.comp.formatted_panics);
2704627324 const gpa = sema.gpa;
2704727325
2704827326 var fail_block: Block = .{
......@@ -27058,10 +27336,10 @@ fn safetyCheckFormatted(
2705827336
2705927337 defer fail_block.instructions.deinit(gpa);
2706027338
27061 if (!sema.mod.backendSupportsFeature(.safety_check_formatted)) {
27339 if (!zcu.backendSupportsFeature(.safety_check_formatted)) {
2706227340 _ = try fail_block.addNoOp(.trap);
2706327341 } else {
27064 const panic_fn = try sema.mod.getBuiltin(func);
27342 const panic_fn = try pt.getBuiltin(func);
2706527343 try sema.callBuiltin(&fail_block, src, panic_fn, .auto, args, .@"safety check");
2706627344 }
2706727345 try sema.addSafetyCheckExtra(parent_block, ok, &fail_block);
......@@ -27102,7 +27380,8 @@ fn fieldVal(
2710227380 // When editing this function, note that there is corresponding logic to be edited
2710327381 // in `fieldPtr`. This function takes a value and returns a value.
2710427382
27105 const mod = sema.mod;
27383 const pt = sema.pt;
27384 const mod = pt.zcu;
2710627385 const ip = &mod.intern_pool;
2710727386 const object_src = src; // TODO better source location
2710827387 const object_ty = sema.typeOf(object);
......@@ -27120,10 +27399,10 @@ fn fieldVal(
2712027399 switch (inner_ty.zigTypeTag(mod)) {
2712127400 .Array => {
2712227401 if (field_name.eqlSlice("len", ip)) {
27123 return Air.internedToRef((try mod.intValue(Type.usize, inner_ty.arrayLen(mod))).toIntern());
27402 return Air.internedToRef((try pt.intValue(Type.usize, inner_ty.arrayLen(mod))).toIntern());
2712427403 } else if (field_name.eqlSlice("ptr", ip) and is_pointer_to) {
2712527404 const ptr_info = object_ty.ptrInfo(mod);
27126 const result_ty = try mod.ptrTypeSema(.{
27405 const result_ty = try pt.ptrTypeSema(.{
2712727406 .child = Type.fromInterned(ptr_info.child).childType(mod).toIntern(),
2712827407 .sentinel = if (inner_ty.sentinel(mod)) |s| s.toIntern() else .none,
2712927408 .flags = .{
......@@ -27143,7 +27422,7 @@ fn fieldVal(
2714327422 block,
2714427423 field_name_src,
2714527424 "no member named '{}' in '{}'",
27146 .{ field_name.fmt(ip), object_ty.fmt(mod) },
27425 .{ field_name.fmt(ip), object_ty.fmt(pt) },
2714727426 );
2714827427 }
2714927428 },
......@@ -27167,7 +27446,7 @@ fn fieldVal(
2716727446 block,
2716827447 field_name_src,
2716927448 "no member named '{}' in '{}'",
27170 .{ field_name.fmt(ip), object_ty.fmt(mod) },
27449 .{ field_name.fmt(ip), object_ty.fmt(pt) },
2717127450 );
2717227451 }
2717327452 }
......@@ -27194,7 +27473,7 @@ fn fieldVal(
2719427473 .error_set_type => |error_set_type| blk: {
2719527474 if (error_set_type.nameIndex(ip, field_name) != null) break :blk;
2719627475 return sema.fail(block, src, "no error named '{}' in '{}'", .{
27197 field_name.fmt(ip), child_type.fmt(mod),
27476 field_name.fmt(ip), child_type.fmt(pt),
2719827477 });
2719927478 },
2720027479 .inferred_error_set_type => {
......@@ -27210,8 +27489,8 @@ fn fieldVal(
2721027489 const error_set_type = if (!child_type.isAnyError(mod))
2721127490 child_type
2721227491 else
27213 try mod.singleErrorSetType(field_name);
27214 return Air.internedToRef((try mod.intern(.{ .err = .{
27492 try pt.singleErrorSetType(field_name);
27493 return Air.internedToRef((try pt.intern(.{ .err = .{
2721527494 .ty = error_set_type.toIntern(),
2721627495 .name = field_name,
2721727496 } })));
......@@ -27220,11 +27499,11 @@ fn fieldVal(
2722027499 if (try sema.namespaceLookupVal(block, src, child_type.getNamespaceIndex(mod), field_name)) |inst| {
2722127500 return inst;
2722227501 }
27223 try child_type.resolveFields(mod);
27502 try child_type.resolveFields(pt);
2722427503 if (child_type.unionTagType(mod)) |enum_ty| {
2722527504 if (enum_ty.enumFieldIndex(field_name, mod)) |field_index_usize| {
2722627505 const field_index: u32 = @intCast(field_index_usize);
27227 return Air.internedToRef((try mod.enumValueFieldIndex(enum_ty, field_index)).toIntern());
27506 return Air.internedToRef((try pt.enumValueFieldIndex(enum_ty, field_index)).toIntern());
2722827507 }
2722927508 }
2723027509 return sema.failWithBadMemberAccess(block, child_type, field_name_src, field_name);
......@@ -27236,7 +27515,7 @@ fn fieldVal(
2723627515 const field_index_usize = child_type.enumFieldIndex(field_name, mod) orelse
2723727516 return sema.failWithBadMemberAccess(block, child_type, field_name_src, field_name);
2723827517 const field_index: u32 = @intCast(field_index_usize);
27239 const enum_val = try mod.enumValueFieldIndex(child_type, field_index);
27518 const enum_val = try pt.enumValueFieldIndex(child_type, field_index);
2724027519 return Air.internedToRef(enum_val.toIntern());
2724127520 },
2724227521 .Struct, .Opaque => {
......@@ -27247,7 +27526,7 @@ fn fieldVal(
2724727526 },
2724827527 else => {
2724927528 const msg = msg: {
27250 const msg = try sema.errMsg(src, "type '{}' has no members", .{child_type.fmt(mod)});
27529 const msg = try sema.errMsg(src, "type '{}' has no members", .{child_type.fmt(pt)});
2725127530 errdefer msg.destroy(sema.gpa);
2725227531 if (child_type.isSlice(mod)) try sema.errNote(src, msg, "slice values have 'len' and 'ptr' members", .{});
2725327532 if (child_type.zigTypeTag(mod) == .Array) try sema.errNote(src, msg, "array values have 'len' member", .{});
......@@ -27288,13 +27567,14 @@ fn fieldPtr(
2728827567 // When editing this function, note that there is corresponding logic to be edited
2728927568 // in `fieldVal`. This function takes a pointer and returns a pointer.
2729027569
27291 const mod = sema.mod;
27570 const pt = sema.pt;
27571 const mod = pt.zcu;
2729227572 const ip = &mod.intern_pool;
2729327573 const object_ptr_src = src; // TODO better source location
2729427574 const object_ptr_ty = sema.typeOf(object_ptr);
2729527575 const object_ty = switch (object_ptr_ty.zigTypeTag(mod)) {
2729627576 .Pointer => object_ptr_ty.childType(mod),
27297 else => return sema.fail(block, object_ptr_src, "expected pointer, found '{}'", .{object_ptr_ty.fmt(mod)}),
27577 else => return sema.fail(block, object_ptr_src, "expected pointer, found '{}'", .{object_ptr_ty.fmt(pt)}),
2729827578 };
2729927579
2730027580 // Zig allows dereferencing a single pointer during field lookup. Note that
......@@ -27310,11 +27590,11 @@ fn fieldPtr(
2731027590 switch (inner_ty.zigTypeTag(mod)) {
2731127591 .Array => {
2731227592 if (field_name.eqlSlice("len", ip)) {
27313 const int_val = try mod.intValue(Type.usize, inner_ty.arrayLen(mod));
27593 const int_val = try pt.intValue(Type.usize, inner_ty.arrayLen(mod));
2731427594 return anonDeclRef(sema, int_val.toIntern());
2731527595 } else if (field_name.eqlSlice("ptr", ip) and is_pointer_to) {
2731627596 const ptr_info = object_ty.ptrInfo(mod);
27317 const new_ptr_ty = try mod.ptrTypeSema(.{
27597 const new_ptr_ty = try pt.ptrTypeSema(.{
2731827598 .child = Type.fromInterned(ptr_info.child).childType(mod).toIntern(),
2731927599 .sentinel = if (object_ty.sentinel(mod)) |s| s.toIntern() else .none,
2732027600 .flags = .{
......@@ -27329,7 +27609,7 @@ fn fieldPtr(
2732927609 .packed_offset = ptr_info.packed_offset,
2733027610 });
2733127611 const ptr_ptr_info = object_ptr_ty.ptrInfo(mod);
27332 const result_ty = try mod.ptrTypeSema(.{
27612 const result_ty = try pt.ptrTypeSema(.{
2733327613 .child = new_ptr_ty.toIntern(),
2733427614 .sentinel = if (object_ptr_ty.sentinel(mod)) |s| s.toIntern() else .none,
2733527615 .flags = .{
......@@ -27348,7 +27628,7 @@ fn fieldPtr(
2734827628 block,
2734927629 field_name_src,
2735027630 "no member named '{}' in '{}'",
27351 .{ field_name.fmt(ip), object_ty.fmt(mod) },
27631 .{ field_name.fmt(ip), object_ty.fmt(pt) },
2735227632 );
2735327633 }
2735427634 },
......@@ -27363,7 +27643,7 @@ fn fieldPtr(
2736327643 if (field_name.eqlSlice("ptr", ip)) {
2736427644 const slice_ptr_ty = inner_ty.slicePtrFieldType(mod);
2736527645
27366 const result_ty = try mod.ptrTypeSema(.{
27646 const result_ty = try pt.ptrTypeSema(.{
2736727647 .child = slice_ptr_ty.toIntern(),
2736827648 .flags = .{
2736927649 .is_const = !attr_ptr_ty.ptrIsMutable(mod),
......@@ -27373,7 +27653,7 @@ fn fieldPtr(
2737327653 });
2737427654
2737527655 if (try sema.resolveDefinedValue(block, object_ptr_src, inner_ptr)) |val| {
27376 return Air.internedToRef((try val.ptrField(Value.slice_ptr_index, mod)).toIntern());
27656 return Air.internedToRef((try val.ptrField(Value.slice_ptr_index, pt)).toIntern());
2737727657 }
2737827658 try sema.requireRuntimeBlock(block, src, null);
2737927659
......@@ -27381,7 +27661,7 @@ fn fieldPtr(
2738127661 try sema.checkKnownAllocPtr(block, inner_ptr, field_ptr);
2738227662 return field_ptr;
2738327663 } else if (field_name.eqlSlice("len", ip)) {
27384 const result_ty = try mod.ptrTypeSema(.{
27664 const result_ty = try pt.ptrTypeSema(.{
2738527665 .child = .usize_type,
2738627666 .flags = .{
2738727667 .is_const = !attr_ptr_ty.ptrIsMutable(mod),
......@@ -27391,7 +27671,7 @@ fn fieldPtr(
2739127671 });
2739227672
2739327673 if (try sema.resolveDefinedValue(block, object_ptr_src, inner_ptr)) |val| {
27394 return Air.internedToRef((try val.ptrField(Value.slice_len_index, mod)).toIntern());
27674 return Air.internedToRef((try val.ptrField(Value.slice_len_index, pt)).toIntern());
2739527675 }
2739627676 try sema.requireRuntimeBlock(block, src, null);
2739727677
......@@ -27403,7 +27683,7 @@ fn fieldPtr(
2740327683 block,
2740427684 field_name_src,
2740527685 "no member named '{}' in '{}'",
27406 .{ field_name.fmt(ip), object_ty.fmt(mod) },
27686 .{ field_name.fmt(ip), object_ty.fmt(pt) },
2740727687 );
2740827688 }
2740927689 },
......@@ -27433,7 +27713,7 @@ fn fieldPtr(
2743327713 break :blk;
2743427714 }
2743527715 return sema.fail(block, src, "no error named '{}' in '{}'", .{
27436 field_name.fmt(ip), child_type.fmt(mod),
27716 field_name.fmt(ip), child_type.fmt(pt),
2743727717 });
2743827718 },
2743927719 .inferred_error_set_type => {
......@@ -27449,8 +27729,8 @@ fn fieldPtr(
2744927729 const error_set_type = if (!child_type.isAnyError(mod))
2745027730 child_type
2745127731 else
27452 try mod.singleErrorSetType(field_name);
27453 return anonDeclRef(sema, try mod.intern(.{ .err = .{
27732 try pt.singleErrorSetType(field_name);
27733 return anonDeclRef(sema, try pt.intern(.{ .err = .{
2745427734 .ty = error_set_type.toIntern(),
2745527735 .name = field_name,
2745627736 } }));
......@@ -27459,11 +27739,11 @@ fn fieldPtr(
2745927739 if (try sema.namespaceLookupRef(block, src, child_type.getNamespaceIndex(mod), field_name)) |inst| {
2746027740 return inst;
2746127741 }
27462 try child_type.resolveFields(mod);
27742 try child_type.resolveFields(pt);
2746327743 if (child_type.unionTagType(mod)) |enum_ty| {
2746427744 if (enum_ty.enumFieldIndex(field_name, mod)) |field_index| {
2746527745 const field_index_u32: u32 = @intCast(field_index);
27466 const idx_val = try mod.enumValueFieldIndex(enum_ty, field_index_u32);
27746 const idx_val = try pt.enumValueFieldIndex(enum_ty, field_index_u32);
2746727747 return anonDeclRef(sema, idx_val.toIntern());
2746827748 }
2746927749 }
......@@ -27477,7 +27757,7 @@ fn fieldPtr(
2747727757 return sema.failWithBadMemberAccess(block, child_type, field_name_src, field_name);
2747827758 };
2747927759 const field_index_u32: u32 = @intCast(field_index);
27480 const idx_val = try mod.enumValueFieldIndex(child_type, field_index_u32);
27760 const idx_val = try pt.enumValueFieldIndex(child_type, field_index_u32);
2748127761 return anonDeclRef(sema, idx_val.toIntern());
2748227762 },
2748327763 .Struct, .Opaque => {
......@@ -27486,7 +27766,7 @@ fn fieldPtr(
2748627766 }
2748727767 return sema.failWithBadMemberAccess(block, child_type, field_name_src, field_name);
2748827768 },
27489 else => return sema.fail(block, src, "type '{}' has no members", .{child_type.fmt(mod)}),
27769 else => return sema.fail(block, src, "type '{}' has no members", .{child_type.fmt(pt)}),
2749027770 }
2749127771 },
2749227772 .Struct => {
......@@ -27533,14 +27813,15 @@ fn fieldCallBind(
2753327813 // When editing this function, note that there is corresponding logic to be edited
2753427814 // in `fieldVal`. This function takes a pointer and returns a pointer.
2753527815
27536 const mod = sema.mod;
27816 const pt = sema.pt;
27817 const mod = pt.zcu;
2753727818 const ip = &mod.intern_pool;
2753827819 const raw_ptr_src = src; // TODO better source location
2753927820 const raw_ptr_ty = sema.typeOf(raw_ptr);
2754027821 const inner_ty = if (raw_ptr_ty.zigTypeTag(mod) == .Pointer and (raw_ptr_ty.ptrSize(mod) == .One or raw_ptr_ty.ptrSize(mod) == .C))
2754127822 raw_ptr_ty.childType(mod)
2754227823 else
27543 return sema.fail(block, raw_ptr_src, "expected single pointer, found '{}'", .{raw_ptr_ty.fmt(mod)});
27824 return sema.fail(block, raw_ptr_src, "expected single pointer, found '{}'", .{raw_ptr_ty.fmt(pt)});
2754427825
2754527826 // Optionally dereference a second pointer to get the concrete type.
2754627827 const is_double_ptr = inner_ty.zigTypeTag(mod) == .Pointer and inner_ty.ptrSize(mod) == .One;
......@@ -27554,7 +27835,7 @@ fn fieldCallBind(
2755427835 find_field: {
2755527836 switch (concrete_ty.zigTypeTag(mod)) {
2755627837 .Struct => {
27557 try concrete_ty.resolveFields(mod);
27838 try concrete_ty.resolveFields(pt);
2755827839 if (mod.typeToStruct(concrete_ty)) |struct_type| {
2755927840 const field_index = struct_type.nameIndex(ip, field_name) orelse
2756027841 break :find_field;
......@@ -27563,7 +27844,7 @@ fn fieldCallBind(
2756327844 return sema.finishFieldCallBind(block, src, ptr_ty, field_ty, field_index, object_ptr);
2756427845 } else if (concrete_ty.isTuple(mod)) {
2756527846 if (field_name.eqlSlice("len", ip)) {
27566 return .{ .direct = try mod.intRef(Type.usize, concrete_ty.structFieldCount(mod)) };
27847 return .{ .direct = try pt.intRef(Type.usize, concrete_ty.structFieldCount(mod)) };
2756727848 }
2756827849 if (field_name.toUnsigned(ip)) |field_index| {
2756927850 if (field_index >= concrete_ty.structFieldCount(mod)) break :find_field;
......@@ -27580,7 +27861,7 @@ fn fieldCallBind(
2758027861 }
2758127862 },
2758227863 .Union => {
27583 try concrete_ty.resolveFields(mod);
27864 try concrete_ty.resolveFields(pt);
2758427865 const union_obj = mod.typeToUnion(concrete_ty).?;
2758527866 _ = union_obj.loadTagType(ip).nameIndex(ip, field_name) orelse break :find_field;
2758627867 const field_ptr = try unionFieldPtr(sema, block, src, object_ptr, field_name, field_name_src, concrete_ty, false);
......@@ -27661,7 +27942,7 @@ fn fieldCallBind(
2766127942 const msg = msg: {
2766227943 const msg = try sema.errMsg(src, "no field or member function named '{}' in '{}'", .{
2766327944 field_name.fmt(ip),
27664 concrete_ty.fmt(mod),
27945 concrete_ty.fmt(pt),
2766527946 });
2766627947 errdefer msg.destroy(sema.gpa);
2766727948 try sema.addDeclaredHereNote(msg, concrete_ty);
......@@ -27689,8 +27970,9 @@ fn finishFieldCallBind(
2768927970 field_index: u32,
2769027971 object_ptr: Air.Inst.Ref,
2769127972) CompileError!ResolvedFieldCallee {
27692 const mod = sema.mod;
27693 const ptr_field_ty = try mod.ptrTypeSema(.{
27973 const pt = sema.pt;
27974 const mod = pt.zcu;
27975 const ptr_field_ty = try pt.ptrTypeSema(.{
2769427976 .child = field_ty.toIntern(),
2769527977 .flags = .{
2769627978 .is_const = !ptr_ty.ptrIsMutable(mod),
......@@ -27701,14 +27983,14 @@ fn finishFieldCallBind(
2770127983 const container_ty = ptr_ty.childType(mod);
2770227984 if (container_ty.zigTypeTag(mod) == .Struct) {
2770327985 if (container_ty.structFieldIsComptime(field_index, mod)) {
27704 try container_ty.resolveStructFieldInits(mod);
27705 const default_val = (try container_ty.structFieldValueComptime(mod, field_index)).?;
27986 try container_ty.resolveStructFieldInits(pt);
27987 const default_val = (try container_ty.structFieldValueComptime(pt, field_index)).?;
2770627988 return .{ .direct = Air.internedToRef(default_val.toIntern()) };
2770727989 }
2770827990 }
2770927991
2771027992 if (try sema.resolveDefinedValue(block, src, object_ptr)) |struct_ptr_val| {
27711 const ptr_val = try struct_ptr_val.ptrField(field_index, mod);
27993 const ptr_val = try struct_ptr_val.ptrField(field_index, pt);
2771227994 const pointer = Air.internedToRef(ptr_val.toIntern());
2771327995 return .{ .direct = try sema.analyzeLoad(block, src, pointer, src) };
2771427996 }
......@@ -27725,7 +28007,8 @@ fn namespaceLookup(
2772528007 opt_namespace: InternPool.OptionalNamespaceIndex,
2772628008 decl_name: InternPool.NullTerminatedString,
2772728009) CompileError!?InternPool.DeclIndex {
27728 const mod = sema.mod;
28010 const pt = sema.pt;
28011 const mod = pt.zcu;
2772928012 const gpa = sema.gpa;
2773028013 if (try sema.lookupInNamespace(block, src, opt_namespace, decl_name, true)) |decl_index| {
2773128014 const decl = mod.declPtr(decl_index);
......@@ -27780,16 +28063,17 @@ fn structFieldPtr(
2778028063 struct_ty: Type,
2778128064 initializing: bool,
2778228065) CompileError!Air.Inst.Ref {
27783 const mod = sema.mod;
28066 const pt = sema.pt;
28067 const mod = pt.zcu;
2778428068 const ip = &mod.intern_pool;
2778528069 assert(struct_ty.zigTypeTag(mod) == .Struct);
2778628070
27787 try struct_ty.resolveFields(mod);
27788 try struct_ty.resolveLayout(mod);
28071 try struct_ty.resolveFields(pt);
28072 try struct_ty.resolveLayout(pt);
2778928073
2779028074 if (struct_ty.isTuple(mod)) {
2779128075 if (field_name.eqlSlice("len", ip)) {
27792 const len_inst = try mod.intRef(Type.usize, struct_ty.structFieldCount(mod));
28076 const len_inst = try pt.intRef(Type.usize, struct_ty.structFieldCount(mod));
2779328077 return sema.analyzeRef(block, src, len_inst);
2779428078 }
2779528079 const field_index = try sema.tupleFieldIndex(block, struct_ty, field_name, field_name_src);
......@@ -27817,14 +28101,15 @@ fn structFieldPtrByIndex(
2781728101 struct_ty: Type,
2781828102 initializing: bool,
2781928103) CompileError!Air.Inst.Ref {
27820 const mod = sema.mod;
28104 const pt = sema.pt;
28105 const mod = pt.zcu;
2782128106 const ip = &mod.intern_pool;
2782228107 if (struct_ty.isAnonStruct(mod)) {
2782328108 return sema.tupleFieldPtr(block, src, struct_ptr, field_src, field_index, initializing);
2782428109 }
2782528110
2782628111 if (try sema.resolveDefinedValue(block, src, struct_ptr)) |struct_ptr_val| {
27827 const val = try struct_ptr_val.ptrField(field_index, mod);
28112 const val = try struct_ptr_val.ptrField(field_index, pt);
2782828113 return Air.internedToRef(val.toIntern());
2782928114 }
2783028115
......@@ -27848,7 +28133,7 @@ fn structFieldPtrByIndex(
2784828133 try sema.typeAbiAlignment(Type.fromInterned(struct_ptr_ty_info.child));
2784928134
2785028135 if (struct_type.layout == .@"packed") {
27851 switch (struct_ty.packedStructFieldPtrInfo(struct_ptr_ty, field_index, mod)) {
28136 switch (struct_ty.packedStructFieldPtrInfo(struct_ptr_ty, field_index, pt)) {
2785228137 .bit_ptr => |packed_offset| {
2785328138 ptr_ty_data.flags.alignment = parent_align;
2785428139 ptr_ty_data.packed_offset = packed_offset;
......@@ -27861,14 +28146,14 @@ fn structFieldPtrByIndex(
2786128146 // For extern structs, field alignment might be bigger than type's
2786228147 // natural alignment. Eg, in `extern struct { x: u32, y: u16 }` the
2786328148 // second field is aligned as u32.
27864 const field_offset = struct_ty.structFieldOffset(field_index, mod);
28149 const field_offset = struct_ty.structFieldOffset(field_index, pt);
2786528150 ptr_ty_data.flags.alignment = if (parent_align == .none)
2786628151 .none
2786728152 else
2786828153 @enumFromInt(@min(@intFromEnum(parent_align), @ctz(field_offset)));
2786928154 } else {
2787028155 // Our alignment is capped at the field alignment.
27871 const field_align = try mod.structFieldAlignmentAdvanced(
28156 const field_align = try pt.structFieldAlignmentAdvanced(
2787228157 struct_type.fieldAlign(ip, field_index),
2787328158 Type.fromInterned(field_ty),
2787428159 struct_type.layout,
......@@ -27880,11 +28165,11 @@ fn structFieldPtrByIndex(
2788028165 field_align.min(parent_align);
2788128166 }
2788228167
27883 const ptr_field_ty = try mod.ptrTypeSema(ptr_ty_data);
28168 const ptr_field_ty = try pt.ptrTypeSema(ptr_ty_data);
2788428169
2788528170 if (struct_type.fieldIsComptime(ip, field_index)) {
27886 try struct_ty.resolveStructFieldInits(mod);
27887 const val = try mod.intern(.{ .ptr = .{
28171 try struct_ty.resolveStructFieldInits(pt);
28172 const val = try pt.intern(.{ .ptr = .{
2788828173 .ty = ptr_field_ty.toIntern(),
2788928174 .base_addr = .{ .comptime_field = struct_type.field_inits.get(ip)[field_index] },
2789028175 .byte_offset = 0,
......@@ -27905,11 +28190,12 @@ fn structFieldVal(
2790528190 field_name_src: LazySrcLoc,
2790628191 struct_ty: Type,
2790728192) CompileError!Air.Inst.Ref {
27908 const mod = sema.mod;
28193 const pt = sema.pt;
28194 const mod = pt.zcu;
2790928195 const ip = &mod.intern_pool;
2791028196 assert(struct_ty.zigTypeTag(mod) == .Struct);
2791128197
27912 try struct_ty.resolveFields(mod);
28198 try struct_ty.resolveFields(pt);
2791328199
2791428200 switch (ip.indexToKey(struct_ty.toIntern())) {
2791528201 .struct_type => {
......@@ -27920,7 +28206,7 @@ fn structFieldVal(
2792028206 const field_index = struct_type.nameIndex(ip, field_name) orelse
2792128207 return sema.failWithBadStructFieldAccess(block, struct_ty, struct_type, field_name_src, field_name);
2792228208 if (struct_type.fieldIsComptime(ip, field_index)) {
27923 try struct_ty.resolveStructFieldInits(mod);
28209 try struct_ty.resolveStructFieldInits(pt);
2792428210 return Air.internedToRef(struct_type.field_inits.get(ip)[field_index]);
2792528211 }
2792628212
......@@ -27929,15 +28215,15 @@ fn structFieldVal(
2792928215 return Air.internedToRef(field_val.toIntern());
2793028216
2793128217 if (try sema.resolveValue(struct_byval)) |struct_val| {
27932 if (struct_val.isUndef(mod)) return mod.undefRef(field_ty);
28218 if (struct_val.isUndef(mod)) return pt.undefRef(field_ty);
2793328219 if ((try sema.typeHasOnePossibleValue(field_ty))) |opv| {
2793428220 return Air.internedToRef(opv.toIntern());
2793528221 }
27936 return Air.internedToRef((try struct_val.fieldValue(mod, field_index)).toIntern());
28222 return Air.internedToRef((try struct_val.fieldValue(pt, field_index)).toIntern());
2793728223 }
2793828224
2793928225 try sema.requireRuntimeBlock(block, src, null);
27940 try field_ty.resolveLayout(mod);
28226 try field_ty.resolveLayout(pt);
2794128227 return block.addStructFieldVal(struct_byval, field_index, field_ty);
2794228228 },
2794328229 .anon_struct_type => |anon_struct| {
......@@ -27961,9 +28247,10 @@ fn tupleFieldVal(
2796128247 field_name_src: LazySrcLoc,
2796228248 tuple_ty: Type,
2796328249) CompileError!Air.Inst.Ref {
27964 const mod = sema.mod;
28250 const pt = sema.pt;
28251 const mod = pt.zcu;
2796528252 if (field_name.eqlSlice("len", &mod.intern_pool)) {
27966 return mod.intRef(Type.usize, tuple_ty.structFieldCount(mod));
28253 return pt.intRef(Type.usize, tuple_ty.structFieldCount(mod));
2796728254 }
2796828255 const field_index = try sema.tupleFieldIndex(block, tuple_ty, field_name, field_name_src);
2796928256 return sema.tupleFieldValByIndex(block, src, tuple_byval, field_index, tuple_ty);
......@@ -27977,18 +28264,18 @@ fn tupleFieldIndex(
2797728264 field_name: InternPool.NullTerminatedString,
2797828265 field_name_src: LazySrcLoc,
2797928266) CompileError!u32 {
27980 const mod = sema.mod;
27981 const ip = &mod.intern_pool;
28267 const pt = sema.pt;
28268 const ip = &pt.zcu.intern_pool;
2798228269 assert(!field_name.eqlSlice("len", ip));
2798328270 if (field_name.toUnsigned(ip)) |field_index| {
27984 if (field_index < tuple_ty.structFieldCount(mod)) return field_index;
28271 if (field_index < tuple_ty.structFieldCount(pt.zcu)) return field_index;
2798528272 return sema.fail(block, field_name_src, "index '{}' out of bounds of tuple '{}'", .{
27986 field_name.fmt(ip), tuple_ty.fmt(mod),
28273 field_name.fmt(ip), tuple_ty.fmt(pt),
2798728274 });
2798828275 }
2798928276
2799028277 return sema.fail(block, field_name_src, "no field named '{}' in tuple '{}'", .{
27991 field_name.fmt(ip), tuple_ty.fmt(mod),
28278 field_name.fmt(ip), tuple_ty.fmt(pt),
2799228279 });
2799328280}
2799428281
......@@ -28000,12 +28287,13 @@ fn tupleFieldValByIndex(
2800028287 field_index: u32,
2800128288 tuple_ty: Type,
2800228289) CompileError!Air.Inst.Ref {
28003 const mod = sema.mod;
28290 const pt = sema.pt;
28291 const mod = pt.zcu;
2800428292 const field_ty = tuple_ty.structFieldType(field_index, mod);
2800528293
2800628294 if (tuple_ty.structFieldIsComptime(field_index, mod))
28007 try tuple_ty.resolveStructFieldInits(mod);
28008 if (try tuple_ty.structFieldValueComptime(mod, field_index)) |default_value| {
28295 try tuple_ty.resolveStructFieldInits(pt);
28296 if (try tuple_ty.structFieldValueComptime(pt, field_index)) |default_value| {
2800928297 return Air.internedToRef(default_value.toIntern());
2801028298 }
2801128299
......@@ -28014,9 +28302,9 @@ fn tupleFieldValByIndex(
2801428302 return Air.internedToRef(opv.toIntern());
2801528303 }
2801628304 return switch (mod.intern_pool.indexToKey(tuple_val.toIntern())) {
28017 .undef => mod.undefRef(field_ty),
28305 .undef => pt.undefRef(field_ty),
2801828306 .aggregate => |aggregate| Air.internedToRef(switch (aggregate.storage) {
28019 .bytes => |bytes| try mod.intValue(Type.u8, bytes.at(field_index, &mod.intern_pool)),
28307 .bytes => |bytes| try pt.intValue(Type.u8, bytes.at(field_index, &mod.intern_pool)),
2802028308 .elems => |elems| Value.fromInterned(elems[field_index]),
2802128309 .repeated_elem => |elem| Value.fromInterned(elem),
2802228310 }.toIntern()),
......@@ -28025,7 +28313,7 @@ fn tupleFieldValByIndex(
2802528313 }
2802628314
2802728315 try sema.requireRuntimeBlock(block, src, null);
28028 try field_ty.resolveLayout(mod);
28316 try field_ty.resolveLayout(pt);
2802928317 return block.addStructFieldVal(tuple_byval, field_index, field_ty);
2803028318}
2803128319
......@@ -28039,18 +28327,19 @@ fn unionFieldPtr(
2803928327 union_ty: Type,
2804028328 initializing: bool,
2804128329) CompileError!Air.Inst.Ref {
28042 const mod = sema.mod;
28330 const pt = sema.pt;
28331 const mod = pt.zcu;
2804328332 const ip = &mod.intern_pool;
2804428333
2804528334 assert(union_ty.zigTypeTag(mod) == .Union);
2804628335
2804728336 const union_ptr_ty = sema.typeOf(union_ptr);
2804828337 const union_ptr_info = union_ptr_ty.ptrInfo(mod);
28049 try union_ty.resolveFields(mod);
28338 try union_ty.resolveFields(pt);
2805028339 const union_obj = mod.typeToUnion(union_ty).?;
2805128340 const field_index = try sema.unionFieldIndex(block, union_ty, field_name, field_name_src);
2805228341 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
28053 const ptr_field_ty = try mod.ptrTypeSema(.{
28342 const ptr_field_ty = try pt.ptrTypeSema(.{
2805428343 .child = field_ty.toIntern(),
2805528344 .flags = .{
2805628345 .is_const = union_ptr_info.flags.is_const,
......@@ -28061,7 +28350,7 @@ fn unionFieldPtr(
2806128350 union_ptr_info.flags.alignment
2806228351 else
2806328352 try sema.typeAbiAlignment(union_ty);
28064 const field_align = try mod.unionFieldNormalAlignmentAdvanced(union_obj, field_index, .sema);
28353 const field_align = try pt.unionFieldNormalAlignmentAdvanced(union_obj, field_index, .sema);
2806528354 break :blk union_align.min(field_align);
2806628355 } else union_ptr_info.flags.alignment,
2806728356 },
......@@ -28087,9 +28376,9 @@ fn unionFieldPtr(
2808728376 switch (union_obj.getLayout(ip)) {
2808828377 .auto => if (initializing) {
2808928378 // Store to the union to initialize the tag.
28090 const field_tag = try mod.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
28379 const field_tag = try pt.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
2809128380 const payload_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
28092 const new_union_val = try mod.unionValue(union_ty, field_tag, try mod.undefValue(payload_ty));
28381 const new_union_val = try pt.unionValue(union_ty, field_tag, try pt.undefValue(payload_ty));
2809328382 try sema.storePtrVal(block, src, union_ptr_val, new_union_val, union_ty);
2809428383 } else {
2809528384 const union_val = (try sema.pointerDeref(block, src, union_ptr_val, union_ptr_ty)) orelse
......@@ -28098,7 +28387,7 @@ fn unionFieldPtr(
2809828387 return sema.failWithUseOfUndef(block, src);
2809928388 }
2810028389 const un = ip.indexToKey(union_val.toIntern()).un;
28101 const field_tag = try mod.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
28390 const field_tag = try pt.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
2810228391 const tag_matches = un.tag == field_tag.toIntern();
2810328392 if (!tag_matches) {
2810428393 const msg = msg: {
......@@ -28117,7 +28406,7 @@ fn unionFieldPtr(
2811728406 },
2811828407 .@"packed", .@"extern" => {},
2811928408 }
28120 const field_ptr_val = try union_ptr_val.ptrField(field_index, mod);
28409 const field_ptr_val = try union_ptr_val.ptrField(field_index, pt);
2812128410 return Air.internedToRef(field_ptr_val.toIntern());
2812228411 }
2812328412
......@@ -28125,7 +28414,7 @@ fn unionFieldPtr(
2812528414 if (!initializing and union_obj.getLayout(ip) == .auto and block.wantSafety() and
2812628415 union_ty.unionTagTypeSafety(mod) != null and union_obj.field_types.len > 1)
2812728416 {
28128 const wanted_tag_val = try mod.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
28417 const wanted_tag_val = try pt.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
2812928418 const wanted_tag = Air.internedToRef(wanted_tag_val.toIntern());
2813028419 // TODO would it be better if get_union_tag supported pointers to unions?
2813128420 const union_val = try block.addTyOp(.load, union_ty, union_ptr);
......@@ -28148,21 +28437,22 @@ fn unionFieldVal(
2814828437 field_name_src: LazySrcLoc,
2814928438 union_ty: Type,
2815028439) CompileError!Air.Inst.Ref {
28151 const zcu = sema.mod;
28440 const pt = sema.pt;
28441 const zcu = pt.zcu;
2815228442 const ip = &zcu.intern_pool;
2815328443 assert(union_ty.zigTypeTag(zcu) == .Union);
2815428444
28155 try union_ty.resolveFields(zcu);
28445 try union_ty.resolveFields(pt);
2815628446 const union_obj = zcu.typeToUnion(union_ty).?;
2815728447 const field_index = try sema.unionFieldIndex(block, union_ty, field_name, field_name_src);
2815828448 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
2815928449 const enum_field_index: u32 = @intCast(Type.fromInterned(union_obj.enum_tag_ty).enumFieldIndex(field_name, zcu).?);
2816028450
2816128451 if (try sema.resolveValue(union_byval)) |union_val| {
28162 if (union_val.isUndef(zcu)) return zcu.undefRef(field_ty);
28452 if (union_val.isUndef(zcu)) return pt.undefRef(field_ty);
2816328453
2816428454 const un = ip.indexToKey(union_val.toIntern()).un;
28165 const field_tag = try zcu.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
28455 const field_tag = try pt.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
2816628456 const tag_matches = un.tag == field_tag.toIntern();
2816728457 switch (union_obj.getLayout(ip)) {
2816828458 .auto => {
......@@ -28191,7 +28481,7 @@ fn unionFieldVal(
2819128481 .@"packed" => if (tag_matches) {
2819228482 // Fast path - no need to use bitcast logic.
2819328483 return Air.internedToRef(un.val);
28194 } else if (try sema.bitCastVal(union_val, field_ty, 0, try union_ty.bitSizeAdvanced(zcu, .sema), 0)) |field_val| {
28484 } else if (try sema.bitCastVal(union_val, field_ty, 0, try union_ty.bitSizeAdvanced(pt, .sema), 0)) |field_val| {
2819528485 return Air.internedToRef(field_val.toIntern());
2819628486 },
2819728487 }
......@@ -28201,7 +28491,7 @@ fn unionFieldVal(
2820128491 if (union_obj.getLayout(ip) == .auto and block.wantSafety() and
2820228492 union_ty.unionTagTypeSafety(zcu) != null and union_obj.field_types.len > 1)
2820328493 {
28204 const wanted_tag_val = try zcu.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
28494 const wanted_tag_val = try pt.enumValueFieldIndex(Type.fromInterned(union_obj.enum_tag_ty), enum_field_index);
2820528495 const wanted_tag = Air.internedToRef(wanted_tag_val.toIntern());
2820628496 const active_tag = try block.addTyOp(.get_union_tag, Type.fromInterned(union_obj.enum_tag_ty), union_byval);
2820728497 try sema.panicInactiveUnionField(block, src, active_tag, wanted_tag);
......@@ -28210,7 +28500,7 @@ fn unionFieldVal(
2821028500 _ = try block.addNoOp(.unreach);
2821128501 return .unreachable_value;
2821228502 }
28213 try field_ty.resolveLayout(zcu);
28503 try field_ty.resolveLayout(pt);
2821428504 return block.addStructFieldVal(union_byval, field_index, field_ty);
2821528505}
2821628506
......@@ -28224,13 +28514,14 @@ fn elemPtr(
2822428514 init: bool,
2822528515 oob_safety: bool,
2822628516) CompileError!Air.Inst.Ref {
28227 const mod = sema.mod;
28517 const pt = sema.pt;
28518 const mod = pt.zcu;
2822828519 const indexable_ptr_src = src; // TODO better source location
2822928520 const indexable_ptr_ty = sema.typeOf(indexable_ptr);
2823028521
2823128522 const indexable_ty = switch (indexable_ptr_ty.zigTypeTag(mod)) {
2823228523 .Pointer => indexable_ptr_ty.childType(mod),
28233 else => return sema.fail(block, indexable_ptr_src, "expected pointer, found '{}'", .{indexable_ptr_ty.fmt(mod)}),
28524 else => return sema.fail(block, indexable_ptr_src, "expected pointer, found '{}'", .{indexable_ptr_ty.fmt(pt)}),
2823428525 };
2823528526 try checkIndexable(sema, block, src, indexable_ty);
2823628527
......@@ -28241,7 +28532,7 @@ fn elemPtr(
2824128532 const index_val = try sema.resolveConstDefinedValue(block, elem_index_src, elem_index, .{
2824228533 .needed_comptime_reason = "tuple field access index must be comptime-known",
2824328534 });
28244 const index: u32 = @intCast(try index_val.toUnsignedIntSema(mod));
28535 const index: u32 = @intCast(try index_val.toUnsignedIntSema(pt));
2824528536 break :blk try sema.tupleFieldPtr(block, src, indexable_ptr, elem_index_src, index, init);
2824628537 },
2824728538 else => {
......@@ -28267,7 +28558,8 @@ fn elemPtrOneLayerOnly(
2826728558) CompileError!Air.Inst.Ref {
2826828559 const indexable_src = src; // TODO better source location
2826928560 const indexable_ty = sema.typeOf(indexable);
28270 const mod = sema.mod;
28561 const pt = sema.pt;
28562 const mod = pt.zcu;
2827128563
2827228564 try checkIndexable(sema, block, src, indexable_ty);
2827328565
......@@ -28279,11 +28571,11 @@ fn elemPtrOneLayerOnly(
2827928571 const runtime_src = rs: {
2828028572 const ptr_val = maybe_ptr_val orelse break :rs indexable_src;
2828128573 const index_val = maybe_index_val orelse break :rs elem_index_src;
28282 const index: usize = @intCast(try index_val.toUnsignedIntSema(mod));
28283 const elem_ptr = try ptr_val.ptrElem(index, mod);
28574 const index: usize = @intCast(try index_val.toUnsignedIntSema(pt));
28575 const elem_ptr = try ptr_val.ptrElem(index, pt);
2828428576 return Air.internedToRef(elem_ptr.toIntern());
2828528577 };
28286 const result_ty = try indexable_ty.elemPtrType(null, mod);
28578 const result_ty = try indexable_ty.elemPtrType(null, pt);
2828728579
2828828580 try sema.requireRuntimeBlock(block, src, runtime_src);
2828928581 return block.addPtrElemPtr(indexable, elem_index, result_ty);
......@@ -28297,7 +28589,7 @@ fn elemPtrOneLayerOnly(
2829728589 const index_val = try sema.resolveConstDefinedValue(block, elem_index_src, elem_index, .{
2829828590 .needed_comptime_reason = "tuple field access index must be comptime-known",
2829928591 });
28300 const index: u32 = @intCast(try index_val.toUnsignedIntSema(mod));
28592 const index: u32 = @intCast(try index_val.toUnsignedIntSema(pt));
2830128593 break :blk try sema.tupleFieldPtr(block, indexable_src, indexable, elem_index_src, index, false);
2830228594 },
2830328595 else => unreachable, // Guaranteed by checkIndexable
......@@ -28319,7 +28611,8 @@ fn elemVal(
2831928611) CompileError!Air.Inst.Ref {
2832028612 const indexable_src = src; // TODO better source location
2832128613 const indexable_ty = sema.typeOf(indexable);
28322 const mod = sema.mod;
28614 const pt = sema.pt;
28615 const mod = pt.zcu;
2832328616
2832428617 try checkIndexable(sema, block, src, indexable_ty);
2832528618
......@@ -28337,14 +28630,14 @@ fn elemVal(
2833728630 const runtime_src = rs: {
2833828631 const indexable_val = maybe_indexable_val orelse break :rs indexable_src;
2833928632 const index_val = maybe_index_val orelse break :rs elem_index_src;
28340 const index: usize = @intCast(try index_val.toUnsignedIntSema(mod));
28633 const index: usize = @intCast(try index_val.toUnsignedIntSema(pt));
2834128634 const elem_ty = indexable_ty.elemType2(mod);
28342 const many_ptr_ty = try mod.manyConstPtrType(elem_ty);
28343 const many_ptr_val = try mod.getCoerced(indexable_val, many_ptr_ty);
28344 const elem_ptr_ty = try mod.singleConstPtrType(elem_ty);
28345 const elem_ptr_val = try many_ptr_val.ptrElem(index, mod);
28635 const many_ptr_ty = try pt.manyConstPtrType(elem_ty);
28636 const many_ptr_val = try pt.getCoerced(indexable_val, many_ptr_ty);
28637 const elem_ptr_ty = try pt.singleConstPtrType(elem_ty);
28638 const elem_ptr_val = try many_ptr_val.ptrElem(index, pt);
2834628639 if (try sema.pointerDeref(block, indexable_src, elem_ptr_val, elem_ptr_ty)) |elem_val| {
28347 return Air.internedToRef((try mod.getCoerced(elem_val, elem_ty)).toIntern());
28640 return Air.internedToRef((try pt.getCoerced(elem_val, elem_ty)).toIntern());
2834828641 }
2834928642 break :rs indexable_src;
2835028643 };
......@@ -28358,7 +28651,7 @@ fn elemVal(
2835828651 if (inner_ty.zigTypeTag(mod) != .Array) break :arr_sent;
2835928652 const sentinel = inner_ty.sentinel(mod) orelse break :arr_sent;
2836028653 const index_val = try sema.resolveDefinedValue(block, elem_index_src, elem_index) orelse break :arr_sent;
28361 const index = try sema.usizeCast(block, src, try index_val.toUnsignedIntSema(mod));
28654 const index = try sema.usizeCast(block, src, try index_val.toUnsignedIntSema(pt));
2836228655 if (index != inner_ty.arrayLen(mod)) break :arr_sent;
2836328656 return Air.internedToRef(sentinel.toIntern());
2836428657 }
......@@ -28376,7 +28669,7 @@ fn elemVal(
2837628669 const index_val = try sema.resolveConstDefinedValue(block, elem_index_src, elem_index, .{
2837728670 .needed_comptime_reason = "tuple field access index must be comptime-known",
2837828671 });
28379 const index: u32 = @intCast(try index_val.toUnsignedIntSema(mod));
28672 const index: u32 = @intCast(try index_val.toUnsignedIntSema(pt));
2838028673 return sema.tupleField(block, indexable_src, indexable, elem_index_src, index);
2838128674 },
2838228675 else => unreachable,
......@@ -28391,13 +28684,12 @@ fn validateRuntimeElemAccess(
2839128684 parent_ty: Type,
2839228685 parent_src: LazySrcLoc,
2839328686) CompileError!void {
28394 const mod = sema.mod;
2839528687 if (try sema.typeRequiresComptime(elem_ty)) {
2839628688 const msg = msg: {
2839728689 const msg = try sema.errMsg(
2839828690 elem_index_src,
2839928691 "values of type '{}' must be comptime-known, but index value is runtime-known",
28400 .{parent_ty.fmt(mod)},
28692 .{parent_ty.fmt(sema.pt)},
2840128693 );
2840228694 errdefer msg.destroy(sema.gpa);
2840328695
......@@ -28418,10 +28710,11 @@ fn tupleFieldPtr(
2841828710 field_index: u32,
2841928711 init: bool,
2842028712) CompileError!Air.Inst.Ref {
28421 const mod = sema.mod;
28713 const pt = sema.pt;
28714 const mod = pt.zcu;
2842228715 const tuple_ptr_ty = sema.typeOf(tuple_ptr);
2842328716 const tuple_ty = tuple_ptr_ty.childType(mod);
28424 try tuple_ty.resolveFields(mod);
28717 try tuple_ty.resolveFields(pt);
2842528718 const field_count = tuple_ty.structFieldCount(mod);
2842628719
2842728720 if (field_count == 0) {
......@@ -28435,7 +28728,7 @@ fn tupleFieldPtr(
2843528728 }
2843628729
2843728730 const field_ty = tuple_ty.structFieldType(field_index, mod);
28438 const ptr_field_ty = try mod.ptrTypeSema(.{
28731 const ptr_field_ty = try pt.ptrTypeSema(.{
2843928732 .child = field_ty.toIntern(),
2844028733 .flags = .{
2844128734 .is_const = !tuple_ptr_ty.ptrIsMutable(mod),
......@@ -28445,10 +28738,10 @@ fn tupleFieldPtr(
2844528738 });
2844628739
2844728740 if (tuple_ty.structFieldIsComptime(field_index, mod))
28448 try tuple_ty.resolveStructFieldInits(mod);
28741 try tuple_ty.resolveStructFieldInits(pt);
2844928742
28450 if (try tuple_ty.structFieldValueComptime(mod, field_index)) |default_val| {
28451 return Air.internedToRef((try mod.intern(.{ .ptr = .{
28743 if (try tuple_ty.structFieldValueComptime(pt, field_index)) |default_val| {
28744 return Air.internedToRef((try pt.intern(.{ .ptr = .{
2845228745 .ty = ptr_field_ty.toIntern(),
2845328746 .base_addr = .{ .comptime_field = default_val.toIntern() },
2845428747 .byte_offset = 0,
......@@ -28456,7 +28749,7 @@ fn tupleFieldPtr(
2845628749 }
2845728750
2845828751 if (try sema.resolveValue(tuple_ptr)) |tuple_ptr_val| {
28459 const field_ptr_val = try tuple_ptr_val.ptrField(field_index, mod);
28752 const field_ptr_val = try tuple_ptr_val.ptrField(field_index, pt);
2846028753 return Air.internedToRef(field_ptr_val.toIntern());
2846128754 }
2846228755
......@@ -28476,9 +28769,10 @@ fn tupleField(
2847628769 field_index_src: LazySrcLoc,
2847728770 field_index: u32,
2847828771) CompileError!Air.Inst.Ref {
28479 const mod = sema.mod;
28772 const pt = sema.pt;
28773 const mod = pt.zcu;
2848028774 const tuple_ty = sema.typeOf(tuple);
28481 try tuple_ty.resolveFields(mod);
28775 try tuple_ty.resolveFields(pt);
2848228776 const field_count = tuple_ty.structFieldCount(mod);
2848328777
2848428778 if (field_count == 0) {
......@@ -28494,20 +28788,20 @@ fn tupleField(
2849428788 const field_ty = tuple_ty.structFieldType(field_index, mod);
2849528789
2849628790 if (tuple_ty.structFieldIsComptime(field_index, mod))
28497 try tuple_ty.resolveStructFieldInits(mod);
28498 if (try tuple_ty.structFieldValueComptime(mod, field_index)) |default_value| {
28791 try tuple_ty.resolveStructFieldInits(pt);
28792 if (try tuple_ty.structFieldValueComptime(pt, field_index)) |default_value| {
2849928793 return Air.internedToRef(default_value.toIntern()); // comptime field
2850028794 }
2850128795
2850228796 if (try sema.resolveValue(tuple)) |tuple_val| {
28503 if (tuple_val.isUndef(mod)) return mod.undefRef(field_ty);
28504 return Air.internedToRef((try tuple_val.fieldValue(mod, field_index)).toIntern());
28797 if (tuple_val.isUndef(mod)) return pt.undefRef(field_ty);
28798 return Air.internedToRef((try tuple_val.fieldValue(pt, field_index)).toIntern());
2850528799 }
2850628800
2850728801 try sema.validateRuntimeElemAccess(block, field_index_src, field_ty, tuple_ty, tuple_src);
2850828802
2850928803 try sema.requireRuntimeBlock(block, tuple_src, null);
28510 try field_ty.resolveLayout(mod);
28804 try field_ty.resolveLayout(pt);
2851128805 return block.addStructFieldVal(tuple, field_index, field_ty);
2851228806}
2851328807
......@@ -28521,7 +28815,8 @@ fn elemValArray(
2852128815 elem_index: Air.Inst.Ref,
2852228816 oob_safety: bool,
2852328817) CompileError!Air.Inst.Ref {
28524 const mod = sema.mod;
28818 const pt = sema.pt;
28819 const mod = pt.zcu;
2852528820 const array_ty = sema.typeOf(array);
2852628821 const array_sent = array_ty.sentinel(mod);
2852728822 const array_len = array_ty.arrayLen(mod);
......@@ -28537,7 +28832,7 @@ fn elemValArray(
2853728832 const maybe_index_val = try sema.resolveDefinedValue(block, elem_index_src, elem_index);
2853828833
2853928834 if (maybe_index_val) |index_val| {
28540 const index: usize = @intCast(try index_val.toUnsignedIntSema(mod));
28835 const index: usize = @intCast(try index_val.toUnsignedIntSema(pt));
2854128836 if (array_sent) |s| {
2854228837 if (index == array_len) {
2854328838 return Air.internedToRef(s.toIntern());
......@@ -28550,11 +28845,11 @@ fn elemValArray(
2855028845 }
2855128846 if (maybe_undef_array_val) |array_val| {
2855228847 if (array_val.isUndef(mod)) {
28553 return mod.undefRef(elem_ty);
28848 return pt.undefRef(elem_ty);
2855428849 }
2855528850 if (maybe_index_val) |index_val| {
28556 const index: usize = @intCast(try index_val.toUnsignedIntSema(mod));
28557 const elem_val = try array_val.elemValue(mod, index);
28851 const index: usize = @intCast(try index_val.toUnsignedIntSema(pt));
28852 const elem_val = try array_val.elemValue(pt, index);
2855828853 return Air.internedToRef(elem_val.toIntern());
2855928854 }
2856028855 }
......@@ -28565,7 +28860,7 @@ fn elemValArray(
2856528860 if (oob_safety and block.wantSafety()) {
2856628861 // Runtime check is only needed if unable to comptime check
2856728862 if (maybe_index_val == null) {
28568 const len_inst = try mod.intRef(Type.usize, array_len);
28863 const len_inst = try pt.intRef(Type.usize, array_len);
2856928864 const cmp_op: Air.Inst.Tag = if (array_sent != null) .cmp_lte else .cmp_lt;
2857028865 try sema.panicIndexOutOfBounds(block, src, elem_index, len_inst, cmp_op);
2857128866 }
......@@ -28589,7 +28884,8 @@ fn elemPtrArray(
2858928884 init: bool,
2859028885 oob_safety: bool,
2859128886) CompileError!Air.Inst.Ref {
28592 const mod = sema.mod;
28887 const pt = sema.pt;
28888 const mod = pt.zcu;
2859328889 const array_ptr_ty = sema.typeOf(array_ptr);
2859428890 const array_ty = array_ptr_ty.childType(mod);
2859528891 const array_sent = array_ty.sentinel(mod) != null;
......@@ -28603,7 +28899,7 @@ fn elemPtrArray(
2860328899 const maybe_undef_array_ptr_val = try sema.resolveValue(array_ptr);
2860428900 // The index must not be undefined since it can be out of bounds.
2860528901 const offset: ?usize = if (try sema.resolveDefinedValue(block, elem_index_src, elem_index)) |index_val| o: {
28606 const index = try sema.usizeCast(block, elem_index_src, try index_val.toUnsignedIntSema(mod));
28902 const index = try sema.usizeCast(block, elem_index_src, try index_val.toUnsignedIntSema(pt));
2860728903 if (index >= array_len_s) {
2860828904 const sentinel_label: []const u8 = if (array_sent) " +1 (sentinel)" else "";
2860928905 return sema.fail(block, elem_index_src, "index {d} outside array of length {d}{s}", .{ index, array_len, sentinel_label });
......@@ -28611,14 +28907,14 @@ fn elemPtrArray(
2861128907 break :o index;
2861228908 } else null;
2861328909
28614 const elem_ptr_ty = try array_ptr_ty.elemPtrType(offset, mod);
28910 const elem_ptr_ty = try array_ptr_ty.elemPtrType(offset, pt);
2861528911
2861628912 if (maybe_undef_array_ptr_val) |array_ptr_val| {
2861728913 if (array_ptr_val.isUndef(mod)) {
28618 return mod.undefRef(elem_ptr_ty);
28914 return pt.undefRef(elem_ptr_ty);
2861928915 }
2862028916 if (offset) |index| {
28621 const elem_ptr = try array_ptr_val.ptrElem(index, mod);
28917 const elem_ptr = try array_ptr_val.ptrElem(index, pt);
2862228918 return Air.internedToRef(elem_ptr.toIntern());
2862328919 }
2862428920 }
......@@ -28632,7 +28928,7 @@ fn elemPtrArray(
2863228928
2863328929 // Runtime check is only needed if unable to comptime check.
2863428930 if (oob_safety and block.wantSafety() and offset == null) {
28635 const len_inst = try mod.intRef(Type.usize, array_len);
28931 const len_inst = try pt.intRef(Type.usize, array_len);
2863628932 const cmp_op: Air.Inst.Tag = if (array_sent) .cmp_lte else .cmp_lt;
2863728933 try sema.panicIndexOutOfBounds(block, src, elem_index, len_inst, cmp_op);
2863828934 }
......@@ -28650,7 +28946,8 @@ fn elemValSlice(
2865028946 elem_index: Air.Inst.Ref,
2865128947 oob_safety: bool,
2865228948) CompileError!Air.Inst.Ref {
28653 const mod = sema.mod;
28949 const pt = sema.pt;
28950 const mod = pt.zcu;
2865428951 const slice_ty = sema.typeOf(slice);
2865528952 const slice_sent = slice_ty.sentinel(mod) != null;
2865628953 const elem_ty = slice_ty.elemType2(mod);
......@@ -28663,19 +28960,19 @@ fn elemValSlice(
2866328960
2866428961 if (maybe_slice_val) |slice_val| {
2866528962 runtime_src = elem_index_src;
28666 const slice_len = try slice_val.sliceLen(mod);
28963 const slice_len = try slice_val.sliceLen(pt);
2866728964 const slice_len_s = slice_len + @intFromBool(slice_sent);
2866828965 if (slice_len_s == 0) {
2866928966 return sema.fail(block, slice_src, "indexing into empty slice is not allowed", .{});
2867028967 }
2867128968 if (maybe_index_val) |index_val| {
28672 const index: usize = @intCast(try index_val.toUnsignedIntSema(mod));
28969 const index: usize = @intCast(try index_val.toUnsignedIntSema(pt));
2867328970 if (index >= slice_len_s) {
2867428971 const sentinel_label: []const u8 = if (slice_sent) " +1 (sentinel)" else "";
2867528972 return sema.fail(block, elem_index_src, "index {d} outside slice of length {d}{s}", .{ index, slice_len, sentinel_label });
2867628973 }
28677 const elem_ptr_ty = try slice_ty.elemPtrType(index, mod);
28678 const elem_ptr_val = try slice_val.ptrElem(index, mod);
28974 const elem_ptr_ty = try slice_ty.elemPtrType(index, pt);
28975 const elem_ptr_val = try slice_val.ptrElem(index, pt);
2867928976 if (try sema.pointerDeref(block, slice_src, elem_ptr_val, elem_ptr_ty)) |elem_val| {
2868028977 return Air.internedToRef(elem_val.toIntern());
2868128978 }
......@@ -28688,7 +28985,7 @@ fn elemValSlice(
2868828985 try sema.requireRuntimeBlock(block, src, runtime_src);
2868928986 if (oob_safety and block.wantSafety()) {
2869028987 const len_inst = if (maybe_slice_val) |slice_val|
28691 try mod.intRef(Type.usize, try slice_val.sliceLen(mod))
28988 try pt.intRef(Type.usize, try slice_val.sliceLen(pt))
2869228989 else
2869328990 try block.addTyOp(.slice_len, Type.usize, slice);
2869428991 const cmp_op: Air.Inst.Tag = if (slice_sent) .cmp_lte else .cmp_lt;
......@@ -28707,24 +29004,25 @@ fn elemPtrSlice(
2870729004 elem_index: Air.Inst.Ref,
2870829005 oob_safety: bool,
2870929006) CompileError!Air.Inst.Ref {
28710 const mod = sema.mod;
29007 const pt = sema.pt;
29008 const mod = pt.zcu;
2871129009 const slice_ty = sema.typeOf(slice);
2871229010 const slice_sent = slice_ty.sentinel(mod) != null;
2871329011
2871429012 const maybe_undef_slice_val = try sema.resolveValue(slice);
2871529013 // The index must not be undefined since it can be out of bounds.
2871629014 const offset: ?usize = if (try sema.resolveDefinedValue(block, elem_index_src, elem_index)) |index_val| o: {
28717 const index = try sema.usizeCast(block, elem_index_src, try index_val.toUnsignedIntSema(mod));
29015 const index = try sema.usizeCast(block, elem_index_src, try index_val.toUnsignedIntSema(pt));
2871829016 break :o index;
2871929017 } else null;
2872029018
28721 const elem_ptr_ty = try slice_ty.elemPtrType(offset, mod);
29019 const elem_ptr_ty = try slice_ty.elemPtrType(offset, pt);
2872229020
2872329021 if (maybe_undef_slice_val) |slice_val| {
2872429022 if (slice_val.isUndef(mod)) {
28725 return mod.undefRef(elem_ptr_ty);
29023 return pt.undefRef(elem_ptr_ty);
2872629024 }
28727 const slice_len = try slice_val.sliceLen(mod);
29025 const slice_len = try slice_val.sliceLen(pt);
2872829026 const slice_len_s = slice_len + @intFromBool(slice_sent);
2872929027 if (slice_len_s == 0) {
2873029028 return sema.fail(block, slice_src, "indexing into empty slice is not allowed", .{});
......@@ -28734,7 +29032,7 @@ fn elemPtrSlice(
2873429032 const sentinel_label: []const u8 = if (slice_sent) " +1 (sentinel)" else "";
2873529033 return sema.fail(block, elem_index_src, "index {d} outside slice of length {d}{s}", .{ index, slice_len, sentinel_label });
2873629034 }
28737 const elem_ptr_val = try slice_val.ptrElem(index, mod);
29035 const elem_ptr_val = try slice_val.ptrElem(index, pt);
2873829036 return Air.internedToRef(elem_ptr_val.toIntern());
2873929037 }
2874029038 }
......@@ -28747,7 +29045,7 @@ fn elemPtrSlice(
2874729045 const len_inst = len: {
2874829046 if (maybe_undef_slice_val) |slice_val|
2874929047 if (!slice_val.isUndef(mod))
28750 break :len try mod.intRef(Type.usize, try slice_val.sliceLen(mod));
29048 break :len try pt.intRef(Type.usize, try slice_val.sliceLen(pt));
2875129049 break :len try block.addTyOp(.slice_len, Type.usize, slice);
2875229050 };
2875329051 const cmp_op: Air.Inst.Tag = if (slice_sent) .cmp_lte else .cmp_lt;
......@@ -28810,11 +29108,12 @@ fn coerceExtra(
2881029108 opts: CoerceOpts,
2881129109) CoersionError!Air.Inst.Ref {
2881229110 if (dest_ty.isGenericPoison()) return inst;
28813 const zcu = sema.mod;
29111 const pt = sema.pt;
29112 const zcu = pt.zcu;
2881429113 const dest_ty_src = inst_src; // TODO better source location
28815 try dest_ty.resolveFields(zcu);
29114 try dest_ty.resolveFields(pt);
2881629115 const inst_ty = sema.typeOf(inst);
28817 try inst_ty.resolveFields(zcu);
29116 try inst_ty.resolveFields(pt);
2881829117 const target = zcu.getTarget();
2881929118 // If the types are the same, we can return the operand.
2882029119 if (dest_ty.eql(inst_ty, zcu))
......@@ -28838,12 +29137,12 @@ fn coerceExtra(
2883829137 if (maybe_inst_val) |val| {
2883929138 // undefined sets the optional bit also to undefined.
2884029139 if (val.toIntern() == .undef) {
28841 return zcu.undefRef(dest_ty);
29140 return pt.undefRef(dest_ty);
2884229141 }
2884329142
2884429143 // null to ?T
2884529144 if (val.toIntern() == .null_value) {
28846 return Air.internedToRef((try zcu.intern(.{ .opt = .{
29145 return Air.internedToRef((try pt.intern(.{ .opt = .{
2884729146 .ty = dest_ty.toIntern(),
2884829147 .val = .none,
2884929148 } })));
......@@ -29018,7 +29317,7 @@ fn coerceExtra(
2901829317 switch (dest_info.flags.size) {
2901929318 // coercion to C pointer
2902029319 .C => switch (inst_ty.zigTypeTag(zcu)) {
29021 .Null => return Air.internedToRef(try zcu.intern(.{ .ptr = .{
29320 .Null => return Air.internedToRef(try pt.intern(.{ .ptr = .{
2902229321 .ty = dest_ty.toIntern(),
2902329322 .base_addr = .int,
2902429323 .byte_offset = 0,
......@@ -29063,7 +29362,7 @@ fn coerceExtra(
2906329362 if (inst_info.flags.size == .Slice) {
2906429363 assert(dest_info.sentinel == .none);
2906529364 if (inst_info.sentinel == .none or
29066 inst_info.sentinel != (try zcu.intValue(Type.fromInterned(inst_info.child), 0)).toIntern())
29365 inst_info.sentinel != (try pt.intValue(Type.fromInterned(inst_info.child), 0)).toIntern())
2906729366 break :p;
2906829367
2906929368 const slice_ptr = try sema.analyzeSlicePtr(block, inst_src, inst, inst_ty);
......@@ -29112,7 +29411,7 @@ fn coerceExtra(
2911229411 block,
2911329412 inst_src,
2911429413 "array literal requires address-of operator (&) to coerce to slice type '{}'",
29115 .{dest_ty.fmt(zcu)},
29414 .{dest_ty.fmt(pt)},
2911629415 );
2911729416 }
2911829417
......@@ -29123,10 +29422,10 @@ fn coerceExtra(
2912329422 // empty tuple to zero-length slice
2912429423 // note that this allows coercing to a mutable slice.
2912529424 if (inst_child_ty.structFieldCount(zcu) == 0) {
29126 const align_val = try dest_ty.ptrAlignmentAdvanced(zcu, .sema);
29127 return Air.internedToRef(try zcu.intern(.{ .slice = .{
29425 const align_val = try dest_ty.ptrAlignmentAdvanced(pt, .sema);
29426 return Air.internedToRef(try pt.intern(.{ .slice = .{
2912829427 .ty = dest_ty.toIntern(),
29129 .ptr = try zcu.intern(.{ .ptr = .{
29428 .ptr = try pt.intern(.{ .ptr = .{
2913029429 .ty = dest_ty.slicePtrFieldType(zcu).toIntern(),
2913129430 .base_addr = .int,
2913229431 .byte_offset = align_val.toByteUnits().?,
......@@ -29138,7 +29437,7 @@ fn coerceExtra(
2913829437 // pointer to tuple to slice
2913929438 if (!dest_info.flags.is_const) {
2914029439 const err_msg = err_msg: {
29141 const err_msg = try sema.errMsg(inst_src, "cannot cast pointer to tuple to '{}'", .{dest_ty.fmt(zcu)});
29440 const err_msg = try sema.errMsg(inst_src, "cannot cast pointer to tuple to '{}'", .{dest_ty.fmt(pt)});
2914229441 errdefer err_msg.destroy(sema.gpa);
2914329442 try sema.errNote(dest_ty_src, err_msg, "pointers to tuples can only coerce to constant pointers", .{});
2914429443 break :err_msg err_msg;
......@@ -29194,12 +29493,12 @@ fn coerceExtra(
2919429493 // comptime-known integer to other number
2919529494 if (!(try sema.intFitsInType(val, dest_ty, null))) {
2919629495 if (!opts.report_err) return error.NotCoercible;
29197 return sema.fail(block, inst_src, "type '{}' cannot represent integer value '{}'", .{ dest_ty.fmt(zcu), val.fmtValue(zcu, sema) });
29496 return sema.fail(block, inst_src, "type '{}' cannot represent integer value '{}'", .{ dest_ty.fmt(pt), val.fmtValue(pt, sema) });
2919829497 }
2919929498 return switch (zcu.intern_pool.indexToKey(val.toIntern())) {
29200 .undef => try zcu.undefRef(dest_ty),
29499 .undef => try pt.undefRef(dest_ty),
2920129500 .int => |int| Air.internedToRef(
29202 try zcu.intern_pool.getCoercedInts(zcu.gpa, int, dest_ty.toIntern()),
29501 try zcu.intern_pool.getCoercedInts(zcu.gpa, pt.tid, int, dest_ty.toIntern()),
2920329502 ),
2920429503 else => unreachable,
2920529504 };
......@@ -29228,18 +29527,18 @@ fn coerceExtra(
2922829527 .Float, .ComptimeFloat => switch (inst_ty.zigTypeTag(zcu)) {
2922929528 .ComptimeFloat => {
2923029529 const val = try sema.resolveConstDefinedValue(block, LazySrcLoc.unneeded, inst, undefined);
29231 const result_val = try val.floatCast(dest_ty, zcu);
29530 const result_val = try val.floatCast(dest_ty, pt);
2923229531 return Air.internedToRef(result_val.toIntern());
2923329532 },
2923429533 .Float => {
2923529534 if (maybe_inst_val) |val| {
29236 const result_val = try val.floatCast(dest_ty, zcu);
29237 if (!val.eql(try result_val.floatCast(inst_ty, zcu), inst_ty, zcu)) {
29535 const result_val = try val.floatCast(dest_ty, pt);
29536 if (!val.eql(try result_val.floatCast(inst_ty, pt), inst_ty, zcu)) {
2923829537 return sema.fail(
2923929538 block,
2924029539 inst_src,
2924129540 "type '{}' cannot represent float value '{}'",
29242 .{ dest_ty.fmt(zcu), val.fmtValue(zcu, sema) },
29541 .{ dest_ty.fmt(pt), val.fmtValue(pt, sema) },
2924329542 );
2924429543 }
2924529544 return Air.internedToRef(result_val.toIntern());
......@@ -29268,7 +29567,7 @@ fn coerceExtra(
2926829567 }
2926929568 break :int;
2927029569 };
29271 const result_val = try val.floatFromIntAdvanced(sema.arena, inst_ty, dest_ty, zcu, .sema);
29570 const result_val = try val.floatFromIntAdvanced(sema.arena, inst_ty, dest_ty, pt, .sema);
2927229571 // TODO implement this compile error
2927329572 //const int_again_val = try result_val.intFromFloat(sema.arena, inst_ty);
2927429573 //if (!int_again_val.eql(val, inst_ty, zcu)) {
......@@ -29276,7 +29575,7 @@ fn coerceExtra(
2927629575 // block,
2927729576 // inst_src,
2927829577 // "type '{}' cannot represent integer value '{}'",
29279 // .{ dest_ty.fmt(zcu), val },
29578 // .{ dest_ty.fmt(pt), val },
2928029579 // );
2928129580 //}
2928229581 return Air.internedToRef(result_val.toIntern());
......@@ -29290,10 +29589,10 @@ fn coerceExtra(
2929029589 const string = zcu.intern_pool.indexToKey(val.toIntern()).enum_literal;
2929129590 const field_index = dest_ty.enumFieldIndex(string, zcu) orelse {
2929229591 return sema.fail(block, inst_src, "no field named '{}' in enum '{}'", .{
29293 string.fmt(&zcu.intern_pool), dest_ty.fmt(zcu),
29592 string.fmt(&zcu.intern_pool), dest_ty.fmt(pt),
2929429593 });
2929529594 };
29296 return Air.internedToRef((try zcu.enumValueFieldIndex(dest_ty, @intCast(field_index))).toIntern());
29595 return Air.internedToRef((try pt.enumValueFieldIndex(dest_ty, @intCast(field_index))).toIntern());
2929729596 },
2929829597 .Union => blk: {
2929929598 // union to its own tag type
......@@ -29308,12 +29607,12 @@ fn coerceExtra(
2930829607 .ErrorUnion => eu: {
2930929608 if (maybe_inst_val) |inst_val| {
2931029609 switch (inst_val.toIntern()) {
29311 .undef => return zcu.undefRef(dest_ty),
29610 .undef => return pt.undefRef(dest_ty),
2931229611 else => switch (zcu.intern_pool.indexToKey(inst_val.toIntern())) {
2931329612 .error_union => |error_union| switch (error_union.val) {
2931429613 .err_name => |err_name| {
2931529614 const error_set_ty = inst_ty.errorUnionSet(zcu);
29316 const error_set_val = Air.internedToRef((try zcu.intern(.{ .err = .{
29615 const error_set_val = Air.internedToRef((try pt.intern(.{ .err = .{
2931729616 .ty = error_set_ty.toIntern(),
2931829617 .name = err_name,
2931929618 } })));
......@@ -29370,7 +29669,7 @@ fn coerceExtra(
2937029669
2937129670 if (dest_ty.sentinel(zcu)) |dest_sent| {
2937229671 const src_sent = inst_ty.sentinel(zcu) orelse break :array_to_array;
29373 if (dest_sent.toIntern() != (try zcu.getCoerced(src_sent, dest_ty.childType(zcu))).toIntern()) {
29672 if (dest_sent.toIntern() != (try pt.getCoerced(src_sent, dest_ty.childType(zcu))).toIntern()) {
2937429673 break :array_to_array;
2937529674 }
2937629675 }
......@@ -29414,7 +29713,7 @@ fn coerceExtra(
2941429713 // undefined to anything. We do this after the big switch above so that
2941529714 // special logic has a chance to run first, such as `*[N]T` to `[]T` which
2941629715 // should initialize the length field of the slice.
29417 if (maybe_inst_val) |val| if (val.toIntern() == .undef) return zcu.undefRef(dest_ty);
29716 if (maybe_inst_val) |val| if (val.toIntern() == .undef) return pt.undefRef(dest_ty);
2941829717
2941929718 if (!opts.report_err) return error.NotCoercible;
2942029719
......@@ -29434,7 +29733,7 @@ fn coerceExtra(
2943429733 }
2943529734
2943629735 const msg = msg: {
29437 const msg = try sema.errMsg(inst_src, "expected type '{}', found '{}'", .{ dest_ty.fmt(zcu), inst_ty.fmt(zcu) });
29736 const msg = try sema.errMsg(inst_src, "expected type '{}', found '{}'", .{ dest_ty.fmt(pt), inst_ty.fmt(pt) });
2943829737 errdefer msg.destroy(sema.gpa);
2943929738
2944029739 // E!T to T
......@@ -29486,7 +29785,7 @@ fn coerceInMemory(
2948629785 val: Value,
2948729786 dst_ty: Type,
2948829787) CompileError!Air.Inst.Ref {
29489 return Air.internedToRef((try sema.mod.getCoerced(val, dst_ty)).toIntern());
29788 return Air.internedToRef((try sema.pt.getCoerced(val, dst_ty)).toIntern());
2949029789}
2949129790
2949229791const InMemoryCoercionResult = union(enum) {
......@@ -29607,7 +29906,7 @@ const InMemoryCoercionResult = union(enum) {
2960729906 }
2960829907
2960929908 fn report(res: *const InMemoryCoercionResult, sema: *Sema, src: LazySrcLoc, msg: *Module.ErrorMsg) !void {
29610 const mod = sema.mod;
29909 const pt = sema.pt;
2961129910 var cur = res;
2961229911 while (true) switch (cur.*) {
2961329912 .ok => unreachable,
......@@ -29624,7 +29923,7 @@ const InMemoryCoercionResult = union(enum) {
2962429923 },
2962529924 .error_union_payload => |pair| {
2962629925 try sema.errNote(src, msg, "error union payload '{}' cannot cast into error union payload '{}'", .{
29627 pair.actual.fmt(mod), pair.wanted.fmt(mod),
29926 pair.actual.fmt(pt), pair.wanted.fmt(pt),
2962829927 });
2962929928 cur = pair.child;
2963029929 },
......@@ -29637,18 +29936,18 @@ const InMemoryCoercionResult = union(enum) {
2963729936 .array_sentinel => |sentinel| {
2963829937 if (sentinel.actual.toIntern() != .unreachable_value) {
2963929938 try sema.errNote(src, msg, "array sentinel '{}' cannot cast into array sentinel '{}'", .{
29640 sentinel.actual.fmtValue(mod, sema), sentinel.wanted.fmtValue(mod, sema),
29939 sentinel.actual.fmtValue(pt, sema), sentinel.wanted.fmtValue(pt, sema),
2964129940 });
2964229941 } else {
2964329942 try sema.errNote(src, msg, "destination array requires '{}' sentinel", .{
29644 sentinel.wanted.fmtValue(mod, sema),
29943 sentinel.wanted.fmtValue(pt, sema),
2964529944 });
2964629945 }
2964729946 break;
2964829947 },
2964929948 .array_elem => |pair| {
2965029949 try sema.errNote(src, msg, "array element type '{}' cannot cast into array element type '{}'", .{
29651 pair.actual.fmt(mod), pair.wanted.fmt(mod),
29950 pair.actual.fmt(pt), pair.wanted.fmt(pt),
2965229951 });
2965329952 cur = pair.child;
2965429953 },
......@@ -29660,19 +29959,19 @@ const InMemoryCoercionResult = union(enum) {
2966029959 },
2966129960 .vector_elem => |pair| {
2966229961 try sema.errNote(src, msg, "vector element type '{}' cannot cast into vector element type '{}'", .{
29663 pair.actual.fmt(mod), pair.wanted.fmt(mod),
29962 pair.actual.fmt(pt), pair.wanted.fmt(pt),
2966429963 });
2966529964 cur = pair.child;
2966629965 },
2966729966 .optional_shape => |pair| {
2966829967 try sema.errNote(src, msg, "optional type child '{}' cannot cast into optional type child '{}'", .{
29669 pair.actual.optionalChild(mod).fmt(mod), pair.wanted.optionalChild(mod).fmt(mod),
29968 pair.actual.optionalChild(pt.zcu).fmt(pt), pair.wanted.optionalChild(pt.zcu).fmt(pt),
2967029969 });
2967129970 break;
2967229971 },
2967329972 .optional_child => |pair| {
2967429973 try sema.errNote(src, msg, "optional type child '{}' cannot cast into optional type child '{}'", .{
29675 pair.actual.fmt(mod), pair.wanted.fmt(mod),
29974 pair.actual.fmt(pt), pair.wanted.fmt(pt),
2967629975 });
2967729976 cur = pair.child;
2967829977 },
......@@ -29682,7 +29981,7 @@ const InMemoryCoercionResult = union(enum) {
2968229981 },
2968329982 .missing_error => |missing_errors| {
2968429983 for (missing_errors) |err| {
29685 try sema.errNote(src, msg, "'error.{}' not a member of destination error set", .{err.fmt(&mod.intern_pool)});
29984 try sema.errNote(src, msg, "'error.{}' not a member of destination error set", .{err.fmt(&pt.zcu.intern_pool)});
2968629985 }
2968729986 break;
2968829987 },
......@@ -29736,7 +30035,7 @@ const InMemoryCoercionResult = union(enum) {
2973630035 },
2973730036 .fn_param => |param| {
2973830037 try sema.errNote(src, msg, "parameter {d} '{}' cannot cast into '{}'", .{
29739 param.index, param.actual.fmt(mod), param.wanted.fmt(mod),
30038 param.index, param.actual.fmt(pt), param.wanted.fmt(pt),
2974030039 });
2974130040 cur = param.child;
2974230041 },
......@@ -29746,13 +30045,13 @@ const InMemoryCoercionResult = union(enum) {
2974630045 },
2974730046 .fn_return_type => |pair| {
2974830047 try sema.errNote(src, msg, "return type '{}' cannot cast into return type '{}'", .{
29749 pair.actual.fmt(mod), pair.wanted.fmt(mod),
30048 pair.actual.fmt(pt), pair.wanted.fmt(pt),
2975030049 });
2975130050 cur = pair.child;
2975230051 },
2975330052 .ptr_child => |pair| {
2975430053 try sema.errNote(src, msg, "pointer type child '{}' cannot cast into pointer type child '{}'", .{
29755 pair.actual.fmt(mod), pair.wanted.fmt(mod),
30054 pair.actual.fmt(pt), pair.wanted.fmt(pt),
2975630055 });
2975730056 cur = pair.child;
2975830057 },
......@@ -29763,11 +30062,11 @@ const InMemoryCoercionResult = union(enum) {
2976330062 .ptr_sentinel => |sentinel| {
2976430063 if (sentinel.actual.toIntern() != .unreachable_value) {
2976530064 try sema.errNote(src, msg, "pointer sentinel '{}' cannot cast into pointer sentinel '{}'", .{
29766 sentinel.actual.fmtValue(mod, sema), sentinel.wanted.fmtValue(mod, sema),
30065 sentinel.actual.fmtValue(pt, sema), sentinel.wanted.fmtValue(pt, sema),
2976730066 });
2976830067 } else {
2976930068 try sema.errNote(src, msg, "destination pointer requires '{}' sentinel", .{
29770 sentinel.wanted.fmtValue(mod, sema),
30069 sentinel.wanted.fmtValue(pt, sema),
2977130070 });
2977230071 }
2977330072 break;
......@@ -29787,15 +30086,15 @@ const InMemoryCoercionResult = union(enum) {
2978730086 break;
2978830087 },
2978930088 .ptr_allowzero => |pair| {
29790 const wanted_allow_zero = pair.wanted.ptrAllowsZero(mod);
29791 const actual_allow_zero = pair.actual.ptrAllowsZero(mod);
30089 const wanted_allow_zero = pair.wanted.ptrAllowsZero(pt.zcu);
30090 const actual_allow_zero = pair.actual.ptrAllowsZero(pt.zcu);
2979230091 if (actual_allow_zero and !wanted_allow_zero) {
2979330092 try sema.errNote(src, msg, "'{}' could have null values which are illegal in type '{}'", .{
29794 pair.actual.fmt(mod), pair.wanted.fmt(mod),
30093 pair.actual.fmt(pt), pair.wanted.fmt(pt),
2979530094 });
2979630095 } else {
2979730096 try sema.errNote(src, msg, "mutable '{}' allows illegal null values stored to type '{}'", .{
29798 pair.actual.fmt(mod), pair.wanted.fmt(mod),
30097 pair.actual.fmt(pt), pair.wanted.fmt(pt),
2979930098 });
2980030099 }
2980130100 break;
......@@ -29821,13 +30120,13 @@ const InMemoryCoercionResult = union(enum) {
2982130120 },
2982230121 .double_ptr_to_anyopaque => |pair| {
2982330122 try sema.errNote(src, msg, "cannot implicitly cast double pointer '{}' to anyopaque pointer '{}'", .{
29824 pair.actual.fmt(mod), pair.wanted.fmt(mod),
30123 pair.actual.fmt(pt), pair.wanted.fmt(pt),
2982530124 });
2982630125 break;
2982730126 },
2982830127 .slice_to_anyopaque => |pair| {
2982930128 try sema.errNote(src, msg, "cannot implicitly cast slice '{}' to anyopaque pointer '{}'", .{
29830 pair.actual.fmt(mod), pair.wanted.fmt(mod),
30129 pair.actual.fmt(pt), pair.wanted.fmt(pt),
2983130130 });
2983230131 try sema.errNote(src, msg, "consider using '.ptr'", .{});
2983330132 break;
......@@ -29864,7 +30163,8 @@ pub fn coerceInMemoryAllowed(
2986430163 dest_src: LazySrcLoc,
2986530164 src_src: LazySrcLoc,
2986630165) CompileError!InMemoryCoercionResult {
29867 const mod = sema.mod;
30166 const pt = sema.pt;
30167 const mod = pt.zcu;
2986830168
2986930169 if (dest_ty.eql(src_ty, mod))
2987030170 return .ok;
......@@ -29968,7 +30268,7 @@ pub fn coerceInMemoryAllowed(
2996830268 (src_info.sentinel != null and
2996930269 dest_info.sentinel != null and
2997030270 dest_info.sentinel.?.eql(
29971 try mod.getCoerced(src_info.sentinel.?, dest_info.elem_type),
30271 try pt.getCoerced(src_info.sentinel.?, dest_info.elem_type),
2997230272 dest_info.elem_type,
2997330273 mod,
2997430274 ));
......@@ -30045,8 +30345,8 @@ pub fn coerceInMemoryAllowed(
3004530345 // The memory layout of @Vector(N, iM) is the same as the integer type i(N*M),
3004630346 // that is to say, the padding bits are not in the same place as the array [N]iM.
3004730347 // If there's no padding, the bitcast is possible.
30048 const elem_bit_size = dest_elem_ty.bitSize(mod);
30049 const elem_abi_byte_size = dest_elem_ty.abiSize(mod);
30348 const elem_bit_size = dest_elem_ty.bitSize(pt);
30349 const elem_abi_byte_size = dest_elem_ty.abiSize(pt);
3005030350 if (elem_abi_byte_size * 8 == elem_bit_size)
3005130351 return .ok;
3005230352 }
......@@ -30081,7 +30381,7 @@ pub fn coerceInMemoryAllowed(
3008130381 const field_count = dest_ty.structFieldCount(mod);
3008230382 for (0..field_count) |field_idx| {
3008330383 if (dest_ty.structFieldIsComptime(field_idx, mod) != src_ty.structFieldIsComptime(field_idx, mod)) break :tuple;
30084 if (dest_ty.structFieldAlign(field_idx, mod) != src_ty.structFieldAlign(field_idx, mod)) break :tuple;
30384 if (dest_ty.structFieldAlign(field_idx, pt) != src_ty.structFieldAlign(field_idx, pt)) break :tuple;
3008530385 const dest_field_ty = dest_ty.structFieldType(field_idx, mod);
3008630386 const src_field_ty = src_ty.structFieldType(field_idx, mod);
3008730387 const field = try sema.coerceInMemoryAllowed(block, dest_field_ty, src_field_ty, dest_is_mut, target, dest_src, src_src);
......@@ -30104,7 +30404,8 @@ fn coerceInMemoryAllowedErrorSets(
3010430404 dest_src: LazySrcLoc,
3010530405 src_src: LazySrcLoc,
3010630406) !InMemoryCoercionResult {
30107 const mod = sema.mod;
30407 const pt = sema.pt;
30408 const mod = pt.zcu;
3010830409 const gpa = sema.gpa;
3010930410 const ip = &mod.intern_pool;
3011030411
......@@ -30202,7 +30503,8 @@ fn coerceInMemoryAllowedFns(
3020230503 dest_src: LazySrcLoc,
3020330504 src_src: LazySrcLoc,
3020430505) !InMemoryCoercionResult {
30205 const mod = sema.mod;
30506 const pt = sema.pt;
30507 const mod = pt.zcu;
3020630508 const ip = &mod.intern_pool;
3020730509
3020830510 const dest_info = mod.typeToFunc(dest_ty).?;
......@@ -30303,7 +30605,8 @@ fn coerceInMemoryAllowedPtrs(
3030330605 dest_src: LazySrcLoc,
3030430606 src_src: LazySrcLoc,
3030530607) !InMemoryCoercionResult {
30306 const zcu = sema.mod;
30608 const pt = sema.pt;
30609 const zcu = pt.zcu;
3030730610 const dest_info = dest_ptr_ty.ptrInfo(zcu);
3030830611 const src_info = src_ptr_ty.ptrInfo(zcu);
3030930612
......@@ -30381,7 +30684,7 @@ fn coerceInMemoryAllowedPtrs(
3038130684
3038230685 const ok_sent = dest_info.sentinel == .none or src_info.flags.size == .C or
3038330686 (src_info.sentinel != .none and
30384 dest_info.sentinel == try zcu.intern_pool.getCoerced(sema.gpa, src_info.sentinel, dest_info.child));
30687 dest_info.sentinel == try zcu.intern_pool.getCoerced(sema.gpa, pt.tid, src_info.sentinel, dest_info.child));
3038530688 if (!ok_sent) {
3038630689 return InMemoryCoercionResult{ .ptr_sentinel = .{
3038730690 .actual = switch (src_info.sentinel) {
......@@ -30432,7 +30735,8 @@ fn coerceVarArgParam(
3043230735) !Air.Inst.Ref {
3043330736 if (block.is_typeof) return inst;
3043430737
30435 const mod = sema.mod;
30738 const pt = sema.pt;
30739 const mod = pt.zcu;
3043630740 const uncasted_ty = sema.typeOf(inst);
3043730741 const coerced = switch (uncasted_ty.zigTypeTag(mod)) {
3043830742 // TODO consider casting to c_int/f64 if they fit
......@@ -30449,9 +30753,9 @@ fn coerceVarArgParam(
3044930753 },
3045030754 .Array => return sema.fail(block, inst_src, "arrays must be passed by reference to variadic function", .{}),
3045130755 .Float => float: {
30452 const target = sema.mod.getTarget();
30756 const target = mod.getTarget();
3045330757 const double_bits = target.c_type_bit_size(.double);
30454 const inst_bits = uncasted_ty.floatBits(sema.mod.getTarget());
30758 const inst_bits = uncasted_ty.floatBits(target);
3045530759 if (inst_bits >= double_bits) break :float inst;
3045630760 switch (double_bits) {
3045730761 32 => break :float try sema.coerce(block, Type.f32, inst, inst_src),
......@@ -30461,7 +30765,7 @@ fn coerceVarArgParam(
3046130765 },
3046230766 else => if (uncasted_ty.isAbiInt(mod)) int: {
3046330767 if (!try sema.validateExternType(uncasted_ty, .param_ty)) break :int inst;
30464 const target = sema.mod.getTarget();
30768 const target = mod.getTarget();
3046530769 const uncasted_info = uncasted_ty.intInfo(mod);
3046630770 if (uncasted_info.bits <= target.c_type_bit_size(switch (uncasted_info.signedness) {
3046730771 .signed => .int,
......@@ -30491,7 +30795,7 @@ fn coerceVarArgParam(
3049130795 const coerced_ty = sema.typeOf(coerced);
3049230796 if (!try sema.validateExternType(coerced_ty, .param_ty)) {
3049330797 const msg = msg: {
30494 const msg = try sema.errMsg(inst_src, "cannot pass '{}' to variadic function", .{coerced_ty.fmt(sema.mod)});
30798 const msg = try sema.errMsg(inst_src, "cannot pass '{}' to variadic function", .{coerced_ty.fmt(pt)});
3049530799 errdefer msg.destroy(sema.gpa);
3049630800
3049730801 try sema.explainWhyTypeIsNotExtern(msg, inst_src, coerced_ty, .param_ty);
......@@ -30526,7 +30830,8 @@ fn storePtr2(
3052630830 operand_src: LazySrcLoc,
3052730831 air_tag: Air.Inst.Tag,
3052830832) CompileError!void {
30529 const mod = sema.mod;
30833 const pt = sema.pt;
30834 const mod = pt.zcu;
3053030835 const ptr_ty = sema.typeOf(ptr);
3053130836 if (ptr_ty.isConstPtr(mod))
3053230837 return sema.fail(block, ptr_src, "cannot assign to constant", .{});
......@@ -30548,7 +30853,7 @@ fn storePtr2(
3054830853 while (i < field_count) : (i += 1) {
3054930854 const elem_src = operand_src; // TODO better source location
3055030855 const elem = try sema.tupleField(block, operand_src, uncasted_operand, elem_src, i);
30551 const elem_index = try mod.intRef(Type.usize, i);
30856 const elem_index = try pt.intRef(Type.usize, i);
3055230857 const elem_ptr = try sema.elemPtr(block, ptr_src, ptr, elem_index, elem_src, false, true);
3055330858 try sema.storePtr2(block, src, elem_ptr, elem_src, elem, elem_src, .store);
3055430859 }
......@@ -30620,7 +30925,7 @@ fn storePtr2(
3062030925 return;
3062130926 }
3062230927 return sema.fail(block, ptr_src, "unable to determine vector element index of type '{}'", .{
30623 ptr_ty.fmt(sema.mod),
30928 ptr_ty.fmt(pt),
3062430929 });
3062530930 }
3062630931
......@@ -30734,7 +31039,8 @@ fn markMaybeComptimeAllocRuntime(sema: *Sema, block: *Block, alloc_inst: Air.Ins
3073431039/// pointer. Only if the final element type matches the vector element type, and the
3073531040/// lengths match.
3073631041fn obtainBitCastedVectorPtr(sema: *Sema, ptr: Air.Inst.Ref) ?Air.Inst.Ref {
30737 const mod = sema.mod;
31042 const pt = sema.pt;
31043 const mod = pt.zcu;
3073831044 const array_ty = sema.typeOf(ptr).childType(mod);
3073931045 if (array_ty.zigTypeTag(mod) != .Array) return null;
3074031046 var ptr_ref = ptr;
......@@ -30751,7 +31057,7 @@ fn obtainBitCastedVectorPtr(sema: *Sema, ptr: Air.Inst.Ref) ?Air.Inst.Ref {
3075131057
3075231058 // We have a pointer-to-array and a pointer-to-vector. If the elements and
3075331059 // lengths match, return the result.
30754 if (array_ty.childType(mod).eql(vector_ty.childType(mod), sema.mod) and
31060 if (array_ty.childType(mod).eql(vector_ty.childType(mod), mod) and
3075531061 array_ty.arrayLen(mod) == vector_ty.vectorLen(mod))
3075631062 {
3075731063 return ptr_ref;
......@@ -30770,17 +31076,18 @@ fn storePtrVal(
3077031076 operand_val: Value,
3077131077 operand_ty: Type,
3077231078) !void {
30773 const zcu = sema.mod;
31079 const pt = sema.pt;
31080 const zcu = pt.zcu;
3077431081 const ip = &zcu.intern_pool;
3077531082 // TODO: audit use sites to eliminate this coercion
30776 const coerced_operand_val = try zcu.getCoerced(operand_val, operand_ty);
31083 const coerced_operand_val = try pt.getCoerced(operand_val, operand_ty);
3077731084 // TODO: audit use sites to eliminate this coercion
30778 const ptr_ty = try zcu.ptrType(info: {
31085 const ptr_ty = try pt.ptrType(info: {
3077931086 var info = ptr_val.typeOf(zcu).ptrInfo(zcu);
3078031087 info.child = operand_ty.toIntern();
3078131088 break :info info;
3078231089 });
30783 const coerced_ptr_val = try zcu.getCoerced(ptr_val, ptr_ty);
31090 const coerced_ptr_val = try pt.getCoerced(ptr_val, ptr_ty);
3078431091
3078531092 switch (try sema.storeComptimePtr(block, src, coerced_ptr_val, coerced_operand_val)) {
3078631093 .success => {},
......@@ -30800,13 +31107,13 @@ fn storePtrVal(
3080031107 block,
3080131108 src,
3080231109 "comptime dereference requires '{}' to have a well-defined layout",
30803 .{ty.fmt(zcu)},
31110 .{ty.fmt(pt)},
3080431111 ),
3080531112 .out_of_bounds => |ty| return sema.fail(
3080631113 block,
3080731114 src,
3080831115 "dereference of '{}' exceeds bounds of containing decl of type '{}'",
30809 .{ ptr_ty.fmt(zcu), ty.fmt(zcu) },
31116 .{ ptr_ty.fmt(pt), ty.fmt(pt) },
3081031117 ),
3081131118 .exceeds_host_size => return sema.fail(block, src, "bit-pointer target exceeds host size", .{}),
3081231119 }
......@@ -30820,31 +31127,32 @@ fn bitCast(
3082031127 inst_src: LazySrcLoc,
3082131128 operand_src: ?LazySrcLoc,
3082231129) CompileError!Air.Inst.Ref {
30823 const zcu = sema.mod;
30824 try dest_ty.resolveLayout(zcu);
31130 const pt = sema.pt;
31131 const zcu = pt.zcu;
31132 try dest_ty.resolveLayout(pt);
3082531133
3082631134 const old_ty = sema.typeOf(inst);
30827 try old_ty.resolveLayout(zcu);
31135 try old_ty.resolveLayout(pt);
3082831136
30829 const dest_bits = dest_ty.bitSize(zcu);
30830 const old_bits = old_ty.bitSize(zcu);
31137 const dest_bits = dest_ty.bitSize(pt);
31138 const old_bits = old_ty.bitSize(pt);
3083131139
3083231140 if (old_bits != dest_bits) {
3083331141 return sema.fail(block, inst_src, "@bitCast size mismatch: destination type '{}' has {d} bits but source type '{}' has {d} bits", .{
30834 dest_ty.fmt(zcu),
31142 dest_ty.fmt(pt),
3083531143 dest_bits,
30836 old_ty.fmt(zcu),
31144 old_ty.fmt(pt),
3083731145 old_bits,
3083831146 });
3083931147 }
3084031148
3084131149 if (try sema.resolveValue(inst)) |val| {
3084231150 if (val.isUndef(zcu))
30843 return zcu.undefRef(dest_ty);
31151 return pt.undefRef(dest_ty);
3084431152 if (old_ty.zigTypeTag(zcu) == .ErrorSet and dest_ty.zigTypeTag(zcu) == .ErrorSet) {
3084531153 // Special case: we sometimes call `bitCast` on error set values, but they
3084631154 // don't have a well-defined layout, so we can't use `bitCastVal` on them.
30847 return Air.internedToRef((try zcu.getCoerced(val, dest_ty)).toIntern());
31155 return Air.internedToRef((try pt.getCoerced(val, dest_ty)).toIntern());
3084831156 }
3084931157 if (try sema.bitCastVal(val, dest_ty, 0, 0, 0)) |result_val| {
3085031158 return Air.internedToRef(result_val.toIntern());
......@@ -30862,16 +31170,17 @@ fn coerceArrayPtrToSlice(
3086231170 inst: Air.Inst.Ref,
3086331171 inst_src: LazySrcLoc,
3086431172) CompileError!Air.Inst.Ref {
30865 const mod = sema.mod;
31173 const pt = sema.pt;
31174 const mod = pt.zcu;
3086631175 if (try sema.resolveValue(inst)) |val| {
3086731176 const ptr_array_ty = sema.typeOf(inst);
3086831177 const array_ty = ptr_array_ty.childType(mod);
3086931178 const slice_ptr_ty = dest_ty.slicePtrFieldType(mod);
30870 const slice_ptr = try mod.getCoerced(val, slice_ptr_ty);
30871 const slice_val = try mod.intern(.{ .slice = .{
31179 const slice_ptr = try pt.getCoerced(val, slice_ptr_ty);
31180 const slice_val = try pt.intern(.{ .slice = .{
3087231181 .ty = dest_ty.toIntern(),
3087331182 .ptr = slice_ptr.toIntern(),
30874 .len = (try mod.intValue(Type.usize, array_ty.arrayLen(mod))).toIntern(),
31183 .len = (try pt.intValue(Type.usize, array_ty.arrayLen(mod))).toIntern(),
3087531184 } });
3087631185 return Air.internedToRef(slice_val);
3087731186 }
......@@ -30880,7 +31189,8 @@ fn coerceArrayPtrToSlice(
3088031189}
3088131190
3088231191fn checkPtrAttributes(sema: *Sema, dest_ty: Type, inst_ty: Type, in_memory_result: *InMemoryCoercionResult) bool {
30883 const mod = sema.mod;
31192 const pt = sema.pt;
31193 const mod = pt.zcu;
3088431194 const dest_info = dest_ty.ptrInfo(mod);
3088531195 const inst_info = inst_ty.ptrInfo(mod);
3088631196 const len0 = (Type.fromInterned(inst_info.child).zigTypeTag(mod) == .Array and (Type.fromInterned(inst_info.child).arrayLenIncludingSentinel(mod) == 0 or
......@@ -30913,12 +31223,12 @@ fn checkPtrAttributes(sema: *Sema, dest_ty: Type, inst_ty: Type, in_memory_resul
3091331223 const inst_align = if (inst_info.flags.alignment != .none)
3091431224 inst_info.flags.alignment
3091531225 else
30916 Type.fromInterned(inst_info.child).abiAlignment(mod);
31226 Type.fromInterned(inst_info.child).abiAlignment(pt);
3091731227
3091831228 const dest_align = if (dest_info.flags.alignment != .none)
3091931229 dest_info.flags.alignment
3092031230 else
30921 Type.fromInterned(dest_info.child).abiAlignment(mod);
31231 Type.fromInterned(dest_info.child).abiAlignment(pt);
3092231232
3092331233 if (dest_align.compare(.gt, inst_align)) {
3092431234 in_memory_result.* = .{ .ptr_alignment = .{
......@@ -30937,15 +31247,16 @@ fn coerceCompatiblePtrs(
3093731247 inst: Air.Inst.Ref,
3093831248 inst_src: LazySrcLoc,
3093931249) !Air.Inst.Ref {
30940 const mod = sema.mod;
31250 const pt = sema.pt;
31251 const mod = pt.zcu;
3094131252 const inst_ty = sema.typeOf(inst);
3094231253 if (try sema.resolveValue(inst)) |val| {
3094331254 if (!val.isUndef(mod) and val.isNull(mod) and !dest_ty.isAllowzeroPtr(mod)) {
30944 return sema.fail(block, inst_src, "null pointer casted to type '{}'", .{dest_ty.fmt(sema.mod)});
31255 return sema.fail(block, inst_src, "null pointer casted to type '{}'", .{dest_ty.fmt(pt)});
3094531256 }
3094631257 // The comptime Value representation is compatible with both types.
3094731258 return Air.internedToRef(
30948 (try mod.getCoerced(val, dest_ty)).toIntern(),
31259 (try pt.getCoerced(val, dest_ty)).toIntern(),
3094931260 );
3095031261 }
3095131262 try sema.requireRuntimeBlock(block, inst_src, null);
......@@ -30979,14 +31290,15 @@ fn coerceEnumToUnion(
3097931290 inst: Air.Inst.Ref,
3098031291 inst_src: LazySrcLoc,
3098131292) !Air.Inst.Ref {
30982 const mod = sema.mod;
31293 const pt = sema.pt;
31294 const mod = pt.zcu;
3098331295 const ip = &mod.intern_pool;
3098431296 const inst_ty = sema.typeOf(inst);
3098531297
3098631298 const tag_ty = union_ty.unionTagType(mod) orelse {
3098731299 const msg = msg: {
3098831300 const msg = try sema.errMsg(inst_src, "expected type '{}', found '{}'", .{
30989 union_ty.fmt(sema.mod), inst_ty.fmt(sema.mod),
31301 union_ty.fmt(pt), inst_ty.fmt(pt),
3099031302 });
3099131303 errdefer msg.destroy(sema.gpa);
3099231304 try sema.errNote(union_ty_src, msg, "cannot coerce enum to untagged union", .{});
......@@ -30998,15 +31310,15 @@ fn coerceEnumToUnion(
3099831310
3099931311 const enum_tag = try sema.coerce(block, tag_ty, inst, inst_src);
3100031312 if (try sema.resolveDefinedValue(block, inst_src, enum_tag)) |val| {
31001 const field_index = union_ty.unionTagFieldIndex(val, sema.mod) orelse {
31313 const field_index = union_ty.unionTagFieldIndex(val, pt.zcu) orelse {
3100231314 return sema.fail(block, inst_src, "union '{}' has no tag with value '{}'", .{
31003 union_ty.fmt(sema.mod), val.fmtValue(sema.mod, sema),
31315 union_ty.fmt(pt), val.fmtValue(pt, sema),
3100431316 });
3100531317 };
3100631318
3100731319 const union_obj = mod.typeToUnion(union_ty).?;
3100831320 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
31009 try field_ty.resolveFields(mod);
31321 try field_ty.resolveFields(pt);
3101031322 if (field_ty.zigTypeTag(mod) == .NoReturn) {
3101131323 const msg = msg: {
3101231324 const msg = try sema.errMsg(inst_src, "cannot initialize 'noreturn' field of union", .{});
......@@ -31025,8 +31337,8 @@ fn coerceEnumToUnion(
3102531337 const msg = msg: {
3102631338 const field_name = union_obj.loadTagType(ip).names.get(ip)[field_index];
3102731339 const msg = try sema.errMsg(inst_src, "coercion from enum '{}' to union '{}' must initialize '{}' field '{}'", .{
31028 inst_ty.fmt(sema.mod), union_ty.fmt(sema.mod),
31029 field_ty.fmt(sema.mod), field_name.fmt(ip),
31340 inst_ty.fmt(pt), union_ty.fmt(pt),
31341 field_ty.fmt(pt), field_name.fmt(ip),
3103031342 });
3103131343 errdefer msg.destroy(sema.gpa);
3103231344
......@@ -31039,7 +31351,7 @@ fn coerceEnumToUnion(
3103931351 return sema.failWithOwnedErrorMsg(block, msg);
3104031352 };
3104131353
31042 return Air.internedToRef((try mod.unionValue(union_ty, val, opv)).toIntern());
31354 return Air.internedToRef((try pt.unionValue(union_ty, val, opv)).toIntern());
3104331355 }
3104431356
3104531357 try sema.requireRuntimeBlock(block, inst_src, null);
......@@ -31047,7 +31359,7 @@ fn coerceEnumToUnion(
3104731359 if (tag_ty.isNonexhaustiveEnum(mod)) {
3104831360 const msg = msg: {
3104931361 const msg = try sema.errMsg(inst_src, "runtime coercion to union '{}' from non-exhaustive enum", .{
31050 union_ty.fmt(sema.mod),
31362 union_ty.fmt(pt),
3105131363 });
3105231364 errdefer msg.destroy(sema.gpa);
3105331365 try sema.addDeclaredHereNote(msg, tag_ty);
......@@ -31066,7 +31378,7 @@ fn coerceEnumToUnion(
3106631378 const err_msg = msg orelse try sema.errMsg(
3106731379 inst_src,
3106831380 "runtime coercion from enum '{}' to union '{}' which has a 'noreturn' field",
31069 .{ tag_ty.fmt(sema.mod), union_ty.fmt(sema.mod) },
31381 .{ tag_ty.fmt(pt), union_ty.fmt(pt) },
3107031382 );
3107131383 msg = err_msg;
3107231384
......@@ -31081,7 +31393,7 @@ fn coerceEnumToUnion(
3108131393 }
3108231394
3108331395 // If the union has all fields 0 bits, the union value is just the enum value.
31084 if (union_ty.unionHasAllZeroBitFieldTypes(mod)) {
31396 if (union_ty.unionHasAllZeroBitFieldTypes(pt)) {
3108531397 return block.addBitCast(union_ty, enum_tag);
3108631398 }
3108731399
......@@ -31089,7 +31401,7 @@ fn coerceEnumToUnion(
3108931401 const msg = try sema.errMsg(
3109031402 inst_src,
3109131403 "runtime coercion from enum '{}' to union '{}' which has non-void fields",
31092 .{ tag_ty.fmt(sema.mod), union_ty.fmt(sema.mod) },
31404 .{ tag_ty.fmt(pt), union_ty.fmt(pt) },
3109331405 );
3109431406 errdefer msg.destroy(sema.gpa);
3109531407
......@@ -31099,7 +31411,7 @@ fn coerceEnumToUnion(
3109931411 if (!(try sema.typeHasRuntimeBits(field_ty))) continue;
3110031412 try sema.addFieldErrNote(union_ty, field_index, msg, "field '{}' has type '{}'", .{
3110131413 field_name.fmt(ip),
31102 field_ty.fmt(sema.mod),
31414 field_ty.fmt(pt),
3110331415 });
3110431416 }
3110531417 try sema.addDeclaredHereNote(msg, union_ty);
......@@ -31116,7 +31428,8 @@ fn coerceAnonStructToUnion(
3111631428 inst: Air.Inst.Ref,
3111731429 inst_src: LazySrcLoc,
3111831430) !Air.Inst.Ref {
31119 const mod = sema.mod;
31431 const pt = sema.pt;
31432 const mod = pt.zcu;
3112031433 const ip = &mod.intern_pool;
3112131434 const inst_ty = sema.typeOf(inst);
3112231435 const field_info: union(enum) {
......@@ -31174,7 +31487,8 @@ fn coerceAnonStructToUnionPtrs(
3117431487 ptr_anon_struct: Air.Inst.Ref,
3117531488 anon_struct_src: LazySrcLoc,
3117631489) !Air.Inst.Ref {
31177 const mod = sema.mod;
31490 const pt = sema.pt;
31491 const mod = pt.zcu;
3117831492 const union_ty = ptr_union_ty.childType(mod);
3117931493 const anon_struct = try sema.analyzeLoad(block, anon_struct_src, ptr_anon_struct, anon_struct_src);
3118031494 const union_inst = try sema.coerceAnonStructToUnion(block, union_ty, union_ty_src, anon_struct, anon_struct_src);
......@@ -31189,7 +31503,8 @@ fn coerceAnonStructToStructPtrs(
3118931503 ptr_anon_struct: Air.Inst.Ref,
3119031504 anon_struct_src: LazySrcLoc,
3119131505) !Air.Inst.Ref {
31192 const mod = sema.mod;
31506 const pt = sema.pt;
31507 const mod = pt.zcu;
3119331508 const struct_ty = ptr_struct_ty.childType(mod);
3119431509 const anon_struct = try sema.analyzeLoad(block, anon_struct_src, ptr_anon_struct, anon_struct_src);
3119531510 const struct_inst = try sema.coerceTupleToStruct(block, struct_ty, anon_struct, anon_struct_src);
......@@ -31205,7 +31520,8 @@ fn coerceArrayLike(
3120531520 inst: Air.Inst.Ref,
3120631521 inst_src: LazySrcLoc,
3120731522) !Air.Inst.Ref {
31208 const mod = sema.mod;
31523 const pt = sema.pt;
31524 const mod = pt.zcu;
3120931525 const inst_ty = sema.typeOf(inst);
3121031526 const target = mod.getTarget();
3121131527
......@@ -31226,7 +31542,7 @@ fn coerceArrayLike(
3122631542 if (dest_len != inst_len) {
3122731543 const msg = msg: {
3122831544 const msg = try sema.errMsg(inst_src, "expected type '{}', found '{}'", .{
31229 dest_ty.fmt(mod), inst_ty.fmt(mod),
31545 dest_ty.fmt(pt), inst_ty.fmt(pt),
3123031546 });
3123131547 errdefer msg.destroy(sema.gpa);
3123231548 try sema.errNote(dest_ty_src, msg, "destination has length {d}", .{dest_len});
......@@ -31270,7 +31586,7 @@ fn coerceArrayLike(
3127031586 var runtime_src: ?LazySrcLoc = null;
3127131587
3127231588 for (element_vals, element_refs, 0..) |*val, *ref, i| {
31273 const index_ref = Air.internedToRef((try mod.intValue(Type.usize, i)).toIntern());
31589 const index_ref = Air.internedToRef((try pt.intValue(Type.usize, i)).toIntern());
3127431590 const src = inst_src; // TODO better source location
3127531591 const elem_src = inst_src; // TODO better source location
3127631592 const elem_ref = try sema.elemValArray(block, src, inst_src, inst, elem_src, index_ref, true);
......@@ -31290,7 +31606,7 @@ fn coerceArrayLike(
3129031606 return block.addAggregateInit(dest_ty, element_refs);
3129131607 }
3129231608
31293 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
31609 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
3129431610 .ty = dest_ty.toIntern(),
3129531611 .storage = .{ .elems = element_vals },
3129631612 } })));
......@@ -31305,7 +31621,8 @@ fn coerceTupleToArray(
3130531621 inst: Air.Inst.Ref,
3130631622 inst_src: LazySrcLoc,
3130731623) !Air.Inst.Ref {
31308 const mod = sema.mod;
31624 const pt = sema.pt;
31625 const mod = pt.zcu;
3130931626 const inst_ty = sema.typeOf(inst);
3131031627 const inst_len = inst_ty.arrayLen(mod);
3131131628 const dest_len = dest_ty.arrayLen(mod);
......@@ -31313,7 +31630,7 @@ fn coerceTupleToArray(
3131331630 if (dest_len != inst_len) {
3131431631 const msg = msg: {
3131531632 const msg = try sema.errMsg(inst_src, "expected type '{}', found '{}'", .{
31316 dest_ty.fmt(sema.mod), inst_ty.fmt(sema.mod),
31633 dest_ty.fmt(pt), inst_ty.fmt(pt),
3131731634 });
3131831635 errdefer msg.destroy(sema.gpa);
3131931636 try sema.errNote(dest_ty_src, msg, "destination has length {d}", .{dest_len});
......@@ -31355,7 +31672,7 @@ fn coerceTupleToArray(
3135531672 return block.addAggregateInit(dest_ty, element_refs);
3135631673 }
3135731674
31358 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
31675 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
3135931676 .ty = dest_ty.toIntern(),
3136031677 .storage = .{ .elems = element_vals },
3136131678 } })));
......@@ -31370,11 +31687,12 @@ fn coerceTupleToSlicePtrs(
3137031687 ptr_tuple: Air.Inst.Ref,
3137131688 tuple_src: LazySrcLoc,
3137231689) !Air.Inst.Ref {
31373 const mod = sema.mod;
31690 const pt = sema.pt;
31691 const mod = pt.zcu;
3137431692 const tuple_ty = sema.typeOf(ptr_tuple).childType(mod);
3137531693 const tuple = try sema.analyzeLoad(block, tuple_src, ptr_tuple, tuple_src);
3137631694 const slice_info = slice_ty.ptrInfo(mod);
31377 const array_ty = try mod.arrayType(.{
31695 const array_ty = try pt.arrayType(.{
3137831696 .len = tuple_ty.structFieldCount(mod),
3137931697 .sentinel = slice_info.sentinel,
3138031698 .child = slice_info.child,
......@@ -31396,7 +31714,8 @@ fn coerceTupleToArrayPtrs(
3139631714 ptr_tuple: Air.Inst.Ref,
3139731715 tuple_src: LazySrcLoc,
3139831716) !Air.Inst.Ref {
31399 const mod = sema.mod;
31717 const pt = sema.pt;
31718 const mod = pt.zcu;
3140031719 const tuple = try sema.analyzeLoad(block, tuple_src, ptr_tuple, tuple_src);
3140131720 const ptr_info = ptr_array_ty.ptrInfo(mod);
3140231721 const array_ty = Type.fromInterned(ptr_info.child);
......@@ -31417,10 +31736,11 @@ fn coerceTupleToStruct(
3141731736 inst: Air.Inst.Ref,
3141831737 inst_src: LazySrcLoc,
3141931738) !Air.Inst.Ref {
31420 const mod = sema.mod;
31739 const pt = sema.pt;
31740 const mod = pt.zcu;
3142131741 const ip = &mod.intern_pool;
31422 try struct_ty.resolveFields(mod);
31423 try struct_ty.resolveStructFieldInits(mod);
31742 try struct_ty.resolveFields(pt);
31743 try struct_ty.resolveStructFieldInits(pt);
3142431744
3142531745 if (struct_ty.isTupleOrAnonStruct(mod)) {
3142631746 return sema.coerceTupleToTuple(block, struct_ty, inst, inst_src);
......@@ -31444,7 +31764,7 @@ fn coerceTupleToStruct(
3144431764 .anon_struct_type => |anon_struct_type| if (anon_struct_type.names.len > 0)
3144531765 anon_struct_type.names.get(ip)[tuple_field_index]
3144631766 else
31447 try ip.getOrPutStringFmt(sema.gpa, "{d}", .{tuple_field_index}, .no_embedded_nulls),
31767 try ip.getOrPutStringFmt(sema.gpa, pt.tid, "{d}", .{tuple_field_index}, .no_embedded_nulls),
3144831768 .struct_type => ip.loadStructType(inst_ty.toIntern()).field_names.get(ip)[tuple_field_index],
3144931769 else => unreachable,
3145031770 };
......@@ -31461,7 +31781,7 @@ fn coerceTupleToStruct(
3146131781 };
3146231782
3146331783 const field_init = Value.fromInterned(struct_type.field_inits.get(ip)[struct_field_index]);
31464 if (!init_val.eql(field_init, struct_field_ty, sema.mod)) {
31784 if (!init_val.eql(field_init, struct_field_ty, pt.zcu)) {
3146531785 return sema.failWithInvalidComptimeFieldStore(block, field_src, inst_ty, tuple_field_index);
3146631786 }
3146731787 }
......@@ -31512,7 +31832,7 @@ fn coerceTupleToStruct(
3151231832 return block.addAggregateInit(struct_ty, field_refs);
3151331833 }
3151431834
31515 const struct_val = try mod.intern(.{ .aggregate = .{
31835 const struct_val = try pt.intern(.{ .aggregate = .{
3151631836 .ty = struct_ty.toIntern(),
3151731837 .storage = .{ .elems = field_vals },
3151831838 } });
......@@ -31529,7 +31849,8 @@ fn coerceTupleToTuple(
3152931849 inst: Air.Inst.Ref,
3153031850 inst_src: LazySrcLoc,
3153131851) !Air.Inst.Ref {
31532 const mod = sema.mod;
31852 const pt = sema.pt;
31853 const mod = pt.zcu;
3153331854 const ip = &mod.intern_pool;
3153431855 const dest_field_count = switch (ip.indexToKey(tuple_ty.toIntern())) {
3153531856 .anon_struct_type => |anon_struct_type| anon_struct_type.types.len,
......@@ -31556,13 +31877,13 @@ fn coerceTupleToTuple(
3155631877 .anon_struct_type => |anon_struct_type| if (anon_struct_type.names.len > 0)
3155731878 anon_struct_type.names.get(ip)[field_i]
3155831879 else
31559 try ip.getOrPutStringFmt(sema.gpa, "{d}", .{field_i}, .no_embedded_nulls),
31880 try ip.getOrPutStringFmt(sema.gpa, pt.tid, "{d}", .{field_i}, .no_embedded_nulls),
3156031881 .struct_type => s: {
3156131882 const struct_type = ip.loadStructType(inst_ty.toIntern());
3156231883 if (struct_type.field_names.len > 0) {
3156331884 break :s struct_type.field_names.get(ip)[field_i];
3156431885 } else {
31565 break :s try ip.getOrPutStringFmt(sema.gpa, "{d}", .{field_i}, .no_embedded_nulls);
31886 break :s try ip.getOrPutStringFmt(sema.gpa, pt.tid, "{d}", .{field_i}, .no_embedded_nulls);
3156631887 }
3156731888 },
3156831889 else => unreachable,
......@@ -31594,7 +31915,7 @@ fn coerceTupleToTuple(
3159431915 });
3159531916 };
3159631917
31597 if (!init_val.eql(Value.fromInterned(default_val), Type.fromInterned(field_ty), sema.mod)) {
31918 if (!init_val.eql(Value.fromInterned(default_val), Type.fromInterned(field_ty), pt.zcu)) {
3159831919 return sema.failWithInvalidComptimeFieldStore(block, field_src, inst_ty, field_i);
3159931920 }
3160031921 }
......@@ -31659,7 +31980,7 @@ fn coerceTupleToTuple(
3165931980 return block.addAggregateInit(tuple_ty, field_refs);
3166031981 }
3166131982
31662 return Air.internedToRef((try mod.intern(.{ .aggregate = .{
31983 return Air.internedToRef((try pt.intern(.{ .aggregate = .{
3166331984 .ty = tuple_ty.toIntern(),
3166431985 .storage = .{ .elems = field_vals },
3166531986 } })));
......@@ -31689,17 +32010,19 @@ fn addReferenceEntry(
3168932010 src: LazySrcLoc,
3169032011 referenced_unit: AnalUnit,
3169132012) !void {
31692 if (sema.mod.comp.reference_trace == 0) return;
32013 const zcu = sema.pt.zcu;
32014 if (zcu.comp.reference_trace == 0) return;
3169332015 const gop = try sema.references.getOrPut(sema.gpa, referenced_unit);
3169432016 if (gop.found_existing) return;
3169532017 // TODO: we need to figure out how to model inline calls here.
3169632018 // They aren't references in the analysis sense, but ought to show up in the reference trace!
3169732019 // Would representing inline calls in the reference table cause excessive memory usage?
31698 try sema.mod.addUnitReference(sema.ownerUnit(), referenced_unit, src);
32020 try zcu.addUnitReference(sema.ownerUnit(), referenced_unit, src);
3169932021}
3170032022
3170132023pub fn ensureDeclAnalyzed(sema: *Sema, decl_index: InternPool.DeclIndex) CompileError!void {
31702 const mod = sema.mod;
32024 const pt = sema.pt;
32025 const mod = pt.zcu;
3170332026 const ip = &mod.intern_pool;
3170432027 const decl = mod.declPtr(decl_index);
3170532028 if (decl.analysis == .in_progress) {
......@@ -31710,7 +32033,7 @@ pub fn ensureDeclAnalyzed(sema: *Sema, decl_index: InternPool.DeclIndex) Compile
3171032033 return sema.failWithOwnedErrorMsg(null, msg);
3171132034 }
3171232035
31713 mod.ensureDeclAnalyzed(decl_index) catch |err| {
32036 pt.ensureDeclAnalyzed(decl_index) catch |err| {
3171432037 if (sema.owner_func_index != .none) {
3171532038 ip.funcAnalysis(sema.owner_func_index).state = .dependency_failure;
3171632039 } else {
......@@ -31721,9 +32044,10 @@ pub fn ensureDeclAnalyzed(sema: *Sema, decl_index: InternPool.DeclIndex) Compile
3172132044}
3172232045
3172332046fn ensureFuncBodyAnalyzed(sema: *Sema, func: InternPool.Index) CompileError!void {
31724 const mod = sema.mod;
32047 const pt = sema.pt;
32048 const mod = pt.zcu;
3172532049 const ip = &mod.intern_pool;
31726 mod.ensureFuncBodyAnalyzed(func) catch |err| {
32050 pt.ensureFuncBodyAnalyzed(func) catch |err| {
3172732051 if (sema.owner_func_index != .none) {
3172832052 ip.funcAnalysis(sema.owner_func_index).state = .dependency_failure;
3172932053 } else {
......@@ -31734,15 +32058,15 @@ fn ensureFuncBodyAnalyzed(sema: *Sema, func: InternPool.Index) CompileError!void
3173432058}
3173532059
3173632060fn optRefValue(sema: *Sema, opt_val: ?Value) !Value {
31737 const mod = sema.mod;
31738 const ptr_anyopaque_ty = try mod.singleConstPtrType(Type.anyopaque);
31739 return Value.fromInterned((try mod.intern(.{ .opt = .{
31740 .ty = (try mod.optionalType(ptr_anyopaque_ty.toIntern())).toIntern(),
31741 .val = if (opt_val) |val| (try mod.getCoerced(
32061 const pt = sema.pt;
32062 const ptr_anyopaque_ty = try pt.singleConstPtrType(Type.anyopaque);
32063 return Value.fromInterned(try pt.intern(.{ .opt = .{
32064 .ty = (try pt.optionalType(ptr_anyopaque_ty.toIntern())).toIntern(),
32065 .val = if (opt_val) |val| (try pt.getCoerced(
3174232066 Value.fromInterned(try sema.refValue(val.toIntern())),
3174332067 ptr_anyopaque_ty,
3174432068 )).toIntern() else .none,
31745 } })));
32069 } }));
3174632070}
3174732071
3174832072fn analyzeDeclRef(sema: *Sema, src: LazySrcLoc, decl_index: InternPool.DeclIndex) CompileError!Air.Inst.Ref {
......@@ -31754,7 +32078,8 @@ fn analyzeDeclRef(sema: *Sema, src: LazySrcLoc, decl_index: InternPool.DeclIndex
3175432078/// decl_ref to end up in runtime code, the function body must be analyzed: `analyzeDeclRef` wraps
3175532079/// this function with `analyze_fn_body` set to true.
3175632080fn analyzeDeclRefInner(sema: *Sema, src: LazySrcLoc, decl_index: InternPool.DeclIndex, analyze_fn_body: bool) CompileError!Air.Inst.Ref {
31757 const mod = sema.mod;
32081 const pt = sema.pt;
32082 const mod = pt.zcu;
3175832083 try sema.addReferenceEntry(src, AnalUnit.wrap(.{ .decl = decl_index }));
3175932084 try sema.ensureDeclAnalyzed(decl_index);
3176032085
......@@ -31767,7 +32092,7 @@ fn analyzeDeclRefInner(sema: *Sema, src: LazySrcLoc, decl_index: InternPool.Decl
3176732092 });
3176832093 // TODO: if this is a `decl_ref` of a non-variable decl, only depend on decl type
3176932094 try sema.declareDependency(.{ .decl_val = decl_index });
31770 const ptr_ty = try mod.ptrTypeSema(.{
32095 const ptr_ty = try pt.ptrTypeSema(.{
3177132096 .child = decl_val.typeOf(mod).toIntern(),
3177232097 .flags = .{
3177332098 .alignment = owner_decl.alignment,
......@@ -31778,7 +32103,7 @@ fn analyzeDeclRefInner(sema: *Sema, src: LazySrcLoc, decl_index: InternPool.Decl
3177832103 if (analyze_fn_body) {
3177932104 try sema.maybeQueueFuncBodyAnalysis(src, decl_index);
3178032105 }
31781 return Air.internedToRef((try mod.intern(.{ .ptr = .{
32106 return Air.internedToRef((try pt.intern(.{ .ptr = .{
3178232107 .ty = ptr_ty.toIntern(),
3178332108 .base_addr = .{ .decl = decl_index },
3178432109 .byte_offset = 0,
......@@ -31786,7 +32111,7 @@ fn analyzeDeclRefInner(sema: *Sema, src: LazySrcLoc, decl_index: InternPool.Decl
3178632111}
3178732112
3178832113fn maybeQueueFuncBodyAnalysis(sema: *Sema, src: LazySrcLoc, decl_index: InternPool.DeclIndex) !void {
31789 const mod = sema.mod;
32114 const mod = sema.pt.zcu;
3179032115 const decl = mod.declPtr(decl_index);
3179132116 const decl_val = try decl.valueOrFail();
3179232117 if (!mod.intern_pool.isFuncBody(decl_val.toIntern())) return;
......@@ -31801,7 +32126,8 @@ fn analyzeRef(
3180132126 src: LazySrcLoc,
3180232127 operand: Air.Inst.Ref,
3180332128) CompileError!Air.Inst.Ref {
31804 const mod = sema.mod;
32129 const pt = sema.pt;
32130 const mod = pt.zcu;
3180532131 const operand_ty = sema.typeOf(operand);
3180632132
3180732133 if (try sema.resolveValue(operand)) |val| {
......@@ -31814,14 +32140,14 @@ fn analyzeRef(
3181432140
3181532141 try sema.requireRuntimeBlock(block, src, null);
3181632142 const address_space = target_util.defaultAddressSpace(mod.getTarget(), .local);
31817 const ptr_type = try mod.ptrTypeSema(.{
32143 const ptr_type = try pt.ptrTypeSema(.{
3181832144 .child = operand_ty.toIntern(),
3181932145 .flags = .{
3182032146 .is_const = true,
3182132147 .address_space = address_space,
3182232148 },
3182332149 });
31824 const mut_ptr_type = try mod.ptrTypeSema(.{
32150 const mut_ptr_type = try pt.ptrTypeSema(.{
3182532151 .child = operand_ty.toIntern(),
3182632152 .flags = .{ .address_space = address_space },
3182732153 });
......@@ -31839,14 +32165,15 @@ fn analyzeLoad(
3183932165 ptr: Air.Inst.Ref,
3184032166 ptr_src: LazySrcLoc,
3184132167) CompileError!Air.Inst.Ref {
31842 const mod = sema.mod;
32168 const pt = sema.pt;
32169 const mod = pt.zcu;
3184332170 const ptr_ty = sema.typeOf(ptr);
3184432171 const elem_ty = switch (ptr_ty.zigTypeTag(mod)) {
3184532172 .Pointer => ptr_ty.childType(mod),
31846 else => return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ty.fmt(sema.mod)}),
32173 else => return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ty.fmt(pt)}),
3184732174 };
3184832175 if (elem_ty.zigTypeTag(mod) == .Opaque) {
31849 return sema.fail(block, ptr_src, "cannot load opaque type '{}'", .{elem_ty.fmt(mod)});
32176 return sema.fail(block, ptr_src, "cannot load opaque type '{}'", .{elem_ty.fmt(pt)});
3185032177 }
3185132178
3185232179 if (try sema.typeHasOnePossibleValue(elem_ty)) |opv| {
......@@ -31868,7 +32195,7 @@ fn analyzeLoad(
3186832195 return block.addBinOp(.ptr_elem_val, bin_op.lhs, bin_op.rhs);
3186932196 }
3187032197 return sema.fail(block, ptr_src, "unable to determine vector element index of type '{}'", .{
31871 ptr_ty.fmt(sema.mod),
32198 ptr_ty.fmt(pt),
3187232199 });
3187332200 }
3187432201
......@@ -31882,10 +32209,11 @@ fn analyzeSlicePtr(
3188232209 slice: Air.Inst.Ref,
3188332210 slice_ty: Type,
3188432211) CompileError!Air.Inst.Ref {
31885 const mod = sema.mod;
32212 const pt = sema.pt;
32213 const mod = pt.zcu;
3188632214 const result_ty = slice_ty.slicePtrFieldType(mod);
3188732215 if (try sema.resolveValue(slice)) |val| {
31888 if (val.isUndef(mod)) return mod.undefRef(result_ty);
32216 if (val.isUndef(mod)) return pt.undefRef(result_ty);
3188932217 return Air.internedToRef(val.slicePtr(mod).toIntern());
3189032218 }
3189132219 try sema.requireRuntimeBlock(block, slice_src, null);
......@@ -31899,11 +32227,12 @@ fn analyzeOptionalSlicePtr(
3189932227 opt_slice: Air.Inst.Ref,
3190032228 opt_slice_ty: Type,
3190132229) CompileError!Air.Inst.Ref {
31902 const mod = sema.mod;
32230 const pt = sema.pt;
32231 const mod = pt.zcu;
3190332232 const result_ty = opt_slice_ty.optionalChild(mod).slicePtrFieldType(mod);
3190432233
3190532234 if (try sema.resolveValue(opt_slice)) |opt_val| {
31906 if (opt_val.isUndef(mod)) return mod.undefRef(result_ty);
32235 if (opt_val.isUndef(mod)) return pt.undefRef(result_ty);
3190732236 const slice_ptr: InternPool.Index = if (opt_val.optionalValue(mod)) |val|
3190832237 val.slicePtr(mod).toIntern()
3190932238 else
......@@ -31924,12 +32253,13 @@ fn analyzeSliceLen(
3192432253 src: LazySrcLoc,
3192532254 slice_inst: Air.Inst.Ref,
3192632255) CompileError!Air.Inst.Ref {
31927 const mod = sema.mod;
32256 const pt = sema.pt;
32257 const mod = pt.zcu;
3192832258 if (try sema.resolveValue(slice_inst)) |slice_val| {
3192932259 if (slice_val.isUndef(mod)) {
31930 return mod.undefRef(Type.usize);
32260 return pt.undefRef(Type.usize);
3193132261 }
31932 return mod.intRef(Type.usize, try slice_val.sliceLen(mod));
32262 return pt.intRef(Type.usize, try slice_val.sliceLen(pt));
3193332263 }
3193432264 try sema.requireRuntimeBlock(block, src, null);
3193532265 return block.addTyOp(.slice_len, Type.usize, slice_inst);
......@@ -31942,11 +32272,12 @@ fn analyzeIsNull(
3194232272 operand: Air.Inst.Ref,
3194332273 invert_logic: bool,
3194432274) CompileError!Air.Inst.Ref {
31945 const mod = sema.mod;
32275 const pt = sema.pt;
32276 const mod = pt.zcu;
3194632277 const result_ty = Type.bool;
3194732278 if (try sema.resolveValue(operand)) |opt_val| {
3194832279 if (opt_val.isUndef(mod)) {
31949 return mod.undefRef(result_ty);
32280 return pt.undefRef(result_ty);
3195032281 }
3195132282 const is_null = opt_val.isNull(mod);
3195232283 const bool_value = if (invert_logic) !is_null else is_null;
......@@ -31972,7 +32303,8 @@ fn analyzePtrIsNonErrComptimeOnly(
3197232303 src: LazySrcLoc,
3197332304 operand: Air.Inst.Ref,
3197432305) CompileError!Air.Inst.Ref {
31975 const mod = sema.mod;
32306 const pt = sema.pt;
32307 const mod = pt.zcu;
3197632308 const ptr_ty = sema.typeOf(operand);
3197732309 assert(ptr_ty.zigTypeTag(mod) == .Pointer);
3197832310 const child_ty = ptr_ty.childType(mod);
......@@ -31994,7 +32326,8 @@ fn analyzeIsNonErrComptimeOnly(
3199432326 src: LazySrcLoc,
3199532327 operand: Air.Inst.Ref,
3199632328) CompileError!Air.Inst.Ref {
31997 const mod = sema.mod;
32329 const pt = sema.pt;
32330 const mod = pt.zcu;
3199832331 const ip = &mod.intern_pool;
3199932332 const operand_ty = sema.typeOf(operand);
3200032333 const ot = operand_ty.zigTypeTag(mod);
......@@ -32014,7 +32347,7 @@ fn analyzeIsNonErrComptimeOnly(
3201432347 else => {},
3201532348 }
3201632349 } else if (operand == .undef) {
32017 return mod.undefRef(Type.bool);
32350 return pt.undefRef(Type.bool);
3201832351 } else if (@intFromEnum(operand) < InternPool.static_len) {
3201932352 // None of the ref tags can be errors.
3202032353 return .bool_true;
......@@ -32098,7 +32431,7 @@ fn analyzeIsNonErrComptimeOnly(
3209832431
3209932432 if (maybe_operand_val) |err_union| {
3210032433 if (err_union.isUndef(mod)) {
32101 return mod.undefRef(Type.bool);
32434 return pt.undefRef(Type.bool);
3210232435 }
3210332436 if (err_union.getErrorName(mod) == .none) {
3210432437 return .bool_true;
......@@ -32153,13 +32486,14 @@ fn analyzeSlice(
3215332486 end_src: LazySrcLoc,
3215432487 by_length: bool,
3215532488) CompileError!Air.Inst.Ref {
32156 const mod = sema.mod;
32489 const pt = sema.pt;
32490 const mod = pt.zcu;
3215732491 // Slice expressions can operate on a variable whose type is an array. This requires
3215832492 // the slice operand to be a pointer. In the case of a non-array, it will be a double pointer.
3215932493 const ptr_ptr_ty = sema.typeOf(ptr_ptr);
3216032494 const ptr_ptr_child_ty = switch (ptr_ptr_ty.zigTypeTag(mod)) {
3216132495 .Pointer => ptr_ptr_ty.childType(mod),
32162 else => return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ptr_ty.fmt(mod)}),
32496 else => return sema.fail(block, ptr_src, "expected pointer, found '{}'", .{ptr_ptr_ty.fmt(pt)}),
3216332497 };
3216432498
3216532499 var array_ty = ptr_ptr_child_ty;
......@@ -32210,8 +32544,8 @@ fn analyzeSlice(
3221032544 msg,
3221132545 "expected '{}', found '{}'",
3221232546 .{
32213 Value.zero_comptime_int.fmtValue(mod, sema),
32214 start_value.fmtValue(mod, sema),
32547 Value.zero_comptime_int.fmtValue(pt, sema),
32548 start_value.fmtValue(pt, sema),
3221532549 },
3221632550 );
3221732551 break :msg msg;
......@@ -32226,8 +32560,8 @@ fn analyzeSlice(
3222632560 msg,
3222732561 "expected '{}', found '{}'",
3222832562 .{
32229 Value.one_comptime_int.fmtValue(mod, sema),
32230 end_value.fmtValue(mod, sema),
32563 Value.one_comptime_int.fmtValue(pt, sema),
32564 end_value.fmtValue(pt, sema),
3223132565 },
3223232566 );
3223332567 break :msg msg;
......@@ -32240,17 +32574,17 @@ fn analyzeSlice(
3224032574 block,
3224132575 end_src,
3224232576 "end index {} out of bounds for slice of single-item pointer",
32243 .{end_value.fmtValue(mod, sema)},
32577 .{end_value.fmtValue(pt, sema)},
3224432578 );
3224532579 }
3224632580 }
3224732581
32248 array_ty = try mod.arrayType(.{
32582 array_ty = try pt.arrayType(.{
3224932583 .len = 1,
3225032584 .child = double_child_ty.toIntern(),
3225132585 });
3225232586 const ptr_info = ptr_ptr_child_ty.ptrInfo(mod);
32253 slice_ty = try mod.ptrType(.{
32587 slice_ty = try pt.ptrType(.{
3225432588 .child = array_ty.toIntern(),
3225532589 .flags = .{
3225632590 .alignment = ptr_info.flags.alignment,
......@@ -32286,7 +32620,7 @@ fn analyzeSlice(
3228632620 elem_ty = ptr_ptr_child_ty.childType(mod);
3228732621 },
3228832622 },
32289 else => return sema.fail(block, src, "slice of non-array type '{}'", .{ptr_ptr_child_ty.fmt(mod)}),
32623 else => return sema.fail(block, src, "slice of non-array type '{}'", .{ptr_ptr_child_ty.fmt(pt)}),
3229032624 }
3229132625
3229232626 const ptr = if (slice_ty.isSlice(mod))
......@@ -32297,7 +32631,7 @@ fn analyzeSlice(
3229732631 assert(manyptr_ty_key.flags.size == .One);
3229832632 manyptr_ty_key.child = elem_ty.toIntern();
3229932633 manyptr_ty_key.flags.size = .Many;
32300 break :ptr try sema.coerceCompatiblePtrs(block, try mod.ptrTypeSema(manyptr_ty_key), ptr_or_slice, ptr_src);
32634 break :ptr try sema.coerceCompatiblePtrs(block, try pt.ptrTypeSema(manyptr_ty_key), ptr_or_slice, ptr_src);
3230132635 } else ptr_or_slice;
3230232636
3230332637 const start = try sema.coerce(block, Type.usize, uncasted_start, start_src);
......@@ -32311,7 +32645,7 @@ fn analyzeSlice(
3231132645 var end_is_len = uncasted_end_opt == .none;
3231232646 const end = e: {
3231332647 if (array_ty.zigTypeTag(mod) == .Array) {
32314 const len_val = try mod.intValue(Type.usize, array_ty.arrayLen(mod));
32648 const len_val = try pt.intValue(Type.usize, array_ty.arrayLen(mod));
3231532649
3231632650 if (!end_is_len) {
3231732651 const end = if (by_length) end: {
......@@ -32320,7 +32654,7 @@ fn analyzeSlice(
3232032654 break :end try sema.coerce(block, Type.usize, uncasted_end, end_src);
3232132655 } else try sema.coerce(block, Type.usize, uncasted_end_opt, end_src);
3232232656 if (try sema.resolveDefinedValue(block, end_src, end)) |end_val| {
32323 const len_s_val = try mod.intValue(
32657 const len_s_val = try pt.intValue(
3232432658 Type.usize,
3232532659 array_ty.arrayLenIncludingSentinel(mod),
3232632660 );
......@@ -32335,8 +32669,8 @@ fn analyzeSlice(
3233532669 end_src,
3233632670 "end index {} out of bounds for array of length {}{s}",
3233732671 .{
32338 end_val.fmtValue(mod, sema),
32339 len_val.fmtValue(mod, sema),
32672 end_val.fmtValue(pt, sema),
32673 len_val.fmtValue(pt, sema),
3234032674 sentinel_label,
3234132675 },
3234232676 );
......@@ -32366,9 +32700,9 @@ fn analyzeSlice(
3236632700 return sema.fail(block, src, "slice of undefined", .{});
3236732701 }
3236832702 const has_sentinel = slice_ty.sentinel(mod) != null;
32369 const slice_len = try slice_val.sliceLen(mod);
32703 const slice_len = try slice_val.sliceLen(pt);
3237032704 const len_plus_sent = slice_len + @intFromBool(has_sentinel);
32371 const slice_len_val_with_sentinel = try mod.intValue(Type.usize, len_plus_sent);
32705 const slice_len_val_with_sentinel = try pt.intValue(Type.usize, len_plus_sent);
3237232706 if (!(try sema.compareAll(end_val, .lte, slice_len_val_with_sentinel, Type.usize))) {
3237332707 const sentinel_label: []const u8 = if (has_sentinel)
3237432708 " +1 (sentinel)"
......@@ -32380,8 +32714,8 @@ fn analyzeSlice(
3238032714 end_src,
3238132715 "end index {} out of bounds for slice of length {d}{s}",
3238232716 .{
32383 end_val.fmtValue(mod, sema),
32384 try slice_val.sliceLen(mod),
32717 end_val.fmtValue(pt, sema),
32718 try slice_val.sliceLen(pt),
3238532719 sentinel_label,
3238632720 },
3238732721 );
......@@ -32390,7 +32724,7 @@ fn analyzeSlice(
3239032724 // If the slice has a sentinel, we consider end_is_len
3239132725 // is only true if it equals the length WITHOUT the
3239232726 // sentinel, so we don't add a sentinel type.
32393 const slice_len_val = try mod.intValue(Type.usize, slice_len);
32727 const slice_len_val = try pt.intValue(Type.usize, slice_len);
3239432728 if (end_val.eql(slice_len_val, Type.usize, mod)) {
3239532729 end_is_len = true;
3239632730 }
......@@ -32440,21 +32774,21 @@ fn analyzeSlice(
3244032774 start_src,
3244132775 "start index {} is larger than end index {}",
3244232776 .{
32443 start_val.fmtValue(mod, sema),
32444 end_val.fmtValue(mod, sema),
32777 start_val.fmtValue(pt, sema),
32778 end_val.fmtValue(pt, sema),
3244532779 },
3244632780 );
3244732781 }
3244832782 checked_start_lte_end = true;
3244932783 if (try sema.resolveValue(new_ptr)) |ptr_val| sentinel_check: {
3245032784 const expected_sentinel = sentinel orelse break :sentinel_check;
32451 const start_int = start_val.getUnsignedInt(mod).?;
32452 const end_int = end_val.getUnsignedInt(mod).?;
32785 const start_int = start_val.getUnsignedInt(pt).?;
32786 const end_int = end_val.getUnsignedInt(pt).?;
3245332787 const sentinel_index = try sema.usizeCast(block, end_src, end_int - start_int);
3245432788
32455 const many_ptr_ty = try mod.manyConstPtrType(elem_ty);
32456 const many_ptr_val = try mod.getCoerced(ptr_val, many_ptr_ty);
32457 const elem_ptr = try many_ptr_val.ptrElem(sentinel_index, mod);
32789 const many_ptr_ty = try pt.manyConstPtrType(elem_ty);
32790 const many_ptr_val = try pt.getCoerced(ptr_val, many_ptr_ty);
32791 const elem_ptr = try many_ptr_val.ptrElem(sentinel_index, pt);
3245832792 const res = try sema.pointerDerefExtra(block, src, elem_ptr);
3245932793 const actual_sentinel = switch (res) {
3246032794 .runtime_load => break :sentinel_check,
......@@ -32463,13 +32797,13 @@ fn analyzeSlice(
3246332797 block,
3246432798 src,
3246532799 "comptime dereference requires '{}' to have a well-defined layout",
32466 .{ty.fmt(mod)},
32800 .{ty.fmt(pt)},
3246732801 ),
3246832802 .out_of_bounds => |ty| return sema.fail(
3246932803 block,
3247032804 end_src,
3247132805 "slice end index {d} exceeds bounds of containing decl of type '{}'",
32472 .{ end_int, ty.fmt(mod) },
32806 .{ end_int, ty.fmt(pt) },
3247332807 ),
3247432808 };
3247532809
......@@ -32478,8 +32812,8 @@ fn analyzeSlice(
3247832812 const msg = try sema.errMsg(src, "value in memory does not match slice sentinel", .{});
3247932813 errdefer msg.destroy(sema.gpa);
3248032814 try sema.errNote(src, msg, "expected '{}', found '{}'", .{
32481 expected_sentinel.fmtValue(mod, sema),
32482 actual_sentinel.fmtValue(mod, sema),
32815 expected_sentinel.fmtValue(pt, sema),
32816 actual_sentinel.fmtValue(pt, sema),
3248332817 });
3248432818
3248532819 break :msg msg;
......@@ -32501,7 +32835,7 @@ fn analyzeSlice(
3250132835 assert(!block.is_comptime);
3250232836 try sema.requireRuntimeBlock(block, src, runtime_src.?);
3250332837 const ok = try block.addBinOp(.cmp_lte, start, end);
32504 if (!sema.mod.comp.formatted_panics) {
32838 if (!pt.zcu.comp.formatted_panics) {
3250532839 try sema.addSafetyCheck(block, src, ok, .start_index_greater_than_end);
3250632840 } else {
3250732841 try sema.safetyCheckFormatted(block, src, ok, "panicStartGreaterThanEnd", &.{ start, end });
......@@ -32517,10 +32851,10 @@ fn analyzeSlice(
3251732851 const new_allowzero = new_ptr_ty_info.flags.is_allowzero and sema.typeOf(ptr).ptrSize(mod) != .C;
3251832852
3251932853 if (opt_new_len_val) |new_len_val| {
32520 const new_len_int = try new_len_val.toUnsignedIntSema(mod);
32854 const new_len_int = try new_len_val.toUnsignedIntSema(pt);
3252132855
32522 const return_ty = try mod.ptrTypeSema(.{
32523 .child = (try mod.arrayType(.{
32856 const return_ty = try pt.ptrTypeSema(.{
32857 .child = (try pt.arrayType(.{
3252432858 .len = new_len_int,
3252532859 .sentinel = if (sentinel) |s| s.toIntern() else .none,
3252632860 .child = elem_ty.toIntern(),
......@@ -32546,7 +32880,7 @@ fn analyzeSlice(
3254632880
3254732881 bounds_check: {
3254832882 const actual_len = if (array_ty.zigTypeTag(mod) == .Array)
32549 try mod.intRef(Type.usize, array_ty.arrayLenIncludingSentinel(mod))
32883 try pt.intRef(Type.usize, array_ty.arrayLenIncludingSentinel(mod))
3255032884 else if (slice_ty.isSlice(mod)) l: {
3255132885 const slice_len_inst = try block.addTyOp(.slice_len, Type.usize, ptr_or_slice);
3255232886 break :l if (slice_ty.sentinel(mod) == null)
......@@ -32570,18 +32904,18 @@ fn analyzeSlice(
3257032904 };
3257132905
3257232906 if (!new_ptr_val.isUndef(mod)) {
32573 return Air.internedToRef((try mod.getCoerced(new_ptr_val, return_ty)).toIntern());
32907 return Air.internedToRef((try pt.getCoerced(new_ptr_val, return_ty)).toIntern());
3257432908 }
3257532909
3257632910 // Special case: @as([]i32, undefined)[x..x]
3257732911 if (new_len_int == 0) {
32578 return mod.undefRef(return_ty);
32912 return pt.undefRef(return_ty);
3257932913 }
3258032914
3258132915 return sema.fail(block, src, "non-zero length slice of undefined pointer", .{});
3258232916 }
3258332917
32584 const return_ty = try mod.ptrTypeSema(.{
32918 const return_ty = try pt.ptrTypeSema(.{
3258532919 .child = elem_ty.toIntern(),
3258632920 .sentinel = if (sentinel) |s| s.toIntern() else .none,
3258732921 .flags = .{
......@@ -32604,12 +32938,12 @@ fn analyzeSlice(
3260432938
3260532939 // requirement: end <= len
3260632940 const opt_len_inst = if (array_ty.zigTypeTag(mod) == .Array)
32607 try mod.intRef(Type.usize, array_ty.arrayLenIncludingSentinel(mod))
32941 try pt.intRef(Type.usize, array_ty.arrayLenIncludingSentinel(mod))
3260832942 else if (slice_ty.isSlice(mod)) blk: {
3260932943 if (try sema.resolveDefinedValue(block, src, ptr_or_slice)) |slice_val| {
3261032944 // we don't need to add one for sentinels because the
3261132945 // underlying value data includes the sentinel
32612 break :blk try mod.intRef(Type.usize, try slice_val.sliceLen(mod));
32946 break :blk try pt.intRef(Type.usize, try slice_val.sliceLen(pt));
3261332947 }
3261432948
3261532949 const slice_len_inst = try block.addTyOp(.slice_len, Type.usize, ptr_or_slice);
......@@ -32657,7 +32991,8 @@ fn cmpNumeric(
3265732991 lhs_src: LazySrcLoc,
3265832992 rhs_src: LazySrcLoc,
3265932993) CompileError!Air.Inst.Ref {
32660 const mod = sema.mod;
32994 const pt = sema.pt;
32995 const mod = pt.zcu;
3266132996 const lhs_ty = sema.typeOf(uncasted_lhs);
3266232997 const rhs_ty = sema.typeOf(uncasted_rhs);
3266332998
......@@ -32696,12 +33031,12 @@ fn cmpNumeric(
3269633031 }
3269733032
3269833033 if (lhs_val.isUndef(mod) or rhs_val.isUndef(mod)) {
32699 return mod.undefRef(Type.bool);
33034 return pt.undefRef(Type.bool);
3270033035 }
3270133036 if (lhs_val.isNan(mod) or rhs_val.isNan(mod)) {
3270233037 return if (op == std.math.CompareOperator.neq) .bool_true else .bool_false;
3270333038 }
32704 return if (try Value.compareHeteroAdvanced(lhs_val, op, rhs_val, mod, .sema))
33039 return if (try Value.compareHeteroAdvanced(lhs_val, op, rhs_val, pt, .sema))
3270533040 .bool_true
3270633041 else
3270733042 .bool_false;
......@@ -32770,11 +33105,11 @@ fn cmpNumeric(
3277033105 // a signed integer with mantissa bits + 1, and if there was any non-integral part of the float,
3277133106 // add/subtract 1.
3277233107 const lhs_is_signed = if (try sema.resolveDefinedValue(block, lhs_src, lhs)) |lhs_val|
32773 !(try lhs_val.compareAllWithZeroSema(.gte, mod))
33108 !(try lhs_val.compareAllWithZeroSema(.gte, pt))
3277433109 else
3277533110 (lhs_ty.isRuntimeFloat() or lhs_ty.isSignedInt(mod));
3277633111 const rhs_is_signed = if (try sema.resolveDefinedValue(block, rhs_src, rhs)) |rhs_val|
32777 !(try rhs_val.compareAllWithZeroSema(.gte, mod))
33112 !(try rhs_val.compareAllWithZeroSema(.gte, pt))
3277833113 else
3277933114 (rhs_ty.isRuntimeFloat() or rhs_ty.isSignedInt(mod));
3278033115 const dest_int_is_signed = lhs_is_signed or rhs_is_signed;
......@@ -32784,7 +33119,7 @@ fn cmpNumeric(
3278433119 var lhs_bits: usize = undefined;
3278533120 if (try sema.resolveValueResolveLazy(lhs)) |lhs_val| {
3278633121 if (lhs_val.isUndef(mod))
32787 return mod.undefRef(Type.bool);
33122 return pt.undefRef(Type.bool);
3278833123 if (lhs_val.isNan(mod)) switch (op) {
3278933124 .neq => return .bool_true,
3279033125 else => return .bool_false,
......@@ -32796,7 +33131,7 @@ fn cmpNumeric(
3279633131 .lt, .lte => return if (lhs_val.isNegativeInf(mod)) .bool_true else .bool_false,
3279733132 };
3279833133 if (!rhs_is_signed) {
32799 switch (lhs_val.orderAgainstZero(mod)) {
33134 switch (lhs_val.orderAgainstZero(pt)) {
3280033135 .gt => {},
3280133136 .eq => switch (op) { // LHS = 0, RHS is unsigned
3280233137 .lte => return .bool_true,
......@@ -32818,7 +33153,7 @@ fn cmpNumeric(
3281833153 }
3281933154 }
3282033155
32821 var bigint = try float128IntPartToBigInt(sema.gpa, lhs_val.toFloat(f128, mod));
33156 var bigint = try float128IntPartToBigInt(sema.gpa, lhs_val.toFloat(f128, pt));
3282233157 defer bigint.deinit();
3282333158 if (lhs_val.floatHasFraction(mod)) {
3282433159 if (lhs_is_signed) {
......@@ -32829,7 +33164,7 @@ fn cmpNumeric(
3282933164 }
3283033165 lhs_bits = bigint.toConst().bitCountTwosComp();
3283133166 } else {
32832 lhs_bits = lhs_val.intBitCountTwosComp(mod);
33167 lhs_bits = lhs_val.intBitCountTwosComp(pt);
3283333168 }
3283433169 lhs_bits += @intFromBool(!lhs_is_signed and dest_int_is_signed);
3283533170 } else if (lhs_is_float) {
......@@ -32842,7 +33177,7 @@ fn cmpNumeric(
3284233177 var rhs_bits: usize = undefined;
3284333178 if (try sema.resolveValueResolveLazy(rhs)) |rhs_val| {
3284433179 if (rhs_val.isUndef(mod))
32845 return mod.undefRef(Type.bool);
33180 return pt.undefRef(Type.bool);
3284633181 if (rhs_val.isNan(mod)) switch (op) {
3284733182 .neq => return .bool_true,
3284833183 else => return .bool_false,
......@@ -32854,7 +33189,7 @@ fn cmpNumeric(
3285433189 .lt, .lte => return if (rhs_val.isNegativeInf(mod)) .bool_false else .bool_true,
3285533190 };
3285633191 if (!lhs_is_signed) {
32857 switch (rhs_val.orderAgainstZero(mod)) {
33192 switch (rhs_val.orderAgainstZero(pt)) {
3285833193 .gt => {},
3285933194 .eq => switch (op) { // RHS = 0, LHS is unsigned
3286033195 .gte => return .bool_true,
......@@ -32876,7 +33211,7 @@ fn cmpNumeric(
3287633211 }
3287733212 }
3287833213
32879 var bigint = try float128IntPartToBigInt(sema.gpa, rhs_val.toFloat(f128, mod));
33214 var bigint = try float128IntPartToBigInt(sema.gpa, rhs_val.toFloat(f128, pt));
3288033215 defer bigint.deinit();
3288133216 if (rhs_val.floatHasFraction(mod)) {
3288233217 if (rhs_is_signed) {
......@@ -32887,7 +33222,7 @@ fn cmpNumeric(
3288733222 }
3288833223 rhs_bits = bigint.toConst().bitCountTwosComp();
3288933224 } else {
32890 rhs_bits = rhs_val.intBitCountTwosComp(mod);
33225 rhs_bits = rhs_val.intBitCountTwosComp(pt);
3289133226 }
3289233227 rhs_bits += @intFromBool(!rhs_is_signed and dest_int_is_signed);
3289333228 } else if (rhs_is_float) {
......@@ -32901,7 +33236,7 @@ fn cmpNumeric(
3290133236 const max_bits = @max(lhs_bits, rhs_bits);
3290233237 const casted_bits = std.math.cast(u16, max_bits) orelse return sema.fail(block, src, "{d} exceeds maximum integer bit count", .{max_bits});
3290333238 const signedness: std.builtin.Signedness = if (dest_int_is_signed) .signed else .unsigned;
32904 break :blk try mod.intType(signedness, casted_bits);
33239 break :blk try pt.intType(signedness, casted_bits);
3290533240 };
3290633241 const casted_lhs = try sema.coerce(block, dest_ty, lhs, lhs_src);
3290733242 const casted_rhs = try sema.coerce(block, dest_ty, rhs, rhs_src);
......@@ -32920,9 +33255,10 @@ fn compareIntsOnlyPossibleResult(
3292033255 op: std.math.CompareOperator,
3292133256 rhs_ty: Type,
3292233257) Allocator.Error!?bool {
32923 const mod = sema.mod;
33258 const pt = sema.pt;
33259 const mod = pt.zcu;
3292433260 const rhs_info = rhs_ty.intInfo(mod);
32925 const vs_zero = lhs_val.orderAgainstZeroAdvanced(mod, .sema) catch unreachable;
33261 const vs_zero = lhs_val.orderAgainstZeroAdvanced(pt, .sema) catch unreachable;
3292633262 const is_zero = vs_zero == .eq;
3292733263 const is_negative = vs_zero == .lt;
3292833264 const is_positive = vs_zero == .gt;
......@@ -32954,7 +33290,7 @@ fn compareIntsOnlyPossibleResult(
3295433290 };
3295533291
3295633292 const sign_adj = @intFromBool(!is_negative and rhs_info.signedness == .signed);
32957 const req_bits = lhs_val.intBitCountTwosComp(mod) + sign_adj;
33293 const req_bits = lhs_val.intBitCountTwosComp(pt) + sign_adj;
3295833294
3295933295 // No sized type can have more than 65535 bits.
3296033296 // The RHS type operand is either a runtime value or sized (but undefined) constant.
......@@ -32981,11 +33317,11 @@ fn compareIntsOnlyPossibleResult(
3298133317
3298233318 if (req_bits != rhs_info.bits) break :edge .{ false, false };
3298333319
32984 const ty = try mod.intType(
33320 const ty = try pt.intType(
3298533321 if (is_negative) .signed else .unsigned,
3298633322 @intCast(req_bits),
3298733323 );
32988 const pop_count = lhs_val.popCount(ty, mod);
33324 const pop_count = lhs_val.popCount(ty, pt);
3298933325
3299033326 if (is_negative) {
3299133327 break :edge .{ pop_count == 1, false };
......@@ -33015,7 +33351,8 @@ fn cmpVector(
3301533351 lhs_src: LazySrcLoc,
3301633352 rhs_src: LazySrcLoc,
3301733353) CompileError!Air.Inst.Ref {
33018 const mod = sema.mod;
33354 const pt = sema.pt;
33355 const mod = pt.zcu;
3301933356 const lhs_ty = sema.typeOf(lhs);
3302033357 const rhs_ty = sema.typeOf(rhs);
3302133358 assert(lhs_ty.zigTypeTag(mod) == .Vector);
......@@ -33026,7 +33363,7 @@ fn cmpVector(
3302633363 const casted_lhs = try sema.coerce(block, resolved_ty, lhs, lhs_src);
3302733364 const casted_rhs = try sema.coerce(block, resolved_ty, rhs, rhs_src);
3302833365
33029 const result_ty = try mod.vectorType(.{
33366 const result_ty = try pt.vectorType(.{
3303033367 .len = lhs_ty.vectorLen(mod),
3303133368 .child = .bool_type,
3303233369 });
......@@ -33035,7 +33372,7 @@ fn cmpVector(
3303533372 if (try sema.resolveValue(casted_lhs)) |lhs_val| {
3303633373 if (try sema.resolveValue(casted_rhs)) |rhs_val| {
3303733374 if (lhs_val.isUndef(mod) or rhs_val.isUndef(mod)) {
33038 return mod.undefRef(result_ty);
33375 return pt.undefRef(result_ty);
3303933376 }
3304033377 const cmp_val = try sema.compareVector(lhs_val, op, rhs_val, resolved_ty);
3304133378 return Air.internedToRef(cmp_val.toIntern());
......@@ -33059,7 +33396,7 @@ fn wrapOptional(
3305933396 inst_src: LazySrcLoc,
3306033397) !Air.Inst.Ref {
3306133398 if (try sema.resolveValue(inst)) |val| {
33062 return Air.internedToRef((try sema.mod.intern(.{ .opt = .{
33399 return Air.internedToRef((try sema.pt.intern(.{ .opt = .{
3306333400 .ty = dest_ty.toIntern(),
3306433401 .val = val.toIntern(),
3306533402 } })));
......@@ -33076,11 +33413,12 @@ fn wrapErrorUnionPayload(
3307633413 inst: Air.Inst.Ref,
3307733414 inst_src: LazySrcLoc,
3307833415) !Air.Inst.Ref {
33079 const mod = sema.mod;
33416 const pt = sema.pt;
33417 const mod = pt.zcu;
3308033418 const dest_payload_ty = dest_ty.errorUnionPayload(mod);
3308133419 const coerced = try sema.coerceExtra(block, dest_payload_ty, inst, inst_src, .{ .report_err = false });
3308233420 if (try sema.resolveValue(coerced)) |val| {
33083 return Air.internedToRef((try mod.intern(.{ .error_union = .{
33421 return Air.internedToRef((try pt.intern(.{ .error_union = .{
3308433422 .ty = dest_ty.toIntern(),
3308533423 .val = .{ .payload = val.toIntern() },
3308633424 } })));
......@@ -33096,7 +33434,8 @@ fn wrapErrorUnionSet(
3309633434 inst: Air.Inst.Ref,
3309733435 inst_src: LazySrcLoc,
3309833436) !Air.Inst.Ref {
33099 const mod = sema.mod;
33437 const pt = sema.pt;
33438 const mod = pt.zcu;
3310033439 const ip = &mod.intern_pool;
3310133440 const inst_ty = sema.typeOf(inst);
3310233441 const dest_err_set_ty = dest_ty.errorUnionSet(mod);
......@@ -33140,7 +33479,7 @@ fn wrapErrorUnionSet(
3314033479 else => unreachable,
3314133480 },
3314233481 }
33143 return Air.internedToRef((try mod.intern(.{ .error_union = .{
33482 return Air.internedToRef((try pt.intern(.{ .error_union = .{
3314433483 .ty = dest_ty.toIntern(),
3314533484 .val = .{ .err_name = expected_name },
3314633485 } })));
......@@ -33158,14 +33497,15 @@ fn unionToTag(
3315833497 un: Air.Inst.Ref,
3315933498 un_src: LazySrcLoc,
3316033499) !Air.Inst.Ref {
33161 const mod = sema.mod;
33500 const pt = sema.pt;
33501 const mod = pt.zcu;
3316233502 if ((try sema.typeHasOnePossibleValue(enum_ty))) |opv| {
3316333503 return Air.internedToRef(opv.toIntern());
3316433504 }
3316533505 if (try sema.resolveValue(un)) |un_val| {
3316633506 const tag_val = un_val.unionTag(mod).?;
3316733507 if (tag_val.isUndef(mod))
33168 return try mod.undefRef(enum_ty);
33508 return try pt.undefRef(enum_ty);
3316933509 return Air.internedToRef(tag_val.toIntern());
3317033510 }
3317133511 try sema.requireRuntimeBlock(block, un_src, null);
......@@ -33399,7 +33739,7 @@ const PeerResolveResult = union(enum) {
3339933739 instructions: []const Air.Inst.Ref,
3340033740 candidate_srcs: PeerTypeCandidateSrc,
3340133741 ) !*Module.ErrorMsg {
33402 const mod = sema.mod;
33742 const pt = sema.pt;
3340333743
3340433744 var opt_msg: ?*Module.ErrorMsg = null;
3340533745 errdefer if (opt_msg) |msg| msg.destroy(sema.gpa);
......@@ -33425,7 +33765,7 @@ const PeerResolveResult = union(enum) {
3342533765 },
3342633766 .field_error => |field_error| {
3342733767 const fmt = "struct field '{}' has conflicting types";
33428 const args = .{field_error.field_name.fmt(&mod.intern_pool)};
33768 const args = .{field_error.field_name.fmt(&pt.zcu.intern_pool)};
3342933769 if (opt_msg) |msg| {
3343033770 try sema.errNote(src, msg, fmt, args);
3343133771 } else {
......@@ -33457,8 +33797,8 @@ const PeerResolveResult = union(enum) {
3345733797
3345833798 const fmt = "incompatible types: '{}' and '{}'";
3345933799 const args = .{
33460 conflict_tys[0].fmt(mod),
33461 conflict_tys[1].fmt(mod),
33800 conflict_tys[0].fmt(pt),
33801 conflict_tys[1].fmt(pt),
3346233802 };
3346333803 const msg = if (opt_msg) |msg| msg: {
3346433804 try sema.errNote(src, msg, fmt, args);
......@@ -33469,8 +33809,8 @@ const PeerResolveResult = union(enum) {
3346933809 break :msg msg;
3347033810 };
3347133811
33472 if (conflict_srcs[0]) |src_loc| try sema.errNote(src_loc, msg, "type '{}' here", .{conflict_tys[0].fmt(mod)});
33473 if (conflict_srcs[1]) |src_loc| try sema.errNote(src_loc, msg, "type '{}' here", .{conflict_tys[1].fmt(mod)});
33812 if (conflict_srcs[0]) |src_loc| try sema.errNote(src_loc, msg, "type '{}' here", .{conflict_tys[0].fmt(pt)});
33813 if (conflict_srcs[1]) |src_loc| try sema.errNote(src_loc, msg, "type '{}' here", .{conflict_tys[1].fmt(pt)});
3347433814
3347533815 // No child error
3347633816 break;
......@@ -33517,7 +33857,8 @@ fn resolvePeerTypesInner(
3351733857 peer_tys: []?Type,
3351833858 peer_vals: []?Value,
3351933859) !PeerResolveResult {
33520 const mod = sema.mod;
33860 const pt = sema.pt;
33861 const mod = pt.zcu;
3352133862 const ip = &mod.intern_pool;
3352233863
3352333864 var strat_reason: usize = 0;
......@@ -33581,7 +33922,7 @@ fn resolvePeerTypesInner(
3358133922 .payload => |payload_ip| val_ptr.* = Value.fromInterned(payload_ip),
3358233923 .err_name => val_ptr.* = null,
3358333924 },
33584 .undef => val_ptr.* = Value.fromInterned((try sema.mod.intern(.{ .undef = ty_ptr.*.?.toIntern() }))),
33925 .undef => val_ptr.* = Value.fromInterned(try pt.intern(.{ .undef = ty_ptr.*.?.toIntern() })),
3358533926 else => unreachable,
3358633927 };
3358733928 break :blk set_ty;
......@@ -33604,7 +33945,7 @@ fn resolvePeerTypesInner(
3360433945 .success => |ty| ty,
3360533946 else => |result| return result,
3360633947 };
33607 return .{ .success = try mod.errorUnionType(final_set.?, final_payload) };
33948 return .{ .success = try pt.errorUnionType(final_set.?, final_payload) };
3360833949 },
3360933950
3361033951 .nullable => {
......@@ -33642,7 +33983,7 @@ fn resolvePeerTypesInner(
3364233983 .success => |ty| ty,
3364333984 else => |result| return result,
3364433985 };
33645 return .{ .success = try mod.optionalType(child_ty.toIntern()) };
33986 return .{ .success = try pt.optionalType(child_ty.toIntern()) };
3364633987 },
3364733988
3364833989 .array => {
......@@ -33730,7 +34071,7 @@ fn resolvePeerTypesInner(
3373034071 // There should always be at least one array or vector peer
3373134072 assert(opt_first_arr_idx != null);
3373234073
33733 return .{ .success = try mod.arrayType(.{
34074 return .{ .success = try pt.arrayType(.{
3373434075 .len = len,
3373534076 .child = elem_ty.toIntern(),
3373634077 .sentinel = if (sentinel) |sent_val| sent_val.toIntern() else .none,
......@@ -33792,7 +34133,7 @@ fn resolvePeerTypesInner(
3379234133 else => |result| return result,
3379334134 };
3379434135
33795 return .{ .success = try mod.vectorType(.{
34136 return .{ .success = try pt.vectorType(.{
3379634137 .len = @intCast(len.?),
3379734138 .child = child_ty.toIntern(),
3379834139 }) };
......@@ -33844,8 +34185,8 @@ fn resolvePeerTypesInner(
3384434185 }).toIntern();
3384534186
3384634187 if (ptr_info.sentinel != .none and peer_info.sentinel != .none) {
33847 const peer_sent = try ip.getCoerced(sema.gpa, ptr_info.sentinel, ptr_info.child);
33848 const ptr_sent = try ip.getCoerced(sema.gpa, peer_info.sentinel, ptr_info.child);
34188 const peer_sent = try ip.getCoerced(sema.gpa, pt.tid, ptr_info.sentinel, ptr_info.child);
34189 const ptr_sent = try ip.getCoerced(sema.gpa, pt.tid, peer_info.sentinel, ptr_info.child);
3384934190 if (ptr_sent == peer_sent) {
3385034191 ptr_info.sentinel = ptr_sent;
3385134192 } else {
......@@ -33860,12 +34201,12 @@ fn resolvePeerTypesInner(
3386034201 if (ptr_info.flags.alignment != .none)
3386134202 ptr_info.flags.alignment
3386234203 else
33863 Type.fromInterned(ptr_info.child).abiAlignment(mod),
34204 Type.fromInterned(ptr_info.child).abiAlignment(pt),
3386434205
3386534206 if (peer_info.flags.alignment != .none)
3386634207 peer_info.flags.alignment
3386734208 else
33868 Type.fromInterned(peer_info.child).abiAlignment(mod),
34209 Type.fromInterned(peer_info.child).abiAlignment(pt),
3386934210 );
3387034211 if (ptr_info.flags.address_space != peer_info.flags.address_space) {
3387134212 return .{ .conflict = .{
......@@ -33888,7 +34229,7 @@ fn resolvePeerTypesInner(
3388834229
3388934230 opt_ptr_info = ptr_info;
3389034231 }
33891 return .{ .success = try mod.ptrTypeSema(opt_ptr_info.?) };
34232 return .{ .success = try pt.ptrTypeSema(opt_ptr_info.?) };
3389234233 },
3389334234
3389434235 .ptr => {
......@@ -34004,7 +34345,7 @@ fn resolvePeerTypesInner(
3400434345 if (try sema.resolvePairInMemoryCoercible(block, src, cur_arr.elem_ty, peer_arr.elem_ty)) |elem_ty| {
3400534346 // *[n:x]T + *[n:y]T = *[n]T
3400634347 if (cur_arr.len == peer_arr.len) {
34007 ptr_info.child = (try mod.arrayType(.{
34348 ptr_info.child = (try pt.arrayType(.{
3400834349 .len = cur_arr.len,
3400934350 .child = elem_ty.toIntern(),
3401034351 })).toIntern();
......@@ -34148,12 +34489,12 @@ fn resolvePeerTypesInner(
3414834489 no_sentinel: {
3414934490 if (peer_sentinel == .none) break :no_sentinel;
3415034491 if (cur_sentinel == .none) break :no_sentinel;
34151 const peer_sent_coerced = try ip.getCoerced(sema.gpa, peer_sentinel, sentinel_ty);
34152 const cur_sent_coerced = try ip.getCoerced(sema.gpa, cur_sentinel, sentinel_ty);
34492 const peer_sent_coerced = try ip.getCoerced(sema.gpa, pt.tid, peer_sentinel, sentinel_ty);
34493 const cur_sent_coerced = try ip.getCoerced(sema.gpa, pt.tid, cur_sentinel, sentinel_ty);
3415334494 if (peer_sent_coerced != cur_sent_coerced) break :no_sentinel;
3415434495 // Sentinels match
3415534496 if (ptr_info.flags.size == .One) switch (ip.indexToKey(ptr_info.child)) {
34156 .array_type => |array_type| ptr_info.child = (try mod.arrayType(.{
34497 .array_type => |array_type| ptr_info.child = (try pt.arrayType(.{
3415734498 .len = array_type.len,
3415834499 .child = array_type.child,
3415934500 .sentinel = cur_sent_coerced,
......@@ -34167,7 +34508,7 @@ fn resolvePeerTypesInner(
3416734508 // Clear existing sentinel
3416834509 ptr_info.sentinel = .none;
3416934510 switch (ip.indexToKey(ptr_info.child)) {
34170 .array_type => |array_type| ptr_info.child = (try mod.arrayType(.{
34511 .array_type => |array_type| ptr_info.child = (try pt.arrayType(.{
3417134512 .len = array_type.len,
3417234513 .child = array_type.child,
3417334514 .sentinel = .none,
......@@ -34198,7 +34539,7 @@ fn resolvePeerTypesInner(
3419834539 },
3419934540 }
3420034541
34201 return .{ .success = try mod.ptrTypeSema(opt_ptr_info.?) };
34542 return .{ .success = try pt.ptrTypeSema(opt_ptr_info.?) };
3420234543 },
3420334544
3420434545 .func => {
......@@ -34517,7 +34858,7 @@ fn resolvePeerTypesInner(
3451734858 continue;
3451834859 };
3451934860 peer_field_ty.* = ty.structFieldType(field_index, mod);
34520 peer_field_val.* = if (opt_val) |val| try val.fieldValue(mod, field_index) else null;
34861 peer_field_val.* = if (opt_val) |val| try val.fieldValue(pt, field_index) else null;
3452134862 }
3452234863
3452334864 // Resolve field type recursively
......@@ -34527,7 +34868,7 @@ fn resolvePeerTypesInner(
3452734868 const result_buf = try sema.arena.create(PeerResolveResult);
3452834869 result_buf.* = result;
3452934870 const field_name = if (is_tuple)
34530 try ip.getOrPutStringFmt(sema.gpa, "{d}", .{field_index}, .no_embedded_nulls)
34871 try ip.getOrPutStringFmt(sema.gpa, pt.tid, "{d}", .{field_index}, .no_embedded_nulls)
3453134872 else
3453234873 field_names[field_index];
3453334874
......@@ -34555,9 +34896,9 @@ fn resolvePeerTypesInner(
3455534896 var comptime_val: ?Value = null;
3455634897 for (peer_tys) |opt_ty| {
3455734898 const struct_ty = opt_ty orelse continue;
34558 try struct_ty.resolveStructFieldInits(mod);
34899 try struct_ty.resolveStructFieldInits(pt);
3455934900
34560 const uncoerced_field_val = try struct_ty.structFieldValueComptime(mod, field_index) orelse {
34901 const uncoerced_field_val = try struct_ty.structFieldValueComptime(pt, field_index) orelse {
3456134902 comptime_val = null;
3456234903 break;
3456334904 };
......@@ -34584,7 +34925,7 @@ fn resolvePeerTypesInner(
3458434925 field_val.* = if (comptime_val) |v| v.toIntern() else .none;
3458534926 }
3458634927
34587 const final_ty = try ip.getAnonStructType(mod.gpa, .{
34928 const final_ty = try ip.getAnonStructType(mod.gpa, pt.tid, .{
3458834929 .types = field_types,
3458934930 .names = if (is_tuple) &.{} else field_names,
3459034931 .values = field_vals,
......@@ -34628,13 +34969,15 @@ fn maybeMergeErrorSets(sema: *Sema, block: *Block, src: LazySrcLoc, e0: Type, e1
3462834969}
3462934970
3463034971fn resolvePairInMemoryCoercible(sema: *Sema, block: *Block, src: LazySrcLoc, ty_a: Type, ty_b: Type) !?Type {
34972 const target = sema.pt.zcu.getTarget();
34973
3463134974 // ty_b -> ty_a
34632 if (.ok == try sema.coerceInMemoryAllowed(block, ty_a, ty_b, true, sema.mod.getTarget(), src, src)) {
34975 if (.ok == try sema.coerceInMemoryAllowed(block, ty_a, ty_b, true, target, src, src)) {
3463334976 return ty_a;
3463434977 }
3463534978
3463634979 // ty_a -> ty_b
34637 if (.ok == try sema.coerceInMemoryAllowed(block, ty_b, ty_a, true, sema.mod.getTarget(), src, src)) {
34980 if (.ok == try sema.coerceInMemoryAllowed(block, ty_b, ty_a, true, target, src, src)) {
3463834981 return ty_b;
3463934982 }
3464034983
......@@ -34647,7 +34990,8 @@ const ArrayLike = struct {
3464734990 elem_ty: Type,
3464834991};
3464934992fn typeIsArrayLike(sema: *Sema, ty: Type) ?ArrayLike {
34650 const mod = sema.mod;
34993 const pt = sema.pt;
34994 const mod = pt.zcu;
3465134995 return switch (ty.zigTypeTag(mod)) {
3465234996 .Array => .{
3465334997 .len = ty.arrayLen(mod),
......@@ -34676,7 +35020,8 @@ fn typeIsArrayLike(sema: *Sema, ty: Type) ?ArrayLike {
3467635020}
3467735021
3467835022pub fn resolveIes(sema: *Sema, block: *Block, src: LazySrcLoc) CompileError!void {
34679 const mod = sema.mod;
35023 const pt = sema.pt;
35024 const mod = pt.zcu;
3468035025 const ip = &mod.intern_pool;
3468135026
3468235027 if (sema.fn_ret_ty_ies) |ies| {
......@@ -34687,26 +35032,27 @@ pub fn resolveIes(sema: *Sema, block: *Block, src: LazySrcLoc) CompileError!void
3468735032}
3468835033
3468935034pub fn resolveFnTypes(sema: *Sema, fn_ty: Type) CompileError!void {
34690 const mod = sema.mod;
35035 const pt = sema.pt;
35036 const mod = pt.zcu;
3469135037 const ip = &mod.intern_pool;
3469235038 const fn_ty_info = mod.typeToFunc(fn_ty).?;
3469335039
34694 try Type.fromInterned(fn_ty_info.return_type).resolveFully(mod);
35040 try Type.fromInterned(fn_ty_info.return_type).resolveFully(pt);
3469535041
3469635042 if (mod.comp.config.any_error_tracing and
3469735043 Type.fromInterned(fn_ty_info.return_type).isError(mod))
3469835044 {
3469935045 // Ensure the type exists so that backends can assume that.
34700 _ = try mod.getBuiltinType("StackTrace");
35046 _ = try pt.getBuiltinType("StackTrace");
3470135047 }
3470235048
3470335049 for (0..fn_ty_info.param_types.len) |i| {
34704 try Type.fromInterned(fn_ty_info.param_types.get(ip)[i]).resolveFully(mod);
35050 try Type.fromInterned(fn_ty_info.param_types.get(ip)[i]).resolveFully(pt);
3470535051 }
3470635052}
3470735053
3470835054fn resolveLazyValue(sema: *Sema, val: Value) CompileError!Value {
34709 return val.resolveLazy(sema.arena, sema.mod);
35055 return val.resolveLazy(sema.arena, sema.pt);
3471035056}
3471135057
3471235058/// Resolve a struct's alignment only without triggering resolution of its layout.
......@@ -34716,7 +35062,8 @@ pub fn resolveStructAlignment(
3471635062 ty: InternPool.Index,
3471735063 struct_type: InternPool.LoadedStructType,
3471835064) SemaError!void {
34719 const mod = sema.mod;
35065 const pt = sema.pt;
35066 const mod = pt.zcu;
3472035067 const ip = &mod.intern_pool;
3472135068 const target = mod.getTarget();
3472235069
......@@ -34754,7 +35101,7 @@ pub fn resolveStructAlignment(
3475435101 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
3475535102 if (struct_type.fieldIsComptime(ip, i) or try sema.typeRequiresComptime(field_ty))
3475635103 continue;
34757 const field_align = try mod.structFieldAlignmentAdvanced(
35104 const field_align = try pt.structFieldAlignmentAdvanced(
3475835105 struct_type.fieldAlign(ip, i),
3475935106 field_ty,
3476035107 struct_type.layout,
......@@ -34767,7 +35114,8 @@ pub fn resolveStructAlignment(
3476735114}
3476835115
3476935116pub fn resolveStructLayout(sema: *Sema, ty: Type) SemaError!void {
34770 const zcu = sema.mod;
35117 const pt = sema.pt;
35118 const zcu = pt.zcu;
3477135119 const ip = &zcu.intern_pool;
3477235120 const struct_type = zcu.typeToStruct(ty) orelse return;
3477335121
......@@ -34776,10 +35124,10 @@ pub fn resolveStructLayout(sema: *Sema, ty: Type) SemaError!void {
3477635124 if (struct_type.haveLayout(ip))
3477735125 return;
3477835126
34779 try ty.resolveFields(zcu);
35127 try ty.resolveFields(pt);
3478035128
3478135129 if (struct_type.layout == .@"packed") {
34782 semaBackingIntType(zcu, struct_type) catch |err| switch (err) {
35130 semaBackingIntType(pt, struct_type) catch |err| switch (err) {
3478335131 error.OutOfMemory, error.AnalysisFail => |e| return e,
3478435132 error.ComptimeBreak, error.ComptimeReturn, error.GenericPoison => unreachable,
3478535133 };
......@@ -34790,7 +35138,7 @@ pub fn resolveStructLayout(sema: *Sema, ty: Type) SemaError!void {
3479035138 const msg = try sema.errMsg(
3479135139 ty.srcLoc(zcu),
3479235140 "struct '{}' depends on itself",
34793 .{ty.fmt(zcu)},
35141 .{ty.fmt(pt)},
3479435142 );
3479535143 return sema.failWithOwnedErrorMsg(null, msg);
3479635144 }
......@@ -34818,7 +35166,7 @@ pub fn resolveStructLayout(sema: *Sema, ty: Type) SemaError!void {
3481835166 },
3481935167 else => return err,
3482035168 };
34821 field_align.* = try zcu.structFieldAlignmentAdvanced(
35169 field_align.* = try pt.structFieldAlignmentAdvanced(
3482235170 struct_type.fieldAlign(ip, i),
3482335171 field_ty,
3482435172 struct_type.layout,
......@@ -34911,7 +35259,8 @@ pub fn resolveStructLayout(sema: *Sema, ty: Type) SemaError!void {
3491135259 _ = try sema.typeRequiresComptime(ty);
3491235260}
3491335261
34914fn semaBackingIntType(zcu: *Zcu, struct_type: InternPool.LoadedStructType) CompileError!void {
35262fn semaBackingIntType(pt: Zcu.PerThread, struct_type: InternPool.LoadedStructType) CompileError!void {
35263 const zcu = pt.zcu;
3491535264 const gpa = zcu.gpa;
3491635265 const ip = &zcu.intern_pool;
3491735266
......@@ -34927,7 +35276,7 @@ fn semaBackingIntType(zcu: *Zcu, struct_type: InternPool.LoadedStructType) Compi
3492735276 defer comptime_err_ret_trace.deinit();
3492835277
3492935278 var sema: Sema = .{
34930 .mod = zcu,
35279 .pt = pt,
3493135280 .gpa = gpa,
3493235281 .arena = analysis_arena.allocator(),
3493335282 .code = zir,
......@@ -34958,7 +35307,7 @@ fn semaBackingIntType(zcu: *Zcu, struct_type: InternPool.LoadedStructType) Compi
3495835307 var accumulator: u64 = 0;
3495935308 for (0..struct_type.field_types.len) |i| {
3496035309 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
34961 accumulator += try field_ty.bitSizeAdvanced(zcu, .sema);
35310 accumulator += try field_ty.bitSizeAdvanced(pt, .sema);
3496235311 }
3496335312 break :blk accumulator;
3496435313 };
......@@ -35004,7 +35353,7 @@ fn semaBackingIntType(zcu: *Zcu, struct_type: InternPool.LoadedStructType) Compi
3500435353 if (fields_bit_sum > std.math.maxInt(u16)) {
3500535354 return sema.fail(&block, block.nodeOffset(0), "size of packed struct '{d}' exceeds maximum bit width of 65535", .{fields_bit_sum});
3500635355 }
35007 const backing_int_ty = try zcu.intType(.unsigned, @intCast(fields_bit_sum));
35356 const backing_int_ty = try pt.intType(.unsigned, @intCast(fields_bit_sum));
3500835357 struct_type.backingIntType(ip).* = backing_int_ty.toIntern();
3500935358 }
3501035359
......@@ -35012,26 +35361,27 @@ fn semaBackingIntType(zcu: *Zcu, struct_type: InternPool.LoadedStructType) Compi
3501235361}
3501335362
3501435363fn checkBackingIntType(sema: *Sema, block: *Block, src: LazySrcLoc, backing_int_ty: Type, fields_bit_sum: u64) CompileError!void {
35015 const mod = sema.mod;
35364 const pt = sema.pt;
35365 const mod = pt.zcu;
3501635366
3501735367 if (!backing_int_ty.isInt(mod)) {
35018 return sema.fail(block, src, "expected backing integer type, found '{}'", .{backing_int_ty.fmt(sema.mod)});
35368 return sema.fail(block, src, "expected backing integer type, found '{}'", .{backing_int_ty.fmt(pt)});
3501935369 }
35020 if (backing_int_ty.bitSize(mod) != fields_bit_sum) {
35370 if (backing_int_ty.bitSize(pt) != fields_bit_sum) {
3502135371 return sema.fail(
3502235372 block,
3502335373 src,
3502435374 "backing integer type '{}' has bit size {} but the struct fields have a total bit size of {}",
35025 .{ backing_int_ty.fmt(sema.mod), backing_int_ty.bitSize(mod), fields_bit_sum },
35375 .{ backing_int_ty.fmt(pt), backing_int_ty.bitSize(pt), fields_bit_sum },
3502635376 );
3502735377 }
3502835378}
3502935379
3503035380fn checkIndexable(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) !void {
35031 const mod = sema.mod;
35032 if (!ty.isIndexable(mod)) {
35381 const pt = sema.pt;
35382 if (!ty.isIndexable(pt.zcu)) {
3503335383 const msg = msg: {
35034 const msg = try sema.errMsg(src, "type '{}' does not support indexing", .{ty.fmt(sema.mod)});
35384 const msg = try sema.errMsg(src, "type '{}' does not support indexing", .{ty.fmt(pt)});
3503535385 errdefer msg.destroy(sema.gpa);
3503635386 try sema.errNote(src, msg, "operand must be an array, slice, tuple, or vector", .{});
3503735387 break :msg msg;
......@@ -35041,7 +35391,8 @@ fn checkIndexable(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) !void {
3504135391}
3504235392
3504335393fn checkMemOperand(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) !void {
35044 const mod = sema.mod;
35394 const pt = sema.pt;
35395 const mod = pt.zcu;
3504535396 if (ty.zigTypeTag(mod) == .Pointer) {
3504635397 switch (ty.ptrSize(mod)) {
3504735398 .Slice, .Many, .C => return,
......@@ -35054,7 +35405,7 @@ fn checkMemOperand(sema: *Sema, block: *Block, src: LazySrcLoc, ty: Type) !void
3505435405 }
3505535406 }
3505635407 const msg = msg: {
35057 const msg = try sema.errMsg(src, "type '{}' is not an indexable pointer", .{ty.fmt(sema.mod)});
35408 const msg = try sema.errMsg(src, "type '{}' is not an indexable pointer", .{ty.fmt(pt)});
3505835409 errdefer msg.destroy(sema.gpa);
3505935410 try sema.errNote(src, msg, "operand must be a slice, a many pointer or a pointer to an array", .{});
3506035411 break :msg msg;
......@@ -35069,9 +35420,9 @@ pub fn resolveUnionAlignment(
3506935420 ty: Type,
3507035421 union_type: InternPool.LoadedUnionType,
3507135422) SemaError!void {
35072 const mod = sema.mod;
35073 const ip = &mod.intern_pool;
35074 const target = mod.getTarget();
35423 const zcu = sema.pt.zcu;
35424 const ip = &zcu.intern_pool;
35425 const target = zcu.getTarget();
3507535426
3507635427 assert(sema.ownerUnit().unwrap().decl == union_type.decl);
3507735428
......@@ -35108,8 +35459,8 @@ pub fn resolveUnionAlignment(
3510835459
3510935460/// This logic must be kept in sync with `Module.getUnionLayout`.
3511035461pub fn resolveUnionLayout(sema: *Sema, ty: Type) SemaError!void {
35111 const zcu = sema.mod;
35112 const ip = &zcu.intern_pool;
35462 const pt = sema.pt;
35463 const ip = &pt.zcu.intern_pool;
3511335464
3511435465 try sema.resolveTypeFieldsUnion(ty, ip.loadUnionType(ty.ip_index));
3511535466
......@@ -35122,9 +35473,9 @@ pub fn resolveUnionLayout(sema: *Sema, ty: Type) SemaError!void {
3512235473 .none, .have_field_types => {},
3512335474 .field_types_wip, .layout_wip => {
3512435475 const msg = try sema.errMsg(
35125 ty.srcLoc(zcu),
35476 ty.srcLoc(pt.zcu),
3512635477 "union '{}' depends on itself",
35127 .{ty.fmt(zcu)},
35478 .{ty.fmt(pt)},
3512835479 );
3512935480 return sema.failWithOwnedErrorMsg(null, msg);
3513035481 },
......@@ -35143,7 +35494,7 @@ pub fn resolveUnionLayout(sema: *Sema, ty: Type) SemaError!void {
3514335494 for (0..union_type.field_types.len) |field_index| {
3514435495 const field_ty = Type.fromInterned(union_type.field_types.get(ip)[field_index]);
3514535496
35146 if (try sema.typeRequiresComptime(field_ty) or field_ty.zigTypeTag(zcu) == .NoReturn) continue; // TODO: should this affect alignment?
35497 if (try sema.typeRequiresComptime(field_ty) or field_ty.zigTypeTag(pt.zcu) == .NoReturn) continue; // TODO: should this affect alignment?
3514735498
3514835499 max_size = @max(max_size, sema.typeAbiSize(field_ty) catch |err| switch (err) {
3514935500 error.AnalysisFail => {
......@@ -35185,7 +35536,7 @@ pub fn resolveUnionLayout(sema: *Sema, ty: Type) SemaError!void {
3518535536 } else {
3518635537 // {Payload, Tag}
3518735538 size += max_size;
35188 size = switch (zcu.getTarget().ofmt) {
35539 size = switch (pt.zcu.getTarget().ofmt) {
3518935540 .c => max_align,
3519035541 else => tag_align,
3519135542 }.forward(size);
......@@ -35205,7 +35556,7 @@ pub fn resolveUnionLayout(sema: *Sema, ty: Type) SemaError!void {
3520535556
3520635557 if (union_type.flagsPtr(ip).assumed_runtime_bits and !(try sema.typeHasRuntimeBits(ty))) {
3520735558 const msg = try sema.errMsg(
35208 ty.srcLoc(zcu),
35559 ty.srcLoc(pt.zcu),
3520935560 "union layout depends on it having runtime bits",
3521035561 .{},
3521135562 );
......@@ -35213,10 +35564,10 @@ pub fn resolveUnionLayout(sema: *Sema, ty: Type) SemaError!void {
3521335564 }
3521435565
3521535566 if (union_type.flagsPtr(ip).assumed_pointer_aligned and
35216 alignment.compareStrict(.neq, Alignment.fromByteUnits(@divExact(zcu.getTarget().ptrBitWidth(), 8))))
35567 alignment.compareStrict(.neq, Alignment.fromByteUnits(@divExact(pt.zcu.getTarget().ptrBitWidth(), 8))))
3521735568 {
3521835569 const msg = try sema.errMsg(
35219 ty.srcLoc(zcu),
35570 ty.srcLoc(pt.zcu),
3522035571 "union layout depends on being pointer aligned",
3522135572 .{},
3522235573 );
......@@ -35229,7 +35580,8 @@ pub fn resolveUnionLayout(sema: *Sema, ty: Type) SemaError!void {
3522935580pub fn resolveStructFully(sema: *Sema, ty: Type) SemaError!void {
3523035581 try sema.resolveStructLayout(ty);
3523135582
35232 const mod = sema.mod;
35583 const pt = sema.pt;
35584 const mod = pt.zcu;
3523335585 const ip = &mod.intern_pool;
3523435586 const struct_type = mod.typeToStruct(ty).?;
3523535587
......@@ -35244,14 +35596,15 @@ pub fn resolveStructFully(sema: *Sema, ty: Type) SemaError!void {
3524435596
3524535597 for (0..struct_type.field_types.len) |i| {
3524635598 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
35247 try field_ty.resolveFully(mod);
35599 try field_ty.resolveFully(pt);
3524835600 }
3524935601}
3525035602
3525135603pub fn resolveUnionFully(sema: *Sema, ty: Type) SemaError!void {
3525235604 try sema.resolveUnionLayout(ty);
3525335605
35254 const mod = sema.mod;
35606 const pt = sema.pt;
35607 const mod = pt.zcu;
3525535608 const ip = &mod.intern_pool;
3525635609 const union_obj = mod.typeToUnion(ty).?;
3525735610
......@@ -35272,7 +35625,7 @@ pub fn resolveUnionFully(sema: *Sema, ty: Type) SemaError!void {
3527235625 union_obj.flagsPtr(ip).status = .fully_resolved_wip;
3527335626 for (0..union_obj.field_types.len) |field_index| {
3527435627 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
35275 try field_ty.resolveFully(mod);
35628 try field_ty.resolveFully(pt);
3527635629 }
3527735630 union_obj.flagsPtr(ip).status = .fully_resolved;
3527835631 }
......@@ -35286,7 +35639,8 @@ pub fn resolveTypeFieldsStruct(
3528635639 ty: InternPool.Index,
3528735640 struct_type: InternPool.LoadedStructType,
3528835641) SemaError!void {
35289 const zcu = sema.mod;
35642 const pt = sema.pt;
35643 const zcu = pt.zcu;
3529035644 const ip = &zcu.intern_pool;
3529135645 // If there is no owner decl it means the struct has no fields.
3529235646 const owner_decl = struct_type.decl.unwrap() orelse return;
......@@ -35310,13 +35664,13 @@ pub fn resolveTypeFieldsStruct(
3531035664 const msg = try sema.errMsg(
3531135665 Type.fromInterned(ty).srcLoc(zcu),
3531235666 "struct '{}' depends on itself",
35313 .{Type.fromInterned(ty).fmt(zcu)},
35667 .{Type.fromInterned(ty).fmt(pt)},
3531435668 );
3531535669 return sema.failWithOwnedErrorMsg(null, msg);
3531635670 }
3531735671 defer struct_type.clearTypesWip(ip);
3531835672
35319 semaStructFields(zcu, sema.arena, struct_type) catch |err| switch (err) {
35673 semaStructFields(pt, sema.arena, struct_type) catch |err| switch (err) {
3532035674 error.AnalysisFail => {
3532135675 if (zcu.declPtr(owner_decl).analysis == .complete) {
3532235676 zcu.declPtr(owner_decl).analysis = .dependency_failure;
......@@ -35329,7 +35683,8 @@ pub fn resolveTypeFieldsStruct(
3532935683}
3533035684
3533135685pub fn resolveStructFieldInits(sema: *Sema, ty: Type) SemaError!void {
35332 const zcu = sema.mod;
35686 const pt = sema.pt;
35687 const zcu = pt.zcu;
3533335688 const ip = &zcu.intern_pool;
3533435689 const struct_type = zcu.typeToStruct(ty) orelse return;
3533535690 const owner_decl = struct_type.decl.unwrap() orelse return;
......@@ -35345,13 +35700,13 @@ pub fn resolveStructFieldInits(sema: *Sema, ty: Type) SemaError!void {
3534535700 const msg = try sema.errMsg(
3534635701 ty.srcLoc(zcu),
3534735702 "struct '{}' depends on itself",
35348 .{ty.fmt(zcu)},
35703 .{ty.fmt(pt)},
3534935704 );
3535035705 return sema.failWithOwnedErrorMsg(null, msg);
3535135706 }
3535235707 defer struct_type.clearInitsWip(ip);
3535335708
35354 semaStructFieldInits(zcu, sema.arena, struct_type) catch |err| switch (err) {
35709 semaStructFieldInits(pt, sema.arena, struct_type) catch |err| switch (err) {
3535535710 error.AnalysisFail => {
3535635711 if (zcu.declPtr(owner_decl).analysis == .complete) {
3535735712 zcu.declPtr(owner_decl).analysis = .dependency_failure;
......@@ -35365,7 +35720,8 @@ pub fn resolveStructFieldInits(sema: *Sema, ty: Type) SemaError!void {
3536535720}
3536635721
3536735722pub fn resolveTypeFieldsUnion(sema: *Sema, ty: Type, union_type: InternPool.LoadedUnionType) SemaError!void {
35368 const zcu = sema.mod;
35723 const pt = sema.pt;
35724 const zcu = pt.zcu;
3536935725 const ip = &zcu.intern_pool;
3537035726 const owner_decl = zcu.declPtr(union_type.decl);
3537135727
......@@ -35387,7 +35743,7 @@ pub fn resolveTypeFieldsUnion(sema: *Sema, ty: Type, union_type: InternPool.Load
3538735743 const msg = try sema.errMsg(
3538835744 ty.srcLoc(zcu),
3538935745 "union '{}' depends on itself",
35390 .{ty.fmt(zcu)},
35746 .{ty.fmt(pt)},
3539135747 );
3539235748 return sema.failWithOwnedErrorMsg(null, msg);
3539335749 },
......@@ -35401,7 +35757,7 @@ pub fn resolveTypeFieldsUnion(sema: *Sema, ty: Type, union_type: InternPool.Load
3540135757
3540235758 union_type.flagsPtr(ip).status = .field_types_wip;
3540335759 errdefer union_type.flagsPtr(ip).status = .none;
35404 semaUnionFields(zcu, sema.arena, union_type) catch |err| switch (err) {
35760 semaUnionFields(pt, sema.arena, union_type) catch |err| switch (err) {
3540535761 error.AnalysisFail => {
3540635762 if (owner_decl.analysis == .complete) {
3540735763 owner_decl.analysis = .dependency_failure;
......@@ -35422,7 +35778,8 @@ fn resolveInferredErrorSet(
3542235778 src: LazySrcLoc,
3542335779 ies_index: InternPool.Index,
3542435780) CompileError!InternPool.Index {
35425 const mod = sema.mod;
35781 const pt = sema.pt;
35782 const mod = pt.zcu;
3542635783 const ip = &mod.intern_pool;
3542735784 const func_index = ip.iesFuncIndex(ies_index);
3542835785 const func = mod.funcInfo(func_index);
......@@ -35482,8 +35839,8 @@ pub fn resolveInferredErrorSetPtr(
3548235839 src: LazySrcLoc,
3548335840 ies: *InferredErrorSet,
3548435841) CompileError!void {
35485 const mod = sema.mod;
35486 const ip = &mod.intern_pool;
35842 const pt = sema.pt;
35843 const ip = &pt.zcu.intern_pool;
3548735844
3548835845 if (ies.resolved != .none) return;
3548935846
......@@ -35505,7 +35862,7 @@ pub fn resolveInferredErrorSetPtr(
3550535862 }
3550635863 }
3550735864
35508 const resolved_error_set_ty = try mod.errorSetFromUnsortedNames(ies.errors.keys());
35865 const resolved_error_set_ty = try pt.errorSetFromUnsortedNames(ies.errors.keys());
3550935866 ies.resolved = resolved_error_set_ty.toIntern();
3551035867}
3551135868
......@@ -35515,12 +35872,13 @@ fn resolveAdHocInferredErrorSet(
3551535872 src: LazySrcLoc,
3551635873 value: InternPool.Index,
3551735874) CompileError!InternPool.Index {
35518 const mod = sema.mod;
35875 const pt = sema.pt;
35876 const mod = pt.zcu;
3551935877 const gpa = sema.gpa;
3552035878 const ip = &mod.intern_pool;
3552135879 const new_ty = try resolveAdHocInferredErrorSetTy(sema, block, src, ip.typeOf(value));
3552235880 if (new_ty == .none) return value;
35523 return ip.getCoerced(gpa, value, new_ty);
35881 return ip.getCoerced(gpa, pt.tid, value, new_ty);
3552435882}
3552535883
3552635884fn resolveAdHocInferredErrorSetTy(
......@@ -35530,8 +35888,8 @@ fn resolveAdHocInferredErrorSetTy(
3553035888 ty: InternPool.Index,
3553135889) CompileError!InternPool.Index {
3553235890 const ies = sema.fn_ret_ty_ies orelse return .none;
35533 const mod = sema.mod;
35534 const gpa = sema.gpa;
35891 const pt = sema.pt;
35892 const mod = pt.zcu;
3553535893 const ip = &mod.intern_pool;
3553635894 const error_union_info = switch (ip.indexToKey(ty)) {
3553735895 .error_union_type => |x| x,
......@@ -35541,7 +35899,7 @@ fn resolveAdHocInferredErrorSetTy(
3554135899 return .none;
3554235900
3554335901 try sema.resolveInferredErrorSetPtr(block, src, ies);
35544 const new_ty = try ip.get(gpa, .{ .error_union_type = .{
35902 const new_ty = try pt.intern(.{ .error_union_type = .{
3554535903 .error_set_type = ies.resolved,
3554635904 .payload_type = error_union_info.payload_type,
3554735905 } });
......@@ -35554,7 +35912,8 @@ fn resolveInferredErrorSetTy(
3555435912 src: LazySrcLoc,
3555535913 ty: InternPool.Index,
3555635914) CompileError!InternPool.Index {
35557 const mod = sema.mod;
35915 const pt = sema.pt;
35916 const mod = pt.zcu;
3555835917 const ip = &mod.intern_pool;
3555935918 if (ty == .anyerror_type) return ty;
3556035919 switch (ip.indexToKey(ty)) {
......@@ -35614,10 +35973,11 @@ fn structZirInfo(zir: Zir, zir_index: Zir.Inst.Index) struct {
3561435973}
3561535974
3561635975fn semaStructFields(
35617 zcu: *Zcu,
35976 pt: Zcu.PerThread,
3561835977 arena: Allocator,
3561935978 struct_type: InternPool.LoadedStructType,
3562035979) CompileError!void {
35980 const zcu = pt.zcu;
3562135981 const gpa = zcu.gpa;
3562235982 const ip = &zcu.intern_pool;
3562335983 const decl_index = struct_type.decl.unwrap() orelse return;
......@@ -35630,7 +35990,7 @@ fn semaStructFields(
3563035990
3563135991 if (fields_len == 0) switch (struct_type.layout) {
3563235992 .@"packed" => {
35633 try semaBackingIntType(zcu, struct_type);
35993 try semaBackingIntType(pt, struct_type);
3563435994 return;
3563535995 },
3563635996 .auto, .@"extern" => {
......@@ -35644,7 +36004,7 @@ fn semaStructFields(
3564436004 defer comptime_err_ret_trace.deinit();
3564536005
3564636006 var sema: Sema = .{
35647 .mod = zcu,
36007 .pt = pt,
3564836008 .gpa = gpa,
3564936009 .arena = arena,
3565036010 .code = zir,
......@@ -35725,7 +36085,7 @@ fn semaStructFields(
3572536085
3572636086 // This string needs to outlive the ZIR code.
3572736087 if (opt_field_name_zir) |field_name_zir| {
35728 const field_name = try ip.getOrPutString(gpa, field_name_zir, .no_embedded_nulls);
36088 const field_name = try ip.getOrPutString(gpa, pt.tid, field_name_zir, .no_embedded_nulls);
3572936089 assert(struct_type.addFieldName(ip, field_name) == null);
3573036090 }
3573136091
......@@ -35789,7 +36149,7 @@ fn semaStructFields(
3578936149 switch (struct_type.layout) {
3579036150 .@"extern" => if (!try sema.validateExternType(field_ty, .struct_field)) {
3579136151 const msg = msg: {
35792 const msg = try sema.errMsg(ty_src, "extern structs cannot contain fields of type '{}'", .{field_ty.fmt(zcu)});
36152 const msg = try sema.errMsg(ty_src, "extern structs cannot contain fields of type '{}'", .{field_ty.fmt(pt)});
3579336153 errdefer msg.destroy(sema.gpa);
3579436154
3579536155 try sema.explainWhyTypeIsNotExtern(msg, ty_src, field_ty, .struct_field);
......@@ -35801,7 +36161,7 @@ fn semaStructFields(
3580136161 },
3580236162 .@"packed" => if (!try sema.validatePackedType(field_ty)) {
3580336163 const msg = msg: {
35804 const msg = try sema.errMsg(ty_src, "packed structs cannot contain fields of type '{}'", .{field_ty.fmt(zcu)});
36164 const msg = try sema.errMsg(ty_src, "packed structs cannot contain fields of type '{}'", .{field_ty.fmt(pt)});
3580536165 errdefer msg.destroy(sema.gpa);
3580636166
3580736167 try sema.explainWhyTypeIsNotPacked(msg, ty_src, field_ty);
......@@ -35837,10 +36197,11 @@ fn semaStructFields(
3583736197
3583836198// This logic must be kept in sync with `semaStructFields`
3583936199fn semaStructFieldInits(
35840 zcu: *Zcu,
36200 pt: Zcu.PerThread,
3584136201 arena: Allocator,
3584236202 struct_type: InternPool.LoadedStructType,
3584336203) CompileError!void {
36204 const zcu = pt.zcu;
3584436205 const gpa = zcu.gpa;
3584536206 const ip = &zcu.intern_pool;
3584636207
......@@ -35857,7 +36218,7 @@ fn semaStructFieldInits(
3585736218 defer comptime_err_ret_trace.deinit();
3585836219
3585936220 var sema: Sema = .{
35860 .mod = zcu,
36221 .pt = pt,
3586136222 .gpa = gpa,
3586236223 .arena = arena,
3586336224 .code = zir,
......@@ -35977,10 +36338,11 @@ fn semaStructFieldInits(
3597736338 try sema.flushExports();
3597836339}
3597936340
35980fn semaUnionFields(zcu: *Zcu, arena: Allocator, union_type: InternPool.LoadedUnionType) CompileError!void {
36341fn semaUnionFields(pt: Zcu.PerThread, arena: Allocator, union_type: InternPool.LoadedUnionType) CompileError!void {
3598136342 const tracy = trace(@src());
3598236343 defer tracy.end();
3598336344
36345 const zcu = pt.zcu;
3598436346 const gpa = zcu.gpa;
3598536347 const ip = &zcu.intern_pool;
3598636348 const decl_index = union_type.decl;
......@@ -36034,7 +36396,7 @@ fn semaUnionFields(zcu: *Zcu, arena: Allocator, union_type: InternPool.LoadedUni
3603436396 defer comptime_err_ret_trace.deinit();
3603536397
3603636398 var sema: Sema = .{
36037 .mod = zcu,
36399 .pt = pt,
3603836400 .gpa = gpa,
3603936401 .arena = arena,
3604036402 .code = zir,
......@@ -36081,17 +36443,17 @@ fn semaUnionFields(zcu: *Zcu, arena: Allocator, union_type: InternPool.LoadedUni
3608136443 // The provided type is an integer type and we must construct the enum tag type here.
3608236444 int_tag_ty = provided_ty;
3608336445 if (int_tag_ty.zigTypeTag(zcu) != .Int and int_tag_ty.zigTypeTag(zcu) != .ComptimeInt) {
36084 return sema.fail(&block_scope, tag_ty_src, "expected integer tag type, found '{}'", .{int_tag_ty.fmt(zcu)});
36446 return sema.fail(&block_scope, tag_ty_src, "expected integer tag type, found '{}'", .{int_tag_ty.fmt(pt)});
3608536447 }
3608636448
3608736449 if (fields_len > 0) {
36088 const field_count_val = try zcu.intValue(Type.comptime_int, fields_len - 1);
36450 const field_count_val = try pt.intValue(Type.comptime_int, fields_len - 1);
3608936451 if (!(try sema.intFitsInType(field_count_val, int_tag_ty, null))) {
3609036452 const msg = msg: {
3609136453 const msg = try sema.errMsg(tag_ty_src, "specified integer tag type cannot represent every field", .{});
3609236454 errdefer msg.destroy(sema.gpa);
3609336455 try sema.errNote(tag_ty_src, msg, "type '{}' cannot fit values in range 0...{d}", .{
36094 int_tag_ty.fmt(zcu),
36456 int_tag_ty.fmt(pt),
3609536457 fields_len - 1,
3609636458 });
3609736459 break :msg msg;
......@@ -36106,7 +36468,7 @@ fn semaUnionFields(zcu: *Zcu, arena: Allocator, union_type: InternPool.LoadedUni
3610636468 union_type.tagTypePtr(ip).* = provided_ty.toIntern();
3610736469 const enum_type = switch (ip.indexToKey(provided_ty.toIntern())) {
3610836470 .enum_type => ip.loadEnumType(provided_ty.toIntern()),
36109 else => return sema.fail(&block_scope, tag_ty_src, "expected enum tag type, found '{}'", .{provided_ty.fmt(zcu)}),
36471 else => return sema.fail(&block_scope, tag_ty_src, "expected enum tag type, found '{}'", .{provided_ty.fmt(pt)}),
3611036472 };
3611136473 // The fields of the union must match the enum exactly.
3611236474 // A flag per field is used to check for missing and extraneous fields.
......@@ -36202,7 +36564,7 @@ fn semaUnionFields(zcu: *Zcu, arena: Allocator, union_type: InternPool.LoadedUni
3620236564 const val = if (last_tag_val) |val|
3620336565 try sema.intAdd(val, Value.one_comptime_int, int_tag_ty, undefined)
3620436566 else
36205 try zcu.intValue(int_tag_ty, 0);
36567 try pt.intValue(int_tag_ty, 0);
3620636568 last_tag_val = val;
3620736569
3620836570 break :blk val;
......@@ -36214,7 +36576,7 @@ fn semaUnionFields(zcu: *Zcu, arena: Allocator, union_type: InternPool.LoadedUni
3621436576 .offset = .{ .container_field_value = @intCast(gop.index) },
3621536577 };
3621636578 const msg = msg: {
36217 const msg = try sema.errMsg(value_src, "enum tag value {} already taken", .{enum_tag_val.fmtValue(zcu, &sema)});
36579 const msg = try sema.errMsg(value_src, "enum tag value {} already taken", .{enum_tag_val.fmtValue(pt, &sema)});
3621836580 errdefer msg.destroy(gpa);
3621936581 try sema.errNote(other_value_src, msg, "other occurrence here", .{});
3622036582 break :msg msg;
......@@ -36224,7 +36586,7 @@ fn semaUnionFields(zcu: *Zcu, arena: Allocator, union_type: InternPool.LoadedUni
3622436586 }
3622536587
3622636588 // This string needs to outlive the ZIR code.
36227 const field_name = try ip.getOrPutString(gpa, field_name_zir, .no_embedded_nulls);
36589 const field_name = try ip.getOrPutString(gpa, pt.tid, field_name_zir, .no_embedded_nulls);
3622836590 if (enum_field_names.len != 0) {
3622936591 enum_field_names[field_i] = field_name;
3623036592 }
......@@ -36244,7 +36606,7 @@ fn semaUnionFields(zcu: *Zcu, arena: Allocator, union_type: InternPool.LoadedUni
3624436606 const tag_info = ip.loadEnumType(union_type.tagTypePtr(ip).*);
3624536607 const enum_index = tag_info.nameIndex(ip, field_name) orelse {
3624636608 return sema.fail(&block_scope, name_src, "no field named '{}' in enum '{}'", .{
36247 field_name.fmt(ip), Type.fromInterned(union_type.tagTypePtr(ip).*).fmt(zcu),
36609 field_name.fmt(ip), Type.fromInterned(union_type.tagTypePtr(ip).*).fmt(pt),
3624836610 });
3624936611 };
3625036612
......@@ -36286,7 +36648,7 @@ fn semaUnionFields(zcu: *Zcu, arena: Allocator, union_type: InternPool.LoadedUni
3628636648 !try sema.validateExternType(field_ty, .union_field))
3628736649 {
3628836650 const msg = msg: {
36289 const msg = try sema.errMsg(type_src, "extern unions cannot contain fields of type '{}'", .{field_ty.fmt(zcu)});
36651 const msg = try sema.errMsg(type_src, "extern unions cannot contain fields of type '{}'", .{field_ty.fmt(pt)});
3629036652 errdefer msg.destroy(sema.gpa);
3629136653
3629236654 try sema.explainWhyTypeIsNotExtern(msg, type_src, field_ty, .union_field);
......@@ -36297,7 +36659,7 @@ fn semaUnionFields(zcu: *Zcu, arena: Allocator, union_type: InternPool.LoadedUni
3629736659 return sema.failWithOwnedErrorMsg(&block_scope, msg);
3629836660 } else if (layout == .@"packed" and !try sema.validatePackedType(field_ty)) {
3629936661 const msg = msg: {
36300 const msg = try sema.errMsg(type_src, "packed unions cannot contain fields of type '{}'", .{field_ty.fmt(zcu)});
36662 const msg = try sema.errMsg(type_src, "packed unions cannot contain fields of type '{}'", .{field_ty.fmt(pt)});
3630136663 errdefer msg.destroy(sema.gpa);
3630236664
3630336665 try sema.explainWhyTypeIsNotPacked(msg, type_src, field_ty);
......@@ -36366,15 +36728,17 @@ fn generateUnionTagTypeNumbered(
3636636728 enum_field_vals: []const InternPool.Index,
3636736729 union_owner_decl: *Module.Decl,
3636836730) !InternPool.Index {
36369 const mod = sema.mod;
36731 const pt = sema.pt;
36732 const mod = pt.zcu;
3637036733 const gpa = sema.gpa;
3637136734 const ip = &mod.intern_pool;
3637236735
3637336736 const new_decl_index = try mod.allocateNewDecl(block.namespace);
3637436737 errdefer mod.destroyDecl(new_decl_index);
36375 const fqn = try union_owner_decl.fullyQualifiedName(mod);
36738 const fqn = try union_owner_decl.fullyQualifiedName(pt);
3637636739 const name = try ip.getOrPutStringFmt(
3637736740 gpa,
36741 pt.tid,
3637836742 "@typeInfo({}).Union.tag_type.?",
3637936743 .{fqn.fmt(ip)},
3638036744 .no_embedded_nulls,
......@@ -36390,11 +36754,11 @@ fn generateUnionTagTypeNumbered(
3639036754 new_decl.owns_tv = true;
3639136755 new_decl.name_fully_qualified = true;
3639236756
36393 const enum_ty = try ip.getGeneratedTagEnumType(gpa, .{
36757 const enum_ty = try ip.getGeneratedTagEnumType(gpa, pt.tid, .{
3639436758 .decl = new_decl_index,
3639536759 .owner_union_ty = union_owner_decl.val.toIntern(),
3639636760 .tag_ty = if (enum_field_vals.len == 0)
36397 (try mod.intType(.unsigned, 0)).toIntern()
36761 (try pt.intType(.unsigned, 0)).toIntern()
3639836762 else
3639936763 ip.typeOf(enum_field_vals[0]),
3640036764 .names = enum_field_names,
......@@ -36404,7 +36768,7 @@ fn generateUnionTagTypeNumbered(
3640436768
3640536769 new_decl.val = Value.fromInterned(enum_ty);
3640636770
36407 try mod.finalizeAnonDecl(new_decl_index);
36771 try pt.finalizeAnonDecl(new_decl_index);
3640836772 return enum_ty;
3640936773}
3641036774
......@@ -36414,16 +36778,18 @@ fn generateUnionTagTypeSimple(
3641436778 enum_field_names: []const InternPool.NullTerminatedString,
3641536779 union_owner_decl: *Module.Decl,
3641636780) !InternPool.Index {
36417 const mod = sema.mod;
36781 const pt = sema.pt;
36782 const mod = pt.zcu;
3641836783 const ip = &mod.intern_pool;
3641936784 const gpa = sema.gpa;
3642036785
3642136786 const new_decl_index = new_decl_index: {
36422 const fqn = try union_owner_decl.fullyQualifiedName(mod);
36787 const fqn = try union_owner_decl.fullyQualifiedName(pt);
3642336788 const new_decl_index = try mod.allocateNewDecl(block.namespace);
3642436789 errdefer mod.destroyDecl(new_decl_index);
3642536790 const name = try ip.getOrPutStringFmt(
3642636791 gpa,
36792 pt.tid,
3642736793 "@typeInfo({}).Union.tag_type.?",
3642836794 .{fqn.fmt(ip)},
3642936795 .no_embedded_nulls,
......@@ -36438,13 +36804,13 @@ fn generateUnionTagTypeSimple(
3643836804 };
3643936805 errdefer mod.abortAnonDecl(new_decl_index);
3644036806
36441 const enum_ty = try ip.getGeneratedTagEnumType(gpa, .{
36807 const enum_ty = try ip.getGeneratedTagEnumType(gpa, pt.tid, .{
3644236808 .decl = new_decl_index,
3644336809 .owner_union_ty = union_owner_decl.val.toIntern(),
3644436810 .tag_ty = if (enum_field_names.len == 0)
36445 (try mod.intType(.unsigned, 0)).toIntern()
36811 (try pt.intType(.unsigned, 0)).toIntern()
3644636812 else
36447 (try mod.smallestUnsignedInt(enum_field_names.len - 1)).toIntern(),
36813 (try pt.smallestUnsignedInt(enum_field_names.len - 1)).toIntern(),
3644836814 .names = enum_field_names,
3644936815 .values = &.{},
3645036816 .tag_mode = .auto,
......@@ -36454,7 +36820,7 @@ fn generateUnionTagTypeSimple(
3645436820 new_decl.owns_tv = true;
3645536821 new_decl.val = Value.fromInterned(enum_ty);
3645636822
36457 try mod.finalizeAnonDecl(new_decl_index);
36823 try pt.finalizeAnonDecl(new_decl_index);
3645836824 return enum_ty;
3645936825}
3646036826
......@@ -36464,12 +36830,13 @@ fn generateUnionTagTypeSimple(
3646436830/// that the types are already resolved.
3646536831/// TODO assert the return value matches `ty.onePossibleValue`
3646636832pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
36467 const zcu = sema.mod;
36833 const pt = sema.pt;
36834 const zcu = pt.zcu;
3646836835 const ip = &zcu.intern_pool;
3646936836 return switch (ty.toIntern()) {
3647036837 .u0_type,
3647136838 .i0_type,
36472 => try zcu.intValue(ty, 0),
36839 => try pt.intValue(ty, 0),
3647336840 .u1_type,
3647436841 .u8_type,
3647536842 .i8_type,
......@@ -36532,7 +36899,7 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3653236899 .anyframe_type => unreachable,
3653336900 .null_type => Value.null,
3653436901 .undefined_type => Value.undef,
36535 .optional_noreturn_type => try zcu.nullValue(ty),
36902 .optional_noreturn_type => try pt.nullValue(ty),
3653636903 .generic_poison_type => error.GenericPoison,
3653736904 .empty_struct_type => Value.empty_struct,
3653836905 // values, not types
......@@ -36558,7 +36925,7 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3655836925 .none,
3655936926 => unreachable,
3656036927
36561 _ => switch (ip.items.items(.tag)[@intFromEnum(ty.toIntern())]) {
36928 _ => switch (ty.toIntern().unwrap(ip).getTag(ip)) {
3656236929 .removed => unreachable,
3656336930
3656436931 .type_int_signed, // i0 handled above
......@@ -36646,16 +37013,16 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3664637013 => switch (ip.indexToKey(ty.toIntern())) {
3664737014 inline .array_type, .vector_type => |seq_type, seq_tag| {
3664837015 const has_sentinel = seq_tag == .array_type and seq_type.sentinel != .none;
36649 if (seq_type.len + @intFromBool(has_sentinel) == 0) return Value.fromInterned((try zcu.intern(.{ .aggregate = .{
37016 if (seq_type.len + @intFromBool(has_sentinel) == 0) return Value.fromInterned(try pt.intern(.{ .aggregate = .{
3665037017 .ty = ty.toIntern(),
3665137018 .storage = .{ .elems = &.{} },
36652 } })));
37019 } }));
3665337020
3665437021 if (try sema.typeHasOnePossibleValue(Type.fromInterned(seq_type.child))) |opv| {
36655 return Value.fromInterned((try zcu.intern(.{ .aggregate = .{
37022 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
3665637023 .ty = ty.toIntern(),
3665737024 .storage = .{ .repeated_elem = opv.toIntern() },
36658 } })));
37025 } }));
3665937026 }
3666037027 return null;
3666137028 },
......@@ -36663,17 +37030,17 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3666337030 .struct_type => {
3666437031 // Resolving the layout first helps to avoid loops.
3666537032 // If the type has a coherent layout, we can recurse through fields safely.
36666 try ty.resolveLayout(zcu);
37033 try ty.resolveLayout(pt);
3666737034
3666837035 const struct_type = ip.loadStructType(ty.toIntern());
3666937036
3667037037 if (struct_type.field_types.len == 0) {
3667137038 // In this case the struct has no fields at all and
3667237039 // therefore has one possible value.
36673 return Value.fromInterned((try zcu.intern(.{ .aggregate = .{
37040 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
3667437041 .ty = ty.toIntern(),
3667537042 .storage = .{ .elems = &.{} },
36676 } })));
37043 } }));
3667737044 }
3667837045
3667937046 const field_vals = try sema.arena.alloc(
......@@ -36682,7 +37049,7 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3668237049 );
3668337050 for (field_vals, 0..) |*field_val, i| {
3668437051 if (struct_type.fieldIsComptime(ip, i)) {
36685 try ty.resolveStructFieldInits(zcu);
37052 try ty.resolveStructFieldInits(pt);
3668637053 field_val.* = struct_type.field_inits.get(ip)[i];
3668737054 continue;
3668837055 }
......@@ -36694,10 +37061,10 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3669437061
3669537062 // In this case the struct has no runtime-known fields and
3669637063 // therefore has one possible value.
36697 return Value.fromInterned((try zcu.intern(.{ .aggregate = .{
37064 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
3669837065 .ty = ty.toIntern(),
3669937066 .storage = .{ .elems = field_vals },
36700 } })));
37067 } }));
3670137068 },
3670237069
3670337070 .anon_struct_type => |tuple| {
......@@ -36707,28 +37074,28 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3670737074 // In this case the struct has all comptime-known fields and
3670837075 // therefore has one possible value.
3670937076 // TODO: write something like getCoercedInts to avoid needing to dupe
36710 return Value.fromInterned((try zcu.intern(.{ .aggregate = .{
37077 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
3671137078 .ty = ty.toIntern(),
3671237079 .storage = .{ .elems = try sema.arena.dupe(InternPool.Index, tuple.values.get(ip)) },
36713 } })));
37080 } }));
3671437081 },
3671537082
3671637083 .union_type => {
3671737084 // Resolving the layout first helps to avoid loops.
3671837085 // If the type has a coherent layout, we can recurse through fields safely.
36719 try ty.resolveLayout(zcu);
37086 try ty.resolveLayout(pt);
3672037087
3672137088 const union_obj = ip.loadUnionType(ty.toIntern());
3672237089 const tag_val = (try sema.typeHasOnePossibleValue(Type.fromInterned(union_obj.tagTypePtr(ip).*))) orelse
3672337090 return null;
3672437091 if (union_obj.field_types.len == 0) {
36725 const only = try zcu.intern(.{ .empty_enum_value = ty.toIntern() });
37092 const only = try pt.intern(.{ .empty_enum_value = ty.toIntern() });
3672637093 return Value.fromInterned(only);
3672737094 }
3672837095 const only_field_ty = Type.fromInterned(union_obj.field_types.get(ip)[0]);
3672937096 const val_val = (try sema.typeHasOnePossibleValue(only_field_ty)) orelse
3673037097 return null;
36731 const only = try zcu.intern(.{ .un = .{
37098 const only = try pt.intern(.{ .un = .{
3673237099 .ty = ty.toIntern(),
3673337100 .tag = tag_val.toIntern(),
3673437101 .val = val_val.toIntern(),
......@@ -36743,7 +37110,7 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3674337110 if (enum_type.tag_ty == .comptime_int_type) return null;
3674437111
3674537112 if (try sema.typeHasOnePossibleValue(Type.fromInterned(enum_type.tag_ty))) |int_opv| {
36746 const only = try zcu.intern(.{ .enum_tag = .{
37113 const only = try pt.intern(.{ .enum_tag = .{
3674737114 .ty = ty.toIntern(),
3674837115 .int = int_opv.toIntern(),
3674937116 } });
......@@ -36753,18 +37120,19 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3675337120 return null;
3675437121 },
3675537122 .auto, .explicit => {
36756 if (Type.fromInterned(enum_type.tag_ty).hasRuntimeBits(zcu)) return null;
37123 if (Type.fromInterned(enum_type.tag_ty).hasRuntimeBits(pt)) return null;
3675737124
3675837125 return Value.fromInterned(switch (enum_type.names.len) {
36759 0 => try zcu.intern(.{ .empty_enum_value = ty.toIntern() }),
36760 1 => try zcu.intern(.{ .enum_tag = .{
37126 0 => try pt.intern(.{ .empty_enum_value = ty.toIntern() }),
37127 1 => try pt.intern(.{ .enum_tag = .{
3676137128 .ty = ty.toIntern(),
3676237129 .int = if (enum_type.values.len == 0)
36763 (try zcu.intValue(Type.fromInterned(enum_type.tag_ty), 0)).toIntern()
37130 (try pt.intValue(Type.fromInterned(enum_type.tag_ty), 0)).toIntern()
3676437131 else
36765 try zcu.intern_pool.getCoercedInts(
37132 try ip.getCoercedInts(
3676637133 zcu.gpa,
36767 zcu.intern_pool.indexToKey(enum_type.values.get(ip)[0]).int,
37134 pt.tid,
37135 ip.indexToKey(enum_type.values.get(ip)[0]).int,
3676837136 enum_type.tag_ty,
3676937137 ),
3677037138 } }),
......@@ -36782,7 +37150,7 @@ pub fn typeHasOnePossibleValue(sema: *Sema, ty: Type) CompileError!?Value {
3678237150
3678337151/// Returns the type of the AIR instruction.
3678437152fn typeOf(sema: *Sema, inst: Air.Inst.Ref) Type {
36785 return sema.getTmpAir().typeOf(inst, &sema.mod.intern_pool);
37153 return sema.getTmpAir().typeOf(inst, &sema.pt.zcu.intern_pool);
3678637154}
3678737155
3678837156pub fn getTmpAir(sema: Sema) Air {
......@@ -36838,12 +37206,13 @@ fn analyzeComptimeAlloc(
3683837206 var_type: Type,
3683937207 alignment: Alignment,
3684037208) CompileError!Air.Inst.Ref {
36841 const mod = sema.mod;
37209 const pt = sema.pt;
37210 const mod = pt.zcu;
3684237211
3684337212 // Needed to make an anon decl with type `var_type` (the `finish()` call below).
3684437213 _ = try sema.typeHasOnePossibleValue(var_type);
3684537214
36846 const ptr_type = try mod.ptrTypeSema(.{
37215 const ptr_type = try pt.ptrTypeSema(.{
3684737216 .child = var_type.toIntern(),
3684837217 .flags = .{
3684937218 .alignment = alignment,
......@@ -36853,7 +37222,7 @@ fn analyzeComptimeAlloc(
3685337222
3685437223 const alloc = try sema.newComptimeAlloc(block, var_type, alignment);
3685537224
36856 return Air.internedToRef((try mod.intern(.{ .ptr = .{
37225 return Air.internedToRef((try pt.intern(.{ .ptr = .{
3685737226 .ty = ptr_type.toIntern(),
3685837227 .base_addr = .{ .comptime_alloc = alloc },
3685937228 .byte_offset = 0,
......@@ -36896,13 +37265,14 @@ pub fn analyzeAsAddressSpace(
3689637265 air_ref: Air.Inst.Ref,
3689737266 ctx: AddressSpaceContext,
3689837267) !std.builtin.AddressSpace {
36899 const mod = sema.mod;
37268 const pt = sema.pt;
37269 const mod = pt.zcu;
3690037270 const coerced = try sema.coerce(block, Type.fromInterned(.address_space_type), air_ref, src);
3690137271 const addrspace_val = try sema.resolveConstDefinedValue(block, src, coerced, .{
3690237272 .needed_comptime_reason = "address space must be comptime-known",
3690337273 });
3690437274 const address_space = mod.toEnum(std.builtin.AddressSpace, addrspace_val);
36905 const target = sema.mod.getTarget();
37275 const target = pt.zcu.getTarget();
3690637276 const arch = target.cpu.arch;
3690737277
3690837278 const is_nv = arch == .nvptx or arch == .nvptx64;
......@@ -36946,7 +37316,8 @@ pub fn analyzeAsAddressSpace(
3694637316/// Returns `null` if the pointer contents cannot be loaded at comptime.
3694737317fn pointerDeref(sema: *Sema, block: *Block, src: LazySrcLoc, ptr_val: Value, ptr_ty: Type) CompileError!?Value {
3694837318 // TODO: audit use sites to eliminate this coercion
36949 const coerced_ptr_val = try sema.mod.getCoerced(ptr_val, ptr_ty);
37319 const pt = sema.pt;
37320 const coerced_ptr_val = try pt.getCoerced(ptr_val, ptr_ty);
3695037321 switch (try sema.pointerDerefExtra(block, src, coerced_ptr_val)) {
3695137322 .runtime_load => return null,
3695237323 .val => |v| return v,
......@@ -36954,13 +37325,13 @@ fn pointerDeref(sema: *Sema, block: *Block, src: LazySrcLoc, ptr_val: Value, ptr
3695437325 block,
3695537326 src,
3695637327 "comptime dereference requires '{}' to have a well-defined layout",
36957 .{ty.fmt(sema.mod)},
37328 .{ty.fmt(pt)},
3695837329 ),
3695937330 .out_of_bounds => |ty| return sema.fail(
3696037331 block,
3696137332 src,
3696237333 "dereference of '{}' exceeds bounds of containing decl of type '{}'",
36963 .{ ptr_ty.fmt(sema.mod), ty.fmt(sema.mod) },
37334 .{ ptr_ty.fmt(pt), ty.fmt(pt) },
3696437335 ),
3696537336 }
3696637337}
......@@ -36973,10 +37344,10 @@ const DerefResult = union(enum) {
3697337344};
3697437345
3697537346fn pointerDerefExtra(sema: *Sema, block: *Block, src: LazySrcLoc, ptr_val: Value) CompileError!DerefResult {
36976 const zcu = sema.mod;
36977 const ip = &zcu.intern_pool;
37347 const pt = sema.pt;
37348 const ip = &pt.zcu.intern_pool;
3697837349 switch (try sema.loadComptimePtr(block, src, ptr_val)) {
36979 .success => |mv| return .{ .val = try mv.intern(zcu, sema.arena) },
37350 .success => |mv| return .{ .val = try mv.intern(pt, sema.arena) },
3698037351 .runtime_load => return .runtime_load,
3698137352 .undef => return sema.failWithUseOfUndef(block, src),
3698237353 .err_payload => |err_name| return sema.fail(block, src, "attempt to unwrap error: {}", .{err_name.fmt(ip)}),
......@@ -37001,7 +37372,8 @@ fn usizeCast(sema: *Sema, block: *Block, src: LazySrcLoc, int: u64) CompileError
3700137372/// a type has zero bits, which can cause a "foo depends on itself" compile error.
3700237373/// This logic must be kept in sync with `Type.isPtrLikeOptional`.
3700337374fn typePtrOrOptionalPtrTy(sema: *Sema, ty: Type) !?Type {
37004 const mod = sema.mod;
37375 const pt = sema.pt;
37376 const mod = pt.zcu;
3700537377 return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
3700637378 .ptr_type => |ptr_type| switch (ptr_type.flags.size) {
3700737379 .One, .Many, .C => ty,
......@@ -37031,27 +37403,28 @@ fn typePtrOrOptionalPtrTy(sema: *Sema, ty: Type) !?Type {
3703137403/// `generic_poison` will return false.
3703237404/// May return false negatives when structs and unions are having their field types resolved.
3703337405pub fn typeRequiresComptime(sema: *Sema, ty: Type) SemaError!bool {
37034 return ty.comptimeOnlyAdvanced(sema.mod, .sema);
37406 return ty.comptimeOnlyAdvanced(sema.pt, .sema);
3703537407}
3703637408
3703737409pub fn typeHasRuntimeBits(sema: *Sema, ty: Type) SemaError!bool {
37038 return ty.hasRuntimeBitsAdvanced(sema.mod, false, .sema) catch |err| switch (err) {
37410 return ty.hasRuntimeBitsAdvanced(sema.pt, false, .sema) catch |err| switch (err) {
3703937411 error.NeedLazy => unreachable,
3704037412 else => |e| return e,
3704137413 };
3704237414}
3704337415
3704437416pub fn typeAbiSize(sema: *Sema, ty: Type) SemaError!u64 {
37045 try ty.resolveLayout(sema.mod);
37046 return ty.abiSize(sema.mod);
37417 const pt = sema.pt;
37418 try ty.resolveLayout(pt);
37419 return ty.abiSize(pt);
3704737420}
3704837421
3704937422pub fn typeAbiAlignment(sema: *Sema, ty: Type) SemaError!Alignment {
37050 return (try ty.abiAlignmentAdvanced(sema.mod, .sema)).scalar;
37423 return (try ty.abiAlignmentAdvanced(sema.pt, .sema)).scalar;
3705137424}
3705237425
3705337426pub fn fnHasRuntimeBits(sema: *Sema, ty: Type) CompileError!bool {
37054 return ty.fnHasRuntimeBitsAdvanced(sema.mod, .sema);
37427 return ty.fnHasRuntimeBitsAdvanced(sema.pt, .sema);
3705537428}
3705637429
3705737430fn unionFieldIndex(
......@@ -37061,9 +37434,10 @@ fn unionFieldIndex(
3706137434 field_name: InternPool.NullTerminatedString,
3706237435 field_src: LazySrcLoc,
3706337436) !u32 {
37064 const mod = sema.mod;
37437 const pt = sema.pt;
37438 const mod = pt.zcu;
3706537439 const ip = &mod.intern_pool;
37066 try union_ty.resolveFields(mod);
37440 try union_ty.resolveFields(pt);
3706737441 const union_obj = mod.typeToUnion(union_ty).?;
3706837442 const field_index = union_obj.loadTagType(ip).nameIndex(ip, field_name) orelse
3706937443 return sema.failWithBadUnionFieldAccess(block, union_ty, union_obj, field_src, field_name);
......@@ -37077,9 +37451,10 @@ fn structFieldIndex(
3707737451 field_name: InternPool.NullTerminatedString,
3707837452 field_src: LazySrcLoc,
3707937453) !u32 {
37080 const mod = sema.mod;
37454 const pt = sema.pt;
37455 const mod = pt.zcu;
3708137456 const ip = &mod.intern_pool;
37082 try struct_ty.resolveFields(mod);
37457 try struct_ty.resolveFields(pt);
3708337458 if (struct_ty.isAnonStruct(mod)) {
3708437459 return sema.anonStructFieldIndex(block, struct_ty, field_name, field_src);
3708537460 } else {
......@@ -37096,7 +37471,8 @@ fn anonStructFieldIndex(
3709637471 field_name: InternPool.NullTerminatedString,
3709737472 field_src: LazySrcLoc,
3709837473) !u32 {
37099 const mod = sema.mod;
37474 const pt = sema.pt;
37475 const mod = pt.zcu;
3710037476 const ip = &mod.intern_pool;
3710137477 switch (ip.indexToKey(struct_ty.toIntern())) {
3710237478 .anon_struct_type => |anon_struct_type| for (anon_struct_type.names.get(ip), 0..) |name, i| {
......@@ -37106,20 +37482,21 @@ fn anonStructFieldIndex(
3710637482 else => unreachable,
3710737483 }
3710837484 return sema.fail(block, field_src, "no field named '{}' in anonymous struct '{}'", .{
37109 field_name.fmt(ip), struct_ty.fmt(sema.mod),
37485 field_name.fmt(ip), struct_ty.fmt(pt),
3711037486 });
3711137487}
3711237488
3711337489/// If the value overflowed the type, returns a comptime_int (or vector thereof) instead, setting
3711437490/// overflow_idx to the vector index the overflow was at (or 0 for a scalar).
3711537491fn intAdd(sema: *Sema, lhs: Value, rhs: Value, ty: Type, overflow_idx: *?usize) !Value {
37492 const pt = sema.pt;
3711637493 var overflow: usize = undefined;
3711737494 return sema.intAddInner(lhs, rhs, ty, &overflow) catch |err| switch (err) {
3711837495 error.Overflow => {
37119 const is_vec = ty.isVector(sema.mod);
37496 const is_vec = ty.isVector(pt.zcu);
3712037497 overflow_idx.* = if (is_vec) overflow else 0;
37121 const safe_ty = if (is_vec) try sema.mod.vectorType(.{
37122 .len = ty.vectorLen(sema.mod),
37498 const safe_ty = if (is_vec) try pt.vectorType(.{
37499 .len = ty.vectorLen(pt.zcu),
3712337500 .child = .comptime_int_type,
3712437501 }) else Type.comptime_int;
3712537502 return sema.intAddInner(lhs, rhs, safe_ty, undefined) catch |err1| switch (err1) {
......@@ -37132,13 +37509,14 @@ fn intAdd(sema: *Sema, lhs: Value, rhs: Value, ty: Type, overflow_idx: *?usize)
3713237509}
3713337510
3713437511fn intAddInner(sema: *Sema, lhs: Value, rhs: Value, ty: Type, overflow_idx: *usize) !Value {
37135 const mod = sema.mod;
37512 const pt = sema.pt;
37513 const mod = pt.zcu;
3713637514 if (ty.zigTypeTag(mod) == .Vector) {
3713737515 const result_data = try sema.arena.alloc(InternPool.Index, ty.vectorLen(mod));
3713837516 const scalar_ty = ty.scalarType(mod);
3713937517 for (result_data, 0..) |*scalar, i| {
37140 const lhs_elem = try lhs.elemValue(mod, i);
37141 const rhs_elem = try rhs.elemValue(mod, i);
37518 const lhs_elem = try lhs.elemValue(pt, i);
37519 const rhs_elem = try rhs.elemValue(pt, i);
3714237520 const val = sema.intAddScalar(lhs_elem, rhs_elem, scalar_ty) catch |err| switch (err) {
3714337521 error.Overflow => {
3714437522 overflow_idx.* = i;
......@@ -37148,34 +37526,34 @@ fn intAddInner(sema: *Sema, lhs: Value, rhs: Value, ty: Type, overflow_idx: *usi
3714837526 };
3714937527 scalar.* = val.toIntern();
3715037528 }
37151 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
37529 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
3715237530 .ty = ty.toIntern(),
3715337531 .storage = .{ .elems = result_data },
37154 } })));
37532 } }));
3715537533 }
3715637534 return sema.intAddScalar(lhs, rhs, ty);
3715737535}
3715837536
3715937537fn intAddScalar(sema: *Sema, lhs: Value, rhs: Value, scalar_ty: Type) !Value {
37160 const mod = sema.mod;
37538 const pt = sema.pt;
3716137539 if (scalar_ty.toIntern() != .comptime_int_type) {
3716237540 const res = try sema.intAddWithOverflowScalar(lhs, rhs, scalar_ty);
37163 if (res.overflow_bit.compareAllWithZero(.neq, mod)) return error.Overflow;
37541 if (res.overflow_bit.compareAllWithZero(.neq, pt)) return error.Overflow;
3716437542 return res.wrapped_result;
3716537543 }
3716637544 // TODO is this a performance issue? maybe we should try the operation without
3716737545 // resorting to BigInt first.
3716837546 var lhs_space: Value.BigIntSpace = undefined;
3716937547 var rhs_space: Value.BigIntSpace = undefined;
37170 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, mod, .sema);
37171 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, mod, .sema);
37548 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, pt, .sema);
37549 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, pt, .sema);
3717237550 const limbs = try sema.arena.alloc(
3717337551 std.math.big.Limb,
3717437552 @max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,
3717537553 );
3717637554 var result_bigint = std.math.big.int.Mutable{ .limbs = limbs, .positive = undefined, .len = undefined };
3717737555 result_bigint.add(lhs_bigint, rhs_bigint);
37178 return mod.intValue_big(scalar_ty, result_bigint.toConst());
37556 return pt.intValue_big(scalar_ty, result_bigint.toConst());
3717937557}
3718037558
3718137559/// Supports both floats and ints; handles undefined.
......@@ -37185,15 +37563,16 @@ fn numberAddWrapScalar(
3718537563 rhs: Value,
3718637564 ty: Type,
3718737565) !Value {
37188 const mod = sema.mod;
37189 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return mod.undefValue(ty);
37566 const pt = sema.pt;
37567 const mod = pt.zcu;
37568 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return pt.undefValue(ty);
3719037569
3719137570 if (ty.zigTypeTag(mod) == .ComptimeInt) {
3719237571 return sema.intAdd(lhs, rhs, ty, undefined);
3719337572 }
3719437573
3719537574 if (ty.isAnyFloat()) {
37196 return Value.floatAdd(lhs, rhs, ty, sema.arena, mod);
37575 return Value.floatAdd(lhs, rhs, ty, sema.arena, pt);
3719737576 }
3719837577
3719937578 const overflow_result = try sema.intAddWithOverflow(lhs, rhs, ty);
......@@ -37203,13 +37582,14 @@ fn numberAddWrapScalar(
3720337582/// If the value overflowed the type, returns a comptime_int (or vector thereof) instead, setting
3720437583/// overflow_idx to the vector index the overflow was at (or 0 for a scalar).
3720537584fn intSub(sema: *Sema, lhs: Value, rhs: Value, ty: Type, overflow_idx: *?usize) !Value {
37585 const pt = sema.pt;
3720637586 var overflow: usize = undefined;
3720737587 return sema.intSubInner(lhs, rhs, ty, &overflow) catch |err| switch (err) {
3720837588 error.Overflow => {
37209 const is_vec = ty.isVector(sema.mod);
37589 const is_vec = ty.isVector(pt.zcu);
3721037590 overflow_idx.* = if (is_vec) overflow else 0;
37211 const safe_ty = if (is_vec) try sema.mod.vectorType(.{
37212 .len = ty.vectorLen(sema.mod),
37591 const safe_ty = if (is_vec) try pt.vectorType(.{
37592 .len = ty.vectorLen(pt.zcu),
3721337593 .child = .comptime_int_type,
3721437594 }) else Type.comptime_int;
3721537595 return sema.intSubInner(lhs, rhs, safe_ty, undefined) catch |err1| switch (err1) {
......@@ -37222,13 +37602,13 @@ fn intSub(sema: *Sema, lhs: Value, rhs: Value, ty: Type, overflow_idx: *?usize)
3722237602}
3722337603
3722437604fn intSubInner(sema: *Sema, lhs: Value, rhs: Value, ty: Type, overflow_idx: *usize) !Value {
37225 const mod = sema.mod;
37226 if (ty.zigTypeTag(mod) == .Vector) {
37227 const result_data = try sema.arena.alloc(InternPool.Index, ty.vectorLen(mod));
37228 const scalar_ty = ty.scalarType(mod);
37605 const pt = sema.pt;
37606 if (ty.zigTypeTag(pt.zcu) == .Vector) {
37607 const result_data = try sema.arena.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
37608 const scalar_ty = ty.scalarType(pt.zcu);
3722937609 for (result_data, 0..) |*scalar, i| {
37230 const lhs_elem = try lhs.elemValue(sema.mod, i);
37231 const rhs_elem = try rhs.elemValue(sema.mod, i);
37610 const lhs_elem = try lhs.elemValue(pt, i);
37611 const rhs_elem = try rhs.elemValue(pt, i);
3723237612 const val = sema.intSubScalar(lhs_elem, rhs_elem, scalar_ty) catch |err| switch (err) {
3723337613 error.Overflow => {
3723437614 overflow_idx.* = i;
......@@ -37238,34 +37618,34 @@ fn intSubInner(sema: *Sema, lhs: Value, rhs: Value, ty: Type, overflow_idx: *usi
3723837618 };
3723937619 scalar.* = val.toIntern();
3724037620 }
37241 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
37621 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
3724237622 .ty = ty.toIntern(),
3724337623 .storage = .{ .elems = result_data },
37244 } })));
37624 } }));
3724537625 }
3724637626 return sema.intSubScalar(lhs, rhs, ty);
3724737627}
3724837628
3724937629fn intSubScalar(sema: *Sema, lhs: Value, rhs: Value, scalar_ty: Type) !Value {
37250 const mod = sema.mod;
37630 const pt = sema.pt;
3725137631 if (scalar_ty.toIntern() != .comptime_int_type) {
3725237632 const res = try sema.intSubWithOverflowScalar(lhs, rhs, scalar_ty);
37253 if (res.overflow_bit.compareAllWithZero(.neq, mod)) return error.Overflow;
37633 if (res.overflow_bit.compareAllWithZero(.neq, pt)) return error.Overflow;
3725437634 return res.wrapped_result;
3725537635 }
3725637636 // TODO is this a performance issue? maybe we should try the operation without
3725737637 // resorting to BigInt first.
3725837638 var lhs_space: Value.BigIntSpace = undefined;
3725937639 var rhs_space: Value.BigIntSpace = undefined;
37260 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, mod, .sema);
37261 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, mod, .sema);
37640 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, pt, .sema);
37641 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, pt, .sema);
3726237642 const limbs = try sema.arena.alloc(
3726337643 std.math.big.Limb,
3726437644 @max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1,
3726537645 );
3726637646 var result_bigint = std.math.big.int.Mutable{ .limbs = limbs, .positive = undefined, .len = undefined };
3726737647 result_bigint.sub(lhs_bigint, rhs_bigint);
37268 return mod.intValue_big(scalar_ty, result_bigint.toConst());
37648 return pt.intValue_big(scalar_ty, result_bigint.toConst());
3726937649}
3727037650
3727137651/// Supports both floats and ints; handles undefined.
......@@ -37275,15 +37655,16 @@ fn numberSubWrapScalar(
3727537655 rhs: Value,
3727637656 ty: Type,
3727737657) !Value {
37278 const mod = sema.mod;
37279 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return mod.undefValue(ty);
37658 const pt = sema.pt;
37659 const mod = pt.zcu;
37660 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return pt.undefValue(ty);
3728037661
3728137662 if (ty.zigTypeTag(mod) == .ComptimeInt) {
3728237663 return sema.intSub(lhs, rhs, ty, undefined);
3728337664 }
3728437665
3728537666 if (ty.isAnyFloat()) {
37286 return Value.floatSub(lhs, rhs, ty, sema.arena, mod);
37667 return Value.floatSub(lhs, rhs, ty, sema.arena, pt);
3728737668 }
3728837669
3728937670 const overflow_result = try sema.intSubWithOverflow(lhs, rhs, ty);
......@@ -37296,28 +37677,29 @@ fn intSubWithOverflow(
3729637677 rhs: Value,
3729737678 ty: Type,
3729837679) !Value.OverflowArithmeticResult {
37299 const mod = sema.mod;
37680 const pt = sema.pt;
37681 const mod = pt.zcu;
3730037682 if (ty.zigTypeTag(mod) == .Vector) {
3730137683 const vec_len = ty.vectorLen(mod);
3730237684 const overflowed_data = try sema.arena.alloc(InternPool.Index, vec_len);
3730337685 const result_data = try sema.arena.alloc(InternPool.Index, vec_len);
3730437686 const scalar_ty = ty.scalarType(mod);
3730537687 for (overflowed_data, result_data, 0..) |*of, *scalar, i| {
37306 const lhs_elem = try lhs.elemValue(sema.mod, i);
37307 const rhs_elem = try rhs.elemValue(sema.mod, i);
37688 const lhs_elem = try lhs.elemValue(pt, i);
37689 const rhs_elem = try rhs.elemValue(pt, i);
3730837690 const of_math_result = try sema.intSubWithOverflowScalar(lhs_elem, rhs_elem, scalar_ty);
3730937691 of.* = of_math_result.overflow_bit.toIntern();
3731037692 scalar.* = of_math_result.wrapped_result.toIntern();
3731137693 }
3731237694 return Value.OverflowArithmeticResult{
37313 .overflow_bit = Value.fromInterned((try mod.intern(.{ .aggregate = .{
37314 .ty = (try mod.vectorType(.{ .len = vec_len, .child = .u1_type })).toIntern(),
37695 .overflow_bit = Value.fromInterned(try pt.intern(.{ .aggregate = .{
37696 .ty = (try pt.vectorType(.{ .len = vec_len, .child = .u1_type })).toIntern(),
3731537697 .storage = .{ .elems = overflowed_data },
37316 } }))),
37317 .wrapped_result = Value.fromInterned((try mod.intern(.{ .aggregate = .{
37698 } })),
37699 .wrapped_result = Value.fromInterned(try pt.intern(.{ .aggregate = .{
3731837700 .ty = ty.toIntern(),
3731937701 .storage = .{ .elems = result_data },
37320 } }))),
37702 } })),
3732137703 };
3732237704 }
3732337705 return sema.intSubWithOverflowScalar(lhs, rhs, ty);
......@@ -37329,29 +37711,30 @@ fn intSubWithOverflowScalar(
3732937711 rhs: Value,
3733037712 ty: Type,
3733137713) !Value.OverflowArithmeticResult {
37332 const mod = sema.mod;
37714 const pt = sema.pt;
37715 const mod = pt.zcu;
3733337716 const info = ty.intInfo(mod);
3733437717
3733537718 if (lhs.isUndef(mod) or rhs.isUndef(mod)) {
3733637719 return .{
37337 .overflow_bit = try mod.undefValue(Type.u1),
37338 .wrapped_result = try mod.undefValue(ty),
37720 .overflow_bit = try pt.undefValue(Type.u1),
37721 .wrapped_result = try pt.undefValue(ty),
3733937722 };
3734037723 }
3734137724
3734237725 var lhs_space: Value.BigIntSpace = undefined;
3734337726 var rhs_space: Value.BigIntSpace = undefined;
37344 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, mod, .sema);
37345 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, mod, .sema);
37727 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, pt, .sema);
37728 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, pt, .sema);
3734637729 const limbs = try sema.arena.alloc(
3734737730 std.math.big.Limb,
3734837731 std.math.big.int.calcTwosCompLimbCount(info.bits),
3734937732 );
3735037733 var result_bigint = std.math.big.int.Mutable{ .limbs = limbs, .positive = undefined, .len = undefined };
3735137734 const overflowed = result_bigint.subWrap(lhs_bigint, rhs_bigint, info.signedness, info.bits);
37352 const wrapped_result = try mod.intValue_big(ty, result_bigint.toConst());
37735 const wrapped_result = try pt.intValue_big(ty, result_bigint.toConst());
3735337736 return Value.OverflowArithmeticResult{
37354 .overflow_bit = try mod.intValue(Type.u1, @intFromBool(overflowed)),
37737 .overflow_bit = try pt.intValue(Type.u1, @intFromBool(overflowed)),
3735537738 .wrapped_result = wrapped_result,
3735637739 };
3735737740}
......@@ -37367,17 +37750,18 @@ fn intFromFloat(
3736737750 int_ty: Type,
3736837751 mode: IntFromFloatMode,
3736937752) CompileError!Value {
37370 const mod = sema.mod;
37753 const pt = sema.pt;
37754 const mod = pt.zcu;
3737137755 if (float_ty.zigTypeTag(mod) == .Vector) {
3737237756 const result_data = try sema.arena.alloc(InternPool.Index, float_ty.vectorLen(mod));
3737337757 for (result_data, 0..) |*scalar, i| {
37374 const elem_val = try val.elemValue(sema.mod, i);
37758 const elem_val = try val.elemValue(pt, i);
3737537759 scalar.* = (try sema.intFromFloatScalar(block, src, elem_val, int_ty.scalarType(mod), mode)).toIntern();
3737637760 }
37377 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
37761 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
3737837762 .ty = int_ty.toIntern(),
3737937763 .storage = .{ .elems = result_data },
37380 } })));
37764 } }));
3738137765 }
3738237766 return sema.intFromFloatScalar(block, src, val, int_ty, mode);
3738337767}
......@@ -37415,7 +37799,8 @@ fn intFromFloatScalar(
3741537799 int_ty: Type,
3741637800 mode: IntFromFloatMode,
3741737801) CompileError!Value {
37418 const mod = sema.mod;
37802 const pt = sema.pt;
37803 const mod = pt.zcu;
3741937804
3742037805 if (val.isUndef(mod)) return sema.failWithUseOfUndef(block, src);
3742137806
......@@ -37423,32 +37808,32 @@ fn intFromFloatScalar(
3742337808 block,
3742437809 src,
3742537810 "fractional component prevents float value '{}' from coercion to type '{}'",
37426 .{ val.fmtValue(mod, sema), int_ty.fmt(mod) },
37811 .{ val.fmtValue(pt, sema), int_ty.fmt(pt) },
3742737812 );
3742837813
37429 const float = val.toFloat(f128, mod);
37814 const float = val.toFloat(f128, pt);
3743037815 if (std.math.isNan(float)) {
3743137816 return sema.fail(block, src, "float value NaN cannot be stored in integer type '{}'", .{
37432 int_ty.fmt(sema.mod),
37817 int_ty.fmt(pt),
3743337818 });
3743437819 }
3743537820 if (std.math.isInf(float)) {
3743637821 return sema.fail(block, src, "float value Inf cannot be stored in integer type '{}'", .{
37437 int_ty.fmt(sema.mod),
37822 int_ty.fmt(pt),
3743837823 });
3743937824 }
3744037825
3744137826 var big_int = try float128IntPartToBigInt(sema.arena, float);
3744237827 defer big_int.deinit();
3744337828
37444 const cti_result = try mod.intValue_big(Type.comptime_int, big_int.toConst());
37829 const cti_result = try pt.intValue_big(Type.comptime_int, big_int.toConst());
3744537830
3744637831 if (!(try sema.intFitsInType(cti_result, int_ty, null))) {
3744737832 return sema.fail(block, src, "float value '{}' cannot be stored in integer type '{}'", .{
37448 val.fmtValue(sema.mod, sema), int_ty.fmt(sema.mod),
37833 val.fmtValue(pt, sema), int_ty.fmt(pt),
3744937834 });
3745037835 }
37451 return mod.getCoerced(cti_result, int_ty);
37836 return pt.getCoerced(cti_result, int_ty);
3745237837}
3745337838
3745437839/// Asserts the value is an integer, and the destination type is ComptimeInt or Int.
......@@ -37461,7 +37846,8 @@ fn intFitsInType(
3746137846 ty: Type,
3746237847 vector_index: ?*usize,
3746337848) CompileError!bool {
37464 const mod = sema.mod;
37849 const pt = sema.pt;
37850 const mod = pt.zcu;
3746537851 if (ty.toIntern() == .comptime_int_type) return true;
3746637852 const info = ty.intInfo(mod);
3746737853 switch (val.toIntern()) {
......@@ -37528,22 +37914,23 @@ fn intFitsInType(
3752837914}
3752937915
3753037916fn intInRange(sema: *Sema, tag_ty: Type, int_val: Value, end: usize) !bool {
37531 const mod = sema.mod;
37532 if (!(try int_val.compareAllWithZeroSema(.gte, mod))) return false;
37533 const end_val = try mod.intValue(tag_ty, end);
37917 const pt = sema.pt;
37918 if (!(try int_val.compareAllWithZeroSema(.gte, pt))) return false;
37919 const end_val = try pt.intValue(tag_ty, end);
3753437920 if (!(try sema.compareAll(int_val, .lt, end_val, tag_ty))) return false;
3753537921 return true;
3753637922}
3753737923
3753837924/// Asserts the type is an enum.
3753937925fn enumHasInt(sema: *Sema, ty: Type, int: Value) CompileError!bool {
37540 const mod = sema.mod;
37926 const pt = sema.pt;
37927 const mod = pt.zcu;
3754137928 const enum_type = mod.intern_pool.loadEnumType(ty.toIntern());
3754237929 assert(enum_type.tag_mode != .nonexhaustive);
3754337930 // The `tagValueIndex` function call below relies on the type being the integer tag type.
3754437931 // `getCoerced` assumes the value will fit the new type.
3754537932 if (!(try sema.intFitsInType(int, Type.fromInterned(enum_type.tag_ty), null))) return false;
37546 const int_coerced = try mod.getCoerced(int, Type.fromInterned(enum_type.tag_ty));
37933 const int_coerced = try pt.getCoerced(int, Type.fromInterned(enum_type.tag_ty));
3754737934
3754837935 return enum_type.tagValueIndex(&mod.intern_pool, int_coerced.toIntern()) != null;
3754937936}
......@@ -37554,28 +37941,29 @@ fn intAddWithOverflow(
3755437941 rhs: Value,
3755537942 ty: Type,
3755637943) !Value.OverflowArithmeticResult {
37557 const mod = sema.mod;
37944 const pt = sema.pt;
37945 const mod = pt.zcu;
3755837946 if (ty.zigTypeTag(mod) == .Vector) {
3755937947 const vec_len = ty.vectorLen(mod);
3756037948 const overflowed_data = try sema.arena.alloc(InternPool.Index, vec_len);
3756137949 const result_data = try sema.arena.alloc(InternPool.Index, vec_len);
3756237950 const scalar_ty = ty.scalarType(mod);
3756337951 for (overflowed_data, result_data, 0..) |*of, *scalar, i| {
37564 const lhs_elem = try lhs.elemValue(sema.mod, i);
37565 const rhs_elem = try rhs.elemValue(sema.mod, i);
37952 const lhs_elem = try lhs.elemValue(pt, i);
37953 const rhs_elem = try rhs.elemValue(pt, i);
3756637954 const of_math_result = try sema.intAddWithOverflowScalar(lhs_elem, rhs_elem, scalar_ty);
3756737955 of.* = of_math_result.overflow_bit.toIntern();
3756837956 scalar.* = of_math_result.wrapped_result.toIntern();
3756937957 }
3757037958 return Value.OverflowArithmeticResult{
37571 .overflow_bit = Value.fromInterned((try mod.intern(.{ .aggregate = .{
37572 .ty = (try mod.vectorType(.{ .len = vec_len, .child = .u1_type })).toIntern(),
37959 .overflow_bit = Value.fromInterned(try pt.intern(.{ .aggregate = .{
37960 .ty = (try pt.vectorType(.{ .len = vec_len, .child = .u1_type })).toIntern(),
3757337961 .storage = .{ .elems = overflowed_data },
37574 } }))),
37575 .wrapped_result = Value.fromInterned((try mod.intern(.{ .aggregate = .{
37962 } })),
37963 .wrapped_result = Value.fromInterned(try pt.intern(.{ .aggregate = .{
3757637964 .ty = ty.toIntern(),
3757737965 .storage = .{ .elems = result_data },
37578 } }))),
37966 } })),
3757937967 };
3758037968 }
3758137969 return sema.intAddWithOverflowScalar(lhs, rhs, ty);
......@@ -37587,29 +37975,30 @@ fn intAddWithOverflowScalar(
3758737975 rhs: Value,
3758837976 ty: Type,
3758937977) !Value.OverflowArithmeticResult {
37590 const mod = sema.mod;
37978 const pt = sema.pt;
37979 const mod = pt.zcu;
3759137980 const info = ty.intInfo(mod);
3759237981
3759337982 if (lhs.isUndef(mod) or rhs.isUndef(mod)) {
3759437983 return .{
37595 .overflow_bit = try mod.undefValue(Type.u1),
37596 .wrapped_result = try mod.undefValue(ty),
37984 .overflow_bit = try pt.undefValue(Type.u1),
37985 .wrapped_result = try pt.undefValue(ty),
3759737986 };
3759837987 }
3759937988
3760037989 var lhs_space: Value.BigIntSpace = undefined;
3760137990 var rhs_space: Value.BigIntSpace = undefined;
37602 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, mod, .sema);
37603 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, mod, .sema);
37991 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_space, pt, .sema);
37992 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_space, pt, .sema);
3760437993 const limbs = try sema.arena.alloc(
3760537994 std.math.big.Limb,
3760637995 std.math.big.int.calcTwosCompLimbCount(info.bits),
3760737996 );
3760837997 var result_bigint = std.math.big.int.Mutable{ .limbs = limbs, .positive = undefined, .len = undefined };
3760937998 const overflowed = result_bigint.addWrap(lhs_bigint, rhs_bigint, info.signedness, info.bits);
37610 const result = try mod.intValue_big(ty, result_bigint.toConst());
37999 const result = try pt.intValue_big(ty, result_bigint.toConst());
3761138000 return Value.OverflowArithmeticResult{
37612 .overflow_bit = try mod.intValue(Type.u1, @intFromBool(overflowed)),
38001 .overflow_bit = try pt.intValue(Type.u1, @intFromBool(overflowed)),
3761338002 .wrapped_result = result,
3761438003 };
3761538004}
......@@ -37625,12 +38014,13 @@ fn compareAll(
3762538014 rhs: Value,
3762638015 ty: Type,
3762738016) CompileError!bool {
37628 const mod = sema.mod;
38017 const pt = sema.pt;
38018 const mod = pt.zcu;
3762938019 if (ty.zigTypeTag(mod) == .Vector) {
3763038020 var i: usize = 0;
3763138021 while (i < ty.vectorLen(mod)) : (i += 1) {
37632 const lhs_elem = try lhs.elemValue(sema.mod, i);
37633 const rhs_elem = try rhs.elemValue(sema.mod, i);
38022 const lhs_elem = try lhs.elemValue(pt, i);
38023 const rhs_elem = try rhs.elemValue(pt, i);
3763438024 if (!(try sema.compareScalar(lhs_elem, op, rhs_elem, ty.scalarType(mod)))) {
3763538025 return false;
3763638026 }
......@@ -37648,13 +38038,13 @@ fn compareScalar(
3764838038 rhs: Value,
3764938039 ty: Type,
3765038040) CompileError!bool {
37651 const mod = sema.mod;
37652 const coerced_lhs = try mod.getCoerced(lhs, ty);
37653 const coerced_rhs = try mod.getCoerced(rhs, ty);
38041 const pt = sema.pt;
38042 const coerced_lhs = try pt.getCoerced(lhs, ty);
38043 const coerced_rhs = try pt.getCoerced(rhs, ty);
3765438044 switch (op) {
3765538045 .eq => return sema.valuesEqual(coerced_lhs, coerced_rhs, ty),
3765638046 .neq => return !(try sema.valuesEqual(coerced_lhs, coerced_rhs, ty)),
37657 else => return Value.compareHeteroAdvanced(coerced_lhs, op, coerced_rhs, mod, .sema),
38047 else => return Value.compareHeteroAdvanced(coerced_lhs, op, coerced_rhs, pt, .sema),
3765838048 }
3765938049}
3766038050
......@@ -37664,7 +38054,7 @@ fn valuesEqual(
3766438054 rhs: Value,
3766538055 ty: Type,
3766638056) CompileError!bool {
37667 return lhs.eql(rhs, ty, sema.mod);
38057 return lhs.eql(rhs, ty, sema.pt.zcu);
3766838058}
3766938059
3767038060/// Asserts the values are comparable vectors of type `ty`.
......@@ -37675,29 +38065,30 @@ fn compareVector(
3767538065 rhs: Value,
3767638066 ty: Type,
3767738067) !Value {
37678 const mod = sema.mod;
38068 const pt = sema.pt;
38069 const mod = pt.zcu;
3767938070 assert(ty.zigTypeTag(mod) == .Vector);
3768038071 const result_data = try sema.arena.alloc(InternPool.Index, ty.vectorLen(mod));
3768138072 for (result_data, 0..) |*scalar, i| {
37682 const lhs_elem = try lhs.elemValue(sema.mod, i);
37683 const rhs_elem = try rhs.elemValue(sema.mod, i);
38073 const lhs_elem = try lhs.elemValue(pt, i);
38074 const rhs_elem = try rhs.elemValue(pt, i);
3768438075 const res_bool = try sema.compareScalar(lhs_elem, op, rhs_elem, ty.scalarType(mod));
3768538076 scalar.* = Value.makeBool(res_bool).toIntern();
3768638077 }
37687 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
37688 .ty = (try mod.vectorType(.{ .len = ty.vectorLen(mod), .child = .bool_type })).toIntern(),
38078 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
38079 .ty = (try pt.vectorType(.{ .len = ty.vectorLen(mod), .child = .bool_type })).toIntern(),
3768938080 .storage = .{ .elems = result_data },
37690 } })));
38081 } }));
3769138082}
3769238083
3769338084/// Merge lhs with rhs.
3769438085/// Asserts that lhs and rhs are both error sets and are resolved.
3769538086fn errorSetMerge(sema: *Sema, lhs: Type, rhs: Type) !Type {
37696 const mod = sema.mod;
37697 const ip = &mod.intern_pool;
38087 const pt = sema.pt;
38088 const ip = &pt.zcu.intern_pool;
3769838089 const arena = sema.arena;
37699 const lhs_names = lhs.errorSetNames(mod);
37700 const rhs_names = rhs.errorSetNames(mod);
38090 const lhs_names = lhs.errorSetNames(pt.zcu);
38091 const rhs_names = rhs.errorSetNames(pt.zcu);
3770138092 var names: InferredErrorSet.NameMap = .{};
3770238093 try names.ensureUnusedCapacity(arena, lhs_names.len);
3770338094
......@@ -37708,7 +38099,7 @@ fn errorSetMerge(sema: *Sema, lhs: Type, rhs: Type) !Type {
3770838099 try names.put(arena, rhs_names.get(ip)[rhs_index], {});
3770938100 }
3771038101
37711 return mod.errorSetFromUnsortedNames(names.keys());
38102 return pt.errorSetFromUnsortedNames(names.keys());
3771238103}
3771338104
3771438105/// Avoids crashing the compiler when asking if inferred allocations are noreturn.
......@@ -37718,7 +38109,7 @@ fn isNoReturn(sema: *Sema, ref: Air.Inst.Ref) bool {
3771838109 .inferred_alloc, .inferred_alloc_comptime => return false,
3771938110 else => {},
3772038111 };
37721 return sema.typeOf(ref).isNoReturn(sema.mod);
38112 return sema.typeOf(ref).isNoReturn(sema.pt.zcu);
3772238113}
3772338114
3772438115/// Avoids crashing the compiler when asking if inferred allocations are known to be a certain zig type.
......@@ -37727,11 +38118,12 @@ fn isKnownZigType(sema: *Sema, ref: Air.Inst.Ref, tag: std.builtin.TypeId) bool
3772738118 .inferred_alloc, .inferred_alloc_comptime => return false,
3772838119 else => {},
3772938120 };
37730 return sema.typeOf(ref).zigTypeTag(sema.mod) == tag;
38121 return sema.typeOf(ref).zigTypeTag(sema.pt.zcu) == tag;
3773138122}
3773238123
3773338124pub fn declareDependency(sema: *Sema, dependee: InternPool.Dependee) !void {
37734 if (!sema.mod.comp.debug_incremental) return;
38125 const zcu = sema.pt.zcu;
38126 if (!zcu.comp.debug_incremental) return;
3773538127
3773638128 // Avoid creating dependencies on ourselves. This situation can arise when we analyze the fields
3773738129 // of a type and they use `@This()`. This dependency would be unnecessary, and in fact would
......@@ -37747,11 +38139,11 @@ pub fn declareDependency(sema: *Sema, dependee: InternPool.Dependee) !void {
3774738139 else
3774838140 .{ .decl = sema.owner_decl_index },
3774938141 );
37750 try sema.mod.intern_pool.addDependency(sema.gpa, depender, dependee);
38142 try zcu.intern_pool.addDependency(sema.gpa, depender, dependee);
3775138143}
3775238144
3775338145fn isComptimeMutablePtr(sema: *Sema, val: Value) bool {
37754 return switch (sema.mod.intern_pool.indexToKey(val.toIntern())) {
38146 return switch (sema.pt.zcu.intern_pool.indexToKey(val.toIntern())) {
3775538147 .slice => |slice| sema.isComptimeMutablePtr(Value.fromInterned(slice.ptr)),
3775638148 .ptr => |ptr| switch (ptr.base_addr) {
3775738149 .anon_decl, .decl, .int => false,
......@@ -37766,7 +38158,7 @@ fn isComptimeMutablePtr(sema: *Sema, val: Value) bool {
3776638158
3776738159fn checkRuntimeValue(sema: *Sema, ptr: Air.Inst.Ref) bool {
3776838160 const val = ptr.toInterned() orelse return true;
37769 return !Value.fromInterned(val).canMutateComptimeVarState(sema.mod);
38161 return !Value.fromInterned(val).canMutateComptimeVarState(sema.pt.zcu);
3777038162}
3777138163
3777238164fn validateRuntimeValue(sema: *Sema, block: *Block, val_src: LazySrcLoc, val: Air.Inst.Ref) CompileError!void {
......@@ -37781,7 +38173,8 @@ fn validateRuntimeValue(sema: *Sema, block: *Block, val_src: LazySrcLoc, val: Ai
3778138173
3778238174/// Returns true if any value contained in `val` is undefined.
3778338175fn anyUndef(sema: *Sema, block: *Block, src: LazySrcLoc, val: Value) !bool {
37784 const mod = sema.mod;
38176 const pt = sema.pt;
38177 const mod = pt.zcu;
3778538178 return switch (mod.intern_pool.indexToKey(val.toIntern())) {
3778638179 .undef => true,
3778738180 .simple_value => |v| v == .undefined,
......@@ -37807,13 +38200,14 @@ fn sliceToIpString(
3780738200 slice_val: Value,
3780838201 reason: NeededComptimeReason,
3780938202) CompileError!InternPool.NullTerminatedString {
37810 const zcu = sema.mod;
38203 const pt = sema.pt;
38204 const zcu = pt.zcu;
3781138205 const slice_ty = slice_val.typeOf(zcu);
3781238206 assert(slice_ty.isSlice(zcu));
3781338207 assert(slice_ty.childType(zcu).toIntern() == .u8_type);
3781438208 const array_val = try sema.derefSliceAsArray(block, src, slice_val, reason);
3781538209 const array_ty = array_val.typeOf(zcu);
37816 return array_val.toIpString(array_ty, zcu);
38210 return array_val.toIpString(array_ty, pt);
3781738211}
3781838212
3781938213/// Given a slice value, attempts to dereference it into a comptime-known array.
......@@ -37840,7 +38234,8 @@ fn maybeDerefSliceAsArray(
3784038234 src: LazySrcLoc,
3784138235 slice_val: Value,
3784238236) CompileError!?Value {
37843 const zcu = sema.mod;
38237 const pt = sema.pt;
38238 const zcu = pt.zcu;
3784438239 const ip = &zcu.intern_pool;
3784538240 assert(slice_val.typeOf(zcu).isSlice(zcu));
3784638241 const slice = switch (ip.indexToKey(slice_val.toIntern())) {
......@@ -37849,19 +38244,19 @@ fn maybeDerefSliceAsArray(
3784938244 else => unreachable,
3785038245 };
3785138246 const elem_ty = Type.fromInterned(slice.ty).childType(zcu);
37852 const len = try Value.fromInterned(slice.len).toUnsignedIntSema(zcu);
37853 const array_ty = try zcu.arrayType(.{
38247 const len = try Value.fromInterned(slice.len).toUnsignedIntSema(pt);
38248 const array_ty = try pt.arrayType(.{
3785438249 .child = elem_ty.toIntern(),
3785538250 .len = len,
3785638251 });
37857 const ptr_ty = try zcu.ptrTypeSema(p: {
38252 const ptr_ty = try pt.ptrTypeSema(p: {
3785838253 var p = Type.fromInterned(slice.ty).ptrInfo(zcu);
3785938254 p.flags.size = .One;
3786038255 p.child = array_ty.toIntern();
3786138256 p.sentinel = .none;
3786238257 break :p p;
3786338258 });
37864 const casted_ptr = try zcu.getCoerced(Value.fromInterned(slice.ptr), ptr_ty);
38259 const casted_ptr = try pt.getCoerced(Value.fromInterned(slice.ptr), ptr_ty);
3786538260 return sema.pointerDeref(block, src, casted_ptr, ptr_ty);
3786638261}
3786738262
......@@ -37879,7 +38274,7 @@ fn analyzeUnreachable(sema: *Sema, block: *Block, src: LazySrcLoc, safety_check:
3787938274pub fn flushExports(sema: *Sema) !void {
3788038275 if (sema.exports.items.len == 0) return;
3788138276
37882 const zcu = sema.mod;
38277 const zcu = sema.pt.zcu;
3788338278 const gpa = zcu.gpa;
3788438279
3788538280 const unit = sema.ownerUnit();
src/Sema/bitcast.zig+96-92
......@@ -69,7 +69,8 @@ fn bitCastInner(
6969 host_bits: u64,
7070 bit_offset: u64,
7171) BitCastError!Value {
72 const zcu = sema.mod;
72 const pt = sema.pt;
73 const zcu = pt.zcu;
7374 const endian = zcu.getTarget().cpu.arch.endian();
7475
7576 if (dest_ty.toIntern() == val.typeOf(zcu).toIntern() and bit_offset == 0) {
......@@ -78,29 +79,29 @@ fn bitCastInner(
7879
7980 const val_ty = val.typeOf(zcu);
8081
81 try val_ty.resolveLayout(zcu);
82 try dest_ty.resolveLayout(zcu);
82 try val_ty.resolveLayout(pt);
83 try dest_ty.resolveLayout(pt);
8384
8485 assert(val_ty.hasWellDefinedLayout(zcu));
8586
8687 const abi_pad_bits, const host_pad_bits = if (host_bits > 0)
87 .{ val_ty.abiSize(zcu) * 8 - host_bits, host_bits - val_ty.bitSize(zcu) }
88 .{ val_ty.abiSize(pt) * 8 - host_bits, host_bits - val_ty.bitSize(pt) }
8889 else
89 .{ val_ty.abiSize(zcu) * 8 - val_ty.bitSize(zcu), 0 };
90 .{ val_ty.abiSize(pt) * 8 - val_ty.bitSize(pt), 0 };
9091
9192 const skip_bits = switch (endian) {
9293 .little => bit_offset + byte_offset * 8,
9394 .big => if (host_bits > 0)
94 val_ty.abiSize(zcu) * 8 - byte_offset * 8 - host_bits + bit_offset
95 val_ty.abiSize(pt) * 8 - byte_offset * 8 - host_bits + bit_offset
9596 else
96 val_ty.abiSize(zcu) * 8 - byte_offset * 8 - dest_ty.bitSize(zcu),
97 val_ty.abiSize(pt) * 8 - byte_offset * 8 - dest_ty.bitSize(pt),
9798 };
9899
99100 var unpack: UnpackValueBits = .{
100 .zcu = zcu,
101 .pt = sema.pt,
101102 .arena = sema.arena,
102103 .skip_bits = skip_bits,
103 .remaining_bits = dest_ty.bitSize(zcu),
104 .remaining_bits = dest_ty.bitSize(pt),
104105 .unpacked = std.ArrayList(InternPool.Index).init(sema.arena),
105106 };
106107 switch (endian) {
......@@ -116,7 +117,7 @@ fn bitCastInner(
116117 try unpack.padding(host_pad_bits);
117118
118119 var pack: PackValueBits = .{
119 .zcu = zcu,
120 .pt = sema.pt,
120121 .arena = sema.arena,
121122 .unpacked = unpack.unpacked.items,
122123 };
......@@ -131,33 +132,34 @@ fn bitCastSpliceInner(
131132 host_bits: u64,
132133 bit_offset: u64,
133134) BitCastError!Value {
134 const zcu = sema.mod;
135 const pt = sema.pt;
136 const zcu = pt.zcu;
135137 const endian = zcu.getTarget().cpu.arch.endian();
136138 const val_ty = val.typeOf(zcu);
137139 const splice_val_ty = splice_val.typeOf(zcu);
138140
139 try val_ty.resolveLayout(zcu);
140 try splice_val_ty.resolveLayout(zcu);
141 try val_ty.resolveLayout(pt);
142 try splice_val_ty.resolveLayout(pt);
141143
142 const splice_bits = splice_val_ty.bitSize(zcu);
144 const splice_bits = splice_val_ty.bitSize(pt);
143145
144146 const splice_offset = switch (endian) {
145147 .little => bit_offset + byte_offset * 8,
146148 .big => if (host_bits > 0)
147 val_ty.abiSize(zcu) * 8 - byte_offset * 8 - host_bits + bit_offset
149 val_ty.abiSize(pt) * 8 - byte_offset * 8 - host_bits + bit_offset
148150 else
149 val_ty.abiSize(zcu) * 8 - byte_offset * 8 - splice_bits,
151 val_ty.abiSize(pt) * 8 - byte_offset * 8 - splice_bits,
150152 };
151153
152 assert(splice_offset + splice_bits <= val_ty.abiSize(zcu) * 8);
154 assert(splice_offset + splice_bits <= val_ty.abiSize(pt) * 8);
153155
154156 const abi_pad_bits, const host_pad_bits = if (host_bits > 0)
155 .{ val_ty.abiSize(zcu) * 8 - host_bits, host_bits - val_ty.bitSize(zcu) }
157 .{ val_ty.abiSize(pt) * 8 - host_bits, host_bits - val_ty.bitSize(pt) }
156158 else
157 .{ val_ty.abiSize(zcu) * 8 - val_ty.bitSize(zcu), 0 };
159 .{ val_ty.abiSize(pt) * 8 - val_ty.bitSize(pt), 0 };
158160
159161 var unpack: UnpackValueBits = .{
160 .zcu = zcu,
162 .pt = pt,
161163 .arena = sema.arena,
162164 .skip_bits = 0,
163165 .remaining_bits = splice_offset,
......@@ -179,7 +181,7 @@ fn bitCastSpliceInner(
179181 try unpack.add(splice_val);
180182
181183 unpack.skip_bits = splice_offset + splice_bits;
182 unpack.remaining_bits = val_ty.abiSize(zcu) * 8 - splice_offset - splice_bits;
184 unpack.remaining_bits = val_ty.abiSize(pt) * 8 - splice_offset - splice_bits;
183185 switch (endian) {
184186 .little => {
185187 try unpack.add(val);
......@@ -193,7 +195,7 @@ fn bitCastSpliceInner(
193195 try unpack.padding(host_pad_bits);
194196
195197 var pack: PackValueBits = .{
196 .zcu = zcu,
198 .pt = pt,
197199 .arena = sema.arena,
198200 .unpacked = unpack.unpacked.items,
199201 };
......@@ -209,7 +211,7 @@ fn bitCastSpliceInner(
209211/// of values in *packed* memory - therefore, on big-endian targets, the first element of this
210212/// list contains bits from the *final* byte of the value.
211213const UnpackValueBits = struct {
212 zcu: *Zcu,
214 pt: Zcu.PerThread,
213215 arena: Allocator,
214216 skip_bits: u64,
215217 remaining_bits: u64,
......@@ -217,7 +219,8 @@ const UnpackValueBits = struct {
217219 unpacked: std.ArrayList(InternPool.Index),
218220
219221 fn add(unpack: *UnpackValueBits, val: Value) BitCastError!void {
220 const zcu = unpack.zcu;
222 const pt = unpack.pt;
223 const zcu = pt.zcu;
221224 const endian = zcu.getTarget().cpu.arch.endian();
222225 const ip = &zcu.intern_pool;
223226
......@@ -226,7 +229,7 @@ const UnpackValueBits = struct {
226229 }
227230
228231 const ty = val.typeOf(zcu);
229 const bit_size = ty.bitSize(zcu);
232 const bit_size = ty.bitSize(pt);
230233
231234 if (unpack.skip_bits >= bit_size) {
232235 unpack.skip_bits -= bit_size;
......@@ -279,7 +282,7 @@ const UnpackValueBits = struct {
279282 .little => i,
280283 .big => len - i - 1,
281284 };
282 const elem_val = try val.elemValue(zcu, real_idx);
285 const elem_val = try val.elemValue(pt, real_idx);
283286 try unpack.add(elem_val);
284287 }
285288 },
......@@ -288,7 +291,7 @@ const UnpackValueBits = struct {
288291 // The final element does not have trailing padding.
289292 // Elements are reversed in packed memory on BE targets.
290293 const elem_ty = ty.childType(zcu);
291 const pad_bits = elem_ty.abiSize(zcu) * 8 - elem_ty.bitSize(zcu);
294 const pad_bits = elem_ty.abiSize(pt) * 8 - elem_ty.bitSize(pt);
292295 const len = ty.arrayLen(zcu);
293296 const maybe_sent = ty.sentinel(zcu);
294297
......@@ -303,7 +306,7 @@ const UnpackValueBits = struct {
303306 .little => i,
304307 .big => len - i - 1,
305308 };
306 const elem_val = try val.elemValue(zcu, @intCast(real_idx));
309 const elem_val = try val.elemValue(pt, @intCast(real_idx));
307310 try unpack.add(elem_val);
308311 if (i != len - 1) try unpack.padding(pad_bits);
309312 }
......@@ -320,12 +323,12 @@ const UnpackValueBits = struct {
320323 var cur_bit_off: u64 = 0;
321324 var it = zcu.typeToStruct(ty).?.iterateRuntimeOrder(ip);
322325 while (it.next()) |field_idx| {
323 const want_bit_off = ty.structFieldOffset(field_idx, zcu) * 8;
326 const want_bit_off = ty.structFieldOffset(field_idx, pt) * 8;
324327 const pad_bits = want_bit_off - cur_bit_off;
325 const field_val = try val.fieldValue(zcu, field_idx);
328 const field_val = try val.fieldValue(pt, field_idx);
326329 try unpack.padding(pad_bits);
327330 try unpack.add(field_val);
328 cur_bit_off = want_bit_off + field_val.typeOf(zcu).bitSize(zcu);
331 cur_bit_off = want_bit_off + field_val.typeOf(zcu).bitSize(pt);
329332 }
330333 // Add trailing padding bits.
331334 try unpack.padding(bit_size - cur_bit_off);
......@@ -334,13 +337,13 @@ const UnpackValueBits = struct {
334337 var cur_bit_off: u64 = bit_size;
335338 var it = zcu.typeToStruct(ty).?.iterateRuntimeOrderReverse(ip);
336339 while (it.next()) |field_idx| {
337 const field_val = try val.fieldValue(zcu, field_idx);
340 const field_val = try val.fieldValue(pt, field_idx);
338341 const field_ty = field_val.typeOf(zcu);
339 const want_bit_off = ty.structFieldOffset(field_idx, zcu) * 8 + field_ty.bitSize(zcu);
342 const want_bit_off = ty.structFieldOffset(field_idx, pt) * 8 + field_ty.bitSize(pt);
340343 const pad_bits = cur_bit_off - want_bit_off;
341344 try unpack.padding(pad_bits);
342345 try unpack.add(field_val);
343 cur_bit_off = want_bit_off - field_ty.bitSize(zcu);
346 cur_bit_off = want_bit_off - field_ty.bitSize(pt);
344347 }
345348 assert(cur_bit_off == 0);
346349 },
......@@ -349,7 +352,7 @@ const UnpackValueBits = struct {
349352 // Just add all fields in order. There are no padding bits.
350353 // This is identical between LE and BE targets.
351354 for (0..ty.structFieldCount(zcu)) |i| {
352 const field_val = try val.fieldValue(zcu, i);
355 const field_val = try val.fieldValue(pt, i);
353356 try unpack.add(field_val);
354357 }
355358 },
......@@ -363,7 +366,7 @@ const UnpackValueBits = struct {
363366 // This correctly handles the case where `tag == .none`, since the payload is then
364367 // either an integer or a byte array, both of which we can unpack.
365368 const payload_val = Value.fromInterned(un.val);
366 const pad_bits = bit_size - payload_val.typeOf(zcu).bitSize(zcu);
369 const pad_bits = bit_size - payload_val.typeOf(zcu).bitSize(pt);
367370 if (endian == .little or ty.containerLayout(zcu) == .@"packed") {
368371 try unpack.add(payload_val);
369372 try unpack.padding(pad_bits);
......@@ -377,31 +380,31 @@ const UnpackValueBits = struct {
377380
378381 fn padding(unpack: *UnpackValueBits, pad_bits: u64) BitCastError!void {
379382 if (pad_bits == 0) return;
380 const zcu = unpack.zcu;
383 const pt = unpack.pt;
381384 // Figure out how many full bytes and leftover bits there are.
382385 const bytes = pad_bits / 8;
383386 const bits = pad_bits % 8;
384387 // Add undef u8 values for the bytes...
385 const undef_u8 = try zcu.undefValue(Type.u8);
388 const undef_u8 = try pt.undefValue(Type.u8);
386389 for (0..@intCast(bytes)) |_| {
387390 try unpack.primitive(undef_u8);
388391 }
389392 // ...and an undef int for the leftover bits.
390393 if (bits == 0) return;
391 const bits_ty = try zcu.intType(.unsigned, @intCast(bits));
392 const bits_val = try zcu.undefValue(bits_ty);
394 const bits_ty = try pt.intType(.unsigned, @intCast(bits));
395 const bits_val = try pt.undefValue(bits_ty);
393396 try unpack.primitive(bits_val);
394397 }
395398
396399 fn primitive(unpack: *UnpackValueBits, val: Value) BitCastError!void {
397 const zcu = unpack.zcu;
400 const pt = unpack.pt;
398401
399402 if (unpack.remaining_bits == 0) {
400403 return;
401404 }
402405
403 const ty = val.typeOf(zcu);
404 const bit_size = ty.bitSize(zcu);
406 const ty = val.typeOf(pt.zcu);
407 const bit_size = ty.bitSize(pt);
405408
406409 // Note that this skips all zero-bit types.
407410 if (unpack.skip_bits >= bit_size) {
......@@ -425,21 +428,21 @@ const UnpackValueBits = struct {
425428 }
426429
427430 fn splitPrimitive(unpack: *UnpackValueBits, val: Value, bit_offset: u64, bit_count: u64) BitCastError!void {
428 const zcu = unpack.zcu;
429 const ty = val.typeOf(zcu);
431 const pt = unpack.pt;
432 const ty = val.typeOf(pt.zcu);
430433
431 const val_bits = ty.bitSize(zcu);
434 const val_bits = ty.bitSize(pt);
432435 assert(bit_offset + bit_count <= val_bits);
433436
434 switch (zcu.intern_pool.indexToKey(val.toIntern())) {
437 switch (pt.zcu.intern_pool.indexToKey(val.toIntern())) {
435438 // In the `ptr` case, this will return `error.ReinterpretDeclRef`
436439 // if we're trying to split a non-integer pointer value.
437440 .int, .float, .enum_tag, .ptr, .opt => {
438441 // This @intCast is okay because no primitive can exceed the size of a u16.
439 const int_ty = try zcu.intType(.unsigned, @intCast(bit_count));
442 const int_ty = try unpack.pt.intType(.unsigned, @intCast(bit_count));
440443 const buf = try unpack.arena.alloc(u8, @intCast((val_bits + 7) / 8));
441 try val.writeToPackedMemory(ty, zcu, buf, 0);
442 const sub_val = try Value.readFromPackedMemory(int_ty, zcu, buf, @intCast(bit_offset), unpack.arena);
444 try val.writeToPackedMemory(ty, unpack.pt, buf, 0);
445 const sub_val = try Value.readFromPackedMemory(int_ty, unpack.pt, buf, @intCast(bit_offset), unpack.arena);
443446 try unpack.primitive(sub_val);
444447 },
445448 .undef => try unpack.padding(bit_count),
......@@ -456,13 +459,14 @@ const UnpackValueBits = struct {
456459/// reconstructs a value of an arbitrary type, with correct handling of `undefined`
457460/// values and of pointers which align in virtual memory.
458461const PackValueBits = struct {
459 zcu: *Zcu,
462 pt: Zcu.PerThread,
460463 arena: Allocator,
461464 bit_offset: u64 = 0,
462465 unpacked: []const InternPool.Index,
463466
464467 fn get(pack: *PackValueBits, ty: Type) BitCastError!Value {
465 const zcu = pack.zcu;
468 const pt = pack.pt;
469 const zcu = pt.zcu;
466470 const endian = zcu.getTarget().cpu.arch.endian();
467471 const ip = &zcu.intern_pool;
468472 const arena = pack.arena;
......@@ -485,7 +489,7 @@ const PackValueBits = struct {
485489 }
486490 },
487491 }
488 return Value.fromInterned(try zcu.intern(.{ .aggregate = .{
492 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
489493 .ty = ty.toIntern(),
490494 .storage = .{ .elems = elems },
491495 } }));
......@@ -495,12 +499,12 @@ const PackValueBits = struct {
495499 const len = ty.arrayLen(zcu);
496500 const elem_ty = ty.childType(zcu);
497501 const maybe_sent = ty.sentinel(zcu);
498 const pad_bits = elem_ty.abiSize(zcu) * 8 - elem_ty.bitSize(zcu);
502 const pad_bits = elem_ty.abiSize(pt) * 8 - elem_ty.bitSize(pt);
499503 const elems = try arena.alloc(InternPool.Index, @intCast(len));
500504
501505 if (endian == .big and maybe_sent != null) {
502506 // TODO: validate sentinel was preserved!
503 try pack.padding(elem_ty.bitSize(zcu));
507 try pack.padding(elem_ty.bitSize(pt));
504508 if (len != 0) try pack.padding(pad_bits);
505509 }
506510
......@@ -516,10 +520,10 @@ const PackValueBits = struct {
516520 if (endian == .little and maybe_sent != null) {
517521 // TODO: validate sentinel was preserved!
518522 if (len != 0) try pack.padding(pad_bits);
519 try pack.padding(elem_ty.bitSize(zcu));
523 try pack.padding(elem_ty.bitSize(pt));
520524 }
521525
522 return Value.fromInterned(try zcu.intern(.{ .aggregate = .{
526 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
523527 .ty = ty.toIntern(),
524528 .storage = .{ .elems = elems },
525529 } }));
......@@ -534,23 +538,23 @@ const PackValueBits = struct {
534538 var cur_bit_off: u64 = 0;
535539 var it = zcu.typeToStruct(ty).?.iterateRuntimeOrder(ip);
536540 while (it.next()) |field_idx| {
537 const want_bit_off = ty.structFieldOffset(field_idx, zcu) * 8;
541 const want_bit_off = ty.structFieldOffset(field_idx, pt) * 8;
538542 try pack.padding(want_bit_off - cur_bit_off);
539543 const field_ty = ty.structFieldType(field_idx, zcu);
540544 elems[field_idx] = (try pack.get(field_ty)).toIntern();
541 cur_bit_off = want_bit_off + field_ty.bitSize(zcu);
545 cur_bit_off = want_bit_off + field_ty.bitSize(pt);
542546 }
543 try pack.padding(ty.bitSize(zcu) - cur_bit_off);
547 try pack.padding(ty.bitSize(pt) - cur_bit_off);
544548 },
545549 .big => {
546 var cur_bit_off: u64 = ty.bitSize(zcu);
550 var cur_bit_off: u64 = ty.bitSize(pt);
547551 var it = zcu.typeToStruct(ty).?.iterateRuntimeOrderReverse(ip);
548552 while (it.next()) |field_idx| {
549553 const field_ty = ty.structFieldType(field_idx, zcu);
550 const want_bit_off = ty.structFieldOffset(field_idx, zcu) * 8 + field_ty.bitSize(zcu);
554 const want_bit_off = ty.structFieldOffset(field_idx, pt) * 8 + field_ty.bitSize(pt);
551555 try pack.padding(cur_bit_off - want_bit_off);
552556 elems[field_idx] = (try pack.get(field_ty)).toIntern();
553 cur_bit_off = want_bit_off - field_ty.bitSize(zcu);
557 cur_bit_off = want_bit_off - field_ty.bitSize(pt);
554558 }
555559 assert(cur_bit_off == 0);
556560 },
......@@ -559,10 +563,10 @@ const PackValueBits = struct {
559563 // Fill those values now.
560564 for (elems, 0..) |*elem, field_idx| {
561565 if (elem.* != .none) continue;
562 const val = (try ty.structFieldValueComptime(zcu, field_idx)).?;
566 const val = (try ty.structFieldValueComptime(pt, field_idx)).?;
563567 elem.* = val.toIntern();
564568 }
565 return Value.fromInterned(try zcu.intern(.{ .aggregate = .{
569 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
566570 .ty = ty.toIntern(),
567571 .storage = .{ .elems = elems },
568572 } }));
......@@ -575,7 +579,7 @@ const PackValueBits = struct {
575579 const field_ty = ty.structFieldType(i, zcu);
576580 elem.* = (try pack.get(field_ty)).toIntern();
577581 }
578 return Value.fromInterned(try zcu.intern(.{ .aggregate = .{
582 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
579583 .ty = ty.toIntern(),
580584 .storage = .{ .elems = elems },
581585 } }));
......@@ -591,7 +595,7 @@ const PackValueBits = struct {
591595 const prev_unpacked = pack.unpacked;
592596 const prev_bit_offset = pack.bit_offset;
593597
594 const backing_ty = try ty.unionBackingType(zcu);
598 const backing_ty = try ty.unionBackingType(pt);
595599
596600 backing: {
597601 const backing_val = pack.get(backing_ty) catch |err| switch (err) {
......@@ -607,7 +611,7 @@ const PackValueBits = struct {
607611 pack.bit_offset = prev_bit_offset;
608612 break :backing;
609613 }
610 return Value.fromInterned(try zcu.intern(.{ .un = .{
614 return Value.fromInterned(try pt.intern(.{ .un = .{
611615 .ty = ty.toIntern(),
612616 .tag = .none,
613617 .val = backing_val.toIntern(),
......@@ -618,16 +622,16 @@ const PackValueBits = struct {
618622 for (field_order, 0..) |*f, i| f.* = @intCast(i);
619623 // Sort `field_order` to put the fields with the largest bit sizes first.
620624 const SizeSortCtx = struct {
621 zcu: *Zcu,
625 pt: Zcu.PerThread,
622626 field_types: []const InternPool.Index,
623627 fn lessThan(ctx: @This(), a_idx: u32, b_idx: u32) bool {
624628 const a_ty = Type.fromInterned(ctx.field_types[a_idx]);
625629 const b_ty = Type.fromInterned(ctx.field_types[b_idx]);
626 return a_ty.bitSize(ctx.zcu) > b_ty.bitSize(ctx.zcu);
630 return a_ty.bitSize(ctx.pt) > b_ty.bitSize(ctx.pt);
627631 }
628632 };
629633 std.mem.sortUnstable(u32, field_order, SizeSortCtx{
630 .zcu = zcu,
634 .pt = pt,
631635 .field_types = zcu.typeToUnion(ty).?.field_types.get(ip),
632636 }, SizeSortCtx.lessThan);
633637
......@@ -635,7 +639,7 @@ const PackValueBits = struct {
635639
636640 for (field_order) |field_idx| {
637641 const field_ty = Type.fromInterned(zcu.typeToUnion(ty).?.field_types.get(ip)[field_idx]);
638 const pad_bits = ty.bitSize(zcu) - field_ty.bitSize(zcu);
642 const pad_bits = ty.bitSize(pt) - field_ty.bitSize(pt);
639643 if (!padding_after) try pack.padding(pad_bits);
640644 const field_val = pack.get(field_ty) catch |err| switch (err) {
641645 error.ReinterpretDeclRef => {
......@@ -651,8 +655,8 @@ const PackValueBits = struct {
651655 pack.bit_offset = prev_bit_offset;
652656 continue;
653657 }
654 const tag_val = try zcu.enumValueFieldIndex(ty.unionTagTypeHypothetical(zcu), field_idx);
655 return Value.fromInterned(try zcu.intern(.{ .un = .{
658 const tag_val = try pt.enumValueFieldIndex(ty.unionTagTypeHypothetical(zcu), field_idx);
659 return Value.fromInterned(try pt.intern(.{ .un = .{
656660 .ty = ty.toIntern(),
657661 .tag = tag_val.toIntern(),
658662 .val = field_val.toIntern(),
......@@ -662,7 +666,7 @@ const PackValueBits = struct {
662666 // No field could represent the value. Just do whatever happens when we try to read
663667 // the backing type - either `undefined` or `error.ReinterpretDeclRef`.
664668 const backing_val = try pack.get(backing_ty);
665 return Value.fromInterned(try zcu.intern(.{ .un = .{
669 return Value.fromInterned(try pt.intern(.{ .un = .{
666670 .ty = ty.toIntern(),
667671 .tag = .none,
668672 .val = backing_val.toIntern(),
......@@ -677,14 +681,14 @@ const PackValueBits = struct {
677681 }
678682
679683 fn primitive(pack: *PackValueBits, want_ty: Type) BitCastError!Value {
680 const zcu = pack.zcu;
681 const vals, const bit_offset = pack.prepareBits(want_ty.bitSize(zcu));
684 const pt = pack.pt;
685 const vals, const bit_offset = pack.prepareBits(want_ty.bitSize(pt));
682686
683687 for (vals) |val| {
684 if (!Value.fromInterned(val).isUndef(zcu)) break;
688 if (!Value.fromInterned(val).isUndef(pt.zcu)) break;
685689 } else {
686690 // All bits of the value are `undefined`.
687 return zcu.undefValue(want_ty);
691 return pt.undefValue(want_ty);
688692 }
689693
690694 // TODO: we need to decide how to handle partially-undef values here.
......@@ -702,9 +706,9 @@ const PackValueBits = struct {
702706 ptr_cast: {
703707 if (vals.len != 1) break :ptr_cast;
704708 const val = Value.fromInterned(vals[0]);
705 if (!val.typeOf(zcu).isPtrAtRuntime(zcu)) break :ptr_cast;
706 if (!want_ty.isPtrAtRuntime(zcu)) break :ptr_cast;
707 return zcu.getCoerced(val, want_ty);
709 if (!val.typeOf(pt.zcu).isPtrAtRuntime(pt.zcu)) break :ptr_cast;
710 if (!want_ty.isPtrAtRuntime(pt.zcu)) break :ptr_cast;
711 return pt.getCoerced(val, want_ty);
708712 }
709713
710714 // Reinterpret via an in-memory buffer.
......@@ -712,8 +716,8 @@ const PackValueBits = struct {
712716 var buf_bits: u64 = 0;
713717 for (vals) |ip_val| {
714718 const val = Value.fromInterned(ip_val);
715 const ty = val.typeOf(zcu);
716 buf_bits += ty.bitSize(zcu);
719 const ty = val.typeOf(pt.zcu);
720 buf_bits += ty.bitSize(pt);
717721 }
718722
719723 const buf = try pack.arena.alloc(u8, @intCast((buf_bits + 7) / 8));
......@@ -722,25 +726,25 @@ const PackValueBits = struct {
722726 var cur_bit_off: usize = 0;
723727 for (vals) |ip_val| {
724728 const val = Value.fromInterned(ip_val);
725 const ty = val.typeOf(zcu);
726 if (!val.isUndef(zcu)) {
727 try val.writeToPackedMemory(ty, zcu, buf, cur_bit_off);
729 const ty = val.typeOf(pt.zcu);
730 if (!val.isUndef(pt.zcu)) {
731 try val.writeToPackedMemory(ty, pt, buf, cur_bit_off);
728732 }
729 cur_bit_off += @intCast(ty.bitSize(zcu));
733 cur_bit_off += @intCast(ty.bitSize(pt));
730734 }
731735
732 return Value.readFromPackedMemory(want_ty, zcu, buf, @intCast(bit_offset), pack.arena);
736 return Value.readFromPackedMemory(want_ty, pt, buf, @intCast(bit_offset), pack.arena);
733737 }
734738
735739 fn prepareBits(pack: *PackValueBits, need_bits: u64) struct { []const InternPool.Index, u64 } {
736740 if (need_bits == 0) return .{ &.{}, 0 };
737741
738 const zcu = pack.zcu;
742 const pt = pack.pt;
739743
740744 var bits: u64 = 0;
741745 var len: usize = 0;
742746 while (bits < pack.bit_offset + need_bits) {
743 bits += Value.fromInterned(pack.unpacked[len]).typeOf(zcu).bitSize(zcu);
747 bits += Value.fromInterned(pack.unpacked[len]).typeOf(pt.zcu).bitSize(pt);
744748 len += 1;
745749 }
746750
......@@ -753,7 +757,7 @@ const PackValueBits = struct {
753757 pack.bit_offset = 0;
754758 } else {
755759 pack.unpacked = pack.unpacked[len - 1 ..];
756 pack.bit_offset = Value.fromInterned(pack.unpacked[0]).typeOf(zcu).bitSize(zcu) - extra_bits;
760 pack.bit_offset = Value.fromInterned(pack.unpacked[0]).typeOf(pt.zcu).bitSize(pt) - extra_bits;
757761 }
758762
759763 return .{ result_vals, result_offset };
src/Sema/comptime_ptr_access.zig+57-54
......@@ -12,19 +12,19 @@ pub const ComptimeLoadResult = union(enum) {
1212};
1313
1414pub fn loadComptimePtr(sema: *Sema, block: *Block, src: LazySrcLoc, ptr: Value) !ComptimeLoadResult {
15 const zcu = sema.mod;
16 const ptr_info = ptr.typeOf(zcu).ptrInfo(zcu);
15 const pt = sema.pt;
16 const ptr_info = ptr.typeOf(pt.zcu).ptrInfo(pt.zcu);
1717 // TODO: host size for vectors is terrible
1818 const host_bits = switch (ptr_info.flags.vector_index) {
1919 .none => ptr_info.packed_offset.host_size * 8,
20 else => ptr_info.packed_offset.host_size * Type.fromInterned(ptr_info.child).bitSize(zcu),
20 else => ptr_info.packed_offset.host_size * Type.fromInterned(ptr_info.child).bitSize(pt),
2121 };
2222 const bit_offset = if (host_bits != 0) bit_offset: {
23 const child_bits = Type.fromInterned(ptr_info.child).bitSize(zcu);
23 const child_bits = Type.fromInterned(ptr_info.child).bitSize(pt);
2424 const bit_offset = ptr_info.packed_offset.bit_offset + switch (ptr_info.flags.vector_index) {
2525 .none => 0,
2626 .runtime => return .runtime_load,
27 else => |idx| switch (zcu.getTarget().cpu.arch.endian()) {
27 else => |idx| switch (pt.zcu.getTarget().cpu.arch.endian()) {
2828 .little => child_bits * @intFromEnum(idx),
2929 .big => host_bits - child_bits * (@intFromEnum(idx) + 1), // element order reversed on big endian
3030 },
......@@ -60,28 +60,29 @@ pub fn storeComptimePtr(
6060 ptr: Value,
6161 store_val: Value,
6262) !ComptimeStoreResult {
63 const zcu = sema.mod;
63 const pt = sema.pt;
64 const zcu = pt.zcu;
6465 const ptr_info = ptr.typeOf(zcu).ptrInfo(zcu);
6566 assert(store_val.typeOf(zcu).toIntern() == ptr_info.child);
6667 // TODO: host size for vectors is terrible
6768 const host_bits = switch (ptr_info.flags.vector_index) {
6869 .none => ptr_info.packed_offset.host_size * 8,
69 else => ptr_info.packed_offset.host_size * Type.fromInterned(ptr_info.child).bitSize(zcu),
70 else => ptr_info.packed_offset.host_size * Type.fromInterned(ptr_info.child).bitSize(pt),
7071 };
7172 const bit_offset = ptr_info.packed_offset.bit_offset + switch (ptr_info.flags.vector_index) {
7273 .none => 0,
7374 .runtime => return .runtime_store,
7475 else => |idx| switch (zcu.getTarget().cpu.arch.endian()) {
75 .little => Type.fromInterned(ptr_info.child).bitSize(zcu) * @intFromEnum(idx),
76 .big => host_bits - Type.fromInterned(ptr_info.child).bitSize(zcu) * (@intFromEnum(idx) + 1), // element order reversed on big endian
76 .little => Type.fromInterned(ptr_info.child).bitSize(pt) * @intFromEnum(idx),
77 .big => host_bits - Type.fromInterned(ptr_info.child).bitSize(pt) * (@intFromEnum(idx) + 1), // element order reversed on big endian
7778 },
7879 };
7980 const pseudo_store_ty = if (host_bits > 0) t: {
80 const need_bits = Type.fromInterned(ptr_info.child).bitSize(zcu);
81 const need_bits = Type.fromInterned(ptr_info.child).bitSize(pt);
8182 if (need_bits + bit_offset > host_bits) {
8283 return .exceeds_host_size;
8384 }
84 break :t try zcu.intType(.unsigned, @intCast(host_bits));
85 break :t try sema.pt.intType(.unsigned, @intCast(host_bits));
8586 } else Type.fromInterned(ptr_info.child);
8687
8788 const strat = try prepareComptimePtrStore(sema, block, src, ptr, pseudo_store_ty, 0);
......@@ -103,7 +104,7 @@ pub fn storeComptimePtr(
103104 .needed_well_defined => |ty| return .{ .needed_well_defined = ty },
104105 .out_of_bounds => |ty| return .{ .out_of_bounds = ty },
105106 };
106 const expected = try expected_mv.intern(zcu, sema.arena);
107 const expected = try expected_mv.intern(pt, sema.arena);
107108 if (store_val.toIntern() != expected.toIntern()) {
108109 return .{ .comptime_field_mismatch = expected };
109110 }
......@@ -126,14 +127,14 @@ pub fn storeComptimePtr(
126127 switch (strat) {
127128 .direct => |direct| {
128129 const want_ty = direct.val.typeOf(zcu);
129 const coerced_store_val = try zcu.getCoerced(store_val, want_ty);
130 const coerced_store_val = try pt.getCoerced(store_val, want_ty);
130131 direct.val.* = .{ .interned = coerced_store_val.toIntern() };
131132 return .success;
132133 },
133134 .index => |index| {
134135 const want_ty = index.val.typeOf(zcu).childType(zcu);
135 const coerced_store_val = try zcu.getCoerced(store_val, want_ty);
136 try index.val.setElem(zcu, sema.arena, @intCast(index.elem_index), .{ .interned = coerced_store_val.toIntern() });
136 const coerced_store_val = try pt.getCoerced(store_val, want_ty);
137 try index.val.setElem(pt, sema.arena, @intCast(index.elem_index), .{ .interned = coerced_store_val.toIntern() });
137138 return .success;
138139 },
139140 .flat_index => |flat| {
......@@ -149,7 +150,7 @@ pub fn storeComptimePtr(
149150 // Better would be to gather all the store targets into an array.
150151 var index: u64 = flat.flat_elem_index + idx;
151152 const val_ptr, const final_idx = (try recursiveIndex(sema, flat.val, &index)).?;
152 try val_ptr.setElem(zcu, sema.arena, @intCast(final_idx), .{ .interned = elem });
153 try val_ptr.setElem(pt, sema.arena, @intCast(final_idx), .{ .interned = elem });
153154 }
154155 return .success;
155156 },
......@@ -165,9 +166,9 @@ pub fn storeComptimePtr(
165166 .direct => |direct| .{ direct.val, 0 },
166167 .index => |index| .{
167168 index.val,
168 index.elem_index * index.val.typeOf(zcu).childType(zcu).abiSize(zcu),
169 index.elem_index * index.val.typeOf(zcu).childType(zcu).abiSize(pt),
169170 },
170 .flat_index => |flat| .{ flat.val, flat.flat_elem_index * flat.val.typeOf(zcu).arrayBase(zcu)[0].abiSize(zcu) },
171 .flat_index => |flat| .{ flat.val, flat.flat_elem_index * flat.val.typeOf(zcu).arrayBase(zcu)[0].abiSize(pt) },
171172 .reinterpret => |reinterpret| .{ reinterpret.val, reinterpret.byte_offset },
172173 else => unreachable,
173174 };
......@@ -181,7 +182,7 @@ pub fn storeComptimePtr(
181182 }
182183
183184 const new_val = try sema.bitCastSpliceVal(
184 try val_ptr.intern(zcu, sema.arena),
185 try val_ptr.intern(pt, sema.arena),
185186 store_val,
186187 byte_offset,
187188 host_bits,
......@@ -205,7 +206,8 @@ fn loadComptimePtrInner(
205206 /// before `load_ty`. Otherwise, it is ignored and may be `undefined`.
206207 array_offset: u64,
207208) !ComptimeLoadResult {
208 const zcu = sema.mod;
209 const pt = sema.pt;
210 const zcu = pt.zcu;
209211 const ip = &zcu.intern_pool;
210212
211213 const ptr = switch (ip.indexToKey(ptr_val.toIntern())) {
......@@ -263,7 +265,7 @@ fn loadComptimePtrInner(
263265 const load_one_ty, const load_count = load_ty.arrayBase(zcu);
264266 const count = if (load_one_ty.toIntern() == base_ty.toIntern()) load_count else 1;
265267
266 const want_ty = try zcu.arrayType(.{
268 const want_ty = try sema.pt.arrayType(.{
267269 .len = count,
268270 .child = base_ty.toIntern(),
269271 });
......@@ -285,7 +287,7 @@ fn loadComptimePtrInner(
285287
286288 const agg_ty = agg_val.typeOf(zcu);
287289 switch (agg_ty.zigTypeTag(zcu)) {
288 .Struct, .Pointer => break :val try agg_val.getElem(zcu, @intCast(base_index.index)),
290 .Struct, .Pointer => break :val try agg_val.getElem(sema.pt, @intCast(base_index.index)),
289291 .Union => {
290292 const tag_val: Value, const payload_mv: MutableValue = switch (agg_val) {
291293 .un => |un| .{ Value.fromInterned(un.tag), un.payload.* },
......@@ -427,7 +429,7 @@ fn loadComptimePtrInner(
427429 const next_elem_off = elem_size * (elem_idx + 1);
428430 if (cur_offset + need_bytes <= next_elem_off) {
429431 // We can look at a single array element.
430 cur_val = try cur_val.getElem(zcu, @intCast(elem_idx));
432 cur_val = try cur_val.getElem(sema.pt, @intCast(elem_idx));
431433 cur_offset -= elem_idx * elem_size;
432434 } else {
433435 break;
......@@ -437,10 +439,10 @@ fn loadComptimePtrInner(
437439 .auto => unreachable, // ill-defined layout
438440 .@"packed" => break, // let the bitcast logic handle this
439441 .@"extern" => for (0..cur_ty.structFieldCount(zcu)) |field_idx| {
440 const start_off = cur_ty.structFieldOffset(field_idx, zcu);
442 const start_off = cur_ty.structFieldOffset(field_idx, pt);
441443 const end_off = start_off + try sema.typeAbiSize(cur_ty.structFieldType(field_idx, zcu));
442444 if (cur_offset >= start_off and cur_offset + need_bytes <= end_off) {
443 cur_val = try cur_val.getElem(zcu, field_idx);
445 cur_val = try cur_val.getElem(sema.pt, field_idx);
444446 cur_offset -= start_off;
445447 break;
446448 }
......@@ -482,7 +484,7 @@ fn loadComptimePtrInner(
482484 }
483485
484486 const result_val = try sema.bitCastVal(
485 try cur_val.intern(zcu, sema.arena),
487 try cur_val.intern(sema.pt, sema.arena),
486488 load_ty,
487489 cur_offset,
488490 host_bits,
......@@ -564,7 +566,8 @@ fn prepareComptimePtrStore(
564566 /// before `store_ty`. Otherwise, it is ignored and may be `undefined`.
565567 array_offset: u64,
566568) !ComptimeStoreStrategy {
567 const zcu = sema.mod;
569 const pt = sema.pt;
570 const zcu = pt.zcu;
568571 const ip = &zcu.intern_pool;
569572
570573 const ptr = switch (ip.indexToKey(ptr_val.toIntern())) {
......@@ -587,14 +590,14 @@ fn prepareComptimePtrStore(
587590 const eu_val_ptr, const alloc = switch (try prepareComptimePtrStore(sema, block, src, base_ptr, base_ty, undefined)) {
588591 .direct => |direct| .{ direct.val, direct.alloc },
589592 .index => |index| .{
590 try index.val.elem(zcu, sema.arena, @intCast(index.elem_index)),
593 try index.val.elem(pt, sema.arena, @intCast(index.elem_index)),
591594 index.alloc,
592595 },
593596 .flat_index => unreachable, // base_ty is not an array
594597 .reinterpret => unreachable, // base_ty has ill-defined layout
595598 else => |err| return err,
596599 };
597 try eu_val_ptr.unintern(zcu, sema.arena, false, false);
600 try eu_val_ptr.unintern(pt, sema.arena, false, false);
598601 switch (eu_val_ptr.*) {
599602 .interned => |ip_index| switch (ip.indexToKey(ip_index)) {
600603 .undef => return .undef,
......@@ -614,14 +617,14 @@ fn prepareComptimePtrStore(
614617 const opt_val_ptr, const alloc = switch (try prepareComptimePtrStore(sema, block, src, base_ptr, base_ty, undefined)) {
615618 .direct => |direct| .{ direct.val, direct.alloc },
616619 .index => |index| .{
617 try index.val.elem(zcu, sema.arena, @intCast(index.elem_index)),
620 try index.val.elem(pt, sema.arena, @intCast(index.elem_index)),
618621 index.alloc,
619622 },
620623 .flat_index => unreachable, // base_ty is not an array
621624 .reinterpret => unreachable, // base_ty has ill-defined layout
622625 else => |err| return err,
623626 };
624 try opt_val_ptr.unintern(zcu, sema.arena, false, false);
627 try opt_val_ptr.unintern(pt, sema.arena, false, false);
625628 switch (opt_val_ptr.*) {
626629 .interned => |ip_index| switch (ip.indexToKey(ip_index)) {
627630 .undef => return .undef,
......@@ -648,7 +651,7 @@ fn prepareComptimePtrStore(
648651 const store_one_ty, const store_count = store_ty.arrayBase(zcu);
649652 const count = if (store_one_ty.toIntern() == base_ty.toIntern()) store_count else 1;
650653
651 const want_ty = try zcu.arrayType(.{
654 const want_ty = try pt.arrayType(.{
652655 .len = count,
653656 .child = base_ty.toIntern(),
654657 });
......@@ -668,7 +671,7 @@ fn prepareComptimePtrStore(
668671 const agg_val, const alloc = switch (try prepareComptimePtrStore(sema, block, src, base_ptr, base_ty, undefined)) {
669672 .direct => |direct| .{ direct.val, direct.alloc },
670673 .index => |index| .{
671 try index.val.elem(zcu, sema.arena, @intCast(index.elem_index)),
674 try index.val.elem(pt, sema.arena, @intCast(index.elem_index)),
672675 index.alloc,
673676 },
674677 .flat_index => unreachable, // base_ty is not an array
......@@ -679,14 +682,14 @@ fn prepareComptimePtrStore(
679682 const agg_ty = agg_val.typeOf(zcu);
680683 switch (agg_ty.zigTypeTag(zcu)) {
681684 .Struct, .Pointer => break :strat .{ .direct = .{
682 .val = try agg_val.elem(zcu, sema.arena, @intCast(base_index.index)),
685 .val = try agg_val.elem(pt, sema.arena, @intCast(base_index.index)),
683686 .alloc = alloc,
684687 } },
685688 .Union => {
686689 if (agg_val.* == .interned and Value.fromInterned(agg_val.interned).isUndef(zcu)) {
687690 return .undef;
688691 }
689 try agg_val.unintern(zcu, sema.arena, false, false);
692 try agg_val.unintern(pt, sema.arena, false, false);
690693 const un = agg_val.un;
691694 const tag_ty = agg_ty.unionTagTypeHypothetical(zcu);
692695 if (tag_ty.enumTagFieldIndex(Value.fromInterned(un.tag), zcu).? != base_index.index) {
......@@ -847,7 +850,7 @@ fn prepareComptimePtrStore(
847850 const next_elem_off = elem_size * (elem_idx + 1);
848851 if (cur_offset + need_bytes <= next_elem_off) {
849852 // We can look at a single array element.
850 cur_val = try cur_val.elem(zcu, sema.arena, @intCast(elem_idx));
853 cur_val = try cur_val.elem(pt, sema.arena, @intCast(elem_idx));
851854 cur_offset -= elem_idx * elem_size;
852855 } else {
853856 break;
......@@ -857,10 +860,10 @@ fn prepareComptimePtrStore(
857860 .auto => unreachable, // ill-defined layout
858861 .@"packed" => break, // let the bitcast logic handle this
859862 .@"extern" => for (0..cur_ty.structFieldCount(zcu)) |field_idx| {
860 const start_off = cur_ty.structFieldOffset(field_idx, zcu);
863 const start_off = cur_ty.structFieldOffset(field_idx, pt);
861864 const end_off = start_off + try sema.typeAbiSize(cur_ty.structFieldType(field_idx, zcu));
862865 if (cur_offset >= start_off and cur_offset + need_bytes <= end_off) {
863 cur_val = try cur_val.elem(zcu, sema.arena, field_idx);
866 cur_val = try cur_val.elem(pt, sema.arena, field_idx);
864867 cur_offset -= start_off;
865868 break;
866869 }
......@@ -874,7 +877,7 @@ fn prepareComptimePtrStore(
874877 // Otherwise, we might traverse into a union field which doesn't allow pointers.
875878 // Figure out a solution!
876879 if (true) break;
877 try cur_val.unintern(zcu, sema.arena, false, false);
880 try cur_val.unintern(pt, sema.arena, false, false);
878881 const payload = switch (cur_val.*) {
879882 .un => |un| un.payload,
880883 else => unreachable,
......@@ -918,7 +921,7 @@ fn flattenArray(
918921) Allocator.Error!void {
919922 if (next_idx.* == out.len) return;
920923
921 const zcu = sema.mod;
924 const zcu = sema.pt.zcu;
922925
923926 const ty = val.typeOf(zcu);
924927 const base_elem_count = ty.arrayBase(zcu)[1];
......@@ -928,7 +931,7 @@ fn flattenArray(
928931 }
929932
930933 if (ty.zigTypeTag(zcu) != .Array) {
931 out[@intCast(next_idx.*)] = (try val.intern(zcu, sema.arena)).toIntern();
934 out[@intCast(next_idx.*)] = (try val.intern(sema.pt, sema.arena)).toIntern();
932935 next_idx.* += 1;
933936 return;
934937 }
......@@ -942,7 +945,7 @@ fn flattenArray(
942945 skip.* -= arr_base_elem_count;
943946 continue;
944947 }
945 try flattenArray(sema, try val.getElem(zcu, elem_idx), skip, next_idx, out);
948 try flattenArray(sema, try val.getElem(sema.pt, elem_idx), skip, next_idx, out);
946949 }
947950 if (ty.sentinel(zcu)) |s| {
948951 try flattenArray(sema, .{ .interned = s.toIntern() }, skip, next_idx, out);
......@@ -957,13 +960,13 @@ fn unflattenArray(
957960 elems: []const InternPool.Index,
958961 next_idx: *u64,
959962) Allocator.Error!Value {
960 const zcu = sema.mod;
963 const zcu = sema.pt.zcu;
961964 const arena = sema.arena;
962965
963966 if (ty.zigTypeTag(zcu) != .Array) {
964967 const val = Value.fromInterned(elems[@intCast(next_idx.*)]);
965968 next_idx.* += 1;
966 return zcu.getCoerced(val, ty);
969 return sema.pt.getCoerced(val, ty);
967970 }
968971
969972 const elem_ty = ty.childType(zcu);
......@@ -975,7 +978,7 @@ fn unflattenArray(
975978 // TODO: validate sentinel
976979 _ = try unflattenArray(sema, elem_ty, elems, next_idx);
977980 }
978 return Value.fromInterned(try zcu.intern(.{ .aggregate = .{
981 return Value.fromInterned(try sema.pt.intern(.{ .aggregate = .{
979982 .ty = ty.toIntern(),
980983 .storage = .{ .elems = buf },
981984 } }));
......@@ -990,25 +993,25 @@ fn recursiveIndex(
990993 mv: *MutableValue,
991994 index: *u64,
992995) !?struct { *MutableValue, u64 } {
993 const zcu = sema.mod;
996 const pt = sema.pt;
994997
995 const ty = mv.typeOf(zcu);
996 assert(ty.zigTypeTag(zcu) == .Array);
998 const ty = mv.typeOf(pt.zcu);
999 assert(ty.zigTypeTag(pt.zcu) == .Array);
9971000
998 const ty_base_elems = ty.arrayBase(zcu)[1];
1001 const ty_base_elems = ty.arrayBase(pt.zcu)[1];
9991002 if (index.* >= ty_base_elems) {
10001003 index.* -= ty_base_elems;
10011004 return null;
10021005 }
10031006
1004 const elem_ty = ty.childType(zcu);
1005 if (elem_ty.zigTypeTag(zcu) != .Array) {
1006 assert(index.* < ty.arrayLenIncludingSentinel(zcu)); // should be handled by initial check
1007 const elem_ty = ty.childType(pt.zcu);
1008 if (elem_ty.zigTypeTag(pt.zcu) != .Array) {
1009 assert(index.* < ty.arrayLenIncludingSentinel(pt.zcu)); // should be handled by initial check
10071010 return .{ mv, index.* };
10081011 }
10091012
1010 for (0..@intCast(ty.arrayLenIncludingSentinel(zcu))) |elem_index| {
1011 if (try recursiveIndex(sema, try mv.elem(zcu, sema.arena, elem_index), index)) |result| {
1013 for (0..@intCast(ty.arrayLenIncludingSentinel(pt.zcu))) |elem_index| {
1014 if (try recursiveIndex(sema, try mv.elem(pt, sema.arena, elem_index), index)) |result| {
10121015 return result;
10131016 }
10141017 }
src/Type.zig+377-362
......@@ -136,16 +136,16 @@ pub fn format(ty: Type, comptime unused_fmt_string: []const u8, options: std.fmt
136136
137137pub const Formatter = std.fmt.Formatter(format2);
138138
139pub fn fmt(ty: Type, module: *Module) Formatter {
139pub fn fmt(ty: Type, pt: Zcu.PerThread) Formatter {
140140 return .{ .data = .{
141141 .ty = ty,
142 .module = module,
142 .pt = pt,
143143 } };
144144}
145145
146146const FormatContext = struct {
147147 ty: Type,
148 module: *Module,
148 pt: Zcu.PerThread,
149149};
150150
151151fn format2(
......@@ -156,7 +156,7 @@ fn format2(
156156) !void {
157157 comptime assert(unused_format_string.len == 0);
158158 _ = options;
159 return print(ctx.ty, writer, ctx.module);
159 return print(ctx.ty, writer, ctx.pt);
160160}
161161
162162pub fn fmtDebug(ty: Type) std.fmt.Formatter(dump) {
......@@ -178,7 +178,8 @@ pub fn dump(
178178
179179/// Prints a name suitable for `@typeName`.
180180/// TODO: take an `opt_sema` to pass to `fmtValue` when printing sentinels.
181pub fn print(ty: Type, writer: anytype, mod: *Module) @TypeOf(writer).Error!void {
181pub fn print(ty: Type, writer: anytype, pt: Zcu.PerThread) @TypeOf(writer).Error!void {
182 const mod = pt.zcu;
182183 const ip = &mod.intern_pool;
183184 switch (ip.indexToKey(ty.toIntern())) {
184185 .int_type => |int_type| {
......@@ -193,8 +194,8 @@ pub fn print(ty: Type, writer: anytype, mod: *Module) @TypeOf(writer).Error!void
193194
194195 if (info.sentinel != .none) switch (info.flags.size) {
195196 .One, .C => unreachable,
196 .Many => try writer.print("[*:{}]", .{Value.fromInterned(info.sentinel).fmtValue(mod, null)}),
197 .Slice => try writer.print("[:{}]", .{Value.fromInterned(info.sentinel).fmtValue(mod, null)}),
197 .Many => try writer.print("[*:{}]", .{Value.fromInterned(info.sentinel).fmtValue(pt, null)}),
198 .Slice => try writer.print("[:{}]", .{Value.fromInterned(info.sentinel).fmtValue(pt, null)}),
198199 } else switch (info.flags.size) {
199200 .One => try writer.writeAll("*"),
200201 .Many => try writer.writeAll("[*]"),
......@@ -208,7 +209,7 @@ pub fn print(ty: Type, writer: anytype, mod: *Module) @TypeOf(writer).Error!void
208209 const alignment = if (info.flags.alignment != .none)
209210 info.flags.alignment
210211 else
211 Type.fromInterned(info.child).abiAlignment(mod);
212 Type.fromInterned(info.child).abiAlignment(pt);
212213 try writer.print("align({d}", .{alignment.toByteUnits() orelse 0});
213214
214215 if (info.packed_offset.bit_offset != 0 or info.packed_offset.host_size != 0) {
......@@ -230,39 +231,39 @@ pub fn print(ty: Type, writer: anytype, mod: *Module) @TypeOf(writer).Error!void
230231 if (info.flags.is_volatile) try writer.writeAll("volatile ");
231232 if (info.flags.is_allowzero and info.flags.size != .C) try writer.writeAll("allowzero ");
232233
233 try print(Type.fromInterned(info.child), writer, mod);
234 try print(Type.fromInterned(info.child), writer, pt);
234235 return;
235236 },
236237 .array_type => |array_type| {
237238 if (array_type.sentinel == .none) {
238239 try writer.print("[{d}]", .{array_type.len});
239 try print(Type.fromInterned(array_type.child), writer, mod);
240 try print(Type.fromInterned(array_type.child), writer, pt);
240241 } else {
241242 try writer.print("[{d}:{}]", .{
242243 array_type.len,
243 Value.fromInterned(array_type.sentinel).fmtValue(mod, null),
244 Value.fromInterned(array_type.sentinel).fmtValue(pt, null),
244245 });
245 try print(Type.fromInterned(array_type.child), writer, mod);
246 try print(Type.fromInterned(array_type.child), writer, pt);
246247 }
247248 return;
248249 },
249250 .vector_type => |vector_type| {
250251 try writer.print("@Vector({d}, ", .{vector_type.len});
251 try print(Type.fromInterned(vector_type.child), writer, mod);
252 try print(Type.fromInterned(vector_type.child), writer, pt);
252253 try writer.writeAll(")");
253254 return;
254255 },
255256 .opt_type => |child| {
256257 try writer.writeByte('?');
257 return print(Type.fromInterned(child), writer, mod);
258 return print(Type.fromInterned(child), writer, pt);
258259 },
259260 .error_union_type => |error_union_type| {
260 try print(Type.fromInterned(error_union_type.error_set_type), writer, mod);
261 try print(Type.fromInterned(error_union_type.error_set_type), writer, pt);
261262 try writer.writeByte('!');
262263 if (error_union_type.payload_type == .generic_poison_type) {
263264 try writer.writeAll("anytype");
264265 } else {
265 try print(Type.fromInterned(error_union_type.payload_type), writer, mod);
266 try print(Type.fromInterned(error_union_type.payload_type), writer, pt);
266267 }
267268 return;
268269 },
......@@ -355,10 +356,10 @@ pub fn print(ty: Type, writer: anytype, mod: *Module) @TypeOf(writer).Error!void
355356 try writer.print("{}: ", .{anon_struct.names.get(ip)[i].fmt(&mod.intern_pool)});
356357 }
357358
358 try print(Type.fromInterned(field_ty), writer, mod);
359 try print(Type.fromInterned(field_ty), writer, pt);
359360
360361 if (val != .none) {
361 try writer.print(" = {}", .{Value.fromInterned(val).fmtValue(mod, null)});
362 try writer.print(" = {}", .{Value.fromInterned(val).fmtValue(pt, null)});
362363 }
363364 }
364365 try writer.writeAll("}");
......@@ -395,7 +396,7 @@ pub fn print(ty: Type, writer: anytype, mod: *Module) @TypeOf(writer).Error!void
395396 if (param_ty == .generic_poison_type) {
396397 try writer.writeAll("anytype");
397398 } else {
398 try print(Type.fromInterned(param_ty), writer, mod);
399 try print(Type.fromInterned(param_ty), writer, pt);
399400 }
400401 }
401402 if (fn_info.is_var_args) {
......@@ -413,13 +414,13 @@ pub fn print(ty: Type, writer: anytype, mod: *Module) @TypeOf(writer).Error!void
413414 if (fn_info.return_type == .generic_poison_type) {
414415 try writer.writeAll("anytype");
415416 } else {
416 try print(Type.fromInterned(fn_info.return_type), writer, mod);
417 try print(Type.fromInterned(fn_info.return_type), writer, pt);
417418 }
418419 },
419420 .anyframe_type => |child| {
420421 if (child == .none) return writer.writeAll("anyframe");
421422 try writer.writeAll("anyframe->");
422 return print(Type.fromInterned(child), writer, mod);
423 return print(Type.fromInterned(child), writer, pt);
423424 },
424425
425426 // values, not types
......@@ -475,10 +476,11 @@ const RuntimeBitsError = SemaError || error{NeedLazy};
475476/// may return false positives.
476477pub fn hasRuntimeBitsAdvanced(
477478 ty: Type,
478 mod: *Module,
479 pt: Zcu.PerThread,
479480 ignore_comptime_only: bool,
480481 strat: ResolveStratLazy,
481482) RuntimeBitsError!bool {
483 const mod = pt.zcu;
482484 const ip = &mod.intern_pool;
483485 return switch (ty.toIntern()) {
484486 // False because it is a comptime-only type.
......@@ -490,16 +492,16 @@ pub fn hasRuntimeBitsAdvanced(
490492 // to comptime-only types do not, with the exception of function pointers.
491493 if (ignore_comptime_only) return true;
492494 return switch (strat) {
493 .sema => !try ty.comptimeOnlyAdvanced(mod, .sema),
494 .eager => !ty.comptimeOnly(mod),
495 .sema => !try ty.comptimeOnlyAdvanced(pt, .sema),
496 .eager => !ty.comptimeOnly(pt),
495497 .lazy => error.NeedLazy,
496498 };
497499 },
498500 .anyframe_type => true,
499501 .array_type => |array_type| return array_type.lenIncludingSentinel() > 0 and
500 try Type.fromInterned(array_type.child).hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat),
502 try Type.fromInterned(array_type.child).hasRuntimeBitsAdvanced(pt, ignore_comptime_only, strat),
501503 .vector_type => |vector_type| return vector_type.len > 0 and
502 try Type.fromInterned(vector_type.child).hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat),
504 try Type.fromInterned(vector_type.child).hasRuntimeBitsAdvanced(pt, ignore_comptime_only, strat),
503505 .opt_type => |child| {
504506 const child_ty = Type.fromInterned(child);
505507 if (child_ty.isNoReturn(mod)) {
......@@ -508,8 +510,8 @@ pub fn hasRuntimeBitsAdvanced(
508510 }
509511 if (ignore_comptime_only) return true;
510512 return switch (strat) {
511 .sema => !try child_ty.comptimeOnlyAdvanced(mod, .sema),
512 .eager => !child_ty.comptimeOnly(mod),
513 .sema => !try child_ty.comptimeOnlyAdvanced(pt, .sema),
514 .eager => !child_ty.comptimeOnly(pt),
513515 .lazy => error.NeedLazy,
514516 };
515517 },
......@@ -580,14 +582,14 @@ pub fn hasRuntimeBitsAdvanced(
580582 return true;
581583 }
582584 switch (strat) {
583 .sema => try ty.resolveFields(mod),
585 .sema => try ty.resolveFields(pt),
584586 .eager => assert(struct_type.haveFieldTypes(ip)),
585587 .lazy => if (!struct_type.haveFieldTypes(ip)) return error.NeedLazy,
586588 }
587589 for (0..struct_type.field_types.len) |i| {
588590 if (struct_type.comptime_bits.getBit(ip, i)) continue;
589591 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
590 if (try field_ty.hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat))
592 if (try field_ty.hasRuntimeBitsAdvanced(pt, ignore_comptime_only, strat))
591593 return true;
592594 } else {
593595 return false;
......@@ -596,7 +598,7 @@ pub fn hasRuntimeBitsAdvanced(
596598 .anon_struct_type => |tuple| {
597599 for (tuple.types.get(ip), tuple.values.get(ip)) |field_ty, val| {
598600 if (val != .none) continue; // comptime field
599 if (try Type.fromInterned(field_ty).hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat)) return true;
601 if (try Type.fromInterned(field_ty).hasRuntimeBitsAdvanced(pt, ignore_comptime_only, strat)) return true;
600602 }
601603 return false;
602604 },
......@@ -617,21 +619,21 @@ pub fn hasRuntimeBitsAdvanced(
617619 // tag_ty will be `none` if this union's tag type is not resolved yet,
618620 // in which case we want control flow to continue down below.
619621 if (tag_ty != .none and
620 try Type.fromInterned(tag_ty).hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat))
622 try Type.fromInterned(tag_ty).hasRuntimeBitsAdvanced(pt, ignore_comptime_only, strat))
621623 {
622624 return true;
623625 }
624626 },
625627 }
626628 switch (strat) {
627 .sema => try ty.resolveFields(mod),
629 .sema => try ty.resolveFields(pt),
628630 .eager => assert(union_type.flagsPtr(ip).status.haveFieldTypes()),
629631 .lazy => if (!union_type.flagsPtr(ip).status.haveFieldTypes())
630632 return error.NeedLazy,
631633 }
632634 for (0..union_type.field_types.len) |field_index| {
633635 const field_ty = Type.fromInterned(union_type.field_types.get(ip)[field_index]);
634 if (try field_ty.hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat))
636 if (try field_ty.hasRuntimeBitsAdvanced(pt, ignore_comptime_only, strat))
635637 return true;
636638 } else {
637639 return false;
......@@ -639,7 +641,7 @@ pub fn hasRuntimeBitsAdvanced(
639641 },
640642
641643 .opaque_type => true,
642 .enum_type => Type.fromInterned(ip.loadEnumType(ty.toIntern()).tag_ty).hasRuntimeBitsAdvanced(mod, ignore_comptime_only, strat),
644 .enum_type => Type.fromInterned(ip.loadEnumType(ty.toIntern()).tag_ty).hasRuntimeBitsAdvanced(pt, ignore_comptime_only, strat),
643645
644646 // values, not types
645647 .undef,
......@@ -777,41 +779,41 @@ pub fn hasWellDefinedLayout(ty: Type, mod: *Module) bool {
777779 };
778780}
779781
780pub fn hasRuntimeBits(ty: Type, mod: *Module) bool {
781 return hasRuntimeBitsAdvanced(ty, mod, false, .eager) catch unreachable;
782pub fn hasRuntimeBits(ty: Type, pt: Zcu.PerThread) bool {
783 return hasRuntimeBitsAdvanced(ty, pt, false, .eager) catch unreachable;
782784}
783785
784pub fn hasRuntimeBitsIgnoreComptime(ty: Type, mod: *Module) bool {
785 return hasRuntimeBitsAdvanced(ty, mod, true, .eager) catch unreachable;
786pub fn hasRuntimeBitsIgnoreComptime(ty: Type, pt: Zcu.PerThread) bool {
787 return hasRuntimeBitsAdvanced(ty, pt, true, .eager) catch unreachable;
786788}
787789
788pub fn fnHasRuntimeBits(ty: Type, mod: *Module) bool {
789 return ty.fnHasRuntimeBitsAdvanced(mod, .normal) catch unreachable;
790pub fn fnHasRuntimeBits(ty: Type, pt: Zcu.PerThread) bool {
791 return ty.fnHasRuntimeBitsAdvanced(pt, .normal) catch unreachable;
790792}
791793
792794/// Determines whether a function type has runtime bits, i.e. whether a
793795/// function with this type can exist at runtime.
794796/// Asserts that `ty` is a function type.
795pub fn fnHasRuntimeBitsAdvanced(ty: Type, mod: *Module, strat: ResolveStrat) SemaError!bool {
796 const fn_info = mod.typeToFunc(ty).?;
797pub fn fnHasRuntimeBitsAdvanced(ty: Type, pt: Zcu.PerThread, strat: ResolveStrat) SemaError!bool {
798 const fn_info = pt.zcu.typeToFunc(ty).?;
797799 if (fn_info.is_generic) return false;
798800 if (fn_info.is_var_args) return true;
799801 if (fn_info.cc == .Inline) return false;
800 return !try Type.fromInterned(fn_info.return_type).comptimeOnlyAdvanced(mod, strat);
802 return !try Type.fromInterned(fn_info.return_type).comptimeOnlyAdvanced(pt, strat);
801803}
802804
803pub fn isFnOrHasRuntimeBits(ty: Type, mod: *Module) bool {
804 switch (ty.zigTypeTag(mod)) {
805 .Fn => return ty.fnHasRuntimeBits(mod),
806 else => return ty.hasRuntimeBits(mod),
805pub fn isFnOrHasRuntimeBits(ty: Type, pt: Zcu.PerThread) bool {
806 switch (ty.zigTypeTag(pt.zcu)) {
807 .Fn => return ty.fnHasRuntimeBits(pt),
808 else => return ty.hasRuntimeBits(pt),
807809 }
808810}
809811
810812/// Same as `isFnOrHasRuntimeBits` but comptime-only types may return a false positive.
811pub fn isFnOrHasRuntimeBitsIgnoreComptime(ty: Type, mod: *Module) bool {
812 return switch (ty.zigTypeTag(mod)) {
813pub fn isFnOrHasRuntimeBitsIgnoreComptime(ty: Type, pt: Zcu.PerThread) bool {
814 return switch (ty.zigTypeTag(pt.zcu)) {
813815 .Fn => true,
814 else => return ty.hasRuntimeBitsIgnoreComptime(mod),
816 else => return ty.hasRuntimeBitsIgnoreComptime(pt),
815817 };
816818}
817819
......@@ -820,24 +822,24 @@ pub fn isNoReturn(ty: Type, mod: *Module) bool {
820822}
821823
822824/// Returns `none` if the pointer is naturally aligned and the element type is 0-bit.
823pub fn ptrAlignment(ty: Type, mod: *Module) Alignment {
824 return ptrAlignmentAdvanced(ty, mod, .normal) catch unreachable;
825pub fn ptrAlignment(ty: Type, pt: Zcu.PerThread) Alignment {
826 return ptrAlignmentAdvanced(ty, pt, .normal) catch unreachable;
825827}
826828
827pub fn ptrAlignmentAdvanced(ty: Type, mod: *Module, strat: ResolveStrat) !Alignment {
828 return switch (mod.intern_pool.indexToKey(ty.toIntern())) {
829pub fn ptrAlignmentAdvanced(ty: Type, pt: Zcu.PerThread, strat: ResolveStrat) !Alignment {
830 return switch (pt.zcu.intern_pool.indexToKey(ty.toIntern())) {
829831 .ptr_type => |ptr_type| {
830832 if (ptr_type.flags.alignment != .none)
831833 return ptr_type.flags.alignment;
832834
833835 if (strat == .sema) {
834 const res = try Type.fromInterned(ptr_type.child).abiAlignmentAdvanced(mod, .sema);
836 const res = try Type.fromInterned(ptr_type.child).abiAlignmentAdvanced(pt, .sema);
835837 return res.scalar;
836838 }
837839
838 return (Type.fromInterned(ptr_type.child).abiAlignmentAdvanced(mod, .eager) catch unreachable).scalar;
840 return (Type.fromInterned(ptr_type.child).abiAlignmentAdvanced(pt, .eager) catch unreachable).scalar;
839841 },
840 .opt_type => |child| Type.fromInterned(child).ptrAlignmentAdvanced(mod, strat),
842 .opt_type => |child| Type.fromInterned(child).ptrAlignmentAdvanced(pt, strat),
841843 else => unreachable,
842844 };
843845}
......@@ -851,16 +853,16 @@ pub fn ptrAddressSpace(ty: Type, mod: *const Module) std.builtin.AddressSpace {
851853}
852854
853855/// Never returns `none`. Asserts that all necessary type resolution is already done.
854pub fn abiAlignment(ty: Type, mod: *Module) Alignment {
855 return (ty.abiAlignmentAdvanced(mod, .eager) catch unreachable).scalar;
856pub fn abiAlignment(ty: Type, pt: Zcu.PerThread) Alignment {
857 return (ty.abiAlignmentAdvanced(pt, .eager) catch unreachable).scalar;
856858}
857859
858860/// May capture a reference to `ty`.
859861/// Returned value has type `comptime_int`.
860pub fn lazyAbiAlignment(ty: Type, mod: *Module) !Value {
861 switch (try ty.abiAlignmentAdvanced(mod, .lazy)) {
862pub fn lazyAbiAlignment(ty: Type, pt: Zcu.PerThread) !Value {
863 switch (try ty.abiAlignmentAdvanced(pt, .lazy)) {
862864 .val => |val| return val,
863 .scalar => |x| return mod.intValue(Type.comptime_int, x.toByteUnits() orelse 0),
865 .scalar => |x| return pt.intValue(Type.comptime_int, x.toByteUnits() orelse 0),
864866 }
865867}
866868
......@@ -907,38 +909,39 @@ pub const ResolveStrat = enum {
907909/// necessary, possibly returning a CompileError.
908910pub fn abiAlignmentAdvanced(
909911 ty: Type,
910 mod: *Module,
912 pt: Zcu.PerThread,
911913 strat: ResolveStratLazy,
912914) SemaError!AbiAlignmentAdvanced {
915 const mod = pt.zcu;
913916 const target = mod.getTarget();
914917 const use_llvm = mod.comp.config.use_llvm;
915918 const ip = &mod.intern_pool;
916919
917920 switch (ty.toIntern()) {
918 .empty_struct_type => return AbiAlignmentAdvanced{ .scalar = .@"1" },
921 .empty_struct_type => return .{ .scalar = .@"1" },
919922 else => switch (ip.indexToKey(ty.toIntern())) {
920923 .int_type => |int_type| {
921 if (int_type.bits == 0) return AbiAlignmentAdvanced{ .scalar = .@"1" };
924 if (int_type.bits == 0) return .{ .scalar = .@"1" };
922925 return .{ .scalar = intAbiAlignment(int_type.bits, target, use_llvm) };
923926 },
924927 .ptr_type, .anyframe_type => {
925928 return .{ .scalar = ptrAbiAlignment(target) };
926929 },
927930 .array_type => |array_type| {
928 return Type.fromInterned(array_type.child).abiAlignmentAdvanced(mod, strat);
931 return Type.fromInterned(array_type.child).abiAlignmentAdvanced(pt, strat);
929932 },
930933 .vector_type => |vector_type| {
931934 if (vector_type.len == 0) return .{ .scalar = .@"1" };
932935 switch (mod.comp.getZigBackend()) {
933936 else => {
934 const elem_bits: u32 = @intCast(try Type.fromInterned(vector_type.child).bitSizeAdvanced(mod, .sema));
937 const elem_bits: u32 = @intCast(try Type.fromInterned(vector_type.child).bitSizeAdvanced(pt, .sema));
935938 if (elem_bits == 0) return .{ .scalar = .@"1" };
936939 const bytes = ((elem_bits * vector_type.len) + 7) / 8;
937940 const alignment = std.math.ceilPowerOfTwoAssert(u32, bytes);
938941 return .{ .scalar = Alignment.fromByteUnits(alignment) };
939942 },
940943 .stage2_c => {
941 return Type.fromInterned(vector_type.child).abiAlignmentAdvanced(mod, strat);
944 return Type.fromInterned(vector_type.child).abiAlignmentAdvanced(pt, strat);
942945 },
943946 .stage2_x86_64 => {
944947 if (vector_type.child == .bool_type) {
......@@ -949,7 +952,7 @@ pub fn abiAlignmentAdvanced(
949952 const alignment = std.math.ceilPowerOfTwoAssert(u32, bytes);
950953 return .{ .scalar = Alignment.fromByteUnits(alignment) };
951954 }
952 const elem_bytes: u32 = @intCast((try Type.fromInterned(vector_type.child).abiSizeAdvanced(mod, strat)).scalar);
955 const elem_bytes: u32 = @intCast((try Type.fromInterned(vector_type.child).abiSizeAdvanced(pt, strat)).scalar);
953956 if (elem_bytes == 0) return .{ .scalar = .@"1" };
954957 const bytes = elem_bytes * vector_type.len;
955958 if (bytes > 32 and std.Target.x86.featureSetHas(target.cpu.features, .avx512f)) return .{ .scalar = .@"64" };
......@@ -959,12 +962,12 @@ pub fn abiAlignmentAdvanced(
959962 }
960963 },
961964
962 .opt_type => return abiAlignmentAdvancedOptional(ty, mod, strat),
963 .error_union_type => |info| return abiAlignmentAdvancedErrorUnion(ty, mod, strat, Type.fromInterned(info.payload_type)),
965 .opt_type => return ty.abiAlignmentAdvancedOptional(pt, strat),
966 .error_union_type => |info| return ty.abiAlignmentAdvancedErrorUnion(pt, strat, Type.fromInterned(info.payload_type)),
964967
965968 .error_set_type, .inferred_error_set_type => {
966969 const bits = mod.errorSetBits();
967 if (bits == 0) return AbiAlignmentAdvanced{ .scalar = .@"1" };
970 if (bits == 0) return .{ .scalar = .@"1" };
968971 return .{ .scalar = intAbiAlignment(bits, target, use_llvm) };
969972 },
970973
......@@ -1012,10 +1015,7 @@ pub fn abiAlignmentAdvanced(
10121015 },
10131016 .f80 => switch (target.c_type_bit_size(.longdouble)) {
10141017 80 => return .{ .scalar = cTypeAlign(target, .longdouble) },
1015 else => {
1016 const u80_ty: Type = .{ .ip_index = .u80_type };
1017 return .{ .scalar = abiAlignment(u80_ty, mod) };
1018 },
1018 else => return .{ .scalar = Type.u80.abiAlignment(pt) },
10191019 },
10201020 .f128 => switch (target.c_type_bit_size(.longdouble)) {
10211021 128 => return .{ .scalar = cTypeAlign(target, .longdouble) },
......@@ -1024,7 +1024,7 @@ pub fn abiAlignmentAdvanced(
10241024
10251025 .anyerror, .adhoc_inferred_error_set => {
10261026 const bits = mod.errorSetBits();
1027 if (bits == 0) return AbiAlignmentAdvanced{ .scalar = .@"1" };
1027 if (bits == 0) return .{ .scalar = .@"1" };
10281028 return .{ .scalar = intAbiAlignment(bits, target, use_llvm) };
10291029 },
10301030
......@@ -1044,22 +1044,22 @@ pub fn abiAlignmentAdvanced(
10441044 const struct_type = ip.loadStructType(ty.toIntern());
10451045 if (struct_type.layout == .@"packed") {
10461046 switch (strat) {
1047 .sema => try ty.resolveLayout(mod),
1047 .sema => try ty.resolveLayout(pt),
10481048 .lazy => if (struct_type.backingIntType(ip).* == .none) return .{
1049 .val = Value.fromInterned((try mod.intern(.{ .int = .{
1049 .val = Value.fromInterned(try pt.intern(.{ .int = .{
10501050 .ty = .comptime_int_type,
10511051 .storage = .{ .lazy_align = ty.toIntern() },
1052 } }))),
1052 } })),
10531053 },
10541054 .eager => {},
10551055 }
1056 return .{ .scalar = Type.fromInterned(struct_type.backingIntType(ip).*).abiAlignment(mod) };
1056 return .{ .scalar = Type.fromInterned(struct_type.backingIntType(ip).*).abiAlignment(pt) };
10571057 }
10581058
10591059 if (struct_type.flagsPtr(ip).alignment == .none) switch (strat) {
10601060 .eager => unreachable, // struct alignment not resolved
1061 .sema => try ty.resolveStructAlignment(mod),
1062 .lazy => return .{ .val = Value.fromInterned(try mod.intern(.{ .int = .{
1061 .sema => try ty.resolveStructAlignment(pt),
1062 .lazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
10631063 .ty = .comptime_int_type,
10641064 .storage = .{ .lazy_align = ty.toIntern() },
10651065 } })) },
......@@ -1071,15 +1071,15 @@ pub fn abiAlignmentAdvanced(
10711071 var big_align: Alignment = .@"1";
10721072 for (tuple.types.get(ip), tuple.values.get(ip)) |field_ty, val| {
10731073 if (val != .none) continue; // comptime field
1074 switch (try Type.fromInterned(field_ty).abiAlignmentAdvanced(mod, strat)) {
1074 switch (try Type.fromInterned(field_ty).abiAlignmentAdvanced(pt, strat)) {
10751075 .scalar => |field_align| big_align = big_align.max(field_align),
10761076 .val => switch (strat) {
10771077 .eager => unreachable, // field type alignment not resolved
10781078 .sema => unreachable, // passed to abiAlignmentAdvanced above
1079 .lazy => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1079 .lazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
10801080 .ty = .comptime_int_type,
10811081 .storage = .{ .lazy_align = ty.toIntern() },
1082 } }))) },
1082 } })) },
10831083 },
10841084 }
10851085 }
......@@ -1090,18 +1090,18 @@ pub fn abiAlignmentAdvanced(
10901090
10911091 if (union_type.flagsPtr(ip).alignment == .none) switch (strat) {
10921092 .eager => unreachable, // union layout not resolved
1093 .sema => try ty.resolveUnionAlignment(mod),
1094 .lazy => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1093 .sema => try ty.resolveUnionAlignment(pt),
1094 .lazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
10951095 .ty = .comptime_int_type,
10961096 .storage = .{ .lazy_align = ty.toIntern() },
1097 } }))) },
1097 } })) },
10981098 };
10991099
11001100 return .{ .scalar = union_type.flagsPtr(ip).alignment };
11011101 },
11021102 .opaque_type => return .{ .scalar = .@"1" },
11031103 .enum_type => return .{
1104 .scalar = Type.fromInterned(ip.loadEnumType(ty.toIntern()).tag_ty).abiAlignment(mod),
1104 .scalar = Type.fromInterned(ip.loadEnumType(ty.toIntern()).tag_ty).abiAlignment(pt),
11051105 },
11061106
11071107 // values, not types
......@@ -1131,91 +1131,92 @@ pub fn abiAlignmentAdvanced(
11311131
11321132fn abiAlignmentAdvancedErrorUnion(
11331133 ty: Type,
1134 mod: *Module,
1134 pt: Zcu.PerThread,
11351135 strat: ResolveStratLazy,
11361136 payload_ty: Type,
11371137) SemaError!AbiAlignmentAdvanced {
11381138 // This code needs to be kept in sync with the equivalent switch prong
11391139 // in abiSizeAdvanced.
1140 const code_align = abiAlignment(Type.anyerror, mod);
1140 const code_align = Type.anyerror.abiAlignment(pt);
11411141 switch (strat) {
11421142 .eager, .sema => {
1143 if (!(payload_ty.hasRuntimeBitsAdvanced(mod, false, strat) catch |err| switch (err) {
1144 error.NeedLazy => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1143 if (!(payload_ty.hasRuntimeBitsAdvanced(pt, false, strat) catch |err| switch (err) {
1144 error.NeedLazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
11451145 .ty = .comptime_int_type,
11461146 .storage = .{ .lazy_align = ty.toIntern() },
1147 } }))) },
1147 } })) },
11481148 else => |e| return e,
11491149 })) {
11501150 return .{ .scalar = code_align };
11511151 }
11521152 return .{ .scalar = code_align.max(
1153 (try payload_ty.abiAlignmentAdvanced(mod, strat)).scalar,
1153 (try payload_ty.abiAlignmentAdvanced(pt, strat)).scalar,
11541154 ) };
11551155 },
11561156 .lazy => {
1157 switch (try payload_ty.abiAlignmentAdvanced(mod, strat)) {
1157 switch (try payload_ty.abiAlignmentAdvanced(pt, strat)) {
11581158 .scalar => |payload_align| return .{ .scalar = code_align.max(payload_align) },
11591159 .val => {},
11601160 }
1161 return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1161 return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
11621162 .ty = .comptime_int_type,
11631163 .storage = .{ .lazy_align = ty.toIntern() },
1164 } }))) };
1164 } })) };
11651165 },
11661166 }
11671167}
11681168
11691169fn abiAlignmentAdvancedOptional(
11701170 ty: Type,
1171 mod: *Module,
1171 pt: Zcu.PerThread,
11721172 strat: ResolveStratLazy,
11731173) SemaError!AbiAlignmentAdvanced {
1174 const mod = pt.zcu;
11741175 const target = mod.getTarget();
11751176 const child_type = ty.optionalChild(mod);
11761177
11771178 switch (child_type.zigTypeTag(mod)) {
11781179 .Pointer => return .{ .scalar = ptrAbiAlignment(target) },
1179 .ErrorSet => return abiAlignmentAdvanced(Type.anyerror, mod, strat),
1180 .ErrorSet => return Type.anyerror.abiAlignmentAdvanced(pt, strat),
11801181 .NoReturn => return .{ .scalar = .@"1" },
11811182 else => {},
11821183 }
11831184
11841185 switch (strat) {
11851186 .eager, .sema => {
1186 if (!(child_type.hasRuntimeBitsAdvanced(mod, false, strat) catch |err| switch (err) {
1187 error.NeedLazy => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1187 if (!(child_type.hasRuntimeBitsAdvanced(pt, false, strat) catch |err| switch (err) {
1188 error.NeedLazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
11881189 .ty = .comptime_int_type,
11891190 .storage = .{ .lazy_align = ty.toIntern() },
1190 } }))) },
1191 } })) },
11911192 else => |e| return e,
11921193 })) {
11931194 return .{ .scalar = .@"1" };
11941195 }
1195 return child_type.abiAlignmentAdvanced(mod, strat);
1196 return child_type.abiAlignmentAdvanced(pt, strat);
11961197 },
1197 .lazy => switch (try child_type.abiAlignmentAdvanced(mod, strat)) {
1198 .lazy => switch (try child_type.abiAlignmentAdvanced(pt, strat)) {
11981199 .scalar => |x| return .{ .scalar = x.max(.@"1") },
1199 .val => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1200 .val => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
12001201 .ty = .comptime_int_type,
12011202 .storage = .{ .lazy_align = ty.toIntern() },
1202 } }))) },
1203 } })) },
12031204 },
12041205 }
12051206}
12061207
12071208/// May capture a reference to `ty`.
1208pub fn lazyAbiSize(ty: Type, mod: *Module) !Value {
1209 switch (try ty.abiSizeAdvanced(mod, .lazy)) {
1209pub fn lazyAbiSize(ty: Type, pt: Zcu.PerThread) !Value {
1210 switch (try ty.abiSizeAdvanced(pt, .lazy)) {
12101211 .val => |val| return val,
1211 .scalar => |x| return mod.intValue(Type.comptime_int, x),
1212 .scalar => |x| return pt.intValue(Type.comptime_int, x),
12121213 }
12131214}
12141215
12151216/// Asserts the type has the ABI size already resolved.
12161217/// Types that return false for hasRuntimeBits() return 0.
1217pub fn abiSize(ty: Type, mod: *Module) u64 {
1218 return (abiSizeAdvanced(ty, mod, .eager) catch unreachable).scalar;
1218pub fn abiSize(ty: Type, pt: Zcu.PerThread) u64 {
1219 return (abiSizeAdvanced(ty, pt, .eager) catch unreachable).scalar;
12191220}
12201221
12211222const AbiSizeAdvanced = union(enum) {
......@@ -1231,38 +1232,39 @@ const AbiSizeAdvanced = union(enum) {
12311232/// necessary, possibly returning a CompileError.
12321233pub fn abiSizeAdvanced(
12331234 ty: Type,
1234 mod: *Module,
1235 pt: Zcu.PerThread,
12351236 strat: ResolveStratLazy,
12361237) SemaError!AbiSizeAdvanced {
1238 const mod = pt.zcu;
12371239 const target = mod.getTarget();
12381240 const use_llvm = mod.comp.config.use_llvm;
12391241 const ip = &mod.intern_pool;
12401242
12411243 switch (ty.toIntern()) {
1242 .empty_struct_type => return AbiSizeAdvanced{ .scalar = 0 },
1244 .empty_struct_type => return .{ .scalar = 0 },
12431245
12441246 else => switch (ip.indexToKey(ty.toIntern())) {
12451247 .int_type => |int_type| {
1246 if (int_type.bits == 0) return AbiSizeAdvanced{ .scalar = 0 };
1247 return AbiSizeAdvanced{ .scalar = intAbiSize(int_type.bits, target, use_llvm) };
1248 if (int_type.bits == 0) return .{ .scalar = 0 };
1249 return .{ .scalar = intAbiSize(int_type.bits, target, use_llvm) };
12481250 },
12491251 .ptr_type => |ptr_type| switch (ptr_type.flags.size) {
12501252 .Slice => return .{ .scalar = @divExact(target.ptrBitWidth(), 8) * 2 },
12511253 else => return .{ .scalar = @divExact(target.ptrBitWidth(), 8) },
12521254 },
1253 .anyframe_type => return AbiSizeAdvanced{ .scalar = @divExact(target.ptrBitWidth(), 8) },
1255 .anyframe_type => return .{ .scalar = @divExact(target.ptrBitWidth(), 8) },
12541256
12551257 .array_type => |array_type| {
12561258 const len = array_type.lenIncludingSentinel();
12571259 if (len == 0) return .{ .scalar = 0 };
1258 switch (try Type.fromInterned(array_type.child).abiSizeAdvanced(mod, strat)) {
1260 switch (try Type.fromInterned(array_type.child).abiSizeAdvanced(pt, strat)) {
12591261 .scalar => |elem_size| return .{ .scalar = len * elem_size },
12601262 .val => switch (strat) {
12611263 .sema, .eager => unreachable,
1262 .lazy => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1264 .lazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
12631265 .ty = .comptime_int_type,
12641266 .storage = .{ .lazy_size = ty.toIntern() },
1265 } }))) },
1267 } })) },
12661268 },
12671269 }
12681270 },
......@@ -1270,71 +1272,71 @@ pub fn abiSizeAdvanced(
12701272 const sub_strat: ResolveStrat = switch (strat) {
12711273 .sema => .sema,
12721274 .eager => .normal,
1273 .lazy => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1275 .lazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
12741276 .ty = .comptime_int_type,
12751277 .storage = .{ .lazy_size = ty.toIntern() },
1276 } }))) },
1278 } })) },
12771279 };
1278 const alignment = switch (try ty.abiAlignmentAdvanced(mod, strat)) {
1280 const alignment = switch (try ty.abiAlignmentAdvanced(pt, strat)) {
12791281 .scalar => |x| x,
1280 .val => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1282 .val => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
12811283 .ty = .comptime_int_type,
12821284 .storage = .{ .lazy_size = ty.toIntern() },
1283 } }))) },
1285 } })) },
12841286 };
12851287 const total_bytes = switch (mod.comp.getZigBackend()) {
12861288 else => total_bytes: {
1287 const elem_bits = try Type.fromInterned(vector_type.child).bitSizeAdvanced(mod, sub_strat);
1289 const elem_bits = try Type.fromInterned(vector_type.child).bitSizeAdvanced(pt, sub_strat);
12881290 const total_bits = elem_bits * vector_type.len;
12891291 break :total_bytes (total_bits + 7) / 8;
12901292 },
12911293 .stage2_c => total_bytes: {
1292 const elem_bytes: u32 = @intCast((try Type.fromInterned(vector_type.child).abiSizeAdvanced(mod, strat)).scalar);
1294 const elem_bytes: u32 = @intCast((try Type.fromInterned(vector_type.child).abiSizeAdvanced(pt, strat)).scalar);
12931295 break :total_bytes elem_bytes * vector_type.len;
12941296 },
12951297 .stage2_x86_64 => total_bytes: {
12961298 if (vector_type.child == .bool_type) break :total_bytes std.math.divCeil(u32, vector_type.len, 8) catch unreachable;
1297 const elem_bytes: u32 = @intCast((try Type.fromInterned(vector_type.child).abiSizeAdvanced(mod, strat)).scalar);
1299 const elem_bytes: u32 = @intCast((try Type.fromInterned(vector_type.child).abiSizeAdvanced(pt, strat)).scalar);
12981300 break :total_bytes elem_bytes * vector_type.len;
12991301 },
13001302 };
1301 return AbiSizeAdvanced{ .scalar = alignment.forward(total_bytes) };
1303 return .{ .scalar = alignment.forward(total_bytes) };
13021304 },
13031305
1304 .opt_type => return ty.abiSizeAdvancedOptional(mod, strat),
1306 .opt_type => return ty.abiSizeAdvancedOptional(pt, strat),
13051307
13061308 .error_set_type, .inferred_error_set_type => {
13071309 const bits = mod.errorSetBits();
1308 if (bits == 0) return AbiSizeAdvanced{ .scalar = 0 };
1309 return AbiSizeAdvanced{ .scalar = intAbiSize(bits, target, use_llvm) };
1310 if (bits == 0) return .{ .scalar = 0 };
1311 return .{ .scalar = intAbiSize(bits, target, use_llvm) };
13101312 },
13111313
13121314 .error_union_type => |error_union_type| {
13131315 const payload_ty = Type.fromInterned(error_union_type.payload_type);
13141316 // This code needs to be kept in sync with the equivalent switch prong
13151317 // in abiAlignmentAdvanced.
1316 const code_size = abiSize(Type.anyerror, mod);
1317 if (!(payload_ty.hasRuntimeBitsAdvanced(mod, false, strat) catch |err| switch (err) {
1318 error.NeedLazy => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1318 const code_size = Type.anyerror.abiSize(pt);
1319 if (!(payload_ty.hasRuntimeBitsAdvanced(pt, false, strat) catch |err| switch (err) {
1320 error.NeedLazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
13191321 .ty = .comptime_int_type,
13201322 .storage = .{ .lazy_size = ty.toIntern() },
1321 } }))) },
1323 } })) },
13221324 else => |e| return e,
13231325 })) {
13241326 // Same as anyerror.
1325 return AbiSizeAdvanced{ .scalar = code_size };
1327 return .{ .scalar = code_size };
13261328 }
1327 const code_align = abiAlignment(Type.anyerror, mod);
1328 const payload_align = abiAlignment(payload_ty, mod);
1329 const payload_size = switch (try payload_ty.abiSizeAdvanced(mod, strat)) {
1329 const code_align = Type.anyerror.abiAlignment(pt);
1330 const payload_align = payload_ty.abiAlignment(pt);
1331 const payload_size = switch (try payload_ty.abiSizeAdvanced(pt, strat)) {
13301332 .scalar => |elem_size| elem_size,
13311333 .val => switch (strat) {
13321334 .sema => unreachable,
13331335 .eager => unreachable,
1334 .lazy => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1336 .lazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
13351337 .ty = .comptime_int_type,
13361338 .storage = .{ .lazy_size = ty.toIntern() },
1337 } }))) },
1339 } })) },
13381340 },
13391341 };
13401342
......@@ -1350,7 +1352,7 @@ pub fn abiSizeAdvanced(
13501352 size += code_size;
13511353 size = payload_align.forward(size);
13521354 }
1353 return AbiSizeAdvanced{ .scalar = size };
1355 return .{ .scalar = size };
13541356 },
13551357 .func_type => unreachable, // represents machine code; not a pointer
13561358 .simple_type => |t| switch (t) {
......@@ -1362,34 +1364,31 @@ pub fn abiSizeAdvanced(
13621364 .float_mode,
13631365 .reduce_op,
13641366 .call_modifier,
1365 => return AbiSizeAdvanced{ .scalar = 1 },
1367 => return .{ .scalar = 1 },
13661368
1367 .f16 => return AbiSizeAdvanced{ .scalar = 2 },
1368 .f32 => return AbiSizeAdvanced{ .scalar = 4 },
1369 .f64 => return AbiSizeAdvanced{ .scalar = 8 },
1370 .f128 => return AbiSizeAdvanced{ .scalar = 16 },
1369 .f16 => return .{ .scalar = 2 },
1370 .f32 => return .{ .scalar = 4 },
1371 .f64 => return .{ .scalar = 8 },
1372 .f128 => return .{ .scalar = 16 },
13711373 .f80 => switch (target.c_type_bit_size(.longdouble)) {
1372 80 => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.longdouble) },
1373 else => {
1374 const u80_ty: Type = .{ .ip_index = .u80_type };
1375 return AbiSizeAdvanced{ .scalar = abiSize(u80_ty, mod) };
1376 },
1374 80 => return .{ .scalar = target.c_type_byte_size(.longdouble) },
1375 else => return .{ .scalar = Type.u80.abiSize(pt) },
13771376 },
13781377
13791378 .usize,
13801379 .isize,
1381 => return AbiSizeAdvanced{ .scalar = @divExact(target.ptrBitWidth(), 8) },
1382
1383 .c_char => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.char) },
1384 .c_short => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.short) },
1385 .c_ushort => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.ushort) },
1386 .c_int => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.int) },
1387 .c_uint => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.uint) },
1388 .c_long => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.long) },
1389 .c_ulong => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.ulong) },
1390 .c_longlong => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.longlong) },
1391 .c_ulonglong => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.ulonglong) },
1392 .c_longdouble => return AbiSizeAdvanced{ .scalar = target.c_type_byte_size(.longdouble) },
1380 => return .{ .scalar = @divExact(target.ptrBitWidth(), 8) },
1381
1382 .c_char => return .{ .scalar = target.c_type_byte_size(.char) },
1383 .c_short => return .{ .scalar = target.c_type_byte_size(.short) },
1384 .c_ushort => return .{ .scalar = target.c_type_byte_size(.ushort) },
1385 .c_int => return .{ .scalar = target.c_type_byte_size(.int) },
1386 .c_uint => return .{ .scalar = target.c_type_byte_size(.uint) },
1387 .c_long => return .{ .scalar = target.c_type_byte_size(.long) },
1388 .c_ulong => return .{ .scalar = target.c_type_byte_size(.ulong) },
1389 .c_longlong => return .{ .scalar = target.c_type_byte_size(.longlong) },
1390 .c_ulonglong => return .{ .scalar = target.c_type_byte_size(.ulonglong) },
1391 .c_longdouble => return .{ .scalar = target.c_type_byte_size(.longdouble) },
13931392
13941393 .anyopaque,
13951394 .void,
......@@ -1399,12 +1398,12 @@ pub fn abiSizeAdvanced(
13991398 .null,
14001399 .undefined,
14011400 .enum_literal,
1402 => return AbiSizeAdvanced{ .scalar = 0 },
1401 => return .{ .scalar = 0 },
14031402
14041403 .anyerror, .adhoc_inferred_error_set => {
14051404 const bits = mod.errorSetBits();
1406 if (bits == 0) return AbiSizeAdvanced{ .scalar = 0 };
1407 return AbiSizeAdvanced{ .scalar = intAbiSize(bits, target, use_llvm) };
1405 if (bits == 0) return .{ .scalar = 0 };
1406 return .{ .scalar = intAbiSize(bits, target, use_llvm) };
14081407 },
14091408
14101409 .prefetch_options => unreachable, // missing call to resolveTypeFields
......@@ -1418,22 +1417,22 @@ pub fn abiSizeAdvanced(
14181417 .struct_type => {
14191418 const struct_type = ip.loadStructType(ty.toIntern());
14201419 switch (strat) {
1421 .sema => try ty.resolveLayout(mod),
1420 .sema => try ty.resolveLayout(pt),
14221421 .lazy => switch (struct_type.layout) {
14231422 .@"packed" => {
14241423 if (struct_type.backingIntType(ip).* == .none) return .{
1425 .val = Value.fromInterned((try mod.intern(.{ .int = .{
1424 .val = Value.fromInterned(try pt.intern(.{ .int = .{
14261425 .ty = .comptime_int_type,
14271426 .storage = .{ .lazy_size = ty.toIntern() },
1428 } }))),
1427 } })),
14291428 };
14301429 },
14311430 .auto, .@"extern" => {
14321431 if (!struct_type.haveLayout(ip)) return .{
1433 .val = Value.fromInterned((try mod.intern(.{ .int = .{
1432 .val = Value.fromInterned(try pt.intern(.{ .int = .{
14341433 .ty = .comptime_int_type,
14351434 .storage = .{ .lazy_size = ty.toIntern() },
1436 } }))),
1435 } })),
14371436 };
14381437 },
14391438 },
......@@ -1441,7 +1440,7 @@ pub fn abiSizeAdvanced(
14411440 }
14421441 switch (struct_type.layout) {
14431442 .@"packed" => return .{
1444 .scalar = Type.fromInterned(struct_type.backingIntType(ip).*).abiSize(mod),
1443 .scalar = Type.fromInterned(struct_type.backingIntType(ip).*).abiSize(pt),
14451444 },
14461445 .auto, .@"extern" => {
14471446 assert(struct_type.haveLayout(ip));
......@@ -1451,25 +1450,25 @@ pub fn abiSizeAdvanced(
14511450 },
14521451 .anon_struct_type => |tuple| {
14531452 switch (strat) {
1454 .sema => try ty.resolveLayout(mod),
1453 .sema => try ty.resolveLayout(pt),
14551454 .lazy, .eager => {},
14561455 }
14571456 const field_count = tuple.types.len;
14581457 if (field_count == 0) {
1459 return AbiSizeAdvanced{ .scalar = 0 };
1458 return .{ .scalar = 0 };
14601459 }
1461 return AbiSizeAdvanced{ .scalar = ty.structFieldOffset(field_count, mod) };
1460 return .{ .scalar = ty.structFieldOffset(field_count, pt) };
14621461 },
14631462
14641463 .union_type => {
14651464 const union_type = ip.loadUnionType(ty.toIntern());
14661465 switch (strat) {
1467 .sema => try ty.resolveLayout(mod),
1466 .sema => try ty.resolveLayout(pt),
14681467 .lazy => if (!union_type.flagsPtr(ip).status.haveLayout()) return .{
1469 .val = Value.fromInterned((try mod.intern(.{ .int = .{
1468 .val = Value.fromInterned(try pt.intern(.{ .int = .{
14701469 .ty = .comptime_int_type,
14711470 .storage = .{ .lazy_size = ty.toIntern() },
1472 } }))),
1471 } })),
14731472 },
14741473 .eager => {},
14751474 }
......@@ -1478,7 +1477,7 @@ pub fn abiSizeAdvanced(
14781477 return .{ .scalar = union_type.size(ip).* };
14791478 },
14801479 .opaque_type => unreachable, // no size available
1481 .enum_type => return .{ .scalar = Type.fromInterned(ip.loadEnumType(ty.toIntern()).tag_ty).abiSize(mod) },
1480 .enum_type => return .{ .scalar = Type.fromInterned(ip.loadEnumType(ty.toIntern()).tag_ty).abiSize(pt) },
14821481
14831482 // values, not types
14841483 .undef,
......@@ -1507,36 +1506,37 @@ pub fn abiSizeAdvanced(
15071506
15081507fn abiSizeAdvancedOptional(
15091508 ty: Type,
1510 mod: *Module,
1509 pt: Zcu.PerThread,
15111510 strat: ResolveStratLazy,
15121511) SemaError!AbiSizeAdvanced {
1512 const mod = pt.zcu;
15131513 const child_ty = ty.optionalChild(mod);
15141514
15151515 if (child_ty.isNoReturn(mod)) {
1516 return AbiSizeAdvanced{ .scalar = 0 };
1516 return .{ .scalar = 0 };
15171517 }
15181518
1519 if (!(child_ty.hasRuntimeBitsAdvanced(mod, false, strat) catch |err| switch (err) {
1520 error.NeedLazy => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1519 if (!(child_ty.hasRuntimeBitsAdvanced(pt, false, strat) catch |err| switch (err) {
1520 error.NeedLazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
15211521 .ty = .comptime_int_type,
15221522 .storage = .{ .lazy_size = ty.toIntern() },
1523 } }))) },
1523 } })) },
15241524 else => |e| return e,
1525 })) return AbiSizeAdvanced{ .scalar = 1 };
1525 })) return .{ .scalar = 1 };
15261526
15271527 if (ty.optionalReprIsPayload(mod)) {
1528 return abiSizeAdvanced(child_ty, mod, strat);
1528 return child_ty.abiSizeAdvanced(pt, strat);
15291529 }
15301530
1531 const payload_size = switch (try child_ty.abiSizeAdvanced(mod, strat)) {
1531 const payload_size = switch (try child_ty.abiSizeAdvanced(pt, strat)) {
15321532 .scalar => |elem_size| elem_size,
15331533 .val => switch (strat) {
15341534 .sema => unreachable,
15351535 .eager => unreachable,
1536 .lazy => return .{ .val = Value.fromInterned((try mod.intern(.{ .int = .{
1536 .lazy => return .{ .val = Value.fromInterned(try pt.intern(.{ .int = .{
15371537 .ty = .comptime_int_type,
15381538 .storage = .{ .lazy_size = ty.toIntern() },
1539 } }))) },
1539 } })) },
15401540 },
15411541 };
15421542
......@@ -1544,8 +1544,8 @@ fn abiSizeAdvancedOptional(
15441544 // field and a boolean as the second. Since the child type's abi alignment is
15451545 // guaranteed to be >= that of bool's (1 byte) the added size is exactly equal
15461546 // to the child type's ABI alignment.
1547 return AbiSizeAdvanced{
1548 .scalar = (child_ty.abiAlignment(mod).toByteUnits() orelse 0) + payload_size,
1547 return .{
1548 .scalar = (child_ty.abiAlignment(pt).toByteUnits() orelse 0) + payload_size,
15491549 };
15501550}
15511551
......@@ -1675,15 +1675,16 @@ pub fn maxIntAlignment(target: std.Target, use_llvm: bool) u16 {
16751675 };
16761676}
16771677
1678pub fn bitSize(ty: Type, mod: *Module) u64 {
1679 return bitSizeAdvanced(ty, mod, .normal) catch unreachable;
1678pub fn bitSize(ty: Type, pt: Zcu.PerThread) u64 {
1679 return bitSizeAdvanced(ty, pt, .normal) catch unreachable;
16801680}
16811681
16821682pub fn bitSizeAdvanced(
16831683 ty: Type,
1684 mod: *Module,
1684 pt: Zcu.PerThread,
16851685 strat: ResolveStrat,
16861686) SemaError!u64 {
1687 const mod = pt.zcu;
16871688 const target = mod.getTarget();
16881689 const ip = &mod.intern_pool;
16891690
......@@ -1702,22 +1703,22 @@ pub fn bitSizeAdvanced(
17021703 if (len == 0) return 0;
17031704 const elem_ty = Type.fromInterned(array_type.child);
17041705 const elem_size = @max(
1705 (try elem_ty.abiAlignmentAdvanced(mod, strat_lazy)).scalar.toByteUnits() orelse 0,
1706 (try elem_ty.abiSizeAdvanced(mod, strat_lazy)).scalar,
1706 (try elem_ty.abiAlignmentAdvanced(pt, strat_lazy)).scalar.toByteUnits() orelse 0,
1707 (try elem_ty.abiSizeAdvanced(pt, strat_lazy)).scalar,
17071708 );
17081709 if (elem_size == 0) return 0;
1709 const elem_bit_size = try bitSizeAdvanced(elem_ty, mod, strat);
1710 const elem_bit_size = try elem_ty.bitSizeAdvanced(pt, strat);
17101711 return (len - 1) * 8 * elem_size + elem_bit_size;
17111712 },
17121713 .vector_type => |vector_type| {
17131714 const child_ty = Type.fromInterned(vector_type.child);
1714 const elem_bit_size = try bitSizeAdvanced(child_ty, mod, strat);
1715 const elem_bit_size = try child_ty.bitSizeAdvanced(pt, strat);
17151716 return elem_bit_size * vector_type.len;
17161717 },
17171718 .opt_type => {
17181719 // Optionals and error unions are not packed so their bitsize
17191720 // includes padding bits.
1720 return (try abiSizeAdvanced(ty, mod, strat_lazy)).scalar * 8;
1721 return (try ty.abiSizeAdvanced(pt, strat_lazy)).scalar * 8;
17211722 },
17221723
17231724 .error_set_type, .inferred_error_set_type => return mod.errorSetBits(),
......@@ -1725,7 +1726,7 @@ pub fn bitSizeAdvanced(
17251726 .error_union_type => {
17261727 // Optionals and error unions are not packed so their bitsize
17271728 // includes padding bits.
1728 return (try abiSizeAdvanced(ty, mod, strat_lazy)).scalar * 8;
1729 return (try ty.abiSizeAdvanced(pt, strat_lazy)).scalar * 8;
17291730 },
17301731 .func_type => unreachable, // represents machine code; not a pointer
17311732 .simple_type => |t| switch (t) {
......@@ -1783,42 +1784,42 @@ pub fn bitSizeAdvanced(
17831784 const struct_type = ip.loadStructType(ty.toIntern());
17841785 const is_packed = struct_type.layout == .@"packed";
17851786 if (strat == .sema) {
1786 try ty.resolveFields(mod);
1787 if (is_packed) try ty.resolveLayout(mod);
1787 try ty.resolveFields(pt);
1788 if (is_packed) try ty.resolveLayout(pt);
17881789 }
17891790 if (is_packed) {
1790 return try Type.fromInterned(struct_type.backingIntType(ip).*).bitSizeAdvanced(mod, strat);
1791 return try Type.fromInterned(struct_type.backingIntType(ip).*).bitSizeAdvanced(pt, strat);
17911792 }
1792 return (try ty.abiSizeAdvanced(mod, strat_lazy)).scalar * 8;
1793 return (try ty.abiSizeAdvanced(pt, strat_lazy)).scalar * 8;
17931794 },
17941795
17951796 .anon_struct_type => {
1796 if (strat == .sema) try ty.resolveFields(mod);
1797 return (try ty.abiSizeAdvanced(mod, strat_lazy)).scalar * 8;
1797 if (strat == .sema) try ty.resolveFields(pt);
1798 return (try ty.abiSizeAdvanced(pt, strat_lazy)).scalar * 8;
17981799 },
17991800
18001801 .union_type => {
18011802 const union_type = ip.loadUnionType(ty.toIntern());
18021803 const is_packed = ty.containerLayout(mod) == .@"packed";
18031804 if (strat == .sema) {
1804 try ty.resolveFields(mod);
1805 if (is_packed) try ty.resolveLayout(mod);
1805 try ty.resolveFields(pt);
1806 if (is_packed) try ty.resolveLayout(pt);
18061807 }
18071808 if (!is_packed) {
1808 return (try ty.abiSizeAdvanced(mod, strat_lazy)).scalar * 8;
1809 return (try ty.abiSizeAdvanced(pt, strat_lazy)).scalar * 8;
18091810 }
18101811 assert(union_type.flagsPtr(ip).status.haveFieldTypes());
18111812
18121813 var size: u64 = 0;
18131814 for (0..union_type.field_types.len) |field_index| {
18141815 const field_ty = union_type.field_types.get(ip)[field_index];
1815 size = @max(size, try bitSizeAdvanced(Type.fromInterned(field_ty), mod, strat));
1816 size = @max(size, try Type.fromInterned(field_ty).bitSizeAdvanced(pt, strat));
18161817 }
18171818
18181819 return size;
18191820 },
18201821 .opaque_type => unreachable,
1821 .enum_type => return bitSizeAdvanced(Type.fromInterned(ip.loadEnumType(ty.toIntern()).tag_ty), mod, strat),
1822 .enum_type => return Type.fromInterned(ip.loadEnumType(ty.toIntern()).tag_ty).bitSizeAdvanced(pt, strat),
18221823
18231824 // values, not types
18241825 .undef,
......@@ -1870,7 +1871,7 @@ pub fn isSinglePointer(ty: Type, mod: *const Module) bool {
18701871
18711872/// Asserts `ty` is a pointer.
18721873pub fn ptrSize(ty: Type, mod: *const Module) std.builtin.Type.Pointer.Size {
1873 return ptrSizeOrNull(ty, mod).?;
1874 return ty.ptrSizeOrNull(mod).?;
18741875}
18751876
18761877/// Returns `null` if `ty` is not a pointer.
......@@ -2105,29 +2106,28 @@ pub fn unionTagFieldIndex(ty: Type, enum_tag: Value, mod: *Module) ?u32 {
21052106 return mod.unionTagFieldIndex(union_obj, enum_tag);
21062107}
21072108
2108pub fn unionHasAllZeroBitFieldTypes(ty: Type, mod: *Module) bool {
2109 const ip = &mod.intern_pool;
2110 const union_obj = mod.typeToUnion(ty).?;
2109pub fn unionHasAllZeroBitFieldTypes(ty: Type, pt: Zcu.PerThread) bool {
2110 const ip = &pt.zcu.intern_pool;
2111 const union_obj = pt.zcu.typeToUnion(ty).?;
21112112 for (union_obj.field_types.get(ip)) |field_ty| {
2112 if (Type.fromInterned(field_ty).hasRuntimeBits(mod)) return false;
2113 if (Type.fromInterned(field_ty).hasRuntimeBits(pt)) return false;
21132114 }
21142115 return true;
21152116}
21162117
21172118/// Returns the type used for backing storage of this union during comptime operations.
21182119/// Asserts the type is either an extern or packed union.
2119pub fn unionBackingType(ty: Type, mod: *Module) !Type {
2120 return switch (ty.containerLayout(mod)) {
2121 .@"extern" => try mod.arrayType(.{ .len = ty.abiSize(mod), .child = .u8_type }),
2122 .@"packed" => try mod.intType(.unsigned, @intCast(ty.bitSize(mod))),
2120pub fn unionBackingType(ty: Type, pt: Zcu.PerThread) !Type {
2121 return switch (ty.containerLayout(pt.zcu)) {
2122 .@"extern" => try pt.arrayType(.{ .len = ty.abiSize(pt), .child = .u8_type }),
2123 .@"packed" => try pt.intType(.unsigned, @intCast(ty.bitSize(pt))),
21232124 .auto => unreachable,
21242125 };
21252126}
21262127
2127pub fn unionGetLayout(ty: Type, mod: *Module) Module.UnionLayout {
2128 const ip = &mod.intern_pool;
2129 const union_obj = ip.loadUnionType(ty.toIntern());
2130 return mod.getUnionLayout(union_obj);
2128pub fn unionGetLayout(ty: Type, pt: Zcu.PerThread) Module.UnionLayout {
2129 const union_obj = pt.zcu.intern_pool.loadUnionType(ty.toIntern());
2130 return pt.getUnionLayout(union_obj);
21312131}
21322132
21332133pub fn containerLayout(ty: Type, mod: *Module) std.builtin.Type.ContainerLayout {
......@@ -2509,7 +2509,8 @@ pub fn isNumeric(ty: Type, mod: *const Module) bool {
25092509
25102510/// During semantic analysis, instead call `Sema.typeHasOnePossibleValue` which
25112511/// resolves field types rather than asserting they are already resolved.
2512pub fn onePossibleValue(starting_type: Type, mod: *Module) !?Value {
2512pub fn onePossibleValue(starting_type: Type, pt: Zcu.PerThread) !?Value {
2513 const mod = pt.zcu;
25132514 var ty = starting_type;
25142515 const ip = &mod.intern_pool;
25152516 while (true) switch (ty.toIntern()) {
......@@ -2518,7 +2519,7 @@ pub fn onePossibleValue(starting_type: Type, mod: *Module) !?Value {
25182519 else => switch (ip.indexToKey(ty.toIntern())) {
25192520 .int_type => |int_type| {
25202521 if (int_type.bits == 0) {
2521 return try mod.intValue(ty, 0);
2522 return try pt.intValue(ty, 0);
25222523 } else {
25232524 return null;
25242525 }
......@@ -2534,21 +2535,21 @@ pub fn onePossibleValue(starting_type: Type, mod: *Module) !?Value {
25342535
25352536 inline .array_type, .vector_type => |seq_type, seq_tag| {
25362537 const has_sentinel = seq_tag == .array_type and seq_type.sentinel != .none;
2537 if (seq_type.len + @intFromBool(has_sentinel) == 0) return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2538 if (seq_type.len + @intFromBool(has_sentinel) == 0) return Value.fromInterned(try pt.intern(.{ .aggregate = .{
25382539 .ty = ty.toIntern(),
25392540 .storage = .{ .elems = &.{} },
2540 } })));
2541 if (try Type.fromInterned(seq_type.child).onePossibleValue(mod)) |opv| {
2542 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2541 } }));
2542 if (try Type.fromInterned(seq_type.child).onePossibleValue(pt)) |opv| {
2543 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
25432544 .ty = ty.toIntern(),
25442545 .storage = .{ .repeated_elem = opv.toIntern() },
2545 } })));
2546 } }));
25462547 }
25472548 return null;
25482549 },
25492550 .opt_type => |child| {
25502551 if (child == .noreturn_type) {
2551 return try mod.nullValue(ty);
2552 return try pt.nullValue(ty);
25522553 } else {
25532554 return null;
25542555 }
......@@ -2615,17 +2616,17 @@ pub fn onePossibleValue(starting_type: Type, mod: *Module) !?Value {
26152616 continue;
26162617 }
26172618 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
2618 if (try field_ty.onePossibleValue(mod)) |field_opv| {
2619 if (try field_ty.onePossibleValue(pt)) |field_opv| {
26192620 field_val.* = field_opv.toIntern();
26202621 } else return null;
26212622 }
26222623
26232624 // In this case the struct has no runtime-known fields and
26242625 // therefore has one possible value.
2625 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2626 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
26262627 .ty = ty.toIntern(),
26272628 .storage = .{ .elems = field_vals },
2628 } })));
2629 } }));
26292630 },
26302631
26312632 .anon_struct_type => |tuple| {
......@@ -2637,24 +2638,24 @@ pub fn onePossibleValue(starting_type: Type, mod: *Module) !?Value {
26372638 // TODO: write something like getCoercedInts to avoid needing to dupe
26382639 const duped_values = try mod.gpa.dupe(InternPool.Index, tuple.values.get(ip));
26392640 defer mod.gpa.free(duped_values);
2640 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2641 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
26412642 .ty = ty.toIntern(),
26422643 .storage = .{ .elems = duped_values },
2643 } })));
2644 } }));
26442645 },
26452646
26462647 .union_type => {
26472648 const union_obj = ip.loadUnionType(ty.toIntern());
2648 const tag_val = (try Type.fromInterned(union_obj.enum_tag_ty).onePossibleValue(mod)) orelse
2649 const tag_val = (try Type.fromInterned(union_obj.enum_tag_ty).onePossibleValue(pt)) orelse
26492650 return null;
26502651 if (union_obj.field_types.len == 0) {
2651 const only = try mod.intern(.{ .empty_enum_value = ty.toIntern() });
2652 const only = try pt.intern(.{ .empty_enum_value = ty.toIntern() });
26522653 return Value.fromInterned(only);
26532654 }
26542655 const only_field_ty = union_obj.field_types.get(ip)[0];
2655 const val_val = (try Type.fromInterned(only_field_ty).onePossibleValue(mod)) orelse
2656 const val_val = (try Type.fromInterned(only_field_ty).onePossibleValue(pt)) orelse
26562657 return null;
2657 const only = try mod.intern(.{ .un = .{
2658 const only = try pt.intern(.{ .un = .{
26582659 .ty = ty.toIntern(),
26592660 .tag = tag_val.toIntern(),
26602661 .val = val_val.toIntern(),
......@@ -2668,8 +2669,8 @@ pub fn onePossibleValue(starting_type: Type, mod: *Module) !?Value {
26682669 .nonexhaustive => {
26692670 if (enum_type.tag_ty == .comptime_int_type) return null;
26702671
2671 if (try Type.fromInterned(enum_type.tag_ty).onePossibleValue(mod)) |int_opv| {
2672 const only = try mod.intern(.{ .enum_tag = .{
2672 if (try Type.fromInterned(enum_type.tag_ty).onePossibleValue(pt)) |int_opv| {
2673 const only = try pt.intern(.{ .enum_tag = .{
26732674 .ty = ty.toIntern(),
26742675 .int = int_opv.toIntern(),
26752676 } });
......@@ -2679,18 +2680,18 @@ pub fn onePossibleValue(starting_type: Type, mod: *Module) !?Value {
26792680 return null;
26802681 },
26812682 .auto, .explicit => {
2682 if (Type.fromInterned(enum_type.tag_ty).hasRuntimeBits(mod)) return null;
2683 if (Type.fromInterned(enum_type.tag_ty).hasRuntimeBits(pt)) return null;
26832684
26842685 switch (enum_type.names.len) {
26852686 0 => {
2686 const only = try mod.intern(.{ .empty_enum_value = ty.toIntern() });
2687 const only = try pt.intern(.{ .empty_enum_value = ty.toIntern() });
26872688 return Value.fromInterned(only);
26882689 },
26892690 1 => {
26902691 if (enum_type.values.len == 0) {
2691 const only = try mod.intern(.{ .enum_tag = .{
2692 const only = try pt.intern(.{ .enum_tag = .{
26922693 .ty = ty.toIntern(),
2693 .int = try mod.intern(.{ .int = .{
2694 .int = try pt.intern(.{ .int = .{
26942695 .ty = enum_type.tag_ty,
26952696 .storage = .{ .u64 = 0 },
26962697 } }),
......@@ -2733,13 +2734,14 @@ pub fn onePossibleValue(starting_type: Type, mod: *Module) !?Value {
27332734
27342735/// During semantic analysis, instead call `Sema.typeRequiresComptime` which
27352736/// resolves field types rather than asserting they are already resolved.
2736pub fn comptimeOnly(ty: Type, mod: *Module) bool {
2737 return ty.comptimeOnlyAdvanced(mod, .normal) catch unreachable;
2737pub fn comptimeOnly(ty: Type, pt: Zcu.PerThread) bool {
2738 return ty.comptimeOnlyAdvanced(pt, .normal) catch unreachable;
27382739}
27392740
27402741/// `generic_poison` will return false.
27412742/// May return false negatives when structs and unions are having their field types resolved.
2742pub fn comptimeOnlyAdvanced(ty: Type, mod: *Module, strat: ResolveStrat) SemaError!bool {
2743pub fn comptimeOnlyAdvanced(ty: Type, pt: Zcu.PerThread, strat: ResolveStrat) SemaError!bool {
2744 const mod = pt.zcu;
27432745 const ip = &mod.intern_pool;
27442746 return switch (ty.toIntern()) {
27452747 .empty_struct_type => false,
......@@ -2749,19 +2751,19 @@ pub fn comptimeOnlyAdvanced(ty: Type, mod: *Module, strat: ResolveStrat) SemaErr
27492751 .ptr_type => |ptr_type| {
27502752 const child_ty = Type.fromInterned(ptr_type.child);
27512753 switch (child_ty.zigTypeTag(mod)) {
2752 .Fn => return !try child_ty.fnHasRuntimeBitsAdvanced(mod, strat),
2754 .Fn => return !try child_ty.fnHasRuntimeBitsAdvanced(pt, strat),
27532755 .Opaque => return false,
2754 else => return child_ty.comptimeOnlyAdvanced(mod, strat),
2756 else => return child_ty.comptimeOnlyAdvanced(pt, strat),
27552757 }
27562758 },
27572759 .anyframe_type => |child| {
27582760 if (child == .none) return false;
2759 return Type.fromInterned(child).comptimeOnlyAdvanced(mod, strat);
2761 return Type.fromInterned(child).comptimeOnlyAdvanced(pt, strat);
27602762 },
2761 .array_type => |array_type| return Type.fromInterned(array_type.child).comptimeOnlyAdvanced(mod, strat),
2762 .vector_type => |vector_type| return Type.fromInterned(vector_type.child).comptimeOnlyAdvanced(mod, strat),
2763 .opt_type => |child| return Type.fromInterned(child).comptimeOnlyAdvanced(mod, strat),
2764 .error_union_type => |error_union_type| return Type.fromInterned(error_union_type.payload_type).comptimeOnlyAdvanced(mod, strat),
2763 .array_type => |array_type| return Type.fromInterned(array_type.child).comptimeOnlyAdvanced(pt, strat),
2764 .vector_type => |vector_type| return Type.fromInterned(vector_type.child).comptimeOnlyAdvanced(pt, strat),
2765 .opt_type => |child| return Type.fromInterned(child).comptimeOnlyAdvanced(pt, strat),
2766 .error_union_type => |error_union_type| return Type.fromInterned(error_union_type.payload_type).comptimeOnlyAdvanced(pt, strat),
27652767
27662768 .error_set_type,
27672769 .inferred_error_set_type,
......@@ -2836,13 +2838,13 @@ pub fn comptimeOnlyAdvanced(ty: Type, mod: *Module, strat: ResolveStrat) SemaErr
28362838 struct_type.flagsPtr(ip).requires_comptime = .wip;
28372839 errdefer struct_type.flagsPtr(ip).requires_comptime = .unknown;
28382840
2839 try ty.resolveFields(mod);
2841 try ty.resolveFields(pt);
28402842
28412843 for (0..struct_type.field_types.len) |i_usize| {
28422844 const i: u32 = @intCast(i_usize);
28432845 if (struct_type.fieldIsComptime(ip, i)) continue;
28442846 const field_ty = struct_type.field_types.get(ip)[i];
2845 if (try Type.fromInterned(field_ty).comptimeOnlyAdvanced(mod, strat)) {
2847 if (try Type.fromInterned(field_ty).comptimeOnlyAdvanced(pt, strat)) {
28462848 // Note that this does not cause the layout to
28472849 // be considered resolved. Comptime-only types
28482850 // still maintain a layout of their
......@@ -2861,7 +2863,7 @@ pub fn comptimeOnlyAdvanced(ty: Type, mod: *Module, strat: ResolveStrat) SemaErr
28612863 .anon_struct_type => |tuple| {
28622864 for (tuple.types.get(ip), tuple.values.get(ip)) |field_ty, val| {
28632865 const have_comptime_val = val != .none;
2864 if (!have_comptime_val and try Type.fromInterned(field_ty).comptimeOnlyAdvanced(mod, strat)) return true;
2866 if (!have_comptime_val and try Type.fromInterned(field_ty).comptimeOnlyAdvanced(pt, strat)) return true;
28652867 }
28662868 return false;
28672869 },
......@@ -2880,11 +2882,11 @@ pub fn comptimeOnlyAdvanced(ty: Type, mod: *Module, strat: ResolveStrat) SemaErr
28802882 union_type.flagsPtr(ip).requires_comptime = .wip;
28812883 errdefer union_type.flagsPtr(ip).requires_comptime = .unknown;
28822884
2883 try ty.resolveFields(mod);
2885 try ty.resolveFields(pt);
28842886
28852887 for (0..union_type.field_types.len) |field_idx| {
28862888 const field_ty = union_type.field_types.get(ip)[field_idx];
2887 if (try Type.fromInterned(field_ty).comptimeOnlyAdvanced(mod, strat)) {
2889 if (try Type.fromInterned(field_ty).comptimeOnlyAdvanced(pt, strat)) {
28882890 union_type.flagsPtr(ip).requires_comptime = .yes;
28892891 return true;
28902892 }
......@@ -2898,7 +2900,7 @@ pub fn comptimeOnlyAdvanced(ty: Type, mod: *Module, strat: ResolveStrat) SemaErr
28982900
28992901 .opaque_type => false,
29002902
2901 .enum_type => return Type.fromInterned(ip.loadEnumType(ty.toIntern()).tag_ty).comptimeOnlyAdvanced(mod, strat),
2903 .enum_type => return Type.fromInterned(ip.loadEnumType(ty.toIntern()).tag_ty).comptimeOnlyAdvanced(pt, strat),
29022904
29032905 // values, not types
29042906 .undef,
......@@ -2930,10 +2932,10 @@ pub fn isVector(ty: Type, mod: *const Module) bool {
29302932}
29312933
29322934/// Returns 0 if not a vector, otherwise returns @bitSizeOf(Element) * vector_len.
2933pub fn totalVectorBits(ty: Type, zcu: *Zcu) u64 {
2934 if (!ty.isVector(zcu)) return 0;
2935 const v = zcu.intern_pool.indexToKey(ty.toIntern()).vector_type;
2936 return v.len * Type.fromInterned(v.child).bitSize(zcu);
2935pub fn totalVectorBits(ty: Type, pt: Zcu.PerThread) u64 {
2936 if (!ty.isVector(pt.zcu)) return 0;
2937 const v = pt.zcu.intern_pool.indexToKey(ty.toIntern()).vector_type;
2938 return v.len * Type.fromInterned(v.child).bitSize(pt);
29372939}
29382940
29392941pub fn isArrayOrVector(ty: Type, mod: *const Module) bool {
......@@ -3013,23 +3015,25 @@ pub fn getNamespace(ty: Type, zcu: *Zcu) ?InternPool.OptionalNamespaceIndex {
30133015}
30143016
30153017// Works for vectors and vectors of integers.
3016pub fn minInt(ty: Type, mod: *Module, dest_ty: Type) !Value {
3017 const scalar = try minIntScalar(ty.scalarType(mod), mod, dest_ty.scalarType(mod));
3018 return if (ty.zigTypeTag(mod) == .Vector) Value.fromInterned((try mod.intern(.{ .aggregate = .{
3018pub fn minInt(ty: Type, pt: Zcu.PerThread, dest_ty: Type) !Value {
3019 const mod = pt.zcu;
3020 const scalar = try minIntScalar(ty.scalarType(mod), pt, dest_ty.scalarType(mod));
3021 return if (ty.zigTypeTag(mod) == .Vector) Value.fromInterned(try pt.intern(.{ .aggregate = .{
30193022 .ty = dest_ty.toIntern(),
30203023 .storage = .{ .repeated_elem = scalar.toIntern() },
3021 } }))) else scalar;
3024 } })) else scalar;
30223025}
30233026
30243027/// Asserts that the type is an integer.
3025pub fn minIntScalar(ty: Type, mod: *Module, dest_ty: Type) !Value {
3028pub fn minIntScalar(ty: Type, pt: Zcu.PerThread, dest_ty: Type) !Value {
3029 const mod = pt.zcu;
30263030 const info = ty.intInfo(mod);
3027 if (info.signedness == .unsigned) return mod.intValue(dest_ty, 0);
3028 if (info.bits == 0) return mod.intValue(dest_ty, -1);
3031 if (info.signedness == .unsigned) return pt.intValue(dest_ty, 0);
3032 if (info.bits == 0) return pt.intValue(dest_ty, -1);
30293033
30303034 if (std.math.cast(u6, info.bits - 1)) |shift| {
30313035 const n = @as(i64, std.math.minInt(i64)) >> (63 - shift);
3032 return mod.intValue(dest_ty, n);
3036 return pt.intValue(dest_ty, n);
30333037 }
30343038
30353039 var res = try std.math.big.int.Managed.init(mod.gpa);
......@@ -3037,31 +3041,32 @@ pub fn minIntScalar(ty: Type, mod: *Module, dest_ty: Type) !Value {
30373041
30383042 try res.setTwosCompIntLimit(.min, info.signedness, info.bits);
30393043
3040 return mod.intValue_big(dest_ty, res.toConst());
3044 return pt.intValue_big(dest_ty, res.toConst());
30413045}
30423046
30433047// Works for vectors and vectors of integers.
30443048/// The returned Value will have type dest_ty.
3045pub fn maxInt(ty: Type, mod: *Module, dest_ty: Type) !Value {
3046 const scalar = try maxIntScalar(ty.scalarType(mod), mod, dest_ty.scalarType(mod));
3047 return if (ty.zigTypeTag(mod) == .Vector) Value.fromInterned((try mod.intern(.{ .aggregate = .{
3049pub fn maxInt(ty: Type, pt: Zcu.PerThread, dest_ty: Type) !Value {
3050 const mod = pt.zcu;
3051 const scalar = try maxIntScalar(ty.scalarType(mod), pt, dest_ty.scalarType(mod));
3052 return if (ty.zigTypeTag(mod) == .Vector) Value.fromInterned(try pt.intern(.{ .aggregate = .{
30483053 .ty = dest_ty.toIntern(),
30493054 .storage = .{ .repeated_elem = scalar.toIntern() },
3050 } }))) else scalar;
3055 } })) else scalar;
30513056}
30523057
30533058/// The returned Value will have type dest_ty.
3054pub fn maxIntScalar(ty: Type, mod: *Module, dest_ty: Type) !Value {
3055 const info = ty.intInfo(mod);
3059pub fn maxIntScalar(ty: Type, pt: Zcu.PerThread, dest_ty: Type) !Value {
3060 const info = ty.intInfo(pt.zcu);
30563061
30573062 switch (info.bits) {
30583063 0 => return switch (info.signedness) {
3059 .signed => try mod.intValue(dest_ty, -1),
3060 .unsigned => try mod.intValue(dest_ty, 0),
3064 .signed => try pt.intValue(dest_ty, -1),
3065 .unsigned => try pt.intValue(dest_ty, 0),
30613066 },
30623067 1 => return switch (info.signedness) {
3063 .signed => try mod.intValue(dest_ty, 0),
3064 .unsigned => try mod.intValue(dest_ty, 1),
3068 .signed => try pt.intValue(dest_ty, 0),
3069 .unsigned => try pt.intValue(dest_ty, 1),
30653070 },
30663071 else => {},
30673072 }
......@@ -3069,20 +3074,20 @@ pub fn maxIntScalar(ty: Type, mod: *Module, dest_ty: Type) !Value {
30693074 if (std.math.cast(u6, info.bits - 1)) |shift| switch (info.signedness) {
30703075 .signed => {
30713076 const n = @as(i64, std.math.maxInt(i64)) >> (63 - shift);
3072 return mod.intValue(dest_ty, n);
3077 return pt.intValue(dest_ty, n);
30733078 },
30743079 .unsigned => {
30753080 const n = @as(u64, std.math.maxInt(u64)) >> (63 - shift);
3076 return mod.intValue(dest_ty, n);
3081 return pt.intValue(dest_ty, n);
30773082 },
30783083 };
30793084
3080 var res = try std.math.big.int.Managed.init(mod.gpa);
3085 var res = try std.math.big.int.Managed.init(pt.zcu.gpa);
30813086 defer res.deinit();
30823087
30833088 try res.setTwosCompIntLimit(.max, info.signedness, info.bits);
30843089
3085 return mod.intValue_big(dest_ty, res.toConst());
3090 return pt.intValue_big(dest_ty, res.toConst());
30863091}
30873092
30883093/// Asserts the type is an enum or a union.
......@@ -3188,26 +3193,26 @@ pub fn structFieldType(ty: Type, index: usize, mod: *Module) Type {
31883193 };
31893194}
31903195
3191pub fn structFieldAlign(ty: Type, index: usize, zcu: *Zcu) Alignment {
3192 return ty.structFieldAlignAdvanced(index, zcu, .normal) catch unreachable;
3196pub fn structFieldAlign(ty: Type, index: usize, pt: Zcu.PerThread) Alignment {
3197 return ty.structFieldAlignAdvanced(index, pt, .normal) catch unreachable;
31933198}
31943199
3195pub fn structFieldAlignAdvanced(ty: Type, index: usize, zcu: *Zcu, strat: ResolveStrat) !Alignment {
3196 const ip = &zcu.intern_pool;
3200pub fn structFieldAlignAdvanced(ty: Type, index: usize, pt: Zcu.PerThread, strat: ResolveStrat) !Alignment {
3201 const ip = &pt.zcu.intern_pool;
31973202 switch (ip.indexToKey(ty.toIntern())) {
31983203 .struct_type => {
31993204 const struct_type = ip.loadStructType(ty.toIntern());
32003205 assert(struct_type.layout != .@"packed");
32013206 const explicit_align = struct_type.fieldAlign(ip, index);
32023207 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[index]);
3203 return zcu.structFieldAlignmentAdvanced(explicit_align, field_ty, struct_type.layout, strat);
3208 return pt.structFieldAlignmentAdvanced(explicit_align, field_ty, struct_type.layout, strat);
32043209 },
32053210 .anon_struct_type => |anon_struct| {
3206 return (try Type.fromInterned(anon_struct.types.get(ip)[index]).abiAlignmentAdvanced(zcu, strat.toLazy())).scalar;
3211 return (try Type.fromInterned(anon_struct.types.get(ip)[index]).abiAlignmentAdvanced(pt, strat.toLazy())).scalar;
32073212 },
32083213 .union_type => {
32093214 const union_obj = ip.loadUnionType(ty.toIntern());
3210 return zcu.unionFieldNormalAlignmentAdvanced(union_obj, @intCast(index), strat);
3215 return pt.unionFieldNormalAlignmentAdvanced(union_obj, @intCast(index), strat);
32113216 },
32123217 else => unreachable,
32133218 }
......@@ -3233,7 +3238,8 @@ pub fn structFieldDefaultValue(ty: Type, index: usize, mod: *Module) Value {
32333238 }
32343239}
32353240
3236pub fn structFieldValueComptime(ty: Type, mod: *Module, index: usize) !?Value {
3241pub fn structFieldValueComptime(ty: Type, pt: Zcu.PerThread, index: usize) !?Value {
3242 const mod = pt.zcu;
32373243 const ip = &mod.intern_pool;
32383244 switch (ip.indexToKey(ty.toIntern())) {
32393245 .struct_type => {
......@@ -3242,13 +3248,13 @@ pub fn structFieldValueComptime(ty: Type, mod: *Module, index: usize) !?Value {
32423248 assert(struct_type.haveFieldInits(ip));
32433249 return Value.fromInterned(struct_type.field_inits.get(ip)[index]);
32443250 } else {
3245 return Type.fromInterned(struct_type.field_types.get(ip)[index]).onePossibleValue(mod);
3251 return Type.fromInterned(struct_type.field_types.get(ip)[index]).onePossibleValue(pt);
32463252 }
32473253 },
32483254 .anon_struct_type => |tuple| {
32493255 const val = tuple.values.get(ip)[index];
32503256 if (val == .none) {
3251 return Type.fromInterned(tuple.types.get(ip)[index]).onePossibleValue(mod);
3257 return Type.fromInterned(tuple.types.get(ip)[index]).onePossibleValue(pt);
32523258 } else {
32533259 return Value.fromInterned(val);
32543260 }
......@@ -3272,7 +3278,8 @@ pub const FieldOffset = struct {
32723278};
32733279
32743280/// Supports structs and unions.
3275pub fn structFieldOffset(ty: Type, index: usize, mod: *Module) u64 {
3281pub fn structFieldOffset(ty: Type, index: usize, pt: Zcu.PerThread) u64 {
3282 const mod = pt.zcu;
32763283 const ip = &mod.intern_pool;
32773284 switch (ip.indexToKey(ty.toIntern())) {
32783285 .struct_type => {
......@@ -3287,17 +3294,17 @@ pub fn structFieldOffset(ty: Type, index: usize, mod: *Module) u64 {
32873294 var big_align: Alignment = .none;
32883295
32893296 for (tuple.types.get(ip), tuple.values.get(ip), 0..) |field_ty, field_val, i| {
3290 if (field_val != .none or !Type.fromInterned(field_ty).hasRuntimeBits(mod)) {
3297 if (field_val != .none or !Type.fromInterned(field_ty).hasRuntimeBits(pt)) {
32913298 // comptime field
32923299 if (i == index) return offset;
32933300 continue;
32943301 }
32953302
3296 const field_align = Type.fromInterned(field_ty).abiAlignment(mod);
3303 const field_align = Type.fromInterned(field_ty).abiAlignment(pt);
32973304 big_align = big_align.max(field_align);
32983305 offset = field_align.forward(offset);
32993306 if (i == index) return offset;
3300 offset += Type.fromInterned(field_ty).abiSize(mod);
3307 offset += Type.fromInterned(field_ty).abiSize(pt);
33013308 }
33023309 offset = big_align.max(.@"1").forward(offset);
33033310 return offset;
......@@ -3307,7 +3314,7 @@ pub fn structFieldOffset(ty: Type, index: usize, mod: *Module) u64 {
33073314 const union_type = ip.loadUnionType(ty.toIntern());
33083315 if (!union_type.hasTag(ip))
33093316 return 0;
3310 const layout = mod.getUnionLayout(union_type);
3317 const layout = pt.getUnionLayout(union_type);
33113318 if (layout.tag_align.compare(.gte, layout.payload_align)) {
33123319 // {Tag, Payload}
33133320 return layout.payload_align.forward(layout.tag_size);
......@@ -3421,12 +3428,13 @@ pub fn optEuBaseType(ty: Type, mod: *Module) Type {
34213428 };
34223429}
34233430
3424pub fn toUnsigned(ty: Type, mod: *Module) !Type {
3431pub fn toUnsigned(ty: Type, pt: Zcu.PerThread) !Type {
3432 const mod = pt.zcu;
34253433 return switch (ty.zigTypeTag(mod)) {
3426 .Int => mod.intType(.unsigned, ty.intInfo(mod).bits),
3427 .Vector => try mod.vectorType(.{
3434 .Int => pt.intType(.unsigned, ty.intInfo(mod).bits),
3435 .Vector => try pt.vectorType(.{
34283436 .len = ty.vectorLen(mod),
3429 .child = (try ty.childType(mod).toUnsigned(mod)).toIntern(),
3437 .child = (try ty.childType(mod).toUnsigned(pt)).toIntern(),
34303438 }),
34313439 else => unreachable,
34323440 };
......@@ -3492,7 +3500,7 @@ pub fn arrayBase(ty: Type, zcu: *const Zcu) struct { Type, u64 } {
34923500 return .{ cur_ty, cur_len };
34933501}
34943502
3495pub fn packedStructFieldPtrInfo(struct_ty: Type, parent_ptr_ty: Type, field_idx: u32, zcu: *Zcu) union(enum) {
3503pub fn packedStructFieldPtrInfo(struct_ty: Type, parent_ptr_ty: Type, field_idx: u32, pt: Zcu.PerThread) union(enum) {
34963504 /// The result is a bit-pointer with the same value and a new packed offset.
34973505 bit_ptr: InternPool.Key.PtrType.PackedOffset,
34983506 /// The result is a standard pointer.
......@@ -3505,6 +3513,7 @@ pub fn packedStructFieldPtrInfo(struct_ty: Type, parent_ptr_ty: Type, field_idx:
35053513} {
35063514 comptime assert(Type.packed_struct_layout_version == 2);
35073515
3516 const zcu = pt.zcu;
35083517 const parent_ptr_info = parent_ptr_ty.ptrInfo(zcu);
35093518 const field_ty = struct_ty.structFieldType(field_idx, zcu);
35103519
......@@ -3515,7 +3524,7 @@ pub fn packedStructFieldPtrInfo(struct_ty: Type, parent_ptr_ty: Type, field_idx:
35153524 if (i == field_idx) {
35163525 bit_offset = running_bits;
35173526 }
3518 running_bits += @intCast(f_ty.bitSize(zcu));
3527 running_bits += @intCast(f_ty.bitSize(pt));
35193528 }
35203529
35213530 const res_host_size: u16, const res_bit_offset: u16 = if (parent_ptr_info.packed_offset.host_size != 0)
......@@ -3532,9 +3541,9 @@ pub fn packedStructFieldPtrInfo(struct_ty: Type, parent_ptr_ty: Type, field_idx:
35323541 // targets before adding the necessary complications to this code. This will not
35333542 // cause miscompilations; it only means the field pointer uses bit masking when it
35343543 // might not be strictly necessary.
3535 if (res_bit_offset % 8 == 0 and field_ty.bitSize(zcu) == field_ty.abiSize(zcu) * 8 and zcu.getTarget().cpu.arch.endian() == .little) {
3544 if (res_bit_offset % 8 == 0 and field_ty.bitSize(pt) == field_ty.abiSize(pt) * 8 and zcu.getTarget().cpu.arch.endian() == .little) {
35363545 const byte_offset = res_bit_offset / 8;
3537 const new_align = Alignment.fromLog2Units(@ctz(byte_offset | parent_ptr_ty.ptrAlignment(zcu).toByteUnits().?));
3546 const new_align = Alignment.fromLog2Units(@ctz(byte_offset | parent_ptr_ty.ptrAlignment(pt).toByteUnits().?));
35383547 return .{ .byte_ptr = .{
35393548 .offset = byte_offset,
35403549 .alignment = new_align,
......@@ -3547,34 +3556,35 @@ pub fn packedStructFieldPtrInfo(struct_ty: Type, parent_ptr_ty: Type, field_idx:
35473556 } };
35483557}
35493558
3550pub fn resolveLayout(ty: Type, zcu: *Zcu) SemaError!void {
3559pub fn resolveLayout(ty: Type, pt: Zcu.PerThread) SemaError!void {
3560 const zcu = pt.zcu;
35513561 const ip = &zcu.intern_pool;
35523562 switch (ip.indexToKey(ty.toIntern())) {
3553 .simple_type => |simple_type| return resolveSimpleType(simple_type, zcu),
3563 .simple_type => |simple_type| return resolveSimpleType(simple_type, pt),
35543564 else => {},
35553565 }
35563566 switch (ty.zigTypeTag(zcu)) {
35573567 .Struct => switch (ip.indexToKey(ty.toIntern())) {
35583568 .anon_struct_type => |anon_struct_type| for (0..anon_struct_type.types.len) |i| {
35593569 const field_ty = Type.fromInterned(anon_struct_type.types.get(ip)[i]);
3560 try field_ty.resolveLayout(zcu);
3570 try field_ty.resolveLayout(pt);
35613571 },
3562 .struct_type => return ty.resolveStructInner(zcu, .layout),
3572 .struct_type => return ty.resolveStructInner(pt, .layout),
35633573 else => unreachable,
35643574 },
3565 .Union => return ty.resolveUnionInner(zcu, .layout),
3575 .Union => return ty.resolveUnionInner(pt, .layout),
35663576 .Array => {
35673577 if (ty.arrayLenIncludingSentinel(zcu) == 0) return;
35683578 const elem_ty = ty.childType(zcu);
3569 return elem_ty.resolveLayout(zcu);
3579 return elem_ty.resolveLayout(pt);
35703580 },
35713581 .Optional => {
35723582 const payload_ty = ty.optionalChild(zcu);
3573 return payload_ty.resolveLayout(zcu);
3583 return payload_ty.resolveLayout(pt);
35743584 },
35753585 .ErrorUnion => {
35763586 const payload_ty = ty.errorUnionPayload(zcu);
3577 return payload_ty.resolveLayout(zcu);
3587 return payload_ty.resolveLayout(pt);
35783588 },
35793589 .Fn => {
35803590 const info = zcu.typeToFunc(ty).?;
......@@ -3585,16 +3595,16 @@ pub fn resolveLayout(ty: Type, zcu: *Zcu) SemaError!void {
35853595 }
35863596 for (0..info.param_types.len) |i| {
35873597 const param_ty = info.param_types.get(ip)[i];
3588 try Type.fromInterned(param_ty).resolveLayout(zcu);
3598 try Type.fromInterned(param_ty).resolveLayout(pt);
35893599 }
3590 try Type.fromInterned(info.return_type).resolveLayout(zcu);
3600 try Type.fromInterned(info.return_type).resolveLayout(pt);
35913601 },
35923602 else => {},
35933603 }
35943604}
35953605
3596pub fn resolveFields(ty: Type, zcu: *Zcu) SemaError!void {
3597 const ip = &zcu.intern_pool;
3606pub fn resolveFields(ty: Type, pt: Zcu.PerThread) SemaError!void {
3607 const ip = &pt.zcu.intern_pool;
35983608 const ty_ip = ty.toIntern();
35993609
36003610 switch (ty_ip) {
......@@ -3676,26 +3686,27 @@ pub fn resolveFields(ty: Type, zcu: *Zcu) SemaError!void {
36763686 .empty_struct => unreachable,
36773687 .generic_poison => unreachable,
36783688
3679 else => switch (ip.items.items(.tag)[@intFromEnum(ty_ip)]) {
3689 else => switch (ty_ip.unwrap(ip).getTag(ip)) {
36803690 .type_struct,
36813691 .type_struct_packed,
36823692 .type_struct_packed_inits,
3683 => return ty.resolveStructInner(zcu, .fields),
3693 => return ty.resolveStructInner(pt, .fields),
36843694
3685 .type_union => return ty.resolveUnionInner(zcu, .fields),
3695 .type_union => return ty.resolveUnionInner(pt, .fields),
36863696
3687 .simple_type => return resolveSimpleType(ip.indexToKey(ty_ip).simple_type, zcu),
3697 .simple_type => return resolveSimpleType(ip.indexToKey(ty_ip).simple_type, pt),
36883698
36893699 else => {},
36903700 },
36913701 }
36923702}
36933703
3694pub fn resolveFully(ty: Type, zcu: *Zcu) SemaError!void {
3704pub fn resolveFully(ty: Type, pt: Zcu.PerThread) SemaError!void {
3705 const zcu = pt.zcu;
36953706 const ip = &zcu.intern_pool;
36963707
36973708 switch (ip.indexToKey(ty.toIntern())) {
3698 .simple_type => |simple_type| return resolveSimpleType(simple_type, zcu),
3709 .simple_type => |simple_type| return resolveSimpleType(simple_type, pt),
36993710 else => {},
37003711 }
37013712
......@@ -3719,52 +3730,53 @@ pub fn resolveFully(ty: Type, zcu: *Zcu) SemaError!void {
37193730 .EnumLiteral,
37203731 => {},
37213732
3722 .Pointer => return ty.childType(zcu).resolveFully(zcu),
3723 .Array => return ty.childType(zcu).resolveFully(zcu),
3724 .Optional => return ty.optionalChild(zcu).resolveFully(zcu),
3725 .ErrorUnion => return ty.errorUnionPayload(zcu).resolveFully(zcu),
3733 .Pointer => return ty.childType(zcu).resolveFully(pt),
3734 .Array => return ty.childType(zcu).resolveFully(pt),
3735 .Optional => return ty.optionalChild(zcu).resolveFully(pt),
3736 .ErrorUnion => return ty.errorUnionPayload(zcu).resolveFully(pt),
37263737 .Fn => {
37273738 const info = zcu.typeToFunc(ty).?;
37283739 if (info.is_generic) return;
37293740 for (0..info.param_types.len) |i| {
37303741 const param_ty = info.param_types.get(ip)[i];
3731 try Type.fromInterned(param_ty).resolveFully(zcu);
3742 try Type.fromInterned(param_ty).resolveFully(pt);
37323743 }
3733 try Type.fromInterned(info.return_type).resolveFully(zcu);
3744 try Type.fromInterned(info.return_type).resolveFully(pt);
37343745 },
37353746
37363747 .Struct => switch (ip.indexToKey(ty.toIntern())) {
37373748 .anon_struct_type => |anon_struct_type| for (0..anon_struct_type.types.len) |i| {
37383749 const field_ty = Type.fromInterned(anon_struct_type.types.get(ip)[i]);
3739 try field_ty.resolveFully(zcu);
3750 try field_ty.resolveFully(pt);
37403751 },
3741 .struct_type => return ty.resolveStructInner(zcu, .full),
3752 .struct_type => return ty.resolveStructInner(pt, .full),
37423753 else => unreachable,
37433754 },
3744 .Union => return ty.resolveUnionInner(zcu, .full),
3755 .Union => return ty.resolveUnionInner(pt, .full),
37453756 }
37463757}
37473758
3748pub fn resolveStructFieldInits(ty: Type, zcu: *Zcu) SemaError!void {
3759pub fn resolveStructFieldInits(ty: Type, pt: Zcu.PerThread) SemaError!void {
37493760 // TODO: stop calling this for tuples!
3750 _ = zcu.typeToStruct(ty) orelse return;
3751 return ty.resolveStructInner(zcu, .inits);
3761 _ = pt.zcu.typeToStruct(ty) orelse return;
3762 return ty.resolveStructInner(pt, .inits);
37523763}
37533764
3754pub fn resolveStructAlignment(ty: Type, zcu: *Zcu) SemaError!void {
3755 return ty.resolveStructInner(zcu, .alignment);
3765pub fn resolveStructAlignment(ty: Type, pt: Zcu.PerThread) SemaError!void {
3766 return ty.resolveStructInner(pt, .alignment);
37563767}
37573768
3758pub fn resolveUnionAlignment(ty: Type, zcu: *Zcu) SemaError!void {
3759 return ty.resolveUnionInner(zcu, .alignment);
3769pub fn resolveUnionAlignment(ty: Type, pt: Zcu.PerThread) SemaError!void {
3770 return ty.resolveUnionInner(pt, .alignment);
37603771}
37613772
37623773/// `ty` must be a struct.
37633774fn resolveStructInner(
37643775 ty: Type,
3765 zcu: *Zcu,
3776 pt: Zcu.PerThread,
37663777 resolution: enum { fields, inits, alignment, layout, full },
37673778) SemaError!void {
3779 const zcu = pt.zcu;
37683780 const gpa = zcu.gpa;
37693781
37703782 const struct_obj = zcu.typeToStruct(ty).?;
......@@ -3777,7 +3789,7 @@ fn resolveStructInner(
37773789 defer comptime_err_ret_trace.deinit();
37783790
37793791 var sema: Sema = .{
3780 .mod = zcu,
3792 .pt = pt,
37813793 .gpa = gpa,
37823794 .arena = analysis_arena.allocator(),
37833795 .code = undefined, // This ZIR will not be used.
......@@ -3804,9 +3816,10 @@ fn resolveStructInner(
38043816/// `ty` must be a union.
38053817fn resolveUnionInner(
38063818 ty: Type,
3807 zcu: *Zcu,
3819 pt: Zcu.PerThread,
38083820 resolution: enum { fields, alignment, layout, full },
38093821) SemaError!void {
3822 const zcu = pt.zcu;
38103823 const gpa = zcu.gpa;
38113824
38123825 const union_obj = zcu.typeToUnion(ty).?;
......@@ -3819,7 +3832,7 @@ fn resolveUnionInner(
38193832 defer comptime_err_ret_trace.deinit();
38203833
38213834 var sema: Sema = .{
3822 .mod = zcu,
3835 .pt = pt,
38233836 .gpa = gpa,
38243837 .arena = analysis_arena.allocator(),
38253838 .code = undefined, // This ZIR will not be used.
......@@ -3845,7 +3858,7 @@ fn resolveUnionInner(
38453858/// Fully resolves a simple type. This is usually a nop, but for builtin types with
38463859/// special InternPool indices (such as std.builtin.Type) it will analyze and fully
38473860/// resolve the type.
3848fn resolveSimpleType(simple_type: InternPool.SimpleType, zcu: *Zcu) Allocator.Error!void {
3861fn resolveSimpleType(simple_type: InternPool.SimpleType, pt: Zcu.PerThread) Allocator.Error!void {
38493862 const builtin_type_name: []const u8 = switch (simple_type) {
38503863 .atomic_order => "AtomicOrder",
38513864 .atomic_rmw_op => "AtomicRmwOp",
......@@ -3861,7 +3874,7 @@ fn resolveSimpleType(simple_type: InternPool.SimpleType, zcu: *Zcu) Allocator.Er
38613874 else => return,
38623875 };
38633876 // This will fully resolve the type.
3864 _ = try zcu.getBuiltinType(builtin_type_name);
3877 _ = try pt.getBuiltinType(builtin_type_name);
38653878}
38663879
38673880/// Returns the type of a pointer to an element.
......@@ -3874,7 +3887,8 @@ fn resolveSimpleType(simple_type: InternPool.SimpleType, zcu: *Zcu) Allocator.Er
38743887/// Handles const-ness and address spaces in particular.
38753888/// This code is duplicated in `Sema.analyzePtrArithmetic`.
38763889/// May perform type resolution and return a transitive `error.AnalysisFail`.
3877pub fn elemPtrType(ptr_ty: Type, offset: ?usize, zcu: *Zcu) !Type {
3890pub fn elemPtrType(ptr_ty: Type, offset: ?usize, pt: Zcu.PerThread) !Type {
3891 const zcu = pt.zcu;
38783892 const ptr_info = ptr_ty.ptrInfo(zcu);
38793893 const elem_ty = ptr_ty.elemType2(zcu);
38803894 const is_allowzero = ptr_info.flags.is_allowzero and (offset orelse 0) == 0;
......@@ -3887,14 +3901,14 @@ pub fn elemPtrType(ptr_ty: Type, offset: ?usize, zcu: *Zcu) !Type {
38873901 alignment: Alignment = .none,
38883902 vector_index: VI = .none,
38893903 } = if (parent_ty.isVector(zcu) and ptr_info.flags.size == .One) blk: {
3890 const elem_bits = elem_ty.bitSize(zcu);
3904 const elem_bits = elem_ty.bitSize(pt);
38913905 if (elem_bits == 0) break :blk .{};
38923906 const is_packed = elem_bits < 8 or !std.math.isPowerOfTwo(elem_bits);
38933907 if (!is_packed) break :blk .{};
38943908
38953909 break :blk .{
38963910 .host_size = @intCast(parent_ty.arrayLen(zcu)),
3897 .alignment = parent_ty.abiAlignment(zcu),
3911 .alignment = parent_ty.abiAlignment(pt),
38983912 .vector_index = if (offset) |some| @enumFromInt(some) else .runtime,
38993913 };
39003914 } else .{};
......@@ -3908,7 +3922,7 @@ pub fn elemPtrType(ptr_ty: Type, offset: ?usize, zcu: *Zcu) !Type {
39083922 }
39093923 // If the addend is not a comptime-known value we can still count on
39103924 // it being a multiple of the type size.
3911 const elem_size = (try elem_ty.abiSizeAdvanced(zcu, .sema)).scalar;
3925 const elem_size = (try elem_ty.abiSizeAdvanced(pt, .sema)).scalar;
39123926 const addend = if (offset) |off| elem_size * off else elem_size;
39133927
39143928 // The resulting pointer is aligned to the lcd between the offset (an
......@@ -3921,7 +3935,7 @@ pub fn elemPtrType(ptr_ty: Type, offset: ?usize, zcu: *Zcu) !Type {
39213935 assert(new_align != .none);
39223936 break :a new_align;
39233937 };
3924 return zcu.ptrTypeSema(.{
3938 return pt.ptrTypeSema(.{
39253939 .child = elem_ty.toIntern(),
39263940 .flags = .{
39273941 .alignment = alignment,
......@@ -3944,6 +3958,7 @@ pub const @"u16": Type = .{ .ip_index = .u16_type };
39443958pub const @"u29": Type = .{ .ip_index = .u29_type };
39453959pub const @"u32": Type = .{ .ip_index = .u32_type };
39463960pub const @"u64": Type = .{ .ip_index = .u64_type };
3961pub const @"u80": Type = .{ .ip_index = .u80_type };
39473962pub const @"u128": Type = .{ .ip_index = .u128_type };
39483963
39493964pub const @"i8": Type = .{ .ip_index = .i8_type };
src/Value.zig+1174-1093
......@@ -40,10 +40,10 @@ pub fn fmtDebug(val: Value) std.fmt.Formatter(dump) {
4040 return .{ .data = val };
4141}
4242
43pub fn fmtValue(val: Value, mod: *Module, opt_sema: ?*Sema) std.fmt.Formatter(print_value.format) {
43pub fn fmtValue(val: Value, pt: Zcu.PerThread, opt_sema: ?*Sema) std.fmt.Formatter(print_value.format) {
4444 return .{ .data = .{
4545 .val = val,
46 .mod = mod,
46 .pt = pt,
4747 .opt_sema = opt_sema,
4848 .depth = 3,
4949 } };
......@@ -55,34 +55,37 @@ pub fn fmtValueFull(ctx: print_value.FormatContext) std.fmt.Formatter(print_valu
5555
5656/// Converts `val` to a null-terminated string stored in the InternPool.
5757/// Asserts `val` is an array of `u8`
58pub fn toIpString(val: Value, ty: Type, mod: *Module) !InternPool.NullTerminatedString {
58pub fn toIpString(val: Value, ty: Type, pt: Zcu.PerThread) !InternPool.NullTerminatedString {
59 const mod = pt.zcu;
5960 assert(ty.zigTypeTag(mod) == .Array);
6061 assert(ty.childType(mod).toIntern() == .u8_type);
6162 const ip = &mod.intern_pool;
6263 switch (mod.intern_pool.indexToKey(val.toIntern()).aggregate.storage) {
6364 .bytes => |bytes| return bytes.toNullTerminatedString(ty.arrayLen(mod), ip),
64 .elems => return arrayToIpString(val, ty.arrayLen(mod), mod),
65 .elems => return arrayToIpString(val, ty.arrayLen(mod), pt),
6566 .repeated_elem => |elem| {
66 const byte: u8 = @intCast(Value.fromInterned(elem).toUnsignedInt(mod));
67 const len: usize = @intCast(ty.arrayLen(mod));
68 try ip.string_bytes.appendNTimes(mod.gpa, byte, len);
69 return ip.getOrPutTrailingString(mod.gpa, len, .no_embedded_nulls);
67 const byte: u8 = @intCast(Value.fromInterned(elem).toUnsignedInt(pt));
68 const len: u32 = @intCast(ty.arrayLen(mod));
69 const strings = ip.getLocal(pt.tid).getMutableStrings(mod.gpa);
70 try strings.appendNTimes(.{byte}, len);
71 return ip.getOrPutTrailingString(mod.gpa, pt.tid, len, .no_embedded_nulls);
7072 },
7173 }
7274}
7375
7476/// Asserts that the value is representable as an array of bytes.
7577/// Copies the value into a freshly allocated slice of memory, which is owned by the caller.
76pub fn toAllocatedBytes(val: Value, ty: Type, allocator: Allocator, mod: *Module) ![]u8 {
78pub fn toAllocatedBytes(val: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) ![]u8 {
79 const mod = pt.zcu;
7780 const ip = &mod.intern_pool;
7881 return switch (ip.indexToKey(val.toIntern())) {
7982 .enum_literal => |enum_literal| allocator.dupe(u8, enum_literal.toSlice(ip)),
80 .slice => |slice| try arrayToAllocatedBytes(val, Value.fromInterned(slice.len).toUnsignedInt(mod), allocator, mod),
83 .slice => |slice| try arrayToAllocatedBytes(val, Value.fromInterned(slice.len).toUnsignedInt(pt), allocator, pt),
8184 .aggregate => |aggregate| switch (aggregate.storage) {
8285 .bytes => |bytes| try allocator.dupe(u8, bytes.toSlice(ty.arrayLenIncludingSentinel(mod), ip)),
83 .elems => try arrayToAllocatedBytes(val, ty.arrayLen(mod), allocator, mod),
86 .elems => try arrayToAllocatedBytes(val, ty.arrayLen(mod), allocator, pt),
8487 .repeated_elem => |elem| {
85 const byte: u8 = @intCast(Value.fromInterned(elem).toUnsignedInt(mod));
88 const byte: u8 = @intCast(Value.fromInterned(elem).toUnsignedInt(pt));
8689 const result = try allocator.alloc(u8, @intCast(ty.arrayLen(mod)));
8790 @memset(result, byte);
8891 return result;
......@@ -92,30 +95,32 @@ pub fn toAllocatedBytes(val: Value, ty: Type, allocator: Allocator, mod: *Module
9295 };
9396}
9497
95fn arrayToAllocatedBytes(val: Value, len: u64, allocator: Allocator, mod: *Module) ![]u8 {
98fn arrayToAllocatedBytes(val: Value, len: u64, allocator: Allocator, pt: Zcu.PerThread) ![]u8 {
9699 const result = try allocator.alloc(u8, @intCast(len));
97100 for (result, 0..) |*elem, i| {
98 const elem_val = try val.elemValue(mod, i);
99 elem.* = @intCast(elem_val.toUnsignedInt(mod));
101 const elem_val = try val.elemValue(pt, i);
102 elem.* = @intCast(elem_val.toUnsignedInt(pt));
100103 }
101104 return result;
102105}
103106
104fn arrayToIpString(val: Value, len_u64: u64, mod: *Module) !InternPool.NullTerminatedString {
107fn arrayToIpString(val: Value, len_u64: u64, pt: Zcu.PerThread) !InternPool.NullTerminatedString {
108 const mod = pt.zcu;
105109 const gpa = mod.gpa;
106110 const ip = &mod.intern_pool;
107 const len: usize = @intCast(len_u64);
108 try ip.string_bytes.ensureUnusedCapacity(gpa, len);
111 const len: u32 = @intCast(len_u64);
112 const strings = ip.getLocal(pt.tid).getMutableStrings(gpa);
113 try strings.ensureUnusedCapacity(len);
109114 for (0..len) |i| {
110115 // I don't think elemValue has the possibility to affect ip.string_bytes. Let's
111116 // assert just to be sure.
112 const prev = ip.string_bytes.items.len;
113 const elem_val = try val.elemValue(mod, i);
114 assert(ip.string_bytes.items.len == prev);
115 const byte: u8 = @intCast(elem_val.toUnsignedInt(mod));
116 ip.string_bytes.appendAssumeCapacity(byte);
117 const prev_len = strings.mutate.len;
118 const elem_val = try val.elemValue(pt, i);
119 assert(strings.mutate.len == prev_len);
120 const byte: u8 = @intCast(elem_val.toUnsignedInt(pt));
121 strings.appendAssumeCapacity(.{byte});
117122 }
118 return ip.getOrPutTrailingString(gpa, len, .no_embedded_nulls);
123 return ip.getOrPutTrailingString(gpa, pt.tid, len, .no_embedded_nulls);
119124}
120125
121126pub fn fromInterned(i: InternPool.Index) Value {
......@@ -133,14 +138,14 @@ pub fn toType(self: Value) Type {
133138 return Type.fromInterned(self.toIntern());
134139}
135140
136pub fn intFromEnum(val: Value, ty: Type, mod: *Module) Allocator.Error!Value {
137 const ip = &mod.intern_pool;
141pub fn intFromEnum(val: Value, ty: Type, pt: Zcu.PerThread) Allocator.Error!Value {
142 const ip = &pt.zcu.intern_pool;
138143 const enum_ty = ip.typeOf(val.toIntern());
139144 return switch (ip.indexToKey(enum_ty)) {
140145 // Assume it is already an integer and return it directly.
141146 .simple_type, .int_type => val,
142147 .enum_literal => |enum_literal| {
143 const field_index = ty.enumFieldIndex(enum_literal, mod).?;
148 const field_index = ty.enumFieldIndex(enum_literal, pt.zcu).?;
144149 switch (ip.indexToKey(ty.toIntern())) {
145150 // Assume it is already an integer and return it directly.
146151 .simple_type, .int_type => return val,
......@@ -150,13 +155,13 @@ pub fn intFromEnum(val: Value, ty: Type, mod: *Module) Allocator.Error!Value {
150155 return Value.fromInterned(enum_type.values.get(ip)[field_index]);
151156 } else {
152157 // Field index and integer values are the same.
153 return mod.intValue(Type.fromInterned(enum_type.tag_ty), field_index);
158 return pt.intValue(Type.fromInterned(enum_type.tag_ty), field_index);
154159 }
155160 },
156161 else => unreachable,
157162 }
158163 },
159 .enum_type => try mod.getCoerced(val, Type.fromInterned(ip.loadEnumType(enum_ty).tag_ty)),
164 .enum_type => try pt.getCoerced(val, Type.fromInterned(ip.loadEnumType(enum_ty).tag_ty)),
160165 else => unreachable,
161166 };
162167}
......@@ -164,38 +169,38 @@ pub fn intFromEnum(val: Value, ty: Type, mod: *Module) Allocator.Error!Value {
164169pub const ResolveStrat = Type.ResolveStrat;
165170
166171/// Asserts the value is an integer.
167pub fn toBigInt(val: Value, space: *BigIntSpace, mod: *Module) BigIntConst {
168 return val.toBigIntAdvanced(space, mod, .normal) catch unreachable;
172pub fn toBigInt(val: Value, space: *BigIntSpace, pt: Zcu.PerThread) BigIntConst {
173 return val.toBigIntAdvanced(space, pt, .normal) catch unreachable;
169174}
170175
171176/// Asserts the value is an integer.
172177pub fn toBigIntAdvanced(
173178 val: Value,
174179 space: *BigIntSpace,
175 mod: *Module,
180 pt: Zcu.PerThread,
176181 strat: ResolveStrat,
177182) Module.CompileError!BigIntConst {
178183 return switch (val.toIntern()) {
179184 .bool_false => BigIntMutable.init(&space.limbs, 0).toConst(),
180185 .bool_true => BigIntMutable.init(&space.limbs, 1).toConst(),
181186 .null_value => BigIntMutable.init(&space.limbs, 0).toConst(),
182 else => switch (mod.intern_pool.indexToKey(val.toIntern())) {
187 else => switch (pt.zcu.intern_pool.indexToKey(val.toIntern())) {
183188 .int => |int| switch (int.storage) {
184189 .u64, .i64, .big_int => int.storage.toBigInt(space),
185190 .lazy_align, .lazy_size => |ty| {
186 if (strat == .sema) try Type.fromInterned(ty).resolveLayout(mod);
191 if (strat == .sema) try Type.fromInterned(ty).resolveLayout(pt);
187192 const x = switch (int.storage) {
188193 else => unreachable,
189 .lazy_align => Type.fromInterned(ty).abiAlignment(mod).toByteUnits() orelse 0,
190 .lazy_size => Type.fromInterned(ty).abiSize(mod),
194 .lazy_align => Type.fromInterned(ty).abiAlignment(pt).toByteUnits() orelse 0,
195 .lazy_size => Type.fromInterned(ty).abiSize(pt),
191196 };
192197 return BigIntMutable.init(&space.limbs, x).toConst();
193198 },
194199 },
195 .enum_tag => |enum_tag| Value.fromInterned(enum_tag.int).toBigIntAdvanced(space, mod, strat),
200 .enum_tag => |enum_tag| Value.fromInterned(enum_tag.int).toBigIntAdvanced(space, pt, strat),
196201 .opt, .ptr => BigIntMutable.init(
197202 &space.limbs,
198 (try val.getUnsignedIntAdvanced(mod, strat)).?,
203 (try val.getUnsignedIntAdvanced(pt, strat)).?,
199204 ).toConst(),
200205 else => unreachable,
201206 },
......@@ -229,13 +234,14 @@ pub fn getVariable(val: Value, mod: *Module) ?InternPool.Key.Variable {
229234
230235/// If the value fits in a u64, return it, otherwise null.
231236/// Asserts not undefined.
232pub fn getUnsignedInt(val: Value, mod: *Module) ?u64 {
233 return getUnsignedIntAdvanced(val, mod, .normal) catch unreachable;
237pub fn getUnsignedInt(val: Value, pt: Zcu.PerThread) ?u64 {
238 return getUnsignedIntAdvanced(val, pt, .normal) catch unreachable;
234239}
235240
236241/// If the value fits in a u64, return it, otherwise null.
237242/// Asserts not undefined.
238pub fn getUnsignedIntAdvanced(val: Value, mod: *Module, strat: ResolveStrat) !?u64 {
243pub fn getUnsignedIntAdvanced(val: Value, pt: Zcu.PerThread, strat: ResolveStrat) !?u64 {
244 const mod = pt.zcu;
239245 return switch (val.toIntern()) {
240246 .undef => unreachable,
241247 .bool_false => 0,
......@@ -246,22 +252,22 @@ pub fn getUnsignedIntAdvanced(val: Value, mod: *Module, strat: ResolveStrat) !?u
246252 .big_int => |big_int| big_int.to(u64) catch null,
247253 .u64 => |x| x,
248254 .i64 => |x| std.math.cast(u64, x),
249 .lazy_align => |ty| (try Type.fromInterned(ty).abiAlignmentAdvanced(mod, strat.toLazy())).scalar.toByteUnits() orelse 0,
250 .lazy_size => |ty| (try Type.fromInterned(ty).abiSizeAdvanced(mod, strat.toLazy())).scalar,
255 .lazy_align => |ty| (try Type.fromInterned(ty).abiAlignmentAdvanced(pt, strat.toLazy())).scalar.toByteUnits() orelse 0,
256 .lazy_size => |ty| (try Type.fromInterned(ty).abiSizeAdvanced(pt, strat.toLazy())).scalar,
251257 },
252258 .ptr => |ptr| switch (ptr.base_addr) {
253259 .int => ptr.byte_offset,
254260 .field => |field| {
255 const base_addr = (try Value.fromInterned(field.base).getUnsignedIntAdvanced(mod, strat)) orelse return null;
261 const base_addr = (try Value.fromInterned(field.base).getUnsignedIntAdvanced(pt, strat)) orelse return null;
256262 const struct_ty = Value.fromInterned(field.base).typeOf(mod).childType(mod);
257 if (strat == .sema) try struct_ty.resolveLayout(mod);
258 return base_addr + struct_ty.structFieldOffset(@intCast(field.index), mod) + ptr.byte_offset;
263 if (strat == .sema) try struct_ty.resolveLayout(pt);
264 return base_addr + struct_ty.structFieldOffset(@intCast(field.index), pt) + ptr.byte_offset;
259265 },
260266 else => null,
261267 },
262268 .opt => |opt| switch (opt.val) {
263269 .none => 0,
264 else => |payload| Value.fromInterned(payload).getUnsignedIntAdvanced(mod, strat),
270 else => |payload| Value.fromInterned(payload).getUnsignedIntAdvanced(pt, strat),
265271 },
266272 else => null,
267273 },
......@@ -269,27 +275,27 @@ pub fn getUnsignedIntAdvanced(val: Value, mod: *Module, strat: ResolveStrat) !?u
269275}
270276
271277/// Asserts the value is an integer and it fits in a u64
272pub fn toUnsignedInt(val: Value, zcu: *Zcu) u64 {
273 return getUnsignedInt(val, zcu).?;
278pub fn toUnsignedInt(val: Value, pt: Zcu.PerThread) u64 {
279 return getUnsignedInt(val, pt).?;
274280}
275281
276282/// Asserts the value is an integer and it fits in a u64
277pub fn toUnsignedIntSema(val: Value, zcu: *Zcu) !u64 {
278 return (try getUnsignedIntAdvanced(val, zcu, .sema)).?;
283pub fn toUnsignedIntSema(val: Value, pt: Zcu.PerThread) !u64 {
284 return (try getUnsignedIntAdvanced(val, pt, .sema)).?;
279285}
280286
281287/// Asserts the value is an integer and it fits in a i64
282pub fn toSignedInt(val: Value, mod: *Module) i64 {
288pub fn toSignedInt(val: Value, pt: Zcu.PerThread) i64 {
283289 return switch (val.toIntern()) {
284290 .bool_false => 0,
285291 .bool_true => 1,
286 else => switch (mod.intern_pool.indexToKey(val.toIntern())) {
292 else => switch (pt.zcu.intern_pool.indexToKey(val.toIntern())) {
287293 .int => |int| switch (int.storage) {
288294 .big_int => |big_int| big_int.to(i64) catch unreachable,
289295 .i64 => |x| x,
290296 .u64 => |x| @intCast(x),
291 .lazy_align => |ty| @intCast(Type.fromInterned(ty).abiAlignment(mod).toByteUnits() orelse 0),
292 .lazy_size => |ty| @intCast(Type.fromInterned(ty).abiSize(mod)),
297 .lazy_align => |ty| @intCast(Type.fromInterned(ty).abiAlignment(pt).toByteUnits() orelse 0),
298 .lazy_size => |ty| @intCast(Type.fromInterned(ty).abiSize(pt)),
293299 },
294300 else => unreachable,
295301 },
......@@ -321,16 +327,17 @@ fn ptrHasIntAddr(val: Value, mod: *Module) bool {
321327///
322328/// Asserts that buffer.len >= ty.abiSize(). The buffer is allowed to extend past
323329/// the end of the value in memory.
324pub fn writeToMemory(val: Value, ty: Type, mod: *Module, buffer: []u8) error{
330pub fn writeToMemory(val: Value, ty: Type, pt: Zcu.PerThread, buffer: []u8) error{
325331 ReinterpretDeclRef,
326332 IllDefinedMemoryLayout,
327333 Unimplemented,
328334 OutOfMemory,
329335}!void {
336 const mod = pt.zcu;
330337 const target = mod.getTarget();
331338 const endian = target.cpu.arch.endian();
332339 if (val.isUndef(mod)) {
333 const size: usize = @intCast(ty.abiSize(mod));
340 const size: usize = @intCast(ty.abiSize(pt));
334341 @memset(buffer[0..size], 0xaa);
335342 return;
336343 }
......@@ -346,41 +353,41 @@ pub fn writeToMemory(val: Value, ty: Type, mod: *Module, buffer: []u8) error{
346353 const byte_count: u16 = @intCast((@as(u17, bits) + 7) / 8);
347354
348355 var bigint_buffer: BigIntSpace = undefined;
349 const bigint = val.toBigInt(&bigint_buffer, mod);
356 const bigint = val.toBigInt(&bigint_buffer, pt);
350357 bigint.writeTwosComplement(buffer[0..byte_count], endian);
351358 },
352359 .Float => switch (ty.floatBits(target)) {
353 16 => std.mem.writeInt(u16, buffer[0..2], @bitCast(val.toFloat(f16, mod)), endian),
354 32 => std.mem.writeInt(u32, buffer[0..4], @bitCast(val.toFloat(f32, mod)), endian),
355 64 => std.mem.writeInt(u64, buffer[0..8], @bitCast(val.toFloat(f64, mod)), endian),
356 80 => std.mem.writeInt(u80, buffer[0..10], @bitCast(val.toFloat(f80, mod)), endian),
357 128 => std.mem.writeInt(u128, buffer[0..16], @bitCast(val.toFloat(f128, mod)), endian),
360 16 => std.mem.writeInt(u16, buffer[0..2], @bitCast(val.toFloat(f16, pt)), endian),
361 32 => std.mem.writeInt(u32, buffer[0..4], @bitCast(val.toFloat(f32, pt)), endian),
362 64 => std.mem.writeInt(u64, buffer[0..8], @bitCast(val.toFloat(f64, pt)), endian),
363 80 => std.mem.writeInt(u80, buffer[0..10], @bitCast(val.toFloat(f80, pt)), endian),
364 128 => std.mem.writeInt(u128, buffer[0..16], @bitCast(val.toFloat(f128, pt)), endian),
358365 else => unreachable,
359366 },
360367 .Array => {
361368 const len = ty.arrayLen(mod);
362369 const elem_ty = ty.childType(mod);
363 const elem_size: usize = @intCast(elem_ty.abiSize(mod));
370 const elem_size: usize = @intCast(elem_ty.abiSize(pt));
364371 var elem_i: usize = 0;
365372 var buf_off: usize = 0;
366373 while (elem_i < len) : (elem_i += 1) {
367 const elem_val = try val.elemValue(mod, elem_i);
368 try elem_val.writeToMemory(elem_ty, mod, buffer[buf_off..]);
374 const elem_val = try val.elemValue(pt, elem_i);
375 try elem_val.writeToMemory(elem_ty, pt, buffer[buf_off..]);
369376 buf_off += elem_size;
370377 }
371378 },
372379 .Vector => {
373380 // We use byte_count instead of abi_size here, so that any padding bytes
374381 // follow the data bytes, on both big- and little-endian systems.
375 const byte_count = (@as(usize, @intCast(ty.bitSize(mod))) + 7) / 8;
376 return writeToPackedMemory(val, ty, mod, buffer[0..byte_count], 0);
382 const byte_count = (@as(usize, @intCast(ty.bitSize(pt))) + 7) / 8;
383 return writeToPackedMemory(val, ty, pt, buffer[0..byte_count], 0);
377384 },
378385 .Struct => {
379386 const struct_type = mod.typeToStruct(ty) orelse return error.IllDefinedMemoryLayout;
380387 switch (struct_type.layout) {
381388 .auto => return error.IllDefinedMemoryLayout,
382389 .@"extern" => for (0..struct_type.field_types.len) |field_index| {
383 const off: usize = @intCast(ty.structFieldOffset(field_index, mod));
390 const off: usize = @intCast(ty.structFieldOffset(field_index, pt));
384391 const field_val = Value.fromInterned(switch (ip.indexToKey(val.toIntern()).aggregate.storage) {
385392 .bytes => |bytes| {
386393 buffer[off] = bytes.at(field_index, ip);
......@@ -390,11 +397,11 @@ pub fn writeToMemory(val: Value, ty: Type, mod: *Module, buffer: []u8) error{
390397 .repeated_elem => |elem| elem,
391398 });
392399 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
393 try writeToMemory(field_val, field_ty, mod, buffer[off..]);
400 try writeToMemory(field_val, field_ty, pt, buffer[off..]);
394401 },
395402 .@"packed" => {
396 const byte_count = (@as(usize, @intCast(ty.bitSize(mod))) + 7) / 8;
397 return writeToPackedMemory(val, ty, mod, buffer[0..byte_count], 0);
403 const byte_count = (@as(usize, @intCast(ty.bitSize(pt))) + 7) / 8;
404 return writeToPackedMemory(val, ty, pt, buffer[0..byte_count], 0);
398405 },
399406 }
400407 },
......@@ -421,34 +428,34 @@ pub fn writeToMemory(val: Value, ty: Type, mod: *Module, buffer: []u8) error{
421428 const union_obj = mod.typeToUnion(ty).?;
422429 const field_index = mod.unionTagFieldIndex(union_obj, union_tag).?;
423430 const field_type = Type.fromInterned(union_obj.field_types.get(&mod.intern_pool)[field_index]);
424 const field_val = try val.fieldValue(mod, field_index);
425 const byte_count: usize = @intCast(field_type.abiSize(mod));
426 return writeToMemory(field_val, field_type, mod, buffer[0..byte_count]);
431 const field_val = try val.fieldValue(pt, field_index);
432 const byte_count: usize = @intCast(field_type.abiSize(pt));
433 return writeToMemory(field_val, field_type, pt, buffer[0..byte_count]);
427434 } else {
428 const backing_ty = try ty.unionBackingType(mod);
429 const byte_count: usize = @intCast(backing_ty.abiSize(mod));
430 return writeToMemory(val.unionValue(mod), backing_ty, mod, buffer[0..byte_count]);
435 const backing_ty = try ty.unionBackingType(pt);
436 const byte_count: usize = @intCast(backing_ty.abiSize(pt));
437 return writeToMemory(val.unionValue(mod), backing_ty, pt, buffer[0..byte_count]);
431438 }
432439 },
433440 .@"packed" => {
434 const backing_ty = try ty.unionBackingType(mod);
435 const byte_count: usize = @intCast(backing_ty.abiSize(mod));
436 return writeToPackedMemory(val, ty, mod, buffer[0..byte_count], 0);
441 const backing_ty = try ty.unionBackingType(pt);
442 const byte_count: usize = @intCast(backing_ty.abiSize(pt));
443 return writeToPackedMemory(val, ty, pt, buffer[0..byte_count], 0);
437444 },
438445 },
439446 .Pointer => {
440447 if (ty.isSlice(mod)) return error.IllDefinedMemoryLayout;
441448 if (!val.ptrHasIntAddr(mod)) return error.ReinterpretDeclRef;
442 return val.writeToMemory(Type.usize, mod, buffer);
449 return val.writeToMemory(Type.usize, pt, buffer);
443450 },
444451 .Optional => {
445452 if (!ty.isPtrLikeOptional(mod)) return error.IllDefinedMemoryLayout;
446453 const child = ty.optionalChild(mod);
447454 const opt_val = val.optionalValue(mod);
448455 if (opt_val) |some| {
449 return some.writeToMemory(child, mod, buffer);
456 return some.writeToMemory(child, pt, buffer);
450457 } else {
451 return writeToMemory(try mod.intValue(Type.usize, 0), Type.usize, mod, buffer);
458 return writeToMemory(try pt.intValue(Type.usize, 0), Type.usize, pt, buffer);
452459 }
453460 },
454461 else => return error.Unimplemented,
......@@ -462,15 +469,16 @@ pub fn writeToMemory(val: Value, ty: Type, mod: *Module, buffer: []u8) error{
462469pub fn writeToPackedMemory(
463470 val: Value,
464471 ty: Type,
465 mod: *Module,
472 pt: Zcu.PerThread,
466473 buffer: []u8,
467474 bit_offset: usize,
468475) error{ ReinterpretDeclRef, OutOfMemory }!void {
476 const mod = pt.zcu;
469477 const ip = &mod.intern_pool;
470478 const target = mod.getTarget();
471479 const endian = target.cpu.arch.endian();
472480 if (val.isUndef(mod)) {
473 const bit_size: usize = @intCast(ty.bitSize(mod));
481 const bit_size: usize = @intCast(ty.bitSize(pt));
474482 if (bit_size != 0) {
475483 std.mem.writeVarPackedInt(buffer, bit_offset, bit_size, @as(u1, 0), endian);
476484 }
......@@ -494,30 +502,30 @@ pub fn writeToPackedMemory(
494502 const bits = ty.intInfo(mod).bits;
495503 if (bits == 0) return;
496504
497 switch (ip.indexToKey((try val.intFromEnum(ty, mod)).toIntern()).int.storage) {
505 switch (ip.indexToKey((try val.intFromEnum(ty, pt)).toIntern()).int.storage) {
498506 inline .u64, .i64 => |int| std.mem.writeVarPackedInt(buffer, bit_offset, bits, int, endian),
499507 .big_int => |bigint| bigint.writePackedTwosComplement(buffer, bit_offset, bits, endian),
500508 .lazy_align => |lazy_align| {
501 const num = Type.fromInterned(lazy_align).abiAlignment(mod).toByteUnits() orelse 0;
509 const num = Type.fromInterned(lazy_align).abiAlignment(pt).toByteUnits() orelse 0;
502510 std.mem.writeVarPackedInt(buffer, bit_offset, bits, num, endian);
503511 },
504512 .lazy_size => |lazy_size| {
505 const num = Type.fromInterned(lazy_size).abiSize(mod);
513 const num = Type.fromInterned(lazy_size).abiSize(pt);
506514 std.mem.writeVarPackedInt(buffer, bit_offset, bits, num, endian);
507515 },
508516 }
509517 },
510518 .Float => switch (ty.floatBits(target)) {
511 16 => std.mem.writePackedInt(u16, buffer, bit_offset, @bitCast(val.toFloat(f16, mod)), endian),
512 32 => std.mem.writePackedInt(u32, buffer, bit_offset, @bitCast(val.toFloat(f32, mod)), endian),
513 64 => std.mem.writePackedInt(u64, buffer, bit_offset, @bitCast(val.toFloat(f64, mod)), endian),
514 80 => std.mem.writePackedInt(u80, buffer, bit_offset, @bitCast(val.toFloat(f80, mod)), endian),
515 128 => std.mem.writePackedInt(u128, buffer, bit_offset, @bitCast(val.toFloat(f128, mod)), endian),
519 16 => std.mem.writePackedInt(u16, buffer, bit_offset, @bitCast(val.toFloat(f16, pt)), endian),
520 32 => std.mem.writePackedInt(u32, buffer, bit_offset, @bitCast(val.toFloat(f32, pt)), endian),
521 64 => std.mem.writePackedInt(u64, buffer, bit_offset, @bitCast(val.toFloat(f64, pt)), endian),
522 80 => std.mem.writePackedInt(u80, buffer, bit_offset, @bitCast(val.toFloat(f80, pt)), endian),
523 128 => std.mem.writePackedInt(u128, buffer, bit_offset, @bitCast(val.toFloat(f128, pt)), endian),
516524 else => unreachable,
517525 },
518526 .Vector => {
519527 const elem_ty = ty.childType(mod);
520 const elem_bit_size: u16 = @intCast(elem_ty.bitSize(mod));
528 const elem_bit_size: u16 = @intCast(elem_ty.bitSize(pt));
521529 const len: usize = @intCast(ty.arrayLen(mod));
522530
523531 var bits: u16 = 0;
......@@ -525,8 +533,8 @@ pub fn writeToPackedMemory(
525533 while (elem_i < len) : (elem_i += 1) {
526534 // On big-endian systems, LLVM reverses the element order of vectors by default
527535 const tgt_elem_i = if (endian == .big) len - elem_i - 1 else elem_i;
528 const elem_val = try val.elemValue(mod, tgt_elem_i);
529 try elem_val.writeToPackedMemory(elem_ty, mod, buffer, bit_offset + bits);
536 const elem_val = try val.elemValue(pt, tgt_elem_i);
537 try elem_val.writeToPackedMemory(elem_ty, pt, buffer, bit_offset + bits);
530538 bits += elem_bit_size;
531539 }
532540 },
......@@ -543,8 +551,8 @@ pub fn writeToPackedMemory(
543551 .repeated_elem => |elem| elem,
544552 });
545553 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
546 const field_bits: u16 = @intCast(field_ty.bitSize(mod));
547 try field_val.writeToPackedMemory(field_ty, mod, buffer, bit_offset + bits);
554 const field_bits: u16 = @intCast(field_ty.bitSize(pt));
555 try field_val.writeToPackedMemory(field_ty, pt, buffer, bit_offset + bits);
548556 bits += field_bits;
549557 }
550558 },
......@@ -556,11 +564,11 @@ pub fn writeToPackedMemory(
556564 if (val.unionTag(mod)) |union_tag| {
557565 const field_index = mod.unionTagFieldIndex(union_obj, union_tag).?;
558566 const field_type = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
559 const field_val = try val.fieldValue(mod, field_index);
560 return field_val.writeToPackedMemory(field_type, mod, buffer, bit_offset);
567 const field_val = try val.fieldValue(pt, field_index);
568 return field_val.writeToPackedMemory(field_type, pt, buffer, bit_offset);
561569 } else {
562 const backing_ty = try ty.unionBackingType(mod);
563 return val.unionValue(mod).writeToPackedMemory(backing_ty, mod, buffer, bit_offset);
570 const backing_ty = try ty.unionBackingType(pt);
571 return val.unionValue(mod).writeToPackedMemory(backing_ty, pt, buffer, bit_offset);
564572 }
565573 },
566574 }
......@@ -568,16 +576,16 @@ pub fn writeToPackedMemory(
568576 .Pointer => {
569577 assert(!ty.isSlice(mod)); // No well defined layout.
570578 if (!val.ptrHasIntAddr(mod)) return error.ReinterpretDeclRef;
571 return val.writeToPackedMemory(Type.usize, mod, buffer, bit_offset);
579 return val.writeToPackedMemory(Type.usize, pt, buffer, bit_offset);
572580 },
573581 .Optional => {
574582 assert(ty.isPtrLikeOptional(mod));
575583 const child = ty.optionalChild(mod);
576584 const opt_val = val.optionalValue(mod);
577585 if (opt_val) |some| {
578 return some.writeToPackedMemory(child, mod, buffer, bit_offset);
586 return some.writeToPackedMemory(child, pt, buffer, bit_offset);
579587 } else {
580 return writeToPackedMemory(try mod.intValue(Type.usize, 0), Type.usize, mod, buffer, bit_offset);
588 return writeToPackedMemory(try pt.intValue(Type.usize, 0), Type.usize, pt, buffer, bit_offset);
581589 }
582590 },
583591 else => @panic("TODO implement writeToPackedMemory for more types"),
......@@ -590,7 +598,7 @@ pub fn writeToPackedMemory(
590598/// the end of the value in memory.
591599pub fn readFromMemory(
592600 ty: Type,
593 mod: *Module,
601 pt: Zcu.PerThread,
594602 buffer: []const u8,
595603 arena: Allocator,
596604) error{
......@@ -598,6 +606,7 @@ pub fn readFromMemory(
598606 Unimplemented,
599607 OutOfMemory,
600608}!Value {
609 const mod = pt.zcu;
601610 const ip = &mod.intern_pool;
602611 const target = mod.getTarget();
603612 const endian = target.cpu.arch.endian();
......@@ -642,7 +651,7 @@ pub fn readFromMemory(
642651 return mod.getCoerced(try mod.intValue_big(int_ty, bigint.toConst()), ty);
643652 }
644653 },
645 .Float => return Value.fromInterned((try mod.intern(.{ .float = .{
654 .Float => return Value.fromInterned(try pt.intern(.{ .float = .{
646655 .ty = ty.toIntern(),
647656 .storage = switch (ty.floatBits(target)) {
648657 16 => .{ .f16 = @bitCast(std.mem.readInt(u16, buffer[0..2], endian)) },
......@@ -652,25 +661,25 @@ pub fn readFromMemory(
652661 128 => .{ .f128 = @bitCast(std.mem.readInt(u128, buffer[0..16], endian)) },
653662 else => unreachable,
654663 },
655 } }))),
664 } })),
656665 .Array => {
657666 const elem_ty = ty.childType(mod);
658 const elem_size = elem_ty.abiSize(mod);
667 const elem_size = elem_ty.abiSize(pt);
659668 const elems = try arena.alloc(InternPool.Index, @intCast(ty.arrayLen(mod)));
660669 var offset: usize = 0;
661670 for (elems) |*elem| {
662671 elem.* = (try readFromMemory(elem_ty, mod, buffer[offset..], arena)).toIntern();
663672 offset += @intCast(elem_size);
664673 }
665 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
674 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
666675 .ty = ty.toIntern(),
667676 .storage = .{ .elems = elems },
668 } })));
677 } }));
669678 },
670679 .Vector => {
671680 // We use byte_count instead of abi_size here, so that any padding bytes
672681 // follow the data bytes, on both big- and little-endian systems.
673 const byte_count = (@as(usize, @intCast(ty.bitSize(mod))) + 7) / 8;
682 const byte_count = (@as(usize, @intCast(ty.bitSize(pt))) + 7) / 8;
674683 return readFromPackedMemory(ty, mod, buffer[0..byte_count], 0, arena);
675684 },
676685 .Struct => {
......@@ -683,16 +692,16 @@ pub fn readFromMemory(
683692 for (field_vals, 0..) |*field_val, i| {
684693 const field_ty = Type.fromInterned(field_types.get(ip)[i]);
685694 const off: usize = @intCast(ty.structFieldOffset(i, mod));
686 const sz: usize = @intCast(field_ty.abiSize(mod));
695 const sz: usize = @intCast(field_ty.abiSize(pt));
687696 field_val.* = (try readFromMemory(field_ty, mod, buffer[off..(off + sz)], arena)).toIntern();
688697 }
689 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
698 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
690699 .ty = ty.toIntern(),
691700 .storage = .{ .elems = field_vals },
692 } })));
701 } }));
693702 },
694703 .@"packed" => {
695 const byte_count = (@as(usize, @intCast(ty.bitSize(mod))) + 7) / 8;
704 const byte_count = (@as(usize, @intCast(ty.bitSize(pt))) + 7) / 8;
696705 return readFromPackedMemory(ty, mod, buffer[0..byte_count], 0, arena);
697706 },
698707 }
......@@ -704,49 +713,49 @@ pub fn readFromMemory(
704713 const index = (int << @as(u6, @intCast(64 - bits))) >> @as(u6, @intCast(64 - bits));
705714 const name = mod.global_error_set.keys()[@intCast(index)];
706715
707 return Value.fromInterned((try mod.intern(.{ .err = .{
716 return Value.fromInterned(try pt.intern(.{ .err = .{
708717 .ty = ty.toIntern(),
709718 .name = name,
710 } })));
719 } }));
711720 },
712721 .Union => switch (ty.containerLayout(mod)) {
713722 .auto => return error.IllDefinedMemoryLayout,
714723 .@"extern" => {
715 const union_size = ty.abiSize(mod);
724 const union_size = ty.abiSize(pt);
716725 const array_ty = try mod.arrayType(.{ .len = union_size, .child = .u8_type });
717726 const val = (try readFromMemory(array_ty, mod, buffer, arena)).toIntern();
718 return Value.fromInterned((try mod.intern(.{ .un = .{
727 return Value.fromInterned(try pt.intern(.{ .un = .{
719728 .ty = ty.toIntern(),
720729 .tag = .none,
721730 .val = val,
722 } })));
731 } }));
723732 },
724733 .@"packed" => {
725 const byte_count = (@as(usize, @intCast(ty.bitSize(mod))) + 7) / 8;
734 const byte_count = (@as(usize, @intCast(ty.bitSize(pt))) + 7) / 8;
726735 return readFromPackedMemory(ty, mod, buffer[0..byte_count], 0, arena);
727736 },
728737 },
729738 .Pointer => {
730739 assert(!ty.isSlice(mod)); // No well defined layout.
731740 const int_val = try readFromMemory(Type.usize, mod, buffer, arena);
732 return Value.fromInterned((try mod.intern(.{ .ptr = .{
741 return Value.fromInterned(try pt.intern(.{ .ptr = .{
733742 .ty = ty.toIntern(),
734743 .base_addr = .int,
735 .byte_offset = int_val.toUnsignedInt(mod),
736 } })));
744 .byte_offset = int_val.toUnsignedInt(pt),
745 } }));
737746 },
738747 .Optional => {
739748 assert(ty.isPtrLikeOptional(mod));
740749 const child_ty = ty.optionalChild(mod);
741750 const child_val = try readFromMemory(child_ty, mod, buffer, arena);
742 return Value.fromInterned((try mod.intern(.{ .opt = .{
751 return Value.fromInterned(try pt.intern(.{ .opt = .{
743752 .ty = ty.toIntern(),
744 .val = switch (child_val.orderAgainstZero(mod)) {
753 .val = switch (child_val.orderAgainstZero(pt)) {
745754 .lt => unreachable,
746755 .eq => .none,
747756 .gt => child_val.toIntern(),
748757 },
749 } })));
758 } }));
750759 },
751760 else => return error.Unimplemented,
752761 }
......@@ -758,7 +767,7 @@ pub fn readFromMemory(
758767/// big-endian packed memory layouts start at the end of the buffer.
759768pub fn readFromPackedMemory(
760769 ty: Type,
761 mod: *Module,
770 pt: Zcu.PerThread,
762771 buffer: []const u8,
763772 bit_offset: usize,
764773 arena: Allocator,
......@@ -766,6 +775,7 @@ pub fn readFromPackedMemory(
766775 IllDefinedMemoryLayout,
767776 OutOfMemory,
768777}!Value {
778 const mod = pt.zcu;
769779 const ip = &mod.intern_pool;
770780 const target = mod.getTarget();
771781 const endian = target.cpu.arch.endian();
......@@ -783,35 +793,35 @@ pub fn readFromPackedMemory(
783793 }
784794 },
785795 .Int => {
786 if (buffer.len == 0) return mod.intValue(ty, 0);
796 if (buffer.len == 0) return pt.intValue(ty, 0);
787797 const int_info = ty.intInfo(mod);
788798 const bits = int_info.bits;
789 if (bits == 0) return mod.intValue(ty, 0);
799 if (bits == 0) return pt.intValue(ty, 0);
790800
791801 // Fast path for integers <= u64
792802 if (bits <= 64) switch (int_info.signedness) {
793803 // Use different backing types for unsigned vs signed to avoid the need to go via
794804 // a larger type like `i128`.
795 .unsigned => return mod.intValue(ty, std.mem.readVarPackedInt(u64, buffer, bit_offset, bits, endian, .unsigned)),
796 .signed => return mod.intValue(ty, std.mem.readVarPackedInt(i64, buffer, bit_offset, bits, endian, .signed)),
805 .unsigned => return pt.intValue(ty, std.mem.readVarPackedInt(u64, buffer, bit_offset, bits, endian, .unsigned)),
806 .signed => return pt.intValue(ty, std.mem.readVarPackedInt(i64, buffer, bit_offset, bits, endian, .signed)),
797807 };
798808
799809 // Slow path, we have to construct a big-int
800 const abi_size: usize = @intCast(ty.abiSize(mod));
810 const abi_size: usize = @intCast(ty.abiSize(pt));
801811 const Limb = std.math.big.Limb;
802812 const limb_count = (abi_size + @sizeOf(Limb) - 1) / @sizeOf(Limb);
803813 const limbs_buffer = try arena.alloc(Limb, limb_count);
804814
805815 var bigint = BigIntMutable.init(limbs_buffer, 0);
806816 bigint.readPackedTwosComplement(buffer, bit_offset, bits, endian, int_info.signedness);
807 return mod.intValue_big(ty, bigint.toConst());
817 return pt.intValue_big(ty, bigint.toConst());
808818 },
809819 .Enum => {
810820 const int_ty = ty.intTagType(mod);
811 const int_val = try Value.readFromPackedMemory(int_ty, mod, buffer, bit_offset, arena);
812 return mod.getCoerced(int_val, ty);
821 const int_val = try Value.readFromPackedMemory(int_ty, pt, buffer, bit_offset, arena);
822 return pt.getCoerced(int_val, ty);
813823 },
814 .Float => return Value.fromInterned((try mod.intern(.{ .float = .{
824 .Float => return Value.fromInterned(try pt.intern(.{ .float = .{
815825 .ty = ty.toIntern(),
816826 .storage = switch (ty.floatBits(target)) {
817827 16 => .{ .f16 = @bitCast(std.mem.readPackedInt(u16, buffer, bit_offset, endian)) },
......@@ -821,23 +831,23 @@ pub fn readFromPackedMemory(
821831 128 => .{ .f128 = @bitCast(std.mem.readPackedInt(u128, buffer, bit_offset, endian)) },
822832 else => unreachable,
823833 },
824 } }))),
834 } })),
825835 .Vector => {
826836 const elem_ty = ty.childType(mod);
827837 const elems = try arena.alloc(InternPool.Index, @intCast(ty.arrayLen(mod)));
828838
829839 var bits: u16 = 0;
830 const elem_bit_size: u16 = @intCast(elem_ty.bitSize(mod));
840 const elem_bit_size: u16 = @intCast(elem_ty.bitSize(pt));
831841 for (elems, 0..) |_, i| {
832842 // On big-endian systems, LLVM reverses the element order of vectors by default
833843 const tgt_elem_i = if (endian == .big) elems.len - i - 1 else i;
834 elems[tgt_elem_i] = (try readFromPackedMemory(elem_ty, mod, buffer, bit_offset + bits, arena)).toIntern();
844 elems[tgt_elem_i] = (try readFromPackedMemory(elem_ty, pt, buffer, bit_offset + bits, arena)).toIntern();
835845 bits += elem_bit_size;
836846 }
837 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
847 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
838848 .ty = ty.toIntern(),
839849 .storage = .{ .elems = elems },
840 } })));
850 } }));
841851 },
842852 .Struct => {
843853 // Sema is supposed to have emitted a compile error already for Auto layout structs,
......@@ -847,43 +857,43 @@ pub fn readFromPackedMemory(
847857 const field_vals = try arena.alloc(InternPool.Index, struct_type.field_types.len);
848858 for (field_vals, 0..) |*field_val, i| {
849859 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
850 const field_bits: u16 = @intCast(field_ty.bitSize(mod));
851 field_val.* = (try readFromPackedMemory(field_ty, mod, buffer, bit_offset + bits, arena)).toIntern();
860 const field_bits: u16 = @intCast(field_ty.bitSize(pt));
861 field_val.* = (try readFromPackedMemory(field_ty, pt, buffer, bit_offset + bits, arena)).toIntern();
852862 bits += field_bits;
853863 }
854 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
864 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
855865 .ty = ty.toIntern(),
856866 .storage = .{ .elems = field_vals },
857 } })));
867 } }));
858868 },
859869 .Union => switch (ty.containerLayout(mod)) {
860870 .auto, .@"extern" => unreachable, // Handled by non-packed readFromMemory
861871 .@"packed" => {
862 const backing_ty = try ty.unionBackingType(mod);
863 const val = (try readFromPackedMemory(backing_ty, mod, buffer, bit_offset, arena)).toIntern();
864 return Value.fromInterned((try mod.intern(.{ .un = .{
872 const backing_ty = try ty.unionBackingType(pt);
873 const val = (try readFromPackedMemory(backing_ty, pt, buffer, bit_offset, arena)).toIntern();
874 return Value.fromInterned(try pt.intern(.{ .un = .{
865875 .ty = ty.toIntern(),
866876 .tag = .none,
867877 .val = val,
868 } })));
878 } }));
869879 },
870880 },
871881 .Pointer => {
872882 assert(!ty.isSlice(mod)); // No well defined layout.
873 const int_val = try readFromPackedMemory(Type.usize, mod, buffer, bit_offset, arena);
874 return Value.fromInterned(try mod.intern(.{ .ptr = .{
883 const int_val = try readFromPackedMemory(Type.usize, pt, buffer, bit_offset, arena);
884 return Value.fromInterned(try pt.intern(.{ .ptr = .{
875885 .ty = ty.toIntern(),
876886 .base_addr = .int,
877 .byte_offset = int_val.toUnsignedInt(mod),
887 .byte_offset = int_val.toUnsignedInt(pt),
878888 } }));
879889 },
880890 .Optional => {
881891 assert(ty.isPtrLikeOptional(mod));
882892 const child_ty = ty.optionalChild(mod);
883 const child_val = try readFromPackedMemory(child_ty, mod, buffer, bit_offset, arena);
884 return Value.fromInterned(try mod.intern(.{ .opt = .{
893 const child_val = try readFromPackedMemory(child_ty, pt, buffer, bit_offset, arena);
894 return Value.fromInterned(try pt.intern(.{ .opt = .{
885895 .ty = ty.toIntern(),
886 .val = switch (child_val.orderAgainstZero(mod)) {
896 .val = switch (child_val.orderAgainstZero(pt)) {
887897 .lt => unreachable,
888898 .eq => .none,
889899 .gt => child_val.toIntern(),
......@@ -895,8 +905,8 @@ pub fn readFromPackedMemory(
895905}
896906
897907/// Asserts that the value is a float or an integer.
898pub fn toFloat(val: Value, comptime T: type, mod: *Module) T {
899 return switch (mod.intern_pool.indexToKey(val.toIntern())) {
908pub fn toFloat(val: Value, comptime T: type, pt: Zcu.PerThread) T {
909 return switch (pt.zcu.intern_pool.indexToKey(val.toIntern())) {
900910 .int => |int| switch (int.storage) {
901911 .big_int => |big_int| @floatCast(bigIntToFloat(big_int.limbs, big_int.positive)),
902912 inline .u64, .i64 => |x| {
......@@ -905,8 +915,8 @@ pub fn toFloat(val: Value, comptime T: type, mod: *Module) T {
905915 }
906916 return @floatFromInt(x);
907917 },
908 .lazy_align => |ty| @floatFromInt(Type.fromInterned(ty).abiAlignment(mod).toByteUnits() orelse 0),
909 .lazy_size => |ty| @floatFromInt(Type.fromInterned(ty).abiSize(mod)),
918 .lazy_align => |ty| @floatFromInt(Type.fromInterned(ty).abiAlignment(pt).toByteUnits() orelse 0),
919 .lazy_size => |ty| @floatFromInt(Type.fromInterned(ty).abiSize(pt)),
910920 },
911921 .float => |float| switch (float.storage) {
912922 inline else => |x| @floatCast(x),
......@@ -934,29 +944,30 @@ fn bigIntToFloat(limbs: []const std.math.big.Limb, positive: bool) f128 {
934944 }
935945}
936946
937pub fn clz(val: Value, ty: Type, mod: *Module) u64 {
947pub fn clz(val: Value, ty: Type, pt: Zcu.PerThread) u64 {
938948 var bigint_buf: BigIntSpace = undefined;
939 const bigint = val.toBigInt(&bigint_buf, mod);
940 return bigint.clz(ty.intInfo(mod).bits);
949 const bigint = val.toBigInt(&bigint_buf, pt);
950 return bigint.clz(ty.intInfo(pt.zcu).bits);
941951}
942952
943pub fn ctz(val: Value, ty: Type, mod: *Module) u64 {
953pub fn ctz(val: Value, ty: Type, pt: Zcu.PerThread) u64 {
944954 var bigint_buf: BigIntSpace = undefined;
945 const bigint = val.toBigInt(&bigint_buf, mod);
946 return bigint.ctz(ty.intInfo(mod).bits);
955 const bigint = val.toBigInt(&bigint_buf, pt);
956 return bigint.ctz(ty.intInfo(pt.zcu).bits);
947957}
948958
949pub fn popCount(val: Value, ty: Type, mod: *Module) u64 {
959pub fn popCount(val: Value, ty: Type, pt: Zcu.PerThread) u64 {
950960 var bigint_buf: BigIntSpace = undefined;
951 const bigint = val.toBigInt(&bigint_buf, mod);
952 return @intCast(bigint.popCount(ty.intInfo(mod).bits));
961 const bigint = val.toBigInt(&bigint_buf, pt);
962 return @intCast(bigint.popCount(ty.intInfo(pt.zcu).bits));
953963}
954964
955pub fn bitReverse(val: Value, ty: Type, mod: *Module, arena: Allocator) !Value {
965pub fn bitReverse(val: Value, ty: Type, pt: Zcu.PerThread, arena: Allocator) !Value {
966 const mod = pt.zcu;
956967 const info = ty.intInfo(mod);
957968
958969 var buffer: Value.BigIntSpace = undefined;
959 const operand_bigint = val.toBigInt(&buffer, mod);
970 const operand_bigint = val.toBigInt(&buffer, pt);
960971
961972 const limbs = try arena.alloc(
962973 std.math.big.Limb,
......@@ -965,17 +976,18 @@ pub fn bitReverse(val: Value, ty: Type, mod: *Module, arena: Allocator) !Value {
965976 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
966977 result_bigint.bitReverse(operand_bigint, info.signedness, info.bits);
967978
968 return mod.intValue_big(ty, result_bigint.toConst());
979 return pt.intValue_big(ty, result_bigint.toConst());
969980}
970981
971pub fn byteSwap(val: Value, ty: Type, mod: *Module, arena: Allocator) !Value {
982pub fn byteSwap(val: Value, ty: Type, pt: Zcu.PerThread, arena: Allocator) !Value {
983 const mod = pt.zcu;
972984 const info = ty.intInfo(mod);
973985
974986 // Bit count must be evenly divisible by 8
975987 assert(info.bits % 8 == 0);
976988
977989 var buffer: Value.BigIntSpace = undefined;
978 const operand_bigint = val.toBigInt(&buffer, mod);
990 const operand_bigint = val.toBigInt(&buffer, pt);
979991
980992 const limbs = try arena.alloc(
981993 std.math.big.Limb,
......@@ -984,33 +996,33 @@ pub fn byteSwap(val: Value, ty: Type, mod: *Module, arena: Allocator) !Value {
984996 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
985997 result_bigint.byteSwap(operand_bigint, info.signedness, info.bits / 8);
986998
987 return mod.intValue_big(ty, result_bigint.toConst());
999 return pt.intValue_big(ty, result_bigint.toConst());
9881000}
9891001
9901002/// Asserts the value is an integer and not undefined.
9911003/// Returns the number of bits the value requires to represent stored in twos complement form.
992pub fn intBitCountTwosComp(self: Value, mod: *Module) usize {
1004pub fn intBitCountTwosComp(self: Value, pt: Zcu.PerThread) usize {
9931005 var buffer: BigIntSpace = undefined;
994 const big_int = self.toBigInt(&buffer, mod);
1006 const big_int = self.toBigInt(&buffer, pt);
9951007 return big_int.bitCountTwosComp();
9961008}
9971009
9981010/// Converts an integer or a float to a float. May result in a loss of information.
9991011/// Caller can find out by equality checking the result against the operand.
1000pub fn floatCast(val: Value, dest_ty: Type, zcu: *Zcu) !Value {
1001 const target = zcu.getTarget();
1002 if (val.isUndef(zcu)) return zcu.undefValue(dest_ty);
1003 return Value.fromInterned((try zcu.intern(.{ .float = .{
1012pub fn floatCast(val: Value, dest_ty: Type, pt: Zcu.PerThread) !Value {
1013 const target = pt.zcu.getTarget();
1014 if (val.isUndef(pt.zcu)) return pt.undefValue(dest_ty);
1015 return Value.fromInterned(try pt.intern(.{ .float = .{
10041016 .ty = dest_ty.toIntern(),
10051017 .storage = switch (dest_ty.floatBits(target)) {
1006 16 => .{ .f16 = val.toFloat(f16, zcu) },
1007 32 => .{ .f32 = val.toFloat(f32, zcu) },
1008 64 => .{ .f64 = val.toFloat(f64, zcu) },
1009 80 => .{ .f80 = val.toFloat(f80, zcu) },
1010 128 => .{ .f128 = val.toFloat(f128, zcu) },
1018 16 => .{ .f16 = val.toFloat(f16, pt) },
1019 32 => .{ .f32 = val.toFloat(f32, pt) },
1020 64 => .{ .f64 = val.toFloat(f64, pt) },
1021 80 => .{ .f80 = val.toFloat(f80, pt) },
1022 128 => .{ .f128 = val.toFloat(f128, pt) },
10111023 else => unreachable,
10121024 },
1013 } })));
1025 } }));
10141026}
10151027
10161028/// Asserts the value is a float
......@@ -1023,19 +1035,19 @@ pub fn floatHasFraction(self: Value, mod: *const Module) bool {
10231035 };
10241036}
10251037
1026pub fn orderAgainstZero(lhs: Value, mod: *Module) std.math.Order {
1027 return orderAgainstZeroAdvanced(lhs, mod, .normal) catch unreachable;
1038pub fn orderAgainstZero(lhs: Value, pt: Zcu.PerThread) std.math.Order {
1039 return orderAgainstZeroAdvanced(lhs, pt, .normal) catch unreachable;
10281040}
10291041
10301042pub fn orderAgainstZeroAdvanced(
10311043 lhs: Value,
1032 mod: *Module,
1044 pt: Zcu.PerThread,
10331045 strat: ResolveStrat,
10341046) Module.CompileError!std.math.Order {
10351047 return switch (lhs.toIntern()) {
10361048 .bool_false => .eq,
10371049 .bool_true => .gt,
1038 else => switch (mod.intern_pool.indexToKey(lhs.toIntern())) {
1050 else => switch (pt.zcu.intern_pool.indexToKey(lhs.toIntern())) {
10391051 .ptr => |ptr| if (ptr.byte_offset > 0) .gt else switch (ptr.base_addr) {
10401052 .decl, .comptime_alloc, .comptime_field => .gt,
10411053 .int => .eq,
......@@ -1046,7 +1058,7 @@ pub fn orderAgainstZeroAdvanced(
10461058 inline .u64, .i64 => |x| std.math.order(x, 0),
10471059 .lazy_align => .gt, // alignment is never 0
10481060 .lazy_size => |ty| return if (Type.fromInterned(ty).hasRuntimeBitsAdvanced(
1049 mod,
1061 pt,
10501062 false,
10511063 strat.toLazy(),
10521064 ) catch |err| switch (err) {
......@@ -1054,7 +1066,7 @@ pub fn orderAgainstZeroAdvanced(
10541066 else => |e| return e,
10551067 }) .gt else .eq,
10561068 },
1057 .enum_tag => |enum_tag| Value.fromInterned(enum_tag.int).orderAgainstZeroAdvanced(mod, strat),
1069 .enum_tag => |enum_tag| Value.fromInterned(enum_tag.int).orderAgainstZeroAdvanced(pt, strat),
10581070 .float => |float| switch (float.storage) {
10591071 inline else => |x| std.math.order(x, 0),
10601072 },
......@@ -1064,14 +1076,14 @@ pub fn orderAgainstZeroAdvanced(
10641076}
10651077
10661078/// Asserts the value is comparable.
1067pub fn order(lhs: Value, rhs: Value, mod: *Module) std.math.Order {
1068 return orderAdvanced(lhs, rhs, mod, .normal) catch unreachable;
1079pub fn order(lhs: Value, rhs: Value, pt: Zcu.PerThread) std.math.Order {
1080 return orderAdvanced(lhs, rhs, pt, .normal) catch unreachable;
10691081}
10701082
10711083/// Asserts the value is comparable.
1072pub fn orderAdvanced(lhs: Value, rhs: Value, mod: *Module, strat: ResolveStrat) !std.math.Order {
1073 const lhs_against_zero = try lhs.orderAgainstZeroAdvanced(mod, strat);
1074 const rhs_against_zero = try rhs.orderAgainstZeroAdvanced(mod, strat);
1084pub fn orderAdvanced(lhs: Value, rhs: Value, pt: Zcu.PerThread, strat: ResolveStrat) !std.math.Order {
1085 const lhs_against_zero = try lhs.orderAgainstZeroAdvanced(pt, strat);
1086 const rhs_against_zero = try rhs.orderAgainstZeroAdvanced(pt, strat);
10751087 switch (lhs_against_zero) {
10761088 .lt => if (rhs_against_zero != .lt) return .lt,
10771089 .eq => return rhs_against_zero.invert(),
......@@ -1083,34 +1095,34 @@ pub fn orderAdvanced(lhs: Value, rhs: Value, mod: *Module, strat: ResolveStrat)
10831095 .gt => {},
10841096 }
10851097
1086 if (lhs.isFloat(mod) or rhs.isFloat(mod)) {
1087 const lhs_f128 = lhs.toFloat(f128, mod);
1088 const rhs_f128 = rhs.toFloat(f128, mod);
1098 if (lhs.isFloat(pt.zcu) or rhs.isFloat(pt.zcu)) {
1099 const lhs_f128 = lhs.toFloat(f128, pt);
1100 const rhs_f128 = rhs.toFloat(f128, pt);
10891101 return std.math.order(lhs_f128, rhs_f128);
10901102 }
10911103
10921104 var lhs_bigint_space: BigIntSpace = undefined;
10931105 var rhs_bigint_space: BigIntSpace = undefined;
1094 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_bigint_space, mod, strat);
1095 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_bigint_space, mod, strat);
1106 const lhs_bigint = try lhs.toBigIntAdvanced(&lhs_bigint_space, pt, strat);
1107 const rhs_bigint = try rhs.toBigIntAdvanced(&rhs_bigint_space, pt, strat);
10961108 return lhs_bigint.order(rhs_bigint);
10971109}
10981110
10991111/// Asserts the value is comparable. Does not take a type parameter because it supports
11001112/// comparisons between heterogeneous types.
1101pub fn compareHetero(lhs: Value, op: std.math.CompareOperator, rhs: Value, mod: *Module) bool {
1102 return compareHeteroAdvanced(lhs, op, rhs, mod, .normal) catch unreachable;
1113pub fn compareHetero(lhs: Value, op: std.math.CompareOperator, rhs: Value, pt: Zcu.PerThread) bool {
1114 return compareHeteroAdvanced(lhs, op, rhs, pt, .normal) catch unreachable;
11031115}
11041116
11051117pub fn compareHeteroAdvanced(
11061118 lhs: Value,
11071119 op: std.math.CompareOperator,
11081120 rhs: Value,
1109 mod: *Module,
1121 pt: Zcu.PerThread,
11101122 strat: ResolveStrat,
11111123) !bool {
1112 if (lhs.pointerDecl(mod)) |lhs_decl| {
1113 if (rhs.pointerDecl(mod)) |rhs_decl| {
1124 if (lhs.pointerDecl(pt.zcu)) |lhs_decl| {
1125 if (rhs.pointerDecl(pt.zcu)) |rhs_decl| {
11141126 switch (op) {
11151127 .eq => return lhs_decl == rhs_decl,
11161128 .neq => return lhs_decl != rhs_decl,
......@@ -1123,31 +1135,32 @@ pub fn compareHeteroAdvanced(
11231135 else => {},
11241136 }
11251137 }
1126 } else if (rhs.pointerDecl(mod)) |_| {
1138 } else if (rhs.pointerDecl(pt.zcu)) |_| {
11271139 switch (op) {
11281140 .eq => return false,
11291141 .neq => return true,
11301142 else => {},
11311143 }
11321144 }
1133 return (try orderAdvanced(lhs, rhs, mod, strat)).compare(op);
1145 return (try orderAdvanced(lhs, rhs, pt, strat)).compare(op);
11341146}
11351147
11361148/// Asserts the values are comparable. Both operands have type `ty`.
11371149/// For vectors, returns true if comparison is true for ALL elements.
1138pub fn compareAll(lhs: Value, op: std.math.CompareOperator, rhs: Value, ty: Type, mod: *Module) !bool {
1150pub fn compareAll(lhs: Value, op: std.math.CompareOperator, rhs: Value, ty: Type, pt: Zcu.PerThread) !bool {
1151 const mod = pt.zcu;
11391152 if (ty.zigTypeTag(mod) == .Vector) {
11401153 const scalar_ty = ty.scalarType(mod);
11411154 for (0..ty.vectorLen(mod)) |i| {
1142 const lhs_elem = try lhs.elemValue(mod, i);
1143 const rhs_elem = try rhs.elemValue(mod, i);
1144 if (!compareScalar(lhs_elem, op, rhs_elem, scalar_ty, mod)) {
1155 const lhs_elem = try lhs.elemValue(pt, i);
1156 const rhs_elem = try rhs.elemValue(pt, i);
1157 if (!compareScalar(lhs_elem, op, rhs_elem, scalar_ty, pt)) {
11451158 return false;
11461159 }
11471160 }
11481161 return true;
11491162 }
1150 return compareScalar(lhs, op, rhs, ty, mod);
1163 return compareScalar(lhs, op, rhs, ty, pt);
11511164}
11521165
11531166/// Asserts the values are comparable. Both operands have type `ty`.
......@@ -1156,12 +1169,12 @@ pub fn compareScalar(
11561169 op: std.math.CompareOperator,
11571170 rhs: Value,
11581171 ty: Type,
1159 mod: *Module,
1172 pt: Zcu.PerThread,
11601173) bool {
11611174 return switch (op) {
1162 .eq => lhs.eql(rhs, ty, mod),
1163 .neq => !lhs.eql(rhs, ty, mod),
1164 else => compareHetero(lhs, op, rhs, mod),
1175 .eq => lhs.eql(rhs, ty, pt.zcu),
1176 .neq => !lhs.eql(rhs, ty, pt.zcu),
1177 else => compareHetero(lhs, op, rhs, pt),
11651178 };
11661179}
11671180
......@@ -1170,24 +1183,25 @@ pub fn compareScalar(
11701183/// Returns `false` if the value or any vector element is undefined.
11711184///
11721185/// Note that `!compareAllWithZero(.eq, ...) != compareAllWithZero(.neq, ...)`
1173pub fn compareAllWithZero(lhs: Value, op: std.math.CompareOperator, mod: *Module) bool {
1174 return compareAllWithZeroAdvancedExtra(lhs, op, mod, .normal) catch unreachable;
1186pub fn compareAllWithZero(lhs: Value, op: std.math.CompareOperator, pt: Zcu.PerThread) bool {
1187 return compareAllWithZeroAdvancedExtra(lhs, op, pt, .normal) catch unreachable;
11751188}
11761189
11771190pub fn compareAllWithZeroSema(
11781191 lhs: Value,
11791192 op: std.math.CompareOperator,
1180 zcu: *Zcu,
1193 pt: Zcu.PerThread,
11811194) Module.CompileError!bool {
1182 return compareAllWithZeroAdvancedExtra(lhs, op, zcu, .sema);
1195 return compareAllWithZeroAdvancedExtra(lhs, op, pt, .sema);
11831196}
11841197
11851198pub fn compareAllWithZeroAdvancedExtra(
11861199 lhs: Value,
11871200 op: std.math.CompareOperator,
1188 mod: *Module,
1201 pt: Zcu.PerThread,
11891202 strat: ResolveStrat,
11901203) Module.CompileError!bool {
1204 const mod = pt.zcu;
11911205 if (lhs.isInf(mod)) {
11921206 switch (op) {
11931207 .neq => return true,
......@@ -1206,14 +1220,14 @@ pub fn compareAllWithZeroAdvancedExtra(
12061220 if (!std.math.order(byte, 0).compare(op)) break false;
12071221 } else true,
12081222 .elems => |elems| for (elems) |elem| {
1209 if (!try Value.fromInterned(elem).compareAllWithZeroAdvancedExtra(op, mod, strat)) break false;
1223 if (!try Value.fromInterned(elem).compareAllWithZeroAdvancedExtra(op, pt, strat)) break false;
12101224 } else true,
1211 .repeated_elem => |elem| Value.fromInterned(elem).compareAllWithZeroAdvancedExtra(op, mod, strat),
1225 .repeated_elem => |elem| Value.fromInterned(elem).compareAllWithZeroAdvancedExtra(op, pt, strat),
12121226 },
12131227 .undef => return false,
12141228 else => {},
12151229 }
1216 return (try orderAgainstZeroAdvanced(lhs, mod, strat)).compare(op);
1230 return (try orderAgainstZeroAdvanced(lhs, pt, strat)).compare(op);
12171231}
12181232
12191233pub fn eql(a: Value, b: Value, ty: Type, mod: *Module) bool {
......@@ -1275,21 +1289,22 @@ pub fn slicePtr(val: Value, mod: *Module) Value {
12751289
12761290/// Gets the `len` field of a slice value as a `u64`.
12771291/// Resolves the length using `Sema` if necessary.
1278pub fn sliceLen(val: Value, zcu: *Zcu) !u64 {
1279 return Value.fromInterned(zcu.intern_pool.sliceLen(val.toIntern())).toUnsignedIntSema(zcu);
1292pub fn sliceLen(val: Value, pt: Zcu.PerThread) !u64 {
1293 return Value.fromInterned(pt.zcu.intern_pool.sliceLen(val.toIntern())).toUnsignedIntSema(pt);
12801294}
12811295
12821296/// Asserts the value is an aggregate, and returns the element value at the given index.
1283pub fn elemValue(val: Value, zcu: *Zcu, index: usize) Allocator.Error!Value {
1297pub fn elemValue(val: Value, pt: Zcu.PerThread, index: usize) Allocator.Error!Value {
1298 const zcu = pt.zcu;
12841299 const ip = &zcu.intern_pool;
12851300 switch (zcu.intern_pool.indexToKey(val.toIntern())) {
12861301 .undef => |ty| {
1287 return Value.fromInterned(try zcu.intern(.{ .undef = Type.fromInterned(ty).childType(zcu).toIntern() }));
1302 return Value.fromInterned(try pt.intern(.{ .undef = Type.fromInterned(ty).childType(zcu).toIntern() }));
12881303 },
12891304 .aggregate => |aggregate| {
12901305 const len = ip.aggregateTypeLen(aggregate.ty);
12911306 if (index < len) return Value.fromInterned(switch (aggregate.storage) {
1292 .bytes => |bytes| try zcu.intern(.{ .int = .{
1307 .bytes => |bytes| try pt.intern(.{ .int = .{
12931308 .ty = .u8_type,
12941309 .storage = .{ .u64 = bytes.at(index, ip) },
12951310 } }),
......@@ -1330,17 +1345,17 @@ pub fn sliceArray(
13301345 start: usize,
13311346 end: usize,
13321347) error{OutOfMemory}!Value {
1333 const mod = sema.mod;
1334 const ip = &mod.intern_pool;
1335 return Value.fromInterned(try mod.intern(.{
1348 const pt = sema.pt;
1349 const ip = &pt.zcu.intern_pool;
1350 return Value.fromInterned(try pt.intern(.{
13361351 .aggregate = .{
1337 .ty = switch (mod.intern_pool.indexToKey(mod.intern_pool.typeOf(val.toIntern()))) {
1338 .array_type => |array_type| try mod.arrayType(.{
1352 .ty = switch (pt.zcu.intern_pool.indexToKey(pt.zcu.intern_pool.typeOf(val.toIntern()))) {
1353 .array_type => |array_type| try pt.arrayType(.{
13391354 .len = @intCast(end - start),
13401355 .child = array_type.child,
13411356 .sentinel = if (end == array_type.len) array_type.sentinel else .none,
13421357 }),
1343 .vector_type => |vector_type| try mod.vectorType(.{
1358 .vector_type => |vector_type| try pt.vectorType(.{
13441359 .len = @intCast(end - start),
13451360 .child = vector_type.child,
13461361 }),
......@@ -1363,13 +1378,14 @@ pub fn sliceArray(
13631378 }));
13641379}
13651380
1366pub fn fieldValue(val: Value, mod: *Module, index: usize) !Value {
1381pub fn fieldValue(val: Value, pt: Zcu.PerThread, index: usize) !Value {
1382 const mod = pt.zcu;
13671383 return switch (mod.intern_pool.indexToKey(val.toIntern())) {
1368 .undef => |ty| Value.fromInterned((try mod.intern(.{
1384 .undef => |ty| Value.fromInterned(try pt.intern(.{
13691385 .undef = Type.fromInterned(ty).structFieldType(index, mod).toIntern(),
1370 }))),
1386 })),
13711387 .aggregate => |aggregate| Value.fromInterned(switch (aggregate.storage) {
1372 .bytes => |bytes| try mod.intern(.{ .int = .{
1388 .bytes => |bytes| try pt.intern(.{ .int = .{
13731389 .ty = .u8_type,
13741390 .storage = .{ .u64 = bytes.at(index, &mod.intern_pool) },
13751391 } }),
......@@ -1483,40 +1499,49 @@ pub fn floatFromInt(val: Value, arena: Allocator, int_ty: Type, float_ty: Type,
14831499 };
14841500}
14851501
1486pub fn floatFromIntAdvanced(val: Value, arena: Allocator, int_ty: Type, float_ty: Type, mod: *Module, strat: ResolveStrat) !Value {
1502pub fn floatFromIntAdvanced(
1503 val: Value,
1504 arena: Allocator,
1505 int_ty: Type,
1506 float_ty: Type,
1507 pt: Zcu.PerThread,
1508 strat: ResolveStrat,
1509) !Value {
1510 const mod = pt.zcu;
14871511 if (int_ty.zigTypeTag(mod) == .Vector) {
14881512 const result_data = try arena.alloc(InternPool.Index, int_ty.vectorLen(mod));
14891513 const scalar_ty = float_ty.scalarType(mod);
14901514 for (result_data, 0..) |*scalar, i| {
1491 const elem_val = try val.elemValue(mod, i);
1492 scalar.* = (try floatFromIntScalar(elem_val, scalar_ty, mod, strat)).toIntern();
1515 const elem_val = try val.elemValue(pt, i);
1516 scalar.* = (try floatFromIntScalar(elem_val, scalar_ty, pt, strat)).toIntern();
14931517 }
1494 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
1518 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
14951519 .ty = float_ty.toIntern(),
14961520 .storage = .{ .elems = result_data },
1497 } })));
1521 } }));
14981522 }
1499 return floatFromIntScalar(val, float_ty, mod, strat);
1523 return floatFromIntScalar(val, float_ty, pt, strat);
15001524}
15011525
1502pub fn floatFromIntScalar(val: Value, float_ty: Type, mod: *Module, strat: ResolveStrat) !Value {
1526pub fn floatFromIntScalar(val: Value, float_ty: Type, pt: Zcu.PerThread, strat: ResolveStrat) !Value {
1527 const mod = pt.zcu;
15031528 return switch (mod.intern_pool.indexToKey(val.toIntern())) {
1504 .undef => try mod.undefValue(float_ty),
1529 .undef => try pt.undefValue(float_ty),
15051530 .int => |int| switch (int.storage) {
15061531 .big_int => |big_int| {
15071532 const float = bigIntToFloat(big_int.limbs, big_int.positive);
1508 return mod.floatValue(float_ty, float);
1533 return pt.floatValue(float_ty, float);
15091534 },
1510 inline .u64, .i64 => |x| floatFromIntInner(x, float_ty, mod),
1511 .lazy_align => |ty| return floatFromIntInner((try Type.fromInterned(ty).abiAlignmentAdvanced(mod, strat.toLazy())).scalar.toByteUnits() orelse 0, float_ty, mod),
1512 .lazy_size => |ty| return floatFromIntInner((try Type.fromInterned(ty).abiSizeAdvanced(mod, strat.toLazy())).scalar, float_ty, mod),
1535 inline .u64, .i64 => |x| floatFromIntInner(x, float_ty, pt),
1536 .lazy_align => |ty| return floatFromIntInner((try Type.fromInterned(ty).abiAlignmentAdvanced(pt, strat.toLazy())).scalar.toByteUnits() orelse 0, float_ty, pt),
1537 .lazy_size => |ty| return floatFromIntInner((try Type.fromInterned(ty).abiSizeAdvanced(pt, strat.toLazy())).scalar, float_ty, pt),
15131538 },
15141539 else => unreachable,
15151540 };
15161541}
15171542
1518fn floatFromIntInner(x: anytype, dest_ty: Type, mod: *Module) !Value {
1519 const target = mod.getTarget();
1543fn floatFromIntInner(x: anytype, dest_ty: Type, pt: Zcu.PerThread) !Value {
1544 const target = pt.zcu.getTarget();
15201545 const storage: InternPool.Key.Float.Storage = switch (dest_ty.floatBits(target)) {
15211546 16 => .{ .f16 = @floatFromInt(x) },
15221547 32 => .{ .f32 = @floatFromInt(x) },
......@@ -1525,10 +1550,10 @@ fn floatFromIntInner(x: anytype, dest_ty: Type, mod: *Module) !Value {
15251550 128 => .{ .f128 = @floatFromInt(x) },
15261551 else => unreachable,
15271552 };
1528 return Value.fromInterned((try mod.intern(.{ .float = .{
1553 return Value.fromInterned(try pt.intern(.{ .float = .{
15291554 .ty = dest_ty.toIntern(),
15301555 .storage = storage,
1531 } })));
1556 } }));
15321557}
15331558
15341559fn calcLimbLenFloat(scalar: anytype) usize {
......@@ -1551,22 +1576,22 @@ pub fn intAddSat(
15511576 rhs: Value,
15521577 ty: Type,
15531578 arena: Allocator,
1554 mod: *Module,
1579 pt: Zcu.PerThread,
15551580) !Value {
1556 if (ty.zigTypeTag(mod) == .Vector) {
1557 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(mod));
1558 const scalar_ty = ty.scalarType(mod);
1581 if (ty.zigTypeTag(pt.zcu) == .Vector) {
1582 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
1583 const scalar_ty = ty.scalarType(pt.zcu);
15591584 for (result_data, 0..) |*scalar, i| {
1560 const lhs_elem = try lhs.elemValue(mod, i);
1561 const rhs_elem = try rhs.elemValue(mod, i);
1562 scalar.* = (try intAddSatScalar(lhs_elem, rhs_elem, scalar_ty, arena, mod)).toIntern();
1585 const lhs_elem = try lhs.elemValue(pt, i);
1586 const rhs_elem = try rhs.elemValue(pt, i);
1587 scalar.* = (try intAddSatScalar(lhs_elem, rhs_elem, scalar_ty, arena, pt)).toIntern();
15631588 }
1564 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
1589 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
15651590 .ty = ty.toIntern(),
15661591 .storage = .{ .elems = result_data },
1567 } })));
1592 } }));
15681593 }
1569 return intAddSatScalar(lhs, rhs, ty, arena, mod);
1594 return intAddSatScalar(lhs, rhs, ty, arena, pt);
15701595}
15711596
15721597/// Supports integers only; asserts neither operand is undefined.
......@@ -1575,24 +1600,24 @@ pub fn intAddSatScalar(
15751600 rhs: Value,
15761601 ty: Type,
15771602 arena: Allocator,
1578 mod: *Module,
1603 pt: Zcu.PerThread,
15791604) !Value {
1580 assert(!lhs.isUndef(mod));
1581 assert(!rhs.isUndef(mod));
1605 assert(!lhs.isUndef(pt.zcu));
1606 assert(!rhs.isUndef(pt.zcu));
15821607
1583 const info = ty.intInfo(mod);
1608 const info = ty.intInfo(pt.zcu);
15841609
15851610 var lhs_space: Value.BigIntSpace = undefined;
15861611 var rhs_space: Value.BigIntSpace = undefined;
1587 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
1588 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);
1612 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
1613 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
15891614 const limbs = try arena.alloc(
15901615 std.math.big.Limb,
15911616 std.math.big.int.calcTwosCompLimbCount(info.bits),
15921617 );
15931618 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
15941619 result_bigint.addSat(lhs_bigint, rhs_bigint, info.signedness, info.bits);
1595 return mod.intValue_big(ty, result_bigint.toConst());
1620 return pt.intValue_big(ty, result_bigint.toConst());
15961621}
15971622
15981623/// Supports (vectors of) integers only; asserts neither operand is undefined.
......@@ -1601,22 +1626,22 @@ pub fn intSubSat(
16011626 rhs: Value,
16021627 ty: Type,
16031628 arena: Allocator,
1604 mod: *Module,
1629 pt: Zcu.PerThread,
16051630) !Value {
1606 if (ty.zigTypeTag(mod) == .Vector) {
1607 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(mod));
1608 const scalar_ty = ty.scalarType(mod);
1631 if (ty.zigTypeTag(pt.zcu) == .Vector) {
1632 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
1633 const scalar_ty = ty.scalarType(pt.zcu);
16091634 for (result_data, 0..) |*scalar, i| {
1610 const lhs_elem = try lhs.elemValue(mod, i);
1611 const rhs_elem = try rhs.elemValue(mod, i);
1612 scalar.* = (try intSubSatScalar(lhs_elem, rhs_elem, scalar_ty, arena, mod)).toIntern();
1635 const lhs_elem = try lhs.elemValue(pt, i);
1636 const rhs_elem = try rhs.elemValue(pt, i);
1637 scalar.* = (try intSubSatScalar(lhs_elem, rhs_elem, scalar_ty, arena, pt)).toIntern();
16131638 }
1614 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
1639 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
16151640 .ty = ty.toIntern(),
16161641 .storage = .{ .elems = result_data },
1617 } })));
1642 } }));
16181643 }
1619 return intSubSatScalar(lhs, rhs, ty, arena, mod);
1644 return intSubSatScalar(lhs, rhs, ty, arena, pt);
16201645}
16211646
16221647/// Supports integers only; asserts neither operand is undefined.
......@@ -1625,24 +1650,24 @@ pub fn intSubSatScalar(
16251650 rhs: Value,
16261651 ty: Type,
16271652 arena: Allocator,
1628 mod: *Module,
1653 pt: Zcu.PerThread,
16291654) !Value {
1630 assert(!lhs.isUndef(mod));
1631 assert(!rhs.isUndef(mod));
1655 assert(!lhs.isUndef(pt.zcu));
1656 assert(!rhs.isUndef(pt.zcu));
16321657
1633 const info = ty.intInfo(mod);
1658 const info = ty.intInfo(pt.zcu);
16341659
16351660 var lhs_space: Value.BigIntSpace = undefined;
16361661 var rhs_space: Value.BigIntSpace = undefined;
1637 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
1638 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);
1662 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
1663 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
16391664 const limbs = try arena.alloc(
16401665 std.math.big.Limb,
16411666 std.math.big.int.calcTwosCompLimbCount(info.bits),
16421667 );
16431668 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
16441669 result_bigint.subSat(lhs_bigint, rhs_bigint, info.signedness, info.bits);
1645 return mod.intValue_big(ty, result_bigint.toConst());
1670 return pt.intValue_big(ty, result_bigint.toConst());
16461671}
16471672
16481673pub fn intMulWithOverflow(
......@@ -1650,32 +1675,33 @@ pub fn intMulWithOverflow(
16501675 rhs: Value,
16511676 ty: Type,
16521677 arena: Allocator,
1653 mod: *Module,
1678 pt: Zcu.PerThread,
16541679) !OverflowArithmeticResult {
1680 const mod = pt.zcu;
16551681 if (ty.zigTypeTag(mod) == .Vector) {
16561682 const vec_len = ty.vectorLen(mod);
16571683 const overflowed_data = try arena.alloc(InternPool.Index, vec_len);
16581684 const result_data = try arena.alloc(InternPool.Index, vec_len);
16591685 const scalar_ty = ty.scalarType(mod);
16601686 for (overflowed_data, result_data, 0..) |*of, *scalar, i| {
1661 const lhs_elem = try lhs.elemValue(mod, i);
1662 const rhs_elem = try rhs.elemValue(mod, i);
1663 const of_math_result = try intMulWithOverflowScalar(lhs_elem, rhs_elem, scalar_ty, arena, mod);
1687 const lhs_elem = try lhs.elemValue(pt, i);
1688 const rhs_elem = try rhs.elemValue(pt, i);
1689 const of_math_result = try intMulWithOverflowScalar(lhs_elem, rhs_elem, scalar_ty, arena, pt);
16641690 of.* = of_math_result.overflow_bit.toIntern();
16651691 scalar.* = of_math_result.wrapped_result.toIntern();
16661692 }
16671693 return OverflowArithmeticResult{
1668 .overflow_bit = Value.fromInterned((try mod.intern(.{ .aggregate = .{
1669 .ty = (try mod.vectorType(.{ .len = vec_len, .child = .u1_type })).toIntern(),
1694 .overflow_bit = Value.fromInterned(try pt.intern(.{ .aggregate = .{
1695 .ty = (try pt.vectorType(.{ .len = vec_len, .child = .u1_type })).toIntern(),
16701696 .storage = .{ .elems = overflowed_data },
1671 } }))),
1672 .wrapped_result = Value.fromInterned((try mod.intern(.{ .aggregate = .{
1697 } })),
1698 .wrapped_result = Value.fromInterned(try pt.intern(.{ .aggregate = .{
16731699 .ty = ty.toIntern(),
16741700 .storage = .{ .elems = result_data },
1675 } }))),
1701 } })),
16761702 };
16771703 }
1678 return intMulWithOverflowScalar(lhs, rhs, ty, arena, mod);
1704 return intMulWithOverflowScalar(lhs, rhs, ty, arena, pt);
16791705}
16801706
16811707pub fn intMulWithOverflowScalar(
......@@ -1683,21 +1709,22 @@ pub fn intMulWithOverflowScalar(
16831709 rhs: Value,
16841710 ty: Type,
16851711 arena: Allocator,
1686 mod: *Module,
1712 pt: Zcu.PerThread,
16871713) !OverflowArithmeticResult {
1714 const mod = pt.zcu;
16881715 const info = ty.intInfo(mod);
16891716
16901717 if (lhs.isUndef(mod) or rhs.isUndef(mod)) {
16911718 return .{
1692 .overflow_bit = try mod.undefValue(Type.u1),
1693 .wrapped_result = try mod.undefValue(ty),
1719 .overflow_bit = try pt.undefValue(Type.u1),
1720 .wrapped_result = try pt.undefValue(ty),
16941721 };
16951722 }
16961723
16971724 var lhs_space: Value.BigIntSpace = undefined;
16981725 var rhs_space: Value.BigIntSpace = undefined;
1699 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
1700 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);
1726 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
1727 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
17011728 const limbs = try arena.alloc(
17021729 std.math.big.Limb,
17031730 lhs_bigint.limbs.len + rhs_bigint.limbs.len,
......@@ -1715,8 +1742,8 @@ pub fn intMulWithOverflowScalar(
17151742 }
17161743
17171744 return OverflowArithmeticResult{
1718 .overflow_bit = try mod.intValue(Type.u1, @intFromBool(overflowed)),
1719 .wrapped_result = try mod.intValue_big(ty, result_bigint.toConst()),
1745 .overflow_bit = try pt.intValue(Type.u1, @intFromBool(overflowed)),
1746 .wrapped_result = try pt.intValue_big(ty, result_bigint.toConst()),
17201747 };
17211748}
17221749
......@@ -1726,22 +1753,23 @@ pub fn numberMulWrap(
17261753 rhs: Value,
17271754 ty: Type,
17281755 arena: Allocator,
1729 mod: *Module,
1756 pt: Zcu.PerThread,
17301757) !Value {
1758 const mod = pt.zcu;
17311759 if (ty.zigTypeTag(mod) == .Vector) {
17321760 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(mod));
17331761 const scalar_ty = ty.scalarType(mod);
17341762 for (result_data, 0..) |*scalar, i| {
1735 const lhs_elem = try lhs.elemValue(mod, i);
1736 const rhs_elem = try rhs.elemValue(mod, i);
1737 scalar.* = (try numberMulWrapScalar(lhs_elem, rhs_elem, scalar_ty, arena, mod)).toIntern();
1763 const lhs_elem = try lhs.elemValue(pt, i);
1764 const rhs_elem = try rhs.elemValue(pt, i);
1765 scalar.* = (try numberMulWrapScalar(lhs_elem, rhs_elem, scalar_ty, arena, pt)).toIntern();
17381766 }
1739 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
1767 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
17401768 .ty = ty.toIntern(),
17411769 .storage = .{ .elems = result_data },
1742 } })));
1770 } }));
17431771 }
1744 return numberMulWrapScalar(lhs, rhs, ty, arena, mod);
1772 return numberMulWrapScalar(lhs, rhs, ty, arena, pt);
17451773}
17461774
17471775/// Supports both floats and ints; handles undefined.
......@@ -1750,19 +1778,20 @@ pub fn numberMulWrapScalar(
17501778 rhs: Value,
17511779 ty: Type,
17521780 arena: Allocator,
1753 mod: *Module,
1781 pt: Zcu.PerThread,
17541782) !Value {
1783 const mod = pt.zcu;
17551784 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return Value.undef;
17561785
17571786 if (ty.zigTypeTag(mod) == .ComptimeInt) {
1758 return intMul(lhs, rhs, ty, undefined, arena, mod);
1787 return intMul(lhs, rhs, ty, undefined, arena, pt);
17591788 }
17601789
17611790 if (ty.isAnyFloat()) {
1762 return floatMul(lhs, rhs, ty, arena, mod);
1791 return floatMul(lhs, rhs, ty, arena, pt);
17631792 }
17641793
1765 const overflow_result = try intMulWithOverflow(lhs, rhs, ty, arena, mod);
1794 const overflow_result = try intMulWithOverflow(lhs, rhs, ty, arena, pt);
17661795 return overflow_result.wrapped_result;
17671796}
17681797
......@@ -1772,22 +1801,22 @@ pub fn intMulSat(
17721801 rhs: Value,
17731802 ty: Type,
17741803 arena: Allocator,
1775 mod: *Module,
1804 pt: Zcu.PerThread,
17761805) !Value {
1777 if (ty.zigTypeTag(mod) == .Vector) {
1778 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(mod));
1779 const scalar_ty = ty.scalarType(mod);
1806 if (ty.zigTypeTag(pt.zcu) == .Vector) {
1807 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
1808 const scalar_ty = ty.scalarType(pt.zcu);
17801809 for (result_data, 0..) |*scalar, i| {
1781 const lhs_elem = try lhs.elemValue(mod, i);
1782 const rhs_elem = try rhs.elemValue(mod, i);
1783 scalar.* = (try intMulSatScalar(lhs_elem, rhs_elem, scalar_ty, arena, mod)).toIntern();
1810 const lhs_elem = try lhs.elemValue(pt, i);
1811 const rhs_elem = try rhs.elemValue(pt, i);
1812 scalar.* = (try intMulSatScalar(lhs_elem, rhs_elem, scalar_ty, arena, pt)).toIntern();
17841813 }
1785 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
1814 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
17861815 .ty = ty.toIntern(),
17871816 .storage = .{ .elems = result_data },
1788 } })));
1817 } }));
17891818 }
1790 return intMulSatScalar(lhs, rhs, ty, arena, mod);
1819 return intMulSatScalar(lhs, rhs, ty, arena, pt);
17911820}
17921821
17931822/// Supports (vectors of) integers only; asserts neither operand is undefined.
......@@ -1796,17 +1825,17 @@ pub fn intMulSatScalar(
17961825 rhs: Value,
17971826 ty: Type,
17981827 arena: Allocator,
1799 mod: *Module,
1828 pt: Zcu.PerThread,
18001829) !Value {
1801 assert(!lhs.isUndef(mod));
1802 assert(!rhs.isUndef(mod));
1830 assert(!lhs.isUndef(pt.zcu));
1831 assert(!rhs.isUndef(pt.zcu));
18031832
1804 const info = ty.intInfo(mod);
1833 const info = ty.intInfo(pt.zcu);
18051834
18061835 var lhs_space: Value.BigIntSpace = undefined;
18071836 var rhs_space: Value.BigIntSpace = undefined;
1808 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
1809 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);
1837 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
1838 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
18101839 const limbs = try arena.alloc(
18111840 std.math.big.Limb,
18121841 @max(
......@@ -1822,53 +1851,55 @@ pub fn intMulSatScalar(
18221851 );
18231852 result_bigint.mul(lhs_bigint, rhs_bigint, limbs_buffer, arena);
18241853 result_bigint.saturate(result_bigint.toConst(), info.signedness, info.bits);
1825 return mod.intValue_big(ty, result_bigint.toConst());
1854 return pt.intValue_big(ty, result_bigint.toConst());
18261855}
18271856
18281857/// Supports both floats and ints; handles undefined.
1829pub fn numberMax(lhs: Value, rhs: Value, mod: *Module) Value {
1830 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return undef;
1831 if (lhs.isNan(mod)) return rhs;
1832 if (rhs.isNan(mod)) return lhs;
1858pub fn numberMax(lhs: Value, rhs: Value, pt: Zcu.PerThread) Value {
1859 if (lhs.isUndef(pt.zcu) or rhs.isUndef(pt.zcu)) return undef;
1860 if (lhs.isNan(pt.zcu)) return rhs;
1861 if (rhs.isNan(pt.zcu)) return lhs;
18331862
1834 return switch (order(lhs, rhs, mod)) {
1863 return switch (order(lhs, rhs, pt)) {
18351864 .lt => rhs,
18361865 .gt, .eq => lhs,
18371866 };
18381867}
18391868
18401869/// Supports both floats and ints; handles undefined.
1841pub fn numberMin(lhs: Value, rhs: Value, mod: *Module) Value {
1842 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return undef;
1843 if (lhs.isNan(mod)) return rhs;
1844 if (rhs.isNan(mod)) return lhs;
1870pub fn numberMin(lhs: Value, rhs: Value, pt: Zcu.PerThread) Value {
1871 if (lhs.isUndef(pt.zcu) or rhs.isUndef(pt.zcu)) return undef;
1872 if (lhs.isNan(pt.zcu)) return rhs;
1873 if (rhs.isNan(pt.zcu)) return lhs;
18451874
1846 return switch (order(lhs, rhs, mod)) {
1875 return switch (order(lhs, rhs, pt)) {
18471876 .lt => lhs,
18481877 .gt, .eq => rhs,
18491878 };
18501879}
18511880
18521881/// operands must be (vectors of) integers; handles undefined scalars.
1853pub fn bitwiseNot(val: Value, ty: Type, arena: Allocator, mod: *Module) !Value {
1882pub fn bitwiseNot(val: Value, ty: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
1883 const mod = pt.zcu;
18541884 if (ty.zigTypeTag(mod) == .Vector) {
18551885 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(mod));
18561886 const scalar_ty = ty.scalarType(mod);
18571887 for (result_data, 0..) |*scalar, i| {
1858 const elem_val = try val.elemValue(mod, i);
1859 scalar.* = (try bitwiseNotScalar(elem_val, scalar_ty, arena, mod)).toIntern();
1888 const elem_val = try val.elemValue(pt, i);
1889 scalar.* = (try bitwiseNotScalar(elem_val, scalar_ty, arena, pt)).toIntern();
18601890 }
1861 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
1891 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
18621892 .ty = ty.toIntern(),
18631893 .storage = .{ .elems = result_data },
1864 } })));
1894 } }));
18651895 }
1866 return bitwiseNotScalar(val, ty, arena, mod);
1896 return bitwiseNotScalar(val, ty, arena, pt);
18671897}
18681898
18691899/// operands must be integers; handles undefined.
1870pub fn bitwiseNotScalar(val: Value, ty: Type, arena: Allocator, mod: *Module) !Value {
1871 if (val.isUndef(mod)) return Value.fromInterned((try mod.intern(.{ .undef = ty.toIntern() })));
1900pub fn bitwiseNotScalar(val: Value, ty: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
1901 const mod = pt.zcu;
1902 if (val.isUndef(mod)) return Value.fromInterned(try pt.intern(.{ .undef = ty.toIntern() }));
18721903 if (ty.toIntern() == .bool_type) return makeBool(!val.toBool());
18731904
18741905 const info = ty.intInfo(mod);
......@@ -1880,7 +1911,7 @@ pub fn bitwiseNotScalar(val: Value, ty: Type, arena: Allocator, mod: *Module) !V
18801911 // TODO is this a performance issue? maybe we should try the operation without
18811912 // resorting to BigInt first.
18821913 var val_space: Value.BigIntSpace = undefined;
1883 const val_bigint = val.toBigInt(&val_space, mod);
1914 const val_bigint = val.toBigInt(&val_space, pt);
18841915 const limbs = try arena.alloc(
18851916 std.math.big.Limb,
18861917 std.math.big.int.calcTwosCompLimbCount(info.bits),
......@@ -1888,29 +1919,31 @@ pub fn bitwiseNotScalar(val: Value, ty: Type, arena: Allocator, mod: *Module) !V
18881919
18891920 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
18901921 result_bigint.bitNotWrap(val_bigint, info.signedness, info.bits);
1891 return mod.intValue_big(ty, result_bigint.toConst());
1922 return pt.intValue_big(ty, result_bigint.toConst());
18921923}
18931924
18941925/// operands must be (vectors of) integers; handles undefined scalars.
1895pub fn bitwiseAnd(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
1926pub fn bitwiseAnd(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
1927 const mod = pt.zcu;
18961928 if (ty.zigTypeTag(mod) == .Vector) {
18971929 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
18981930 const scalar_ty = ty.scalarType(mod);
18991931 for (result_data, 0..) |*scalar, i| {
1900 const lhs_elem = try lhs.elemValue(mod, i);
1901 const rhs_elem = try rhs.elemValue(mod, i);
1902 scalar.* = (try bitwiseAndScalar(lhs_elem, rhs_elem, scalar_ty, allocator, mod)).toIntern();
1932 const lhs_elem = try lhs.elemValue(pt, i);
1933 const rhs_elem = try rhs.elemValue(pt, i);
1934 scalar.* = (try bitwiseAndScalar(lhs_elem, rhs_elem, scalar_ty, allocator, pt)).toIntern();
19031935 }
1904 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
1936 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
19051937 .ty = ty.toIntern(),
19061938 .storage = .{ .elems = result_data },
1907 } })));
1939 } }));
19081940 }
1909 return bitwiseAndScalar(lhs, rhs, ty, allocator, mod);
1941 return bitwiseAndScalar(lhs, rhs, ty, allocator, pt);
19101942}
19111943
19121944/// operands must be integers; handles undefined.
1913pub fn bitwiseAndScalar(orig_lhs: Value, orig_rhs: Value, ty: Type, arena: Allocator, zcu: *Zcu) !Value {
1945pub fn bitwiseAndScalar(orig_lhs: Value, orig_rhs: Value, ty: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
1946 const zcu = pt.zcu;
19141947 // If one operand is defined, we turn the other into `0xAA` so the bitwise AND can
19151948 // still zero out some bits.
19161949 // TODO: ideally we'd still like tracking for the undef bits. Related: #19634.
......@@ -1919,9 +1952,9 @@ pub fn bitwiseAndScalar(orig_lhs: Value, orig_rhs: Value, ty: Type, arena: Alloc
19191952 const rhs_undef = orig_rhs.isUndef(zcu);
19201953 break :make_defined switch ((@as(u2, @intFromBool(lhs_undef)) << 1) | @intFromBool(rhs_undef)) {
19211954 0b00 => .{ orig_lhs, orig_rhs },
1922 0b01 => .{ orig_lhs, try intValueAa(ty, arena, zcu) },
1923 0b10 => .{ try intValueAa(ty, arena, zcu), orig_rhs },
1924 0b11 => return zcu.undefValue(ty),
1955 0b01 => .{ orig_lhs, try intValueAa(ty, arena, pt) },
1956 0b10 => .{ try intValueAa(ty, arena, pt), orig_rhs },
1957 0b11 => return pt.undefValue(ty),
19251958 };
19261959 };
19271960
......@@ -1931,8 +1964,8 @@ pub fn bitwiseAndScalar(orig_lhs: Value, orig_rhs: Value, ty: Type, arena: Alloc
19311964 // resorting to BigInt first.
19321965 var lhs_space: Value.BigIntSpace = undefined;
19331966 var rhs_space: Value.BigIntSpace = undefined;
1934 const lhs_bigint = lhs.toBigInt(&lhs_space, zcu);
1935 const rhs_bigint = rhs.toBigInt(&rhs_space, zcu);
1967 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
1968 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
19361969 const limbs = try arena.alloc(
19371970 std.math.big.Limb,
19381971 // + 1 for negatives
......@@ -1940,12 +1973,13 @@ pub fn bitwiseAndScalar(orig_lhs: Value, orig_rhs: Value, ty: Type, arena: Alloc
19401973 );
19411974 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
19421975 result_bigint.bitAnd(lhs_bigint, rhs_bigint);
1943 return zcu.intValue_big(ty, result_bigint.toConst());
1976 return pt.intValue_big(ty, result_bigint.toConst());
19441977}
19451978
19461979/// Given an integer or boolean type, creates an value of that with the bit pattern 0xAA.
19471980/// This is used to convert undef values into 0xAA when performing e.g. bitwise operations.
1948fn intValueAa(ty: Type, arena: Allocator, zcu: *Zcu) !Value {
1981fn intValueAa(ty: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
1982 const zcu = pt.zcu;
19491983 if (ty.toIntern() == .bool_type) return Value.true;
19501984 const info = ty.intInfo(zcu);
19511985
......@@ -1958,68 +1992,71 @@ fn intValueAa(ty: Type, arena: Allocator, zcu: *Zcu) !Value {
19581992 );
19591993 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
19601994 result_bigint.readTwosComplement(buf, info.bits, zcu.getTarget().cpu.arch.endian(), info.signedness);
1961 return zcu.intValue_big(ty, result_bigint.toConst());
1995 return pt.intValue_big(ty, result_bigint.toConst());
19621996}
19631997
19641998/// operands must be (vectors of) integers; handles undefined scalars.
1965pub fn bitwiseNand(lhs: Value, rhs: Value, ty: Type, arena: Allocator, mod: *Module) !Value {
1999pub fn bitwiseNand(lhs: Value, rhs: Value, ty: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
2000 const mod = pt.zcu;
19662001 if (ty.zigTypeTag(mod) == .Vector) {
19672002 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(mod));
19682003 const scalar_ty = ty.scalarType(mod);
19692004 for (result_data, 0..) |*scalar, i| {
1970 const lhs_elem = try lhs.elemValue(mod, i);
1971 const rhs_elem = try rhs.elemValue(mod, i);
1972 scalar.* = (try bitwiseNandScalar(lhs_elem, rhs_elem, scalar_ty, arena, mod)).toIntern();
2005 const lhs_elem = try lhs.elemValue(pt, i);
2006 const rhs_elem = try rhs.elemValue(pt, i);
2007 scalar.* = (try bitwiseNandScalar(lhs_elem, rhs_elem, scalar_ty, arena, pt)).toIntern();
19732008 }
1974 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2009 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
19752010 .ty = ty.toIntern(),
19762011 .storage = .{ .elems = result_data },
1977 } })));
2012 } }));
19782013 }
1979 return bitwiseNandScalar(lhs, rhs, ty, arena, mod);
2014 return bitwiseNandScalar(lhs, rhs, ty, arena, pt);
19802015}
19812016
19822017/// operands must be integers; handles undefined.
1983pub fn bitwiseNandScalar(lhs: Value, rhs: Value, ty: Type, arena: Allocator, mod: *Module) !Value {
1984 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return Value.fromInterned((try mod.intern(.{ .undef = ty.toIntern() })));
2018pub fn bitwiseNandScalar(lhs: Value, rhs: Value, ty: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
2019 const mod = pt.zcu;
2020 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return Value.fromInterned(try pt.intern(.{ .undef = ty.toIntern() }));
19852021 if (ty.toIntern() == .bool_type) return makeBool(!(lhs.toBool() and rhs.toBool()));
19862022
1987 const anded = try bitwiseAnd(lhs, rhs, ty, arena, mod);
1988 const all_ones = if (ty.isSignedInt(mod)) try mod.intValue(ty, -1) else try ty.maxIntScalar(mod, ty);
1989 return bitwiseXor(anded, all_ones, ty, arena, mod);
2023 const anded = try bitwiseAnd(lhs, rhs, ty, arena, pt);
2024 const all_ones = if (ty.isSignedInt(mod)) try pt.intValue(ty, -1) else try ty.maxIntScalar(pt, ty);
2025 return bitwiseXor(anded, all_ones, ty, arena, pt);
19902026}
19912027
19922028/// operands must be (vectors of) integers; handles undefined scalars.
1993pub fn bitwiseOr(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2029pub fn bitwiseOr(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
2030 const mod = pt.zcu;
19942031 if (ty.zigTypeTag(mod) == .Vector) {
19952032 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
19962033 const scalar_ty = ty.scalarType(mod);
19972034 for (result_data, 0..) |*scalar, i| {
1998 const lhs_elem = try lhs.elemValue(mod, i);
1999 const rhs_elem = try rhs.elemValue(mod, i);
2000 scalar.* = (try bitwiseOrScalar(lhs_elem, rhs_elem, scalar_ty, allocator, mod)).toIntern();
2035 const lhs_elem = try lhs.elemValue(pt, i);
2036 const rhs_elem = try rhs.elemValue(pt, i);
2037 scalar.* = (try bitwiseOrScalar(lhs_elem, rhs_elem, scalar_ty, allocator, pt)).toIntern();
20012038 }
2002 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2039 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
20032040 .ty = ty.toIntern(),
20042041 .storage = .{ .elems = result_data },
2005 } })));
2042 } }));
20062043 }
2007 return bitwiseOrScalar(lhs, rhs, ty, allocator, mod);
2044 return bitwiseOrScalar(lhs, rhs, ty, allocator, pt);
20082045}
20092046
20102047/// operands must be integers; handles undefined.
2011pub fn bitwiseOrScalar(orig_lhs: Value, orig_rhs: Value, ty: Type, arena: Allocator, zcu: *Zcu) !Value {
2048pub fn bitwiseOrScalar(orig_lhs: Value, orig_rhs: Value, ty: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
20122049 // If one operand is defined, we turn the other into `0xAA` so the bitwise AND can
20132050 // still zero out some bits.
20142051 // TODO: ideally we'd still like tracking for the undef bits. Related: #19634.
20152052 const lhs: Value, const rhs: Value = make_defined: {
2016 const lhs_undef = orig_lhs.isUndef(zcu);
2017 const rhs_undef = orig_rhs.isUndef(zcu);
2053 const lhs_undef = orig_lhs.isUndef(pt.zcu);
2054 const rhs_undef = orig_rhs.isUndef(pt.zcu);
20182055 break :make_defined switch ((@as(u2, @intFromBool(lhs_undef)) << 1) | @intFromBool(rhs_undef)) {
20192056 0b00 => .{ orig_lhs, orig_rhs },
2020 0b01 => .{ orig_lhs, try intValueAa(ty, arena, zcu) },
2021 0b10 => .{ try intValueAa(ty, arena, zcu), orig_rhs },
2022 0b11 => return zcu.undefValue(ty),
2057 0b01 => .{ orig_lhs, try intValueAa(ty, arena, pt) },
2058 0b10 => .{ try intValueAa(ty, arena, pt), orig_rhs },
2059 0b11 => return pt.undefValue(ty),
20232060 };
20242061 };
20252062
......@@ -2029,46 +2066,48 @@ pub fn bitwiseOrScalar(orig_lhs: Value, orig_rhs: Value, ty: Type, arena: Alloca
20292066 // resorting to BigInt first.
20302067 var lhs_space: Value.BigIntSpace = undefined;
20312068 var rhs_space: Value.BigIntSpace = undefined;
2032 const lhs_bigint = lhs.toBigInt(&lhs_space, zcu);
2033 const rhs_bigint = rhs.toBigInt(&rhs_space, zcu);
2069 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
2070 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
20342071 const limbs = try arena.alloc(
20352072 std.math.big.Limb,
20362073 @max(lhs_bigint.limbs.len, rhs_bigint.limbs.len),
20372074 );
20382075 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
20392076 result_bigint.bitOr(lhs_bigint, rhs_bigint);
2040 return zcu.intValue_big(ty, result_bigint.toConst());
2077 return pt.intValue_big(ty, result_bigint.toConst());
20412078}
20422079
20432080/// operands must be (vectors of) integers; handles undefined scalars.
2044pub fn bitwiseXor(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2081pub fn bitwiseXor(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
2082 const mod = pt.zcu;
20452083 if (ty.zigTypeTag(mod) == .Vector) {
20462084 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
20472085 const scalar_ty = ty.scalarType(mod);
20482086 for (result_data, 0..) |*scalar, i| {
2049 const lhs_elem = try lhs.elemValue(mod, i);
2050 const rhs_elem = try rhs.elemValue(mod, i);
2051 scalar.* = (try bitwiseXorScalar(lhs_elem, rhs_elem, scalar_ty, allocator, mod)).toIntern();
2087 const lhs_elem = try lhs.elemValue(pt, i);
2088 const rhs_elem = try rhs.elemValue(pt, i);
2089 scalar.* = (try bitwiseXorScalar(lhs_elem, rhs_elem, scalar_ty, allocator, pt)).toIntern();
20522090 }
2053 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2091 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
20542092 .ty = ty.toIntern(),
20552093 .storage = .{ .elems = result_data },
2056 } })));
2094 } }));
20572095 }
2058 return bitwiseXorScalar(lhs, rhs, ty, allocator, mod);
2096 return bitwiseXorScalar(lhs, rhs, ty, allocator, pt);
20592097}
20602098
20612099/// operands must be integers; handles undefined.
2062pub fn bitwiseXorScalar(lhs: Value, rhs: Value, ty: Type, arena: Allocator, mod: *Module) !Value {
2063 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return Value.fromInterned((try mod.intern(.{ .undef = ty.toIntern() })));
2100pub fn bitwiseXorScalar(lhs: Value, rhs: Value, ty: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
2101 const mod = pt.zcu;
2102 if (lhs.isUndef(mod) or rhs.isUndef(mod)) return Value.fromInterned(try pt.intern(.{ .undef = ty.toIntern() }));
20642103 if (ty.toIntern() == .bool_type) return makeBool(lhs.toBool() != rhs.toBool());
20652104
20662105 // TODO is this a performance issue? maybe we should try the operation without
20672106 // resorting to BigInt first.
20682107 var lhs_space: Value.BigIntSpace = undefined;
20692108 var rhs_space: Value.BigIntSpace = undefined;
2070 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
2071 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);
2109 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
2110 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
20722111 const limbs = try arena.alloc(
20732112 std.math.big.Limb,
20742113 // + 1 for negatives
......@@ -2076,22 +2115,22 @@ pub fn bitwiseXorScalar(lhs: Value, rhs: Value, ty: Type, arena: Allocator, mod:
20762115 );
20772116 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
20782117 result_bigint.bitXor(lhs_bigint, rhs_bigint);
2079 return mod.intValue_big(ty, result_bigint.toConst());
2118 return pt.intValue_big(ty, result_bigint.toConst());
20802119}
20812120
20822121/// If the value overflowed the type, returns a comptime_int (or vector thereof) instead, setting
20832122/// overflow_idx to the vector index the overflow was at (or 0 for a scalar).
2084pub fn intDiv(lhs: Value, rhs: Value, ty: Type, overflow_idx: *?usize, allocator: Allocator, mod: *Module) !Value {
2123pub fn intDiv(lhs: Value, rhs: Value, ty: Type, overflow_idx: *?usize, allocator: Allocator, pt: Zcu.PerThread) !Value {
20852124 var overflow: usize = undefined;
2086 return intDivInner(lhs, rhs, ty, &overflow, allocator, mod) catch |err| switch (err) {
2125 return intDivInner(lhs, rhs, ty, &overflow, allocator, pt) catch |err| switch (err) {
20872126 error.Overflow => {
2088 const is_vec = ty.isVector(mod);
2127 const is_vec = ty.isVector(pt.zcu);
20892128 overflow_idx.* = if (is_vec) overflow else 0;
2090 const safe_ty = if (is_vec) try mod.vectorType(.{
2091 .len = ty.vectorLen(mod),
2129 const safe_ty = if (is_vec) try pt.vectorType(.{
2130 .len = ty.vectorLen(pt.zcu),
20922131 .child = .comptime_int_type,
20932132 }) else Type.comptime_int;
2094 return intDivInner(lhs, rhs, safe_ty, undefined, allocator, mod) catch |err1| switch (err1) {
2133 return intDivInner(lhs, rhs, safe_ty, undefined, allocator, pt) catch |err1| switch (err1) {
20952134 error.Overflow => unreachable,
20962135 else => |e| return e,
20972136 };
......@@ -2100,14 +2139,14 @@ pub fn intDiv(lhs: Value, rhs: Value, ty: Type, overflow_idx: *?usize, allocator
21002139 };
21012140}
21022141
2103fn intDivInner(lhs: Value, rhs: Value, ty: Type, overflow_idx: *usize, allocator: Allocator, mod: *Module) !Value {
2104 if (ty.zigTypeTag(mod) == .Vector) {
2105 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
2106 const scalar_ty = ty.scalarType(mod);
2142fn intDivInner(lhs: Value, rhs: Value, ty: Type, overflow_idx: *usize, allocator: Allocator, pt: Zcu.PerThread) !Value {
2143 if (ty.zigTypeTag(pt.zcu) == .Vector) {
2144 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
2145 const scalar_ty = ty.scalarType(pt.zcu);
21072146 for (result_data, 0..) |*scalar, i| {
2108 const lhs_elem = try lhs.elemValue(mod, i);
2109 const rhs_elem = try rhs.elemValue(mod, i);
2110 const val = intDivScalar(lhs_elem, rhs_elem, scalar_ty, allocator, mod) catch |err| switch (err) {
2147 const lhs_elem = try lhs.elemValue(pt, i);
2148 const rhs_elem = try rhs.elemValue(pt, i);
2149 const val = intDivScalar(lhs_elem, rhs_elem, scalar_ty, allocator, pt) catch |err| switch (err) {
21112150 error.Overflow => {
21122151 overflow_idx.* = i;
21132152 return error.Overflow;
......@@ -2116,21 +2155,21 @@ fn intDivInner(lhs: Value, rhs: Value, ty: Type, overflow_idx: *usize, allocator
21162155 };
21172156 scalar.* = val.toIntern();
21182157 }
2119 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2158 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
21202159 .ty = ty.toIntern(),
21212160 .storage = .{ .elems = result_data },
2122 } })));
2161 } }));
21232162 }
2124 return intDivScalar(lhs, rhs, ty, allocator, mod);
2163 return intDivScalar(lhs, rhs, ty, allocator, pt);
21252164}
21262165
2127pub fn intDivScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2166pub fn intDivScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
21282167 // TODO is this a performance issue? maybe we should try the operation without
21292168 // resorting to BigInt first.
21302169 var lhs_space: Value.BigIntSpace = undefined;
21312170 var rhs_space: Value.BigIntSpace = undefined;
2132 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
2133 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);
2171 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
2172 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
21342173 const limbs_q = try allocator.alloc(
21352174 std.math.big.Limb,
21362175 lhs_bigint.limbs.len,
......@@ -2147,38 +2186,38 @@ pub fn intDivScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod:
21472186 var result_r = BigIntMutable{ .limbs = limbs_r, .positive = undefined, .len = undefined };
21482187 result_q.divTrunc(&result_r, lhs_bigint, rhs_bigint, limbs_buffer);
21492188 if (ty.toIntern() != .comptime_int_type) {
2150 const info = ty.intInfo(mod);
2189 const info = ty.intInfo(pt.zcu);
21512190 if (!result_q.toConst().fitsInTwosComp(info.signedness, info.bits)) {
21522191 return error.Overflow;
21532192 }
21542193 }
2155 return mod.intValue_big(ty, result_q.toConst());
2194 return pt.intValue_big(ty, result_q.toConst());
21562195}
21572196
2158pub fn intDivFloor(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2159 if (ty.zigTypeTag(mod) == .Vector) {
2160 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
2161 const scalar_ty = ty.scalarType(mod);
2197pub fn intDivFloor(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
2198 if (ty.zigTypeTag(pt.zcu) == .Vector) {
2199 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
2200 const scalar_ty = ty.scalarType(pt.zcu);
21622201 for (result_data, 0..) |*scalar, i| {
2163 const lhs_elem = try lhs.elemValue(mod, i);
2164 const rhs_elem = try rhs.elemValue(mod, i);
2165 scalar.* = (try intDivFloorScalar(lhs_elem, rhs_elem, scalar_ty, allocator, mod)).toIntern();
2202 const lhs_elem = try lhs.elemValue(pt, i);
2203 const rhs_elem = try rhs.elemValue(pt, i);
2204 scalar.* = (try intDivFloorScalar(lhs_elem, rhs_elem, scalar_ty, allocator, pt)).toIntern();
21662205 }
2167 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2206 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
21682207 .ty = ty.toIntern(),
21692208 .storage = .{ .elems = result_data },
2170 } })));
2209 } }));
21712210 }
2172 return intDivFloorScalar(lhs, rhs, ty, allocator, mod);
2211 return intDivFloorScalar(lhs, rhs, ty, allocator, pt);
21732212}
21742213
2175pub fn intDivFloorScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2214pub fn intDivFloorScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
21762215 // TODO is this a performance issue? maybe we should try the operation without
21772216 // resorting to BigInt first.
21782217 var lhs_space: Value.BigIntSpace = undefined;
21792218 var rhs_space: Value.BigIntSpace = undefined;
2180 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
2181 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);
2219 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
2220 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
21822221 const limbs_q = try allocator.alloc(
21832222 std.math.big.Limb,
21842223 lhs_bigint.limbs.len,
......@@ -2194,33 +2233,33 @@ pub fn intDivFloorScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator,
21942233 var result_q = BigIntMutable{ .limbs = limbs_q, .positive = undefined, .len = undefined };
21952234 var result_r = BigIntMutable{ .limbs = limbs_r, .positive = undefined, .len = undefined };
21962235 result_q.divFloor(&result_r, lhs_bigint, rhs_bigint, limbs_buffer);
2197 return mod.intValue_big(ty, result_q.toConst());
2236 return pt.intValue_big(ty, result_q.toConst());
21982237}
21992238
2200pub fn intMod(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2201 if (ty.zigTypeTag(mod) == .Vector) {
2202 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
2203 const scalar_ty = ty.scalarType(mod);
2239pub fn intMod(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
2240 if (ty.zigTypeTag(pt.zcu) == .Vector) {
2241 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
2242 const scalar_ty = ty.scalarType(pt.zcu);
22042243 for (result_data, 0..) |*scalar, i| {
2205 const lhs_elem = try lhs.elemValue(mod, i);
2206 const rhs_elem = try rhs.elemValue(mod, i);
2207 scalar.* = (try intModScalar(lhs_elem, rhs_elem, scalar_ty, allocator, mod)).toIntern();
2244 const lhs_elem = try lhs.elemValue(pt, i);
2245 const rhs_elem = try rhs.elemValue(pt, i);
2246 scalar.* = (try intModScalar(lhs_elem, rhs_elem, scalar_ty, allocator, pt)).toIntern();
22082247 }
2209 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2248 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
22102249 .ty = ty.toIntern(),
22112250 .storage = .{ .elems = result_data },
2212 } })));
2251 } }));
22132252 }
2214 return intModScalar(lhs, rhs, ty, allocator, mod);
2253 return intModScalar(lhs, rhs, ty, allocator, pt);
22152254}
22162255
2217pub fn intModScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2256pub fn intModScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
22182257 // TODO is this a performance issue? maybe we should try the operation without
22192258 // resorting to BigInt first.
22202259 var lhs_space: Value.BigIntSpace = undefined;
22212260 var rhs_space: Value.BigIntSpace = undefined;
2222 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
2223 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);
2261 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
2262 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
22242263 const limbs_q = try allocator.alloc(
22252264 std.math.big.Limb,
22262265 lhs_bigint.limbs.len,
......@@ -2236,7 +2275,7 @@ pub fn intModScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod:
22362275 var result_q = BigIntMutable{ .limbs = limbs_q, .positive = undefined, .len = undefined };
22372276 var result_r = BigIntMutable{ .limbs = limbs_r, .positive = undefined, .len = undefined };
22382277 result_q.divFloor(&result_r, lhs_bigint, rhs_bigint, limbs_buffer);
2239 return mod.intValue_big(ty, result_r.toConst());
2278 return pt.intValue_big(ty, result_r.toConst());
22402279}
22412280
22422281/// Returns true if the value is a floating point type and is NaN. Returns false otherwise.
......@@ -2268,85 +2307,86 @@ pub fn isNegativeInf(val: Value, mod: *const Module) bool {
22682307 };
22692308}
22702309
2271pub fn floatRem(lhs: Value, rhs: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
2272 if (float_type.zigTypeTag(mod) == .Vector) {
2273 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
2274 const scalar_ty = float_type.scalarType(mod);
2310pub fn floatRem(lhs: Value, rhs: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
2311 if (float_type.zigTypeTag(pt.zcu) == .Vector) {
2312 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(pt.zcu));
2313 const scalar_ty = float_type.scalarType(pt.zcu);
22752314 for (result_data, 0..) |*scalar, i| {
2276 const lhs_elem = try lhs.elemValue(mod, i);
2277 const rhs_elem = try rhs.elemValue(mod, i);
2278 scalar.* = (try floatRemScalar(lhs_elem, rhs_elem, scalar_ty, mod)).toIntern();
2315 const lhs_elem = try lhs.elemValue(pt, i);
2316 const rhs_elem = try rhs.elemValue(pt, i);
2317 scalar.* = (try floatRemScalar(lhs_elem, rhs_elem, scalar_ty, pt)).toIntern();
22792318 }
2280 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2319 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
22812320 .ty = float_type.toIntern(),
22822321 .storage = .{ .elems = result_data },
2283 } })));
2322 } }));
22842323 }
2285 return floatRemScalar(lhs, rhs, float_type, mod);
2324 return floatRemScalar(lhs, rhs, float_type, pt);
22862325}
22872326
2288pub fn floatRemScalar(lhs: Value, rhs: Value, float_type: Type, mod: *Module) !Value {
2289 const target = mod.getTarget();
2327pub fn floatRemScalar(lhs: Value, rhs: Value, float_type: Type, pt: Zcu.PerThread) !Value {
2328 const target = pt.zcu.getTarget();
22902329 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
2291 16 => .{ .f16 = @rem(lhs.toFloat(f16, mod), rhs.toFloat(f16, mod)) },
2292 32 => .{ .f32 = @rem(lhs.toFloat(f32, mod), rhs.toFloat(f32, mod)) },
2293 64 => .{ .f64 = @rem(lhs.toFloat(f64, mod), rhs.toFloat(f64, mod)) },
2294 80 => .{ .f80 = @rem(lhs.toFloat(f80, mod), rhs.toFloat(f80, mod)) },
2295 128 => .{ .f128 = @rem(lhs.toFloat(f128, mod), rhs.toFloat(f128, mod)) },
2330 16 => .{ .f16 = @rem(lhs.toFloat(f16, pt), rhs.toFloat(f16, pt)) },
2331 32 => .{ .f32 = @rem(lhs.toFloat(f32, pt), rhs.toFloat(f32, pt)) },
2332 64 => .{ .f64 = @rem(lhs.toFloat(f64, pt), rhs.toFloat(f64, pt)) },
2333 80 => .{ .f80 = @rem(lhs.toFloat(f80, pt), rhs.toFloat(f80, pt)) },
2334 128 => .{ .f128 = @rem(lhs.toFloat(f128, pt), rhs.toFloat(f128, pt)) },
22962335 else => unreachable,
22972336 };
2298 return Value.fromInterned((try mod.intern(.{ .float = .{
2337 return Value.fromInterned(try pt.intern(.{ .float = .{
22992338 .ty = float_type.toIntern(),
23002339 .storage = storage,
2301 } })));
2340 } }));
23022341}
23032342
2304pub fn floatMod(lhs: Value, rhs: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
2305 if (float_type.zigTypeTag(mod) == .Vector) {
2306 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
2307 const scalar_ty = float_type.scalarType(mod);
2343pub fn floatMod(lhs: Value, rhs: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
2344 if (float_type.zigTypeTag(pt.zcu) == .Vector) {
2345 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(pt.zcu));
2346 const scalar_ty = float_type.scalarType(pt.zcu);
23082347 for (result_data, 0..) |*scalar, i| {
2309 const lhs_elem = try lhs.elemValue(mod, i);
2310 const rhs_elem = try rhs.elemValue(mod, i);
2311 scalar.* = (try floatModScalar(lhs_elem, rhs_elem, scalar_ty, mod)).toIntern();
2348 const lhs_elem = try lhs.elemValue(pt, i);
2349 const rhs_elem = try rhs.elemValue(pt, i);
2350 scalar.* = (try floatModScalar(lhs_elem, rhs_elem, scalar_ty, pt)).toIntern();
23122351 }
2313 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2352 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
23142353 .ty = float_type.toIntern(),
23152354 .storage = .{ .elems = result_data },
2316 } })));
2355 } }));
23172356 }
2318 return floatModScalar(lhs, rhs, float_type, mod);
2357 return floatModScalar(lhs, rhs, float_type, pt);
23192358}
23202359
2321pub fn floatModScalar(lhs: Value, rhs: Value, float_type: Type, mod: *Module) !Value {
2322 const target = mod.getTarget();
2360pub fn floatModScalar(lhs: Value, rhs: Value, float_type: Type, pt: Zcu.PerThread) !Value {
2361 const target = pt.zcu.getTarget();
23232362 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
2324 16 => .{ .f16 = @mod(lhs.toFloat(f16, mod), rhs.toFloat(f16, mod)) },
2325 32 => .{ .f32 = @mod(lhs.toFloat(f32, mod), rhs.toFloat(f32, mod)) },
2326 64 => .{ .f64 = @mod(lhs.toFloat(f64, mod), rhs.toFloat(f64, mod)) },
2327 80 => .{ .f80 = @mod(lhs.toFloat(f80, mod), rhs.toFloat(f80, mod)) },
2328 128 => .{ .f128 = @mod(lhs.toFloat(f128, mod), rhs.toFloat(f128, mod)) },
2363 16 => .{ .f16 = @mod(lhs.toFloat(f16, pt), rhs.toFloat(f16, pt)) },
2364 32 => .{ .f32 = @mod(lhs.toFloat(f32, pt), rhs.toFloat(f32, pt)) },
2365 64 => .{ .f64 = @mod(lhs.toFloat(f64, pt), rhs.toFloat(f64, pt)) },
2366 80 => .{ .f80 = @mod(lhs.toFloat(f80, pt), rhs.toFloat(f80, pt)) },
2367 128 => .{ .f128 = @mod(lhs.toFloat(f128, pt), rhs.toFloat(f128, pt)) },
23292368 else => unreachable,
23302369 };
2331 return Value.fromInterned((try mod.intern(.{ .float = .{
2370 return Value.fromInterned(try pt.intern(.{ .float = .{
23322371 .ty = float_type.toIntern(),
23332372 .storage = storage,
2334 } })));
2373 } }));
23352374}
23362375
23372376/// If the value overflowed the type, returns a comptime_int (or vector thereof) instead, setting
23382377/// overflow_idx to the vector index the overflow was at (or 0 for a scalar).
2339pub fn intMul(lhs: Value, rhs: Value, ty: Type, overflow_idx: *?usize, allocator: Allocator, mod: *Module) !Value {
2378pub fn intMul(lhs: Value, rhs: Value, ty: Type, overflow_idx: *?usize, allocator: Allocator, pt: Zcu.PerThread) !Value {
2379 const mod = pt.zcu;
23402380 var overflow: usize = undefined;
2341 return intMulInner(lhs, rhs, ty, &overflow, allocator, mod) catch |err| switch (err) {
2381 return intMulInner(lhs, rhs, ty, &overflow, allocator, pt) catch |err| switch (err) {
23422382 error.Overflow => {
23432383 const is_vec = ty.isVector(mod);
23442384 overflow_idx.* = if (is_vec) overflow else 0;
2345 const safe_ty = if (is_vec) try mod.vectorType(.{
2385 const safe_ty = if (is_vec) try pt.vectorType(.{
23462386 .len = ty.vectorLen(mod),
23472387 .child = .comptime_int_type,
23482388 }) else Type.comptime_int;
2349 return intMulInner(lhs, rhs, safe_ty, undefined, allocator, mod) catch |err1| switch (err1) {
2389 return intMulInner(lhs, rhs, safe_ty, undefined, allocator, pt) catch |err1| switch (err1) {
23502390 error.Overflow => unreachable,
23512391 else => |e| return e,
23522392 };
......@@ -2355,14 +2395,15 @@ pub fn intMul(lhs: Value, rhs: Value, ty: Type, overflow_idx: *?usize, allocator
23552395 };
23562396}
23572397
2358fn intMulInner(lhs: Value, rhs: Value, ty: Type, overflow_idx: *usize, allocator: Allocator, mod: *Module) !Value {
2398fn intMulInner(lhs: Value, rhs: Value, ty: Type, overflow_idx: *usize, allocator: Allocator, pt: Zcu.PerThread) !Value {
2399 const mod = pt.zcu;
23592400 if (ty.zigTypeTag(mod) == .Vector) {
23602401 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
23612402 const scalar_ty = ty.scalarType(mod);
23622403 for (result_data, 0..) |*scalar, i| {
2363 const lhs_elem = try lhs.elemValue(mod, i);
2364 const rhs_elem = try rhs.elemValue(mod, i);
2365 const val = intMulScalar(lhs_elem, rhs_elem, scalar_ty, allocator, mod) catch |err| switch (err) {
2404 const lhs_elem = try lhs.elemValue(pt, i);
2405 const rhs_elem = try rhs.elemValue(pt, i);
2406 const val = intMulScalar(lhs_elem, rhs_elem, scalar_ty, allocator, pt) catch |err| switch (err) {
23662407 error.Overflow => {
23672408 overflow_idx.* = i;
23682409 return error.Overflow;
......@@ -2371,26 +2412,26 @@ fn intMulInner(lhs: Value, rhs: Value, ty: Type, overflow_idx: *usize, allocator
23712412 };
23722413 scalar.* = val.toIntern();
23732414 }
2374 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2415 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
23752416 .ty = ty.toIntern(),
23762417 .storage = .{ .elems = result_data },
2377 } })));
2418 } }));
23782419 }
2379 return intMulScalar(lhs, rhs, ty, allocator, mod);
2420 return intMulScalar(lhs, rhs, ty, allocator, pt);
23802421}
23812422
2382pub fn intMulScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2423pub fn intMulScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
23832424 if (ty.toIntern() != .comptime_int_type) {
2384 const res = try intMulWithOverflowScalar(lhs, rhs, ty, allocator, mod);
2385 if (res.overflow_bit.compareAllWithZero(.neq, mod)) return error.Overflow;
2425 const res = try intMulWithOverflowScalar(lhs, rhs, ty, allocator, pt);
2426 if (res.overflow_bit.compareAllWithZero(.neq, pt)) return error.Overflow;
23862427 return res.wrapped_result;
23872428 }
23882429 // TODO is this a performance issue? maybe we should try the operation without
23892430 // resorting to BigInt first.
23902431 var lhs_space: Value.BigIntSpace = undefined;
23912432 var rhs_space: Value.BigIntSpace = undefined;
2392 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
2393 const rhs_bigint = rhs.toBigInt(&rhs_space, mod);
2433 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
2434 const rhs_bigint = rhs.toBigInt(&rhs_space, pt);
23942435 const limbs = try allocator.alloc(
23952436 std.math.big.Limb,
23962437 lhs_bigint.limbs.len + rhs_bigint.limbs.len,
......@@ -2402,23 +2443,24 @@ pub fn intMulScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod:
24022443 );
24032444 defer allocator.free(limbs_buffer);
24042445 result_bigint.mul(lhs_bigint, rhs_bigint, limbs_buffer, allocator);
2405 return mod.intValue_big(ty, result_bigint.toConst());
2446 return pt.intValue_big(ty, result_bigint.toConst());
24062447}
24072448
2408pub fn intTrunc(val: Value, ty: Type, allocator: Allocator, signedness: std.builtin.Signedness, bits: u16, mod: *Module) !Value {
2449pub fn intTrunc(val: Value, ty: Type, allocator: Allocator, signedness: std.builtin.Signedness, bits: u16, pt: Zcu.PerThread) !Value {
2450 const mod = pt.zcu;
24092451 if (ty.zigTypeTag(mod) == .Vector) {
24102452 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
24112453 const scalar_ty = ty.scalarType(mod);
24122454 for (result_data, 0..) |*scalar, i| {
2413 const elem_val = try val.elemValue(mod, i);
2414 scalar.* = (try intTruncScalar(elem_val, scalar_ty, allocator, signedness, bits, mod)).toIntern();
2455 const elem_val = try val.elemValue(pt, i);
2456 scalar.* = (try intTruncScalar(elem_val, scalar_ty, allocator, signedness, bits, pt)).toIntern();
24152457 }
2416 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2458 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
24172459 .ty = ty.toIntern(),
24182460 .storage = .{ .elems = result_data },
2419 } })));
2461 } }));
24202462 }
2421 return intTruncScalar(val, ty, allocator, signedness, bits, mod);
2463 return intTruncScalar(val, ty, allocator, signedness, bits, pt);
24222464}
24232465
24242466/// This variant may vectorize on `bits`. Asserts that `bits` is a (vector of) `u16`.
......@@ -2428,22 +2470,22 @@ pub fn intTruncBitsAsValue(
24282470 allocator: Allocator,
24292471 signedness: std.builtin.Signedness,
24302472 bits: Value,
2431 mod: *Module,
2473 pt: Zcu.PerThread,
24322474) !Value {
2433 if (ty.zigTypeTag(mod) == .Vector) {
2434 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
2435 const scalar_ty = ty.scalarType(mod);
2475 if (ty.zigTypeTag(pt.zcu) == .Vector) {
2476 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
2477 const scalar_ty = ty.scalarType(pt.zcu);
24362478 for (result_data, 0..) |*scalar, i| {
2437 const elem_val = try val.elemValue(mod, i);
2438 const bits_elem = try bits.elemValue(mod, i);
2439 scalar.* = (try intTruncScalar(elem_val, scalar_ty, allocator, signedness, @intCast(bits_elem.toUnsignedInt(mod)), mod)).toIntern();
2479 const elem_val = try val.elemValue(pt, i);
2480 const bits_elem = try bits.elemValue(pt, i);
2481 scalar.* = (try intTruncScalar(elem_val, scalar_ty, allocator, signedness, @intCast(bits_elem.toUnsignedInt(pt)), pt)).toIntern();
24402482 }
2441 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2483 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
24422484 .ty = ty.toIntern(),
24432485 .storage = .{ .elems = result_data },
2444 } })));
2486 } }));
24452487 }
2446 return intTruncScalar(val, ty, allocator, signedness, @intCast(bits.toUnsignedInt(mod)), mod);
2488 return intTruncScalar(val, ty, allocator, signedness, @intCast(bits.toUnsignedInt(pt)), pt);
24472489}
24482490
24492491pub fn intTruncScalar(
......@@ -2452,14 +2494,15 @@ pub fn intTruncScalar(
24522494 allocator: Allocator,
24532495 signedness: std.builtin.Signedness,
24542496 bits: u16,
2455 zcu: *Zcu,
2497 pt: Zcu.PerThread,
24562498) !Value {
2457 if (bits == 0) return zcu.intValue(ty, 0);
2499 const zcu = pt.zcu;
2500 if (bits == 0) return pt.intValue(ty, 0);
24582501
2459 if (val.isUndef(zcu)) return zcu.undefValue(ty);
2502 if (val.isUndef(zcu)) return pt.undefValue(ty);
24602503
24612504 var val_space: Value.BigIntSpace = undefined;
2462 const val_bigint = val.toBigInt(&val_space, zcu);
2505 const val_bigint = val.toBigInt(&val_space, pt);
24632506
24642507 const limbs = try allocator.alloc(
24652508 std.math.big.Limb,
......@@ -2468,32 +2511,33 @@ pub fn intTruncScalar(
24682511 var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined };
24692512
24702513 result_bigint.truncate(val_bigint, signedness, bits);
2471 return zcu.intValue_big(ty, result_bigint.toConst());
2514 return pt.intValue_big(ty, result_bigint.toConst());
24722515}
24732516
2474pub fn shl(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2517pub fn shl(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
2518 const mod = pt.zcu;
24752519 if (ty.zigTypeTag(mod) == .Vector) {
24762520 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
24772521 const scalar_ty = ty.scalarType(mod);
24782522 for (result_data, 0..) |*scalar, i| {
2479 const lhs_elem = try lhs.elemValue(mod, i);
2480 const rhs_elem = try rhs.elemValue(mod, i);
2481 scalar.* = (try shlScalar(lhs_elem, rhs_elem, scalar_ty, allocator, mod)).toIntern();
2523 const lhs_elem = try lhs.elemValue(pt, i);
2524 const rhs_elem = try rhs.elemValue(pt, i);
2525 scalar.* = (try shlScalar(lhs_elem, rhs_elem, scalar_ty, allocator, pt)).toIntern();
24822526 }
2483 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2527 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
24842528 .ty = ty.toIntern(),
24852529 .storage = .{ .elems = result_data },
2486 } })));
2530 } }));
24872531 }
2488 return shlScalar(lhs, rhs, ty, allocator, mod);
2532 return shlScalar(lhs, rhs, ty, allocator, pt);
24892533}
24902534
2491pub fn shlScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2535pub fn shlScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
24922536 // TODO is this a performance issue? maybe we should try the operation without
24932537 // resorting to BigInt first.
24942538 var lhs_space: Value.BigIntSpace = undefined;
2495 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
2496 const shift: usize = @intCast(rhs.toUnsignedInt(mod));
2539 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
2540 const shift: usize = @intCast(rhs.toUnsignedInt(pt));
24972541 const limbs = try allocator.alloc(
24982542 std.math.big.Limb,
24992543 lhs_bigint.limbs.len + (shift / (@sizeOf(std.math.big.Limb) * 8)) + 1,
......@@ -2505,11 +2549,11 @@ pub fn shlScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *M
25052549 };
25062550 result_bigint.shiftLeft(lhs_bigint, shift);
25072551 if (ty.toIntern() != .comptime_int_type) {
2508 const int_info = ty.intInfo(mod);
2552 const int_info = ty.intInfo(pt.zcu);
25092553 result_bigint.truncate(result_bigint.toConst(), int_info.signedness, int_info.bits);
25102554 }
25112555
2512 return mod.intValue_big(ty, result_bigint.toConst());
2556 return pt.intValue_big(ty, result_bigint.toConst());
25132557}
25142558
25152559pub fn shlWithOverflow(
......@@ -2517,32 +2561,32 @@ pub fn shlWithOverflow(
25172561 rhs: Value,
25182562 ty: Type,
25192563 allocator: Allocator,
2520 mod: *Module,
2564 pt: Zcu.PerThread,
25212565) !OverflowArithmeticResult {
2522 if (ty.zigTypeTag(mod) == .Vector) {
2523 const vec_len = ty.vectorLen(mod);
2566 if (ty.zigTypeTag(pt.zcu) == .Vector) {
2567 const vec_len = ty.vectorLen(pt.zcu);
25242568 const overflowed_data = try allocator.alloc(InternPool.Index, vec_len);
25252569 const result_data = try allocator.alloc(InternPool.Index, vec_len);
2526 const scalar_ty = ty.scalarType(mod);
2570 const scalar_ty = ty.scalarType(pt.zcu);
25272571 for (overflowed_data, result_data, 0..) |*of, *scalar, i| {
2528 const lhs_elem = try lhs.elemValue(mod, i);
2529 const rhs_elem = try rhs.elemValue(mod, i);
2530 const of_math_result = try shlWithOverflowScalar(lhs_elem, rhs_elem, scalar_ty, allocator, mod);
2572 const lhs_elem = try lhs.elemValue(pt, i);
2573 const rhs_elem = try rhs.elemValue(pt, i);
2574 const of_math_result = try shlWithOverflowScalar(lhs_elem, rhs_elem, scalar_ty, allocator, pt);
25312575 of.* = of_math_result.overflow_bit.toIntern();
25322576 scalar.* = of_math_result.wrapped_result.toIntern();
25332577 }
25342578 return OverflowArithmeticResult{
2535 .overflow_bit = Value.fromInterned((try mod.intern(.{ .aggregate = .{
2536 .ty = (try mod.vectorType(.{ .len = vec_len, .child = .u1_type })).toIntern(),
2579 .overflow_bit = Value.fromInterned(try pt.intern(.{ .aggregate = .{
2580 .ty = (try pt.vectorType(.{ .len = vec_len, .child = .u1_type })).toIntern(),
25372581 .storage = .{ .elems = overflowed_data },
2538 } }))),
2539 .wrapped_result = Value.fromInterned((try mod.intern(.{ .aggregate = .{
2582 } })),
2583 .wrapped_result = Value.fromInterned(try pt.intern(.{ .aggregate = .{
25402584 .ty = ty.toIntern(),
25412585 .storage = .{ .elems = result_data },
2542 } }))),
2586 } })),
25432587 };
25442588 }
2545 return shlWithOverflowScalar(lhs, rhs, ty, allocator, mod);
2589 return shlWithOverflowScalar(lhs, rhs, ty, allocator, pt);
25462590}
25472591
25482592pub fn shlWithOverflowScalar(
......@@ -2550,12 +2594,12 @@ pub fn shlWithOverflowScalar(
25502594 rhs: Value,
25512595 ty: Type,
25522596 allocator: Allocator,
2553 mod: *Module,
2597 pt: Zcu.PerThread,
25542598) !OverflowArithmeticResult {
2555 const info = ty.intInfo(mod);
2599 const info = ty.intInfo(pt.zcu);
25562600 var lhs_space: Value.BigIntSpace = undefined;
2557 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
2558 const shift: usize = @intCast(rhs.toUnsignedInt(mod));
2601 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
2602 const shift: usize = @intCast(rhs.toUnsignedInt(pt));
25592603 const limbs = try allocator.alloc(
25602604 std.math.big.Limb,
25612605 lhs_bigint.limbs.len + (shift / (@sizeOf(std.math.big.Limb) * 8)) + 1,
......@@ -2571,8 +2615,8 @@ pub fn shlWithOverflowScalar(
25712615 result_bigint.truncate(result_bigint.toConst(), info.signedness, info.bits);
25722616 }
25732617 return OverflowArithmeticResult{
2574 .overflow_bit = try mod.intValue(Type.u1, @intFromBool(overflowed)),
2575 .wrapped_result = try mod.intValue_big(ty, result_bigint.toConst()),
2618 .overflow_bit = try pt.intValue(Type.u1, @intFromBool(overflowed)),
2619 .wrapped_result = try pt.intValue_big(ty, result_bigint.toConst()),
25762620 };
25772621}
25782622
......@@ -2581,22 +2625,22 @@ pub fn shlSat(
25812625 rhs: Value,
25822626 ty: Type,
25832627 arena: Allocator,
2584 mod: *Module,
2628 pt: Zcu.PerThread,
25852629) !Value {
2586 if (ty.zigTypeTag(mod) == .Vector) {
2587 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(mod));
2588 const scalar_ty = ty.scalarType(mod);
2630 if (ty.zigTypeTag(pt.zcu) == .Vector) {
2631 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
2632 const scalar_ty = ty.scalarType(pt.zcu);
25892633 for (result_data, 0..) |*scalar, i| {
2590 const lhs_elem = try lhs.elemValue(mod, i);
2591 const rhs_elem = try rhs.elemValue(mod, i);
2592 scalar.* = (try shlSatScalar(lhs_elem, rhs_elem, scalar_ty, arena, mod)).toIntern();
2634 const lhs_elem = try lhs.elemValue(pt, i);
2635 const rhs_elem = try rhs.elemValue(pt, i);
2636 scalar.* = (try shlSatScalar(lhs_elem, rhs_elem, scalar_ty, arena, pt)).toIntern();
25932637 }
2594 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2638 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
25952639 .ty = ty.toIntern(),
25962640 .storage = .{ .elems = result_data },
2597 } })));
2641 } }));
25982642 }
2599 return shlSatScalar(lhs, rhs, ty, arena, mod);
2643 return shlSatScalar(lhs, rhs, ty, arena, pt);
26002644}
26012645
26022646pub fn shlSatScalar(
......@@ -2604,15 +2648,15 @@ pub fn shlSatScalar(
26042648 rhs: Value,
26052649 ty: Type,
26062650 arena: Allocator,
2607 mod: *Module,
2651 pt: Zcu.PerThread,
26082652) !Value {
26092653 // TODO is this a performance issue? maybe we should try the operation without
26102654 // resorting to BigInt first.
2611 const info = ty.intInfo(mod);
2655 const info = ty.intInfo(pt.zcu);
26122656
26132657 var lhs_space: Value.BigIntSpace = undefined;
2614 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
2615 const shift: usize = @intCast(rhs.toUnsignedInt(mod));
2658 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
2659 const shift: usize = @intCast(rhs.toUnsignedInt(pt));
26162660 const limbs = try arena.alloc(
26172661 std.math.big.Limb,
26182662 std.math.big.int.calcTwosCompLimbCount(info.bits) + 1,
......@@ -2623,7 +2667,7 @@ pub fn shlSatScalar(
26232667 .len = undefined,
26242668 };
26252669 result_bigint.shiftLeftSat(lhs_bigint, shift, info.signedness, info.bits);
2626 return mod.intValue_big(ty, result_bigint.toConst());
2670 return pt.intValue_big(ty, result_bigint.toConst());
26272671}
26282672
26292673pub fn shlTrunc(
......@@ -2631,22 +2675,22 @@ pub fn shlTrunc(
26312675 rhs: Value,
26322676 ty: Type,
26332677 arena: Allocator,
2634 mod: *Module,
2678 pt: Zcu.PerThread,
26352679) !Value {
2636 if (ty.zigTypeTag(mod) == .Vector) {
2637 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(mod));
2638 const scalar_ty = ty.scalarType(mod);
2680 if (ty.zigTypeTag(pt.zcu) == .Vector) {
2681 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
2682 const scalar_ty = ty.scalarType(pt.zcu);
26392683 for (result_data, 0..) |*scalar, i| {
2640 const lhs_elem = try lhs.elemValue(mod, i);
2641 const rhs_elem = try rhs.elemValue(mod, i);
2642 scalar.* = (try shlTruncScalar(lhs_elem, rhs_elem, scalar_ty, arena, mod)).toIntern();
2684 const lhs_elem = try lhs.elemValue(pt, i);
2685 const rhs_elem = try rhs.elemValue(pt, i);
2686 scalar.* = (try shlTruncScalar(lhs_elem, rhs_elem, scalar_ty, arena, pt)).toIntern();
26432687 }
2644 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2688 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
26452689 .ty = ty.toIntern(),
26462690 .storage = .{ .elems = result_data },
2647 } })));
2691 } }));
26482692 }
2649 return shlTruncScalar(lhs, rhs, ty, arena, mod);
2693 return shlTruncScalar(lhs, rhs, ty, arena, pt);
26502694}
26512695
26522696pub fn shlTruncScalar(
......@@ -2654,46 +2698,46 @@ pub fn shlTruncScalar(
26542698 rhs: Value,
26552699 ty: Type,
26562700 arena: Allocator,
2657 mod: *Module,
2701 pt: Zcu.PerThread,
26582702) !Value {
2659 const shifted = try lhs.shl(rhs, ty, arena, mod);
2660 const int_info = ty.intInfo(mod);
2661 const truncated = try shifted.intTrunc(ty, arena, int_info.signedness, int_info.bits, mod);
2703 const shifted = try lhs.shl(rhs, ty, arena, pt);
2704 const int_info = ty.intInfo(pt.zcu);
2705 const truncated = try shifted.intTrunc(ty, arena, int_info.signedness, int_info.bits, pt);
26622706 return truncated;
26632707}
26642708
2665pub fn shr(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2666 if (ty.zigTypeTag(mod) == .Vector) {
2667 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(mod));
2668 const scalar_ty = ty.scalarType(mod);
2709pub fn shr(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
2710 if (ty.zigTypeTag(pt.zcu) == .Vector) {
2711 const result_data = try allocator.alloc(InternPool.Index, ty.vectorLen(pt.zcu));
2712 const scalar_ty = ty.scalarType(pt.zcu);
26692713 for (result_data, 0..) |*scalar, i| {
2670 const lhs_elem = try lhs.elemValue(mod, i);
2671 const rhs_elem = try rhs.elemValue(mod, i);
2672 scalar.* = (try shrScalar(lhs_elem, rhs_elem, scalar_ty, allocator, mod)).toIntern();
2714 const lhs_elem = try lhs.elemValue(pt, i);
2715 const rhs_elem = try rhs.elemValue(pt, i);
2716 scalar.* = (try shrScalar(lhs_elem, rhs_elem, scalar_ty, allocator, pt)).toIntern();
26732717 }
2674 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2718 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
26752719 .ty = ty.toIntern(),
26762720 .storage = .{ .elems = result_data },
2677 } })));
2721 } }));
26782722 }
2679 return shrScalar(lhs, rhs, ty, allocator, mod);
2723 return shrScalar(lhs, rhs, ty, allocator, pt);
26802724}
26812725
2682pub fn shrScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *Module) !Value {
2726pub fn shrScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, pt: Zcu.PerThread) !Value {
26832727 // TODO is this a performance issue? maybe we should try the operation without
26842728 // resorting to BigInt first.
26852729 var lhs_space: Value.BigIntSpace = undefined;
2686 const lhs_bigint = lhs.toBigInt(&lhs_space, mod);
2687 const shift: usize = @intCast(rhs.toUnsignedInt(mod));
2730 const lhs_bigint = lhs.toBigInt(&lhs_space, pt);
2731 const shift: usize = @intCast(rhs.toUnsignedInt(pt));
26882732
26892733 const result_limbs = lhs_bigint.limbs.len -| (shift / (@sizeOf(std.math.big.Limb) * 8));
26902734 if (result_limbs == 0) {
26912735 // The shift is enough to remove all the bits from the number, which means the
26922736 // result is 0 or -1 depending on the sign.
26932737 if (lhs_bigint.positive) {
2694 return mod.intValue(ty, 0);
2738 return pt.intValue(ty, 0);
26952739 } else {
2696 return mod.intValue(ty, -1);
2740 return pt.intValue(ty, -1);
26972741 }
26982742 }
26992743
......@@ -2707,48 +2751,45 @@ pub fn shrScalar(lhs: Value, rhs: Value, ty: Type, allocator: Allocator, mod: *M
27072751 .len = undefined,
27082752 };
27092753 result_bigint.shiftRight(lhs_bigint, shift);
2710 return mod.intValue_big(ty, result_bigint.toConst());
2754 return pt.intValue_big(ty, result_bigint.toConst());
27112755}
27122756
27132757pub fn floatNeg(
27142758 val: Value,
27152759 float_type: Type,
27162760 arena: Allocator,
2717 mod: *Module,
2761 pt: Zcu.PerThread,
27182762) !Value {
2763 const mod = pt.zcu;
27192764 if (float_type.zigTypeTag(mod) == .Vector) {
27202765 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
27212766 const scalar_ty = float_type.scalarType(mod);
27222767 for (result_data, 0..) |*scalar, i| {
2723 const elem_val = try val.elemValue(mod, i);
2724 scalar.* = (try floatNegScalar(elem_val, scalar_ty, mod)).toIntern();
2768 const elem_val = try val.elemValue(pt, i);
2769 scalar.* = (try floatNegScalar(elem_val, scalar_ty, pt)).toIntern();
27252770 }
2726 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2771 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
27272772 .ty = float_type.toIntern(),
27282773 .storage = .{ .elems = result_data },
2729 } })));
2774 } }));
27302775 }
2731 return floatNegScalar(val, float_type, mod);
2776 return floatNegScalar(val, float_type, pt);
27322777}
27332778
2734pub fn floatNegScalar(
2735 val: Value,
2736 float_type: Type,
2737 mod: *Module,
2738) !Value {
2739 const target = mod.getTarget();
2779pub fn floatNegScalar(val: Value, float_type: Type, pt: Zcu.PerThread) !Value {
2780 const target = pt.zcu.getTarget();
27402781 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
2741 16 => .{ .f16 = -val.toFloat(f16, mod) },
2742 32 => .{ .f32 = -val.toFloat(f32, mod) },
2743 64 => .{ .f64 = -val.toFloat(f64, mod) },
2744 80 => .{ .f80 = -val.toFloat(f80, mod) },
2745 128 => .{ .f128 = -val.toFloat(f128, mod) },
2782 16 => .{ .f16 = -val.toFloat(f16, pt) },
2783 32 => .{ .f32 = -val.toFloat(f32, pt) },
2784 64 => .{ .f64 = -val.toFloat(f64, pt) },
2785 80 => .{ .f80 = -val.toFloat(f80, pt) },
2786 128 => .{ .f128 = -val.toFloat(f128, pt) },
27462787 else => unreachable,
27472788 };
2748 return Value.fromInterned((try mod.intern(.{ .float = .{
2789 return Value.fromInterned(try pt.intern(.{ .float = .{
27492790 .ty = float_type.toIntern(),
27502791 .storage = storage,
2751 } })));
2792 } }));
27522793}
27532794
27542795pub fn floatAdd(
......@@ -2756,43 +2797,45 @@ pub fn floatAdd(
27562797 rhs: Value,
27572798 float_type: Type,
27582799 arena: Allocator,
2759 mod: *Module,
2800 pt: Zcu.PerThread,
27602801) !Value {
2802 const mod = pt.zcu;
27612803 if (float_type.zigTypeTag(mod) == .Vector) {
27622804 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
27632805 const scalar_ty = float_type.scalarType(mod);
27642806 for (result_data, 0..) |*scalar, i| {
2765 const lhs_elem = try lhs.elemValue(mod, i);
2766 const rhs_elem = try rhs.elemValue(mod, i);
2767 scalar.* = (try floatAddScalar(lhs_elem, rhs_elem, scalar_ty, mod)).toIntern();
2807 const lhs_elem = try lhs.elemValue(pt, i);
2808 const rhs_elem = try rhs.elemValue(pt, i);
2809 scalar.* = (try floatAddScalar(lhs_elem, rhs_elem, scalar_ty, pt)).toIntern();
27682810 }
2769 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2811 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
27702812 .ty = float_type.toIntern(),
27712813 .storage = .{ .elems = result_data },
2772 } })));
2814 } }));
27732815 }
2774 return floatAddScalar(lhs, rhs, float_type, mod);
2816 return floatAddScalar(lhs, rhs, float_type, pt);
27752817}
27762818
27772819pub fn floatAddScalar(
27782820 lhs: Value,
27792821 rhs: Value,
27802822 float_type: Type,
2781 mod: *Module,
2823 pt: Zcu.PerThread,
27822824) !Value {
2825 const mod = pt.zcu;
27832826 const target = mod.getTarget();
27842827 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
2785 16 => .{ .f16 = lhs.toFloat(f16, mod) + rhs.toFloat(f16, mod) },
2786 32 => .{ .f32 = lhs.toFloat(f32, mod) + rhs.toFloat(f32, mod) },
2787 64 => .{ .f64 = lhs.toFloat(f64, mod) + rhs.toFloat(f64, mod) },
2788 80 => .{ .f80 = lhs.toFloat(f80, mod) + rhs.toFloat(f80, mod) },
2789 128 => .{ .f128 = lhs.toFloat(f128, mod) + rhs.toFloat(f128, mod) },
2828 16 => .{ .f16 = lhs.toFloat(f16, pt) + rhs.toFloat(f16, pt) },
2829 32 => .{ .f32 = lhs.toFloat(f32, pt) + rhs.toFloat(f32, pt) },
2830 64 => .{ .f64 = lhs.toFloat(f64, pt) + rhs.toFloat(f64, pt) },
2831 80 => .{ .f80 = lhs.toFloat(f80, pt) + rhs.toFloat(f80, pt) },
2832 128 => .{ .f128 = lhs.toFloat(f128, pt) + rhs.toFloat(f128, pt) },
27902833 else => unreachable,
27912834 };
2792 return Value.fromInterned((try mod.intern(.{ .float = .{
2835 return Value.fromInterned(try pt.intern(.{ .float = .{
27932836 .ty = float_type.toIntern(),
27942837 .storage = storage,
2795 } })));
2838 } }));
27962839}
27972840
27982841pub fn floatSub(
......@@ -2800,43 +2843,45 @@ pub fn floatSub(
28002843 rhs: Value,
28012844 float_type: Type,
28022845 arena: Allocator,
2803 mod: *Module,
2846 pt: Zcu.PerThread,
28042847) !Value {
2848 const mod = pt.zcu;
28052849 if (float_type.zigTypeTag(mod) == .Vector) {
28062850 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
28072851 const scalar_ty = float_type.scalarType(mod);
28082852 for (result_data, 0..) |*scalar, i| {
2809 const lhs_elem = try lhs.elemValue(mod, i);
2810 const rhs_elem = try rhs.elemValue(mod, i);
2811 scalar.* = (try floatSubScalar(lhs_elem, rhs_elem, scalar_ty, mod)).toIntern();
2853 const lhs_elem = try lhs.elemValue(pt, i);
2854 const rhs_elem = try rhs.elemValue(pt, i);
2855 scalar.* = (try floatSubScalar(lhs_elem, rhs_elem, scalar_ty, pt)).toIntern();
28122856 }
2813 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2857 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
28142858 .ty = float_type.toIntern(),
28152859 .storage = .{ .elems = result_data },
2816 } })));
2860 } }));
28172861 }
2818 return floatSubScalar(lhs, rhs, float_type, mod);
2862 return floatSubScalar(lhs, rhs, float_type, pt);
28192863}
28202864
28212865pub fn floatSubScalar(
28222866 lhs: Value,
28232867 rhs: Value,
28242868 float_type: Type,
2825 mod: *Module,
2869 pt: Zcu.PerThread,
28262870) !Value {
2871 const mod = pt.zcu;
28272872 const target = mod.getTarget();
28282873 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
2829 16 => .{ .f16 = lhs.toFloat(f16, mod) - rhs.toFloat(f16, mod) },
2830 32 => .{ .f32 = lhs.toFloat(f32, mod) - rhs.toFloat(f32, mod) },
2831 64 => .{ .f64 = lhs.toFloat(f64, mod) - rhs.toFloat(f64, mod) },
2832 80 => .{ .f80 = lhs.toFloat(f80, mod) - rhs.toFloat(f80, mod) },
2833 128 => .{ .f128 = lhs.toFloat(f128, mod) - rhs.toFloat(f128, mod) },
2874 16 => .{ .f16 = lhs.toFloat(f16, pt) - rhs.toFloat(f16, pt) },
2875 32 => .{ .f32 = lhs.toFloat(f32, pt) - rhs.toFloat(f32, pt) },
2876 64 => .{ .f64 = lhs.toFloat(f64, pt) - rhs.toFloat(f64, pt) },
2877 80 => .{ .f80 = lhs.toFloat(f80, pt) - rhs.toFloat(f80, pt) },
2878 128 => .{ .f128 = lhs.toFloat(f128, pt) - rhs.toFloat(f128, pt) },
28342879 else => unreachable,
28352880 };
2836 return Value.fromInterned((try mod.intern(.{ .float = .{
2881 return Value.fromInterned(try pt.intern(.{ .float = .{
28372882 .ty = float_type.toIntern(),
28382883 .storage = storage,
2839 } })));
2884 } }));
28402885}
28412886
28422887pub fn floatDiv(
......@@ -2844,43 +2889,43 @@ pub fn floatDiv(
28442889 rhs: Value,
28452890 float_type: Type,
28462891 arena: Allocator,
2847 mod: *Module,
2892 pt: Zcu.PerThread,
28482893) !Value {
2849 if (float_type.zigTypeTag(mod) == .Vector) {
2850 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
2851 const scalar_ty = float_type.scalarType(mod);
2894 if (float_type.zigTypeTag(pt.zcu) == .Vector) {
2895 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(pt.zcu));
2896 const scalar_ty = float_type.scalarType(pt.zcu);
28522897 for (result_data, 0..) |*scalar, i| {
2853 const lhs_elem = try lhs.elemValue(mod, i);
2854 const rhs_elem = try rhs.elemValue(mod, i);
2855 scalar.* = (try floatDivScalar(lhs_elem, rhs_elem, scalar_ty, mod)).toIntern();
2898 const lhs_elem = try lhs.elemValue(pt, i);
2899 const rhs_elem = try rhs.elemValue(pt, i);
2900 scalar.* = (try floatDivScalar(lhs_elem, rhs_elem, scalar_ty, pt)).toIntern();
28562901 }
2857 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2902 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
28582903 .ty = float_type.toIntern(),
28592904 .storage = .{ .elems = result_data },
2860 } })));
2905 } }));
28612906 }
2862 return floatDivScalar(lhs, rhs, float_type, mod);
2907 return floatDivScalar(lhs, rhs, float_type, pt);
28632908}
28642909
28652910pub fn floatDivScalar(
28662911 lhs: Value,
28672912 rhs: Value,
28682913 float_type: Type,
2869 mod: *Module,
2914 pt: Zcu.PerThread,
28702915) !Value {
2871 const target = mod.getTarget();
2916 const target = pt.zcu.getTarget();
28722917 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
2873 16 => .{ .f16 = lhs.toFloat(f16, mod) / rhs.toFloat(f16, mod) },
2874 32 => .{ .f32 = lhs.toFloat(f32, mod) / rhs.toFloat(f32, mod) },
2875 64 => .{ .f64 = lhs.toFloat(f64, mod) / rhs.toFloat(f64, mod) },
2876 80 => .{ .f80 = lhs.toFloat(f80, mod) / rhs.toFloat(f80, mod) },
2877 128 => .{ .f128 = lhs.toFloat(f128, mod) / rhs.toFloat(f128, mod) },
2918 16 => .{ .f16 = lhs.toFloat(f16, pt) / rhs.toFloat(f16, pt) },
2919 32 => .{ .f32 = lhs.toFloat(f32, pt) / rhs.toFloat(f32, pt) },
2920 64 => .{ .f64 = lhs.toFloat(f64, pt) / rhs.toFloat(f64, pt) },
2921 80 => .{ .f80 = lhs.toFloat(f80, pt) / rhs.toFloat(f80, pt) },
2922 128 => .{ .f128 = lhs.toFloat(f128, pt) / rhs.toFloat(f128, pt) },
28782923 else => unreachable,
28792924 };
2880 return Value.fromInterned((try mod.intern(.{ .float = .{
2925 return Value.fromInterned(try pt.intern(.{ .float = .{
28812926 .ty = float_type.toIntern(),
28822927 .storage = storage,
2883 } })));
2928 } }));
28842929}
28852930
28862931pub fn floatDivFloor(
......@@ -2888,43 +2933,43 @@ pub fn floatDivFloor(
28882933 rhs: Value,
28892934 float_type: Type,
28902935 arena: Allocator,
2891 mod: *Module,
2936 pt: Zcu.PerThread,
28922937) !Value {
2893 if (float_type.zigTypeTag(mod) == .Vector) {
2894 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
2895 const scalar_ty = float_type.scalarType(mod);
2938 if (float_type.zigTypeTag(pt.zcu) == .Vector) {
2939 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(pt.zcu));
2940 const scalar_ty = float_type.scalarType(pt.zcu);
28962941 for (result_data, 0..) |*scalar, i| {
2897 const lhs_elem = try lhs.elemValue(mod, i);
2898 const rhs_elem = try rhs.elemValue(mod, i);
2899 scalar.* = (try floatDivFloorScalar(lhs_elem, rhs_elem, scalar_ty, mod)).toIntern();
2942 const lhs_elem = try lhs.elemValue(pt, i);
2943 const rhs_elem = try rhs.elemValue(pt, i);
2944 scalar.* = (try floatDivFloorScalar(lhs_elem, rhs_elem, scalar_ty, pt)).toIntern();
29002945 }
2901 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2946 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
29022947 .ty = float_type.toIntern(),
29032948 .storage = .{ .elems = result_data },
2904 } })));
2949 } }));
29052950 }
2906 return floatDivFloorScalar(lhs, rhs, float_type, mod);
2951 return floatDivFloorScalar(lhs, rhs, float_type, pt);
29072952}
29082953
29092954pub fn floatDivFloorScalar(
29102955 lhs: Value,
29112956 rhs: Value,
29122957 float_type: Type,
2913 mod: *Module,
2958 pt: Zcu.PerThread,
29142959) !Value {
2915 const target = mod.getTarget();
2960 const target = pt.zcu.getTarget();
29162961 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
2917 16 => .{ .f16 = @divFloor(lhs.toFloat(f16, mod), rhs.toFloat(f16, mod)) },
2918 32 => .{ .f32 = @divFloor(lhs.toFloat(f32, mod), rhs.toFloat(f32, mod)) },
2919 64 => .{ .f64 = @divFloor(lhs.toFloat(f64, mod), rhs.toFloat(f64, mod)) },
2920 80 => .{ .f80 = @divFloor(lhs.toFloat(f80, mod), rhs.toFloat(f80, mod)) },
2921 128 => .{ .f128 = @divFloor(lhs.toFloat(f128, mod), rhs.toFloat(f128, mod)) },
2962 16 => .{ .f16 = @divFloor(lhs.toFloat(f16, pt), rhs.toFloat(f16, pt)) },
2963 32 => .{ .f32 = @divFloor(lhs.toFloat(f32, pt), rhs.toFloat(f32, pt)) },
2964 64 => .{ .f64 = @divFloor(lhs.toFloat(f64, pt), rhs.toFloat(f64, pt)) },
2965 80 => .{ .f80 = @divFloor(lhs.toFloat(f80, pt), rhs.toFloat(f80, pt)) },
2966 128 => .{ .f128 = @divFloor(lhs.toFloat(f128, pt), rhs.toFloat(f128, pt)) },
29222967 else => unreachable,
29232968 };
2924 return Value.fromInterned((try mod.intern(.{ .float = .{
2969 return Value.fromInterned(try pt.intern(.{ .float = .{
29252970 .ty = float_type.toIntern(),
29262971 .storage = storage,
2927 } })));
2972 } }));
29282973}
29292974
29302975pub fn floatDivTrunc(
......@@ -2932,43 +2977,43 @@ pub fn floatDivTrunc(
29322977 rhs: Value,
29332978 float_type: Type,
29342979 arena: Allocator,
2935 mod: *Module,
2980 pt: Zcu.PerThread,
29362981) !Value {
2937 if (float_type.zigTypeTag(mod) == .Vector) {
2938 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
2939 const scalar_ty = float_type.scalarType(mod);
2982 if (float_type.zigTypeTag(pt.zcu) == .Vector) {
2983 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(pt.zcu));
2984 const scalar_ty = float_type.scalarType(pt.zcu);
29402985 for (result_data, 0..) |*scalar, i| {
2941 const lhs_elem = try lhs.elemValue(mod, i);
2942 const rhs_elem = try rhs.elemValue(mod, i);
2943 scalar.* = (try floatDivTruncScalar(lhs_elem, rhs_elem, scalar_ty, mod)).toIntern();
2986 const lhs_elem = try lhs.elemValue(pt, i);
2987 const rhs_elem = try rhs.elemValue(pt, i);
2988 scalar.* = (try floatDivTruncScalar(lhs_elem, rhs_elem, scalar_ty, pt)).toIntern();
29442989 }
2945 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
2990 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
29462991 .ty = float_type.toIntern(),
29472992 .storage = .{ .elems = result_data },
2948 } })));
2993 } }));
29492994 }
2950 return floatDivTruncScalar(lhs, rhs, float_type, mod);
2995 return floatDivTruncScalar(lhs, rhs, float_type, pt);
29512996}
29522997
29532998pub fn floatDivTruncScalar(
29542999 lhs: Value,
29553000 rhs: Value,
29563001 float_type: Type,
2957 mod: *Module,
3002 pt: Zcu.PerThread,
29583003) !Value {
2959 const target = mod.getTarget();
3004 const target = pt.zcu.getTarget();
29603005 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
2961 16 => .{ .f16 = @divTrunc(lhs.toFloat(f16, mod), rhs.toFloat(f16, mod)) },
2962 32 => .{ .f32 = @divTrunc(lhs.toFloat(f32, mod), rhs.toFloat(f32, mod)) },
2963 64 => .{ .f64 = @divTrunc(lhs.toFloat(f64, mod), rhs.toFloat(f64, mod)) },
2964 80 => .{ .f80 = @divTrunc(lhs.toFloat(f80, mod), rhs.toFloat(f80, mod)) },
2965 128 => .{ .f128 = @divTrunc(lhs.toFloat(f128, mod), rhs.toFloat(f128, mod)) },
3006 16 => .{ .f16 = @divTrunc(lhs.toFloat(f16, pt), rhs.toFloat(f16, pt)) },
3007 32 => .{ .f32 = @divTrunc(lhs.toFloat(f32, pt), rhs.toFloat(f32, pt)) },
3008 64 => .{ .f64 = @divTrunc(lhs.toFloat(f64, pt), rhs.toFloat(f64, pt)) },
3009 80 => .{ .f80 = @divTrunc(lhs.toFloat(f80, pt), rhs.toFloat(f80, pt)) },
3010 128 => .{ .f128 = @divTrunc(lhs.toFloat(f128, pt), rhs.toFloat(f128, pt)) },
29663011 else => unreachable,
29673012 };
2968 return Value.fromInterned((try mod.intern(.{ .float = .{
3013 return Value.fromInterned(try pt.intern(.{ .float = .{
29693014 .ty = float_type.toIntern(),
29703015 .storage = storage,
2971 } })));
3016 } }));
29723017}
29733018
29743019pub fn floatMul(
......@@ -2976,510 +3021,539 @@ pub fn floatMul(
29763021 rhs: Value,
29773022 float_type: Type,
29783023 arena: Allocator,
2979 mod: *Module,
3024 pt: Zcu.PerThread,
29803025) !Value {
3026 const mod = pt.zcu;
29813027 if (float_type.zigTypeTag(mod) == .Vector) {
29823028 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
29833029 const scalar_ty = float_type.scalarType(mod);
29843030 for (result_data, 0..) |*scalar, i| {
2985 const lhs_elem = try lhs.elemValue(mod, i);
2986 const rhs_elem = try rhs.elemValue(mod, i);
2987 scalar.* = (try floatMulScalar(lhs_elem, rhs_elem, scalar_ty, mod)).toIntern();
3031 const lhs_elem = try lhs.elemValue(pt, i);
3032 const rhs_elem = try rhs.elemValue(pt, i);
3033 scalar.* = (try floatMulScalar(lhs_elem, rhs_elem, scalar_ty, pt)).toIntern();
29883034 }
2989 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3035 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
29903036 .ty = float_type.toIntern(),
29913037 .storage = .{ .elems = result_data },
2992 } })));
3038 } }));
29933039 }
2994 return floatMulScalar(lhs, rhs, float_type, mod);
3040 return floatMulScalar(lhs, rhs, float_type, pt);
29953041}
29963042
29973043pub fn floatMulScalar(
29983044 lhs: Value,
29993045 rhs: Value,
30003046 float_type: Type,
3001 mod: *Module,
3047 pt: Zcu.PerThread,
30023048) !Value {
3049 const mod = pt.zcu;
30033050 const target = mod.getTarget();
30043051 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3005 16 => .{ .f16 = lhs.toFloat(f16, mod) * rhs.toFloat(f16, mod) },
3006 32 => .{ .f32 = lhs.toFloat(f32, mod) * rhs.toFloat(f32, mod) },
3007 64 => .{ .f64 = lhs.toFloat(f64, mod) * rhs.toFloat(f64, mod) },
3008 80 => .{ .f80 = lhs.toFloat(f80, mod) * rhs.toFloat(f80, mod) },
3009 128 => .{ .f128 = lhs.toFloat(f128, mod) * rhs.toFloat(f128, mod) },
3052 16 => .{ .f16 = lhs.toFloat(f16, pt) * rhs.toFloat(f16, pt) },
3053 32 => .{ .f32 = lhs.toFloat(f32, pt) * rhs.toFloat(f32, pt) },
3054 64 => .{ .f64 = lhs.toFloat(f64, pt) * rhs.toFloat(f64, pt) },
3055 80 => .{ .f80 = lhs.toFloat(f80, pt) * rhs.toFloat(f80, pt) },
3056 128 => .{ .f128 = lhs.toFloat(f128, pt) * rhs.toFloat(f128, pt) },
30103057 else => unreachable,
30113058 };
3012 return Value.fromInterned((try mod.intern(.{ .float = .{
3059 return Value.fromInterned(try pt.intern(.{ .float = .{
30133060 .ty = float_type.toIntern(),
30143061 .storage = storage,
3015 } })));
3062 } }));
30163063}
30173064
3018pub fn sqrt(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3019 if (float_type.zigTypeTag(mod) == .Vector) {
3020 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
3021 const scalar_ty = float_type.scalarType(mod);
3065pub fn sqrt(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3066 if (float_type.zigTypeTag(pt.zcu) == .Vector) {
3067 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(pt.zcu));
3068 const scalar_ty = float_type.scalarType(pt.zcu);
30223069 for (result_data, 0..) |*scalar, i| {
3023 const elem_val = try val.elemValue(mod, i);
3024 scalar.* = (try sqrtScalar(elem_val, scalar_ty, mod)).toIntern();
3070 const elem_val = try val.elemValue(pt, i);
3071 scalar.* = (try sqrtScalar(elem_val, scalar_ty, pt)).toIntern();
30253072 }
3026 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3073 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
30273074 .ty = float_type.toIntern(),
30283075 .storage = .{ .elems = result_data },
3029 } })));
3076 } }));
30303077 }
3031 return sqrtScalar(val, float_type, mod);
3078 return sqrtScalar(val, float_type, pt);
30323079}
30333080
3034pub fn sqrtScalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3081pub fn sqrtScalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3082 const mod = pt.zcu;
30353083 const target = mod.getTarget();
30363084 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3037 16 => .{ .f16 = @sqrt(val.toFloat(f16, mod)) },
3038 32 => .{ .f32 = @sqrt(val.toFloat(f32, mod)) },
3039 64 => .{ .f64 = @sqrt(val.toFloat(f64, mod)) },
3040 80 => .{ .f80 = @sqrt(val.toFloat(f80, mod)) },
3041 128 => .{ .f128 = @sqrt(val.toFloat(f128, mod)) },
3085 16 => .{ .f16 = @sqrt(val.toFloat(f16, pt)) },
3086 32 => .{ .f32 = @sqrt(val.toFloat(f32, pt)) },
3087 64 => .{ .f64 = @sqrt(val.toFloat(f64, pt)) },
3088 80 => .{ .f80 = @sqrt(val.toFloat(f80, pt)) },
3089 128 => .{ .f128 = @sqrt(val.toFloat(f128, pt)) },
30423090 else => unreachable,
30433091 };
3044 return Value.fromInterned((try mod.intern(.{ .float = .{
3092 return Value.fromInterned(try pt.intern(.{ .float = .{
30453093 .ty = float_type.toIntern(),
30463094 .storage = storage,
3047 } })));
3095 } }));
30483096}
30493097
3050pub fn sin(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3098pub fn sin(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3099 const mod = pt.zcu;
30513100 if (float_type.zigTypeTag(mod) == .Vector) {
30523101 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
30533102 const scalar_ty = float_type.scalarType(mod);
30543103 for (result_data, 0..) |*scalar, i| {
3055 const elem_val = try val.elemValue(mod, i);
3056 scalar.* = (try sinScalar(elem_val, scalar_ty, mod)).toIntern();
3104 const elem_val = try val.elemValue(pt, i);
3105 scalar.* = (try sinScalar(elem_val, scalar_ty, pt)).toIntern();
30573106 }
3058 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3107 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
30593108 .ty = float_type.toIntern(),
30603109 .storage = .{ .elems = result_data },
3061 } })));
3110 } }));
30623111 }
3063 return sinScalar(val, float_type, mod);
3112 return sinScalar(val, float_type, pt);
30643113}
30653114
3066pub fn sinScalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3115pub fn sinScalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3116 const mod = pt.zcu;
30673117 const target = mod.getTarget();
30683118 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3069 16 => .{ .f16 = @sin(val.toFloat(f16, mod)) },
3070 32 => .{ .f32 = @sin(val.toFloat(f32, mod)) },
3071 64 => .{ .f64 = @sin(val.toFloat(f64, mod)) },
3072 80 => .{ .f80 = @sin(val.toFloat(f80, mod)) },
3073 128 => .{ .f128 = @sin(val.toFloat(f128, mod)) },
3119 16 => .{ .f16 = @sin(val.toFloat(f16, pt)) },
3120 32 => .{ .f32 = @sin(val.toFloat(f32, pt)) },
3121 64 => .{ .f64 = @sin(val.toFloat(f64, pt)) },
3122 80 => .{ .f80 = @sin(val.toFloat(f80, pt)) },
3123 128 => .{ .f128 = @sin(val.toFloat(f128, pt)) },
30743124 else => unreachable,
30753125 };
3076 return Value.fromInterned((try mod.intern(.{ .float = .{
3126 return Value.fromInterned(try pt.intern(.{ .float = .{
30773127 .ty = float_type.toIntern(),
30783128 .storage = storage,
3079 } })));
3129 } }));
30803130}
30813131
3082pub fn cos(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3132pub fn cos(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3133 const mod = pt.zcu;
30833134 if (float_type.zigTypeTag(mod) == .Vector) {
30843135 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
30853136 const scalar_ty = float_type.scalarType(mod);
30863137 for (result_data, 0..) |*scalar, i| {
3087 const elem_val = try val.elemValue(mod, i);
3088 scalar.* = (try cosScalar(elem_val, scalar_ty, mod)).toIntern();
3138 const elem_val = try val.elemValue(pt, i);
3139 scalar.* = (try cosScalar(elem_val, scalar_ty, pt)).toIntern();
30893140 }
3090 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3141 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
30913142 .ty = float_type.toIntern(),
30923143 .storage = .{ .elems = result_data },
3093 } })));
3144 } }));
30943145 }
3095 return cosScalar(val, float_type, mod);
3146 return cosScalar(val, float_type, pt);
30963147}
30973148
3098pub fn cosScalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3149pub fn cosScalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3150 const mod = pt.zcu;
30993151 const target = mod.getTarget();
31003152 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3101 16 => .{ .f16 = @cos(val.toFloat(f16, mod)) },
3102 32 => .{ .f32 = @cos(val.toFloat(f32, mod)) },
3103 64 => .{ .f64 = @cos(val.toFloat(f64, mod)) },
3104 80 => .{ .f80 = @cos(val.toFloat(f80, mod)) },
3105 128 => .{ .f128 = @cos(val.toFloat(f128, mod)) },
3153 16 => .{ .f16 = @cos(val.toFloat(f16, pt)) },
3154 32 => .{ .f32 = @cos(val.toFloat(f32, pt)) },
3155 64 => .{ .f64 = @cos(val.toFloat(f64, pt)) },
3156 80 => .{ .f80 = @cos(val.toFloat(f80, pt)) },
3157 128 => .{ .f128 = @cos(val.toFloat(f128, pt)) },
31063158 else => unreachable,
31073159 };
3108 return Value.fromInterned((try mod.intern(.{ .float = .{
3160 return Value.fromInterned(try pt.intern(.{ .float = .{
31093161 .ty = float_type.toIntern(),
31103162 .storage = storage,
3111 } })));
3163 } }));
31123164}
31133165
3114pub fn tan(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3166pub fn tan(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3167 const mod = pt.zcu;
31153168 if (float_type.zigTypeTag(mod) == .Vector) {
31163169 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
31173170 const scalar_ty = float_type.scalarType(mod);
31183171 for (result_data, 0..) |*scalar, i| {
3119 const elem_val = try val.elemValue(mod, i);
3120 scalar.* = (try tanScalar(elem_val, scalar_ty, mod)).toIntern();
3172 const elem_val = try val.elemValue(pt, i);
3173 scalar.* = (try tanScalar(elem_val, scalar_ty, pt)).toIntern();
31213174 }
3122 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3175 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
31233176 .ty = float_type.toIntern(),
31243177 .storage = .{ .elems = result_data },
3125 } })));
3178 } }));
31263179 }
3127 return tanScalar(val, float_type, mod);
3180 return tanScalar(val, float_type, pt);
31283181}
31293182
3130pub fn tanScalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3183pub fn tanScalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3184 const mod = pt.zcu;
31313185 const target = mod.getTarget();
31323186 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3133 16 => .{ .f16 = @tan(val.toFloat(f16, mod)) },
3134 32 => .{ .f32 = @tan(val.toFloat(f32, mod)) },
3135 64 => .{ .f64 = @tan(val.toFloat(f64, mod)) },
3136 80 => .{ .f80 = @tan(val.toFloat(f80, mod)) },
3137 128 => .{ .f128 = @tan(val.toFloat(f128, mod)) },
3187 16 => .{ .f16 = @tan(val.toFloat(f16, pt)) },
3188 32 => .{ .f32 = @tan(val.toFloat(f32, pt)) },
3189 64 => .{ .f64 = @tan(val.toFloat(f64, pt)) },
3190 80 => .{ .f80 = @tan(val.toFloat(f80, pt)) },
3191 128 => .{ .f128 = @tan(val.toFloat(f128, pt)) },
31383192 else => unreachable,
31393193 };
3140 return Value.fromInterned((try mod.intern(.{ .float = .{
3194 return Value.fromInterned(try pt.intern(.{ .float = .{
31413195 .ty = float_type.toIntern(),
31423196 .storage = storage,
3143 } })));
3197 } }));
31443198}
31453199
3146pub fn exp(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3200pub fn exp(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3201 const mod = pt.zcu;
31473202 if (float_type.zigTypeTag(mod) == .Vector) {
31483203 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
31493204 const scalar_ty = float_type.scalarType(mod);
31503205 for (result_data, 0..) |*scalar, i| {
3151 const elem_val = try val.elemValue(mod, i);
3152 scalar.* = (try expScalar(elem_val, scalar_ty, mod)).toIntern();
3206 const elem_val = try val.elemValue(pt, i);
3207 scalar.* = (try expScalar(elem_val, scalar_ty, pt)).toIntern();
31533208 }
3154 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3209 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
31553210 .ty = float_type.toIntern(),
31563211 .storage = .{ .elems = result_data },
3157 } })));
3212 } }));
31583213 }
3159 return expScalar(val, float_type, mod);
3214 return expScalar(val, float_type, pt);
31603215}
31613216
3162pub fn expScalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3217pub fn expScalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3218 const mod = pt.zcu;
31633219 const target = mod.getTarget();
31643220 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3165 16 => .{ .f16 = @exp(val.toFloat(f16, mod)) },
3166 32 => .{ .f32 = @exp(val.toFloat(f32, mod)) },
3167 64 => .{ .f64 = @exp(val.toFloat(f64, mod)) },
3168 80 => .{ .f80 = @exp(val.toFloat(f80, mod)) },
3169 128 => .{ .f128 = @exp(val.toFloat(f128, mod)) },
3221 16 => .{ .f16 = @exp(val.toFloat(f16, pt)) },
3222 32 => .{ .f32 = @exp(val.toFloat(f32, pt)) },
3223 64 => .{ .f64 = @exp(val.toFloat(f64, pt)) },
3224 80 => .{ .f80 = @exp(val.toFloat(f80, pt)) },
3225 128 => .{ .f128 = @exp(val.toFloat(f128, pt)) },
31703226 else => unreachable,
31713227 };
3172 return Value.fromInterned((try mod.intern(.{ .float = .{
3228 return Value.fromInterned(try pt.intern(.{ .float = .{
31733229 .ty = float_type.toIntern(),
31743230 .storage = storage,
3175 } })));
3231 } }));
31763232}
31773233
3178pub fn exp2(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3234pub fn exp2(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3235 const mod = pt.zcu;
31793236 if (float_type.zigTypeTag(mod) == .Vector) {
31803237 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
31813238 const scalar_ty = float_type.scalarType(mod);
31823239 for (result_data, 0..) |*scalar, i| {
3183 const elem_val = try val.elemValue(mod, i);
3184 scalar.* = (try exp2Scalar(elem_val, scalar_ty, mod)).toIntern();
3240 const elem_val = try val.elemValue(pt, i);
3241 scalar.* = (try exp2Scalar(elem_val, scalar_ty, pt)).toIntern();
31853242 }
3186 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3243 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
31873244 .ty = float_type.toIntern(),
31883245 .storage = .{ .elems = result_data },
3189 } })));
3246 } }));
31903247 }
3191 return exp2Scalar(val, float_type, mod);
3248 return exp2Scalar(val, float_type, pt);
31923249}
31933250
3194pub fn exp2Scalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3251pub fn exp2Scalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3252 const mod = pt.zcu;
31953253 const target = mod.getTarget();
31963254 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3197 16 => .{ .f16 = @exp2(val.toFloat(f16, mod)) },
3198 32 => .{ .f32 = @exp2(val.toFloat(f32, mod)) },
3199 64 => .{ .f64 = @exp2(val.toFloat(f64, mod)) },
3200 80 => .{ .f80 = @exp2(val.toFloat(f80, mod)) },
3201 128 => .{ .f128 = @exp2(val.toFloat(f128, mod)) },
3255 16 => .{ .f16 = @exp2(val.toFloat(f16, pt)) },
3256 32 => .{ .f32 = @exp2(val.toFloat(f32, pt)) },
3257 64 => .{ .f64 = @exp2(val.toFloat(f64, pt)) },
3258 80 => .{ .f80 = @exp2(val.toFloat(f80, pt)) },
3259 128 => .{ .f128 = @exp2(val.toFloat(f128, pt)) },
32023260 else => unreachable,
32033261 };
3204 return Value.fromInterned((try mod.intern(.{ .float = .{
3262 return Value.fromInterned(try pt.intern(.{ .float = .{
32053263 .ty = float_type.toIntern(),
32063264 .storage = storage,
3207 } })));
3265 } }));
32083266}
32093267
3210pub fn log(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3268pub fn log(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3269 const mod = pt.zcu;
32113270 if (float_type.zigTypeTag(mod) == .Vector) {
32123271 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
32133272 const scalar_ty = float_type.scalarType(mod);
32143273 for (result_data, 0..) |*scalar, i| {
3215 const elem_val = try val.elemValue(mod, i);
3216 scalar.* = (try logScalar(elem_val, scalar_ty, mod)).toIntern();
3274 const elem_val = try val.elemValue(pt, i);
3275 scalar.* = (try logScalar(elem_val, scalar_ty, pt)).toIntern();
32173276 }
3218 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3277 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
32193278 .ty = float_type.toIntern(),
32203279 .storage = .{ .elems = result_data },
3221 } })));
3280 } }));
32223281 }
3223 return logScalar(val, float_type, mod);
3282 return logScalar(val, float_type, pt);
32243283}
32253284
3226pub fn logScalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3285pub fn logScalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3286 const mod = pt.zcu;
32273287 const target = mod.getTarget();
32283288 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3229 16 => .{ .f16 = @log(val.toFloat(f16, mod)) },
3230 32 => .{ .f32 = @log(val.toFloat(f32, mod)) },
3231 64 => .{ .f64 = @log(val.toFloat(f64, mod)) },
3232 80 => .{ .f80 = @log(val.toFloat(f80, mod)) },
3233 128 => .{ .f128 = @log(val.toFloat(f128, mod)) },
3289 16 => .{ .f16 = @log(val.toFloat(f16, pt)) },
3290 32 => .{ .f32 = @log(val.toFloat(f32, pt)) },
3291 64 => .{ .f64 = @log(val.toFloat(f64, pt)) },
3292 80 => .{ .f80 = @log(val.toFloat(f80, pt)) },
3293 128 => .{ .f128 = @log(val.toFloat(f128, pt)) },
32343294 else => unreachable,
32353295 };
3236 return Value.fromInterned((try mod.intern(.{ .float = .{
3296 return Value.fromInterned(try pt.intern(.{ .float = .{
32373297 .ty = float_type.toIntern(),
32383298 .storage = storage,
3239 } })));
3299 } }));
32403300}
32413301
3242pub fn log2(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3302pub fn log2(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3303 const mod = pt.zcu;
32433304 if (float_type.zigTypeTag(mod) == .Vector) {
32443305 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
32453306 const scalar_ty = float_type.scalarType(mod);
32463307 for (result_data, 0..) |*scalar, i| {
3247 const elem_val = try val.elemValue(mod, i);
3248 scalar.* = (try log2Scalar(elem_val, scalar_ty, mod)).toIntern();
3308 const elem_val = try val.elemValue(pt, i);
3309 scalar.* = (try log2Scalar(elem_val, scalar_ty, pt)).toIntern();
32493310 }
3250 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3311 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
32513312 .ty = float_type.toIntern(),
32523313 .storage = .{ .elems = result_data },
3253 } })));
3314 } }));
32543315 }
3255 return log2Scalar(val, float_type, mod);
3316 return log2Scalar(val, float_type, pt);
32563317}
32573318
3258pub fn log2Scalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3319pub fn log2Scalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3320 const mod = pt.zcu;
32593321 const target = mod.getTarget();
32603322 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3261 16 => .{ .f16 = @log2(val.toFloat(f16, mod)) },
3262 32 => .{ .f32 = @log2(val.toFloat(f32, mod)) },
3263 64 => .{ .f64 = @log2(val.toFloat(f64, mod)) },
3264 80 => .{ .f80 = @log2(val.toFloat(f80, mod)) },
3265 128 => .{ .f128 = @log2(val.toFloat(f128, mod)) },
3323 16 => .{ .f16 = @log2(val.toFloat(f16, pt)) },
3324 32 => .{ .f32 = @log2(val.toFloat(f32, pt)) },
3325 64 => .{ .f64 = @log2(val.toFloat(f64, pt)) },
3326 80 => .{ .f80 = @log2(val.toFloat(f80, pt)) },
3327 128 => .{ .f128 = @log2(val.toFloat(f128, pt)) },
32663328 else => unreachable,
32673329 };
3268 return Value.fromInterned((try mod.intern(.{ .float = .{
3330 return Value.fromInterned(try pt.intern(.{ .float = .{
32693331 .ty = float_type.toIntern(),
32703332 .storage = storage,
3271 } })));
3333 } }));
32723334}
32733335
3274pub fn log10(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3336pub fn log10(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3337 const mod = pt.zcu;
32753338 if (float_type.zigTypeTag(mod) == .Vector) {
32763339 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
32773340 const scalar_ty = float_type.scalarType(mod);
32783341 for (result_data, 0..) |*scalar, i| {
3279 const elem_val = try val.elemValue(mod, i);
3280 scalar.* = (try log10Scalar(elem_val, scalar_ty, mod)).toIntern();
3342 const elem_val = try val.elemValue(pt, i);
3343 scalar.* = (try log10Scalar(elem_val, scalar_ty, pt)).toIntern();
32813344 }
3282 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3345 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
32833346 .ty = float_type.toIntern(),
32843347 .storage = .{ .elems = result_data },
3285 } })));
3348 } }));
32863349 }
3287 return log10Scalar(val, float_type, mod);
3350 return log10Scalar(val, float_type, pt);
32883351}
32893352
3290pub fn log10Scalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3353pub fn log10Scalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3354 const mod = pt.zcu;
32913355 const target = mod.getTarget();
32923356 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3293 16 => .{ .f16 = @log10(val.toFloat(f16, mod)) },
3294 32 => .{ .f32 = @log10(val.toFloat(f32, mod)) },
3295 64 => .{ .f64 = @log10(val.toFloat(f64, mod)) },
3296 80 => .{ .f80 = @log10(val.toFloat(f80, mod)) },
3297 128 => .{ .f128 = @log10(val.toFloat(f128, mod)) },
3357 16 => .{ .f16 = @log10(val.toFloat(f16, pt)) },
3358 32 => .{ .f32 = @log10(val.toFloat(f32, pt)) },
3359 64 => .{ .f64 = @log10(val.toFloat(f64, pt)) },
3360 80 => .{ .f80 = @log10(val.toFloat(f80, pt)) },
3361 128 => .{ .f128 = @log10(val.toFloat(f128, pt)) },
32983362 else => unreachable,
32993363 };
3300 return Value.fromInterned((try mod.intern(.{ .float = .{
3364 return Value.fromInterned(try pt.intern(.{ .float = .{
33013365 .ty = float_type.toIntern(),
33023366 .storage = storage,
3303 } })));
3367 } }));
33043368}
33053369
3306pub fn abs(val: Value, ty: Type, arena: Allocator, mod: *Module) !Value {
3370pub fn abs(val: Value, ty: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3371 const mod = pt.zcu;
33073372 if (ty.zigTypeTag(mod) == .Vector) {
33083373 const result_data = try arena.alloc(InternPool.Index, ty.vectorLen(mod));
33093374 const scalar_ty = ty.scalarType(mod);
33103375 for (result_data, 0..) |*scalar, i| {
3311 const elem_val = try val.elemValue(mod, i);
3312 scalar.* = (try absScalar(elem_val, scalar_ty, mod, arena)).toIntern();
3376 const elem_val = try val.elemValue(pt, i);
3377 scalar.* = (try absScalar(elem_val, scalar_ty, pt, arena)).toIntern();
33133378 }
3314 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3379 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
33153380 .ty = ty.toIntern(),
33163381 .storage = .{ .elems = result_data },
3317 } })));
3382 } }));
33183383 }
3319 return absScalar(val, ty, mod, arena);
3384 return absScalar(val, ty, pt, arena);
33203385}
33213386
3322pub fn absScalar(val: Value, ty: Type, mod: *Module, arena: Allocator) Allocator.Error!Value {
3387pub fn absScalar(val: Value, ty: Type, pt: Zcu.PerThread, arena: Allocator) Allocator.Error!Value {
3388 const mod = pt.zcu;
33233389 switch (ty.zigTypeTag(mod)) {
33243390 .Int => {
33253391 var buffer: Value.BigIntSpace = undefined;
3326 var operand_bigint = try val.toBigInt(&buffer, mod).toManaged(arena);
3392 var operand_bigint = try val.toBigInt(&buffer, pt).toManaged(arena);
33273393 operand_bigint.abs();
33283394
3329 return mod.intValue_big(try ty.toUnsigned(mod), operand_bigint.toConst());
3395 return pt.intValue_big(try ty.toUnsigned(pt), operand_bigint.toConst());
33303396 },
33313397 .ComptimeInt => {
33323398 var buffer: Value.BigIntSpace = undefined;
3333 var operand_bigint = try val.toBigInt(&buffer, mod).toManaged(arena);
3399 var operand_bigint = try val.toBigInt(&buffer, pt).toManaged(arena);
33343400 operand_bigint.abs();
33353401
3336 return mod.intValue_big(ty, operand_bigint.toConst());
3402 return pt.intValue_big(ty, operand_bigint.toConst());
33373403 },
33383404 .ComptimeFloat, .Float => {
33393405 const target = mod.getTarget();
33403406 const storage: InternPool.Key.Float.Storage = switch (ty.floatBits(target)) {
3341 16 => .{ .f16 = @abs(val.toFloat(f16, mod)) },
3342 32 => .{ .f32 = @abs(val.toFloat(f32, mod)) },
3343 64 => .{ .f64 = @abs(val.toFloat(f64, mod)) },
3344 80 => .{ .f80 = @abs(val.toFloat(f80, mod)) },
3345 128 => .{ .f128 = @abs(val.toFloat(f128, mod)) },
3407 16 => .{ .f16 = @abs(val.toFloat(f16, pt)) },
3408 32 => .{ .f32 = @abs(val.toFloat(f32, pt)) },
3409 64 => .{ .f64 = @abs(val.toFloat(f64, pt)) },
3410 80 => .{ .f80 = @abs(val.toFloat(f80, pt)) },
3411 128 => .{ .f128 = @abs(val.toFloat(f128, pt)) },
33463412 else => unreachable,
33473413 };
3348 return Value.fromInterned((try mod.intern(.{ .float = .{
3414 return Value.fromInterned(try pt.intern(.{ .float = .{
33493415 .ty = ty.toIntern(),
33503416 .storage = storage,
3351 } })));
3417 } }));
33523418 },
33533419 else => unreachable,
33543420 }
33553421}
33563422
3357pub fn floor(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3423pub fn floor(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3424 const mod = pt.zcu;
33583425 if (float_type.zigTypeTag(mod) == .Vector) {
33593426 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
33603427 const scalar_ty = float_type.scalarType(mod);
33613428 for (result_data, 0..) |*scalar, i| {
3362 const elem_val = try val.elemValue(mod, i);
3363 scalar.* = (try floorScalar(elem_val, scalar_ty, mod)).toIntern();
3429 const elem_val = try val.elemValue(pt, i);
3430 scalar.* = (try floorScalar(elem_val, scalar_ty, pt)).toIntern();
33643431 }
3365 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3432 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
33663433 .ty = float_type.toIntern(),
33673434 .storage = .{ .elems = result_data },
3368 } })));
3435 } }));
33693436 }
3370 return floorScalar(val, float_type, mod);
3437 return floorScalar(val, float_type, pt);
33713438}
33723439
3373pub fn floorScalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3440pub fn floorScalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3441 const mod = pt.zcu;
33743442 const target = mod.getTarget();
33753443 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3376 16 => .{ .f16 = @floor(val.toFloat(f16, mod)) },
3377 32 => .{ .f32 = @floor(val.toFloat(f32, mod)) },
3378 64 => .{ .f64 = @floor(val.toFloat(f64, mod)) },
3379 80 => .{ .f80 = @floor(val.toFloat(f80, mod)) },
3380 128 => .{ .f128 = @floor(val.toFloat(f128, mod)) },
3444 16 => .{ .f16 = @floor(val.toFloat(f16, pt)) },
3445 32 => .{ .f32 = @floor(val.toFloat(f32, pt)) },
3446 64 => .{ .f64 = @floor(val.toFloat(f64, pt)) },
3447 80 => .{ .f80 = @floor(val.toFloat(f80, pt)) },
3448 128 => .{ .f128 = @floor(val.toFloat(f128, pt)) },
33813449 else => unreachable,
33823450 };
3383 return Value.fromInterned((try mod.intern(.{ .float = .{
3451 return Value.fromInterned(try pt.intern(.{ .float = .{
33843452 .ty = float_type.toIntern(),
33853453 .storage = storage,
3386 } })));
3454 } }));
33873455}
33883456
3389pub fn ceil(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3457pub fn ceil(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3458 const mod = pt.zcu;
33903459 if (float_type.zigTypeTag(mod) == .Vector) {
33913460 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
33923461 const scalar_ty = float_type.scalarType(mod);
33933462 for (result_data, 0..) |*scalar, i| {
3394 const elem_val = try val.elemValue(mod, i);
3395 scalar.* = (try ceilScalar(elem_val, scalar_ty, mod)).toIntern();
3463 const elem_val = try val.elemValue(pt, i);
3464 scalar.* = (try ceilScalar(elem_val, scalar_ty, pt)).toIntern();
33963465 }
3397 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3466 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
33983467 .ty = float_type.toIntern(),
33993468 .storage = .{ .elems = result_data },
3400 } })));
3469 } }));
34013470 }
3402 return ceilScalar(val, float_type, mod);
3471 return ceilScalar(val, float_type, pt);
34033472}
34043473
3405pub fn ceilScalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3474pub fn ceilScalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3475 const mod = pt.zcu;
34063476 const target = mod.getTarget();
34073477 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3408 16 => .{ .f16 = @ceil(val.toFloat(f16, mod)) },
3409 32 => .{ .f32 = @ceil(val.toFloat(f32, mod)) },
3410 64 => .{ .f64 = @ceil(val.toFloat(f64, mod)) },
3411 80 => .{ .f80 = @ceil(val.toFloat(f80, mod)) },
3412 128 => .{ .f128 = @ceil(val.toFloat(f128, mod)) },
3478 16 => .{ .f16 = @ceil(val.toFloat(f16, pt)) },
3479 32 => .{ .f32 = @ceil(val.toFloat(f32, pt)) },
3480 64 => .{ .f64 = @ceil(val.toFloat(f64, pt)) },
3481 80 => .{ .f80 = @ceil(val.toFloat(f80, pt)) },
3482 128 => .{ .f128 = @ceil(val.toFloat(f128, pt)) },
34133483 else => unreachable,
34143484 };
3415 return Value.fromInterned((try mod.intern(.{ .float = .{
3485 return Value.fromInterned(try pt.intern(.{ .float = .{
34163486 .ty = float_type.toIntern(),
34173487 .storage = storage,
3418 } })));
3488 } }));
34193489}
34203490
3421pub fn round(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3491pub fn round(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3492 const mod = pt.zcu;
34223493 if (float_type.zigTypeTag(mod) == .Vector) {
34233494 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
34243495 const scalar_ty = float_type.scalarType(mod);
34253496 for (result_data, 0..) |*scalar, i| {
3426 const elem_val = try val.elemValue(mod, i);
3427 scalar.* = (try roundScalar(elem_val, scalar_ty, mod)).toIntern();
3497 const elem_val = try val.elemValue(pt, i);
3498 scalar.* = (try roundScalar(elem_val, scalar_ty, pt)).toIntern();
34283499 }
3429 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3500 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
34303501 .ty = float_type.toIntern(),
34313502 .storage = .{ .elems = result_data },
3432 } })));
3503 } }));
34333504 }
3434 return roundScalar(val, float_type, mod);
3505 return roundScalar(val, float_type, pt);
34353506}
34363507
3437pub fn roundScalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3508pub fn roundScalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3509 const mod = pt.zcu;
34383510 const target = mod.getTarget();
34393511 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3440 16 => .{ .f16 = @round(val.toFloat(f16, mod)) },
3441 32 => .{ .f32 = @round(val.toFloat(f32, mod)) },
3442 64 => .{ .f64 = @round(val.toFloat(f64, mod)) },
3443 80 => .{ .f80 = @round(val.toFloat(f80, mod)) },
3444 128 => .{ .f128 = @round(val.toFloat(f128, mod)) },
3512 16 => .{ .f16 = @round(val.toFloat(f16, pt)) },
3513 32 => .{ .f32 = @round(val.toFloat(f32, pt)) },
3514 64 => .{ .f64 = @round(val.toFloat(f64, pt)) },
3515 80 => .{ .f80 = @round(val.toFloat(f80, pt)) },
3516 128 => .{ .f128 = @round(val.toFloat(f128, pt)) },
34453517 else => unreachable,
34463518 };
3447 return Value.fromInterned((try mod.intern(.{ .float = .{
3519 return Value.fromInterned(try pt.intern(.{ .float = .{
34483520 .ty = float_type.toIntern(),
34493521 .storage = storage,
3450 } })));
3522 } }));
34513523}
34523524
3453pub fn trunc(val: Value, float_type: Type, arena: Allocator, mod: *Module) !Value {
3525pub fn trunc(val: Value, float_type: Type, arena: Allocator, pt: Zcu.PerThread) !Value {
3526 const mod = pt.zcu;
34543527 if (float_type.zigTypeTag(mod) == .Vector) {
34553528 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
34563529 const scalar_ty = float_type.scalarType(mod);
34573530 for (result_data, 0..) |*scalar, i| {
3458 const elem_val = try val.elemValue(mod, i);
3459 scalar.* = (try truncScalar(elem_val, scalar_ty, mod)).toIntern();
3531 const elem_val = try val.elemValue(pt, i);
3532 scalar.* = (try truncScalar(elem_val, scalar_ty, pt)).toIntern();
34603533 }
3461 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3534 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
34623535 .ty = float_type.toIntern(),
34633536 .storage = .{ .elems = result_data },
3464 } })));
3537 } }));
34653538 }
3466 return truncScalar(val, float_type, mod);
3539 return truncScalar(val, float_type, pt);
34673540}
34683541
3469pub fn truncScalar(val: Value, float_type: Type, mod: *Module) Allocator.Error!Value {
3542pub fn truncScalar(val: Value, float_type: Type, pt: Zcu.PerThread) Allocator.Error!Value {
3543 const mod = pt.zcu;
34703544 const target = mod.getTarget();
34713545 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3472 16 => .{ .f16 = @trunc(val.toFloat(f16, mod)) },
3473 32 => .{ .f32 = @trunc(val.toFloat(f32, mod)) },
3474 64 => .{ .f64 = @trunc(val.toFloat(f64, mod)) },
3475 80 => .{ .f80 = @trunc(val.toFloat(f80, mod)) },
3476 128 => .{ .f128 = @trunc(val.toFloat(f128, mod)) },
3546 16 => .{ .f16 = @trunc(val.toFloat(f16, pt)) },
3547 32 => .{ .f32 = @trunc(val.toFloat(f32, pt)) },
3548 64 => .{ .f64 = @trunc(val.toFloat(f64, pt)) },
3549 80 => .{ .f80 = @trunc(val.toFloat(f80, pt)) },
3550 128 => .{ .f128 = @trunc(val.toFloat(f128, pt)) },
34773551 else => unreachable,
34783552 };
3479 return Value.fromInterned((try mod.intern(.{ .float = .{
3553 return Value.fromInterned(try pt.intern(.{ .float = .{
34803554 .ty = float_type.toIntern(),
34813555 .storage = storage,
3482 } })));
3556 } }));
34833557}
34843558
34853559pub fn mulAdd(
......@@ -3488,23 +3562,24 @@ pub fn mulAdd(
34883562 mulend2: Value,
34893563 addend: Value,
34903564 arena: Allocator,
3491 mod: *Module,
3565 pt: Zcu.PerThread,
34923566) !Value {
3567 const mod = pt.zcu;
34933568 if (float_type.zigTypeTag(mod) == .Vector) {
34943569 const result_data = try arena.alloc(InternPool.Index, float_type.vectorLen(mod));
34953570 const scalar_ty = float_type.scalarType(mod);
34963571 for (result_data, 0..) |*scalar, i| {
3497 const mulend1_elem = try mulend1.elemValue(mod, i);
3498 const mulend2_elem = try mulend2.elemValue(mod, i);
3499 const addend_elem = try addend.elemValue(mod, i);
3500 scalar.* = (try mulAddScalar(scalar_ty, mulend1_elem, mulend2_elem, addend_elem, mod)).toIntern();
3572 const mulend1_elem = try mulend1.elemValue(pt, i);
3573 const mulend2_elem = try mulend2.elemValue(pt, i);
3574 const addend_elem = try addend.elemValue(pt, i);
3575 scalar.* = (try mulAddScalar(scalar_ty, mulend1_elem, mulend2_elem, addend_elem, pt)).toIntern();
35013576 }
3502 return Value.fromInterned((try mod.intern(.{ .aggregate = .{
3577 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
35033578 .ty = float_type.toIntern(),
35043579 .storage = .{ .elems = result_data },
3505 } })));
3580 } }));
35063581 }
3507 return mulAddScalar(float_type, mulend1, mulend2, addend, mod);
3582 return mulAddScalar(float_type, mulend1, mulend2, addend, pt);
35083583}
35093584
35103585pub fn mulAddScalar(
......@@ -3512,32 +3587,33 @@ pub fn mulAddScalar(
35123587 mulend1: Value,
35133588 mulend2: Value,
35143589 addend: Value,
3515 mod: *Module,
3590 pt: Zcu.PerThread,
35163591) Allocator.Error!Value {
3592 const mod = pt.zcu;
35173593 const target = mod.getTarget();
35183594 const storage: InternPool.Key.Float.Storage = switch (float_type.floatBits(target)) {
3519 16 => .{ .f16 = @mulAdd(f16, mulend1.toFloat(f16, mod), mulend2.toFloat(f16, mod), addend.toFloat(f16, mod)) },
3520 32 => .{ .f32 = @mulAdd(f32, mulend1.toFloat(f32, mod), mulend2.toFloat(f32, mod), addend.toFloat(f32, mod)) },
3521 64 => .{ .f64 = @mulAdd(f64, mulend1.toFloat(f64, mod), mulend2.toFloat(f64, mod), addend.toFloat(f64, mod)) },
3522 80 => .{ .f80 = @mulAdd(f80, mulend1.toFloat(f80, mod), mulend2.toFloat(f80, mod), addend.toFloat(f80, mod)) },
3523 128 => .{ .f128 = @mulAdd(f128, mulend1.toFloat(f128, mod), mulend2.toFloat(f128, mod), addend.toFloat(f128, mod)) },
3595 16 => .{ .f16 = @mulAdd(f16, mulend1.toFloat(f16, pt), mulend2.toFloat(f16, pt), addend.toFloat(f16, pt)) },
3596 32 => .{ .f32 = @mulAdd(f32, mulend1.toFloat(f32, pt), mulend2.toFloat(f32, pt), addend.toFloat(f32, pt)) },
3597 64 => .{ .f64 = @mulAdd(f64, mulend1.toFloat(f64, pt), mulend2.toFloat(f64, pt), addend.toFloat(f64, pt)) },
3598 80 => .{ .f80 = @mulAdd(f80, mulend1.toFloat(f80, pt), mulend2.toFloat(f80, pt), addend.toFloat(f80, pt)) },
3599 128 => .{ .f128 = @mulAdd(f128, mulend1.toFloat(f128, pt), mulend2.toFloat(f128, pt), addend.toFloat(f128, pt)) },
35243600 else => unreachable,
35253601 };
3526 return Value.fromInterned((try mod.intern(.{ .float = .{
3602 return Value.fromInterned(try pt.intern(.{ .float = .{
35273603 .ty = float_type.toIntern(),
35283604 .storage = storage,
3529 } })));
3605 } }));
35303606}
35313607
35323608/// If the value is represented in-memory as a series of bytes that all
35333609/// have the same value, return that byte value, otherwise null.
3534pub fn hasRepeatedByteRepr(val: Value, ty: Type, mod: *Module) !?u8 {
3535 const abi_size = std.math.cast(usize, ty.abiSize(mod)) orelse return null;
3610pub fn hasRepeatedByteRepr(val: Value, ty: Type, pt: Zcu.PerThread) !?u8 {
3611 const abi_size = std.math.cast(usize, ty.abiSize(pt)) orelse return null;
35363612 assert(abi_size >= 1);
3537 const byte_buffer = try mod.gpa.alloc(u8, abi_size);
3538 defer mod.gpa.free(byte_buffer);
3613 const byte_buffer = try pt.zcu.gpa.alloc(u8, abi_size);
3614 defer pt.zcu.gpa.free(byte_buffer);
35393615
3540 writeToMemory(val, ty, mod, byte_buffer) catch |err| switch (err) {
3616 writeToMemory(val, ty, pt, byte_buffer) catch |err| switch (err) {
35413617 error.OutOfMemory => return error.OutOfMemory,
35423618 error.ReinterpretDeclRef => return null,
35433619 // TODO: The writeToMemory function was originally created for the purpose
......@@ -3567,13 +3643,13 @@ pub fn typeOf(val: Value, zcu: *const Zcu) Type {
35673643/// If `val` is not undef, the bounds are both `val`.
35683644/// If `val` is undef and has a fixed-width type, the bounds are the bounds of the type.
35693645/// If `val` is undef and is a `comptime_int`, returns null.
3570pub fn intValueBounds(val: Value, mod: *Module) !?[2]Value {
3571 if (!val.isUndef(mod)) return .{ val, val };
3572 const ty = mod.intern_pool.typeOf(val.toIntern());
3646pub fn intValueBounds(val: Value, pt: Zcu.PerThread) !?[2]Value {
3647 if (!val.isUndef(pt.zcu)) return .{ val, val };
3648 const ty = pt.zcu.intern_pool.typeOf(val.toIntern());
35733649 if (ty == .comptime_int_type) return null;
35743650 return .{
3575 try Type.fromInterned(ty).minInt(mod, Type.fromInterned(ty)),
3576 try Type.fromInterned(ty).maxInt(mod, Type.fromInterned(ty)),
3651 try Type.fromInterned(ty).minInt(pt, Type.fromInterned(ty)),
3652 try Type.fromInterned(ty).maxInt(pt, Type.fromInterned(ty)),
35773653 };
35783654}
35793655
......@@ -3604,14 +3680,15 @@ pub const RuntimeIndex = InternPool.RuntimeIndex;
36043680/// `parent_ptr` must be a single-pointer to some optional.
36053681/// Returns a pointer to the payload of the optional.
36063682/// May perform type resolution.
3607pub fn ptrOptPayload(parent_ptr: Value, zcu: *Zcu) !Value {
3683pub fn ptrOptPayload(parent_ptr: Value, pt: Zcu.PerThread) !Value {
3684 const zcu = pt.zcu;
36083685 const parent_ptr_ty = parent_ptr.typeOf(zcu);
36093686 const opt_ty = parent_ptr_ty.childType(zcu);
36103687
36113688 assert(parent_ptr_ty.ptrSize(zcu) == .One);
36123689 assert(opt_ty.zigTypeTag(zcu) == .Optional);
36133690
3614 const result_ty = try zcu.ptrTypeSema(info: {
3691 const result_ty = try pt.ptrTypeSema(info: {
36153692 var new = parent_ptr_ty.ptrInfo(zcu);
36163693 // We can correctly preserve alignment `.none`, since an optional has the same
36173694 // natural alignment as its child type.
......@@ -3619,15 +3696,15 @@ pub fn ptrOptPayload(parent_ptr: Value, zcu: *Zcu) !Value {
36193696 break :info new;
36203697 });
36213698
3622 if (parent_ptr.isUndef(zcu)) return zcu.undefValue(result_ty);
3699 if (parent_ptr.isUndef(zcu)) return pt.undefValue(result_ty);
36233700
36243701 if (opt_ty.isPtrLikeOptional(zcu)) {
36253702 // Just reinterpret the pointer, since the layout is well-defined
3626 return zcu.getCoerced(parent_ptr, result_ty);
3703 return pt.getCoerced(parent_ptr, result_ty);
36273704 }
36283705
3629 const base_ptr = try parent_ptr.canonicalizeBasePtr(.One, opt_ty, zcu);
3630 return Value.fromInterned(try zcu.intern(.{ .ptr = .{
3706 const base_ptr = try parent_ptr.canonicalizeBasePtr(.One, opt_ty, pt);
3707 return Value.fromInterned(try pt.intern(.{ .ptr = .{
36313708 .ty = result_ty.toIntern(),
36323709 .base_addr = .{ .opt_payload = base_ptr.toIntern() },
36333710 .byte_offset = 0,
......@@ -3637,14 +3714,15 @@ pub fn ptrOptPayload(parent_ptr: Value, zcu: *Zcu) !Value {
36373714/// `parent_ptr` must be a single-pointer to some error union.
36383715/// Returns a pointer to the payload of the error union.
36393716/// May perform type resolution.
3640pub fn ptrEuPayload(parent_ptr: Value, zcu: *Zcu) !Value {
3717pub fn ptrEuPayload(parent_ptr: Value, pt: Zcu.PerThread) !Value {
3718 const zcu = pt.zcu;
36413719 const parent_ptr_ty = parent_ptr.typeOf(zcu);
36423720 const eu_ty = parent_ptr_ty.childType(zcu);
36433721
36443722 assert(parent_ptr_ty.ptrSize(zcu) == .One);
36453723 assert(eu_ty.zigTypeTag(zcu) == .ErrorUnion);
36463724
3647 const result_ty = try zcu.ptrTypeSema(info: {
3725 const result_ty = try pt.ptrTypeSema(info: {
36483726 var new = parent_ptr_ty.ptrInfo(zcu);
36493727 // We can correctly preserve alignment `.none`, since an error union has a
36503728 // natural alignment greater than or equal to that of its payload type.
......@@ -3652,10 +3730,10 @@ pub fn ptrEuPayload(parent_ptr: Value, zcu: *Zcu) !Value {
36523730 break :info new;
36533731 });
36543732
3655 if (parent_ptr.isUndef(zcu)) return zcu.undefValue(result_ty);
3733 if (parent_ptr.isUndef(zcu)) return pt.undefValue(result_ty);
36563734
3657 const base_ptr = try parent_ptr.canonicalizeBasePtr(.One, eu_ty, zcu);
3658 return Value.fromInterned(try zcu.intern(.{ .ptr = .{
3735 const base_ptr = try parent_ptr.canonicalizeBasePtr(.One, eu_ty, pt);
3736 return Value.fromInterned(try pt.intern(.{ .ptr = .{
36593737 .ty = result_ty.toIntern(),
36603738 .base_addr = .{ .eu_payload = base_ptr.toIntern() },
36613739 .byte_offset = 0,
......@@ -3666,7 +3744,8 @@ pub fn ptrEuPayload(parent_ptr: Value, zcu: *Zcu) !Value {
36663744/// Returns a pointer to the aggregate field at the specified index.
36673745/// For slices, uses `slice_ptr_index` and `slice_len_index`.
36683746/// May perform type resolution.
3669pub fn ptrField(parent_ptr: Value, field_idx: u32, zcu: *Zcu) !Value {
3747pub fn ptrField(parent_ptr: Value, field_idx: u32, pt: Zcu.PerThread) !Value {
3748 const zcu = pt.zcu;
36703749 const parent_ptr_ty = parent_ptr.typeOf(zcu);
36713750 const aggregate_ty = parent_ptr_ty.childType(zcu);
36723751
......@@ -3679,39 +3758,39 @@ pub fn ptrField(parent_ptr: Value, field_idx: u32, zcu: *Zcu) !Value {
36793758 .Struct => field: {
36803759 const field_ty = aggregate_ty.structFieldType(field_idx, zcu);
36813760 switch (aggregate_ty.containerLayout(zcu)) {
3682 .auto => break :field .{ field_ty, try aggregate_ty.structFieldAlignAdvanced(@intCast(field_idx), zcu, .sema) },
3761 .auto => break :field .{ field_ty, try aggregate_ty.structFieldAlignAdvanced(@intCast(field_idx), pt, .sema) },
36833762 .@"extern" => {
36843763 // Well-defined layout, so just offset the pointer appropriately.
3685 const byte_off = aggregate_ty.structFieldOffset(field_idx, zcu);
3764 const byte_off = aggregate_ty.structFieldOffset(field_idx, pt);
36863765 const field_align = a: {
36873766 const parent_align = if (parent_ptr_info.flags.alignment == .none) pa: {
3688 break :pa (try aggregate_ty.abiAlignmentAdvanced(zcu, .sema)).scalar;
3767 break :pa (try aggregate_ty.abiAlignmentAdvanced(pt, .sema)).scalar;
36893768 } else parent_ptr_info.flags.alignment;
36903769 break :a InternPool.Alignment.fromLog2Units(@min(parent_align.toLog2Units(), @ctz(byte_off)));
36913770 };
3692 const result_ty = try zcu.ptrTypeSema(info: {
3771 const result_ty = try pt.ptrTypeSema(info: {
36933772 var new = parent_ptr_info;
36943773 new.child = field_ty.toIntern();
36953774 new.flags.alignment = field_align;
36963775 break :info new;
36973776 });
3698 return parent_ptr.getOffsetPtr(byte_off, result_ty, zcu);
3777 return parent_ptr.getOffsetPtr(byte_off, result_ty, pt);
36993778 },
3700 .@"packed" => switch (aggregate_ty.packedStructFieldPtrInfo(parent_ptr_ty, field_idx, zcu)) {
3779 .@"packed" => switch (aggregate_ty.packedStructFieldPtrInfo(parent_ptr_ty, field_idx, pt)) {
37013780 .bit_ptr => |packed_offset| {
3702 const result_ty = try zcu.ptrType(info: {
3781 const result_ty = try pt.ptrType(info: {
37033782 var new = parent_ptr_info;
37043783 new.packed_offset = packed_offset;
37053784 new.child = field_ty.toIntern();
37063785 if (new.flags.alignment == .none) {
3707 new.flags.alignment = (try aggregate_ty.abiAlignmentAdvanced(zcu, .sema)).scalar;
3786 new.flags.alignment = (try aggregate_ty.abiAlignmentAdvanced(pt, .sema)).scalar;
37083787 }
37093788 break :info new;
37103789 });
3711 return zcu.getCoerced(parent_ptr, result_ty);
3790 return pt.getCoerced(parent_ptr, result_ty);
37123791 },
37133792 .byte_ptr => |ptr_info| {
3714 const result_ty = try zcu.ptrTypeSema(info: {
3793 const result_ty = try pt.ptrTypeSema(info: {
37153794 var new = parent_ptr_info;
37163795 new.child = field_ty.toIntern();
37173796 new.packed_offset = .{
......@@ -3721,7 +3800,7 @@ pub fn ptrField(parent_ptr: Value, field_idx: u32, zcu: *Zcu) !Value {
37213800 new.flags.alignment = ptr_info.alignment;
37223801 break :info new;
37233802 });
3724 return parent_ptr.getOffsetPtr(ptr_info.offset, result_ty, zcu);
3803 return parent_ptr.getOffsetPtr(ptr_info.offset, result_ty, pt);
37253804 },
37263805 },
37273806 }
......@@ -3730,46 +3809,46 @@ pub fn ptrField(parent_ptr: Value, field_idx: u32, zcu: *Zcu) !Value {
37303809 const union_obj = zcu.typeToUnion(aggregate_ty).?;
37313810 const field_ty = Type.fromInterned(union_obj.field_types.get(&zcu.intern_pool)[field_idx]);
37323811 switch (aggregate_ty.containerLayout(zcu)) {
3733 .auto => break :field .{ field_ty, try aggregate_ty.structFieldAlignAdvanced(@intCast(field_idx), zcu, .sema) },
3812 .auto => break :field .{ field_ty, try aggregate_ty.structFieldAlignAdvanced(@intCast(field_idx), pt, .sema) },
37343813 .@"extern" => {
37353814 // Point to the same address.
3736 const result_ty = try zcu.ptrTypeSema(info: {
3815 const result_ty = try pt.ptrTypeSema(info: {
37373816 var new = parent_ptr_info;
37383817 new.child = field_ty.toIntern();
37393818 break :info new;
37403819 });
3741 return zcu.getCoerced(parent_ptr, result_ty);
3820 return pt.getCoerced(parent_ptr, result_ty);
37423821 },
37433822 .@"packed" => {
37443823 // If the field has an ABI size matching its bit size, then we can continue to use a
37453824 // non-bit pointer if the parent pointer is also a non-bit pointer.
3746 if (parent_ptr_info.packed_offset.host_size == 0 and (try field_ty.abiSizeAdvanced(zcu, .sema)).scalar * 8 == try field_ty.bitSizeAdvanced(zcu, .sema)) {
3825 if (parent_ptr_info.packed_offset.host_size == 0 and (try field_ty.abiSizeAdvanced(pt, .sema)).scalar * 8 == try field_ty.bitSizeAdvanced(pt, .sema)) {
37473826 // We must offset the pointer on big-endian targets, since the bits of packed memory don't align nicely.
37483827 const byte_offset = switch (zcu.getTarget().cpu.arch.endian()) {
37493828 .little => 0,
3750 .big => (try aggregate_ty.abiSizeAdvanced(zcu, .sema)).scalar - (try field_ty.abiSizeAdvanced(zcu, .sema)).scalar,
3829 .big => (try aggregate_ty.abiSizeAdvanced(pt, .sema)).scalar - (try field_ty.abiSizeAdvanced(pt, .sema)).scalar,
37513830 };
3752 const result_ty = try zcu.ptrTypeSema(info: {
3831 const result_ty = try pt.ptrTypeSema(info: {
37533832 var new = parent_ptr_info;
37543833 new.child = field_ty.toIntern();
37553834 new.flags.alignment = InternPool.Alignment.fromLog2Units(
3756 @ctz(byte_offset | (try parent_ptr_ty.ptrAlignmentAdvanced(zcu, .sema)).toByteUnits().?),
3835 @ctz(byte_offset | (try parent_ptr_ty.ptrAlignmentAdvanced(pt, .sema)).toByteUnits().?),
37573836 );
37583837 break :info new;
37593838 });
3760 return parent_ptr.getOffsetPtr(byte_offset, result_ty, zcu);
3839 return parent_ptr.getOffsetPtr(byte_offset, result_ty, pt);
37613840 } else {
37623841 // The result must be a bit-pointer if it is not already.
3763 const result_ty = try zcu.ptrTypeSema(info: {
3842 const result_ty = try pt.ptrTypeSema(info: {
37643843 var new = parent_ptr_info;
37653844 new.child = field_ty.toIntern();
37663845 if (new.packed_offset.host_size == 0) {
3767 new.packed_offset.host_size = @intCast(((try aggregate_ty.bitSizeAdvanced(zcu, .sema)) + 7) / 8);
3846 new.packed_offset.host_size = @intCast(((try aggregate_ty.bitSizeAdvanced(pt, .sema)) + 7) / 8);
37683847 assert(new.packed_offset.bit_offset == 0);
37693848 }
37703849 break :info new;
37713850 });
3772 return zcu.getCoerced(parent_ptr, result_ty);
3851 return pt.getCoerced(parent_ptr, result_ty);
37733852 }
37743853 },
37753854 }
......@@ -3777,8 +3856,8 @@ pub fn ptrField(parent_ptr: Value, field_idx: u32, zcu: *Zcu) !Value {
37773856 .Pointer => field_ty: {
37783857 assert(aggregate_ty.isSlice(zcu));
37793858 break :field_ty switch (field_idx) {
3780 Value.slice_ptr_index => .{ aggregate_ty.slicePtrFieldType(zcu), Type.usize.abiAlignment(zcu) },
3781 Value.slice_len_index => .{ Type.usize, Type.usize.abiAlignment(zcu) },
3859 Value.slice_ptr_index => .{ aggregate_ty.slicePtrFieldType(zcu), Type.usize.abiAlignment(pt) },
3860 Value.slice_len_index => .{ Type.usize, Type.usize.abiAlignment(pt) },
37823861 else => unreachable,
37833862 };
37843863 },
......@@ -3786,24 +3865,24 @@ pub fn ptrField(parent_ptr: Value, field_idx: u32, zcu: *Zcu) !Value {
37863865 };
37873866
37883867 const new_align: InternPool.Alignment = if (parent_ptr_info.flags.alignment != .none) a: {
3789 const ty_align = (try field_ty.abiAlignmentAdvanced(zcu, .sema)).scalar;
3868 const ty_align = (try field_ty.abiAlignmentAdvanced(pt, .sema)).scalar;
37903869 const true_field_align = if (field_align == .none) ty_align else field_align;
37913870 const new_align = true_field_align.min(parent_ptr_info.flags.alignment);
37923871 if (new_align == ty_align) break :a .none;
37933872 break :a new_align;
37943873 } else field_align;
37953874
3796 const result_ty = try zcu.ptrTypeSema(info: {
3875 const result_ty = try pt.ptrTypeSema(info: {
37973876 var new = parent_ptr_info;
37983877 new.child = field_ty.toIntern();
37993878 new.flags.alignment = new_align;
38003879 break :info new;
38013880 });
38023881
3803 if (parent_ptr.isUndef(zcu)) return zcu.undefValue(result_ty);
3882 if (parent_ptr.isUndef(zcu)) return pt.undefValue(result_ty);
38043883
3805 const base_ptr = try parent_ptr.canonicalizeBasePtr(.One, aggregate_ty, zcu);
3806 return Value.fromInterned(try zcu.intern(.{ .ptr = .{
3884 const base_ptr = try parent_ptr.canonicalizeBasePtr(.One, aggregate_ty, pt);
3885 return Value.fromInterned(try pt.intern(.{ .ptr = .{
38073886 .ty = result_ty.toIntern(),
38083887 .base_addr = .{ .field = .{
38093888 .base = base_ptr.toIntern(),
......@@ -3816,7 +3895,8 @@ pub fn ptrField(parent_ptr: Value, field_idx: u32, zcu: *Zcu) !Value {
38163895/// `orig_parent_ptr` must be either a single-pointer to an array or vector, or a many-pointer or C-pointer or slice.
38173896/// Returns a pointer to the element at the specified index.
38183897/// May perform type resolution.
3819pub fn ptrElem(orig_parent_ptr: Value, field_idx: u64, zcu: *Zcu) !Value {
3898pub fn ptrElem(orig_parent_ptr: Value, field_idx: u64, pt: Zcu.PerThread) !Value {
3899 const zcu = pt.zcu;
38203900 const parent_ptr = switch (orig_parent_ptr.typeOf(zcu).ptrSize(zcu)) {
38213901 .One, .Many, .C => orig_parent_ptr,
38223902 .Slice => orig_parent_ptr.slicePtr(zcu),
......@@ -3824,14 +3904,14 @@ pub fn ptrElem(orig_parent_ptr: Value, field_idx: u64, zcu: *Zcu) !Value {
38243904
38253905 const parent_ptr_ty = parent_ptr.typeOf(zcu);
38263906 const elem_ty = parent_ptr_ty.childType(zcu);
3827 const result_ty = try parent_ptr_ty.elemPtrType(@intCast(field_idx), zcu);
3907 const result_ty = try parent_ptr_ty.elemPtrType(@intCast(field_idx), pt);
38283908
3829 if (parent_ptr.isUndef(zcu)) return zcu.undefValue(result_ty);
3909 if (parent_ptr.isUndef(zcu)) return pt.undefValue(result_ty);
38303910
38313911 if (result_ty.ptrInfo(zcu).packed_offset.host_size != 0) {
38323912 // Since we have a bit-pointer, the pointer address should be unchanged.
38333913 assert(elem_ty.zigTypeTag(zcu) == .Vector);
3834 return zcu.getCoerced(parent_ptr, result_ty);
3914 return pt.getCoerced(parent_ptr, result_ty);
38353915 }
38363916
38373917 const PtrStrat = union(enum) {
......@@ -3841,31 +3921,31 @@ pub fn ptrElem(orig_parent_ptr: Value, field_idx: u64, zcu: *Zcu) !Value {
38413921
38423922 const strat: PtrStrat = switch (parent_ptr_ty.ptrSize(zcu)) {
38433923 .One => switch (elem_ty.zigTypeTag(zcu)) {
3844 .Vector => .{ .offset = field_idx * @divExact(try elem_ty.childType(zcu).bitSizeAdvanced(zcu, .sema), 8) },
3924 .Vector => .{ .offset = field_idx * @divExact(try elem_ty.childType(zcu).bitSizeAdvanced(pt, .sema), 8) },
38453925 .Array => strat: {
38463926 const arr_elem_ty = elem_ty.childType(zcu);
3847 if (try arr_elem_ty.comptimeOnlyAdvanced(zcu, .sema)) {
3927 if (try arr_elem_ty.comptimeOnlyAdvanced(pt, .sema)) {
38483928 break :strat .{ .elem_ptr = arr_elem_ty };
38493929 }
3850 break :strat .{ .offset = field_idx * (try arr_elem_ty.abiSizeAdvanced(zcu, .sema)).scalar };
3930 break :strat .{ .offset = field_idx * (try arr_elem_ty.abiSizeAdvanced(pt, .sema)).scalar };
38513931 },
38523932 else => unreachable,
38533933 },
38543934
3855 .Many, .C => if (try elem_ty.comptimeOnlyAdvanced(zcu, .sema))
3935 .Many, .C => if (try elem_ty.comptimeOnlyAdvanced(pt, .sema))
38563936 .{ .elem_ptr = elem_ty }
38573937 else
3858 .{ .offset = field_idx * (try elem_ty.abiSizeAdvanced(zcu, .sema)).scalar },
3938 .{ .offset = field_idx * (try elem_ty.abiSizeAdvanced(pt, .sema)).scalar },
38593939
38603940 .Slice => unreachable,
38613941 };
38623942
38633943 switch (strat) {
38643944 .offset => |byte_offset| {
3865 return parent_ptr.getOffsetPtr(byte_offset, result_ty, zcu);
3945 return parent_ptr.getOffsetPtr(byte_offset, result_ty, pt);
38663946 },
38673947 .elem_ptr => |manyptr_elem_ty| if (field_idx == 0) {
3868 return zcu.getCoerced(parent_ptr, result_ty);
3948 return pt.getCoerced(parent_ptr, result_ty);
38693949 } else {
38703950 const arr_base_ty, const arr_base_len = manyptr_elem_ty.arrayBase(zcu);
38713951 const base_idx = arr_base_len * field_idx;
......@@ -3875,7 +3955,7 @@ pub fn ptrElem(orig_parent_ptr: Value, field_idx: u64, zcu: *Zcu) !Value {
38753955 if (Value.fromInterned(arr_elem.base).typeOf(zcu).childType(zcu).toIntern() == arr_base_ty.toIntern()) {
38763956 // We already have a pointer to an element of an array of this type.
38773957 // Just modify the index.
3878 return Value.fromInterned(try zcu.intern(.{ .ptr = ptr: {
3958 return Value.fromInterned(try pt.intern(.{ .ptr = ptr: {
38793959 var new = parent_info;
38803960 new.base_addr.arr_elem.index += base_idx;
38813961 new.ty = result_ty.toIntern();
......@@ -3885,8 +3965,8 @@ pub fn ptrElem(orig_parent_ptr: Value, field_idx: u64, zcu: *Zcu) !Value {
38853965 },
38863966 else => {},
38873967 }
3888 const base_ptr = try parent_ptr.canonicalizeBasePtr(.Many, arr_base_ty, zcu);
3889 return Value.fromInterned(try zcu.intern(.{ .ptr = .{
3968 const base_ptr = try parent_ptr.canonicalizeBasePtr(.Many, arr_base_ty, pt);
3969 return Value.fromInterned(try pt.intern(.{ .ptr = .{
38903970 .ty = result_ty.toIntern(),
38913971 .base_addr = .{ .arr_elem = .{
38923972 .base = base_ptr.toIntern(),
......@@ -3898,9 +3978,9 @@ pub fn ptrElem(orig_parent_ptr: Value, field_idx: u64, zcu: *Zcu) !Value {
38983978 }
38993979}
39003980
3901fn canonicalizeBasePtr(base_ptr: Value, want_size: std.builtin.Type.Pointer.Size, want_child: Type, zcu: *Zcu) !Value {
3902 const ptr_ty = base_ptr.typeOf(zcu);
3903 const ptr_info = ptr_ty.ptrInfo(zcu);
3981fn canonicalizeBasePtr(base_ptr: Value, want_size: std.builtin.Type.Pointer.Size, want_child: Type, pt: Zcu.PerThread) !Value {
3982 const ptr_ty = base_ptr.typeOf(pt.zcu);
3983 const ptr_info = ptr_ty.ptrInfo(pt.zcu);
39043984
39053985 if (ptr_info.flags.size == want_size and
39063986 ptr_info.child == want_child.toIntern() and
......@@ -3914,7 +3994,7 @@ fn canonicalizeBasePtr(base_ptr: Value, want_size: std.builtin.Type.Pointer.Size
39143994 return base_ptr;
39153995 }
39163996
3917 const new_ty = try zcu.ptrType(.{
3997 const new_ty = try pt.ptrType(.{
39183998 .child = want_child.toIntern(),
39193999 .sentinel = .none,
39204000 .flags = .{
......@@ -3926,15 +4006,15 @@ fn canonicalizeBasePtr(base_ptr: Value, want_size: std.builtin.Type.Pointer.Size
39264006 .address_space = ptr_info.flags.address_space,
39274007 },
39284008 });
3929 return zcu.getCoerced(base_ptr, new_ty);
4009 return pt.getCoerced(base_ptr, new_ty);
39304010}
39314011
3932pub fn getOffsetPtr(ptr_val: Value, byte_off: u64, new_ty: Type, zcu: *Zcu) !Value {
3933 if (ptr_val.isUndef(zcu)) return ptr_val;
3934 var ptr = zcu.intern_pool.indexToKey(ptr_val.toIntern()).ptr;
4012pub fn getOffsetPtr(ptr_val: Value, byte_off: u64, new_ty: Type, pt: Zcu.PerThread) !Value {
4013 if (ptr_val.isUndef(pt.zcu)) return ptr_val;
4014 var ptr = pt.zcu.intern_pool.indexToKey(ptr_val.toIntern()).ptr;
39354015 ptr.ty = new_ty.toIntern();
39364016 ptr.byte_offset += byte_off;
3937 return Value.fromInterned(try zcu.intern(.{ .ptr = ptr }));
4017 return Value.fromInterned(try pt.intern(.{ .ptr = ptr }));
39384018}
39394019
39404020pub const PointerDeriveStep = union(enum) {
......@@ -3977,21 +4057,21 @@ pub const PointerDeriveStep = union(enum) {
39774057 new_ptr_ty: Type,
39784058 },
39794059
3980 pub fn ptrType(step: PointerDeriveStep, zcu: *Zcu) !Type {
4060 pub fn ptrType(step: PointerDeriveStep, pt: Zcu.PerThread) !Type {
39814061 return switch (step) {
39824062 .int => |int| int.ptr_ty,
3983 .decl_ptr => |decl| try zcu.declPtr(decl).declPtrType(zcu),
4063 .decl_ptr => |decl| try pt.zcu.declPtr(decl).declPtrType(pt),
39844064 .anon_decl_ptr => |ad| Type.fromInterned(ad.orig_ty),
39854065 .comptime_alloc_ptr => |info| info.ptr_ty,
3986 .comptime_field_ptr => |val| try zcu.singleConstPtrType(val.typeOf(zcu)),
4066 .comptime_field_ptr => |val| try pt.singleConstPtrType(val.typeOf(pt.zcu)),
39874067 .offset_and_cast => |oac| oac.new_ptr_ty,
39884068 inline .eu_payload_ptr, .opt_payload_ptr, .field_ptr, .elem_ptr => |x| x.result_ptr_ty,
39894069 };
39904070 }
39914071};
39924072
3993pub fn pointerDerivation(ptr_val: Value, arena: Allocator, zcu: *Zcu) Allocator.Error!PointerDeriveStep {
3994 return ptr_val.pointerDerivationAdvanced(arena, zcu, null) catch |err| switch (err) {
4073pub fn pointerDerivation(ptr_val: Value, arena: Allocator, pt: Zcu.PerThread) Allocator.Error!PointerDeriveStep {
4074 return ptr_val.pointerDerivationAdvanced(arena, pt, null) catch |err| switch (err) {
39954075 error.OutOfMemory => |e| return e,
39964076 error.AnalysisFail => unreachable,
39974077 };
......@@ -4001,7 +4081,8 @@ pub fn pointerDerivation(ptr_val: Value, arena: Allocator, zcu: *Zcu) Allocator.
40014081/// only field and element pointers with no casts. This can be used by codegen backends
40024082/// which prefer field/elem accesses when lowering constant pointer values.
40034083/// It is also used by the Value printing logic for pointers.
4004pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, opt_sema: ?*Sema) !PointerDeriveStep {
4084pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, pt: Zcu.PerThread, opt_sema: ?*Sema) !PointerDeriveStep {
4085 const zcu = pt.zcu;
40054086 const ptr = zcu.intern_pool.indexToKey(ptr_val.toIntern()).ptr;
40064087 const base_derive: PointerDeriveStep = switch (ptr.base_addr) {
40074088 .int => return .{ .int = .{
......@@ -4012,7 +4093,7 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
40124093 .anon_decl => |ad| base: {
40134094 // A slight tweak: `orig_ty` here is sometimes not `const`, but it ought to be.
40144095 // TODO: fix this in the sites interning anon decls!
4015 const const_ty = try zcu.ptrType(info: {
4096 const const_ty = try pt.ptrType(info: {
40164097 var info = Type.fromInterned(ad.orig_ty).ptrInfo(zcu);
40174098 info.flags.is_const = true;
40184099 break :info info;
......@@ -4024,11 +4105,11 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
40244105 },
40254106 .comptime_alloc => |idx| base: {
40264107 const alloc = opt_sema.?.getComptimeAlloc(idx);
4027 const val = try alloc.val.intern(zcu, opt_sema.?.arena);
4108 const val = try alloc.val.intern(pt, opt_sema.?.arena);
40284109 const ty = val.typeOf(zcu);
40294110 break :base .{ .comptime_alloc_ptr = .{
40304111 .val = val,
4031 .ptr_ty = try zcu.ptrType(.{
4112 .ptr_ty = try pt.ptrType(.{
40324113 .child = ty.toIntern(),
40334114 .flags = .{
40344115 .alignment = alloc.alignment,
......@@ -4041,20 +4122,20 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
40414122 const base_ptr = Value.fromInterned(eu_ptr);
40424123 const base_ptr_ty = base_ptr.typeOf(zcu);
40434124 const parent_step = try arena.create(PointerDeriveStep);
4044 parent_step.* = try pointerDerivationAdvanced(Value.fromInterned(eu_ptr), arena, zcu, opt_sema);
4125 parent_step.* = try pointerDerivationAdvanced(Value.fromInterned(eu_ptr), arena, pt, opt_sema);
40454126 break :base .{ .eu_payload_ptr = .{
40464127 .parent = parent_step,
4047 .result_ptr_ty = try zcu.adjustPtrTypeChild(base_ptr_ty, base_ptr_ty.childType(zcu).errorUnionPayload(zcu)),
4128 .result_ptr_ty = try pt.adjustPtrTypeChild(base_ptr_ty, base_ptr_ty.childType(zcu).errorUnionPayload(zcu)),
40484129 } };
40494130 },
40504131 .opt_payload => |opt_ptr| base: {
40514132 const base_ptr = Value.fromInterned(opt_ptr);
40524133 const base_ptr_ty = base_ptr.typeOf(zcu);
40534134 const parent_step = try arena.create(PointerDeriveStep);
4054 parent_step.* = try pointerDerivationAdvanced(Value.fromInterned(opt_ptr), arena, zcu, opt_sema);
4135 parent_step.* = try pointerDerivationAdvanced(Value.fromInterned(opt_ptr), arena, pt, opt_sema);
40554136 break :base .{ .opt_payload_ptr = .{
40564137 .parent = parent_step,
4057 .result_ptr_ty = try zcu.adjustPtrTypeChild(base_ptr_ty, base_ptr_ty.childType(zcu).optionalChild(zcu)),
4138 .result_ptr_ty = try pt.adjustPtrTypeChild(base_ptr_ty, base_ptr_ty.childType(zcu).optionalChild(zcu)),
40584139 } };
40594140 },
40604141 .field => |field| base: {
......@@ -4062,22 +4143,22 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
40624143 const base_ptr_ty = base_ptr.typeOf(zcu);
40634144 const agg_ty = base_ptr_ty.childType(zcu);
40644145 const field_ty, const field_align = switch (agg_ty.zigTypeTag(zcu)) {
4065 .Struct => .{ agg_ty.structFieldType(@intCast(field.index), zcu), try agg_ty.structFieldAlignAdvanced(@intCast(field.index), zcu, .sema) },
4066 .Union => .{ agg_ty.unionFieldTypeByIndex(@intCast(field.index), zcu), try agg_ty.structFieldAlignAdvanced(@intCast(field.index), zcu, .sema) },
4146 .Struct => .{ agg_ty.structFieldType(@intCast(field.index), zcu), try agg_ty.structFieldAlignAdvanced(@intCast(field.index), pt, .sema) },
4147 .Union => .{ agg_ty.unionFieldTypeByIndex(@intCast(field.index), zcu), try agg_ty.structFieldAlignAdvanced(@intCast(field.index), pt, .sema) },
40674148 .Pointer => .{ switch (field.index) {
40684149 Value.slice_ptr_index => agg_ty.slicePtrFieldType(zcu),
40694150 Value.slice_len_index => Type.usize,
40704151 else => unreachable,
4071 }, Type.usize.abiAlignment(zcu) },
4152 }, Type.usize.abiAlignment(pt) },
40724153 else => unreachable,
40734154 };
4074 const base_align = base_ptr_ty.ptrAlignment(zcu);
4155 const base_align = base_ptr_ty.ptrAlignment(pt);
40754156 const result_align = field_align.minStrict(base_align);
4076 const result_ty = try zcu.ptrType(.{
4157 const result_ty = try pt.ptrType(.{
40774158 .child = field_ty.toIntern(),
40784159 .flags = flags: {
40794160 var flags = base_ptr_ty.ptrInfo(zcu).flags;
4080 if (result_align == field_ty.abiAlignment(zcu)) {
4161 if (result_align == field_ty.abiAlignment(pt)) {
40814162 flags.alignment = .none;
40824163 } else {
40834164 flags.alignment = result_align;
......@@ -4086,7 +4167,7 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
40864167 },
40874168 });
40884169 const parent_step = try arena.create(PointerDeriveStep);
4089 parent_step.* = try pointerDerivationAdvanced(base_ptr, arena, zcu, opt_sema);
4170 parent_step.* = try pointerDerivationAdvanced(base_ptr, arena, pt, opt_sema);
40904171 break :base .{ .field_ptr = .{
40914172 .parent = parent_step,
40924173 .field_idx = @intCast(field.index),
......@@ -4095,9 +4176,9 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
40954176 },
40964177 .arr_elem => |arr_elem| base: {
40974178 const parent_step = try arena.create(PointerDeriveStep);
4098 parent_step.* = try pointerDerivationAdvanced(Value.fromInterned(arr_elem.base), arena, zcu, opt_sema);
4099 const parent_ptr_info = (try parent_step.ptrType(zcu)).ptrInfo(zcu);
4100 const result_ptr_ty = try zcu.ptrType(.{
4179 parent_step.* = try pointerDerivationAdvanced(Value.fromInterned(arr_elem.base), arena, pt, opt_sema);
4180 const parent_ptr_info = (try parent_step.ptrType(pt)).ptrInfo(zcu);
4181 const result_ptr_ty = try pt.ptrType(.{
41014182 .child = parent_ptr_info.child,
41024183 .flags = flags: {
41034184 var flags = parent_ptr_info.flags;
......@@ -4113,12 +4194,12 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
41134194 },
41144195 };
41154196
4116 if (ptr.byte_offset == 0 and ptr.ty == (try base_derive.ptrType(zcu)).toIntern()) {
4197 if (ptr.byte_offset == 0 and ptr.ty == (try base_derive.ptrType(pt)).toIntern()) {
41174198 return base_derive;
41184199 }
41194200
41204201 const need_child = Type.fromInterned(ptr.ty).childType(zcu);
4121 if (need_child.comptimeOnly(zcu)) {
4202 if (need_child.comptimeOnly(pt)) {
41224203 // No refinement can happen - this pointer is presumably invalid.
41234204 // Just offset it.
41244205 const parent = try arena.create(PointerDeriveStep);
......@@ -4129,7 +4210,7 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
41294210 .new_ptr_ty = Type.fromInterned(ptr.ty),
41304211 } };
41314212 }
4132 const need_bytes = need_child.abiSize(zcu);
4213 const need_bytes = need_child.abiSize(pt);
41334214
41344215 var cur_derive = base_derive;
41354216 var cur_offset = ptr.byte_offset;
......@@ -4137,7 +4218,7 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
41374218 // Refine through fields and array elements as much as possible.
41384219
41394220 if (need_bytes > 0) while (true) {
4140 const cur_ty = (try cur_derive.ptrType(zcu)).childType(zcu);
4221 const cur_ty = (try cur_derive.ptrType(pt)).childType(zcu);
41414222 if (cur_ty.toIntern() == need_child.toIntern() and cur_offset == 0) {
41424223 break;
41434224 }
......@@ -4168,7 +4249,7 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
41684249
41694250 .Array => {
41704251 const elem_ty = cur_ty.childType(zcu);
4171 const elem_size = elem_ty.abiSize(zcu);
4252 const elem_size = elem_ty.abiSize(pt);
41724253 const start_idx = cur_offset / elem_size;
41734254 const end_idx = (cur_offset + need_bytes + elem_size - 1) / elem_size;
41744255 if (end_idx == start_idx + 1) {
......@@ -4177,7 +4258,7 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
41774258 cur_derive = .{ .elem_ptr = .{
41784259 .parent = parent,
41794260 .elem_idx = start_idx,
4180 .result_ptr_ty = try zcu.adjustPtrTypeChild(try parent.ptrType(zcu), elem_ty),
4261 .result_ptr_ty = try pt.adjustPtrTypeChild(try parent.ptrType(pt), elem_ty),
41814262 } };
41824263 cur_offset -= start_idx * elem_size;
41834264 } else {
......@@ -4188,7 +4269,7 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
41884269 cur_derive = .{ .elem_ptr = .{
41894270 .parent = parent,
41904271 .elem_idx = start_idx,
4191 .result_ptr_ty = try zcu.adjustPtrTypeChild(try parent.ptrType(zcu), elem_ty),
4272 .result_ptr_ty = try pt.adjustPtrTypeChild(try parent.ptrType(pt), elem_ty),
41924273 } };
41934274 cur_offset -= start_idx * elem_size;
41944275 }
......@@ -4199,19 +4280,19 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
41994280 .auto, .@"packed" => break,
42004281 .@"extern" => for (0..cur_ty.structFieldCount(zcu)) |field_idx| {
42014282 const field_ty = cur_ty.structFieldType(field_idx, zcu);
4202 const start_off = cur_ty.structFieldOffset(field_idx, zcu);
4203 const end_off = start_off + field_ty.abiSize(zcu);
4283 const start_off = cur_ty.structFieldOffset(field_idx, pt);
4284 const end_off = start_off + field_ty.abiSize(pt);
42044285 if (cur_offset >= start_off and cur_offset + need_bytes <= end_off) {
4205 const old_ptr_ty = try cur_derive.ptrType(zcu);
4206 const parent_align = old_ptr_ty.ptrAlignment(zcu);
4286 const old_ptr_ty = try cur_derive.ptrType(pt);
4287 const parent_align = old_ptr_ty.ptrAlignment(pt);
42074288 const field_align = InternPool.Alignment.fromLog2Units(@min(parent_align.toLog2Units(), @ctz(start_off)));
42084289 const parent = try arena.create(PointerDeriveStep);
42094290 parent.* = cur_derive;
4210 const new_ptr_ty = try zcu.ptrType(.{
4291 const new_ptr_ty = try pt.ptrType(.{
42114292 .child = field_ty.toIntern(),
42124293 .flags = flags: {
42134294 var flags = old_ptr_ty.ptrInfo(zcu).flags;
4214 if (field_align == field_ty.abiAlignment(zcu)) {
4295 if (field_align == field_ty.abiAlignment(pt)) {
42154296 flags.alignment = .none;
42164297 } else {
42174298 flags.alignment = field_align;
......@@ -4232,7 +4313,7 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
42324313 }
42334314 };
42344315
4235 if (cur_offset == 0 and (try cur_derive.ptrType(zcu)).toIntern() == ptr.ty) {
4316 if (cur_offset == 0 and (try cur_derive.ptrType(pt)).toIntern() == ptr.ty) {
42364317 return cur_derive;
42374318 }
42384319
......@@ -4245,20 +4326,20 @@ pub fn pointerDerivationAdvanced(ptr_val: Value, arena: Allocator, zcu: *Zcu, op
42454326 } };
42464327}
42474328
4248pub fn resolveLazy(val: Value, arena: Allocator, zcu: *Zcu) Zcu.SemaError!Value {
4249 switch (zcu.intern_pool.indexToKey(val.toIntern())) {
4329pub fn resolveLazy(val: Value, arena: Allocator, pt: Zcu.PerThread) Zcu.SemaError!Value {
4330 switch (pt.zcu.intern_pool.indexToKey(val.toIntern())) {
42504331 .int => |int| switch (int.storage) {
42514332 .u64, .i64, .big_int => return val,
4252 .lazy_align, .lazy_size => return zcu.intValue(
4333 .lazy_align, .lazy_size => return pt.intValue(
42534334 Type.fromInterned(int.ty),
4254 (try val.getUnsignedIntAdvanced(zcu, .sema)).?,
4335 (try val.getUnsignedIntAdvanced(pt, .sema)).?,
42554336 ),
42564337 },
42574338 .slice => |slice| {
4258 const ptr = try Value.fromInterned(slice.ptr).resolveLazy(arena, zcu);
4259 const len = try Value.fromInterned(slice.len).resolveLazy(arena, zcu);
4339 const ptr = try Value.fromInterned(slice.ptr).resolveLazy(arena, pt);
4340 const len = try Value.fromInterned(slice.len).resolveLazy(arena, pt);
42604341 if (ptr.toIntern() == slice.ptr and len.toIntern() == slice.len) return val;
4261 return Value.fromInterned(try zcu.intern(.{ .slice = .{
4342 return Value.fromInterned(try pt.intern(.{ .slice = .{
42624343 .ty = slice.ty,
42634344 .ptr = ptr.toIntern(),
42644345 .len = len.toIntern(),
......@@ -4268,22 +4349,22 @@ pub fn resolveLazy(val: Value, arena: Allocator, zcu: *Zcu) Zcu.SemaError!Value
42684349 switch (ptr.base_addr) {
42694350 .decl, .comptime_alloc, .anon_decl, .int => return val,
42704351 .comptime_field => |field_val| {
4271 const resolved_field_val = (try Value.fromInterned(field_val).resolveLazy(arena, zcu)).toIntern();
4352 const resolved_field_val = (try Value.fromInterned(field_val).resolveLazy(arena, pt)).toIntern();
42724353 return if (resolved_field_val == field_val)
42734354 val
42744355 else
4275 Value.fromInterned((try zcu.intern(.{ .ptr = .{
4356 Value.fromInterned(try pt.intern(.{ .ptr = .{
42764357 .ty = ptr.ty,
42774358 .base_addr = .{ .comptime_field = resolved_field_val },
42784359 .byte_offset = ptr.byte_offset,
4279 } })));
4360 } }));
42804361 },
42814362 .eu_payload, .opt_payload => |base| {
4282 const resolved_base = (try Value.fromInterned(base).resolveLazy(arena, zcu)).toIntern();
4363 const resolved_base = (try Value.fromInterned(base).resolveLazy(arena, pt)).toIntern();
42834364 return if (resolved_base == base)
42844365 val
42854366 else
4286 Value.fromInterned((try zcu.intern(.{ .ptr = .{
4367 Value.fromInterned(try pt.intern(.{ .ptr = .{
42874368 .ty = ptr.ty,
42884369 .base_addr = switch (ptr.base_addr) {
42894370 .eu_payload => .{ .eu_payload = resolved_base },
......@@ -4291,14 +4372,14 @@ pub fn resolveLazy(val: Value, arena: Allocator, zcu: *Zcu) Zcu.SemaError!Value
42914372 else => unreachable,
42924373 },
42934374 .byte_offset = ptr.byte_offset,
4294 } })));
4375 } }));
42954376 },
42964377 .arr_elem, .field => |base_index| {
4297 const resolved_base = (try Value.fromInterned(base_index.base).resolveLazy(arena, zcu)).toIntern();
4378 const resolved_base = (try Value.fromInterned(base_index.base).resolveLazy(arena, pt)).toIntern();
42984379 return if (resolved_base == base_index.base)
42994380 val
43004381 else
4301 Value.fromInterned((try zcu.intern(.{ .ptr = .{
4382 Value.fromInterned(try pt.intern(.{ .ptr = .{
43024383 .ty = ptr.ty,
43034384 .base_addr = switch (ptr.base_addr) {
43044385 .arr_elem => .{ .arr_elem = .{
......@@ -4312,7 +4393,7 @@ pub fn resolveLazy(val: Value, arena: Allocator, zcu: *Zcu) Zcu.SemaError!Value
43124393 else => unreachable,
43134394 },
43144395 .byte_offset = ptr.byte_offset,
4315 } })));
4396 } }));
43164397 },
43174398 }
43184399 },
......@@ -4321,40 +4402,40 @@ pub fn resolveLazy(val: Value, arena: Allocator, zcu: *Zcu) Zcu.SemaError!Value
43214402 .elems => |elems| {
43224403 var resolved_elems: []InternPool.Index = &.{};
43234404 for (elems, 0..) |elem, i| {
4324 const resolved_elem = (try Value.fromInterned(elem).resolveLazy(arena, zcu)).toIntern();
4405 const resolved_elem = (try Value.fromInterned(elem).resolveLazy(arena, pt)).toIntern();
43254406 if (resolved_elems.len == 0 and resolved_elem != elem) {
43264407 resolved_elems = try arena.alloc(InternPool.Index, elems.len);
43274408 @memcpy(resolved_elems[0..i], elems[0..i]);
43284409 }
43294410 if (resolved_elems.len > 0) resolved_elems[i] = resolved_elem;
43304411 }
4331 return if (resolved_elems.len == 0) val else Value.fromInterned((try zcu.intern(.{ .aggregate = .{
4412 return if (resolved_elems.len == 0) val else Value.fromInterned(try pt.intern(.{ .aggregate = .{
43324413 .ty = aggregate.ty,
43334414 .storage = .{ .elems = resolved_elems },
4334 } })));
4415 } }));
43354416 },
43364417 .repeated_elem => |elem| {
4337 const resolved_elem = (try Value.fromInterned(elem).resolveLazy(arena, zcu)).toIntern();
4338 return if (resolved_elem == elem) val else Value.fromInterned((try zcu.intern(.{ .aggregate = .{
4418 const resolved_elem = (try Value.fromInterned(elem).resolveLazy(arena, pt)).toIntern();
4419 return if (resolved_elem == elem) val else Value.fromInterned(try pt.intern(.{ .aggregate = .{
43394420 .ty = aggregate.ty,
43404421 .storage = .{ .repeated_elem = resolved_elem },
4341 } })));
4422 } }));
43424423 },
43434424 },
43444425 .un => |un| {
43454426 const resolved_tag = if (un.tag == .none)
43464427 .none
43474428 else
4348 (try Value.fromInterned(un.tag).resolveLazy(arena, zcu)).toIntern();
4349 const resolved_val = (try Value.fromInterned(un.val).resolveLazy(arena, zcu)).toIntern();
4429 (try Value.fromInterned(un.tag).resolveLazy(arena, pt)).toIntern();
4430 const resolved_val = (try Value.fromInterned(un.val).resolveLazy(arena, pt)).toIntern();
43504431 return if (resolved_tag == un.tag and resolved_val == un.val)
43514432 val
43524433 else
4353 Value.fromInterned((try zcu.intern(.{ .un = .{
4434 Value.fromInterned(try pt.intern(.{ .un = .{
43544435 .ty = un.ty,
43554436 .tag = resolved_tag,
43564437 .val = resolved_val,
4357 } })));
4438 } }));
43584439 },
43594440 else => return val,
43604441 }
src/Zcu.zig+129-2875
......@@ -6,7 +6,6 @@ const std = @import("std");
66const builtin = @import("builtin");
77const mem = std.mem;
88const Allocator = std.mem.Allocator;
9const ArrayListUnmanaged = std.ArrayListUnmanaged;
109const assert = std.debug.assert;
1110const log = std.log.scoped(.module);
1211const BigIntConst = std.math.big.int.Const;
......@@ -65,8 +64,8 @@ root_mod: *Package.Module,
6564/// `root_mod` is the test runner, and `main_mod` is the user's source file which has the tests.
6665main_mod: *Package.Module,
6766std_mod: *Package.Module,
68sema_prog_node: std.Progress.Node = undefined,
69codegen_prog_node: std.Progress.Node = undefined,
67sema_prog_node: std.Progress.Node = std.Progress.Node.none,
68codegen_prog_node: std.Progress.Node = std.Progress.Node.none,
7069
7170/// Used by AstGen worker to load and store ZIR cache.
7271global_zir_cache: Compilation.Directory,
......@@ -75,10 +74,10 @@ local_zir_cache: Compilation.Directory,
7574
7675/// This is where all `Export` values are stored. Not all values here are necessarily valid exports;
7776/// to enumerate all exports, `single_exports` and `multi_exports` must be consulted.
78all_exports: ArrayListUnmanaged(Export) = .{},
77all_exports: std.ArrayListUnmanaged(Export) = .{},
7978/// This is a list of free indices in `all_exports`. These indices may be reused by exports from
8079/// future semantic analysis.
81free_exports: ArrayListUnmanaged(u32) = .{},
80free_exports: std.ArrayListUnmanaged(u32) = .{},
8281/// Maps from an `AnalUnit` which performs a single export, to the index into `all_exports` of
8382/// the export it performs. Note that the key is not the `Decl` being exported, but the `AnalUnit`
8483/// whose analysis triggered the export.
......@@ -179,7 +178,7 @@ stage1_flags: packed struct {
179178 reserved: u2 = 0,
180179} = .{},
181180
182compile_log_text: ArrayListUnmanaged(u8) = .{},
181compile_log_text: std.ArrayListUnmanaged(u8) = .{},
183182
184183emit_h: ?*GlobalEmitH,
185184
......@@ -203,6 +202,8 @@ panic_messages: [PanicId.len]Decl.OptionalIndex = .{.none} ** PanicId.len,
203202panic_func_index: InternPool.Index = .none,
204203null_stack_trace: InternPool.Index = .none,
205204
205pub const PerThread = @import("Zcu/PerThread.zig");
206
206207pub const PanicId = enum {
207208 unreach,
208209 unwrap_null,
......@@ -419,11 +420,11 @@ pub const Decl = struct {
419420 return zcu.namespacePtr(decl.src_namespace).renderFullyQualifiedDebugName(zcu, decl.name, writer);
420421 }
421422
422 pub fn fullyQualifiedName(decl: Decl, zcu: *Zcu) !InternPool.NullTerminatedString {
423 pub fn fullyQualifiedName(decl: Decl, pt: Zcu.PerThread) !InternPool.NullTerminatedString {
423424 return if (decl.name_fully_qualified)
424425 decl.name
425426 else
426 zcu.namespacePtr(decl.src_namespace).fullyQualifiedName(zcu, decl.name);
427 pt.zcu.namespacePtr(decl.src_namespace).fullyQualifiedName(pt, decl.name);
427428 }
428429
429430 pub fn typeOf(decl: Decl, zcu: *const Zcu) Type {
......@@ -519,24 +520,24 @@ pub const Decl = struct {
519520 return decl.getExternDecl(zcu) != .none;
520521 }
521522
522 pub fn getAlignment(decl: Decl, zcu: *Zcu) Alignment {
523 pub fn getAlignment(decl: Decl, pt: Zcu.PerThread) Alignment {
523524 assert(decl.has_tv);
524525 if (decl.alignment != .none) return decl.alignment;
525 return decl.typeOf(zcu).abiAlignment(zcu);
526 return decl.typeOf(pt.zcu).abiAlignment(pt);
526527 }
527528
528 pub fn declPtrType(decl: Decl, zcu: *Zcu) !Type {
529 pub fn declPtrType(decl: Decl, pt: Zcu.PerThread) !Type {
529530 assert(decl.has_tv);
530 const decl_ty = decl.typeOf(zcu);
531 return zcu.ptrType(.{
531 const decl_ty = decl.typeOf(pt.zcu);
532 return pt.ptrType(.{
532533 .child = decl_ty.toIntern(),
533534 .flags = .{
534 .alignment = if (decl.alignment == decl_ty.abiAlignment(zcu))
535 .alignment = if (decl.alignment == decl_ty.abiAlignment(pt))
535536 .none
536537 else
537538 decl.alignment,
538539 .address_space = decl.@"addrspace",
539 .is_const = decl.getOwnedVariable(zcu) == null,
540 .is_const = decl.getOwnedVariable(pt.zcu) == null,
540541 },
541542 });
542543 }
......@@ -589,7 +590,7 @@ pub const Decl = struct {
589590
590591/// This state is attached to every Decl when Module emit_h is non-null.
591592pub const EmitH = struct {
592 fwd_decl: ArrayListUnmanaged(u8) = .{},
593 fwd_decl: std.ArrayListUnmanaged(u8) = .{},
593594};
594595
595596pub const DeclAdapter = struct {
......@@ -622,8 +623,8 @@ pub const Namespace = struct {
622623 /// Value is whether the usingnamespace decl is marked `pub`.
623624 usingnamespace_set: std.AutoHashMapUnmanaged(Decl.Index, bool) = .{},
624625
625 const Index = InternPool.NamespaceIndex;
626 const OptionalIndex = InternPool.OptionalNamespaceIndex;
626 pub const Index = InternPool.NamespaceIndex;
627 pub const OptionalIndex = InternPool.OptionalNamespaceIndex;
627628
628629 const DeclContext = struct {
629630 zcu: *Zcu,
......@@ -687,42 +688,44 @@ pub const Namespace = struct {
687688
688689 pub fn fullyQualifiedName(
689690 ns: Namespace,
690 zcu: *Zcu,
691 pt: Zcu.PerThread,
691692 name: InternPool.NullTerminatedString,
692693 ) !InternPool.NullTerminatedString {
694 const zcu = pt.zcu;
693695 const ip = &zcu.intern_pool;
694 const count = count: {
696
697 const gpa = zcu.gpa;
698 const strings = ip.getLocal(pt.tid).getMutableStrings(gpa);
699 // Protects reads of interned strings from being reallocated during the call to
700 // renderFullyQualifiedName.
701 const slice = try strings.addManyAsSlice(count: {
695702 var count: usize = name.length(ip) + 1;
696703 var cur_ns = &ns;
697704 while (true) {
698705 const decl = zcu.declPtr(cur_ns.decl_index);
699 count += decl.name.length(ip) + 1;
700706 cur_ns = zcu.namespacePtr(cur_ns.parent.unwrap() orelse {
701 count += ns.fileScope(zcu).sub_file_path.len;
707 count += ns.fileScope(zcu).fullyQualifiedNameLen();
702708 break :count count;
703709 });
710 count += decl.name.length(ip) + 1;
704711 }
705 };
706
707 const gpa = zcu.gpa;
708 const start = ip.string_bytes.items.len;
709 // Protects reads of interned strings from being reallocated during the call to
710 // renderFullyQualifiedName.
711 try ip.string_bytes.ensureUnusedCapacity(gpa, count);
712 ns.renderFullyQualifiedName(zcu, name, ip.string_bytes.writer(gpa)) catch unreachable;
712 });
713 var fbs = std.io.fixedBufferStream(slice[0]);
714 ns.renderFullyQualifiedName(zcu, name, fbs.writer()) catch unreachable;
715 assert(fbs.pos == slice[0].len);
713716
714717 // Sanitize the name for nvptx which is more restrictive.
715718 // TODO This should be handled by the backend, not the frontend. Have a
716719 // look at how the C backend does it for inspiration.
717720 const cpu_arch = zcu.root_mod.resolved_target.result.cpu.arch;
718721 if (cpu_arch.isNvptx()) {
719 for (ip.string_bytes.items[start..]) |*byte| switch (byte.*) {
722 for (slice[0]) |*byte| switch (byte.*) {
720723 '{', '}', '*', '[', ']', '(', ')', ',', ' ', '\'' => byte.* = '_',
721724 else => {},
722725 };
723726 }
724727
725 return ip.getOrPutTrailingString(gpa, ip.string_bytes.items.len - start, .no_embedded_nulls);
728 return ip.getOrPutTrailingString(gpa, pt.tid, @intCast(slice[0].len), .no_embedded_nulls);
726729 }
727730
728731 pub fn getType(ns: Namespace, zcu: *Zcu) Type {
......@@ -857,6 +860,11 @@ pub const File = struct {
857860 return &file.tree;
858861 }
859862
863 pub fn fullyQualifiedNameLen(file: File) usize {
864 const ext = std.fs.path.extension(file.sub_file_path);
865 return file.sub_file_path.len - ext.len;
866 }
867
860868 pub fn renderFullyQualifiedName(file: File, writer: anytype) !void {
861869 // Convert all the slashes into dots and truncate the extension.
862870 const ext = std.fs.path.extension(file.sub_file_path);
......@@ -874,11 +882,15 @@ pub const File = struct {
874882 };
875883 }
876884
877 pub fn fullyQualifiedName(file: File, mod: *Module) !InternPool.NullTerminatedString {
878 const ip = &mod.intern_pool;
879 const start = ip.string_bytes.items.len;
880 try file.renderFullyQualifiedName(ip.string_bytes.writer(mod.gpa));
881 return ip.getOrPutTrailingString(mod.gpa, ip.string_bytes.items.len - start, .no_embedded_nulls);
885 pub fn fullyQualifiedName(file: File, pt: Zcu.PerThread) !InternPool.NullTerminatedString {
886 const gpa = pt.zcu.gpa;
887 const ip = &pt.zcu.intern_pool;
888 const strings = ip.getLocal(pt.tid).getMutableStrings(gpa);
889 const slice = try strings.addManyAsSlice(file.fullyQualifiedNameLen());
890 var fbs = std.io.fixedBufferStream(slice[0]);
891 file.renderFullyQualifiedName(fbs.writer()) catch unreachable;
892 assert(fbs.pos == slice[0].len);
893 return ip.getOrPutTrailingString(gpa, pt.tid, @intCast(slice[0].len), .no_embedded_nulls);
882894 }
883895
884896 pub fn fullPath(file: File, ally: Allocator) ![]u8 {
......@@ -2391,9 +2403,9 @@ pub const CompileError = error{
23912403 ComptimeBreak,
23922404};
23932405
2394pub fn init(mod: *Module) !void {
2406pub fn init(mod: *Module, thread_count: usize) !void {
23952407 const gpa = mod.gpa;
2396 try mod.intern_pool.init(gpa);
2408 try mod.intern_pool.init(gpa, thread_count);
23972409 try mod.global_error_set.put(gpa, .empty, {});
23982410}
23992411
......@@ -2568,8 +2580,8 @@ pub fn declIsRoot(mod: *Module, decl_index: Decl.Index) bool {
25682580}
25692581
25702582// TODO https://github.com/ziglang/zig/issues/8643
2571const data_has_safety_tag = @sizeOf(Zir.Inst.Data) != 8;
2572const HackDataLayout = extern struct {
2583pub const data_has_safety_tag = @sizeOf(Zir.Inst.Data) != 8;
2584pub const HackDataLayout = extern struct {
25732585 data: [8]u8 align(@alignOf(Zir.Inst.Data)),
25742586 safety_tag: u8,
25752587};
......@@ -2579,291 +2591,11 @@ comptime {
25792591 }
25802592}
25812593
2582pub fn astGenFile(
2583 zcu: *Zcu,
2584 file: *File,
2585 /// This parameter is provided separately from `file` because it is not
2586 /// safe to access `import_table` without a lock, and this index is needed
2587 /// in the call to `updateZirRefs`.
2588 file_index: File.Index,
2589 path_digest: Cache.BinDigest,
2590 opt_root_decl: Zcu.Decl.OptionalIndex,
2591) !void {
2592 assert(!file.mod.isBuiltin());
2593
2594 const tracy = trace(@src());
2595 defer tracy.end();
2596
2597 const comp = zcu.comp;
2598 const gpa = zcu.gpa;
2599
2600 // In any case we need to examine the stat of the file to determine the course of action.
2601 var source_file = try file.mod.root.openFile(file.sub_file_path, .{});
2602 defer source_file.close();
2603
2604 const stat = try source_file.stat();
2605
2606 const want_local_cache = file.mod == zcu.main_mod;
2607 const hex_digest = Cache.binToHex(path_digest);
2608 const cache_directory = if (want_local_cache) zcu.local_zir_cache else zcu.global_zir_cache;
2609 const zir_dir = cache_directory.handle;
2610
2611 // Determine whether we need to reload the file from disk and redo parsing and AstGen.
2612 var lock: std.fs.File.Lock = switch (file.status) {
2613 .never_loaded, .retryable_failure => lock: {
2614 // First, load the cached ZIR code, if any.
2615 log.debug("AstGen checking cache: {s} (local={}, digest={s})", .{
2616 file.sub_file_path, want_local_cache, &hex_digest,
2617 });
2618
2619 break :lock .shared;
2620 },
2621 .parse_failure, .astgen_failure, .success_zir => lock: {
2622 const unchanged_metadata =
2623 stat.size == file.stat.size and
2624 stat.mtime == file.stat.mtime and
2625 stat.inode == file.stat.inode;
2626
2627 if (unchanged_metadata) {
2628 log.debug("unmodified metadata of file: {s}", .{file.sub_file_path});
2629 return;
2630 }
2631
2632 log.debug("metadata changed: {s}", .{file.sub_file_path});
2633
2634 break :lock .exclusive;
2635 },
2636 };
2637
2638 // We ask for a lock in order to coordinate with other zig processes.
2639 // If another process is already working on this file, we will get the cached
2640 // version. Likewise if we're working on AstGen and another process asks for
2641 // the cached file, they'll get it.
2642 const cache_file = while (true) {
2643 break zir_dir.createFile(&hex_digest, .{
2644 .read = true,
2645 .truncate = false,
2646 .lock = lock,
2647 }) catch |err| switch (err) {
2648 error.NotDir => unreachable, // no dir components
2649 error.InvalidUtf8 => unreachable, // it's a hex encoded name
2650 error.InvalidWtf8 => unreachable, // it's a hex encoded name
2651 error.BadPathName => unreachable, // it's a hex encoded name
2652 error.NameTooLong => unreachable, // it's a fixed size name
2653 error.PipeBusy => unreachable, // it's not a pipe
2654 error.WouldBlock => unreachable, // not asking for non-blocking I/O
2655 // There are no dir components, so you would think that this was
2656 // unreachable, however we have observed on macOS two processes racing
2657 // to do openat() with O_CREAT manifest in ENOENT.
2658 error.FileNotFound => continue,
2659
2660 else => |e| return e, // Retryable errors are handled at callsite.
2661 };
2662 };
2663 defer cache_file.close();
2664
2665 while (true) {
2666 update: {
2667 // First we read the header to determine the lengths of arrays.
2668 const header = cache_file.reader().readStruct(Zir.Header) catch |err| switch (err) {
2669 // This can happen if Zig bails out of this function between creating
2670 // the cached file and writing it.
2671 error.EndOfStream => break :update,
2672 else => |e| return e,
2673 };
2674 const unchanged_metadata =
2675 stat.size == header.stat_size and
2676 stat.mtime == header.stat_mtime and
2677 stat.inode == header.stat_inode;
2678
2679 if (!unchanged_metadata) {
2680 log.debug("AstGen cache stale: {s}", .{file.sub_file_path});
2681 break :update;
2682 }
2683 log.debug("AstGen cache hit: {s} instructions_len={d}", .{
2684 file.sub_file_path, header.instructions_len,
2685 });
2686
2687 file.zir = loadZirCacheBody(gpa, header, cache_file) catch |err| switch (err) {
2688 error.UnexpectedFileSize => {
2689 log.warn("unexpected EOF reading cached ZIR for {s}", .{file.sub_file_path});
2690 break :update;
2691 },
2692 else => |e| return e,
2693 };
2694 file.zir_loaded = true;
2695 file.stat = .{
2696 .size = header.stat_size,
2697 .inode = header.stat_inode,
2698 .mtime = header.stat_mtime,
2699 };
2700 file.status = .success_zir;
2701 log.debug("AstGen cached success: {s}", .{file.sub_file_path});
2702
2703 // TODO don't report compile errors until Sema @importFile
2704 if (file.zir.hasCompileErrors()) {
2705 {
2706 comp.mutex.lock();
2707 defer comp.mutex.unlock();
2708 try zcu.failed_files.putNoClobber(gpa, file, null);
2709 }
2710 file.status = .astgen_failure;
2711 return error.AnalysisFail;
2712 }
2713 return;
2714 }
2715
2716 // If we already have the exclusive lock then it is our job to update.
2717 if (builtin.os.tag == .wasi or lock == .exclusive) break;
2718 // Otherwise, unlock to give someone a chance to get the exclusive lock
2719 // and then upgrade to an exclusive lock.
2720 cache_file.unlock();
2721 lock = .exclusive;
2722 try cache_file.lock(lock);
2723 }
2724
2725 // The cache is definitely stale so delete the contents to avoid an underwrite later.
2726 cache_file.setEndPos(0) catch |err| switch (err) {
2727 error.FileTooBig => unreachable, // 0 is not too big
2728
2729 else => |e| return e,
2730 };
2731
2732 zcu.lockAndClearFileCompileError(file);
2733
2734 // If the previous ZIR does not have compile errors, keep it around
2735 // in case parsing or new ZIR fails. In case of successful ZIR update
2736 // at the end of this function we will free it.
2737 // We keep the previous ZIR loaded so that we can use it
2738 // for the update next time it does not have any compile errors. This avoids
2739 // needlessly tossing out semantic analysis work when an error is
2740 // temporarily introduced.
2741 if (file.zir_loaded and !file.zir.hasCompileErrors()) {
2742 assert(file.prev_zir == null);
2743 const prev_zir_ptr = try gpa.create(Zir);
2744 file.prev_zir = prev_zir_ptr;
2745 prev_zir_ptr.* = file.zir;
2746 file.zir = undefined;
2747 file.zir_loaded = false;
2748 }
2749 file.unload(gpa);
2750
2751 if (stat.size > std.math.maxInt(u32))
2752 return error.FileTooBig;
2753
2754 const source = try gpa.allocSentinel(u8, @as(usize, @intCast(stat.size)), 0);
2755 defer if (!file.source_loaded) gpa.free(source);
2756 const amt = try source_file.readAll(source);
2757 if (amt != stat.size)
2758 return error.UnexpectedEndOfFile;
2759
2760 file.stat = .{
2761 .size = stat.size,
2762 .inode = stat.inode,
2763 .mtime = stat.mtime,
2764 };
2765 file.source = source;
2766 file.source_loaded = true;
2767
2768 file.tree = try Ast.parse(gpa, source, .zig);
2769 file.tree_loaded = true;
2770
2771 // Any potential AST errors are converted to ZIR errors here.
2772 file.zir = try AstGen.generate(gpa, file.tree);
2773 file.zir_loaded = true;
2774 file.status = .success_zir;
2775 log.debug("AstGen fresh success: {s}", .{file.sub_file_path});
2776
2777 const safety_buffer = if (data_has_safety_tag)
2778 try gpa.alloc([8]u8, file.zir.instructions.len)
2779 else
2780 undefined;
2781 defer if (data_has_safety_tag) gpa.free(safety_buffer);
2782 const data_ptr = if (data_has_safety_tag)
2783 if (file.zir.instructions.len == 0)
2784 @as([*]const u8, undefined)
2785 else
2786 @as([*]const u8, @ptrCast(safety_buffer.ptr))
2787 else
2788 @as([*]const u8, @ptrCast(file.zir.instructions.items(.data).ptr));
2789 if (data_has_safety_tag) {
2790 // The `Data` union has a safety tag but in the file format we store it without.
2791 for (file.zir.instructions.items(.data), 0..) |*data, i| {
2792 const as_struct = @as(*const HackDataLayout, @ptrCast(data));
2793 safety_buffer[i] = as_struct.data;
2794 }
2795 }
2796
2797 const header: Zir.Header = .{
2798 .instructions_len = @as(u32, @intCast(file.zir.instructions.len)),
2799 .string_bytes_len = @as(u32, @intCast(file.zir.string_bytes.len)),
2800 .extra_len = @as(u32, @intCast(file.zir.extra.len)),
2801
2802 .stat_size = stat.size,
2803 .stat_inode = stat.inode,
2804 .stat_mtime = stat.mtime,
2805 };
2806 var iovecs = [_]std.posix.iovec_const{
2807 .{
2808 .base = @as([*]const u8, @ptrCast(&header)),
2809 .len = @sizeOf(Zir.Header),
2810 },
2811 .{
2812 .base = @as([*]const u8, @ptrCast(file.zir.instructions.items(.tag).ptr)),
2813 .len = file.zir.instructions.len,
2814 },
2815 .{
2816 .base = data_ptr,
2817 .len = file.zir.instructions.len * 8,
2818 },
2819 .{
2820 .base = file.zir.string_bytes.ptr,
2821 .len = file.zir.string_bytes.len,
2822 },
2823 .{
2824 .base = @as([*]const u8, @ptrCast(file.zir.extra.ptr)),
2825 .len = file.zir.extra.len * 4,
2826 },
2827 };
2828 cache_file.writevAll(&iovecs) catch |err| {
2829 log.warn("unable to write cached ZIR code for {}{s} to {}{s}: {s}", .{
2830 file.mod.root, file.sub_file_path, cache_directory, &hex_digest, @errorName(err),
2831 });
2832 };
2833
2834 if (file.zir.hasCompileErrors()) {
2835 {
2836 comp.mutex.lock();
2837 defer comp.mutex.unlock();
2838 try zcu.failed_files.putNoClobber(gpa, file, null);
2839 }
2840 file.status = .astgen_failure;
2841 return error.AnalysisFail;
2842 }
2843
2844 if (file.prev_zir) |prev_zir| {
2845 try updateZirRefs(zcu, file, file_index, prev_zir.*);
2846 // No need to keep previous ZIR.
2847 prev_zir.deinit(gpa);
2848 gpa.destroy(prev_zir);
2849 file.prev_zir = null;
2850 }
2851
2852 if (opt_root_decl.unwrap()) |root_decl| {
2853 // The root of this file must be re-analyzed, since the file has changed.
2854 comp.mutex.lock();
2855 defer comp.mutex.unlock();
2856
2857 log.debug("outdated root Decl: {}", .{root_decl});
2858 try zcu.outdated_file_root.put(gpa, root_decl, {});
2859 }
2860}
2861
28622594pub fn loadZirCache(gpa: Allocator, cache_file: std.fs.File) !Zir {
28632595 return loadZirCacheBody(gpa, try cache_file.reader().readStruct(Zir.Header), cache_file);
28642596}
28652597
2866fn loadZirCacheBody(gpa: Allocator, header: Zir.Header, cache_file: std.fs.File) !Zir {
2598pub fn loadZirCacheBody(gpa: Allocator, header: Zir.Header, cache_file: std.fs.File) !Zir {
28672599 var instructions: std.MultiArrayList(Zir.Inst) = .{};
28682600 errdefer instructions.deinit(gpa);
28692601
......@@ -2929,127 +2661,6 @@ fn loadZirCacheBody(gpa: Allocator, header: Zir.Header, cache_file: std.fs.File)
29292661 return zir;
29302662}
29312663
2932/// This is called from the AstGen thread pool, so must acquire
2933/// the Compilation mutex when acting on shared state.
2934fn updateZirRefs(zcu: *Module, file: *File, file_index: File.Index, old_zir: Zir) !void {
2935 const gpa = zcu.gpa;
2936 const new_zir = file.zir;
2937
2938 var inst_map: std.AutoHashMapUnmanaged(Zir.Inst.Index, Zir.Inst.Index) = .{};
2939 defer inst_map.deinit(gpa);
2940
2941 try mapOldZirToNew(gpa, old_zir, new_zir, &inst_map);
2942
2943 const old_tag = old_zir.instructions.items(.tag);
2944 const old_data = old_zir.instructions.items(.data);
2945
2946 // TODO: this should be done after all AstGen workers complete, to avoid
2947 // iterating over this full set for every updated file.
2948 for (zcu.intern_pool.tracked_insts.keys(), 0..) |*ti, idx_raw| {
2949 const ti_idx: InternPool.TrackedInst.Index = @enumFromInt(idx_raw);
2950 if (ti.file != file_index) continue;
2951 const old_inst = ti.inst;
2952 ti.inst = inst_map.get(ti.inst) orelse {
2953 // Tracking failed for this instruction. Invalidate associated `src_hash` deps.
2954 zcu.comp.mutex.lock();
2955 defer zcu.comp.mutex.unlock();
2956 log.debug("tracking failed for %{d}", .{old_inst});
2957 try zcu.markDependeeOutdated(.{ .src_hash = ti_idx });
2958 continue;
2959 };
2960
2961 if (old_zir.getAssociatedSrcHash(old_inst)) |old_hash| hash_changed: {
2962 if (new_zir.getAssociatedSrcHash(ti.inst)) |new_hash| {
2963 if (std.zig.srcHashEql(old_hash, new_hash)) {
2964 break :hash_changed;
2965 }
2966 log.debug("hash for (%{d} -> %{d}) changed: {} -> {}", .{
2967 old_inst,
2968 ti.inst,
2969 std.fmt.fmtSliceHexLower(&old_hash),
2970 std.fmt.fmtSliceHexLower(&new_hash),
2971 });
2972 }
2973 // The source hash associated with this instruction changed - invalidate relevant dependencies.
2974 zcu.comp.mutex.lock();
2975 defer zcu.comp.mutex.unlock();
2976 try zcu.markDependeeOutdated(.{ .src_hash = ti_idx });
2977 }
2978
2979 // If this is a `struct_decl` etc, we must invalidate any outdated namespace dependencies.
2980 const has_namespace = switch (old_tag[@intFromEnum(old_inst)]) {
2981 .extended => switch (old_data[@intFromEnum(old_inst)].extended.opcode) {
2982 .struct_decl, .union_decl, .opaque_decl, .enum_decl => true,
2983 else => false,
2984 },
2985 else => false,
2986 };
2987 if (!has_namespace) continue;
2988
2989 var old_names: std.AutoArrayHashMapUnmanaged(InternPool.NullTerminatedString, void) = .{};
2990 defer old_names.deinit(zcu.gpa);
2991 {
2992 var it = old_zir.declIterator(old_inst);
2993 while (it.next()) |decl_inst| {
2994 const decl_name = old_zir.getDeclaration(decl_inst)[0].name;
2995 switch (decl_name) {
2996 .@"comptime", .@"usingnamespace", .unnamed_test, .decltest => continue,
2997 _ => if (decl_name.isNamedTest(old_zir)) continue,
2998 }
2999 const name_zir = decl_name.toString(old_zir).?;
3000 const name_ip = try zcu.intern_pool.getOrPutString(
3001 zcu.gpa,
3002 old_zir.nullTerminatedString(name_zir),
3003 .no_embedded_nulls,
3004 );
3005 try old_names.put(zcu.gpa, name_ip, {});
3006 }
3007 }
3008 var any_change = false;
3009 {
3010 var it = new_zir.declIterator(ti.inst);
3011 while (it.next()) |decl_inst| {
3012 const decl_name = old_zir.getDeclaration(decl_inst)[0].name;
3013 switch (decl_name) {
3014 .@"comptime", .@"usingnamespace", .unnamed_test, .decltest => continue,
3015 _ => if (decl_name.isNamedTest(old_zir)) continue,
3016 }
3017 const name_zir = decl_name.toString(old_zir).?;
3018 const name_ip = try zcu.intern_pool.getOrPutString(
3019 zcu.gpa,
3020 old_zir.nullTerminatedString(name_zir),
3021 .no_embedded_nulls,
3022 );
3023 if (!old_names.swapRemove(name_ip)) continue;
3024 // Name added
3025 any_change = true;
3026 zcu.comp.mutex.lock();
3027 defer zcu.comp.mutex.unlock();
3028 try zcu.markDependeeOutdated(.{ .namespace_name = .{
3029 .namespace = ti_idx,
3030 .name = name_ip,
3031 } });
3032 }
3033 }
3034 // The only elements remaining in `old_names` now are any names which were removed.
3035 for (old_names.keys()) |name_ip| {
3036 any_change = true;
3037 zcu.comp.mutex.lock();
3038 defer zcu.comp.mutex.unlock();
3039 try zcu.markDependeeOutdated(.{ .namespace_name = .{
3040 .namespace = ti_idx,
3041 .name = name_ip,
3042 } });
3043 }
3044
3045 if (any_change) {
3046 zcu.comp.mutex.lock();
3047 defer zcu.comp.mutex.unlock();
3048 try zcu.markDependeeOutdated(.{ .namespace = ti_idx });
3049 }
3050 }
3051}
3052
30532664pub fn markDependeeOutdated(zcu: *Zcu, dependee: InternPool.Dependee) !void {
30542665 log.debug("outdated dependee: {}", .{dependee});
30552666 var it = zcu.intern_pool.dependencyIterator(dependee);
......@@ -3079,7 +2690,7 @@ pub fn markDependeeOutdated(zcu: *Zcu, dependee: InternPool.Dependee) !void {
30792690 }
30802691}
30812692
3082fn markPoDependeeUpToDate(zcu: *Zcu, dependee: InternPool.Dependee) !void {
2693pub fn markPoDependeeUpToDate(zcu: *Zcu, dependee: InternPool.Dependee) !void {
30832694 var it = zcu.intern_pool.dependencyIterator(dependee);
30842695 while (it.next()) |depender| {
30852696 if (zcu.outdated.getPtr(depender)) |po_dep_count| {
......@@ -3279,7 +2890,7 @@ pub fn mapOldZirToNew(
32792890 old_inst: Zir.Inst.Index,
32802891 new_inst: Zir.Inst.Index,
32812892 };
3282 var match_stack: ArrayListUnmanaged(MatchedZirDecl) = .{};
2893 var match_stack: std.ArrayListUnmanaged(MatchedZirDecl) = .{};
32832894 defer match_stack.deinit(gpa);
32842895
32852896 // Main struct inst is always matched
......@@ -3394,970 +3005,80 @@ pub fn mapOldZirToNew(
33943005 }
33953006}
33963007
3397/// Like `ensureDeclAnalyzed`, but the Decl is a file's root Decl.
3398pub fn ensureFileAnalyzed(zcu: *Zcu, file_index: File.Index) SemaError!void {
3399 if (zcu.fileRootDecl(file_index).unwrap()) |existing_root| {
3400 return zcu.ensureDeclAnalyzed(existing_root);
3401 } else {
3402 return zcu.semaFile(file_index);
3403 }
3404}
3405
3406/// This ensures that the Decl will have an up-to-date Type and Value populated.
3407/// However the resolution status of the Type may not be fully resolved.
3408/// For example an inferred error set is not resolved until after `analyzeFnBody`.
3409/// is called.
3410pub fn ensureDeclAnalyzed(mod: *Module, decl_index: Decl.Index) SemaError!void {
3411 const tracy = trace(@src());
3412 defer tracy.end();
3413
3008/// Ensure this function's body is or will be analyzed and emitted. This should
3009/// be called whenever a potential runtime call of a function is seen.
3010///
3011/// The caller is responsible for ensuring the function decl itself is already
3012/// analyzed, and for ensuring it can exist at runtime (see
3013/// `sema.fnHasRuntimeBits`). This function does *not* guarantee that the body
3014/// will be analyzed when it returns: for that, see `ensureFuncBodyAnalyzed`.
3015pub fn ensureFuncBodyAnalysisQueued(mod: *Module, func_index: InternPool.Index) !void {
34143016 const ip = &mod.intern_pool;
3415 const decl = mod.declPtr(decl_index);
3416
3417 log.debug("ensureDeclAnalyzed '{d}' (name '{}')", .{
3418 @intFromEnum(decl_index),
3419 decl.name.fmt(ip),
3420 });
3421
3422 // Determine whether or not this Decl is outdated, i.e. requires re-analysis
3423 // even if `complete`. If a Decl is PO, we pessismistically assume that it
3424 // *does* require re-analysis, to ensure that the Decl is definitely
3425 // up-to-date when this function returns.
3426
3427 // If analysis occurs in a poor order, this could result in over-analysis.
3428 // We do our best to avoid this by the other dependency logic in this file
3429 // which tries to limit re-analysis to Decls whose previously listed
3430 // dependencies are all up-to-date.
3431
3432 const decl_as_depender = AnalUnit.wrap(.{ .decl = decl_index });
3433 const decl_was_outdated = mod.outdated.swapRemove(decl_as_depender) or
3434 mod.potentially_outdated.swapRemove(decl_as_depender);
3435
3436 if (decl_was_outdated) {
3437 _ = mod.outdated_ready.swapRemove(decl_as_depender);
3438 }
3439
3440 const was_outdated = mod.outdated_file_root.swapRemove(decl_index) or decl_was_outdated;
3441
3442 switch (decl.analysis) {
3443 .in_progress => unreachable,
3444
3445 .file_failure => return error.AnalysisFail,
3446
3447 .sema_failure,
3448 .dependency_failure,
3449 .codegen_failure,
3450 => if (!was_outdated) return error.AnalysisFail,
3451
3452 .complete => if (!was_outdated) return,
3453
3454 .unreferenced => {},
3455 }
3456
3457 if (was_outdated) {
3458 // The exports this Decl performs will be re-discovered, so we remove them here
3459 // prior to re-analysis.
3460 if (build_options.only_c) unreachable;
3461 mod.deleteUnitExports(decl_as_depender);
3462 mod.deleteUnitReferences(decl_as_depender);
3463 }
3464
3465 const sema_result: SemaDeclResult = blk: {
3466 if (decl.zir_decl_index == .none and !mod.declIsRoot(decl_index)) {
3467 // Anonymous decl. We don't semantically analyze these.
3468 break :blk .{
3469 .invalidate_decl_val = false,
3470 .invalidate_decl_ref = false,
3471 };
3472 }
3473
3474 if (mod.declIsRoot(decl_index)) {
3475 const changed = try mod.semaFileUpdate(decl.getFileScopeIndex(mod), decl_was_outdated);
3476 break :blk .{
3477 .invalidate_decl_val = changed,
3478 .invalidate_decl_ref = changed,
3479 };
3480 }
3481
3482 const decl_prog_node = mod.sema_prog_node.start((try decl.fullyQualifiedName(mod)).toSlice(ip), 0);
3483 defer decl_prog_node.end();
3484
3485 break :blk mod.semaDecl(decl_index) catch |err| switch (err) {
3486 error.AnalysisFail => {
3487 if (decl.analysis == .in_progress) {
3488 // If this decl caused the compile error, the analysis field would
3489 // be changed to indicate it was this Decl's fault. Because this
3490 // did not happen, we infer here that it was a dependency failure.
3491 decl.analysis = .dependency_failure;
3492 }
3493 return error.AnalysisFail;
3494 },
3495 error.GenericPoison => unreachable,
3496 else => |e| {
3497 decl.analysis = .sema_failure;
3498 try mod.failed_analysis.ensureUnusedCapacity(mod.gpa, 1);
3499 try mod.retryable_failures.append(mod.gpa, AnalUnit.wrap(.{ .decl = decl_index }));
3500 mod.failed_analysis.putAssumeCapacityNoClobber(AnalUnit.wrap(.{ .decl = decl_index }), try ErrorMsg.create(
3501 mod.gpa,
3502 decl.navSrcLoc(mod),
3503 "unable to analyze: {s}",
3504 .{@errorName(e)},
3505 ));
3506 return error.AnalysisFail;
3507 },
3508 };
3509 };
3510
3511 // TODO: we do not yet have separate dependencies for decl values vs types.
3512 if (decl_was_outdated) {
3513 if (sema_result.invalidate_decl_val or sema_result.invalidate_decl_ref) {
3514 log.debug("Decl tv invalidated ('{d}')", .{@intFromEnum(decl_index)});
3515 // This dependency was marked as PO, meaning dependees were waiting
3516 // on its analysis result, and it has turned out to be outdated.
3517 // Update dependees accordingly.
3518 try mod.markDependeeOutdated(.{ .decl_val = decl_index });
3519 } else {
3520 log.debug("Decl tv up-to-date ('{d}')", .{@intFromEnum(decl_index)});
3521 // This dependency was previously PO, but turned out to be up-to-date.
3522 // We do not need to queue successive analysis.
3523 try mod.markPoDependeeUpToDate(.{ .decl_val = decl_index });
3524 }
3525 }
3526}
3527
3528pub fn ensureFuncBodyAnalyzed(zcu: *Zcu, maybe_coerced_func_index: InternPool.Index) SemaError!void {
3529 const tracy = trace(@src());
3530 defer tracy.end();
3531
3532 const gpa = zcu.gpa;
3533 const ip = &zcu.intern_pool;
3534
3535 // We only care about the uncoerced function.
3536 // We need to do this for the "orphaned function" check below to be valid.
3537 const func_index = ip.unwrapCoercedFunc(maybe_coerced_func_index);
3538
3539 const func = zcu.funcInfo(maybe_coerced_func_index);
3017 const func = mod.funcInfo(func_index);
35403018 const decl_index = func.owner_decl;
3541 const decl = zcu.declPtr(decl_index);
3542
3543 log.debug("ensureFuncBodyAnalyzed '{d}' (instance of '{}')", .{
3544 @intFromEnum(func_index),
3545 decl.name.fmt(ip),
3546 });
3547
3548 // First, our owner decl must be up-to-date. This will always be the case
3549 // during the first update, but may not on successive updates if we happen
3550 // to get analyzed before our parent decl.
3551 try zcu.ensureDeclAnalyzed(decl_index);
3552
3553 // On an update, it's possible this function changed such that our owner
3554 // decl now refers to a different function, making this one orphaned. If
3555 // that's the case, we should remove this function from the binary.
3556 if (decl.val.ip_index != func_index) {
3557 try zcu.markDependeeOutdated(.{ .func_ies = func_index });
3558 ip.removeDependenciesForDepender(gpa, AnalUnit.wrap(.{ .func = func_index }));
3559 ip.remove(func_index);
3560 @panic("TODO: remove orphaned function from binary");
3561 }
3562
3563 // We'll want to remember what the IES used to be before the update for
3564 // dependency invalidation purposes.
3565 const old_resolved_ies = if (func.analysis(ip).inferred_error_set)
3566 func.resolvedErrorSet(ip).*
3567 else
3568 .none;
3019 const decl = mod.declPtr(decl_index);
35693020
35703021 switch (decl.analysis) {
35713022 .unreferenced => unreachable,
35723023 .in_progress => unreachable,
35733024
3574 .codegen_failure => unreachable, // functions do not perform constant value generation
3575
35763025 .file_failure,
35773026 .sema_failure,
3027 .codegen_failure,
35783028 .dependency_failure,
3579 => return error.AnalysisFail,
3029 // Analysis of the function Decl itself failed, but we've already
3030 // emitted an error for that. The callee doesn't need the function to be
3031 // analyzed right now, so its analysis can safely continue.
3032 => return,
35803033
35813034 .complete => {},
35823035 }
35833036
3584 const func_as_depender = AnalUnit.wrap(.{ .func = func_index });
3585 const was_outdated = zcu.outdated.swapRemove(func_as_depender) or
3586 zcu.potentially_outdated.swapRemove(func_as_depender);
3037 assert(decl.has_tv);
35873038
3588 if (was_outdated) {
3589 if (build_options.only_c) unreachable;
3590 _ = zcu.outdated_ready.swapRemove(func_as_depender);
3591 zcu.deleteUnitExports(func_as_depender);
3592 zcu.deleteUnitReferences(func_as_depender);
3593 }
3039 const func_as_depender = AnalUnit.wrap(.{ .func = func_index });
3040 const is_outdated = mod.outdated.contains(func_as_depender) or
3041 mod.potentially_outdated.contains(func_as_depender);
35943042
35953043 switch (func.analysis(ip).state) {
3596 .success => if (!was_outdated) return,
3044 .none => {},
3045 .queued => return,
3046 // As above, we don't need to forward errors here.
35973047 .sema_failure,
35983048 .dependency_failure,
35993049 .codegen_failure,
3600 => if (!was_outdated) return error.AnalysisFail,
3601 .none, .queued => {},
3602 .in_progress => unreachable,
3050 .success,
3051 => if (!is_outdated) return,
3052 .in_progress => return,
36033053 .inline_only => unreachable, // don't queue work for this
36043054 }
36053055
3606 log.debug("analyze and generate fn body '{d}'; reason='{s}'", .{
3607 @intFromEnum(func_index),
3608 if (was_outdated) "outdated" else "never analyzed",
3609 });
3610
3611 var tmp_arena = std.heap.ArenaAllocator.init(gpa);
3612 defer tmp_arena.deinit();
3613 const sema_arena = tmp_arena.allocator();
3614
3615 var air = zcu.analyzeFnBody(func_index, sema_arena) catch |err| switch (err) {
3616 error.AnalysisFail => {
3617 if (func.analysis(ip).state == .in_progress) {
3618 // If this decl caused the compile error, the analysis field would
3619 // be changed to indicate it was this Decl's fault. Because this
3620 // did not happen, we infer here that it was a dependency failure.
3621 func.analysis(ip).state = .dependency_failure;
3622 }
3623 return error.AnalysisFail;
3624 },
3625 error.OutOfMemory => return error.OutOfMemory,
3626 };
3627 errdefer air.deinit(gpa);
3056 // Decl itself is safely analyzed, and body analysis is not yet queued
36283057
3629 const invalidate_ies_deps = i: {
3630 if (!was_outdated) break :i false;
3631 if (!func.analysis(ip).inferred_error_set) break :i true;
3632 const new_resolved_ies = func.resolvedErrorSet(ip).*;
3633 break :i new_resolved_ies != old_resolved_ies;
3634 };
3635 if (invalidate_ies_deps) {
3636 log.debug("func IES invalidated ('{d}')", .{@intFromEnum(func_index)});
3637 try zcu.markDependeeOutdated(.{ .func_ies = func_index });
3638 } else if (was_outdated) {
3639 log.debug("func IES up-to-date ('{d}')", .{@intFromEnum(func_index)});
3640 try zcu.markPoDependeeUpToDate(.{ .func_ies = func_index });
3058 try mod.comp.work_queue.writeItem(.{ .analyze_func = func_index });
3059 if (mod.emit_h != null) {
3060 // TODO: we ideally only want to do this if the function's type changed
3061 // since the last update
3062 try mod.comp.work_queue.writeItem(.{ .emit_h_decl = decl_index });
36413063 }
3064 func.analysis(ip).state = .queued;
3065}
36423066
3643 const comp = zcu.comp;
3644
3645 const dump_air = build_options.enable_debug_extensions and comp.verbose_air;
3646 const dump_llvm_ir = build_options.enable_debug_extensions and (comp.verbose_llvm_ir != null or comp.verbose_llvm_bc != null);
3647
3648 if (comp.bin_file == null and zcu.llvm_object == null and !dump_air and !dump_llvm_ir) {
3649 air.deinit(gpa);
3650 return;
3651 }
3067pub const SemaDeclResult = packed struct {
3068 /// Whether the value of a `decl_val` of this Decl changed.
3069 invalidate_decl_val: bool,
3070 /// Whether the type of a `decl_ref` of this Decl changed.
3071 invalidate_decl_ref: bool,
3072};
36523073
3653 try comp.work_queue.writeItem(.{ .codegen_func = .{
3654 .func = func_index,
3655 .air = air,
3656 } });
3657}
3074pub const ImportFileResult = struct {
3075 file: *File,
3076 file_index: File.Index,
3077 is_new: bool,
3078 is_pkg: bool,
3079};
36583080
3659/// Takes ownership of `air`, even on error.
3660/// If any types referenced by `air` are unresolved, marks the codegen as failed.
3661pub fn linkerUpdateFunc(zcu: *Zcu, func_index: InternPool.Index, air: Air) Allocator.Error!void {
3662 const gpa = zcu.gpa;
3663 const ip = &zcu.intern_pool;
3664 const comp = zcu.comp;
3665
3666 defer {
3667 var air_mut = air;
3668 air_mut.deinit(gpa);
3669 }
3670
3671 const func = zcu.funcInfo(func_index);
3672 const decl_index = func.owner_decl;
3673 const decl = zcu.declPtr(decl_index);
3674
3675 var liveness = try Liveness.analyze(gpa, air, ip);
3676 defer liveness.deinit(gpa);
3677
3678 if (build_options.enable_debug_extensions and comp.verbose_air) {
3679 const fqn = try decl.fullyQualifiedName(zcu);
3680 std.debug.print("# Begin Function AIR: {}:\n", .{fqn.fmt(ip)});
3681 @import("print_air.zig").dump(zcu, air, liveness);
3682 std.debug.print("# End Function AIR: {}\n\n", .{fqn.fmt(ip)});
3683 }
3684
3685 if (std.debug.runtime_safety) {
3686 var verify: Liveness.Verify = .{
3687 .gpa = gpa,
3688 .air = air,
3689 .liveness = liveness,
3690 .intern_pool = ip,
3691 };
3692 defer verify.deinit();
3693
3694 verify.verify() catch |err| switch (err) {
3695 error.OutOfMemory => return error.OutOfMemory,
3696 else => {
3697 try zcu.failed_analysis.ensureUnusedCapacity(gpa, 1);
3698 zcu.failed_analysis.putAssumeCapacityNoClobber(
3699 AnalUnit.wrap(.{ .func = func_index }),
3700 try Module.ErrorMsg.create(
3701 gpa,
3702 decl.navSrcLoc(zcu),
3703 "invalid liveness: {s}",
3704 .{@errorName(err)},
3705 ),
3706 );
3707 func.analysis(ip).state = .codegen_failure;
3708 return;
3709 },
3710 };
3711 }
3712
3713 const codegen_prog_node = zcu.codegen_prog_node.start((try decl.fullyQualifiedName(zcu)).toSlice(ip), 0);
3714 defer codegen_prog_node.end();
3715
3716 if (!air.typesFullyResolved(zcu)) {
3717 // A type we depend on failed to resolve. This is a transitive failure.
3718 // Correcting this failure will involve changing a type this function
3719 // depends on, hence triggering re-analysis of this function, so this
3720 // interacts correctly with incremental compilation.
3721 func.analysis(ip).state = .codegen_failure;
3722 } else if (comp.bin_file) |lf| {
3723 lf.updateFunc(zcu, func_index, air, liveness) catch |err| switch (err) {
3724 error.OutOfMemory => return error.OutOfMemory,
3725 error.AnalysisFail => {
3726 func.analysis(ip).state = .codegen_failure;
3727 },
3728 else => {
3729 try zcu.failed_analysis.ensureUnusedCapacity(gpa, 1);
3730 zcu.failed_analysis.putAssumeCapacityNoClobber(AnalUnit.wrap(.{ .func = func_index }), try Module.ErrorMsg.create(
3731 gpa,
3732 decl.navSrcLoc(zcu),
3733 "unable to codegen: {s}",
3734 .{@errorName(err)},
3735 ));
3736 func.analysis(ip).state = .codegen_failure;
3737 try zcu.retryable_failures.append(zcu.gpa, AnalUnit.wrap(.{ .func = func_index }));
3738 },
3739 };
3740 } else if (zcu.llvm_object) |llvm_object| {
3741 if (build_options.only_c) unreachable;
3742 llvm_object.updateFunc(zcu, func_index, air, liveness) catch |err| switch (err) {
3743 error.OutOfMemory => return error.OutOfMemory,
3744 };
3745 }
3746}
3747
3748/// Ensure this function's body is or will be analyzed and emitted. This should
3749/// be called whenever a potential runtime call of a function is seen.
3750///
3751/// The caller is responsible for ensuring the function decl itself is already
3752/// analyzed, and for ensuring it can exist at runtime (see
3753/// `sema.fnHasRuntimeBits`). This function does *not* guarantee that the body
3754/// will be analyzed when it returns: for that, see `ensureFuncBodyAnalyzed`.
3755pub fn ensureFuncBodyAnalysisQueued(mod: *Module, func_index: InternPool.Index) !void {
3756 const ip = &mod.intern_pool;
3757 const func = mod.funcInfo(func_index);
3758 const decl_index = func.owner_decl;
3759 const decl = mod.declPtr(decl_index);
3760
3761 switch (decl.analysis) {
3762 .unreferenced => unreachable,
3763 .in_progress => unreachable,
3764
3765 .file_failure,
3766 .sema_failure,
3767 .codegen_failure,
3768 .dependency_failure,
3769 // Analysis of the function Decl itself failed, but we've already
3770 // emitted an error for that. The callee doesn't need the function to be
3771 // analyzed right now, so its analysis can safely continue.
3772 => return,
3773
3774 .complete => {},
3775 }
3776
3777 assert(decl.has_tv);
3778
3779 const func_as_depender = AnalUnit.wrap(.{ .func = func_index });
3780 const is_outdated = mod.outdated.contains(func_as_depender) or
3781 mod.potentially_outdated.contains(func_as_depender);
3782
3783 switch (func.analysis(ip).state) {
3784 .none => {},
3785 .queued => return,
3786 // As above, we don't need to forward errors here.
3787 .sema_failure,
3788 .dependency_failure,
3789 .codegen_failure,
3790 .success,
3791 => if (!is_outdated) return,
3792 .in_progress => return,
3793 .inline_only => unreachable, // don't queue work for this
3794 }
3795
3796 // Decl itself is safely analyzed, and body analysis is not yet queued
3797
3798 try mod.comp.work_queue.writeItem(.{ .analyze_func = func_index });
3799 if (mod.emit_h != null) {
3800 // TODO: we ideally only want to do this if the function's type changed
3801 // since the last update
3802 try mod.comp.work_queue.writeItem(.{ .emit_h_decl = decl_index });
3803 }
3804 func.analysis(ip).state = .queued;
3805}
3806
3807pub fn semaPkg(zcu: *Zcu, pkg: *Package.Module) !void {
3808 const import_file_result = try zcu.importPkg(pkg);
3809 const root_decl_index = zcu.fileRootDecl(import_file_result.file_index);
3810 if (root_decl_index == .none) {
3811 return zcu.semaFile(import_file_result.file_index);
3812 }
3813}
3814
3815fn getFileRootStruct(
3816 zcu: *Zcu,
3817 decl_index: Decl.Index,
3818 namespace_index: Namespace.Index,
3819 file_index: File.Index,
3820) Allocator.Error!InternPool.Index {
3821 const gpa = zcu.gpa;
3822 const ip = &zcu.intern_pool;
3823 const file = zcu.fileByIndex(file_index);
3824 const extended = file.zir.instructions.items(.data)[@intFromEnum(Zir.Inst.Index.main_struct_inst)].extended;
3825 assert(extended.opcode == .struct_decl);
3826 const small: Zir.Inst.StructDecl.Small = @bitCast(extended.small);
3827 assert(!small.has_captures_len);
3828 assert(!small.has_backing_int);
3829 assert(small.layout == .auto);
3830 var extra_index: usize = extended.operand + @typeInfo(Zir.Inst.StructDecl).Struct.fields.len;
3831 const fields_len = if (small.has_fields_len) blk: {
3832 const fields_len = file.zir.extra[extra_index];
3833 extra_index += 1;
3834 break :blk fields_len;
3835 } else 0;
3836 const decls_len = if (small.has_decls_len) blk: {
3837 const decls_len = file.zir.extra[extra_index];
3838 extra_index += 1;
3839 break :blk decls_len;
3840 } else 0;
3841 const decls = file.zir.bodySlice(extra_index, decls_len);
3842 extra_index += decls_len;
3843
3844 const tracked_inst = try ip.trackZir(gpa, file_index, .main_struct_inst);
3845 const wip_ty = switch (try ip.getStructType(gpa, .{
3846 .layout = .auto,
3847 .fields_len = fields_len,
3848 .known_non_opv = small.known_non_opv,
3849 .requires_comptime = if (small.known_comptime_only) .yes else .unknown,
3850 .is_tuple = small.is_tuple,
3851 .any_comptime_fields = small.any_comptime_fields,
3852 .any_default_inits = small.any_default_inits,
3853 .inits_resolved = false,
3854 .any_aligned_fields = small.any_aligned_fields,
3855 .has_namespace = true,
3856 .key = .{ .declared = .{
3857 .zir_index = tracked_inst,
3858 .captures = &.{},
3859 } },
3860 })) {
3861 .existing => unreachable, // we wouldn't be analysing the file root if this type existed
3862 .wip => |wip| wip,
3863 };
3864 errdefer wip_ty.cancel(ip);
3865
3866 if (zcu.comp.debug_incremental) {
3867 try ip.addDependency(
3868 gpa,
3869 AnalUnit.wrap(.{ .decl = decl_index }),
3870 .{ .src_hash = tracked_inst },
3871 );
3872 }
3873
3874 const decl = zcu.declPtr(decl_index);
3875 decl.val = Value.fromInterned(wip_ty.index);
3876 decl.has_tv = true;
3877 decl.owns_tv = true;
3878 decl.analysis = .complete;
3879
3880 try zcu.scanNamespace(namespace_index, decls, decl);
3881 try zcu.comp.work_queue.writeItem(.{ .resolve_type_fully = wip_ty.index });
3882 return wip_ty.finish(ip, decl_index, namespace_index.toOptional());
3883}
3884
3885/// Re-analyze the root Decl of a file on an incremental update.
3886/// If `type_outdated`, the struct type itself is considered outdated and is
3887/// reconstructed at a new InternPool index. Otherwise, the namespace is just
3888/// re-analyzed. Returns whether the decl's tyval was invalidated.
3889fn semaFileUpdate(zcu: *Zcu, file_index: File.Index, type_outdated: bool) SemaError!bool {
3890 const file = zcu.fileByIndex(file_index);
3891 const decl = zcu.declPtr(zcu.fileRootDecl(file_index).unwrap().?);
3892
3893 log.debug("semaFileUpdate mod={s} sub_file_path={s} type_outdated={}", .{
3894 file.mod.fully_qualified_name,
3895 file.sub_file_path,
3896 type_outdated,
3897 });
3898
3899 if (file.status != .success_zir) {
3900 if (decl.analysis == .file_failure) {
3901 return false;
3902 } else {
3903 decl.analysis = .file_failure;
3904 return true;
3905 }
3906 }
3907
3908 if (decl.analysis == .file_failure) {
3909 // No struct type currently exists. Create one!
3910 const root_decl = zcu.fileRootDecl(file_index);
3911 _ = try zcu.getFileRootStruct(root_decl.unwrap().?, decl.src_namespace, file_index);
3912 return true;
3913 }
3914
3915 assert(decl.has_tv);
3916 assert(decl.owns_tv);
3917
3918 if (type_outdated) {
3919 // Invalidate the existing type, reusing the decl and namespace.
3920 const file_root_decl = zcu.fileRootDecl(file_index).unwrap().?;
3921 zcu.intern_pool.removeDependenciesForDepender(zcu.gpa, AnalUnit.wrap(.{
3922 .decl = file_root_decl,
3923 }));
3924 zcu.intern_pool.remove(decl.val.toIntern());
3925 decl.val = undefined;
3926 _ = try zcu.getFileRootStruct(file_root_decl, decl.src_namespace, file_index);
3927 return true;
3928 }
3929
3930 // Only the struct's namespace is outdated.
3931 // Preserve the type - just scan the namespace again.
3932
3933 const extended = file.zir.instructions.items(.data)[@intFromEnum(Zir.Inst.Index.main_struct_inst)].extended;
3934 const small: Zir.Inst.StructDecl.Small = @bitCast(extended.small);
3935
3936 var extra_index: usize = extended.operand + @typeInfo(Zir.Inst.StructDecl).Struct.fields.len;
3937 extra_index += @intFromBool(small.has_fields_len);
3938 const decls_len = if (small.has_decls_len) blk: {
3939 const decls_len = file.zir.extra[extra_index];
3940 extra_index += 1;
3941 break :blk decls_len;
3942 } else 0;
3943 const decls = file.zir.bodySlice(extra_index, decls_len);
3944
3945 if (!type_outdated) {
3946 try zcu.scanNamespace(decl.src_namespace, decls, decl);
3947 }
3948
3949 return false;
3950}
3951
3952/// Regardless of the file status, will create a `Decl` if none exists so that we can track
3953/// dependencies and re-analyze when the file becomes outdated.
3954fn semaFile(zcu: *Zcu, file_index: File.Index) SemaError!void {
3955 const tracy = trace(@src());
3956 defer tracy.end();
3957
3958 const file = zcu.fileByIndex(file_index);
3959 assert(zcu.fileRootDecl(file_index) == .none);
3960
3961 const gpa = zcu.gpa;
3962 log.debug("semaFile zcu={s} sub_file_path={s}", .{
3963 file.mod.fully_qualified_name, file.sub_file_path,
3964 });
3965
3966 // Because these three things each reference each other, `undefined`
3967 // placeholders are used before being set after the struct type gains an
3968 // InternPool index.
3969 const new_namespace_index = try zcu.createNamespace(.{
3970 .parent = .none,
3971 .decl_index = undefined,
3972 .file_scope = file_index,
3973 });
3974 errdefer zcu.destroyNamespace(new_namespace_index);
3975
3976 const new_decl_index = try zcu.allocateNewDecl(new_namespace_index);
3977 const new_decl = zcu.declPtr(new_decl_index);
3978 errdefer @panic("TODO error handling");
3979
3980 zcu.setFileRootDecl(file_index, new_decl_index.toOptional());
3981 zcu.namespacePtr(new_namespace_index).decl_index = new_decl_index;
3982
3983 new_decl.name = try file.fullyQualifiedName(zcu);
3984 new_decl.name_fully_qualified = true;
3985 new_decl.is_pub = true;
3986 new_decl.is_exported = false;
3987 new_decl.alignment = .none;
3988 new_decl.@"linksection" = .none;
3989 new_decl.analysis = .in_progress;
3990
3991 if (file.status != .success_zir) {
3992 new_decl.analysis = .file_failure;
3993 return;
3994 }
3995 assert(file.zir_loaded);
3996
3997 const struct_ty = try zcu.getFileRootStruct(new_decl_index, new_namespace_index, file_index);
3998 errdefer zcu.intern_pool.remove(struct_ty);
3999
4000 switch (zcu.comp.cache_use) {
4001 .whole => |whole| if (whole.cache_manifest) |man| {
4002 const source = file.getSource(gpa) catch |err| {
4003 try reportRetryableFileError(zcu, file_index, "unable to load source: {s}", .{@errorName(err)});
4004 return error.AnalysisFail;
4005 };
4006
4007 const resolved_path = std.fs.path.resolve(gpa, &.{
4008 file.mod.root.root_dir.path orelse ".",
4009 file.mod.root.sub_path,
4010 file.sub_file_path,
4011 }) catch |err| {
4012 try reportRetryableFileError(zcu, file_index, "unable to resolve path: {s}", .{@errorName(err)});
4013 return error.AnalysisFail;
4014 };
4015 errdefer gpa.free(resolved_path);
4016
4017 whole.cache_manifest_mutex.lock();
4018 defer whole.cache_manifest_mutex.unlock();
4019 try man.addFilePostContents(resolved_path, source.bytes, source.stat);
4020 },
4021 .incremental => {},
4022 }
4023}
4024
4025const SemaDeclResult = packed struct {
4026 /// Whether the value of a `decl_val` of this Decl changed.
4027 invalidate_decl_val: bool,
4028 /// Whether the type of a `decl_ref` of this Decl changed.
4029 invalidate_decl_ref: bool,
4030};
4031
4032fn semaDecl(zcu: *Zcu, decl_index: Decl.Index) !SemaDeclResult {
4033 const tracy = trace(@src());
4034 defer tracy.end();
4035
4036 const decl = zcu.declPtr(decl_index);
4037 const ip = &zcu.intern_pool;
4038
4039 if (decl.getFileScope(zcu).status != .success_zir) {
4040 return error.AnalysisFail;
4041 }
4042
4043 assert(!zcu.declIsRoot(decl_index));
4044
4045 if (decl.zir_decl_index == .none and decl.owns_tv) {
4046 // We are re-analyzing an anonymous owner Decl (for a function or a namespace type).
4047 return zcu.semaAnonOwnerDecl(decl_index);
4048 }
4049
4050 log.debug("semaDecl '{d}'", .{@intFromEnum(decl_index)});
4051 log.debug("decl name '{}'", .{(try decl.fullyQualifiedName(zcu)).fmt(ip)});
4052 defer blk: {
4053 log.debug("finish decl name '{}'", .{(decl.fullyQualifiedName(zcu) catch break :blk).fmt(ip)});
4054 }
4055
4056 const old_has_tv = decl.has_tv;
4057 // The following values are ignored if `!old_has_tv`
4058 const old_ty = if (old_has_tv) decl.typeOf(zcu) else undefined;
4059 const old_val = decl.val;
4060 const old_align = decl.alignment;
4061 const old_linksection = decl.@"linksection";
4062 const old_addrspace = decl.@"addrspace";
4063 const old_is_inline = if (decl.getOwnedFunction(zcu)) |prev_func|
4064 prev_func.analysis(ip).state == .inline_only
4065 else
4066 false;
4067
4068 const decl_inst = decl.zir_decl_index.unwrap().?.resolve(ip);
4069
4070 const gpa = zcu.gpa;
4071 const zir = decl.getFileScope(zcu).zir;
4072
4073 const builtin_type_target_index: InternPool.Index = ip_index: {
4074 const std_mod = zcu.std_mod;
4075 if (decl.getFileScope(zcu).mod != std_mod) break :ip_index .none;
4076 // We're in the std module.
4077 const std_file_imported = try zcu.importPkg(std_mod);
4078 const std_file_root_decl_index = zcu.fileRootDecl(std_file_imported.file_index);
4079 const std_decl = zcu.declPtr(std_file_root_decl_index.unwrap().?);
4080 const std_namespace = std_decl.getInnerNamespace(zcu).?;
4081 const builtin_str = try ip.getOrPutString(gpa, "builtin", .no_embedded_nulls);
4082 const builtin_decl = zcu.declPtr(std_namespace.decls.getKeyAdapted(builtin_str, DeclAdapter{ .zcu = zcu }) orelse break :ip_index .none);
4083 const builtin_namespace = builtin_decl.getInnerNamespaceIndex(zcu).unwrap() orelse break :ip_index .none;
4084 if (decl.src_namespace != builtin_namespace) break :ip_index .none;
4085 // We're in builtin.zig. This could be a builtin we need to add to a specific InternPool index.
4086 for ([_][]const u8{
4087 "AtomicOrder",
4088 "AtomicRmwOp",
4089 "CallingConvention",
4090 "AddressSpace",
4091 "FloatMode",
4092 "ReduceOp",
4093 "CallModifier",
4094 "PrefetchOptions",
4095 "ExportOptions",
4096 "ExternOptions",
4097 "Type",
4098 }, [_]InternPool.Index{
4099 .atomic_order_type,
4100 .atomic_rmw_op_type,
4101 .calling_convention_type,
4102 .address_space_type,
4103 .float_mode_type,
4104 .reduce_op_type,
4105 .call_modifier_type,
4106 .prefetch_options_type,
4107 .export_options_type,
4108 .extern_options_type,
4109 .type_info_type,
4110 }) |type_name, type_ip| {
4111 if (decl.name.eqlSlice(type_name, ip)) break :ip_index type_ip;
4112 }
4113 break :ip_index .none;
4114 };
4115
4116 zcu.intern_pool.removeDependenciesForDepender(gpa, AnalUnit.wrap(.{ .decl = decl_index }));
4117
4118 decl.analysis = .in_progress;
4119
4120 var analysis_arena = std.heap.ArenaAllocator.init(gpa);
4121 defer analysis_arena.deinit();
4122
4123 var comptime_err_ret_trace = std.ArrayList(LazySrcLoc).init(gpa);
4124 defer comptime_err_ret_trace.deinit();
4125
4126 var sema: Sema = .{
4127 .mod = zcu,
4128 .gpa = gpa,
4129 .arena = analysis_arena.allocator(),
4130 .code = zir,
4131 .owner_decl = decl,
4132 .owner_decl_index = decl_index,
4133 .func_index = .none,
4134 .func_is_naked = false,
4135 .fn_ret_ty = Type.void,
4136 .fn_ret_ty_ies = null,
4137 .owner_func_index = .none,
4138 .comptime_err_ret_trace = &comptime_err_ret_trace,
4139 .builtin_type_target_index = builtin_type_target_index,
4140 };
4141 defer sema.deinit();
4142
4143 // Every Decl (other than file root Decls, which do not have a ZIR index) has a dependency on its own source.
4144 try sema.declareDependency(.{ .src_hash = try ip.trackZir(
4145 gpa,
4146 decl.getFileScopeIndex(zcu),
4147 decl_inst,
4148 ) });
4149
4150 var block_scope: Sema.Block = .{
4151 .parent = null,
4152 .sema = &sema,
4153 .namespace = decl.src_namespace,
4154 .instructions = .{},
4155 .inlining = null,
4156 .is_comptime = true,
4157 .src_base_inst = decl.zir_decl_index.unwrap().?,
4158 .type_name_ctx = decl.name,
4159 };
4160 defer block_scope.instructions.deinit(gpa);
4161
4162 const decl_bodies = decl.zirBodies(zcu);
4163
4164 const result_ref = try sema.resolveInlineBody(&block_scope, decl_bodies.value_body, decl_inst);
4165 // We'll do some other bits with the Sema. Clear the type target index just
4166 // in case they analyze any type.
4167 sema.builtin_type_target_index = .none;
4168 const align_src: LazySrcLoc = block_scope.src(.{ .node_offset_var_decl_align = 0 });
4169 const section_src: LazySrcLoc = block_scope.src(.{ .node_offset_var_decl_section = 0 });
4170 const address_space_src: LazySrcLoc = block_scope.src(.{ .node_offset_var_decl_addrspace = 0 });
4171 const ty_src: LazySrcLoc = block_scope.src(.{ .node_offset_var_decl_ty = 0 });
4172 const init_src: LazySrcLoc = block_scope.src(.{ .node_offset_var_decl_init = 0 });
4173 const decl_val = try sema.resolveFinalDeclValue(&block_scope, init_src, result_ref);
4174 const decl_ty = decl_val.typeOf(zcu);
4175
4176 // Note this resolves the type of the Decl, not the value; if this Decl
4177 // is a struct, for example, this resolves `type` (which needs no resolution),
4178 // not the struct itself.
4179 try decl_ty.resolveLayout(zcu);
4180
4181 if (decl.kind == .@"usingnamespace") {
4182 if (!decl_ty.eql(Type.type, zcu)) {
4183 return sema.fail(&block_scope, ty_src, "expected type, found {}", .{
4184 decl_ty.fmt(zcu),
4185 });
4186 }
4187 const ty = decl_val.toType();
4188 if (ty.getNamespace(zcu) == null) {
4189 return sema.fail(&block_scope, ty_src, "type {} has no namespace", .{ty.fmt(zcu)});
4190 }
4191
4192 decl.val = ty.toValue();
4193 decl.alignment = .none;
4194 decl.@"linksection" = .none;
4195 decl.has_tv = true;
4196 decl.owns_tv = false;
4197 decl.analysis = .complete;
4198
4199 // TODO: usingnamespace cannot currently participate in incremental compilation
4200 return .{
4201 .invalidate_decl_val = true,
4202 .invalidate_decl_ref = true,
4203 };
4204 }
4205
4206 var queue_linker_work = true;
4207 var is_func = false;
4208 var is_inline = false;
4209 switch (decl_val.toIntern()) {
4210 .generic_poison => unreachable,
4211 .unreachable_value => unreachable,
4212 else => switch (ip.indexToKey(decl_val.toIntern())) {
4213 .variable => |variable| {
4214 decl.owns_tv = variable.decl == decl_index;
4215 queue_linker_work = decl.owns_tv;
4216 },
4217
4218 .extern_func => |extern_func| {
4219 decl.owns_tv = extern_func.decl == decl_index;
4220 queue_linker_work = decl.owns_tv;
4221 is_func = decl.owns_tv;
4222 },
4223
4224 .func => |func| {
4225 decl.owns_tv = func.owner_decl == decl_index;
4226 queue_linker_work = false;
4227 is_inline = decl.owns_tv and decl_ty.fnCallingConvention(zcu) == .Inline;
4228 is_func = decl.owns_tv;
4229 },
4230
4231 else => {},
4232 },
4233 }
4234
4235 decl.val = decl_val;
4236 // Function linksection, align, and addrspace were already set by Sema
4237 if (!is_func) {
4238 decl.alignment = blk: {
4239 const align_body = decl_bodies.align_body orelse break :blk .none;
4240 const align_ref = try sema.resolveInlineBody(&block_scope, align_body, decl_inst);
4241 break :blk try sema.analyzeAsAlign(&block_scope, align_src, align_ref);
4242 };
4243 decl.@"linksection" = blk: {
4244 const linksection_body = decl_bodies.linksection_body orelse break :blk .none;
4245 const linksection_ref = try sema.resolveInlineBody(&block_scope, linksection_body, decl_inst);
4246 const bytes = try sema.toConstString(&block_scope, section_src, linksection_ref, .{
4247 .needed_comptime_reason = "linksection must be comptime-known",
4248 });
4249 if (mem.indexOfScalar(u8, bytes, 0) != null) {
4250 return sema.fail(&block_scope, section_src, "linksection cannot contain null bytes", .{});
4251 } else if (bytes.len == 0) {
4252 return sema.fail(&block_scope, section_src, "linksection cannot be empty", .{});
4253 }
4254 break :blk try ip.getOrPutStringOpt(gpa, bytes, .no_embedded_nulls);
4255 };
4256 decl.@"addrspace" = blk: {
4257 const addrspace_ctx: Sema.AddressSpaceContext = switch (ip.indexToKey(decl_val.toIntern())) {
4258 .variable => .variable,
4259 .extern_func, .func => .function,
4260 else => .constant,
4261 };
4262
4263 const target = sema.mod.getTarget();
4264
4265 const addrspace_body = decl_bodies.addrspace_body orelse break :blk switch (addrspace_ctx) {
4266 .function => target_util.defaultAddressSpace(target, .function),
4267 .variable => target_util.defaultAddressSpace(target, .global_mutable),
4268 .constant => target_util.defaultAddressSpace(target, .global_constant),
4269 else => unreachable,
4270 };
4271 const addrspace_ref = try sema.resolveInlineBody(&block_scope, addrspace_body, decl_inst);
4272 break :blk try sema.analyzeAsAddressSpace(&block_scope, address_space_src, addrspace_ref, addrspace_ctx);
4273 };
4274 }
4275 decl.has_tv = true;
4276 decl.analysis = .complete;
4277
4278 const result: SemaDeclResult = if (old_has_tv) .{
4279 .invalidate_decl_val = !decl_ty.eql(old_ty, zcu) or
4280 !decl.val.eql(old_val, decl_ty, zcu) or
4281 is_inline != old_is_inline,
4282 .invalidate_decl_ref = !decl_ty.eql(old_ty, zcu) or
4283 decl.alignment != old_align or
4284 decl.@"linksection" != old_linksection or
4285 decl.@"addrspace" != old_addrspace or
4286 is_inline != old_is_inline,
4287 } else .{
4288 .invalidate_decl_val = true,
4289 .invalidate_decl_ref = true,
4290 };
4291
4292 const has_runtime_bits = queue_linker_work and (is_func or try sema.typeHasRuntimeBits(decl_ty));
4293 if (has_runtime_bits) {
4294 // Needed for codegen_decl which will call updateDecl and then the
4295 // codegen backend wants full access to the Decl Type.
4296 try decl_ty.resolveFully(zcu);
4297
4298 try zcu.comp.work_queue.writeItem(.{ .codegen_decl = decl_index });
4299
4300 if (result.invalidate_decl_ref and zcu.emit_h != null) {
4301 try zcu.comp.work_queue.writeItem(.{ .emit_h_decl = decl_index });
4302 }
4303 }
4304
4305 if (decl.is_exported) {
4306 const export_src: LazySrcLoc = block_scope.src(.{ .token_offset = @intFromBool(decl.is_pub) });
4307 if (is_inline) return sema.fail(&block_scope, export_src, "export of inline function", .{});
4308 // The scope needs to have the decl in it.
4309 try sema.analyzeExport(&block_scope, export_src, .{ .name = decl.name }, decl_index);
4310 }
4311
4312 try sema.flushExports();
4313
4314 return result;
4315}
4316
4317fn semaAnonOwnerDecl(zcu: *Zcu, decl_index: Decl.Index) !SemaDeclResult {
4318 const decl = zcu.declPtr(decl_index);
4319
4320 assert(decl.has_tv);
4321 assert(decl.owns_tv);
4322
4323 log.debug("semaAnonOwnerDecl '{d}'", .{@intFromEnum(decl_index)});
4324
4325 switch (decl.typeOf(zcu).zigTypeTag(zcu)) {
4326 .Fn => @panic("TODO: update fn instance"),
4327 .Type => {},
4328 else => unreachable,
4329 }
4330
4331 // We are the owner Decl of a type, and we were marked as outdated. That means the *structure*
4332 // of this type changed; not just its namespace. Therefore, we need a new InternPool index.
4333 //
4334 // However, as soon as we make that, the context that created us will require re-analysis anyway
4335 // (as it depends on this Decl's value), meaning the `struct_decl` (or equivalent) instruction
4336 // will be analyzed again. Since Sema already needs to be able to reconstruct types like this,
4337 // why should we bother implementing it here too when the Sema logic will be hit right after?
4338 //
4339 // So instead, let's just mark this Decl as failed - so that any remaining Decls which genuinely
4340 // reference it (via `@This`) end up silently erroring too - and we'll let Sema make a new type
4341 // with a new Decl.
4342 //
4343 // Yes, this does mean that any type owner Decl has a constant value for its entire lifetime.
4344 zcu.intern_pool.removeDependenciesForDepender(zcu.gpa, AnalUnit.wrap(.{ .decl = decl_index }));
4345 zcu.intern_pool.remove(decl.val.toIntern());
4346 decl.analysis = .dependency_failure;
4347 return .{
4348 .invalidate_decl_val = true,
4349 .invalidate_decl_ref = true,
4350 };
4351}
4352
4353pub const ImportFileResult = struct {
4354 file: *File,
4355 file_index: File.Index,
4356 is_new: bool,
4357 is_pkg: bool,
4358};
4359
4360pub fn importPkg(zcu: *Zcu, mod: *Package.Module) !ImportFileResult {
3081pub fn importPkg(zcu: *Zcu, mod: *Package.Module) !ImportFileResult {
43613082 const gpa = zcu.gpa;
43623083
43633084 // The resolved path is used as the key in the import table, to detect if
......@@ -4533,78 +3254,6 @@ pub fn importFile(
45333254 };
45343255}
45353256
4536pub fn embedFile(
4537 mod: *Module,
4538 cur_file: *File,
4539 import_string: []const u8,
4540 src_loc: LazySrcLoc,
4541) !InternPool.Index {
4542 const gpa = mod.gpa;
4543
4544 if (cur_file.mod.deps.get(import_string)) |pkg| {
4545 const resolved_path = try std.fs.path.resolve(gpa, &.{
4546 pkg.root.root_dir.path orelse ".",
4547 pkg.root.sub_path,
4548 pkg.root_src_path,
4549 });
4550 var keep_resolved_path = false;
4551 defer if (!keep_resolved_path) gpa.free(resolved_path);
4552
4553 const gop = try mod.embed_table.getOrPut(gpa, resolved_path);
4554 errdefer {
4555 assert(std.mem.eql(u8, mod.embed_table.pop().key, resolved_path));
4556 keep_resolved_path = false;
4557 }
4558 if (gop.found_existing) return gop.value_ptr.*.val;
4559 keep_resolved_path = true;
4560
4561 const sub_file_path = try gpa.dupe(u8, pkg.root_src_path);
4562 errdefer gpa.free(sub_file_path);
4563
4564 return newEmbedFile(mod, pkg, sub_file_path, resolved_path, gop.value_ptr, src_loc);
4565 }
4566
4567 // The resolved path is used as the key in the table, to detect if a file
4568 // refers to the same as another, despite different relative paths.
4569 const resolved_path = try std.fs.path.resolve(gpa, &.{
4570 cur_file.mod.root.root_dir.path orelse ".",
4571 cur_file.mod.root.sub_path,
4572 cur_file.sub_file_path,
4573 "..",
4574 import_string,
4575 });
4576
4577 var keep_resolved_path = false;
4578 defer if (!keep_resolved_path) gpa.free(resolved_path);
4579
4580 const gop = try mod.embed_table.getOrPut(gpa, resolved_path);
4581 errdefer {
4582 assert(std.mem.eql(u8, mod.embed_table.pop().key, resolved_path));
4583 keep_resolved_path = false;
4584 }
4585 if (gop.found_existing) return gop.value_ptr.*.val;
4586 keep_resolved_path = true;
4587
4588 const resolved_root_path = try std.fs.path.resolve(gpa, &.{
4589 cur_file.mod.root.root_dir.path orelse ".",
4590 cur_file.mod.root.sub_path,
4591 });
4592 defer gpa.free(resolved_root_path);
4593
4594 const sub_file_path = p: {
4595 const relative = try std.fs.path.relative(gpa, resolved_root_path, resolved_path);
4596 errdefer gpa.free(relative);
4597
4598 if (!isUpDir(relative) and !std.fs.path.isAbsolute(relative)) {
4599 break :p relative;
4600 }
4601 return error.ImportOutsideModulePath;
4602 };
4603 defer gpa.free(sub_file_path);
4604
4605 return newEmbedFile(mod, cur_file.mod, sub_file_path, resolved_path, gop.value_ptr, src_loc);
4606}
4607
46083257fn computePathDigest(zcu: *Zcu, mod: *Package.Module, sub_file_path: []const u8) Cache.BinDigest {
46093258 const want_local_cache = mod == zcu.main_mod;
46103259 var path_hash: Cache.HashHelper = .{};
......@@ -4620,349 +3269,6 @@ fn computePathDigest(zcu: *Zcu, mod: *Package.Module, sub_file_path: []const u8)
46203269 return bin;
46213270}
46223271
4623/// https://github.com/ziglang/zig/issues/14307
4624fn newEmbedFile(
4625 mod: *Module,
4626 pkg: *Package.Module,
4627 sub_file_path: []const u8,
4628 resolved_path: []const u8,
4629 result: **EmbedFile,
4630 src_loc: LazySrcLoc,
4631) !InternPool.Index {
4632 const gpa = mod.gpa;
4633 const ip = &mod.intern_pool;
4634
4635 const new_file = try gpa.create(EmbedFile);
4636 errdefer gpa.destroy(new_file);
4637
4638 var file = try pkg.root.openFile(sub_file_path, .{});
4639 defer file.close();
4640
4641 const actual_stat = try file.stat();
4642 const stat: Cache.File.Stat = .{
4643 .size = actual_stat.size,
4644 .inode = actual_stat.inode,
4645 .mtime = actual_stat.mtime,
4646 };
4647 const size = std.math.cast(usize, actual_stat.size) orelse return error.Overflow;
4648
4649 const bytes = try ip.string_bytes.addManyAsSlice(gpa, try std.math.add(usize, size, 1));
4650 const actual_read = try file.readAll(bytes[0..size]);
4651 if (actual_read != size) return error.UnexpectedEndOfFile;
4652 bytes[size] = 0;
4653
4654 const comp = mod.comp;
4655 switch (comp.cache_use) {
4656 .whole => |whole| if (whole.cache_manifest) |man| {
4657 const copied_resolved_path = try gpa.dupe(u8, resolved_path);
4658 errdefer gpa.free(copied_resolved_path);
4659 whole.cache_manifest_mutex.lock();
4660 defer whole.cache_manifest_mutex.unlock();
4661 try man.addFilePostContents(copied_resolved_path, bytes[0..size], stat);
4662 },
4663 .incremental => {},
4664 }
4665
4666 const array_ty = try ip.get(gpa, .{ .array_type = .{
4667 .len = size,
4668 .sentinel = .zero_u8,
4669 .child = .u8_type,
4670 } });
4671 const array_val = try ip.get(gpa, .{ .aggregate = .{
4672 .ty = array_ty,
4673 .storage = .{ .bytes = try ip.getOrPutTrailingString(gpa, bytes.len, .maybe_embedded_nulls) },
4674 } });
4675
4676 const ptr_ty = (try mod.ptrType(.{
4677 .child = array_ty,
4678 .flags = .{
4679 .alignment = .none,
4680 .is_const = true,
4681 .address_space = .generic,
4682 },
4683 })).toIntern();
4684 const ptr_val = try ip.get(gpa, .{ .ptr = .{
4685 .ty = ptr_ty,
4686 .base_addr = .{ .anon_decl = .{
4687 .val = array_val,
4688 .orig_ty = ptr_ty,
4689 } },
4690 .byte_offset = 0,
4691 } });
4692
4693 result.* = new_file;
4694 new_file.* = .{
4695 .sub_file_path = try ip.getOrPutString(gpa, sub_file_path, .no_embedded_nulls),
4696 .owner = pkg,
4697 .stat = stat,
4698 .val = ptr_val,
4699 .src_loc = src_loc,
4700 };
4701 return ptr_val;
4702}
4703
4704pub fn scanNamespace(
4705 zcu: *Zcu,
4706 namespace_index: Namespace.Index,
4707 decls: []const Zir.Inst.Index,
4708 parent_decl: *Decl,
4709) Allocator.Error!void {
4710 const tracy = trace(@src());
4711 defer tracy.end();
4712
4713 const gpa = zcu.gpa;
4714 const namespace = zcu.namespacePtr(namespace_index);
4715
4716 // For incremental updates, `scanDecl` wants to look up existing decls by their ZIR index rather
4717 // than their name. We'll build an efficient mapping now, then discard the current `decls`.
4718 var existing_by_inst: std.AutoHashMapUnmanaged(InternPool.TrackedInst.Index, Decl.Index) = .{};
4719 defer existing_by_inst.deinit(gpa);
4720
4721 try existing_by_inst.ensureTotalCapacity(gpa, @intCast(namespace.decls.count()));
4722
4723 for (namespace.decls.keys()) |decl_index| {
4724 const decl = zcu.declPtr(decl_index);
4725 existing_by_inst.putAssumeCapacityNoClobber(decl.zir_decl_index.unwrap().?, decl_index);
4726 }
4727
4728 var seen_decls: std.AutoHashMapUnmanaged(InternPool.NullTerminatedString, void) = .{};
4729 defer seen_decls.deinit(gpa);
4730
4731 try zcu.comp.work_queue.ensureUnusedCapacity(decls.len);
4732
4733 namespace.decls.clearRetainingCapacity();
4734 try namespace.decls.ensureTotalCapacity(gpa, decls.len);
4735
4736 namespace.usingnamespace_set.clearRetainingCapacity();
4737
4738 var scan_decl_iter: ScanDeclIter = .{
4739 .zcu = zcu,
4740 .namespace_index = namespace_index,
4741 .parent_decl = parent_decl,
4742 .seen_decls = &seen_decls,
4743 .existing_by_inst = &existing_by_inst,
4744 .pass = .named,
4745 };
4746 for (decls) |decl_inst| {
4747 try scanDecl(&scan_decl_iter, decl_inst);
4748 }
4749 scan_decl_iter.pass = .unnamed;
4750 for (decls) |decl_inst| {
4751 try scanDecl(&scan_decl_iter, decl_inst);
4752 }
4753
4754 if (seen_decls.count() != namespace.decls.count()) {
4755 // Do a pass over the namespace contents and remove any decls from the last update
4756 // which were removed in this one.
4757 var i: usize = 0;
4758 while (i < namespace.decls.count()) {
4759 const decl_index = namespace.decls.keys()[i];
4760 const decl = zcu.declPtr(decl_index);
4761 if (!seen_decls.contains(decl.name)) {
4762 // We must preserve namespace ordering for @typeInfo.
4763 namespace.decls.orderedRemoveAt(i);
4764 i -= 1;
4765 }
4766 }
4767 }
4768}
4769
4770const ScanDeclIter = struct {
4771 zcu: *Zcu,
4772 namespace_index: Namespace.Index,
4773 parent_decl: *Decl,
4774 seen_decls: *std.AutoHashMapUnmanaged(InternPool.NullTerminatedString, void),
4775 existing_by_inst: *const std.AutoHashMapUnmanaged(InternPool.TrackedInst.Index, Decl.Index),
4776 /// Decl scanning is run in two passes, so that we can detect when a generated
4777 /// name would clash with an explicit name and use a different one.
4778 pass: enum { named, unnamed },
4779 usingnamespace_index: usize = 0,
4780 comptime_index: usize = 0,
4781 unnamed_test_index: usize = 0,
4782
4783 fn avoidNameConflict(iter: *ScanDeclIter, comptime fmt: []const u8, args: anytype) !InternPool.NullTerminatedString {
4784 const zcu = iter.zcu;
4785 const gpa = zcu.gpa;
4786 const ip = &zcu.intern_pool;
4787 var name = try ip.getOrPutStringFmt(gpa, fmt, args, .no_embedded_nulls);
4788 var gop = try iter.seen_decls.getOrPut(gpa, name);
4789 var next_suffix: u32 = 0;
4790 while (gop.found_existing) {
4791 name = try ip.getOrPutStringFmt(gpa, "{}_{d}", .{ name.fmt(ip), next_suffix }, .no_embedded_nulls);
4792 gop = try iter.seen_decls.getOrPut(gpa, name);
4793 next_suffix += 1;
4794 }
4795 return name;
4796 }
4797};
4798
4799fn scanDecl(iter: *ScanDeclIter, decl_inst: Zir.Inst.Index) Allocator.Error!void {
4800 const tracy = trace(@src());
4801 defer tracy.end();
4802
4803 const zcu = iter.zcu;
4804 const namespace_index = iter.namespace_index;
4805 const namespace = zcu.namespacePtr(namespace_index);
4806 const gpa = zcu.gpa;
4807 const zir = namespace.fileScope(zcu).zir;
4808 const ip = &zcu.intern_pool;
4809
4810 const inst_data = zir.instructions.items(.data)[@intFromEnum(decl_inst)].declaration;
4811 const extra = zir.extraData(Zir.Inst.Declaration, inst_data.payload_index);
4812 const declaration = extra.data;
4813
4814 // Every Decl needs a name.
4815 const decl_name: InternPool.NullTerminatedString, const kind: Decl.Kind, const is_named_test: bool = switch (declaration.name) {
4816 .@"comptime" => info: {
4817 if (iter.pass != .unnamed) return;
4818 const i = iter.comptime_index;
4819 iter.comptime_index += 1;
4820 break :info .{
4821 try iter.avoidNameConflict("comptime_{d}", .{i}),
4822 .@"comptime",
4823 false,
4824 };
4825 },
4826 .@"usingnamespace" => info: {
4827 // TODO: this isn't right! These should be considered unnamed. Name conflicts can happen here.
4828 // The problem is, we need to preserve the decl ordering for `@typeInfo`.
4829 // I'm not bothering to fix this now, since some upcoming changes will change this code significantly anyway.
4830 if (iter.pass != .named) return;
4831 const i = iter.usingnamespace_index;
4832 iter.usingnamespace_index += 1;
4833 break :info .{
4834 try iter.avoidNameConflict("usingnamespace_{d}", .{i}),
4835 .@"usingnamespace",
4836 false,
4837 };
4838 },
4839 .unnamed_test => info: {
4840 if (iter.pass != .unnamed) return;
4841 const i = iter.unnamed_test_index;
4842 iter.unnamed_test_index += 1;
4843 break :info .{
4844 try iter.avoidNameConflict("test_{d}", .{i}),
4845 .@"test",
4846 false,
4847 };
4848 },
4849 .decltest => info: {
4850 // We consider these to be unnamed since the decl name can be adjusted to avoid conflicts if necessary.
4851 if (iter.pass != .unnamed) return;
4852 assert(declaration.flags.has_doc_comment);
4853 const name = zir.nullTerminatedString(@enumFromInt(zir.extra[extra.end]));
4854 break :info .{
4855 try iter.avoidNameConflict("decltest.{s}", .{name}),
4856 .@"test",
4857 true,
4858 };
4859 },
4860 _ => if (declaration.name.isNamedTest(zir)) info: {
4861 // We consider these to be unnamed since the decl name can be adjusted to avoid conflicts if necessary.
4862 if (iter.pass != .unnamed) return;
4863 break :info .{
4864 try iter.avoidNameConflict("test.{s}", .{zir.nullTerminatedString(declaration.name.toString(zir).?)}),
4865 .@"test",
4866 true,
4867 };
4868 } else info: {
4869 if (iter.pass != .named) return;
4870 const name = try ip.getOrPutString(
4871 gpa,
4872 zir.nullTerminatedString(declaration.name.toString(zir).?),
4873 .no_embedded_nulls,
4874 );
4875 try iter.seen_decls.putNoClobber(gpa, name, {});
4876 break :info .{
4877 name,
4878 .named,
4879 false,
4880 };
4881 },
4882 };
4883
4884 switch (kind) {
4885 .@"usingnamespace" => try namespace.usingnamespace_set.ensureUnusedCapacity(gpa, 1),
4886 .@"test" => try zcu.test_functions.ensureUnusedCapacity(gpa, 1),
4887 else => {},
4888 }
4889
4890 const parent_file_scope_index = iter.parent_decl.getFileScopeIndex(zcu);
4891 const tracked_inst = try ip.trackZir(gpa, parent_file_scope_index, decl_inst);
4892
4893 // We create a Decl for it regardless of analysis status.
4894
4895 const prev_exported, const decl_index = if (iter.existing_by_inst.get(tracked_inst)) |decl_index| decl_index: {
4896 // We need only update this existing Decl.
4897 const decl = zcu.declPtr(decl_index);
4898 const was_exported = decl.is_exported;
4899 assert(decl.kind == kind); // ZIR tracking should preserve this
4900 decl.name = decl_name;
4901 decl.is_pub = declaration.flags.is_pub;
4902 decl.is_exported = declaration.flags.is_export;
4903 break :decl_index .{ was_exported, decl_index };
4904 } else decl_index: {
4905 // Create and set up a new Decl.
4906 const new_decl_index = try zcu.allocateNewDecl(namespace_index);
4907 const new_decl = zcu.declPtr(new_decl_index);
4908 new_decl.kind = kind;
4909 new_decl.name = decl_name;
4910 new_decl.is_pub = declaration.flags.is_pub;
4911 new_decl.is_exported = declaration.flags.is_export;
4912 new_decl.zir_decl_index = tracked_inst.toOptional();
4913 break :decl_index .{ false, new_decl_index };
4914 };
4915
4916 const decl = zcu.declPtr(decl_index);
4917
4918 namespace.decls.putAssumeCapacityNoClobberContext(decl_index, {}, .{ .zcu = zcu });
4919
4920 const comp = zcu.comp;
4921 const decl_mod = namespace.fileScope(zcu).mod;
4922 const want_analysis = declaration.flags.is_export or switch (kind) {
4923 .anon => unreachable,
4924 .@"comptime" => true,
4925 .@"usingnamespace" => a: {
4926 namespace.usingnamespace_set.putAssumeCapacityNoClobber(decl_index, declaration.flags.is_pub);
4927 break :a true;
4928 },
4929 .named => false,
4930 .@"test" => a: {
4931 if (!comp.config.is_test) break :a false;
4932 if (decl_mod != zcu.main_mod) break :a false;
4933 if (is_named_test and comp.test_filters.len > 0) {
4934 const decl_fqn = try namespace.fullyQualifiedName(zcu, decl_name);
4935 const decl_fqn_slice = decl_fqn.toSlice(ip);
4936 for (comp.test_filters) |test_filter| {
4937 if (mem.indexOf(u8, decl_fqn_slice, test_filter)) |_| break;
4938 } else break :a false;
4939 }
4940 zcu.test_functions.putAssumeCapacity(decl_index, {}); // may clobber on incremental update
4941 break :a true;
4942 },
4943 };
4944
4945 if (want_analysis) {
4946 // We will not queue analysis if the decl has been analyzed on a previous update and
4947 // `is_export` is unchanged. In this case, the incremental update mechanism will handle
4948 // re-analysis for us if necessary.
4949 if (prev_exported != declaration.flags.is_export or decl.analysis == .unreferenced) {
4950 log.debug("scanDecl queue analyze_decl file='{s}' decl_name='{}' decl_index={d}", .{
4951 namespace.fileScope(zcu).sub_file_path, decl_name.fmt(ip), decl_index,
4952 });
4953 comp.work_queue.writeItemAssumeCapacity(.{ .analyze_decl = decl_index });
4954 }
4955 }
4956
4957 if (decl.getOwnedFunction(zcu) != null) {
4958 // TODO this logic is insufficient; namespaces we don't re-scan may still require
4959 // updated line numbers. Look into this!
4960 // TODO Look into detecting when this would be unnecessary by storing enough state
4961 // in `Decl` to notice that the line number did not change.
4962 comp.work_queue.writeItemAssumeCapacity(.{ .update_line_number = decl_index });
4963 }
4964}
4965
49663272/// Cancel the creation of an anon decl and delete any references to it.
49673273/// If other decls depend on this decl, they must be aborted first.
49683274pub fn abortAnonDecl(mod: *Module, decl_index: Decl.Index) void {
......@@ -4970,13 +3276,6 @@ pub fn abortAnonDecl(mod: *Module, decl_index: Decl.Index) void {
49703276 mod.destroyDecl(decl_index);
49713277}
49723278
4973/// Finalize the creation of an anon decl.
4974pub fn finalizeAnonDecl(mod: *Module, decl_index: Decl.Index) Allocator.Error!void {
4975 if (mod.declPtr(decl_index).typeOf(mod).isFnOrHasRuntimeBits(mod)) {
4976 try mod.comp.work_queue.writeItem(.{ .codegen_decl = decl_index });
4977 }
4978}
4979
49803279/// Delete all the Export objects that are caused by this `AnalUnit`. Re-analysis of
49813280/// this `AnalUnit` will cause them to be re-created (or not).
49823281pub fn deleteUnitExports(zcu: *Zcu, anal_unit: AnalUnit) void {
......@@ -5019,7 +3318,7 @@ pub fn deleteUnitExports(zcu: *Zcu, anal_unit: AnalUnit) void {
50193318
50203319/// Delete all references in `reference_table` which are caused by this `AnalUnit`.
50213320/// Re-analysis of the `AnalUnit` will cause appropriate references to be recreated.
5022fn deleteUnitReferences(zcu: *Zcu, anal_unit: AnalUnit) void {
3321pub fn deleteUnitReferences(zcu: *Zcu, anal_unit: AnalUnit) void {
50233322 const gpa = zcu.gpa;
50243323
50253324 const kv = zcu.reference_table.fetchSwapRemove(anal_unit) orelse return;
......@@ -5031,276 +3330,31 @@ fn deleteUnitReferences(zcu: *Zcu, anal_unit: AnalUnit) void {
50313330 // Just leak it for now, and let GC reclaim it later on.
50323331 return;
50333332 };
5034 idx = zcu.all_references.items[idx].next;
5035 }
5036}
5037
5038pub fn addUnitReference(zcu: *Zcu, src_unit: AnalUnit, referenced_unit: AnalUnit, ref_src: LazySrcLoc) Allocator.Error!void {
5039 const gpa = zcu.gpa;
5040
5041 try zcu.reference_table.ensureUnusedCapacity(gpa, 1);
5042
5043 const ref_idx = zcu.free_references.popOrNull() orelse idx: {
5044 _ = try zcu.all_references.addOne(gpa);
5045 break :idx zcu.all_references.items.len - 1;
5046 };
5047
5048 errdefer comptime unreachable;
5049
5050 const gop = zcu.reference_table.getOrPutAssumeCapacity(src_unit);
5051
5052 zcu.all_references.items[ref_idx] = .{
5053 .referenced = referenced_unit,
5054 .next = if (gop.found_existing) gop.value_ptr.* else std.math.maxInt(u32),
5055 .src = ref_src,
5056 };
5057
5058 gop.value_ptr.* = @intCast(ref_idx);
5059}
5060
5061pub fn analyzeFnBody(mod: *Module, func_index: InternPool.Index, arena: Allocator) SemaError!Air {
5062 const tracy = trace(@src());
5063 defer tracy.end();
5064
5065 const gpa = mod.gpa;
5066 const ip = &mod.intern_pool;
5067 const func = mod.funcInfo(func_index);
5068 const decl_index = func.owner_decl;
5069 const decl = mod.declPtr(decl_index);
5070
5071 log.debug("func name '{}'", .{(try decl.fullyQualifiedName(mod)).fmt(ip)});
5072 defer blk: {
5073 log.debug("finish func name '{}'", .{(decl.fullyQualifiedName(mod) catch break :blk).fmt(ip)});
5074 }
5075
5076 const decl_prog_node = mod.sema_prog_node.start((try decl.fullyQualifiedName(mod)).toSlice(ip), 0);
5077 defer decl_prog_node.end();
5078
5079 mod.intern_pool.removeDependenciesForDepender(gpa, AnalUnit.wrap(.{ .func = func_index }));
5080
5081 var comptime_err_ret_trace = std.ArrayList(LazySrcLoc).init(gpa);
5082 defer comptime_err_ret_trace.deinit();
5083
5084 // In the case of a generic function instance, this is the type of the
5085 // instance, which has comptime parameters elided. In other words, it is
5086 // the runtime-known parameters only, not to be confused with the
5087 // generic_owner function type, which potentially has more parameters,
5088 // including comptime parameters.
5089 const fn_ty = decl.typeOf(mod);
5090 const fn_ty_info = mod.typeToFunc(fn_ty).?;
5091
5092 var sema: Sema = .{
5093 .mod = mod,
5094 .gpa = gpa,
5095 .arena = arena,
5096 .code = decl.getFileScope(mod).zir,
5097 .owner_decl = decl,
5098 .owner_decl_index = decl_index,
5099 .func_index = func_index,
5100 .func_is_naked = fn_ty_info.cc == .Naked,
5101 .fn_ret_ty = Type.fromInterned(fn_ty_info.return_type),
5102 .fn_ret_ty_ies = null,
5103 .owner_func_index = func_index,
5104 .branch_quota = @max(func.branchQuota(ip).*, Sema.default_branch_quota),
5105 .comptime_err_ret_trace = &comptime_err_ret_trace,
5106 };
5107 defer sema.deinit();
5108
5109 // Every runtime function has a dependency on the source of the Decl it originates from.
5110 // It also depends on the value of its owner Decl.
5111 try sema.declareDependency(.{ .src_hash = decl.zir_decl_index.unwrap().? });
5112 try sema.declareDependency(.{ .decl_val = decl_index });
5113
5114 if (func.analysis(ip).inferred_error_set) {
5115 const ies = try arena.create(Sema.InferredErrorSet);
5116 ies.* = .{ .func = func_index };
5117 sema.fn_ret_ty_ies = ies;
5118 }
5119
5120 // reset in case calls to errorable functions are removed.
5121 func.analysis(ip).calls_or_awaits_errorable_fn = false;
5122
5123 // First few indexes of extra are reserved and set at the end.
5124 const reserved_count = @typeInfo(Air.ExtraIndex).Enum.fields.len;
5125 try sema.air_extra.ensureTotalCapacity(gpa, reserved_count);
5126 sema.air_extra.items.len += reserved_count;
5127
5128 var inner_block: Sema.Block = .{
5129 .parent = null,
5130 .sema = &sema,
5131 .namespace = decl.src_namespace,
5132 .instructions = .{},
5133 .inlining = null,
5134 .is_comptime = false,
5135 .src_base_inst = inst: {
5136 const owner_info = if (func.generic_owner == .none)
5137 func
5138 else
5139 mod.funcInfo(func.generic_owner);
5140 const orig_decl = mod.declPtr(owner_info.owner_decl);
5141 break :inst orig_decl.zir_decl_index.unwrap().?;
5142 },
5143 .type_name_ctx = decl.name,
5144 };
5145 defer inner_block.instructions.deinit(gpa);
5146
5147 const fn_info = sema.code.getFnInfo(func.zirBodyInst(ip).resolve(ip));
5148
5149 // Here we are performing "runtime semantic analysis" for a function body, which means
5150 // we must map the parameter ZIR instructions to `arg` AIR instructions.
5151 // AIR requires the `arg` parameters to be the first N instructions.
5152 // This could be a generic function instantiation, however, in which case we need to
5153 // map the comptime parameters to constant values and only emit arg AIR instructions
5154 // for the runtime ones.
5155 const runtime_params_len = fn_ty_info.param_types.len;
5156 try inner_block.instructions.ensureTotalCapacityPrecise(gpa, runtime_params_len);
5157 try sema.air_instructions.ensureUnusedCapacity(gpa, fn_info.total_params_len);
5158 try sema.inst_map.ensureSpaceForInstructions(gpa, fn_info.param_body);
5159
5160 // In the case of a generic function instance, pre-populate all the comptime args.
5161 if (func.comptime_args.len != 0) {
5162 for (
5163 fn_info.param_body[0..func.comptime_args.len],
5164 func.comptime_args.get(ip),
5165 ) |inst, comptime_arg| {
5166 if (comptime_arg == .none) continue;
5167 sema.inst_map.putAssumeCapacityNoClobber(inst, Air.internedToRef(comptime_arg));
5168 }
5169 }
5170
5171 const src_params_len = if (func.comptime_args.len != 0)
5172 func.comptime_args.len
5173 else
5174 runtime_params_len;
5175
5176 var runtime_param_index: usize = 0;
5177 for (fn_info.param_body[0..src_params_len], 0..) |inst, src_param_index| {
5178 const gop = sema.inst_map.getOrPutAssumeCapacity(inst);
5179 if (gop.found_existing) continue; // provided above by comptime arg
5180
5181 const param_ty = fn_ty_info.param_types.get(ip)[runtime_param_index];
5182 runtime_param_index += 1;
5183
5184 const opt_opv = sema.typeHasOnePossibleValue(Type.fromInterned(param_ty)) catch |err| switch (err) {
5185 error.GenericPoison => unreachable,
5186 error.ComptimeReturn => unreachable,
5187 error.ComptimeBreak => unreachable,
5188 else => |e| return e,
5189 };
5190 if (opt_opv) |opv| {
5191 gop.value_ptr.* = Air.internedToRef(opv.toIntern());
5192 continue;
5193 }
5194 const arg_index: Air.Inst.Index = @enumFromInt(sema.air_instructions.len);
5195 gop.value_ptr.* = arg_index.toRef();
5196 inner_block.instructions.appendAssumeCapacity(arg_index);
5197 sema.air_instructions.appendAssumeCapacity(.{
5198 .tag = .arg,
5199 .data = .{ .arg = .{
5200 .ty = Air.internedToRef(param_ty),
5201 .src_index = @intCast(src_param_index),
5202 } },
5203 });
5204 }
5205
5206 func.analysis(ip).state = .in_progress;
5207
5208 const last_arg_index = inner_block.instructions.items.len;
5209
5210 // Save the error trace as our first action in the function.
5211 // If this is unnecessary after all, Liveness will clean it up for us.
5212 const error_return_trace_index = try sema.analyzeSaveErrRetIndex(&inner_block);
5213 sema.error_return_trace_index_on_fn_entry = error_return_trace_index;
5214 inner_block.error_return_trace_index = error_return_trace_index;
5215
5216 sema.analyzeFnBody(&inner_block, fn_info.body) catch |err| switch (err) {
5217 // TODO make these unreachable instead of @panic
5218 error.GenericPoison => @panic("zig compiler bug: GenericPoison"),
5219 error.ComptimeReturn => @panic("zig compiler bug: ComptimeReturn"),
5220 else => |e| return e,
5221 };
5222
5223 for (sema.unresolved_inferred_allocs.keys()) |ptr_inst| {
5224 // The lack of a resolve_inferred_alloc means that this instruction
5225 // is unused so it just has to be a no-op.
5226 sema.air_instructions.set(@intFromEnum(ptr_inst), .{
5227 .tag = .alloc,
5228 .data = .{ .ty = Type.single_const_pointer_to_comptime_int },
5229 });
5230 }
5231
5232 // If we don't get an error return trace from a caller, create our own.
5233 if (func.analysis(ip).calls_or_awaits_errorable_fn and
5234 mod.comp.config.any_error_tracing and
5235 !sema.fn_ret_ty.isError(mod))
5236 {
5237 sema.setupErrorReturnTrace(&inner_block, last_arg_index) catch |err| switch (err) {
5238 // TODO make these unreachable instead of @panic
5239 error.GenericPoison => @panic("zig compiler bug: GenericPoison"),
5240 error.ComptimeReturn => @panic("zig compiler bug: ComptimeReturn"),
5241 error.ComptimeBreak => @panic("zig compiler bug: ComptimeBreak"),
5242 else => |e| return e,
5243 };
5244 }
5245
5246 // Copy the block into place and mark that as the main block.
5247 try sema.air_extra.ensureUnusedCapacity(gpa, @typeInfo(Air.Block).Struct.fields.len +
5248 inner_block.instructions.items.len);
5249 const main_block_index = sema.addExtraAssumeCapacity(Air.Block{
5250 .body_len = @intCast(inner_block.instructions.items.len),
5251 });
5252 sema.air_extra.appendSliceAssumeCapacity(@ptrCast(inner_block.instructions.items));
5253 sema.air_extra.items[@intFromEnum(Air.ExtraIndex.main_block)] = main_block_index;
5254
5255 // Resolving inferred error sets is done *before* setting the function
5256 // state to success, so that "unable to resolve inferred error set" errors
5257 // can be emitted here.
5258 if (sema.fn_ret_ty_ies) |ies| {
5259 sema.resolveInferredErrorSetPtr(&inner_block, .{
5260 .base_node_inst = inner_block.src_base_inst,
5261 .offset = LazySrcLoc.Offset.nodeOffset(0),
5262 }, ies) catch |err| switch (err) {
5263 error.GenericPoison => unreachable,
5264 error.ComptimeReturn => unreachable,
5265 error.ComptimeBreak => unreachable,
5266 error.AnalysisFail => {
5267 // In this case our function depends on a type that had a compile error.
5268 // We should not try to lower this function.
5269 decl.analysis = .dependency_failure;
5270 return error.AnalysisFail;
5271 },
5272 else => |e| return e,
5273 };
5274 assert(ies.resolved != .none);
5275 ip.funcIesResolved(func_index).* = ies.resolved;
3333 idx = zcu.all_references.items[idx].next;
52763334 }
3335}
52773336
5278 func.analysis(ip).state = .success;
5279
5280 // Finally we must resolve the return type and parameter types so that backends
5281 // have full access to type information.
5282 // Crucially, this happens *after* we set the function state to success above,
5283 // so that dependencies on the function body will now be satisfied rather than
5284 // result in circular dependency errors.
5285 sema.resolveFnTypes(fn_ty) catch |err| switch (err) {
5286 error.GenericPoison => unreachable,
5287 error.ComptimeReturn => unreachable,
5288 error.ComptimeBreak => unreachable,
5289 error.AnalysisFail => {
5290 // In this case our function depends on a type that had a compile error.
5291 // We should not try to lower this function.
5292 decl.analysis = .dependency_failure;
5293 return error.AnalysisFail;
5294 },
5295 else => |e| return e,
3337pub fn addUnitReference(zcu: *Zcu, src_unit: AnalUnit, referenced_unit: AnalUnit, ref_src: LazySrcLoc) Allocator.Error!void {
3338 const gpa = zcu.gpa;
3339
3340 try zcu.reference_table.ensureUnusedCapacity(gpa, 1);
3341
3342 const ref_idx = zcu.free_references.popOrNull() orelse idx: {
3343 _ = try zcu.all_references.addOne(gpa);
3344 break :idx zcu.all_references.items.len - 1;
52963345 };
52973346
5298 try sema.flushExports();
3347 errdefer comptime unreachable;
52993348
5300 return .{
5301 .instructions = sema.air_instructions.toOwnedSlice(),
5302 .extra = try sema.air_extra.toOwnedSlice(gpa),
3349 const gop = zcu.reference_table.getOrPutAssumeCapacity(src_unit);
3350
3351 zcu.all_references.items[ref_idx] = .{
3352 .referenced = referenced_unit,
3353 .next = if (gop.found_existing) gop.value_ptr.* else std.math.maxInt(u32),
3354 .src = ref_src,
53033355 };
3356
3357 gop.value_ptr.* = @intCast(ref_idx);
53043358}
53053359
53063360pub fn createNamespace(mod: *Module, initialization: Namespace) !Namespace.Index {
......@@ -5420,117 +3474,7 @@ fn lockAndClearFileCompileError(mod: *Module, file: *File) void {
54203474 }
54213475}
54223476
5423/// Called from `Compilation.update`, after everything is done, just before
5424/// reporting compile errors. In this function we emit exported symbol collision
5425/// errors and communicate exported symbols to the linker backend.
5426pub fn processExports(zcu: *Zcu) !void {
5427 const gpa = zcu.gpa;
5428
5429 // First, construct a mapping of every exported value and Decl to the indices of all its different exports.
5430 var decl_exports: std.AutoArrayHashMapUnmanaged(Decl.Index, ArrayListUnmanaged(u32)) = .{};
5431 var value_exports: std.AutoArrayHashMapUnmanaged(InternPool.Index, ArrayListUnmanaged(u32)) = .{};
5432 defer {
5433 for (decl_exports.values()) |*exports| {
5434 exports.deinit(gpa);
5435 }
5436 decl_exports.deinit(gpa);
5437 for (value_exports.values()) |*exports| {
5438 exports.deinit(gpa);
5439 }
5440 value_exports.deinit(gpa);
5441 }
5442
5443 // We note as a heuristic:
5444 // * It is rare to export a value.
5445 // * It is rare for one Decl to be exported multiple times.
5446 // So, this ensureTotalCapacity serves as a reasonable (albeit very approximate) optimization.
5447 try decl_exports.ensureTotalCapacity(gpa, zcu.single_exports.count() + zcu.multi_exports.count());
5448
5449 for (zcu.single_exports.values()) |export_idx| {
5450 const exp = zcu.all_exports.items[export_idx];
5451 const value_ptr, const found_existing = switch (exp.exported) {
5452 .decl_index => |i| gop: {
5453 const gop = try decl_exports.getOrPut(gpa, i);
5454 break :gop .{ gop.value_ptr, gop.found_existing };
5455 },
5456 .value => |i| gop: {
5457 const gop = try value_exports.getOrPut(gpa, i);
5458 break :gop .{ gop.value_ptr, gop.found_existing };
5459 },
5460 };
5461 if (!found_existing) value_ptr.* = .{};
5462 try value_ptr.append(gpa, export_idx);
5463 }
5464
5465 for (zcu.multi_exports.values()) |info| {
5466 for (zcu.all_exports.items[info.index..][0..info.len], info.index..) |exp, export_idx| {
5467 const value_ptr, const found_existing = switch (exp.exported) {
5468 .decl_index => |i| gop: {
5469 const gop = try decl_exports.getOrPut(gpa, i);
5470 break :gop .{ gop.value_ptr, gop.found_existing };
5471 },
5472 .value => |i| gop: {
5473 const gop = try value_exports.getOrPut(gpa, i);
5474 break :gop .{ gop.value_ptr, gop.found_existing };
5475 },
5476 };
5477 if (!found_existing) value_ptr.* = .{};
5478 try value_ptr.append(gpa, @intCast(export_idx));
5479 }
5480 }
5481
5482 // Map symbol names to `Export` for name collision detection.
5483 var symbol_exports: SymbolExports = .{};
5484 defer symbol_exports.deinit(gpa);
5485
5486 for (decl_exports.keys(), decl_exports.values()) |exported_decl, exports_list| {
5487 const exported: Exported = .{ .decl_index = exported_decl };
5488 try processExportsInner(zcu, &symbol_exports, exported, exports_list.items);
5489 }
5490
5491 for (value_exports.keys(), value_exports.values()) |exported_value, exports_list| {
5492 const exported: Exported = .{ .value = exported_value };
5493 try processExportsInner(zcu, &symbol_exports, exported, exports_list.items);
5494 }
5495}
5496
5497const SymbolExports = std.AutoArrayHashMapUnmanaged(InternPool.NullTerminatedString, u32);
5498
5499fn processExportsInner(
5500 zcu: *Zcu,
5501 symbol_exports: *SymbolExports,
5502 exported: Exported,
5503 export_indices: []const u32,
5504) error{OutOfMemory}!void {
5505 const gpa = zcu.gpa;
5506
5507 for (export_indices) |export_idx| {
5508 const new_export = &zcu.all_exports.items[export_idx];
5509 const gop = try symbol_exports.getOrPut(gpa, new_export.opts.name);
5510 if (gop.found_existing) {
5511 new_export.status = .failed_retryable;
5512 try zcu.failed_exports.ensureUnusedCapacity(gpa, 1);
5513 const msg = try ErrorMsg.create(gpa, new_export.src, "exported symbol collision: {}", .{
5514 new_export.opts.name.fmt(&zcu.intern_pool),
5515 });
5516 errdefer msg.destroy(gpa);
5517 const other_export = zcu.all_exports.items[gop.value_ptr.*];
5518 try zcu.errNote(other_export.src, msg, "other symbol here", .{});
5519 zcu.failed_exports.putAssumeCapacityNoClobber(export_idx, msg);
5520 new_export.status = .failed;
5521 } else {
5522 gop.value_ptr.* = export_idx;
5523 }
5524 }
5525 if (zcu.comp.bin_file) |lf| {
5526 try handleUpdateExports(zcu, export_indices, lf.updateExports(zcu, exported, export_indices));
5527 } else if (zcu.llvm_object) |llvm_object| {
5528 if (build_options.only_c) unreachable;
5529 try handleUpdateExports(zcu, export_indices, llvm_object.updateExports(zcu, exported, export_indices));
5530 }
5531}
5532
5533fn handleUpdateExports(
3477pub fn handleUpdateExports(
55343478 zcu: *Zcu,
55353479 export_indices: []const u32,
55363480 result: link.File.UpdateExportsError!void,
......@@ -5551,180 +3495,7 @@ fn handleUpdateExports(
55513495 };
55523496}
55533497
5554pub fn populateTestFunctions(
5555 zcu: *Zcu,
5556 main_progress_node: std.Progress.Node,
5557) !void {
5558 const gpa = zcu.gpa;
5559 const ip = &zcu.intern_pool;
5560 const builtin_mod = zcu.root_mod.getBuiltinDependency();
5561 const builtin_file_index = (zcu.importPkg(builtin_mod) catch unreachable).file_index;
5562 const root_decl_index = zcu.fileRootDecl(builtin_file_index);
5563 const root_decl = zcu.declPtr(root_decl_index.unwrap().?);
5564 const builtin_namespace = zcu.namespacePtr(root_decl.src_namespace);
5565 const test_functions_str = try ip.getOrPutString(gpa, "test_functions", .no_embedded_nulls);
5566 const decl_index = builtin_namespace.decls.getKeyAdapted(
5567 test_functions_str,
5568 DeclAdapter{ .zcu = zcu },
5569 ).?;
5570 {
5571 // We have to call `ensureDeclAnalyzed` here in case `builtin.test_functions`
5572 // was not referenced by start code.
5573 zcu.sema_prog_node = main_progress_node.start("Semantic Analysis", 0);
5574 defer {
5575 zcu.sema_prog_node.end();
5576 zcu.sema_prog_node = undefined;
5577 }
5578 try zcu.ensureDeclAnalyzed(decl_index);
5579 }
5580
5581 const decl = zcu.declPtr(decl_index);
5582 const test_fn_ty = decl.typeOf(zcu).slicePtrFieldType(zcu).childType(zcu);
5583
5584 const array_anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl = array: {
5585 // Add zcu.test_functions to an array decl then make the test_functions
5586 // decl reference it as a slice.
5587 const test_fn_vals = try gpa.alloc(InternPool.Index, zcu.test_functions.count());
5588 defer gpa.free(test_fn_vals);
5589
5590 for (test_fn_vals, zcu.test_functions.keys()) |*test_fn_val, test_decl_index| {
5591 const test_decl = zcu.declPtr(test_decl_index);
5592 const test_decl_name = try test_decl.fullyQualifiedName(zcu);
5593 const test_decl_name_len = test_decl_name.length(ip);
5594 const test_name_anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl = n: {
5595 const test_name_ty = try zcu.arrayType(.{
5596 .len = test_decl_name_len,
5597 .child = .u8_type,
5598 });
5599 const test_name_val = try zcu.intern(.{ .aggregate = .{
5600 .ty = test_name_ty.toIntern(),
5601 .storage = .{ .bytes = test_decl_name.toString() },
5602 } });
5603 break :n .{
5604 .orig_ty = (try zcu.singleConstPtrType(test_name_ty)).toIntern(),
5605 .val = test_name_val,
5606 };
5607 };
5608
5609 const test_fn_fields = .{
5610 // name
5611 try zcu.intern(.{ .slice = .{
5612 .ty = .slice_const_u8_type,
5613 .ptr = try zcu.intern(.{ .ptr = .{
5614 .ty = .manyptr_const_u8_type,
5615 .base_addr = .{ .anon_decl = test_name_anon_decl },
5616 .byte_offset = 0,
5617 } }),
5618 .len = try zcu.intern(.{ .int = .{
5619 .ty = .usize_type,
5620 .storage = .{ .u64 = test_decl_name_len },
5621 } }),
5622 } }),
5623 // func
5624 try zcu.intern(.{ .ptr = .{
5625 .ty = try zcu.intern(.{ .ptr_type = .{
5626 .child = test_decl.typeOf(zcu).toIntern(),
5627 .flags = .{
5628 .is_const = true,
5629 },
5630 } }),
5631 .base_addr = .{ .decl = test_decl_index },
5632 .byte_offset = 0,
5633 } }),
5634 };
5635 test_fn_val.* = try zcu.intern(.{ .aggregate = .{
5636 .ty = test_fn_ty.toIntern(),
5637 .storage = .{ .elems = &test_fn_fields },
5638 } });
5639 }
5640
5641 const array_ty = try zcu.arrayType(.{
5642 .len = test_fn_vals.len,
5643 .child = test_fn_ty.toIntern(),
5644 .sentinel = .none,
5645 });
5646 const array_val = try zcu.intern(.{ .aggregate = .{
5647 .ty = array_ty.toIntern(),
5648 .storage = .{ .elems = test_fn_vals },
5649 } });
5650 break :array .{
5651 .orig_ty = (try zcu.singleConstPtrType(array_ty)).toIntern(),
5652 .val = array_val,
5653 };
5654 };
5655
5656 {
5657 const new_ty = try zcu.ptrType(.{
5658 .child = test_fn_ty.toIntern(),
5659 .flags = .{
5660 .is_const = true,
5661 .size = .Slice,
5662 },
5663 });
5664 const new_val = decl.val;
5665 const new_init = try zcu.intern(.{ .slice = .{
5666 .ty = new_ty.toIntern(),
5667 .ptr = try zcu.intern(.{ .ptr = .{
5668 .ty = new_ty.slicePtrFieldType(zcu).toIntern(),
5669 .base_addr = .{ .anon_decl = array_anon_decl },
5670 .byte_offset = 0,
5671 } }),
5672 .len = (try zcu.intValue(Type.usize, zcu.test_functions.count())).toIntern(),
5673 } });
5674 ip.mutateVarInit(decl.val.toIntern(), new_init);
5675
5676 // Since we are replacing the Decl's value we must perform cleanup on the
5677 // previous value.
5678 decl.val = new_val;
5679 decl.has_tv = true;
5680 }
5681 {
5682 zcu.codegen_prog_node = main_progress_node.start("Code Generation", 0);
5683 defer {
5684 zcu.codegen_prog_node.end();
5685 zcu.codegen_prog_node = undefined;
5686 }
5687
5688 try zcu.linkerUpdateDecl(decl_index);
5689 }
5690}
5691
5692pub fn linkerUpdateDecl(zcu: *Zcu, decl_index: Decl.Index) !void {
5693 const comp = zcu.comp;
5694
5695 const decl = zcu.declPtr(decl_index);
5696
5697 const codegen_prog_node = zcu.codegen_prog_node.start((try decl.fullyQualifiedName(zcu)).toSlice(&zcu.intern_pool), 0);
5698 defer codegen_prog_node.end();
5699
5700 if (comp.bin_file) |lf| {
5701 lf.updateDecl(zcu, decl_index) catch |err| switch (err) {
5702 error.OutOfMemory => return error.OutOfMemory,
5703 error.AnalysisFail => {
5704 decl.analysis = .codegen_failure;
5705 },
5706 else => {
5707 const gpa = zcu.gpa;
5708 try zcu.failed_analysis.ensureUnusedCapacity(gpa, 1);
5709 zcu.failed_analysis.putAssumeCapacityNoClobber(AnalUnit.wrap(.{ .decl = decl_index }), try ErrorMsg.create(
5710 gpa,
5711 decl.navSrcLoc(zcu),
5712 "unable to codegen: {s}",
5713 .{@errorName(err)},
5714 ));
5715 decl.analysis = .codegen_failure;
5716 try zcu.retryable_failures.append(zcu.gpa, AnalUnit.wrap(.{ .decl = decl_index }));
5717 },
5718 };
5719 } else if (zcu.llvm_object) |llvm_object| {
5720 if (build_options.only_c) unreachable;
5721 llvm_object.updateDecl(zcu, decl_index) catch |err| switch (err) {
5722 error.OutOfMemory => return error.OutOfMemory,
5723 };
5724 }
5725}
5726
5727fn reportRetryableFileError(
3498pub fn reportRetryableFileError(
57283499 zcu: *Zcu,
57293500 file_index: File.Index,
57303501 comptime format: []const u8,
......@@ -5786,351 +3557,13 @@ pub const Feature = enum {
57863557 /// to generate better machine code in the backends. All backends should migrate to
57873558 /// enabling this feature.
57883559 safety_checked_instructions,
3560 /// If the backend supports running from another thread.
3561 separate_thread,
57893562};
57903563
5791pub fn backendSupportsFeature(zcu: Module, feature: Feature) bool {
5792 const cpu_arch = zcu.root_mod.resolved_target.result.cpu.arch;
5793 const ofmt = zcu.root_mod.resolved_target.result.ofmt;
5794 const use_llvm = zcu.comp.config.use_llvm;
5795 return target_util.backendSupportsFeature(cpu_arch, ofmt, use_llvm, feature);
5796}
5797
5798/// Shortcut for calling `intern_pool.get`.
5799pub fn intern(mod: *Module, key: InternPool.Key) Allocator.Error!InternPool.Index {
5800 return mod.intern_pool.get(mod.gpa, key);
5801}
5802
5803/// Shortcut for calling `intern_pool.getCoerced`.
5804pub fn getCoerced(mod: *Module, val: Value, new_ty: Type) Allocator.Error!Value {
5805 return Value.fromInterned((try mod.intern_pool.getCoerced(mod.gpa, val.toIntern(), new_ty.toIntern())));
5806}
5807
5808pub fn intType(mod: *Module, signedness: std.builtin.Signedness, bits: u16) Allocator.Error!Type {
5809 return Type.fromInterned((try intern(mod, .{ .int_type = .{
5810 .signedness = signedness,
5811 .bits = bits,
5812 } })));
5813}
5814
5815pub fn errorIntType(mod: *Module) std.mem.Allocator.Error!Type {
5816 return mod.intType(.unsigned, mod.errorSetBits());
5817}
5818
5819pub fn arrayType(mod: *Module, info: InternPool.Key.ArrayType) Allocator.Error!Type {
5820 const i = try intern(mod, .{ .array_type = info });
5821 return Type.fromInterned(i);
5822}
5823
5824pub fn vectorType(mod: *Module, info: InternPool.Key.VectorType) Allocator.Error!Type {
5825 const i = try intern(mod, .{ .vector_type = info });
5826 return Type.fromInterned(i);
5827}
5828
5829pub fn optionalType(mod: *Module, child_type: InternPool.Index) Allocator.Error!Type {
5830 const i = try intern(mod, .{ .opt_type = child_type });
5831 return Type.fromInterned(i);
5832}
5833
5834pub fn ptrType(mod: *Module, info: InternPool.Key.PtrType) Allocator.Error!Type {
5835 var canon_info = info;
5836
5837 if (info.flags.size == .C) canon_info.flags.is_allowzero = true;
5838
5839 // Canonicalize non-zero alignment. If it matches the ABI alignment of the pointee
5840 // type, we change it to 0 here. If this causes an assertion trip because the
5841 // pointee type needs to be resolved more, that needs to be done before calling
5842 // this ptr() function.
5843 if (info.flags.alignment != .none and
5844 info.flags.alignment == Type.fromInterned(info.child).abiAlignment(mod))
5845 {
5846 canon_info.flags.alignment = .none;
5847 }
5848
5849 switch (info.flags.vector_index) {
5850 // Canonicalize host_size. If it matches the bit size of the pointee type,
5851 // we change it to 0 here. If this causes an assertion trip, the pointee type
5852 // needs to be resolved before calling this ptr() function.
5853 .none => if (info.packed_offset.host_size != 0) {
5854 const elem_bit_size = Type.fromInterned(info.child).bitSize(mod);
5855 assert(info.packed_offset.bit_offset + elem_bit_size <= info.packed_offset.host_size * 8);
5856 if (info.packed_offset.host_size * 8 == elem_bit_size) {
5857 canon_info.packed_offset.host_size = 0;
5858 }
5859 },
5860 .runtime => {},
5861 _ => assert(@intFromEnum(info.flags.vector_index) < info.packed_offset.host_size),
5862 }
5863
5864 return Type.fromInterned((try intern(mod, .{ .ptr_type = canon_info })));
5865}
5866
5867/// Like `ptrType`, but if `info` specifies an `alignment`, first ensures the pointer
5868/// child type's alignment is resolved so that an invalid alignment is not used.
5869/// In general, prefer this function during semantic analysis.
5870pub fn ptrTypeSema(zcu: *Zcu, info: InternPool.Key.PtrType) SemaError!Type {
5871 if (info.flags.alignment != .none) {
5872 _ = try Type.fromInterned(info.child).abiAlignmentAdvanced(zcu, .sema);
5873 }
5874 return zcu.ptrType(info);
5875}
5876
5877pub fn singleMutPtrType(mod: *Module, child_type: Type) Allocator.Error!Type {
5878 return ptrType(mod, .{ .child = child_type.toIntern() });
5879}
5880
5881pub fn singleConstPtrType(mod: *Module, child_type: Type) Allocator.Error!Type {
5882 return ptrType(mod, .{
5883 .child = child_type.toIntern(),
5884 .flags = .{
5885 .is_const = true,
5886 },
5887 });
5888}
5889
5890pub fn manyConstPtrType(mod: *Module, child_type: Type) Allocator.Error!Type {
5891 return ptrType(mod, .{
5892 .child = child_type.toIntern(),
5893 .flags = .{
5894 .size = .Many,
5895 .is_const = true,
5896 },
5897 });
5898}
5899
5900pub fn adjustPtrTypeChild(mod: *Module, ptr_ty: Type, new_child: Type) Allocator.Error!Type {
5901 var info = ptr_ty.ptrInfo(mod);
5902 info.child = new_child.toIntern();
5903 return mod.ptrType(info);
5904}
5905
5906pub fn funcType(mod: *Module, key: InternPool.GetFuncTypeKey) Allocator.Error!Type {
5907 return Type.fromInterned((try mod.intern_pool.getFuncType(mod.gpa, key)));
5908}
5909
5910/// Use this for `anyframe->T` only.
5911/// For `anyframe`, use the `InternPool.Index.anyframe` tag directly.
5912pub fn anyframeType(mod: *Module, payload_ty: Type) Allocator.Error!Type {
5913 return Type.fromInterned((try intern(mod, .{ .anyframe_type = payload_ty.toIntern() })));
5914}
5915
5916pub fn errorUnionType(mod: *Module, error_set_ty: Type, payload_ty: Type) Allocator.Error!Type {
5917 return Type.fromInterned((try intern(mod, .{ .error_union_type = .{
5918 .error_set_type = error_set_ty.toIntern(),
5919 .payload_type = payload_ty.toIntern(),
5920 } })));
5921}
5922
5923pub fn singleErrorSetType(mod: *Module, name: InternPool.NullTerminatedString) Allocator.Error!Type {
5924 const names: *const [1]InternPool.NullTerminatedString = &name;
5925 const new_ty = try mod.intern_pool.getErrorSetType(mod.gpa, names);
5926 return Type.fromInterned(new_ty);
5927}
5928
5929/// Sorts `names` in place.
5930pub fn errorSetFromUnsortedNames(
5931 mod: *Module,
5932 names: []InternPool.NullTerminatedString,
5933) Allocator.Error!Type {
5934 std.mem.sort(
5935 InternPool.NullTerminatedString,
5936 names,
5937 {},
5938 InternPool.NullTerminatedString.indexLessThan,
5939 );
5940 const new_ty = try mod.intern_pool.getErrorSetType(mod.gpa, names);
5941 return Type.fromInterned(new_ty);
5942}
5943
5944/// Supports only pointers, not pointer-like optionals.
5945pub fn ptrIntValue(mod: *Module, ty: Type, x: u64) Allocator.Error!Value {
5946 assert(ty.zigTypeTag(mod) == .Pointer and !ty.isSlice(mod));
5947 assert(x != 0 or ty.isAllowzeroPtr(mod));
5948 const i = try intern(mod, .{ .ptr = .{
5949 .ty = ty.toIntern(),
5950 .base_addr = .int,
5951 .byte_offset = x,
5952 } });
5953 return Value.fromInterned(i);
5954}
5955
5956/// Creates an enum tag value based on the integer tag value.
5957pub fn enumValue(mod: *Module, ty: Type, tag_int: InternPool.Index) Allocator.Error!Value {
5958 if (std.debug.runtime_safety) {
5959 const tag = ty.zigTypeTag(mod);
5960 assert(tag == .Enum);
5961 }
5962 const i = try intern(mod, .{ .enum_tag = .{
5963 .ty = ty.toIntern(),
5964 .int = tag_int,
5965 } });
5966 return Value.fromInterned(i);
5967}
5968
5969/// Creates an enum tag value based on the field index according to source code
5970/// declaration order.
5971pub fn enumValueFieldIndex(mod: *Module, ty: Type, field_index: u32) Allocator.Error!Value {
5972 const ip = &mod.intern_pool;
5973 const gpa = mod.gpa;
5974 const enum_type = ip.loadEnumType(ty.toIntern());
5975
5976 if (enum_type.values.len == 0) {
5977 // Auto-numbered fields.
5978 return Value.fromInterned((try ip.get(gpa, .{ .enum_tag = .{
5979 .ty = ty.toIntern(),
5980 .int = try ip.get(gpa, .{ .int = .{
5981 .ty = enum_type.tag_ty,
5982 .storage = .{ .u64 = field_index },
5983 } }),
5984 } })));
5985 }
5986
5987 return Value.fromInterned((try ip.get(gpa, .{ .enum_tag = .{
5988 .ty = ty.toIntern(),
5989 .int = enum_type.values.get(ip)[field_index],
5990 } })));
5991}
5992
5993pub fn undefValue(mod: *Module, ty: Type) Allocator.Error!Value {
5994 return Value.fromInterned((try mod.intern(.{ .undef = ty.toIntern() })));
5995}
5996
5997pub fn undefRef(mod: *Module, ty: Type) Allocator.Error!Air.Inst.Ref {
5998 return Air.internedToRef((try mod.undefValue(ty)).toIntern());
5999}
6000
6001pub fn intValue(mod: *Module, ty: Type, x: anytype) Allocator.Error!Value {
6002 if (std.math.cast(u64, x)) |casted| return intValue_u64(mod, ty, casted);
6003 if (std.math.cast(i64, x)) |casted| return intValue_i64(mod, ty, casted);
6004 var limbs_buffer: [4]usize = undefined;
6005 var big_int = BigIntMutable.init(&limbs_buffer, x);
6006 return intValue_big(mod, ty, big_int.toConst());
6007}
6008
6009pub fn intRef(mod: *Module, ty: Type, x: anytype) Allocator.Error!Air.Inst.Ref {
6010 return Air.internedToRef((try mod.intValue(ty, x)).toIntern());
6011}
6012
6013pub fn intValue_big(mod: *Module, ty: Type, x: BigIntConst) Allocator.Error!Value {
6014 const i = try intern(mod, .{ .int = .{
6015 .ty = ty.toIntern(),
6016 .storage = .{ .big_int = x },
6017 } });
6018 return Value.fromInterned(i);
6019}
6020
6021pub fn intValue_u64(mod: *Module, ty: Type, x: u64) Allocator.Error!Value {
6022 const i = try intern(mod, .{ .int = .{
6023 .ty = ty.toIntern(),
6024 .storage = .{ .u64 = x },
6025 } });
6026 return Value.fromInterned(i);
6027}
6028
6029pub fn intValue_i64(mod: *Module, ty: Type, x: i64) Allocator.Error!Value {
6030 const i = try intern(mod, .{ .int = .{
6031 .ty = ty.toIntern(),
6032 .storage = .{ .i64 = x },
6033 } });
6034 return Value.fromInterned(i);
6035}
6036
6037pub fn unionValue(mod: *Module, union_ty: Type, tag: Value, val: Value) Allocator.Error!Value {
6038 const i = try intern(mod, .{ .un = .{
6039 .ty = union_ty.toIntern(),
6040 .tag = tag.toIntern(),
6041 .val = val.toIntern(),
6042 } });
6043 return Value.fromInterned(i);
6044}
6045
6046/// This function casts the float representation down to the representation of the type, potentially
6047/// losing data if the representation wasn't correct.
6048pub fn floatValue(mod: *Module, ty: Type, x: anytype) Allocator.Error!Value {
6049 const storage: InternPool.Key.Float.Storage = switch (ty.floatBits(mod.getTarget())) {
6050 16 => .{ .f16 = @as(f16, @floatCast(x)) },
6051 32 => .{ .f32 = @as(f32, @floatCast(x)) },
6052 64 => .{ .f64 = @as(f64, @floatCast(x)) },
6053 80 => .{ .f80 = @as(f80, @floatCast(x)) },
6054 128 => .{ .f128 = @as(f128, @floatCast(x)) },
6055 else => unreachable,
6056 };
6057 const i = try intern(mod, .{ .float = .{
6058 .ty = ty.toIntern(),
6059 .storage = storage,
6060 } });
6061 return Value.fromInterned(i);
6062}
6063
6064pub fn nullValue(mod: *Module, opt_ty: Type) Allocator.Error!Value {
6065 const ip = &mod.intern_pool;
6066 assert(ip.isOptionalType(opt_ty.toIntern()));
6067 const result = try ip.get(mod.gpa, .{ .opt = .{
6068 .ty = opt_ty.toIntern(),
6069 .val = .none,
6070 } });
6071 return Value.fromInterned(result);
6072}
6073
6074pub fn smallestUnsignedInt(mod: *Module, max: u64) Allocator.Error!Type {
6075 return intType(mod, .unsigned, Type.smallestUnsignedBits(max));
6076}
6077
6078/// Returns the smallest possible integer type containing both `min` and
6079/// `max`. Asserts that neither value is undef.
6080/// TODO: if #3806 is implemented, this becomes trivial
6081pub fn intFittingRange(mod: *Module, min: Value, max: Value) !Type {
6082 assert(!min.isUndef(mod));
6083 assert(!max.isUndef(mod));
6084
6085 if (std.debug.runtime_safety) {
6086 assert(Value.order(min, max, mod).compare(.lte));
6087 }
6088
6089 const sign = min.orderAgainstZero(mod) == .lt;
6090
6091 const min_val_bits = intBitsForValue(mod, min, sign);
6092 const max_val_bits = intBitsForValue(mod, max, sign);
6093
6094 return mod.intType(
6095 if (sign) .signed else .unsigned,
6096 @max(min_val_bits, max_val_bits),
6097 );
6098}
6099
6100/// Given a value representing an integer, returns the number of bits necessary to represent
6101/// this value in an integer. If `sign` is true, returns the number of bits necessary in a
6102/// twos-complement integer; otherwise in an unsigned integer.
6103/// Asserts that `val` is not undef. If `val` is negative, asserts that `sign` is true.
6104pub fn intBitsForValue(mod: *Module, val: Value, sign: bool) u16 {
6105 assert(!val.isUndef(mod));
6106
6107 const key = mod.intern_pool.indexToKey(val.toIntern());
6108 switch (key.int.storage) {
6109 .i64 => |x| {
6110 if (std.math.cast(u64, x)) |casted| return Type.smallestUnsignedBits(casted) + @intFromBool(sign);
6111 assert(sign);
6112 // Protect against overflow in the following negation.
6113 if (x == std.math.minInt(i64)) return 64;
6114 return Type.smallestUnsignedBits(@as(u64, @intCast(-(x + 1)))) + 1;
6115 },
6116 .u64 => |x| {
6117 return Type.smallestUnsignedBits(x) + @intFromBool(sign);
6118 },
6119 .big_int => |big| {
6120 if (big.positive) return @as(u16, @intCast(big.bitCountAbs() + @intFromBool(sign)));
6121
6122 // Zero is still a possibility, in which case unsigned is fine
6123 if (big.eqlZero()) return 0;
6124
6125 return @as(u16, @intCast(big.bitCountTwosComp()));
6126 },
6127 .lazy_align => |lazy_ty| {
6128 return Type.smallestUnsignedBits(Type.fromInterned(lazy_ty).abiAlignment(mod).toByteUnits() orelse 0) + @intFromBool(sign);
6129 },
6130 .lazy_size => |lazy_ty| {
6131 return Type.smallestUnsignedBits(Type.fromInterned(lazy_ty).abiSize(mod)) + @intFromBool(sign);
6132 },
6133 }
3564pub fn backendSupportsFeature(zcu: Module, comptime feature: Feature) bool {
3565 const backend = target_util.zigBackend(zcu.root_mod.resolved_target.result, zcu.comp.config.use_llvm);
3566 return target_util.backendSupportsFeature(backend, feature);
61343567}
61353568
61363569pub const AtomicPtrAlignmentError = error{
......@@ -6371,101 +3804,6 @@ pub const UnionLayout = struct {
63713804 padding: u32,
63723805};
63733806
6374pub fn getUnionLayout(mod: *Module, loaded_union: InternPool.LoadedUnionType) UnionLayout {
6375 const ip = &mod.intern_pool;
6376 assert(loaded_union.haveLayout(ip));
6377 var most_aligned_field: u32 = undefined;
6378 var most_aligned_field_size: u64 = undefined;
6379 var biggest_field: u32 = undefined;
6380 var payload_size: u64 = 0;
6381 var payload_align: Alignment = .@"1";
6382 for (loaded_union.field_types.get(ip), 0..) |field_ty, field_index| {
6383 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(mod)) continue;
6384
6385 const explicit_align = loaded_union.fieldAlign(ip, field_index);
6386 const field_align = if (explicit_align != .none)
6387 explicit_align
6388 else
6389 Type.fromInterned(field_ty).abiAlignment(mod);
6390 const field_size = Type.fromInterned(field_ty).abiSize(mod);
6391 if (field_size > payload_size) {
6392 payload_size = field_size;
6393 biggest_field = @intCast(field_index);
6394 }
6395 if (field_align.compare(.gte, payload_align)) {
6396 payload_align = field_align;
6397 most_aligned_field = @intCast(field_index);
6398 most_aligned_field_size = field_size;
6399 }
6400 }
6401 const have_tag = loaded_union.flagsPtr(ip).runtime_tag.hasTag();
6402 if (!have_tag or !Type.fromInterned(loaded_union.enum_tag_ty).hasRuntimeBits(mod)) {
6403 return .{
6404 .abi_size = payload_align.forward(payload_size),
6405 .abi_align = payload_align,
6406 .most_aligned_field = most_aligned_field,
6407 .most_aligned_field_size = most_aligned_field_size,
6408 .biggest_field = biggest_field,
6409 .payload_size = payload_size,
6410 .payload_align = payload_align,
6411 .tag_align = .none,
6412 .tag_size = 0,
6413 .padding = 0,
6414 };
6415 }
6416
6417 const tag_size = Type.fromInterned(loaded_union.enum_tag_ty).abiSize(mod);
6418 const tag_align = Type.fromInterned(loaded_union.enum_tag_ty).abiAlignment(mod).max(.@"1");
6419 return .{
6420 .abi_size = loaded_union.size(ip).*,
6421 .abi_align = tag_align.max(payload_align),
6422 .most_aligned_field = most_aligned_field,
6423 .most_aligned_field_size = most_aligned_field_size,
6424 .biggest_field = biggest_field,
6425 .payload_size = payload_size,
6426 .payload_align = payload_align,
6427 .tag_align = tag_align,
6428 .tag_size = tag_size,
6429 .padding = loaded_union.padding(ip).*,
6430 };
6431}
6432
6433pub fn unionAbiSize(mod: *Module, loaded_union: InternPool.LoadedUnionType) u64 {
6434 return mod.getUnionLayout(loaded_union).abi_size;
6435}
6436
6437/// Returns 0 if the union is represented with 0 bits at runtime.
6438pub fn unionAbiAlignment(mod: *Module, loaded_union: InternPool.LoadedUnionType) Alignment {
6439 const ip = &mod.intern_pool;
6440 const have_tag = loaded_union.flagsPtr(ip).runtime_tag.hasTag();
6441 var max_align: Alignment = .none;
6442 if (have_tag) max_align = Type.fromInterned(loaded_union.enum_tag_ty).abiAlignment(mod);
6443 for (loaded_union.field_types.get(ip), 0..) |field_ty, field_index| {
6444 if (!Type.fromInterned(field_ty).hasRuntimeBits(mod)) continue;
6445
6446 const field_align = mod.unionFieldNormalAlignment(loaded_union, @intCast(field_index));
6447 max_align = max_align.max(field_align);
6448 }
6449 return max_align;
6450}
6451
6452/// Returns the field alignment of a non-packed union. Asserts the layout is not packed.
6453pub fn unionFieldNormalAlignment(zcu: *Zcu, loaded_union: InternPool.LoadedUnionType, field_index: u32) Alignment {
6454 return zcu.unionFieldNormalAlignmentAdvanced(loaded_union, field_index, .normal) catch unreachable;
6455}
6456
6457/// Returns the field alignment of a non-packed union. Asserts the layout is not packed.
6458/// If `strat` is `.sema`, may perform type resolution.
6459pub fn unionFieldNormalAlignmentAdvanced(zcu: *Zcu, loaded_union: InternPool.LoadedUnionType, field_index: u32, strat: Type.ResolveStrat) SemaError!Alignment {
6460 const ip = &zcu.intern_pool;
6461 assert(loaded_union.flagsPtr(ip).layout != .@"packed");
6462 const field_align = loaded_union.fieldAlign(ip, field_index);
6463 if (field_align != .none) return field_align;
6464 const field_ty = Type.fromInterned(loaded_union.field_types.get(ip)[field_index]);
6465 if (field_ty.isNoReturn(zcu)) return .none;
6466 return (try field_ty.abiAlignmentAdvanced(zcu, strat.toLazy())).scalar;
6467}
6468
64693807/// Returns the index of the active field, given the current tag value
64703808pub fn unionTagFieldIndex(mod: *Module, loaded_union: InternPool.LoadedUnionType, enum_tag: Value) ?u32 {
64713809 const ip = &mod.intern_pool;
......@@ -6474,63 +3812,6 @@ pub fn unionTagFieldIndex(mod: *Module, loaded_union: InternPool.LoadedUnionType
64743812 return loaded_union.loadTagType(ip).tagValueIndex(ip, enum_tag.toIntern());
64753813}
64763814
6477/// Returns the field alignment of a non-packed struct. Asserts the layout is not packed.
6478pub fn structFieldAlignment(
6479 zcu: *Zcu,
6480 explicit_alignment: InternPool.Alignment,
6481 field_ty: Type,
6482 layout: std.builtin.Type.ContainerLayout,
6483) Alignment {
6484 return zcu.structFieldAlignmentAdvanced(explicit_alignment, field_ty, layout, .normal) catch unreachable;
6485}
6486
6487/// Returns the field alignment of a non-packed struct. Asserts the layout is not packed.
6488/// If `strat` is `.sema`, may perform type resolution.
6489pub fn structFieldAlignmentAdvanced(
6490 zcu: *Zcu,
6491 explicit_alignment: InternPool.Alignment,
6492 field_ty: Type,
6493 layout: std.builtin.Type.ContainerLayout,
6494 strat: Type.ResolveStrat,
6495) SemaError!Alignment {
6496 assert(layout != .@"packed");
6497 if (explicit_alignment != .none) return explicit_alignment;
6498 const ty_abi_align = (try field_ty.abiAlignmentAdvanced(zcu, strat.toLazy())).scalar;
6499 switch (layout) {
6500 .@"packed" => unreachable,
6501 .auto => if (zcu.getTarget().ofmt != .c) return ty_abi_align,
6502 .@"extern" => {},
6503 }
6504 // extern
6505 if (field_ty.isAbiInt(zcu) and field_ty.intInfo(zcu).bits >= 128) {
6506 return ty_abi_align.maxStrict(.@"16");
6507 }
6508 return ty_abi_align;
6509}
6510
6511/// https://github.com/ziglang/zig/issues/17178 explored storing these bit offsets
6512/// into the packed struct InternPool data rather than computing this on the
6513/// fly, however it was found to perform worse when measured on real world
6514/// projects.
6515pub fn structPackedFieldBitOffset(
6516 mod: *Module,
6517 struct_type: InternPool.LoadedStructType,
6518 field_index: u32,
6519) u16 {
6520 const ip = &mod.intern_pool;
6521 assert(struct_type.layout == .@"packed");
6522 assert(struct_type.haveLayout(ip));
6523 var bit_sum: u64 = 0;
6524 for (0..struct_type.field_types.len) |i| {
6525 if (i == field_index) {
6526 return @intCast(bit_sum);
6527 }
6528 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
6529 bit_sum += field_ty.bitSize(mod);
6530 }
6531 unreachable; // index out of bounds
6532}
6533
65343815pub const ResolvedReference = struct {
65353816 referencer: AnalUnit,
65363817 src: LazySrcLoc,
......@@ -6564,33 +3845,6 @@ pub fn resolveReferences(zcu: *Zcu) !std.AutoHashMapUnmanaged(AnalUnit, Resolved
65643845 return result;
65653846}
65663847
6567pub fn getBuiltin(zcu: *Zcu, name: []const u8) Allocator.Error!Air.Inst.Ref {
6568 const decl_index = try zcu.getBuiltinDecl(name);
6569 zcu.ensureDeclAnalyzed(decl_index) catch @panic("std.builtin is corrupt");
6570 return Air.internedToRef(zcu.declPtr(decl_index).val.toIntern());
6571}
6572
6573pub fn getBuiltinDecl(zcu: *Zcu, name: []const u8) Allocator.Error!InternPool.DeclIndex {
6574 const gpa = zcu.gpa;
6575 const ip = &zcu.intern_pool;
6576 const std_file_imported = zcu.importPkg(zcu.std_mod) catch @panic("failed to import lib/std.zig");
6577 const std_file_root_decl = zcu.fileRootDecl(std_file_imported.file_index).unwrap().?;
6578 const std_namespace = zcu.declPtr(std_file_root_decl).getOwnedInnerNamespace(zcu).?;
6579 const builtin_str = try ip.getOrPutString(gpa, "builtin", .no_embedded_nulls);
6580 const builtin_decl = std_namespace.decls.getKeyAdapted(builtin_str, Zcu.DeclAdapter{ .zcu = zcu }) orelse @panic("lib/std.zig is corrupt and missing 'builtin'");
6581 zcu.ensureDeclAnalyzed(builtin_decl) catch @panic("std.builtin is corrupt");
6582 const builtin_namespace = zcu.declPtr(builtin_decl).getInnerNamespace(zcu) orelse @panic("std.builtin is corrupt");
6583 const name_str = try ip.getOrPutString(gpa, name, .no_embedded_nulls);
6584 return builtin_namespace.decls.getKeyAdapted(name_str, Zcu.DeclAdapter{ .zcu = zcu }) orelse @panic("lib/std/builtin.zig is corrupt");
6585}
6586
6587pub fn getBuiltinType(zcu: *Zcu, name: []const u8) Allocator.Error!Type {
6588 const ty_inst = try zcu.getBuiltin(name);
6589 const ty = Type.fromInterned(ty_inst.toInterned() orelse @panic("std.builtin is corrupt"));
6590 ty.resolveFully(zcu) catch @panic("std.builtin is corrupt");
6591 return ty;
6592}
6593
65943848pub fn fileByIndex(zcu: *const Zcu, i: File.Index) *File {
65953849 return zcu.import_table.values()[@intFromEnum(i)];
65963850}
src/Zcu/PerThread.zig created+2825
......@@ -0,0 +1,2825 @@
1zcu: *Zcu,
2
3/// Dense, per-thread unique index.
4tid: Id,
5
6pub const Id = if (InternPool.single_threaded) enum { main } else enum(u8) { main, _ };
7
8pub fn astGenFile(
9 pt: Zcu.PerThread,
10 file: *Zcu.File,
11 /// This parameter is provided separately from `file` because it is not
12 /// safe to access `import_table` without a lock, and this index is needed
13 /// in the call to `updateZirRefs`.
14 file_index: Zcu.File.Index,
15 path_digest: Cache.BinDigest,
16 opt_root_decl: Zcu.Decl.OptionalIndex,
17) !void {
18 assert(!file.mod.isBuiltin());
19
20 const tracy = trace(@src());
21 defer tracy.end();
22
23 const zcu = pt.zcu;
24 const comp = zcu.comp;
25 const gpa = zcu.gpa;
26
27 // In any case we need to examine the stat of the file to determine the course of action.
28 var source_file = try file.mod.root.openFile(file.sub_file_path, .{});
29 defer source_file.close();
30
31 const stat = try source_file.stat();
32
33 const want_local_cache = file.mod == zcu.main_mod;
34 const hex_digest = Cache.binToHex(path_digest);
35 const cache_directory = if (want_local_cache) zcu.local_zir_cache else zcu.global_zir_cache;
36 const zir_dir = cache_directory.handle;
37
38 // Determine whether we need to reload the file from disk and redo parsing and AstGen.
39 var lock: std.fs.File.Lock = switch (file.status) {
40 .never_loaded, .retryable_failure => lock: {
41 // First, load the cached ZIR code, if any.
42 log.debug("AstGen checking cache: {s} (local={}, digest={s})", .{
43 file.sub_file_path, want_local_cache, &hex_digest,
44 });
45
46 break :lock .shared;
47 },
48 .parse_failure, .astgen_failure, .success_zir => lock: {
49 const unchanged_metadata =
50 stat.size == file.stat.size and
51 stat.mtime == file.stat.mtime and
52 stat.inode == file.stat.inode;
53
54 if (unchanged_metadata) {
55 log.debug("unmodified metadata of file: {s}", .{file.sub_file_path});
56 return;
57 }
58
59 log.debug("metadata changed: {s}", .{file.sub_file_path});
60
61 break :lock .exclusive;
62 },
63 };
64
65 // We ask for a lock in order to coordinate with other zig processes.
66 // If another process is already working on this file, we will get the cached
67 // version. Likewise if we're working on AstGen and another process asks for
68 // the cached file, they'll get it.
69 const cache_file = while (true) {
70 break zir_dir.createFile(&hex_digest, .{
71 .read = true,
72 .truncate = false,
73 .lock = lock,
74 }) catch |err| switch (err) {
75 error.NotDir => unreachable, // no dir components
76 error.InvalidUtf8 => unreachable, // it's a hex encoded name
77 error.InvalidWtf8 => unreachable, // it's a hex encoded name
78 error.BadPathName => unreachable, // it's a hex encoded name
79 error.NameTooLong => unreachable, // it's a fixed size name
80 error.PipeBusy => unreachable, // it's not a pipe
81 error.WouldBlock => unreachable, // not asking for non-blocking I/O
82 // There are no dir components, so you would think that this was
83 // unreachable, however we have observed on macOS two processes racing
84 // to do openat() with O_CREAT manifest in ENOENT.
85 error.FileNotFound => continue,
86
87 else => |e| return e, // Retryable errors are handled at callsite.
88 };
89 };
90 defer cache_file.close();
91
92 while (true) {
93 update: {
94 // First we read the header to determine the lengths of arrays.
95 const header = cache_file.reader().readStruct(Zir.Header) catch |err| switch (err) {
96 // This can happen if Zig bails out of this function between creating
97 // the cached file and writing it.
98 error.EndOfStream => break :update,
99 else => |e| return e,
100 };
101 const unchanged_metadata =
102 stat.size == header.stat_size and
103 stat.mtime == header.stat_mtime and
104 stat.inode == header.stat_inode;
105
106 if (!unchanged_metadata) {
107 log.debug("AstGen cache stale: {s}", .{file.sub_file_path});
108 break :update;
109 }
110 log.debug("AstGen cache hit: {s} instructions_len={d}", .{
111 file.sub_file_path, header.instructions_len,
112 });
113
114 file.zir = Zcu.loadZirCacheBody(gpa, header, cache_file) catch |err| switch (err) {
115 error.UnexpectedFileSize => {
116 log.warn("unexpected EOF reading cached ZIR for {s}", .{file.sub_file_path});
117 break :update;
118 },
119 else => |e| return e,
120 };
121 file.zir_loaded = true;
122 file.stat = .{
123 .size = header.stat_size,
124 .inode = header.stat_inode,
125 .mtime = header.stat_mtime,
126 };
127 file.status = .success_zir;
128 log.debug("AstGen cached success: {s}", .{file.sub_file_path});
129
130 // TODO don't report compile errors until Sema @importFile
131 if (file.zir.hasCompileErrors()) {
132 {
133 comp.mutex.lock();
134 defer comp.mutex.unlock();
135 try zcu.failed_files.putNoClobber(gpa, file, null);
136 }
137 file.status = .astgen_failure;
138 return error.AnalysisFail;
139 }
140 return;
141 }
142
143 // If we already have the exclusive lock then it is our job to update.
144 if (builtin.os.tag == .wasi or lock == .exclusive) break;
145 // Otherwise, unlock to give someone a chance to get the exclusive lock
146 // and then upgrade to an exclusive lock.
147 cache_file.unlock();
148 lock = .exclusive;
149 try cache_file.lock(lock);
150 }
151
152 // The cache is definitely stale so delete the contents to avoid an underwrite later.
153 cache_file.setEndPos(0) catch |err| switch (err) {
154 error.FileTooBig => unreachable, // 0 is not too big
155
156 else => |e| return e,
157 };
158
159 pt.lockAndClearFileCompileError(file);
160
161 // If the previous ZIR does not have compile errors, keep it around
162 // in case parsing or new ZIR fails. In case of successful ZIR update
163 // at the end of this function we will free it.
164 // We keep the previous ZIR loaded so that we can use it
165 // for the update next time it does not have any compile errors. This avoids
166 // needlessly tossing out semantic analysis work when an error is
167 // temporarily introduced.
168 if (file.zir_loaded and !file.zir.hasCompileErrors()) {
169 assert(file.prev_zir == null);
170 const prev_zir_ptr = try gpa.create(Zir);
171 file.prev_zir = prev_zir_ptr;
172 prev_zir_ptr.* = file.zir;
173 file.zir = undefined;
174 file.zir_loaded = false;
175 }
176 file.unload(gpa);
177
178 if (stat.size > std.math.maxInt(u32))
179 return error.FileTooBig;
180
181 const source = try gpa.allocSentinel(u8, @as(usize, @intCast(stat.size)), 0);
182 defer if (!file.source_loaded) gpa.free(source);
183 const amt = try source_file.readAll(source);
184 if (amt != stat.size)
185 return error.UnexpectedEndOfFile;
186
187 file.stat = .{
188 .size = stat.size,
189 .inode = stat.inode,
190 .mtime = stat.mtime,
191 };
192 file.source = source;
193 file.source_loaded = true;
194
195 file.tree = try Ast.parse(gpa, source, .zig);
196 file.tree_loaded = true;
197
198 // Any potential AST errors are converted to ZIR errors here.
199 file.zir = try AstGen.generate(gpa, file.tree);
200 file.zir_loaded = true;
201 file.status = .success_zir;
202 log.debug("AstGen fresh success: {s}", .{file.sub_file_path});
203
204 const safety_buffer = if (Zcu.data_has_safety_tag)
205 try gpa.alloc([8]u8, file.zir.instructions.len)
206 else
207 undefined;
208 defer if (Zcu.data_has_safety_tag) gpa.free(safety_buffer);
209 const data_ptr = if (Zcu.data_has_safety_tag)
210 if (file.zir.instructions.len == 0)
211 @as([*]const u8, undefined)
212 else
213 @as([*]const u8, @ptrCast(safety_buffer.ptr))
214 else
215 @as([*]const u8, @ptrCast(file.zir.instructions.items(.data).ptr));
216 if (Zcu.data_has_safety_tag) {
217 // The `Data` union has a safety tag but in the file format we store it without.
218 for (file.zir.instructions.items(.data), 0..) |*data, i| {
219 const as_struct: *const Zcu.HackDataLayout = @ptrCast(data);
220 safety_buffer[i] = as_struct.data;
221 }
222 }
223
224 const header: Zir.Header = .{
225 .instructions_len = @as(u32, @intCast(file.zir.instructions.len)),
226 .string_bytes_len = @as(u32, @intCast(file.zir.string_bytes.len)),
227 .extra_len = @as(u32, @intCast(file.zir.extra.len)),
228
229 .stat_size = stat.size,
230 .stat_inode = stat.inode,
231 .stat_mtime = stat.mtime,
232 };
233 var iovecs = [_]std.posix.iovec_const{
234 .{
235 .base = @as([*]const u8, @ptrCast(&header)),
236 .len = @sizeOf(Zir.Header),
237 },
238 .{
239 .base = @as([*]const u8, @ptrCast(file.zir.instructions.items(.tag).ptr)),
240 .len = file.zir.instructions.len,
241 },
242 .{
243 .base = data_ptr,
244 .len = file.zir.instructions.len * 8,
245 },
246 .{
247 .base = file.zir.string_bytes.ptr,
248 .len = file.zir.string_bytes.len,
249 },
250 .{
251 .base = @as([*]const u8, @ptrCast(file.zir.extra.ptr)),
252 .len = file.zir.extra.len * 4,
253 },
254 };
255 cache_file.writevAll(&iovecs) catch |err| {
256 log.warn("unable to write cached ZIR code for {}{s} to {}{s}: {s}", .{
257 file.mod.root, file.sub_file_path, cache_directory, &hex_digest, @errorName(err),
258 });
259 };
260
261 if (file.zir.hasCompileErrors()) {
262 {
263 comp.mutex.lock();
264 defer comp.mutex.unlock();
265 try zcu.failed_files.putNoClobber(gpa, file, null);
266 }
267 file.status = .astgen_failure;
268 return error.AnalysisFail;
269 }
270
271 if (file.prev_zir) |prev_zir| {
272 try pt.updateZirRefs(file, file_index, prev_zir.*);
273 // No need to keep previous ZIR.
274 prev_zir.deinit(gpa);
275 gpa.destroy(prev_zir);
276 file.prev_zir = null;
277 }
278
279 if (opt_root_decl.unwrap()) |root_decl| {
280 // The root of this file must be re-analyzed, since the file has changed.
281 comp.mutex.lock();
282 defer comp.mutex.unlock();
283
284 log.debug("outdated root Decl: {}", .{root_decl});
285 try zcu.outdated_file_root.put(gpa, root_decl, {});
286 }
287}
288
289/// This is called from the AstGen thread pool, so must acquire
290/// the Compilation mutex when acting on shared state.
291fn updateZirRefs(pt: Zcu.PerThread, file: *Zcu.File, file_index: Zcu.File.Index, old_zir: Zir) !void {
292 const zcu = pt.zcu;
293 const gpa = zcu.gpa;
294 const new_zir = file.zir;
295
296 var inst_map: std.AutoHashMapUnmanaged(Zir.Inst.Index, Zir.Inst.Index) = .{};
297 defer inst_map.deinit(gpa);
298
299 try Zcu.mapOldZirToNew(gpa, old_zir, new_zir, &inst_map);
300
301 const old_tag = old_zir.instructions.items(.tag);
302 const old_data = old_zir.instructions.items(.data);
303
304 // TODO: this should be done after all AstGen workers complete, to avoid
305 // iterating over this full set for every updated file.
306 for (zcu.intern_pool.tracked_insts.keys(), 0..) |*ti, idx_raw| {
307 const ti_idx: InternPool.TrackedInst.Index = @enumFromInt(idx_raw);
308 if (ti.file != file_index) continue;
309 const old_inst = ti.inst;
310 ti.inst = inst_map.get(ti.inst) orelse {
311 // Tracking failed for this instruction. Invalidate associated `src_hash` deps.
312 zcu.comp.mutex.lock();
313 defer zcu.comp.mutex.unlock();
314 log.debug("tracking failed for %{d}", .{old_inst});
315 try zcu.markDependeeOutdated(.{ .src_hash = ti_idx });
316 continue;
317 };
318
319 if (old_zir.getAssociatedSrcHash(old_inst)) |old_hash| hash_changed: {
320 if (new_zir.getAssociatedSrcHash(ti.inst)) |new_hash| {
321 if (std.zig.srcHashEql(old_hash, new_hash)) {
322 break :hash_changed;
323 }
324 log.debug("hash for (%{d} -> %{d}) changed: {} -> {}", .{
325 old_inst,
326 ti.inst,
327 std.fmt.fmtSliceHexLower(&old_hash),
328 std.fmt.fmtSliceHexLower(&new_hash),
329 });
330 }
331 // The source hash associated with this instruction changed - invalidate relevant dependencies.
332 zcu.comp.mutex.lock();
333 defer zcu.comp.mutex.unlock();
334 try zcu.markDependeeOutdated(.{ .src_hash = ti_idx });
335 }
336
337 // If this is a `struct_decl` etc, we must invalidate any outdated namespace dependencies.
338 const has_namespace = switch (old_tag[@intFromEnum(old_inst)]) {
339 .extended => switch (old_data[@intFromEnum(old_inst)].extended.opcode) {
340 .struct_decl, .union_decl, .opaque_decl, .enum_decl => true,
341 else => false,
342 },
343 else => false,
344 };
345 if (!has_namespace) continue;
346
347 var old_names: std.AutoArrayHashMapUnmanaged(InternPool.NullTerminatedString, void) = .{};
348 defer old_names.deinit(zcu.gpa);
349 {
350 var it = old_zir.declIterator(old_inst);
351 while (it.next()) |decl_inst| {
352 const decl_name = old_zir.getDeclaration(decl_inst)[0].name;
353 switch (decl_name) {
354 .@"comptime", .@"usingnamespace", .unnamed_test, .decltest => continue,
355 _ => if (decl_name.isNamedTest(old_zir)) continue,
356 }
357 const name_zir = decl_name.toString(old_zir).?;
358 const name_ip = try zcu.intern_pool.getOrPutString(
359 zcu.gpa,
360 pt.tid,
361 old_zir.nullTerminatedString(name_zir),
362 .no_embedded_nulls,
363 );
364 try old_names.put(zcu.gpa, name_ip, {});
365 }
366 }
367 var any_change = false;
368 {
369 var it = new_zir.declIterator(ti.inst);
370 while (it.next()) |decl_inst| {
371 const decl_name = old_zir.getDeclaration(decl_inst)[0].name;
372 switch (decl_name) {
373 .@"comptime", .@"usingnamespace", .unnamed_test, .decltest => continue,
374 _ => if (decl_name.isNamedTest(old_zir)) continue,
375 }
376 const name_zir = decl_name.toString(old_zir).?;
377 const name_ip = try zcu.intern_pool.getOrPutString(
378 zcu.gpa,
379 pt.tid,
380 old_zir.nullTerminatedString(name_zir),
381 .no_embedded_nulls,
382 );
383 if (!old_names.swapRemove(name_ip)) continue;
384 // Name added
385 any_change = true;
386 zcu.comp.mutex.lock();
387 defer zcu.comp.mutex.unlock();
388 try zcu.markDependeeOutdated(.{ .namespace_name = .{
389 .namespace = ti_idx,
390 .name = name_ip,
391 } });
392 }
393 }
394 // The only elements remaining in `old_names` now are any names which were removed.
395 for (old_names.keys()) |name_ip| {
396 any_change = true;
397 zcu.comp.mutex.lock();
398 defer zcu.comp.mutex.unlock();
399 try zcu.markDependeeOutdated(.{ .namespace_name = .{
400 .namespace = ti_idx,
401 .name = name_ip,
402 } });
403 }
404
405 if (any_change) {
406 zcu.comp.mutex.lock();
407 defer zcu.comp.mutex.unlock();
408 try zcu.markDependeeOutdated(.{ .namespace = ti_idx });
409 }
410 }
411}
412
413/// Like `ensureDeclAnalyzed`, but the Decl is a file's root Decl.
414pub fn ensureFileAnalyzed(pt: Zcu.PerThread, file_index: Zcu.File.Index) Zcu.SemaError!void {
415 if (pt.zcu.fileRootDecl(file_index).unwrap()) |existing_root| {
416 return pt.ensureDeclAnalyzed(existing_root);
417 } else {
418 return pt.semaFile(file_index);
419 }
420}
421
422/// This ensures that the Decl will have an up-to-date Type and Value populated.
423/// However the resolution status of the Type may not be fully resolved.
424/// For example an inferred error set is not resolved until after `analyzeFnBody`.
425/// is called.
426pub fn ensureDeclAnalyzed(pt: Zcu.PerThread, decl_index: Zcu.Decl.Index) Zcu.SemaError!void {
427 const tracy = trace(@src());
428 defer tracy.end();
429
430 const mod = pt.zcu;
431 const ip = &mod.intern_pool;
432 const decl = mod.declPtr(decl_index);
433
434 log.debug("ensureDeclAnalyzed '{d}' (name '{}')", .{
435 @intFromEnum(decl_index),
436 decl.name.fmt(ip),
437 });
438
439 // Determine whether or not this Decl is outdated, i.e. requires re-analysis
440 // even if `complete`. If a Decl is PO, we pessismistically assume that it
441 // *does* require re-analysis, to ensure that the Decl is definitely
442 // up-to-date when this function returns.
443
444 // If analysis occurs in a poor order, this could result in over-analysis.
445 // We do our best to avoid this by the other dependency logic in this file
446 // which tries to limit re-analysis to Decls whose previously listed
447 // dependencies are all up-to-date.
448
449 const decl_as_depender = InternPool.AnalUnit.wrap(.{ .decl = decl_index });
450 const decl_was_outdated = mod.outdated.swapRemove(decl_as_depender) or
451 mod.potentially_outdated.swapRemove(decl_as_depender);
452
453 if (decl_was_outdated) {
454 _ = mod.outdated_ready.swapRemove(decl_as_depender);
455 }
456
457 const was_outdated = mod.outdated_file_root.swapRemove(decl_index) or decl_was_outdated;
458
459 switch (decl.analysis) {
460 .in_progress => unreachable,
461
462 .file_failure => return error.AnalysisFail,
463
464 .sema_failure,
465 .dependency_failure,
466 .codegen_failure,
467 => if (!was_outdated) return error.AnalysisFail,
468
469 .complete => if (!was_outdated) return,
470
471 .unreferenced => {},
472 }
473
474 if (was_outdated) {
475 // The exports this Decl performs will be re-discovered, so we remove them here
476 // prior to re-analysis.
477 if (build_options.only_c) unreachable;
478 mod.deleteUnitExports(decl_as_depender);
479 mod.deleteUnitReferences(decl_as_depender);
480 }
481
482 const sema_result: Zcu.SemaDeclResult = blk: {
483 if (decl.zir_decl_index == .none and !mod.declIsRoot(decl_index)) {
484 // Anonymous decl. We don't semantically analyze these.
485 break :blk .{
486 .invalidate_decl_val = false,
487 .invalidate_decl_ref = false,
488 };
489 }
490
491 if (mod.declIsRoot(decl_index)) {
492 const changed = try pt.semaFileUpdate(decl.getFileScopeIndex(mod), decl_was_outdated);
493 break :blk .{
494 .invalidate_decl_val = changed,
495 .invalidate_decl_ref = changed,
496 };
497 }
498
499 const decl_prog_node = mod.sema_prog_node.start((try decl.fullyQualifiedName(pt)).toSlice(ip), 0);
500 defer decl_prog_node.end();
501
502 break :blk pt.semaDecl(decl_index) catch |err| switch (err) {
503 error.AnalysisFail => {
504 if (decl.analysis == .in_progress) {
505 // If this decl caused the compile error, the analysis field would
506 // be changed to indicate it was this Decl's fault. Because this
507 // did not happen, we infer here that it was a dependency failure.
508 decl.analysis = .dependency_failure;
509 }
510 return error.AnalysisFail;
511 },
512 error.GenericPoison => unreachable,
513 else => |e| {
514 decl.analysis = .sema_failure;
515 try mod.failed_analysis.ensureUnusedCapacity(mod.gpa, 1);
516 try mod.retryable_failures.append(mod.gpa, InternPool.AnalUnit.wrap(.{ .decl = decl_index }));
517 mod.failed_analysis.putAssumeCapacityNoClobber(InternPool.AnalUnit.wrap(.{ .decl = decl_index }), try Zcu.ErrorMsg.create(
518 mod.gpa,
519 decl.navSrcLoc(mod),
520 "unable to analyze: {s}",
521 .{@errorName(e)},
522 ));
523 return error.AnalysisFail;
524 },
525 };
526 };
527
528 // TODO: we do not yet have separate dependencies for decl values vs types.
529 if (decl_was_outdated) {
530 if (sema_result.invalidate_decl_val or sema_result.invalidate_decl_ref) {
531 log.debug("Decl tv invalidated ('{d}')", .{@intFromEnum(decl_index)});
532 // This dependency was marked as PO, meaning dependees were waiting
533 // on its analysis result, and it has turned out to be outdated.
534 // Update dependees accordingly.
535 try mod.markDependeeOutdated(.{ .decl_val = decl_index });
536 } else {
537 log.debug("Decl tv up-to-date ('{d}')", .{@intFromEnum(decl_index)});
538 // This dependency was previously PO, but turned out to be up-to-date.
539 // We do not need to queue successive analysis.
540 try mod.markPoDependeeUpToDate(.{ .decl_val = decl_index });
541 }
542 }
543}
544
545pub fn ensureFuncBodyAnalyzed(pt: Zcu.PerThread, maybe_coerced_func_index: InternPool.Index) Zcu.SemaError!void {
546 const tracy = trace(@src());
547 defer tracy.end();
548
549 const zcu = pt.zcu;
550 const gpa = zcu.gpa;
551 const ip = &zcu.intern_pool;
552
553 // We only care about the uncoerced function.
554 // We need to do this for the "orphaned function" check below to be valid.
555 const func_index = ip.unwrapCoercedFunc(maybe_coerced_func_index);
556
557 const func = zcu.funcInfo(maybe_coerced_func_index);
558 const decl_index = func.owner_decl;
559 const decl = zcu.declPtr(decl_index);
560
561 log.debug("ensureFuncBodyAnalyzed '{d}' (instance of '{}')", .{
562 @intFromEnum(func_index),
563 decl.name.fmt(ip),
564 });
565
566 // First, our owner decl must be up-to-date. This will always be the case
567 // during the first update, but may not on successive updates if we happen
568 // to get analyzed before our parent decl.
569 try pt.ensureDeclAnalyzed(decl_index);
570
571 // On an update, it's possible this function changed such that our owner
572 // decl now refers to a different function, making this one orphaned. If
573 // that's the case, we should remove this function from the binary.
574 if (decl.val.ip_index != func_index) {
575 try zcu.markDependeeOutdated(.{ .func_ies = func_index });
576 ip.removeDependenciesForDepender(gpa, InternPool.AnalUnit.wrap(.{ .func = func_index }));
577 ip.remove(pt.tid, func_index);
578 @panic("TODO: remove orphaned function from binary");
579 }
580
581 // We'll want to remember what the IES used to be before the update for
582 // dependency invalidation purposes.
583 const old_resolved_ies = if (func.analysis(ip).inferred_error_set)
584 func.resolvedErrorSet(ip).*
585 else
586 .none;
587
588 switch (decl.analysis) {
589 .unreferenced => unreachable,
590 .in_progress => unreachable,
591
592 .codegen_failure => unreachable, // functions do not perform constant value generation
593
594 .file_failure,
595 .sema_failure,
596 .dependency_failure,
597 => return error.AnalysisFail,
598
599 .complete => {},
600 }
601
602 const func_as_depender = InternPool.AnalUnit.wrap(.{ .func = func_index });
603 const was_outdated = zcu.outdated.swapRemove(func_as_depender) or
604 zcu.potentially_outdated.swapRemove(func_as_depender);
605
606 if (was_outdated) {
607 if (build_options.only_c) unreachable;
608 _ = zcu.outdated_ready.swapRemove(func_as_depender);
609 zcu.deleteUnitExports(func_as_depender);
610 zcu.deleteUnitReferences(func_as_depender);
611 }
612
613 switch (func.analysis(ip).state) {
614 .success => if (!was_outdated) return,
615 .sema_failure,
616 .dependency_failure,
617 .codegen_failure,
618 => if (!was_outdated) return error.AnalysisFail,
619 .none, .queued => {},
620 .in_progress => unreachable,
621 .inline_only => unreachable, // don't queue work for this
622 }
623
624 log.debug("analyze and generate fn body '{d}'; reason='{s}'", .{
625 @intFromEnum(func_index),
626 if (was_outdated) "outdated" else "never analyzed",
627 });
628
629 var tmp_arena = std.heap.ArenaAllocator.init(gpa);
630 defer tmp_arena.deinit();
631 const sema_arena = tmp_arena.allocator();
632
633 var air = pt.analyzeFnBody(func_index, sema_arena) catch |err| switch (err) {
634 error.AnalysisFail => {
635 if (func.analysis(ip).state == .in_progress) {
636 // If this decl caused the compile error, the analysis field would
637 // be changed to indicate it was this Decl's fault. Because this
638 // did not happen, we infer here that it was a dependency failure.
639 func.analysis(ip).state = .dependency_failure;
640 }
641 return error.AnalysisFail;
642 },
643 error.OutOfMemory => return error.OutOfMemory,
644 };
645 errdefer air.deinit(gpa);
646
647 const invalidate_ies_deps = i: {
648 if (!was_outdated) break :i false;
649 if (!func.analysis(ip).inferred_error_set) break :i true;
650 const new_resolved_ies = func.resolvedErrorSet(ip).*;
651 break :i new_resolved_ies != old_resolved_ies;
652 };
653 if (invalidate_ies_deps) {
654 log.debug("func IES invalidated ('{d}')", .{@intFromEnum(func_index)});
655 try zcu.markDependeeOutdated(.{ .func_ies = func_index });
656 } else if (was_outdated) {
657 log.debug("func IES up-to-date ('{d}')", .{@intFromEnum(func_index)});
658 try zcu.markPoDependeeUpToDate(.{ .func_ies = func_index });
659 }
660
661 const comp = zcu.comp;
662
663 const dump_air = build_options.enable_debug_extensions and comp.verbose_air;
664 const dump_llvm_ir = build_options.enable_debug_extensions and (comp.verbose_llvm_ir != null or comp.verbose_llvm_bc != null);
665
666 if (comp.bin_file == null and zcu.llvm_object == null and !dump_air and !dump_llvm_ir) {
667 air.deinit(gpa);
668 return;
669 }
670
671 try comp.work_queue.writeItem(.{ .codegen_func = .{
672 .func = func_index,
673 .air = air,
674 } });
675}
676
677/// Takes ownership of `air`, even on error.
678/// If any types referenced by `air` are unresolved, marks the codegen as failed.
679pub fn linkerUpdateFunc(pt: Zcu.PerThread, func_index: InternPool.Index, air: Air) Allocator.Error!void {
680 const zcu = pt.zcu;
681 const gpa = zcu.gpa;
682 const ip = &zcu.intern_pool;
683 const comp = zcu.comp;
684
685 defer {
686 var air_mut = air;
687 air_mut.deinit(gpa);
688 }
689
690 const func = zcu.funcInfo(func_index);
691 const decl_index = func.owner_decl;
692 const decl = zcu.declPtr(decl_index);
693
694 var liveness = try Liveness.analyze(gpa, air, ip);
695 defer liveness.deinit(gpa);
696
697 if (build_options.enable_debug_extensions and comp.verbose_air) {
698 const fqn = try decl.fullyQualifiedName(pt);
699 std.debug.print("# Begin Function AIR: {}:\n", .{fqn.fmt(ip)});
700 @import("../print_air.zig").dump(pt, air, liveness);
701 std.debug.print("# End Function AIR: {}\n\n", .{fqn.fmt(ip)});
702 }
703
704 if (std.debug.runtime_safety) {
705 var verify: Liveness.Verify = .{
706 .gpa = gpa,
707 .air = air,
708 .liveness = liveness,
709 .intern_pool = ip,
710 };
711 defer verify.deinit();
712
713 verify.verify() catch |err| switch (err) {
714 error.OutOfMemory => return error.OutOfMemory,
715 else => {
716 try zcu.failed_analysis.ensureUnusedCapacity(gpa, 1);
717 zcu.failed_analysis.putAssumeCapacityNoClobber(
718 InternPool.AnalUnit.wrap(.{ .func = func_index }),
719 try Zcu.ErrorMsg.create(
720 gpa,
721 decl.navSrcLoc(zcu),
722 "invalid liveness: {s}",
723 .{@errorName(err)},
724 ),
725 );
726 func.analysis(ip).state = .codegen_failure;
727 return;
728 },
729 };
730 }
731
732 const codegen_prog_node = zcu.codegen_prog_node.start((try decl.fullyQualifiedName(pt)).toSlice(ip), 0);
733 defer codegen_prog_node.end();
734
735 if (!air.typesFullyResolved(zcu)) {
736 // A type we depend on failed to resolve. This is a transitive failure.
737 // Correcting this failure will involve changing a type this function
738 // depends on, hence triggering re-analysis of this function, so this
739 // interacts correctly with incremental compilation.
740 func.analysis(ip).state = .codegen_failure;
741 } else if (comp.bin_file) |lf| {
742 lf.updateFunc(pt, func_index, air, liveness) catch |err| switch (err) {
743 error.OutOfMemory => return error.OutOfMemory,
744 error.AnalysisFail => {
745 func.analysis(ip).state = .codegen_failure;
746 },
747 else => {
748 try zcu.failed_analysis.ensureUnusedCapacity(gpa, 1);
749 zcu.failed_analysis.putAssumeCapacityNoClobber(InternPool.AnalUnit.wrap(.{ .func = func_index }), try Zcu.ErrorMsg.create(
750 gpa,
751 decl.navSrcLoc(zcu),
752 "unable to codegen: {s}",
753 .{@errorName(err)},
754 ));
755 func.analysis(ip).state = .codegen_failure;
756 try zcu.retryable_failures.append(zcu.gpa, InternPool.AnalUnit.wrap(.{ .func = func_index }));
757 },
758 };
759 } else if (zcu.llvm_object) |llvm_object| {
760 if (build_options.only_c) unreachable;
761 llvm_object.updateFunc(pt, func_index, air, liveness) catch |err| switch (err) {
762 error.OutOfMemory => return error.OutOfMemory,
763 };
764 }
765}
766
767/// https://github.com/ziglang/zig/issues/14307
768pub fn semaPkg(pt: Zcu.PerThread, pkg: *Module) !void {
769 const import_file_result = try pt.zcu.importPkg(pkg);
770 const root_decl_index = pt.zcu.fileRootDecl(import_file_result.file_index);
771 if (root_decl_index == .none) {
772 return pt.semaFile(import_file_result.file_index);
773 }
774}
775
776fn getFileRootStruct(
777 pt: Zcu.PerThread,
778 decl_index: Zcu.Decl.Index,
779 namespace_index: Zcu.Namespace.Index,
780 file_index: Zcu.File.Index,
781) Allocator.Error!InternPool.Index {
782 const zcu = pt.zcu;
783 const gpa = zcu.gpa;
784 const ip = &zcu.intern_pool;
785 const file = zcu.fileByIndex(file_index);
786 const extended = file.zir.instructions.items(.data)[@intFromEnum(Zir.Inst.Index.main_struct_inst)].extended;
787 assert(extended.opcode == .struct_decl);
788 const small: Zir.Inst.StructDecl.Small = @bitCast(extended.small);
789 assert(!small.has_captures_len);
790 assert(!small.has_backing_int);
791 assert(small.layout == .auto);
792 var extra_index: usize = extended.operand + @typeInfo(Zir.Inst.StructDecl).Struct.fields.len;
793 const fields_len = if (small.has_fields_len) blk: {
794 const fields_len = file.zir.extra[extra_index];
795 extra_index += 1;
796 break :blk fields_len;
797 } else 0;
798 const decls_len = if (small.has_decls_len) blk: {
799 const decls_len = file.zir.extra[extra_index];
800 extra_index += 1;
801 break :blk decls_len;
802 } else 0;
803 const decls = file.zir.bodySlice(extra_index, decls_len);
804 extra_index += decls_len;
805
806 const tracked_inst = try ip.trackZir(gpa, file_index, .main_struct_inst);
807 const wip_ty = switch (try ip.getStructType(gpa, pt.tid, .{
808 .layout = .auto,
809 .fields_len = fields_len,
810 .known_non_opv = small.known_non_opv,
811 .requires_comptime = if (small.known_comptime_only) .yes else .unknown,
812 .is_tuple = small.is_tuple,
813 .any_comptime_fields = small.any_comptime_fields,
814 .any_default_inits = small.any_default_inits,
815 .inits_resolved = false,
816 .any_aligned_fields = small.any_aligned_fields,
817 .has_namespace = true,
818 .key = .{ .declared = .{
819 .zir_index = tracked_inst,
820 .captures = &.{},
821 } },
822 })) {
823 .existing => unreachable, // we wouldn't be analysing the file root if this type existed
824 .wip => |wip| wip,
825 };
826 errdefer wip_ty.cancel(ip, pt.tid);
827
828 if (zcu.comp.debug_incremental) {
829 try ip.addDependency(
830 gpa,
831 InternPool.AnalUnit.wrap(.{ .decl = decl_index }),
832 .{ .src_hash = tracked_inst },
833 );
834 }
835
836 const decl = zcu.declPtr(decl_index);
837 decl.val = Value.fromInterned(wip_ty.index);
838 decl.has_tv = true;
839 decl.owns_tv = true;
840 decl.analysis = .complete;
841
842 try pt.scanNamespace(namespace_index, decls, decl);
843 try zcu.comp.work_queue.writeItem(.{ .resolve_type_fully = wip_ty.index });
844 return wip_ty.finish(ip, decl_index, namespace_index.toOptional());
845}
846
847/// Re-analyze the root Decl of a file on an incremental update.
848/// If `type_outdated`, the struct type itself is considered outdated and is
849/// reconstructed at a new InternPool index. Otherwise, the namespace is just
850/// re-analyzed. Returns whether the decl's tyval was invalidated.
851fn semaFileUpdate(pt: Zcu.PerThread, file_index: Zcu.File.Index, type_outdated: bool) Zcu.SemaError!bool {
852 const zcu = pt.zcu;
853 const ip = &zcu.intern_pool;
854 const file = zcu.fileByIndex(file_index);
855 const decl = zcu.declPtr(zcu.fileRootDecl(file_index).unwrap().?);
856
857 log.debug("semaFileUpdate mod={s} sub_file_path={s} type_outdated={}", .{
858 file.mod.fully_qualified_name,
859 file.sub_file_path,
860 type_outdated,
861 });
862
863 if (file.status != .success_zir) {
864 if (decl.analysis == .file_failure) {
865 return false;
866 } else {
867 decl.analysis = .file_failure;
868 return true;
869 }
870 }
871
872 if (decl.analysis == .file_failure) {
873 // No struct type currently exists. Create one!
874 const root_decl = zcu.fileRootDecl(file_index);
875 _ = try pt.getFileRootStruct(root_decl.unwrap().?, decl.src_namespace, file_index);
876 return true;
877 }
878
879 assert(decl.has_tv);
880 assert(decl.owns_tv);
881
882 if (type_outdated) {
883 // Invalidate the existing type, reusing the decl and namespace.
884 const file_root_decl = zcu.fileRootDecl(file_index).unwrap().?;
885 ip.removeDependenciesForDepender(zcu.gpa, InternPool.AnalUnit.wrap(.{
886 .decl = file_root_decl,
887 }));
888 ip.remove(pt.tid, decl.val.toIntern());
889 decl.val = undefined;
890 _ = try pt.getFileRootStruct(file_root_decl, decl.src_namespace, file_index);
891 return true;
892 }
893
894 // Only the struct's namespace is outdated.
895 // Preserve the type - just scan the namespace again.
896
897 const extended = file.zir.instructions.items(.data)[@intFromEnum(Zir.Inst.Index.main_struct_inst)].extended;
898 const small: Zir.Inst.StructDecl.Small = @bitCast(extended.small);
899
900 var extra_index: usize = extended.operand + @typeInfo(Zir.Inst.StructDecl).Struct.fields.len;
901 extra_index += @intFromBool(small.has_fields_len);
902 const decls_len = if (small.has_decls_len) blk: {
903 const decls_len = file.zir.extra[extra_index];
904 extra_index += 1;
905 break :blk decls_len;
906 } else 0;
907 const decls = file.zir.bodySlice(extra_index, decls_len);
908
909 if (!type_outdated) {
910 try pt.scanNamespace(decl.src_namespace, decls, decl);
911 }
912
913 return false;
914}
915
916/// Regardless of the file status, will create a `Decl` if none exists so that we can track
917/// dependencies and re-analyze when the file becomes outdated.
918fn semaFile(pt: Zcu.PerThread, file_index: Zcu.File.Index) Zcu.SemaError!void {
919 const tracy = trace(@src());
920 defer tracy.end();
921
922 const zcu = pt.zcu;
923 const gpa = zcu.gpa;
924 const file = zcu.fileByIndex(file_index);
925 assert(zcu.fileRootDecl(file_index) == .none);
926 log.debug("semaFile zcu={s} sub_file_path={s}", .{
927 file.mod.fully_qualified_name, file.sub_file_path,
928 });
929
930 // Because these three things each reference each other, `undefined`
931 // placeholders are used before being set after the struct type gains an
932 // InternPool index.
933 const new_namespace_index = try zcu.createNamespace(.{
934 .parent = .none,
935 .decl_index = undefined,
936 .file_scope = file_index,
937 });
938 errdefer zcu.destroyNamespace(new_namespace_index);
939
940 const new_decl_index = try zcu.allocateNewDecl(new_namespace_index);
941 const new_decl = zcu.declPtr(new_decl_index);
942 errdefer @panic("TODO error handling");
943
944 zcu.setFileRootDecl(file_index, new_decl_index.toOptional());
945 zcu.namespacePtr(new_namespace_index).decl_index = new_decl_index;
946
947 new_decl.name = try file.fullyQualifiedName(pt);
948 new_decl.name_fully_qualified = true;
949 new_decl.is_pub = true;
950 new_decl.is_exported = false;
951 new_decl.alignment = .none;
952 new_decl.@"linksection" = .none;
953 new_decl.analysis = .in_progress;
954
955 if (file.status != .success_zir) {
956 new_decl.analysis = .file_failure;
957 return;
958 }
959 assert(file.zir_loaded);
960
961 const struct_ty = try pt.getFileRootStruct(new_decl_index, new_namespace_index, file_index);
962 errdefer zcu.intern_pool.remove(pt.tid, struct_ty);
963
964 switch (zcu.comp.cache_use) {
965 .whole => |whole| if (whole.cache_manifest) |man| {
966 const source = file.getSource(gpa) catch |err| {
967 try Zcu.reportRetryableFileError(zcu, file_index, "unable to load source: {s}", .{@errorName(err)});
968 return error.AnalysisFail;
969 };
970
971 const resolved_path = std.fs.path.resolve(gpa, &.{
972 file.mod.root.root_dir.path orelse ".",
973 file.mod.root.sub_path,
974 file.sub_file_path,
975 }) catch |err| {
976 try Zcu.reportRetryableFileError(zcu, file_index, "unable to resolve path: {s}", .{@errorName(err)});
977 return error.AnalysisFail;
978 };
979 errdefer gpa.free(resolved_path);
980
981 whole.cache_manifest_mutex.lock();
982 defer whole.cache_manifest_mutex.unlock();
983 try man.addFilePostContents(resolved_path, source.bytes, source.stat);
984 },
985 .incremental => {},
986 }
987}
988
989fn semaDecl(pt: Zcu.PerThread, decl_index: Zcu.Decl.Index) !Zcu.SemaDeclResult {
990 const tracy = trace(@src());
991 defer tracy.end();
992
993 const zcu = pt.zcu;
994 const decl = zcu.declPtr(decl_index);
995 const ip = &zcu.intern_pool;
996
997 if (decl.getFileScope(zcu).status != .success_zir) {
998 return error.AnalysisFail;
999 }
1000
1001 assert(!zcu.declIsRoot(decl_index));
1002
1003 if (decl.zir_decl_index == .none and decl.owns_tv) {
1004 // We are re-analyzing an anonymous owner Decl (for a function or a namespace type).
1005 return pt.semaAnonOwnerDecl(decl_index);
1006 }
1007
1008 log.debug("semaDecl '{d}'", .{@intFromEnum(decl_index)});
1009 log.debug("decl name '{}'", .{(try decl.fullyQualifiedName(pt)).fmt(ip)});
1010 defer blk: {
1011 log.debug("finish decl name '{}'", .{(decl.fullyQualifiedName(pt) catch break :blk).fmt(ip)});
1012 }
1013
1014 const old_has_tv = decl.has_tv;
1015 // The following values are ignored if `!old_has_tv`
1016 const old_ty = if (old_has_tv) decl.typeOf(zcu) else undefined;
1017 const old_val = decl.val;
1018 const old_align = decl.alignment;
1019 const old_linksection = decl.@"linksection";
1020 const old_addrspace = decl.@"addrspace";
1021 const old_is_inline = if (decl.getOwnedFunction(zcu)) |prev_func|
1022 prev_func.analysis(ip).state == .inline_only
1023 else
1024 false;
1025
1026 const decl_inst = decl.zir_decl_index.unwrap().?.resolve(ip);
1027
1028 const gpa = zcu.gpa;
1029 const zir = decl.getFileScope(zcu).zir;
1030
1031 const builtin_type_target_index: InternPool.Index = ip_index: {
1032 const std_mod = zcu.std_mod;
1033 if (decl.getFileScope(zcu).mod != std_mod) break :ip_index .none;
1034 // We're in the std module.
1035 const std_file_imported = try zcu.importPkg(std_mod);
1036 const std_file_root_decl_index = zcu.fileRootDecl(std_file_imported.file_index);
1037 const std_decl = zcu.declPtr(std_file_root_decl_index.unwrap().?);
1038 const std_namespace = std_decl.getInnerNamespace(zcu).?;
1039 const builtin_str = try ip.getOrPutString(gpa, pt.tid, "builtin", .no_embedded_nulls);
1040 const builtin_decl = zcu.declPtr(std_namespace.decls.getKeyAdapted(builtin_str, Zcu.DeclAdapter{ .zcu = zcu }) orelse break :ip_index .none);
1041 const builtin_namespace = builtin_decl.getInnerNamespaceIndex(zcu).unwrap() orelse break :ip_index .none;
1042 if (decl.src_namespace != builtin_namespace) break :ip_index .none;
1043 // We're in builtin.zig. This could be a builtin we need to add to a specific InternPool index.
1044 for ([_][]const u8{
1045 "AtomicOrder",
1046 "AtomicRmwOp",
1047 "CallingConvention",
1048 "AddressSpace",
1049 "FloatMode",
1050 "ReduceOp",
1051 "CallModifier",
1052 "PrefetchOptions",
1053 "ExportOptions",
1054 "ExternOptions",
1055 "Type",
1056 }, [_]InternPool.Index{
1057 .atomic_order_type,
1058 .atomic_rmw_op_type,
1059 .calling_convention_type,
1060 .address_space_type,
1061 .float_mode_type,
1062 .reduce_op_type,
1063 .call_modifier_type,
1064 .prefetch_options_type,
1065 .export_options_type,
1066 .extern_options_type,
1067 .type_info_type,
1068 }) |type_name, type_ip| {
1069 if (decl.name.eqlSlice(type_name, ip)) break :ip_index type_ip;
1070 }
1071 break :ip_index .none;
1072 };
1073
1074 zcu.intern_pool.removeDependenciesForDepender(gpa, InternPool.AnalUnit.wrap(.{ .decl = decl_index }));
1075
1076 decl.analysis = .in_progress;
1077
1078 var analysis_arena = std.heap.ArenaAllocator.init(gpa);
1079 defer analysis_arena.deinit();
1080
1081 var comptime_err_ret_trace = std.ArrayList(Zcu.LazySrcLoc).init(gpa);
1082 defer comptime_err_ret_trace.deinit();
1083
1084 var sema: Sema = .{
1085 .pt = pt,
1086 .gpa = gpa,
1087 .arena = analysis_arena.allocator(),
1088 .code = zir,
1089 .owner_decl = decl,
1090 .owner_decl_index = decl_index,
1091 .func_index = .none,
1092 .func_is_naked = false,
1093 .fn_ret_ty = Type.void,
1094 .fn_ret_ty_ies = null,
1095 .owner_func_index = .none,
1096 .comptime_err_ret_trace = &comptime_err_ret_trace,
1097 .builtin_type_target_index = builtin_type_target_index,
1098 };
1099 defer sema.deinit();
1100
1101 // Every Decl (other than file root Decls, which do not have a ZIR index) has a dependency on its own source.
1102 try sema.declareDependency(.{ .src_hash = try ip.trackZir(
1103 gpa,
1104 decl.getFileScopeIndex(zcu),
1105 decl_inst,
1106 ) });
1107
1108 var block_scope: Sema.Block = .{
1109 .parent = null,
1110 .sema = &sema,
1111 .namespace = decl.src_namespace,
1112 .instructions = .{},
1113 .inlining = null,
1114 .is_comptime = true,
1115 .src_base_inst = decl.zir_decl_index.unwrap().?,
1116 .type_name_ctx = decl.name,
1117 };
1118 defer block_scope.instructions.deinit(gpa);
1119
1120 const decl_bodies = decl.zirBodies(zcu);
1121
1122 const result_ref = try sema.resolveInlineBody(&block_scope, decl_bodies.value_body, decl_inst);
1123 // We'll do some other bits with the Sema. Clear the type target index just
1124 // in case they analyze any type.
1125 sema.builtin_type_target_index = .none;
1126 const align_src = block_scope.src(.{ .node_offset_var_decl_align = 0 });
1127 const section_src = block_scope.src(.{ .node_offset_var_decl_section = 0 });
1128 const address_space_src = block_scope.src(.{ .node_offset_var_decl_addrspace = 0 });
1129 const ty_src = block_scope.src(.{ .node_offset_var_decl_ty = 0 });
1130 const init_src = block_scope.src(.{ .node_offset_var_decl_init = 0 });
1131 const decl_val = try sema.resolveFinalDeclValue(&block_scope, init_src, result_ref);
1132 const decl_ty = decl_val.typeOf(zcu);
1133
1134 // Note this resolves the type of the Decl, not the value; if this Decl
1135 // is a struct, for example, this resolves `type` (which needs no resolution),
1136 // not the struct itself.
1137 try decl_ty.resolveLayout(pt);
1138
1139 if (decl.kind == .@"usingnamespace") {
1140 if (!decl_ty.eql(Type.type, zcu)) {
1141 return sema.fail(&block_scope, ty_src, "expected type, found {}", .{decl_ty.fmt(pt)});
1142 }
1143 const ty = decl_val.toType();
1144 if (ty.getNamespace(zcu) == null) {
1145 return sema.fail(&block_scope, ty_src, "type {} has no namespace", .{ty.fmt(pt)});
1146 }
1147
1148 decl.val = ty.toValue();
1149 decl.alignment = .none;
1150 decl.@"linksection" = .none;
1151 decl.has_tv = true;
1152 decl.owns_tv = false;
1153 decl.analysis = .complete;
1154
1155 // TODO: usingnamespace cannot currently participate in incremental compilation
1156 return .{
1157 .invalidate_decl_val = true,
1158 .invalidate_decl_ref = true,
1159 };
1160 }
1161
1162 var queue_linker_work = true;
1163 var is_func = false;
1164 var is_inline = false;
1165 switch (decl_val.toIntern()) {
1166 .generic_poison => unreachable,
1167 .unreachable_value => unreachable,
1168 else => switch (ip.indexToKey(decl_val.toIntern())) {
1169 .variable => |variable| {
1170 decl.owns_tv = variable.decl == decl_index;
1171 queue_linker_work = decl.owns_tv;
1172 },
1173
1174 .extern_func => |extern_func| {
1175 decl.owns_tv = extern_func.decl == decl_index;
1176 queue_linker_work = decl.owns_tv;
1177 is_func = decl.owns_tv;
1178 },
1179
1180 .func => |func| {
1181 decl.owns_tv = func.owner_decl == decl_index;
1182 queue_linker_work = false;
1183 is_inline = decl.owns_tv and decl_ty.fnCallingConvention(zcu) == .Inline;
1184 is_func = decl.owns_tv;
1185 },
1186
1187 else => {},
1188 },
1189 }
1190
1191 decl.val = decl_val;
1192 // Function linksection, align, and addrspace were already set by Sema
1193 if (!is_func) {
1194 decl.alignment = blk: {
1195 const align_body = decl_bodies.align_body orelse break :blk .none;
1196 const align_ref = try sema.resolveInlineBody(&block_scope, align_body, decl_inst);
1197 break :blk try sema.analyzeAsAlign(&block_scope, align_src, align_ref);
1198 };
1199 decl.@"linksection" = blk: {
1200 const linksection_body = decl_bodies.linksection_body orelse break :blk .none;
1201 const linksection_ref = try sema.resolveInlineBody(&block_scope, linksection_body, decl_inst);
1202 const bytes = try sema.toConstString(&block_scope, section_src, linksection_ref, .{
1203 .needed_comptime_reason = "linksection must be comptime-known",
1204 });
1205 if (std.mem.indexOfScalar(u8, bytes, 0) != null) {
1206 return sema.fail(&block_scope, section_src, "linksection cannot contain null bytes", .{});
1207 } else if (bytes.len == 0) {
1208 return sema.fail(&block_scope, section_src, "linksection cannot be empty", .{});
1209 }
1210 break :blk try ip.getOrPutStringOpt(gpa, pt.tid, bytes, .no_embedded_nulls);
1211 };
1212 decl.@"addrspace" = blk: {
1213 const addrspace_ctx: Sema.AddressSpaceContext = switch (ip.indexToKey(decl_val.toIntern())) {
1214 .variable => .variable,
1215 .extern_func, .func => .function,
1216 else => .constant,
1217 };
1218
1219 const target = zcu.getTarget();
1220
1221 const addrspace_body = decl_bodies.addrspace_body orelse break :blk switch (addrspace_ctx) {
1222 .function => target_util.defaultAddressSpace(target, .function),
1223 .variable => target_util.defaultAddressSpace(target, .global_mutable),
1224 .constant => target_util.defaultAddressSpace(target, .global_constant),
1225 else => unreachable,
1226 };
1227 const addrspace_ref = try sema.resolveInlineBody(&block_scope, addrspace_body, decl_inst);
1228 break :blk try sema.analyzeAsAddressSpace(&block_scope, address_space_src, addrspace_ref, addrspace_ctx);
1229 };
1230 }
1231 decl.has_tv = true;
1232 decl.analysis = .complete;
1233
1234 const result: Zcu.SemaDeclResult = if (old_has_tv) .{
1235 .invalidate_decl_val = !decl_ty.eql(old_ty, zcu) or
1236 !decl.val.eql(old_val, decl_ty, zcu) or
1237 is_inline != old_is_inline,
1238 .invalidate_decl_ref = !decl_ty.eql(old_ty, zcu) or
1239 decl.alignment != old_align or
1240 decl.@"linksection" != old_linksection or
1241 decl.@"addrspace" != old_addrspace or
1242 is_inline != old_is_inline,
1243 } else .{
1244 .invalidate_decl_val = true,
1245 .invalidate_decl_ref = true,
1246 };
1247
1248 const has_runtime_bits = queue_linker_work and (is_func or try sema.typeHasRuntimeBits(decl_ty));
1249 if (has_runtime_bits) {
1250 // Needed for codegen_decl which will call updateDecl and then the
1251 // codegen backend wants full access to the Decl Type.
1252 try decl_ty.resolveFully(pt);
1253
1254 try zcu.comp.work_queue.writeItem(.{ .codegen_decl = decl_index });
1255
1256 if (result.invalidate_decl_ref and zcu.emit_h != null) {
1257 try zcu.comp.work_queue.writeItem(.{ .emit_h_decl = decl_index });
1258 }
1259 }
1260
1261 if (decl.is_exported) {
1262 const export_src = block_scope.src(.{ .token_offset = @intFromBool(decl.is_pub) });
1263 if (is_inline) return sema.fail(&block_scope, export_src, "export of inline function", .{});
1264 // The scope needs to have the decl in it.
1265 try sema.analyzeExport(&block_scope, export_src, .{ .name = decl.name }, decl_index);
1266 }
1267
1268 try sema.flushExports();
1269
1270 return result;
1271}
1272
1273pub fn semaAnonOwnerDecl(pt: Zcu.PerThread, decl_index: Zcu.Decl.Index) !Zcu.SemaDeclResult {
1274 const zcu = pt.zcu;
1275 const decl = zcu.declPtr(decl_index);
1276
1277 assert(decl.has_tv);
1278 assert(decl.owns_tv);
1279
1280 log.debug("semaAnonOwnerDecl '{d}'", .{@intFromEnum(decl_index)});
1281
1282 switch (decl.typeOf(zcu).zigTypeTag(zcu)) {
1283 .Fn => @panic("TODO: update fn instance"),
1284 .Type => {},
1285 else => unreachable,
1286 }
1287
1288 // We are the owner Decl of a type, and we were marked as outdated. That means the *structure*
1289 // of this type changed; not just its namespace. Therefore, we need a new InternPool index.
1290 //
1291 // However, as soon as we make that, the context that created us will require re-analysis anyway
1292 // (as it depends on this Decl's value), meaning the `struct_decl` (or equivalent) instruction
1293 // will be analyzed again. Since Sema already needs to be able to reconstruct types like this,
1294 // why should we bother implementing it here too when the Sema logic will be hit right after?
1295 //
1296 // So instead, let's just mark this Decl as failed - so that any remaining Decls which genuinely
1297 // reference it (via `@This`) end up silently erroring too - and we'll let Sema make a new type
1298 // with a new Decl.
1299 //
1300 // Yes, this does mean that any type owner Decl has a constant value for its entire lifetime.
1301 zcu.intern_pool.removeDependenciesForDepender(zcu.gpa, InternPool.AnalUnit.wrap(.{ .decl = decl_index }));
1302 zcu.intern_pool.remove(pt.tid, decl.val.toIntern());
1303 decl.analysis = .dependency_failure;
1304 return .{
1305 .invalidate_decl_val = true,
1306 .invalidate_decl_ref = true,
1307 };
1308}
1309
1310pub fn embedFile(
1311 pt: Zcu.PerThread,
1312 cur_file: *Zcu.File,
1313 import_string: []const u8,
1314 src_loc: Zcu.LazySrcLoc,
1315) !InternPool.Index {
1316 const mod = pt.zcu;
1317 const gpa = mod.gpa;
1318
1319 if (cur_file.mod.deps.get(import_string)) |pkg| {
1320 const resolved_path = try std.fs.path.resolve(gpa, &.{
1321 pkg.root.root_dir.path orelse ".",
1322 pkg.root.sub_path,
1323 pkg.root_src_path,
1324 });
1325 var keep_resolved_path = false;
1326 defer if (!keep_resolved_path) gpa.free(resolved_path);
1327
1328 const gop = try mod.embed_table.getOrPut(gpa, resolved_path);
1329 errdefer {
1330 assert(std.mem.eql(u8, mod.embed_table.pop().key, resolved_path));
1331 keep_resolved_path = false;
1332 }
1333 if (gop.found_existing) return gop.value_ptr.*.val;
1334 keep_resolved_path = true;
1335
1336 const sub_file_path = try gpa.dupe(u8, pkg.root_src_path);
1337 errdefer gpa.free(sub_file_path);
1338
1339 return pt.newEmbedFile(pkg, sub_file_path, resolved_path, gop.value_ptr, src_loc);
1340 }
1341
1342 // The resolved path is used as the key in the table, to detect if a file
1343 // refers to the same as another, despite different relative paths.
1344 const resolved_path = try std.fs.path.resolve(gpa, &.{
1345 cur_file.mod.root.root_dir.path orelse ".",
1346 cur_file.mod.root.sub_path,
1347 cur_file.sub_file_path,
1348 "..",
1349 import_string,
1350 });
1351
1352 var keep_resolved_path = false;
1353 defer if (!keep_resolved_path) gpa.free(resolved_path);
1354
1355 const gop = try mod.embed_table.getOrPut(gpa, resolved_path);
1356 errdefer {
1357 assert(std.mem.eql(u8, mod.embed_table.pop().key, resolved_path));
1358 keep_resolved_path = false;
1359 }
1360 if (gop.found_existing) return gop.value_ptr.*.val;
1361 keep_resolved_path = true;
1362
1363 const resolved_root_path = try std.fs.path.resolve(gpa, &.{
1364 cur_file.mod.root.root_dir.path orelse ".",
1365 cur_file.mod.root.sub_path,
1366 });
1367 defer gpa.free(resolved_root_path);
1368
1369 const sub_file_path = p: {
1370 const relative = try std.fs.path.relative(gpa, resolved_root_path, resolved_path);
1371 errdefer gpa.free(relative);
1372
1373 if (!isUpDir(relative) and !std.fs.path.isAbsolute(relative)) {
1374 break :p relative;
1375 }
1376 return error.ImportOutsideModulePath;
1377 };
1378 defer gpa.free(sub_file_path);
1379
1380 return pt.newEmbedFile(cur_file.mod, sub_file_path, resolved_path, gop.value_ptr, src_loc);
1381}
1382
1383/// Finalize the creation of an anon decl.
1384pub fn finalizeAnonDecl(pt: Zcu.PerThread, decl_index: Zcu.Decl.Index) Allocator.Error!void {
1385 if (pt.zcu.declPtr(decl_index).typeOf(pt.zcu).isFnOrHasRuntimeBits(pt)) {
1386 try pt.zcu.comp.work_queue.writeItem(.{ .codegen_decl = decl_index });
1387 }
1388}
1389
1390/// https://github.com/ziglang/zig/issues/14307
1391fn newEmbedFile(
1392 pt: Zcu.PerThread,
1393 pkg: *Module,
1394 sub_file_path: []const u8,
1395 resolved_path: []const u8,
1396 result: **Zcu.EmbedFile,
1397 src_loc: Zcu.LazySrcLoc,
1398) !InternPool.Index {
1399 const mod = pt.zcu;
1400 const gpa = mod.gpa;
1401 const ip = &mod.intern_pool;
1402
1403 const new_file = try gpa.create(Zcu.EmbedFile);
1404 errdefer gpa.destroy(new_file);
1405
1406 var file = try pkg.root.openFile(sub_file_path, .{});
1407 defer file.close();
1408
1409 const actual_stat = try file.stat();
1410 const stat: Cache.File.Stat = .{
1411 .size = actual_stat.size,
1412 .inode = actual_stat.inode,
1413 .mtime = actual_stat.mtime,
1414 };
1415 const size = std.math.cast(usize, actual_stat.size) orelse return error.Overflow;
1416
1417 const strings = ip.getLocal(pt.tid).getMutableStrings(gpa);
1418 const bytes = try strings.addManyAsSlice(try std.math.add(usize, size, 1));
1419 const actual_read = try file.readAll(bytes[0][0..size]);
1420 if (actual_read != size) return error.UnexpectedEndOfFile;
1421 bytes[0][size] = 0;
1422
1423 const comp = mod.comp;
1424 switch (comp.cache_use) {
1425 .whole => |whole| if (whole.cache_manifest) |man| {
1426 const copied_resolved_path = try gpa.dupe(u8, resolved_path);
1427 errdefer gpa.free(copied_resolved_path);
1428 whole.cache_manifest_mutex.lock();
1429 defer whole.cache_manifest_mutex.unlock();
1430 try man.addFilePostContents(copied_resolved_path, bytes[0][0..size], stat);
1431 },
1432 .incremental => {},
1433 }
1434
1435 const array_ty = try pt.intern(.{ .array_type = .{
1436 .len = size,
1437 .sentinel = .zero_u8,
1438 .child = .u8_type,
1439 } });
1440 const array_val = try pt.intern(.{ .aggregate = .{
1441 .ty = array_ty,
1442 .storage = .{ .bytes = try ip.getOrPutTrailingString(gpa, pt.tid, @intCast(bytes[0].len), .maybe_embedded_nulls) },
1443 } });
1444
1445 const ptr_ty = (try pt.ptrType(.{
1446 .child = array_ty,
1447 .flags = .{
1448 .alignment = .none,
1449 .is_const = true,
1450 .address_space = .generic,
1451 },
1452 })).toIntern();
1453 const ptr_val = try pt.intern(.{ .ptr = .{
1454 .ty = ptr_ty,
1455 .base_addr = .{ .anon_decl = .{
1456 .val = array_val,
1457 .orig_ty = ptr_ty,
1458 } },
1459 .byte_offset = 0,
1460 } });
1461
1462 result.* = new_file;
1463 new_file.* = .{
1464 .sub_file_path = try ip.getOrPutString(gpa, pt.tid, sub_file_path, .no_embedded_nulls),
1465 .owner = pkg,
1466 .stat = stat,
1467 .val = ptr_val,
1468 .src_loc = src_loc,
1469 };
1470 return ptr_val;
1471}
1472
1473pub fn scanNamespace(
1474 pt: Zcu.PerThread,
1475 namespace_index: Zcu.Namespace.Index,
1476 decls: []const Zir.Inst.Index,
1477 parent_decl: *Zcu.Decl,
1478) Allocator.Error!void {
1479 const tracy = trace(@src());
1480 defer tracy.end();
1481
1482 const zcu = pt.zcu;
1483 const gpa = zcu.gpa;
1484 const namespace = zcu.namespacePtr(namespace_index);
1485
1486 // For incremental updates, `scanDecl` wants to look up existing decls by their ZIR index rather
1487 // than their name. We'll build an efficient mapping now, then discard the current `decls`.
1488 var existing_by_inst: std.AutoHashMapUnmanaged(InternPool.TrackedInst.Index, Zcu.Decl.Index) = .{};
1489 defer existing_by_inst.deinit(gpa);
1490
1491 try existing_by_inst.ensureTotalCapacity(gpa, @intCast(namespace.decls.count()));
1492
1493 for (namespace.decls.keys()) |decl_index| {
1494 const decl = zcu.declPtr(decl_index);
1495 existing_by_inst.putAssumeCapacityNoClobber(decl.zir_decl_index.unwrap().?, decl_index);
1496 }
1497
1498 var seen_decls: std.AutoHashMapUnmanaged(InternPool.NullTerminatedString, void) = .{};
1499 defer seen_decls.deinit(gpa);
1500
1501 try zcu.comp.work_queue.ensureUnusedCapacity(decls.len);
1502
1503 namespace.decls.clearRetainingCapacity();
1504 try namespace.decls.ensureTotalCapacity(gpa, decls.len);
1505
1506 namespace.usingnamespace_set.clearRetainingCapacity();
1507
1508 var scan_decl_iter: ScanDeclIter = .{
1509 .pt = pt,
1510 .namespace_index = namespace_index,
1511 .parent_decl = parent_decl,
1512 .seen_decls = &seen_decls,
1513 .existing_by_inst = &existing_by_inst,
1514 .pass = .named,
1515 };
1516 for (decls) |decl_inst| {
1517 try scan_decl_iter.scanDecl(decl_inst);
1518 }
1519 scan_decl_iter.pass = .unnamed;
1520 for (decls) |decl_inst| {
1521 try scan_decl_iter.scanDecl(decl_inst);
1522 }
1523
1524 if (seen_decls.count() != namespace.decls.count()) {
1525 // Do a pass over the namespace contents and remove any decls from the last update
1526 // which were removed in this one.
1527 var i: usize = 0;
1528 while (i < namespace.decls.count()) {
1529 const decl_index = namespace.decls.keys()[i];
1530 const decl = zcu.declPtr(decl_index);
1531 if (!seen_decls.contains(decl.name)) {
1532 // We must preserve namespace ordering for @typeInfo.
1533 namespace.decls.orderedRemoveAt(i);
1534 i -= 1;
1535 }
1536 }
1537 }
1538}
1539
1540const ScanDeclIter = struct {
1541 pt: Zcu.PerThread,
1542 namespace_index: Zcu.Namespace.Index,
1543 parent_decl: *Zcu.Decl,
1544 seen_decls: *std.AutoHashMapUnmanaged(InternPool.NullTerminatedString, void),
1545 existing_by_inst: *const std.AutoHashMapUnmanaged(InternPool.TrackedInst.Index, Zcu.Decl.Index),
1546 /// Decl scanning is run in two passes, so that we can detect when a generated
1547 /// name would clash with an explicit name and use a different one.
1548 pass: enum { named, unnamed },
1549 usingnamespace_index: usize = 0,
1550 comptime_index: usize = 0,
1551 unnamed_test_index: usize = 0,
1552
1553 fn avoidNameConflict(iter: *ScanDeclIter, comptime fmt: []const u8, args: anytype) !InternPool.NullTerminatedString {
1554 const pt = iter.pt;
1555 const gpa = pt.zcu.gpa;
1556 const ip = &pt.zcu.intern_pool;
1557 var name = try ip.getOrPutStringFmt(gpa, pt.tid, fmt, args, .no_embedded_nulls);
1558 var gop = try iter.seen_decls.getOrPut(gpa, name);
1559 var next_suffix: u32 = 0;
1560 while (gop.found_existing) {
1561 name = try ip.getOrPutStringFmt(gpa, pt.tid, "{}_{d}", .{ name.fmt(ip), next_suffix }, .no_embedded_nulls);
1562 gop = try iter.seen_decls.getOrPut(gpa, name);
1563 next_suffix += 1;
1564 }
1565 return name;
1566 }
1567
1568 fn scanDecl(iter: *ScanDeclIter, decl_inst: Zir.Inst.Index) Allocator.Error!void {
1569 const tracy = trace(@src());
1570 defer tracy.end();
1571
1572 const pt = iter.pt;
1573 const zcu = pt.zcu;
1574 const namespace_index = iter.namespace_index;
1575 const namespace = zcu.namespacePtr(namespace_index);
1576 const gpa = zcu.gpa;
1577 const zir = namespace.fileScope(zcu).zir;
1578 const ip = &zcu.intern_pool;
1579
1580 const inst_data = zir.instructions.items(.data)[@intFromEnum(decl_inst)].declaration;
1581 const extra = zir.extraData(Zir.Inst.Declaration, inst_data.payload_index);
1582 const declaration = extra.data;
1583
1584 // Every Decl needs a name.
1585 const decl_name: InternPool.NullTerminatedString, const kind: Zcu.Decl.Kind, const is_named_test: bool = switch (declaration.name) {
1586 .@"comptime" => info: {
1587 if (iter.pass != .unnamed) return;
1588 const i = iter.comptime_index;
1589 iter.comptime_index += 1;
1590 break :info .{
1591 try iter.avoidNameConflict("comptime_{d}", .{i}),
1592 .@"comptime",
1593 false,
1594 };
1595 },
1596 .@"usingnamespace" => info: {
1597 // TODO: this isn't right! These should be considered unnamed. Name conflicts can happen here.
1598 // The problem is, we need to preserve the decl ordering for `@typeInfo`.
1599 // I'm not bothering to fix this now, since some upcoming changes will change this code significantly anyway.
1600 if (iter.pass != .named) return;
1601 const i = iter.usingnamespace_index;
1602 iter.usingnamespace_index += 1;
1603 break :info .{
1604 try iter.avoidNameConflict("usingnamespace_{d}", .{i}),
1605 .@"usingnamespace",
1606 false,
1607 };
1608 },
1609 .unnamed_test => info: {
1610 if (iter.pass != .unnamed) return;
1611 const i = iter.unnamed_test_index;
1612 iter.unnamed_test_index += 1;
1613 break :info .{
1614 try iter.avoidNameConflict("test_{d}", .{i}),
1615 .@"test",
1616 false,
1617 };
1618 },
1619 .decltest => info: {
1620 // We consider these to be unnamed since the decl name can be adjusted to avoid conflicts if necessary.
1621 if (iter.pass != .unnamed) return;
1622 assert(declaration.flags.has_doc_comment);
1623 const name = zir.nullTerminatedString(@enumFromInt(zir.extra[extra.end]));
1624 break :info .{
1625 try iter.avoidNameConflict("decltest.{s}", .{name}),
1626 .@"test",
1627 true,
1628 };
1629 },
1630 _ => if (declaration.name.isNamedTest(zir)) info: {
1631 // We consider these to be unnamed since the decl name can be adjusted to avoid conflicts if necessary.
1632 if (iter.pass != .unnamed) return;
1633 break :info .{
1634 try iter.avoidNameConflict("test.{s}", .{zir.nullTerminatedString(declaration.name.toString(zir).?)}),
1635 .@"test",
1636 true,
1637 };
1638 } else info: {
1639 if (iter.pass != .named) return;
1640 const name = try ip.getOrPutString(
1641 gpa,
1642 pt.tid,
1643 zir.nullTerminatedString(declaration.name.toString(zir).?),
1644 .no_embedded_nulls,
1645 );
1646 try iter.seen_decls.putNoClobber(gpa, name, {});
1647 break :info .{
1648 name,
1649 .named,
1650 false,
1651 };
1652 },
1653 };
1654
1655 switch (kind) {
1656 .@"usingnamespace" => try namespace.usingnamespace_set.ensureUnusedCapacity(gpa, 1),
1657 .@"test" => try zcu.test_functions.ensureUnusedCapacity(gpa, 1),
1658 else => {},
1659 }
1660
1661 const parent_file_scope_index = iter.parent_decl.getFileScopeIndex(zcu);
1662 const tracked_inst = try ip.trackZir(gpa, parent_file_scope_index, decl_inst);
1663
1664 // We create a Decl for it regardless of analysis status.
1665
1666 const prev_exported, const decl_index = if (iter.existing_by_inst.get(tracked_inst)) |decl_index| decl_index: {
1667 // We need only update this existing Decl.
1668 const decl = zcu.declPtr(decl_index);
1669 const was_exported = decl.is_exported;
1670 assert(decl.kind == kind); // ZIR tracking should preserve this
1671 decl.name = decl_name;
1672 decl.is_pub = declaration.flags.is_pub;
1673 decl.is_exported = declaration.flags.is_export;
1674 break :decl_index .{ was_exported, decl_index };
1675 } else decl_index: {
1676 // Create and set up a new Decl.
1677 const new_decl_index = try zcu.allocateNewDecl(namespace_index);
1678 const new_decl = zcu.declPtr(new_decl_index);
1679 new_decl.kind = kind;
1680 new_decl.name = decl_name;
1681 new_decl.is_pub = declaration.flags.is_pub;
1682 new_decl.is_exported = declaration.flags.is_export;
1683 new_decl.zir_decl_index = tracked_inst.toOptional();
1684 break :decl_index .{ false, new_decl_index };
1685 };
1686
1687 const decl = zcu.declPtr(decl_index);
1688
1689 namespace.decls.putAssumeCapacityNoClobberContext(decl_index, {}, .{ .zcu = zcu });
1690
1691 const comp = zcu.comp;
1692 const decl_mod = namespace.fileScope(zcu).mod;
1693 const want_analysis = declaration.flags.is_export or switch (kind) {
1694 .anon => unreachable,
1695 .@"comptime" => true,
1696 .@"usingnamespace" => a: {
1697 namespace.usingnamespace_set.putAssumeCapacityNoClobber(decl_index, declaration.flags.is_pub);
1698 break :a true;
1699 },
1700 .named => false,
1701 .@"test" => a: {
1702 if (!comp.config.is_test) break :a false;
1703 if (decl_mod != zcu.main_mod) break :a false;
1704 if (is_named_test and comp.test_filters.len > 0) {
1705 const decl_fqn = try namespace.fullyQualifiedName(pt, decl_name);
1706 const decl_fqn_slice = decl_fqn.toSlice(ip);
1707 for (comp.test_filters) |test_filter| {
1708 if (std.mem.indexOf(u8, decl_fqn_slice, test_filter)) |_| break;
1709 } else break :a false;
1710 }
1711 zcu.test_functions.putAssumeCapacity(decl_index, {}); // may clobber on incremental update
1712 break :a true;
1713 },
1714 };
1715
1716 if (want_analysis) {
1717 // We will not queue analysis if the decl has been analyzed on a previous update and
1718 // `is_export` is unchanged. In this case, the incremental update mechanism will handle
1719 // re-analysis for us if necessary.
1720 if (prev_exported != declaration.flags.is_export or decl.analysis == .unreferenced) {
1721 log.debug("scanDecl queue analyze_decl file='{s}' decl_name='{}' decl_index={d}", .{
1722 namespace.fileScope(zcu).sub_file_path, decl_name.fmt(ip), decl_index,
1723 });
1724 comp.work_queue.writeItemAssumeCapacity(.{ .analyze_decl = decl_index });
1725 }
1726 }
1727
1728 if (decl.getOwnedFunction(zcu) != null) {
1729 // TODO this logic is insufficient; namespaces we don't re-scan may still require
1730 // updated line numbers. Look into this!
1731 // TODO Look into detecting when this would be unnecessary by storing enough state
1732 // in `Decl` to notice that the line number did not change.
1733 comp.work_queue.writeItemAssumeCapacity(.{ .update_line_number = decl_index });
1734 }
1735 }
1736};
1737
1738pub fn analyzeFnBody(pt: Zcu.PerThread, func_index: InternPool.Index, arena: Allocator) Zcu.SemaError!Air {
1739 const tracy = trace(@src());
1740 defer tracy.end();
1741
1742 const mod = pt.zcu;
1743 const gpa = mod.gpa;
1744 const ip = &mod.intern_pool;
1745 const func = mod.funcInfo(func_index);
1746 const decl_index = func.owner_decl;
1747 const decl = mod.declPtr(decl_index);
1748
1749 log.debug("func name '{}'", .{(try decl.fullyQualifiedName(pt)).fmt(ip)});
1750 defer blk: {
1751 log.debug("finish func name '{}'", .{(decl.fullyQualifiedName(pt) catch break :blk).fmt(ip)});
1752 }
1753
1754 const decl_prog_node = mod.sema_prog_node.start((try decl.fullyQualifiedName(pt)).toSlice(ip), 0);
1755 defer decl_prog_node.end();
1756
1757 mod.intern_pool.removeDependenciesForDepender(gpa, InternPool.AnalUnit.wrap(.{ .func = func_index }));
1758
1759 var comptime_err_ret_trace = std.ArrayList(Zcu.LazySrcLoc).init(gpa);
1760 defer comptime_err_ret_trace.deinit();
1761
1762 // In the case of a generic function instance, this is the type of the
1763 // instance, which has comptime parameters elided. In other words, it is
1764 // the runtime-known parameters only, not to be confused with the
1765 // generic_owner function type, which potentially has more parameters,
1766 // including comptime parameters.
1767 const fn_ty = decl.typeOf(mod);
1768 const fn_ty_info = mod.typeToFunc(fn_ty).?;
1769
1770 var sema: Sema = .{
1771 .pt = pt,
1772 .gpa = gpa,
1773 .arena = arena,
1774 .code = decl.getFileScope(mod).zir,
1775 .owner_decl = decl,
1776 .owner_decl_index = decl_index,
1777 .func_index = func_index,
1778 .func_is_naked = fn_ty_info.cc == .Naked,
1779 .fn_ret_ty = Type.fromInterned(fn_ty_info.return_type),
1780 .fn_ret_ty_ies = null,
1781 .owner_func_index = func_index,
1782 .branch_quota = @max(func.branchQuota(ip).*, Sema.default_branch_quota),
1783 .comptime_err_ret_trace = &comptime_err_ret_trace,
1784 };
1785 defer sema.deinit();
1786
1787 // Every runtime function has a dependency on the source of the Decl it originates from.
1788 // It also depends on the value of its owner Decl.
1789 try sema.declareDependency(.{ .src_hash = decl.zir_decl_index.unwrap().? });
1790 try sema.declareDependency(.{ .decl_val = decl_index });
1791
1792 if (func.analysis(ip).inferred_error_set) {
1793 const ies = try arena.create(Sema.InferredErrorSet);
1794 ies.* = .{ .func = func_index };
1795 sema.fn_ret_ty_ies = ies;
1796 }
1797
1798 // reset in case calls to errorable functions are removed.
1799 func.analysis(ip).calls_or_awaits_errorable_fn = false;
1800
1801 // First few indexes of extra are reserved and set at the end.
1802 const reserved_count = @typeInfo(Air.ExtraIndex).Enum.fields.len;
1803 try sema.air_extra.ensureTotalCapacity(gpa, reserved_count);
1804 sema.air_extra.items.len += reserved_count;
1805
1806 var inner_block: Sema.Block = .{
1807 .parent = null,
1808 .sema = &sema,
1809 .namespace = decl.src_namespace,
1810 .instructions = .{},
1811 .inlining = null,
1812 .is_comptime = false,
1813 .src_base_inst = inst: {
1814 const owner_info = if (func.generic_owner == .none)
1815 func
1816 else
1817 mod.funcInfo(func.generic_owner);
1818 const orig_decl = mod.declPtr(owner_info.owner_decl);
1819 break :inst orig_decl.zir_decl_index.unwrap().?;
1820 },
1821 .type_name_ctx = decl.name,
1822 };
1823 defer inner_block.instructions.deinit(gpa);
1824
1825 const fn_info = sema.code.getFnInfo(func.zirBodyInst(ip).resolve(ip));
1826
1827 // Here we are performing "runtime semantic analysis" for a function body, which means
1828 // we must map the parameter ZIR instructions to `arg` AIR instructions.
1829 // AIR requires the `arg` parameters to be the first N instructions.
1830 // This could be a generic function instantiation, however, in which case we need to
1831 // map the comptime parameters to constant values and only emit arg AIR instructions
1832 // for the runtime ones.
1833 const runtime_params_len = fn_ty_info.param_types.len;
1834 try inner_block.instructions.ensureTotalCapacityPrecise(gpa, runtime_params_len);
1835 try sema.air_instructions.ensureUnusedCapacity(gpa, fn_info.total_params_len);
1836 try sema.inst_map.ensureSpaceForInstructions(gpa, fn_info.param_body);
1837
1838 // In the case of a generic function instance, pre-populate all the comptime args.
1839 if (func.comptime_args.len != 0) {
1840 for (
1841 fn_info.param_body[0..func.comptime_args.len],
1842 func.comptime_args.get(ip),
1843 ) |inst, comptime_arg| {
1844 if (comptime_arg == .none) continue;
1845 sema.inst_map.putAssumeCapacityNoClobber(inst, Air.internedToRef(comptime_arg));
1846 }
1847 }
1848
1849 const src_params_len = if (func.comptime_args.len != 0)
1850 func.comptime_args.len
1851 else
1852 runtime_params_len;
1853
1854 var runtime_param_index: usize = 0;
1855 for (fn_info.param_body[0..src_params_len], 0..) |inst, src_param_index| {
1856 const gop = sema.inst_map.getOrPutAssumeCapacity(inst);
1857 if (gop.found_existing) continue; // provided above by comptime arg
1858
1859 const param_ty = fn_ty_info.param_types.get(ip)[runtime_param_index];
1860 runtime_param_index += 1;
1861
1862 const opt_opv = sema.typeHasOnePossibleValue(Type.fromInterned(param_ty)) catch |err| switch (err) {
1863 error.GenericPoison => unreachable,
1864 error.ComptimeReturn => unreachable,
1865 error.ComptimeBreak => unreachable,
1866 else => |e| return e,
1867 };
1868 if (opt_opv) |opv| {
1869 gop.value_ptr.* = Air.internedToRef(opv.toIntern());
1870 continue;
1871 }
1872 const arg_index: Air.Inst.Index = @enumFromInt(sema.air_instructions.len);
1873 gop.value_ptr.* = arg_index.toRef();
1874 inner_block.instructions.appendAssumeCapacity(arg_index);
1875 sema.air_instructions.appendAssumeCapacity(.{
1876 .tag = .arg,
1877 .data = .{ .arg = .{
1878 .ty = Air.internedToRef(param_ty),
1879 .src_index = @intCast(src_param_index),
1880 } },
1881 });
1882 }
1883
1884 func.analysis(ip).state = .in_progress;
1885
1886 const last_arg_index = inner_block.instructions.items.len;
1887
1888 // Save the error trace as our first action in the function.
1889 // If this is unnecessary after all, Liveness will clean it up for us.
1890 const error_return_trace_index = try sema.analyzeSaveErrRetIndex(&inner_block);
1891 sema.error_return_trace_index_on_fn_entry = error_return_trace_index;
1892 inner_block.error_return_trace_index = error_return_trace_index;
1893
1894 sema.analyzeFnBody(&inner_block, fn_info.body) catch |err| switch (err) {
1895 // TODO make these unreachable instead of @panic
1896 error.GenericPoison => @panic("zig compiler bug: GenericPoison"),
1897 error.ComptimeReturn => @panic("zig compiler bug: ComptimeReturn"),
1898 else => |e| return e,
1899 };
1900
1901 for (sema.unresolved_inferred_allocs.keys()) |ptr_inst| {
1902 // The lack of a resolve_inferred_alloc means that this instruction
1903 // is unused so it just has to be a no-op.
1904 sema.air_instructions.set(@intFromEnum(ptr_inst), .{
1905 .tag = .alloc,
1906 .data = .{ .ty = Type.single_const_pointer_to_comptime_int },
1907 });
1908 }
1909
1910 // If we don't get an error return trace from a caller, create our own.
1911 if (func.analysis(ip).calls_or_awaits_errorable_fn and
1912 mod.comp.config.any_error_tracing and
1913 !sema.fn_ret_ty.isError(mod))
1914 {
1915 sema.setupErrorReturnTrace(&inner_block, last_arg_index) catch |err| switch (err) {
1916 // TODO make these unreachable instead of @panic
1917 error.GenericPoison => @panic("zig compiler bug: GenericPoison"),
1918 error.ComptimeReturn => @panic("zig compiler bug: ComptimeReturn"),
1919 error.ComptimeBreak => @panic("zig compiler bug: ComptimeBreak"),
1920 else => |e| return e,
1921 };
1922 }
1923
1924 // Copy the block into place and mark that as the main block.
1925 try sema.air_extra.ensureUnusedCapacity(gpa, @typeInfo(Air.Block).Struct.fields.len +
1926 inner_block.instructions.items.len);
1927 const main_block_index = sema.addExtraAssumeCapacity(Air.Block{
1928 .body_len = @intCast(inner_block.instructions.items.len),
1929 });
1930 sema.air_extra.appendSliceAssumeCapacity(@ptrCast(inner_block.instructions.items));
1931 sema.air_extra.items[@intFromEnum(Air.ExtraIndex.main_block)] = main_block_index;
1932
1933 // Resolving inferred error sets is done *before* setting the function
1934 // state to success, so that "unable to resolve inferred error set" errors
1935 // can be emitted here.
1936 if (sema.fn_ret_ty_ies) |ies| {
1937 sema.resolveInferredErrorSetPtr(&inner_block, .{
1938 .base_node_inst = inner_block.src_base_inst,
1939 .offset = Zcu.LazySrcLoc.Offset.nodeOffset(0),
1940 }, ies) catch |err| switch (err) {
1941 error.GenericPoison => unreachable,
1942 error.ComptimeReturn => unreachable,
1943 error.ComptimeBreak => unreachable,
1944 error.AnalysisFail => {
1945 // In this case our function depends on a type that had a compile error.
1946 // We should not try to lower this function.
1947 decl.analysis = .dependency_failure;
1948 return error.AnalysisFail;
1949 },
1950 else => |e| return e,
1951 };
1952 assert(ies.resolved != .none);
1953 ip.funcIesResolved(func_index).* = ies.resolved;
1954 }
1955
1956 func.analysis(ip).state = .success;
1957
1958 // Finally we must resolve the return type and parameter types so that backends
1959 // have full access to type information.
1960 // Crucially, this happens *after* we set the function state to success above,
1961 // so that dependencies on the function body will now be satisfied rather than
1962 // result in circular dependency errors.
1963 sema.resolveFnTypes(fn_ty) catch |err| switch (err) {
1964 error.GenericPoison => unreachable,
1965 error.ComptimeReturn => unreachable,
1966 error.ComptimeBreak => unreachable,
1967 error.AnalysisFail => {
1968 // In this case our function depends on a type that had a compile error.
1969 // We should not try to lower this function.
1970 decl.analysis = .dependency_failure;
1971 return error.AnalysisFail;
1972 },
1973 else => |e| return e,
1974 };
1975
1976 try sema.flushExports();
1977
1978 return .{
1979 .instructions = sema.air_instructions.toOwnedSlice(),
1980 .extra = try sema.air_extra.toOwnedSlice(gpa),
1981 };
1982}
1983
1984fn lockAndClearFileCompileError(pt: Zcu.PerThread, file: *Zcu.File) void {
1985 switch (file.status) {
1986 .success_zir, .retryable_failure => {},
1987 .never_loaded, .parse_failure, .astgen_failure => {
1988 pt.zcu.comp.mutex.lock();
1989 defer pt.zcu.comp.mutex.unlock();
1990 if (pt.zcu.failed_files.fetchSwapRemove(file)) |kv| {
1991 if (kv.value) |msg| msg.destroy(pt.zcu.gpa); // Delete previous error message.
1992 }
1993 },
1994 }
1995}
1996
1997/// Called from `Compilation.update`, after everything is done, just before
1998/// reporting compile errors. In this function we emit exported symbol collision
1999/// errors and communicate exported symbols to the linker backend.
2000pub fn processExports(pt: Zcu.PerThread) !void {
2001 const zcu = pt.zcu;
2002 const gpa = zcu.gpa;
2003
2004 // First, construct a mapping of every exported value and Decl to the indices of all its different exports.
2005 var decl_exports: std.AutoArrayHashMapUnmanaged(Zcu.Decl.Index, std.ArrayListUnmanaged(u32)) = .{};
2006 var value_exports: std.AutoArrayHashMapUnmanaged(InternPool.Index, std.ArrayListUnmanaged(u32)) = .{};
2007 defer {
2008 for (decl_exports.values()) |*exports| {
2009 exports.deinit(gpa);
2010 }
2011 decl_exports.deinit(gpa);
2012 for (value_exports.values()) |*exports| {
2013 exports.deinit(gpa);
2014 }
2015 value_exports.deinit(gpa);
2016 }
2017
2018 // We note as a heuristic:
2019 // * It is rare to export a value.
2020 // * It is rare for one Decl to be exported multiple times.
2021 // So, this ensureTotalCapacity serves as a reasonable (albeit very approximate) optimization.
2022 try decl_exports.ensureTotalCapacity(gpa, zcu.single_exports.count() + zcu.multi_exports.count());
2023
2024 for (zcu.single_exports.values()) |export_idx| {
2025 const exp = zcu.all_exports.items[export_idx];
2026 const value_ptr, const found_existing = switch (exp.exported) {
2027 .decl_index => |i| gop: {
2028 const gop = try decl_exports.getOrPut(gpa, i);
2029 break :gop .{ gop.value_ptr, gop.found_existing };
2030 },
2031 .value => |i| gop: {
2032 const gop = try value_exports.getOrPut(gpa, i);
2033 break :gop .{ gop.value_ptr, gop.found_existing };
2034 },
2035 };
2036 if (!found_existing) value_ptr.* = .{};
2037 try value_ptr.append(gpa, export_idx);
2038 }
2039
2040 for (zcu.multi_exports.values()) |info| {
2041 for (zcu.all_exports.items[info.index..][0..info.len], info.index..) |exp, export_idx| {
2042 const value_ptr, const found_existing = switch (exp.exported) {
2043 .decl_index => |i| gop: {
2044 const gop = try decl_exports.getOrPut(gpa, i);
2045 break :gop .{ gop.value_ptr, gop.found_existing };
2046 },
2047 .value => |i| gop: {
2048 const gop = try value_exports.getOrPut(gpa, i);
2049 break :gop .{ gop.value_ptr, gop.found_existing };
2050 },
2051 };
2052 if (!found_existing) value_ptr.* = .{};
2053 try value_ptr.append(gpa, @intCast(export_idx));
2054 }
2055 }
2056
2057 // Map symbol names to `Export` for name collision detection.
2058 var symbol_exports: SymbolExports = .{};
2059 defer symbol_exports.deinit(gpa);
2060
2061 for (decl_exports.keys(), decl_exports.values()) |exported_decl, exports_list| {
2062 const exported: Zcu.Exported = .{ .decl_index = exported_decl };
2063 try pt.processExportsInner(&symbol_exports, exported, exports_list.items);
2064 }
2065
2066 for (value_exports.keys(), value_exports.values()) |exported_value, exports_list| {
2067 const exported: Zcu.Exported = .{ .value = exported_value };
2068 try pt.processExportsInner(&symbol_exports, exported, exports_list.items);
2069 }
2070}
2071
2072const SymbolExports = std.AutoArrayHashMapUnmanaged(InternPool.NullTerminatedString, u32);
2073
2074fn processExportsInner(
2075 pt: Zcu.PerThread,
2076 symbol_exports: *SymbolExports,
2077 exported: Zcu.Exported,
2078 export_indices: []const u32,
2079) error{OutOfMemory}!void {
2080 const zcu = pt.zcu;
2081 const gpa = zcu.gpa;
2082
2083 for (export_indices) |export_idx| {
2084 const new_export = &zcu.all_exports.items[export_idx];
2085 const gop = try symbol_exports.getOrPut(gpa, new_export.opts.name);
2086 if (gop.found_existing) {
2087 new_export.status = .failed_retryable;
2088 try zcu.failed_exports.ensureUnusedCapacity(gpa, 1);
2089 const msg = try Zcu.ErrorMsg.create(gpa, new_export.src, "exported symbol collision: {}", .{
2090 new_export.opts.name.fmt(&zcu.intern_pool),
2091 });
2092 errdefer msg.destroy(gpa);
2093 const other_export = zcu.all_exports.items[gop.value_ptr.*];
2094 try zcu.errNote(other_export.src, msg, "other symbol here", .{});
2095 zcu.failed_exports.putAssumeCapacityNoClobber(export_idx, msg);
2096 new_export.status = .failed;
2097 } else {
2098 gop.value_ptr.* = export_idx;
2099 }
2100 }
2101 if (zcu.comp.bin_file) |lf| {
2102 try zcu.handleUpdateExports(export_indices, lf.updateExports(pt, exported, export_indices));
2103 } else if (zcu.llvm_object) |llvm_object| {
2104 if (build_options.only_c) unreachable;
2105 try zcu.handleUpdateExports(export_indices, llvm_object.updateExports(pt, exported, export_indices));
2106 }
2107}
2108
2109pub fn populateTestFunctions(
2110 pt: Zcu.PerThread,
2111 main_progress_node: std.Progress.Node,
2112) !void {
2113 const zcu = pt.zcu;
2114 const gpa = zcu.gpa;
2115 const ip = &zcu.intern_pool;
2116 const builtin_mod = zcu.root_mod.getBuiltinDependency();
2117 const builtin_file_index = (zcu.importPkg(builtin_mod) catch unreachable).file_index;
2118 const root_decl_index = zcu.fileRootDecl(builtin_file_index);
2119 const root_decl = zcu.declPtr(root_decl_index.unwrap().?);
2120 const builtin_namespace = zcu.namespacePtr(root_decl.src_namespace);
2121 const test_functions_str = try ip.getOrPutString(gpa, pt.tid, "test_functions", .no_embedded_nulls);
2122 const decl_index = builtin_namespace.decls.getKeyAdapted(
2123 test_functions_str,
2124 Zcu.DeclAdapter{ .zcu = zcu },
2125 ).?;
2126 {
2127 // We have to call `ensureDeclAnalyzed` here in case `builtin.test_functions`
2128 // was not referenced by start code.
2129 zcu.sema_prog_node = main_progress_node.start("Semantic Analysis", 0);
2130 defer {
2131 zcu.sema_prog_node.end();
2132 zcu.sema_prog_node = std.Progress.Node.none;
2133 }
2134 try pt.ensureDeclAnalyzed(decl_index);
2135 }
2136
2137 const decl = zcu.declPtr(decl_index);
2138 const test_fn_ty = decl.typeOf(zcu).slicePtrFieldType(zcu).childType(zcu);
2139
2140 const array_anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl = array: {
2141 // Add zcu.test_functions to an array decl then make the test_functions
2142 // decl reference it as a slice.
2143 const test_fn_vals = try gpa.alloc(InternPool.Index, zcu.test_functions.count());
2144 defer gpa.free(test_fn_vals);
2145
2146 for (test_fn_vals, zcu.test_functions.keys()) |*test_fn_val, test_decl_index| {
2147 const test_decl = zcu.declPtr(test_decl_index);
2148 const test_decl_name = try test_decl.fullyQualifiedName(pt);
2149 const test_decl_name_len = test_decl_name.length(ip);
2150 const test_name_anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl = n: {
2151 const test_name_ty = try pt.arrayType(.{
2152 .len = test_decl_name_len,
2153 .child = .u8_type,
2154 });
2155 const test_name_val = try pt.intern(.{ .aggregate = .{
2156 .ty = test_name_ty.toIntern(),
2157 .storage = .{ .bytes = test_decl_name.toString() },
2158 } });
2159 break :n .{
2160 .orig_ty = (try pt.singleConstPtrType(test_name_ty)).toIntern(),
2161 .val = test_name_val,
2162 };
2163 };
2164
2165 const test_fn_fields = .{
2166 // name
2167 try pt.intern(.{ .slice = .{
2168 .ty = .slice_const_u8_type,
2169 .ptr = try pt.intern(.{ .ptr = .{
2170 .ty = .manyptr_const_u8_type,
2171 .base_addr = .{ .anon_decl = test_name_anon_decl },
2172 .byte_offset = 0,
2173 } }),
2174 .len = try pt.intern(.{ .int = .{
2175 .ty = .usize_type,
2176 .storage = .{ .u64 = test_decl_name_len },
2177 } }),
2178 } }),
2179 // func
2180 try pt.intern(.{ .ptr = .{
2181 .ty = try pt.intern(.{ .ptr_type = .{
2182 .child = test_decl.typeOf(zcu).toIntern(),
2183 .flags = .{
2184 .is_const = true,
2185 },
2186 } }),
2187 .base_addr = .{ .decl = test_decl_index },
2188 .byte_offset = 0,
2189 } }),
2190 };
2191 test_fn_val.* = try pt.intern(.{ .aggregate = .{
2192 .ty = test_fn_ty.toIntern(),
2193 .storage = .{ .elems = &test_fn_fields },
2194 } });
2195 }
2196
2197 const array_ty = try pt.arrayType(.{
2198 .len = test_fn_vals.len,
2199 .child = test_fn_ty.toIntern(),
2200 .sentinel = .none,
2201 });
2202 const array_val = try pt.intern(.{ .aggregate = .{
2203 .ty = array_ty.toIntern(),
2204 .storage = .{ .elems = test_fn_vals },
2205 } });
2206 break :array .{
2207 .orig_ty = (try pt.singleConstPtrType(array_ty)).toIntern(),
2208 .val = array_val,
2209 };
2210 };
2211
2212 {
2213 const new_ty = try pt.ptrType(.{
2214 .child = test_fn_ty.toIntern(),
2215 .flags = .{
2216 .is_const = true,
2217 .size = .Slice,
2218 },
2219 });
2220 const new_val = decl.val;
2221 const new_init = try pt.intern(.{ .slice = .{
2222 .ty = new_ty.toIntern(),
2223 .ptr = try pt.intern(.{ .ptr = .{
2224 .ty = new_ty.slicePtrFieldType(zcu).toIntern(),
2225 .base_addr = .{ .anon_decl = array_anon_decl },
2226 .byte_offset = 0,
2227 } }),
2228 .len = (try pt.intValue(Type.usize, zcu.test_functions.count())).toIntern(),
2229 } });
2230 ip.mutateVarInit(decl.val.toIntern(), new_init);
2231
2232 // Since we are replacing the Decl's value we must perform cleanup on the
2233 // previous value.
2234 decl.val = new_val;
2235 decl.has_tv = true;
2236 }
2237 {
2238 zcu.codegen_prog_node = main_progress_node.start("Code Generation", 0);
2239 defer {
2240 zcu.codegen_prog_node.end();
2241 zcu.codegen_prog_node = std.Progress.Node.none;
2242 }
2243
2244 try pt.linkerUpdateDecl(decl_index);
2245 }
2246}
2247
2248pub fn linkerUpdateDecl(pt: Zcu.PerThread, decl_index: Zcu.Decl.Index) !void {
2249 const zcu = pt.zcu;
2250 const comp = zcu.comp;
2251
2252 const decl = zcu.declPtr(decl_index);
2253
2254 const codegen_prog_node = zcu.codegen_prog_node.start((try decl.fullyQualifiedName(pt)).toSlice(&zcu.intern_pool), 0);
2255 defer codegen_prog_node.end();
2256
2257 if (comp.bin_file) |lf| {
2258 lf.updateDecl(pt, decl_index) catch |err| switch (err) {
2259 error.OutOfMemory => return error.OutOfMemory,
2260 error.AnalysisFail => {
2261 decl.analysis = .codegen_failure;
2262 },
2263 else => {
2264 const gpa = zcu.gpa;
2265 try zcu.failed_analysis.ensureUnusedCapacity(gpa, 1);
2266 zcu.failed_analysis.putAssumeCapacityNoClobber(InternPool.AnalUnit.wrap(.{ .decl = decl_index }), try Zcu.ErrorMsg.create(
2267 gpa,
2268 decl.navSrcLoc(zcu),
2269 "unable to codegen: {s}",
2270 .{@errorName(err)},
2271 ));
2272 decl.analysis = .codegen_failure;
2273 try zcu.retryable_failures.append(zcu.gpa, InternPool.AnalUnit.wrap(.{ .decl = decl_index }));
2274 },
2275 };
2276 } else if (zcu.llvm_object) |llvm_object| {
2277 if (build_options.only_c) unreachable;
2278 llvm_object.updateDecl(pt, decl_index) catch |err| switch (err) {
2279 error.OutOfMemory => return error.OutOfMemory,
2280 };
2281 }
2282}
2283
2284/// Shortcut for calling `intern_pool.get`.
2285pub fn intern(pt: Zcu.PerThread, key: InternPool.Key) Allocator.Error!InternPool.Index {
2286 return pt.zcu.intern_pool.get(pt.zcu.gpa, pt.tid, key);
2287}
2288
2289/// Shortcut for calling `intern_pool.getCoerced`.
2290pub fn getCoerced(pt: Zcu.PerThread, val: Value, new_ty: Type) Allocator.Error!Value {
2291 return Value.fromInterned(try pt.zcu.intern_pool.getCoerced(pt.zcu.gpa, pt.tid, val.toIntern(), new_ty.toIntern()));
2292}
2293
2294pub fn intType(pt: Zcu.PerThread, signedness: std.builtin.Signedness, bits: u16) Allocator.Error!Type {
2295 return Type.fromInterned(try pt.intern(.{ .int_type = .{
2296 .signedness = signedness,
2297 .bits = bits,
2298 } }));
2299}
2300
2301pub fn errorIntType(pt: Zcu.PerThread) std.mem.Allocator.Error!Type {
2302 return pt.intType(.unsigned, pt.zcu.errorSetBits());
2303}
2304
2305pub fn arrayType(pt: Zcu.PerThread, info: InternPool.Key.ArrayType) Allocator.Error!Type {
2306 return Type.fromInterned(try pt.intern(.{ .array_type = info }));
2307}
2308
2309pub fn vectorType(pt: Zcu.PerThread, info: InternPool.Key.VectorType) Allocator.Error!Type {
2310 return Type.fromInterned(try pt.intern(.{ .vector_type = info }));
2311}
2312
2313pub fn optionalType(pt: Zcu.PerThread, child_type: InternPool.Index) Allocator.Error!Type {
2314 return Type.fromInterned(try pt.intern(.{ .opt_type = child_type }));
2315}
2316
2317pub fn ptrType(pt: Zcu.PerThread, info: InternPool.Key.PtrType) Allocator.Error!Type {
2318 var canon_info = info;
2319
2320 if (info.flags.size == .C) canon_info.flags.is_allowzero = true;
2321
2322 // Canonicalize non-zero alignment. If it matches the ABI alignment of the pointee
2323 // type, we change it to 0 here. If this causes an assertion trip because the
2324 // pointee type needs to be resolved more, that needs to be done before calling
2325 // this ptr() function.
2326 if (info.flags.alignment != .none and
2327 info.flags.alignment == Type.fromInterned(info.child).abiAlignment(pt))
2328 {
2329 canon_info.flags.alignment = .none;
2330 }
2331
2332 switch (info.flags.vector_index) {
2333 // Canonicalize host_size. If it matches the bit size of the pointee type,
2334 // we change it to 0 here. If this causes an assertion trip, the pointee type
2335 // needs to be resolved before calling this ptr() function.
2336 .none => if (info.packed_offset.host_size != 0) {
2337 const elem_bit_size = Type.fromInterned(info.child).bitSize(pt);
2338 assert(info.packed_offset.bit_offset + elem_bit_size <= info.packed_offset.host_size * 8);
2339 if (info.packed_offset.host_size * 8 == elem_bit_size) {
2340 canon_info.packed_offset.host_size = 0;
2341 }
2342 },
2343 .runtime => {},
2344 _ => assert(@intFromEnum(info.flags.vector_index) < info.packed_offset.host_size),
2345 }
2346
2347 return Type.fromInterned(try pt.intern(.{ .ptr_type = canon_info }));
2348}
2349
2350/// Like `ptrType`, but if `info` specifies an `alignment`, first ensures the pointer
2351/// child type's alignment is resolved so that an invalid alignment is not used.
2352/// In general, prefer this function during semantic analysis.
2353pub fn ptrTypeSema(pt: Zcu.PerThread, info: InternPool.Key.PtrType) Zcu.SemaError!Type {
2354 if (info.flags.alignment != .none) {
2355 _ = try Type.fromInterned(info.child).abiAlignmentAdvanced(pt, .sema);
2356 }
2357 return pt.ptrType(info);
2358}
2359
2360pub fn singleMutPtrType(pt: Zcu.PerThread, child_type: Type) Allocator.Error!Type {
2361 return pt.ptrType(.{ .child = child_type.toIntern() });
2362}
2363
2364pub fn singleConstPtrType(pt: Zcu.PerThread, child_type: Type) Allocator.Error!Type {
2365 return pt.ptrType(.{
2366 .child = child_type.toIntern(),
2367 .flags = .{
2368 .is_const = true,
2369 },
2370 });
2371}
2372
2373pub fn manyConstPtrType(pt: Zcu.PerThread, child_type: Type) Allocator.Error!Type {
2374 return pt.ptrType(.{
2375 .child = child_type.toIntern(),
2376 .flags = .{
2377 .size = .Many,
2378 .is_const = true,
2379 },
2380 });
2381}
2382
2383pub fn adjustPtrTypeChild(pt: Zcu.PerThread, ptr_ty: Type, new_child: Type) Allocator.Error!Type {
2384 var info = ptr_ty.ptrInfo(pt.zcu);
2385 info.child = new_child.toIntern();
2386 return pt.ptrType(info);
2387}
2388
2389pub fn funcType(pt: Zcu.PerThread, key: InternPool.GetFuncTypeKey) Allocator.Error!Type {
2390 return Type.fromInterned(try pt.zcu.intern_pool.getFuncType(pt.zcu.gpa, pt.tid, key));
2391}
2392
2393/// Use this for `anyframe->T` only.
2394/// For `anyframe`, use the `InternPool.Index.anyframe` tag directly.
2395pub fn anyframeType(pt: Zcu.PerThread, payload_ty: Type) Allocator.Error!Type {
2396 return Type.fromInterned(try pt.intern(.{ .anyframe_type = payload_ty.toIntern() }));
2397}
2398
2399pub fn errorUnionType(pt: Zcu.PerThread, error_set_ty: Type, payload_ty: Type) Allocator.Error!Type {
2400 return Type.fromInterned(try pt.intern(.{ .error_union_type = .{
2401 .error_set_type = error_set_ty.toIntern(),
2402 .payload_type = payload_ty.toIntern(),
2403 } }));
2404}
2405
2406pub fn singleErrorSetType(pt: Zcu.PerThread, name: InternPool.NullTerminatedString) Allocator.Error!Type {
2407 const names: *const [1]InternPool.NullTerminatedString = &name;
2408 return Type.fromInterned(try pt.zcu.intern_pool.getErrorSetType(pt.zcu.gpa, pt.tid, names));
2409}
2410
2411/// Sorts `names` in place.
2412pub fn errorSetFromUnsortedNames(
2413 pt: Zcu.PerThread,
2414 names: []InternPool.NullTerminatedString,
2415) Allocator.Error!Type {
2416 std.mem.sort(
2417 InternPool.NullTerminatedString,
2418 names,
2419 {},
2420 InternPool.NullTerminatedString.indexLessThan,
2421 );
2422 const new_ty = try pt.zcu.intern_pool.getErrorSetType(pt.zcu.gpa, pt.tid, names);
2423 return Type.fromInterned(new_ty);
2424}
2425
2426/// Supports only pointers, not pointer-like optionals.
2427pub fn ptrIntValue(pt: Zcu.PerThread, ty: Type, x: u64) Allocator.Error!Value {
2428 const mod = pt.zcu;
2429 assert(ty.zigTypeTag(mod) == .Pointer and !ty.isSlice(mod));
2430 assert(x != 0 or ty.isAllowzeroPtr(mod));
2431 return Value.fromInterned(try pt.intern(.{ .ptr = .{
2432 .ty = ty.toIntern(),
2433 .base_addr = .int,
2434 .byte_offset = x,
2435 } }));
2436}
2437
2438/// Creates an enum tag value based on the integer tag value.
2439pub fn enumValue(pt: Zcu.PerThread, ty: Type, tag_int: InternPool.Index) Allocator.Error!Value {
2440 if (std.debug.runtime_safety) {
2441 const tag = ty.zigTypeTag(pt.zcu);
2442 assert(tag == .Enum);
2443 }
2444 return Value.fromInterned(try pt.intern(.{ .enum_tag = .{
2445 .ty = ty.toIntern(),
2446 .int = tag_int,
2447 } }));
2448}
2449
2450/// Creates an enum tag value based on the field index according to source code
2451/// declaration order.
2452pub fn enumValueFieldIndex(pt: Zcu.PerThread, ty: Type, field_index: u32) Allocator.Error!Value {
2453 const ip = &pt.zcu.intern_pool;
2454 const enum_type = ip.loadEnumType(ty.toIntern());
2455
2456 if (enum_type.values.len == 0) {
2457 // Auto-numbered fields.
2458 return Value.fromInterned(try pt.intern(.{ .enum_tag = .{
2459 .ty = ty.toIntern(),
2460 .int = try pt.intern(.{ .int = .{
2461 .ty = enum_type.tag_ty,
2462 .storage = .{ .u64 = field_index },
2463 } }),
2464 } }));
2465 }
2466
2467 return Value.fromInterned(try pt.intern(.{ .enum_tag = .{
2468 .ty = ty.toIntern(),
2469 .int = enum_type.values.get(ip)[field_index],
2470 } }));
2471}
2472
2473pub fn undefValue(pt: Zcu.PerThread, ty: Type) Allocator.Error!Value {
2474 return Value.fromInterned(try pt.intern(.{ .undef = ty.toIntern() }));
2475}
2476
2477pub fn undefRef(pt: Zcu.PerThread, ty: Type) Allocator.Error!Air.Inst.Ref {
2478 return Air.internedToRef((try pt.undefValue(ty)).toIntern());
2479}
2480
2481pub fn intValue(pt: Zcu.PerThread, ty: Type, x: anytype) Allocator.Error!Value {
2482 if (std.math.cast(u64, x)) |casted| return pt.intValue_u64(ty, casted);
2483 if (std.math.cast(i64, x)) |casted| return pt.intValue_i64(ty, casted);
2484 var limbs_buffer: [4]usize = undefined;
2485 var big_int = BigIntMutable.init(&limbs_buffer, x);
2486 return pt.intValue_big(ty, big_int.toConst());
2487}
2488
2489pub fn intRef(pt: Zcu.PerThread, ty: Type, x: anytype) Allocator.Error!Air.Inst.Ref {
2490 return Air.internedToRef((try pt.intValue(ty, x)).toIntern());
2491}
2492
2493pub fn intValue_big(pt: Zcu.PerThread, ty: Type, x: BigIntConst) Allocator.Error!Value {
2494 return Value.fromInterned(try pt.intern(.{ .int = .{
2495 .ty = ty.toIntern(),
2496 .storage = .{ .big_int = x },
2497 } }));
2498}
2499
2500pub fn intValue_u64(pt: Zcu.PerThread, ty: Type, x: u64) Allocator.Error!Value {
2501 return Value.fromInterned(try pt.intern(.{ .int = .{
2502 .ty = ty.toIntern(),
2503 .storage = .{ .u64 = x },
2504 } }));
2505}
2506
2507pub fn intValue_i64(pt: Zcu.PerThread, ty: Type, x: i64) Allocator.Error!Value {
2508 return Value.fromInterned(try pt.intern(.{ .int = .{
2509 .ty = ty.toIntern(),
2510 .storage = .{ .i64 = x },
2511 } }));
2512}
2513
2514pub fn unionValue(pt: Zcu.PerThread, union_ty: Type, tag: Value, val: Value) Allocator.Error!Value {
2515 return Value.fromInterned(try pt.intern(.{ .un = .{
2516 .ty = union_ty.toIntern(),
2517 .tag = tag.toIntern(),
2518 .val = val.toIntern(),
2519 } }));
2520}
2521
2522/// This function casts the float representation down to the representation of the type, potentially
2523/// losing data if the representation wasn't correct.
2524pub fn floatValue(pt: Zcu.PerThread, ty: Type, x: anytype) Allocator.Error!Value {
2525 const storage: InternPool.Key.Float.Storage = switch (ty.floatBits(pt.zcu.getTarget())) {
2526 16 => .{ .f16 = @as(f16, @floatCast(x)) },
2527 32 => .{ .f32 = @as(f32, @floatCast(x)) },
2528 64 => .{ .f64 = @as(f64, @floatCast(x)) },
2529 80 => .{ .f80 = @as(f80, @floatCast(x)) },
2530 128 => .{ .f128 = @as(f128, @floatCast(x)) },
2531 else => unreachable,
2532 };
2533 return Value.fromInterned(try pt.intern(.{ .float = .{
2534 .ty = ty.toIntern(),
2535 .storage = storage,
2536 } }));
2537}
2538
2539pub fn nullValue(pt: Zcu.PerThread, opt_ty: Type) Allocator.Error!Value {
2540 assert(pt.zcu.intern_pool.isOptionalType(opt_ty.toIntern()));
2541 return Value.fromInterned(try pt.intern(.{ .opt = .{
2542 .ty = opt_ty.toIntern(),
2543 .val = .none,
2544 } }));
2545}
2546
2547pub fn smallestUnsignedInt(pt: Zcu.PerThread, max: u64) Allocator.Error!Type {
2548 return pt.intType(.unsigned, Type.smallestUnsignedBits(max));
2549}
2550
2551/// Returns the smallest possible integer type containing both `min` and
2552/// `max`. Asserts that neither value is undef.
2553/// TODO: if #3806 is implemented, this becomes trivial
2554pub fn intFittingRange(pt: Zcu.PerThread, min: Value, max: Value) !Type {
2555 const mod = pt.zcu;
2556 assert(!min.isUndef(mod));
2557 assert(!max.isUndef(mod));
2558
2559 if (std.debug.runtime_safety) {
2560 assert(Value.order(min, max, pt).compare(.lte));
2561 }
2562
2563 const sign = min.orderAgainstZero(pt) == .lt;
2564
2565 const min_val_bits = pt.intBitsForValue(min, sign);
2566 const max_val_bits = pt.intBitsForValue(max, sign);
2567
2568 return pt.intType(
2569 if (sign) .signed else .unsigned,
2570 @max(min_val_bits, max_val_bits),
2571 );
2572}
2573
2574/// Given a value representing an integer, returns the number of bits necessary to represent
2575/// this value in an integer. If `sign` is true, returns the number of bits necessary in a
2576/// twos-complement integer; otherwise in an unsigned integer.
2577/// Asserts that `val` is not undef. If `val` is negative, asserts that `sign` is true.
2578pub fn intBitsForValue(pt: Zcu.PerThread, val: Value, sign: bool) u16 {
2579 const mod = pt.zcu;
2580 assert(!val.isUndef(mod));
2581
2582 const key = mod.intern_pool.indexToKey(val.toIntern());
2583 switch (key.int.storage) {
2584 .i64 => |x| {
2585 if (std.math.cast(u64, x)) |casted| return Type.smallestUnsignedBits(casted) + @intFromBool(sign);
2586 assert(sign);
2587 // Protect against overflow in the following negation.
2588 if (x == std.math.minInt(i64)) return 64;
2589 return Type.smallestUnsignedBits(@as(u64, @intCast(-(x + 1)))) + 1;
2590 },
2591 .u64 => |x| {
2592 return Type.smallestUnsignedBits(x) + @intFromBool(sign);
2593 },
2594 .big_int => |big| {
2595 if (big.positive) return @as(u16, @intCast(big.bitCountAbs() + @intFromBool(sign)));
2596
2597 // Zero is still a possibility, in which case unsigned is fine
2598 if (big.eqlZero()) return 0;
2599
2600 return @as(u16, @intCast(big.bitCountTwosComp()));
2601 },
2602 .lazy_align => |lazy_ty| {
2603 return Type.smallestUnsignedBits(Type.fromInterned(lazy_ty).abiAlignment(pt).toByteUnits() orelse 0) + @intFromBool(sign);
2604 },
2605 .lazy_size => |lazy_ty| {
2606 return Type.smallestUnsignedBits(Type.fromInterned(lazy_ty).abiSize(pt)) + @intFromBool(sign);
2607 },
2608 }
2609}
2610
2611pub fn getUnionLayout(pt: Zcu.PerThread, loaded_union: InternPool.LoadedUnionType) Zcu.UnionLayout {
2612 const mod = pt.zcu;
2613 const ip = &mod.intern_pool;
2614 assert(loaded_union.haveLayout(ip));
2615 var most_aligned_field: u32 = undefined;
2616 var most_aligned_field_size: u64 = undefined;
2617 var biggest_field: u32 = undefined;
2618 var payload_size: u64 = 0;
2619 var payload_align: InternPool.Alignment = .@"1";
2620 for (loaded_union.field_types.get(ip), 0..) |field_ty, field_index| {
2621 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(pt)) continue;
2622
2623 const explicit_align = loaded_union.fieldAlign(ip, field_index);
2624 const field_align = if (explicit_align != .none)
2625 explicit_align
2626 else
2627 Type.fromInterned(field_ty).abiAlignment(pt);
2628 const field_size = Type.fromInterned(field_ty).abiSize(pt);
2629 if (field_size > payload_size) {
2630 payload_size = field_size;
2631 biggest_field = @intCast(field_index);
2632 }
2633 if (field_align.compare(.gte, payload_align)) {
2634 payload_align = field_align;
2635 most_aligned_field = @intCast(field_index);
2636 most_aligned_field_size = field_size;
2637 }
2638 }
2639 const have_tag = loaded_union.flagsPtr(ip).runtime_tag.hasTag();
2640 if (!have_tag or !Type.fromInterned(loaded_union.enum_tag_ty).hasRuntimeBits(pt)) {
2641 return .{
2642 .abi_size = payload_align.forward(payload_size),
2643 .abi_align = payload_align,
2644 .most_aligned_field = most_aligned_field,
2645 .most_aligned_field_size = most_aligned_field_size,
2646 .biggest_field = biggest_field,
2647 .payload_size = payload_size,
2648 .payload_align = payload_align,
2649 .tag_align = .none,
2650 .tag_size = 0,
2651 .padding = 0,
2652 };
2653 }
2654
2655 const tag_size = Type.fromInterned(loaded_union.enum_tag_ty).abiSize(pt);
2656 const tag_align = Type.fromInterned(loaded_union.enum_tag_ty).abiAlignment(pt).max(.@"1");
2657 return .{
2658 .abi_size = loaded_union.size(ip).*,
2659 .abi_align = tag_align.max(payload_align),
2660 .most_aligned_field = most_aligned_field,
2661 .most_aligned_field_size = most_aligned_field_size,
2662 .biggest_field = biggest_field,
2663 .payload_size = payload_size,
2664 .payload_align = payload_align,
2665 .tag_align = tag_align,
2666 .tag_size = tag_size,
2667 .padding = loaded_union.padding(ip).*,
2668 };
2669}
2670
2671pub fn unionAbiSize(mod: *Module, loaded_union: InternPool.LoadedUnionType) u64 {
2672 return mod.getUnionLayout(loaded_union).abi_size;
2673}
2674
2675/// Returns 0 if the union is represented with 0 bits at runtime.
2676pub fn unionAbiAlignment(pt: Zcu.PerThread, loaded_union: InternPool.LoadedUnionType) InternPool.Alignment {
2677 const mod = pt.zcu;
2678 const ip = &mod.intern_pool;
2679 const have_tag = loaded_union.flagsPtr(ip).runtime_tag.hasTag();
2680 var max_align: InternPool.Alignment = .none;
2681 if (have_tag) max_align = Type.fromInterned(loaded_union.enum_tag_ty).abiAlignment(pt);
2682 for (loaded_union.field_types.get(ip), 0..) |field_ty, field_index| {
2683 if (!Type.fromInterned(field_ty).hasRuntimeBits(pt)) continue;
2684
2685 const field_align = mod.unionFieldNormalAlignment(loaded_union, @intCast(field_index));
2686 max_align = max_align.max(field_align);
2687 }
2688 return max_align;
2689}
2690
2691/// Returns the field alignment of a non-packed union. Asserts the layout is not packed.
2692pub fn unionFieldNormalAlignment(
2693 pt: Zcu.PerThread,
2694 loaded_union: InternPool.LoadedUnionType,
2695 field_index: u32,
2696) InternPool.Alignment {
2697 return pt.unionFieldNormalAlignmentAdvanced(loaded_union, field_index, .normal) catch unreachable;
2698}
2699
2700/// Returns the field alignment of a non-packed union. Asserts the layout is not packed.
2701/// If `strat` is `.sema`, may perform type resolution.
2702pub fn unionFieldNormalAlignmentAdvanced(
2703 pt: Zcu.PerThread,
2704 loaded_union: InternPool.LoadedUnionType,
2705 field_index: u32,
2706 strat: Type.ResolveStrat,
2707) Zcu.SemaError!InternPool.Alignment {
2708 const ip = &pt.zcu.intern_pool;
2709 assert(loaded_union.flagsPtr(ip).layout != .@"packed");
2710 const field_align = loaded_union.fieldAlign(ip, field_index);
2711 if (field_align != .none) return field_align;
2712 const field_ty = Type.fromInterned(loaded_union.field_types.get(ip)[field_index]);
2713 if (field_ty.isNoReturn(pt.zcu)) return .none;
2714 return (try field_ty.abiAlignmentAdvanced(pt, strat.toLazy())).scalar;
2715}
2716
2717/// Returns the field alignment of a non-packed struct. Asserts the layout is not packed.
2718pub fn structFieldAlignment(
2719 pt: Zcu.PerThread,
2720 explicit_alignment: InternPool.Alignment,
2721 field_ty: Type,
2722 layout: std.builtin.Type.ContainerLayout,
2723) InternPool.Alignment {
2724 return pt.structFieldAlignmentAdvanced(explicit_alignment, field_ty, layout, .normal) catch unreachable;
2725}
2726
2727/// Returns the field alignment of a non-packed struct. Asserts the layout is not packed.
2728/// If `strat` is `.sema`, may perform type resolution.
2729pub fn structFieldAlignmentAdvanced(
2730 pt: Zcu.PerThread,
2731 explicit_alignment: InternPool.Alignment,
2732 field_ty: Type,
2733 layout: std.builtin.Type.ContainerLayout,
2734 strat: Type.ResolveStrat,
2735) Zcu.SemaError!InternPool.Alignment {
2736 assert(layout != .@"packed");
2737 if (explicit_alignment != .none) return explicit_alignment;
2738 const ty_abi_align = (try field_ty.abiAlignmentAdvanced(pt, strat.toLazy())).scalar;
2739 switch (layout) {
2740 .@"packed" => unreachable,
2741 .auto => if (pt.zcu.getTarget().ofmt != .c) return ty_abi_align,
2742 .@"extern" => {},
2743 }
2744 // extern
2745 if (field_ty.isAbiInt(pt.zcu) and field_ty.intInfo(pt.zcu).bits >= 128) {
2746 return ty_abi_align.maxStrict(.@"16");
2747 }
2748 return ty_abi_align;
2749}
2750
2751/// https://github.com/ziglang/zig/issues/17178 explored storing these bit offsets
2752/// into the packed struct InternPool data rather than computing this on the
2753/// fly, however it was found to perform worse when measured on real world
2754/// projects.
2755pub fn structPackedFieldBitOffset(
2756 pt: Zcu.PerThread,
2757 struct_type: InternPool.LoadedStructType,
2758 field_index: u32,
2759) u16 {
2760 const mod = pt.zcu;
2761 const ip = &mod.intern_pool;
2762 assert(struct_type.layout == .@"packed");
2763 assert(struct_type.haveLayout(ip));
2764 var bit_sum: u64 = 0;
2765 for (0..struct_type.field_types.len) |i| {
2766 if (i == field_index) {
2767 return @intCast(bit_sum);
2768 }
2769 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
2770 bit_sum += field_ty.bitSize(pt);
2771 }
2772 unreachable; // index out of bounds
2773}
2774
2775pub fn getBuiltin(pt: Zcu.PerThread, name: []const u8) Allocator.Error!Air.Inst.Ref {
2776 const decl_index = try pt.getBuiltinDecl(name);
2777 pt.ensureDeclAnalyzed(decl_index) catch @panic("std.builtin is corrupt");
2778 return Air.internedToRef(pt.zcu.declPtr(decl_index).val.toIntern());
2779}
2780
2781pub fn getBuiltinDecl(pt: Zcu.PerThread, name: []const u8) Allocator.Error!InternPool.DeclIndex {
2782 const zcu = pt.zcu;
2783 const gpa = zcu.gpa;
2784 const ip = &zcu.intern_pool;
2785 const std_file_imported = zcu.importPkg(zcu.std_mod) catch @panic("failed to import lib/std.zig");
2786 const std_file_root_decl = zcu.fileRootDecl(std_file_imported.file_index).unwrap().?;
2787 const std_namespace = zcu.declPtr(std_file_root_decl).getOwnedInnerNamespace(zcu).?;
2788 const builtin_str = try ip.getOrPutString(gpa, pt.tid, "builtin", .no_embedded_nulls);
2789 const builtin_decl = std_namespace.decls.getKeyAdapted(builtin_str, Zcu.DeclAdapter{ .zcu = zcu }) orelse @panic("lib/std.zig is corrupt and missing 'builtin'");
2790 pt.ensureDeclAnalyzed(builtin_decl) catch @panic("std.builtin is corrupt");
2791 const builtin_namespace = zcu.declPtr(builtin_decl).getInnerNamespace(zcu) orelse @panic("std.builtin is corrupt");
2792 const name_str = try ip.getOrPutString(gpa, pt.tid, name, .no_embedded_nulls);
2793 return builtin_namespace.decls.getKeyAdapted(name_str, Zcu.DeclAdapter{ .zcu = zcu }) orelse @panic("lib/std/builtin.zig is corrupt");
2794}
2795
2796pub fn getBuiltinType(pt: Zcu.PerThread, name: []const u8) Allocator.Error!Type {
2797 const ty_inst = try pt.getBuiltin(name);
2798 const ty = Type.fromInterned(ty_inst.toInterned() orelse @panic("std.builtin is corrupt"));
2799 ty.resolveFully(pt) catch @panic("std.builtin is corrupt");
2800 return ty;
2801}
2802
2803const Air = @import("../Air.zig");
2804const Allocator = std.mem.Allocator;
2805const assert = std.debug.assert;
2806const Ast = std.zig.Ast;
2807const AstGen = std.zig.AstGen;
2808const BigIntConst = std.math.big.int.Const;
2809const BigIntMutable = std.math.big.int.Mutable;
2810const build_options = @import("build_options");
2811const builtin = @import("builtin");
2812const Cache = std.Build.Cache;
2813const InternPool = @import("../InternPool.zig");
2814const isUpDir = @import("../introspect.zig").isUpDir;
2815const Liveness = @import("../Liveness.zig");
2816const log = std.log.scoped(.zcu);
2817const Module = @import("../Package.zig").Module;
2818const Sema = @import("../Sema.zig");
2819const std = @import("std");
2820const target_util = @import("../target.zig");
2821const trace = @import("../tracy.zig").trace;
2822const Type = @import("../Type.zig");
2823const Value = @import("../Value.zig");
2824const Zcu = @import("../Zcu.zig");
2825const Zir = std.zig.Zir;
src/arch/aarch64/CodeGen.zig+220-163
......@@ -12,11 +12,9 @@ const Type = @import("../../Type.zig");
1212const Value = @import("../../Value.zig");
1313const link = @import("../../link.zig");
1414const Zcu = @import("../../Zcu.zig");
15/// Deprecated.
16const Module = Zcu;
1715const InternPool = @import("../../InternPool.zig");
1816const Compilation = @import("../../Compilation.zig");
19const ErrorMsg = Module.ErrorMsg;
17const ErrorMsg = Zcu.ErrorMsg;
2018const Target = std.Target;
2119const Allocator = mem.Allocator;
2220const trace = @import("../../tracy.zig").trace;
......@@ -47,6 +45,7 @@ const gp = abi.RegisterClass.gp;
4745const InnerError = CodeGenError || error{OutOfRegisters};
4846
4947gpa: Allocator,
48pt: Zcu.PerThread,
5049air: Air,
5150liveness: Liveness,
5251bin_file: *link.File,
......@@ -59,7 +58,7 @@ args: []MCValue,
5958ret_mcv: MCValue,
6059fn_type: Type,
6160arg_index: u32,
62src_loc: Module.LazySrcLoc,
61src_loc: Zcu.LazySrcLoc,
6362stack_align: u32,
6463
6564/// MIR Instructions
......@@ -331,15 +330,16 @@ const Self = @This();
331330
332331pub fn generate(
333332 lf: *link.File,
334 src_loc: Module.LazySrcLoc,
333 pt: Zcu.PerThread,
334 src_loc: Zcu.LazySrcLoc,
335335 func_index: InternPool.Index,
336336 air: Air,
337337 liveness: Liveness,
338338 code: *std.ArrayList(u8),
339339 debug_output: DebugInfoOutput,
340340) CodeGenError!Result {
341 const gpa = lf.comp.gpa;
342 const zcu = lf.comp.module.?;
341 const zcu = pt.zcu;
342 const gpa = zcu.gpa;
343343 const func = zcu.funcInfo(func_index);
344344 const fn_owner_decl = zcu.declPtr(func.owner_decl);
345345 assert(fn_owner_decl.has_tv);
......@@ -355,8 +355,9 @@ pub fn generate(
355355 }
356356 try branch_stack.append(.{});
357357
358 var function = Self{
358 var function: Self = .{
359359 .gpa = gpa,
360 .pt = pt,
360361 .air = air,
361362 .liveness = liveness,
362363 .debug_output = debug_output,
......@@ -476,7 +477,8 @@ pub fn addExtraAssumeCapacity(self: *Self, extra: anytype) u32 {
476477}
477478
478479fn gen(self: *Self) !void {
479 const mod = self.bin_file.comp.module.?;
480 const pt = self.pt;
481 const mod = pt.zcu;
480482 const cc = self.fn_type.fnCallingConvention(mod);
481483 if (cc != .Naked) {
482484 // stp fp, lr, [sp, #-16]!
......@@ -526,8 +528,8 @@ fn gen(self: *Self) !void {
526528
527529 const ty = self.typeOfIndex(inst);
528530
529 const abi_size = @as(u32, @intCast(ty.abiSize(mod)));
530 const abi_align = ty.abiAlignment(mod);
531 const abi_size = @as(u32, @intCast(ty.abiSize(pt)));
532 const abi_align = ty.abiAlignment(pt);
531533 const stack_offset = try self.allocMem(abi_size, abi_align, inst);
532534 try self.genSetStack(ty, stack_offset, MCValue{ .register = reg });
533535
......@@ -656,7 +658,8 @@ fn gen(self: *Self) !void {
656658}
657659
658660fn genBody(self: *Self, body: []const Air.Inst.Index) InnerError!void {
659 const mod = self.bin_file.comp.module.?;
661 const pt = self.pt;
662 const mod = pt.zcu;
660663 const ip = &mod.intern_pool;
661664 const air_tags = self.air.instructions.items(.tag);
662665
......@@ -1022,31 +1025,32 @@ fn allocMem(
10221025
10231026/// Use a pointer instruction as the basis for allocating stack memory.
10241027fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !u32 {
1025 const mod = self.bin_file.comp.module.?;
1028 const pt = self.pt;
1029 const mod = pt.zcu;
10261030 const elem_ty = self.typeOfIndex(inst).childType(mod);
10271031
1028 if (!elem_ty.hasRuntimeBits(mod)) {
1032 if (!elem_ty.hasRuntimeBits(pt)) {
10291033 // return the stack offset 0. Stack offset 0 will be where all
10301034 // zero-sized stack allocations live as non-zero-sized
10311035 // allocations will always have an offset > 0.
10321036 return @as(u32, 0);
10331037 }
10341038
1035 const abi_size = math.cast(u32, elem_ty.abiSize(mod)) orelse {
1036 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
1039 const abi_size = math.cast(u32, elem_ty.abiSize(pt)) orelse {
1040 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(pt)});
10371041 };
10381042 // TODO swap this for inst.ty.ptrAlign
1039 const abi_align = elem_ty.abiAlignment(mod);
1043 const abi_align = elem_ty.abiAlignment(pt);
10401044
10411045 return self.allocMem(abi_size, abi_align, inst);
10421046}
10431047
10441048fn allocRegOrMem(self: *Self, elem_ty: Type, reg_ok: bool, maybe_inst: ?Air.Inst.Index) !MCValue {
1045 const mod = self.bin_file.comp.module.?;
1046 const abi_size = math.cast(u32, elem_ty.abiSize(mod)) orelse {
1047 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
1049 const pt = self.pt;
1050 const abi_size = math.cast(u32, elem_ty.abiSize(pt)) orelse {
1051 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(pt)});
10481052 };
1049 const abi_align = elem_ty.abiAlignment(mod);
1053 const abi_align = elem_ty.abiAlignment(pt);
10501054
10511055 if (reg_ok) {
10521056 // Make sure the type can fit in a register before we try to allocate one.
......@@ -1133,14 +1137,15 @@ fn airAlloc(self: *Self, inst: Air.Inst.Index) !void {
11331137}
11341138
11351139fn airRetPtr(self: *Self, inst: Air.Inst.Index) !void {
1136 const mod = self.bin_file.comp.module.?;
1140 const pt = self.pt;
1141 const mod = pt.zcu;
11371142 const result: MCValue = switch (self.ret_mcv) {
11381143 .none, .register => .{ .ptr_stack_offset = try self.allocMemPtr(inst) },
11391144 .stack_offset => blk: {
11401145 // self.ret_mcv is an address to where this function
11411146 // should store its result into
11421147 const ret_ty = self.fn_type.fnReturnType(mod);
1143 const ptr_ty = try mod.singleMutPtrType(ret_ty);
1148 const ptr_ty = try pt.singleMutPtrType(ret_ty);
11441149
11451150 // addr_reg will contain the address of where to store the
11461151 // result into
......@@ -1170,7 +1175,8 @@ fn airIntCast(self: *Self, inst: Air.Inst.Index) !void {
11701175 if (self.liveness.isUnused(inst))
11711176 return self.finishAir(inst, .dead, .{ ty_op.operand, .none, .none });
11721177
1173 const mod = self.bin_file.comp.module.?;
1178 const pt = self.pt;
1179 const mod = pt.zcu;
11741180 const operand = ty_op.operand;
11751181 const operand_mcv = try self.resolveInst(operand);
11761182 const operand_ty = self.typeOf(operand);
......@@ -1251,7 +1257,8 @@ fn trunc(
12511257 operand_ty: Type,
12521258 dest_ty: Type,
12531259) !MCValue {
1254 const mod = self.bin_file.comp.module.?;
1260 const pt = self.pt;
1261 const mod = pt.zcu;
12551262 const info_a = operand_ty.intInfo(mod);
12561263 const info_b = dest_ty.intInfo(mod);
12571264
......@@ -1314,7 +1321,8 @@ fn airIntFromBool(self: *Self, inst: Air.Inst.Index) !void {
13141321
13151322fn airNot(self: *Self, inst: Air.Inst.Index) !void {
13161323 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
1317 const mod = self.bin_file.comp.module.?;
1324 const pt = self.pt;
1325 const mod = pt.zcu;
13181326 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
13191327 const operand = try self.resolveInst(ty_op.operand);
13201328 const operand_ty = self.typeOf(ty_op.operand);
......@@ -1409,7 +1417,8 @@ fn minMax(
14091417 rhs_ty: Type,
14101418 maybe_inst: ?Air.Inst.Index,
14111419) !MCValue {
1412 const mod = self.bin_file.comp.module.?;
1420 const pt = self.pt;
1421 const mod = pt.zcu;
14131422 switch (lhs_ty.zigTypeTag(mod)) {
14141423 .Float => return self.fail("TODO ARM min/max on floats", .{}),
14151424 .Vector => return self.fail("TODO ARM min/max on vectors", .{}),
......@@ -1899,7 +1908,8 @@ fn addSub(
18991908 rhs_ty: Type,
19001909 maybe_inst: ?Air.Inst.Index,
19011910) InnerError!MCValue {
1902 const mod = self.bin_file.comp.module.?;
1911 const pt = self.pt;
1912 const mod = pt.zcu;
19031913 switch (lhs_ty.zigTypeTag(mod)) {
19041914 .Float => return self.fail("TODO binary operations on floats", .{}),
19051915 .Vector => return self.fail("TODO binary operations on vectors", .{}),
......@@ -1960,7 +1970,8 @@ fn mul(
19601970 rhs_ty: Type,
19611971 maybe_inst: ?Air.Inst.Index,
19621972) InnerError!MCValue {
1963 const mod = self.bin_file.comp.module.?;
1973 const pt = self.pt;
1974 const mod = pt.zcu;
19641975 switch (lhs_ty.zigTypeTag(mod)) {
19651976 .Vector => return self.fail("TODO binary operations on vectors", .{}),
19661977 .Int => {
......@@ -1992,7 +2003,8 @@ fn divFloat(
19922003 _ = rhs_ty;
19932004 _ = maybe_inst;
19942005
1995 const mod = self.bin_file.comp.module.?;
2006 const pt = self.pt;
2007 const mod = pt.zcu;
19962008 switch (lhs_ty.zigTypeTag(mod)) {
19972009 .Float => return self.fail("TODO div_float", .{}),
19982010 .Vector => return self.fail("TODO div_float on vectors", .{}),
......@@ -2008,7 +2020,8 @@ fn divTrunc(
20082020 rhs_ty: Type,
20092021 maybe_inst: ?Air.Inst.Index,
20102022) InnerError!MCValue {
2011 const mod = self.bin_file.comp.module.?;
2023 const pt = self.pt;
2024 const mod = pt.zcu;
20122025 switch (lhs_ty.zigTypeTag(mod)) {
20132026 .Float => return self.fail("TODO div on floats", .{}),
20142027 .Vector => return self.fail("TODO div on vectors", .{}),
......@@ -2042,7 +2055,8 @@ fn divFloor(
20422055 rhs_ty: Type,
20432056 maybe_inst: ?Air.Inst.Index,
20442057) InnerError!MCValue {
2045 const mod = self.bin_file.comp.module.?;
2058 const pt = self.pt;
2059 const mod = pt.zcu;
20462060 switch (lhs_ty.zigTypeTag(mod)) {
20472061 .Float => return self.fail("TODO div on floats", .{}),
20482062 .Vector => return self.fail("TODO div on vectors", .{}),
......@@ -2075,7 +2089,8 @@ fn divExact(
20752089 rhs_ty: Type,
20762090 maybe_inst: ?Air.Inst.Index,
20772091) InnerError!MCValue {
2078 const mod = self.bin_file.comp.module.?;
2092 const pt = self.pt;
2093 const mod = pt.zcu;
20792094 switch (lhs_ty.zigTypeTag(mod)) {
20802095 .Float => return self.fail("TODO div on floats", .{}),
20812096 .Vector => return self.fail("TODO div on vectors", .{}),
......@@ -2111,7 +2126,8 @@ fn rem(
21112126) InnerError!MCValue {
21122127 _ = maybe_inst;
21132128
2114 const mod = self.bin_file.comp.module.?;
2129 const pt = self.pt;
2130 const mod = pt.zcu;
21152131 switch (lhs_ty.zigTypeTag(mod)) {
21162132 .Float => return self.fail("TODO rem/mod on floats", .{}),
21172133 .Vector => return self.fail("TODO rem/mod on vectors", .{}),
......@@ -2182,7 +2198,8 @@ fn modulo(
21822198 _ = rhs_ty;
21832199 _ = maybe_inst;
21842200
2185 const mod = self.bin_file.comp.module.?;
2201 const pt = self.pt;
2202 const mod = pt.zcu;
21862203 switch (lhs_ty.zigTypeTag(mod)) {
21872204 .Float => return self.fail("TODO mod on floats", .{}),
21882205 .Vector => return self.fail("TODO mod on vectors", .{}),
......@@ -2200,7 +2217,8 @@ fn wrappingArithmetic(
22002217 rhs_ty: Type,
22012218 maybe_inst: ?Air.Inst.Index,
22022219) InnerError!MCValue {
2203 const mod = self.bin_file.comp.module.?;
2220 const pt = self.pt;
2221 const mod = pt.zcu;
22042222 switch (lhs_ty.zigTypeTag(mod)) {
22052223 .Vector => return self.fail("TODO binary operations on vectors", .{}),
22062224 .Int => {
......@@ -2235,7 +2253,8 @@ fn bitwise(
22352253 rhs_ty: Type,
22362254 maybe_inst: ?Air.Inst.Index,
22372255) InnerError!MCValue {
2238 const mod = self.bin_file.comp.module.?;
2256 const pt = self.pt;
2257 const mod = pt.zcu;
22392258 switch (lhs_ty.zigTypeTag(mod)) {
22402259 .Vector => return self.fail("TODO binary operations on vectors", .{}),
22412260 .Int => {
......@@ -2270,7 +2289,8 @@ fn shiftExact(
22702289) InnerError!MCValue {
22712290 _ = rhs_ty;
22722291
2273 const mod = self.bin_file.comp.module.?;
2292 const pt = self.pt;
2293 const mod = pt.zcu;
22742294 switch (lhs_ty.zigTypeTag(mod)) {
22752295 .Vector => return self.fail("TODO binary operations on vectors", .{}),
22762296 .Int => {
......@@ -2320,7 +2340,8 @@ fn shiftNormal(
23202340 rhs_ty: Type,
23212341 maybe_inst: ?Air.Inst.Index,
23222342) InnerError!MCValue {
2323 const mod = self.bin_file.comp.module.?;
2343 const pt = self.pt;
2344 const mod = pt.zcu;
23242345 switch (lhs_ty.zigTypeTag(mod)) {
23252346 .Vector => return self.fail("TODO binary operations on vectors", .{}),
23262347 .Int => {
......@@ -2360,7 +2381,8 @@ fn booleanOp(
23602381 rhs_ty: Type,
23612382 maybe_inst: ?Air.Inst.Index,
23622383) InnerError!MCValue {
2363 const mod = self.bin_file.comp.module.?;
2384 const pt = self.pt;
2385 const mod = pt.zcu;
23642386 switch (lhs_ty.zigTypeTag(mod)) {
23652387 .Bool => {
23662388 assert((try lhs_bind.resolveToImmediate(self)) == null); // should have been handled by Sema
......@@ -2387,7 +2409,8 @@ fn ptrArithmetic(
23872409 rhs_ty: Type,
23882410 maybe_inst: ?Air.Inst.Index,
23892411) InnerError!MCValue {
2390 const mod = self.bin_file.comp.module.?;
2412 const pt = self.pt;
2413 const mod = pt.zcu;
23912414 switch (lhs_ty.zigTypeTag(mod)) {
23922415 .Pointer => {
23932416 assert(rhs_ty.eql(Type.usize, mod));
......@@ -2397,7 +2420,7 @@ fn ptrArithmetic(
23972420 .One => ptr_ty.childType(mod).childType(mod), // ptr to array, so get array element type
23982421 else => ptr_ty.childType(mod),
23992422 };
2400 const elem_size = elem_ty.abiSize(mod);
2423 const elem_size = elem_ty.abiSize(pt);
24012424
24022425 const base_tag: Air.Inst.Tag = switch (tag) {
24032426 .ptr_add => .add,
......@@ -2510,7 +2533,8 @@ fn airOverflow(self: *Self, inst: Air.Inst.Index) !void {
25102533 const tag = self.air.instructions.items(.tag)[@intFromEnum(inst)];
25112534 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
25122535 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
2513 const mod = self.bin_file.comp.module.?;
2536 const pt = self.pt;
2537 const mod = pt.zcu;
25142538 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
25152539 const lhs_bind: ReadArg.Bind = .{ .inst = extra.lhs };
25162540 const rhs_bind: ReadArg.Bind = .{ .inst = extra.rhs };
......@@ -2518,9 +2542,9 @@ fn airOverflow(self: *Self, inst: Air.Inst.Index) !void {
25182542 const rhs_ty = self.typeOf(extra.rhs);
25192543
25202544 const tuple_ty = self.typeOfIndex(inst);
2521 const tuple_size = @as(u32, @intCast(tuple_ty.abiSize(mod)));
2522 const tuple_align = tuple_ty.abiAlignment(mod);
2523 const overflow_bit_offset = @as(u32, @intCast(tuple_ty.structFieldOffset(1, mod)));
2545 const tuple_size = @as(u32, @intCast(tuple_ty.abiSize(pt)));
2546 const tuple_align = tuple_ty.abiAlignment(pt);
2547 const overflow_bit_offset = @as(u32, @intCast(tuple_ty.structFieldOffset(1, pt)));
25242548
25252549 switch (lhs_ty.zigTypeTag(mod)) {
25262550 .Vector => return self.fail("TODO implement add_with_overflow/sub_with_overflow for vectors", .{}),
......@@ -2638,7 +2662,8 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
26382662 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
26392663 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
26402664 if (self.liveness.isUnused(inst)) return self.finishAir(inst, .dead, .{ extra.lhs, extra.rhs, .none });
2641 const mod = self.bin_file.comp.module.?;
2665 const pt = self.pt;
2666 const mod = pt.zcu;
26422667 const result: MCValue = result: {
26432668 const lhs_bind: ReadArg.Bind = .{ .inst = extra.lhs };
26442669 const rhs_bind: ReadArg.Bind = .{ .inst = extra.rhs };
......@@ -2646,9 +2671,9 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
26462671 const rhs_ty = self.typeOf(extra.rhs);
26472672
26482673 const tuple_ty = self.typeOfIndex(inst);
2649 const tuple_size = @as(u32, @intCast(tuple_ty.abiSize(mod)));
2650 const tuple_align = tuple_ty.abiAlignment(mod);
2651 const overflow_bit_offset = @as(u32, @intCast(tuple_ty.structFieldOffset(1, mod)));
2674 const tuple_size = @as(u32, @intCast(tuple_ty.abiSize(pt)));
2675 const tuple_align = tuple_ty.abiAlignment(pt);
2676 const overflow_bit_offset = @as(u32, @intCast(tuple_ty.structFieldOffset(1, pt)));
26522677
26532678 switch (lhs_ty.zigTypeTag(mod)) {
26542679 .Vector => return self.fail("TODO implement mul_with_overflow for vectors", .{}),
......@@ -2862,7 +2887,8 @@ fn airShlWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
28622887 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
28632888 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
28642889 if (self.liveness.isUnused(inst)) return self.finishAir(inst, .dead, .{ extra.lhs, extra.rhs, .none });
2865 const mod = self.bin_file.comp.module.?;
2890 const pt = self.pt;
2891 const mod = pt.zcu;
28662892 const result: MCValue = result: {
28672893 const lhs_bind: ReadArg.Bind = .{ .inst = extra.lhs };
28682894 const rhs_bind: ReadArg.Bind = .{ .inst = extra.rhs };
......@@ -2870,9 +2896,9 @@ fn airShlWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
28702896 const rhs_ty = self.typeOf(extra.rhs);
28712897
28722898 const tuple_ty = self.typeOfIndex(inst);
2873 const tuple_size = @as(u32, @intCast(tuple_ty.abiSize(mod)));
2874 const tuple_align = tuple_ty.abiAlignment(mod);
2875 const overflow_bit_offset = @as(u32, @intCast(tuple_ty.structFieldOffset(1, mod)));
2899 const tuple_size = @as(u32, @intCast(tuple_ty.abiSize(pt)));
2900 const tuple_align = tuple_ty.abiAlignment(pt);
2901 const overflow_bit_offset = @as(u32, @intCast(tuple_ty.structFieldOffset(1, pt)));
28762902
28772903 switch (lhs_ty.zigTypeTag(mod)) {
28782904 .Vector => return self.fail("TODO implement shl_with_overflow for vectors", .{}),
......@@ -3010,9 +3036,10 @@ fn airOptionalPayload(self: *Self, inst: Air.Inst.Index) !void {
30103036}
30113037
30123038fn optionalPayload(self: *Self, inst: Air.Inst.Index, mcv: MCValue, optional_ty: Type) !MCValue {
3013 const mod = self.bin_file.comp.module.?;
3039 const pt = self.pt;
3040 const mod = pt.zcu;
30143041 const payload_ty = optional_ty.optionalChild(mod);
3015 if (!payload_ty.hasRuntimeBits(mod)) return MCValue.none;
3042 if (!payload_ty.hasRuntimeBits(pt)) return MCValue.none;
30163043 if (optional_ty.isPtrLikeOptional(mod)) {
30173044 // TODO should we reuse the operand here?
30183045 const raw_reg = try self.register_manager.allocReg(inst, gp);
......@@ -3054,17 +3081,18 @@ fn errUnionErr(
30543081 error_union_ty: Type,
30553082 maybe_inst: ?Air.Inst.Index,
30563083) !MCValue {
3057 const mod = self.bin_file.comp.module.?;
3084 const pt = self.pt;
3085 const mod = pt.zcu;
30583086 const err_ty = error_union_ty.errorUnionSet(mod);
30593087 const payload_ty = error_union_ty.errorUnionPayload(mod);
30603088 if (err_ty.errorSetIsEmpty(mod)) {
30613089 return MCValue{ .immediate = 0 };
30623090 }
3063 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
3091 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
30643092 return try error_union_bind.resolveToMcv(self);
30653093 }
30663094
3067 const err_offset = @as(u32, @intCast(errUnionErrorOffset(payload_ty, mod)));
3095 const err_offset: u32 = @intCast(errUnionErrorOffset(payload_ty, pt));
30683096 switch (try error_union_bind.resolveToMcv(self)) {
30693097 .register => {
30703098 var operand_reg: Register = undefined;
......@@ -3086,7 +3114,7 @@ fn errUnionErr(
30863114 );
30873115
30883116 const err_bit_offset = err_offset * 8;
3089 const err_bit_size = @as(u32, @intCast(err_ty.abiSize(mod))) * 8;
3117 const err_bit_size = @as(u32, @intCast(err_ty.abiSize(pt))) * 8;
30903118
30913119 _ = try self.addInst(.{
30923120 .tag = .ubfx, // errors are unsigned integers
......@@ -3134,17 +3162,18 @@ fn errUnionPayload(
31343162 error_union_ty: Type,
31353163 maybe_inst: ?Air.Inst.Index,
31363164) !MCValue {
3137 const mod = self.bin_file.comp.module.?;
3165 const pt = self.pt;
3166 const mod = pt.zcu;
31383167 const err_ty = error_union_ty.errorUnionSet(mod);
31393168 const payload_ty = error_union_ty.errorUnionPayload(mod);
31403169 if (err_ty.errorSetIsEmpty(mod)) {
31413170 return try error_union_bind.resolveToMcv(self);
31423171 }
3143 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
3172 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
31443173 return MCValue.none;
31453174 }
31463175
3147 const payload_offset = @as(u32, @intCast(errUnionPayloadOffset(payload_ty, mod)));
3176 const payload_offset = @as(u32, @intCast(errUnionPayloadOffset(payload_ty, pt)));
31483177 switch (try error_union_bind.resolveToMcv(self)) {
31493178 .register => {
31503179 var operand_reg: Register = undefined;
......@@ -3166,7 +3195,7 @@ fn errUnionPayload(
31663195 );
31673196
31683197 const payload_bit_offset = payload_offset * 8;
3169 const payload_bit_size = @as(u32, @intCast(payload_ty.abiSize(mod))) * 8;
3198 const payload_bit_size = @as(u32, @intCast(payload_ty.abiSize(pt))) * 8;
31703199
31713200 _ = try self.addInst(.{
31723201 .tag = if (payload_ty.isSignedInt(mod)) Mir.Inst.Tag.sbfx else .ubfx,
......@@ -3246,7 +3275,8 @@ fn airSaveErrReturnTraceIndex(self: *Self, inst: Air.Inst.Index) !void {
32463275}
32473276
32483277fn airWrapOptional(self: *Self, inst: Air.Inst.Index) !void {
3249 const mod = self.bin_file.comp.module.?;
3278 const pt = self.pt;
3279 const mod = pt.zcu;
32503280 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
32513281
32523282 if (self.liveness.isUnused(inst)) {
......@@ -3255,7 +3285,7 @@ fn airWrapOptional(self: *Self, inst: Air.Inst.Index) !void {
32553285
32563286 const result: MCValue = result: {
32573287 const payload_ty = self.typeOf(ty_op.operand);
3258 if (!payload_ty.hasRuntimeBits(mod)) {
3288 if (!payload_ty.hasRuntimeBits(pt)) {
32593289 break :result MCValue{ .immediate = 1 };
32603290 }
32613291
......@@ -3275,9 +3305,9 @@ fn airWrapOptional(self: *Self, inst: Air.Inst.Index) !void {
32753305 break :result MCValue{ .register = reg };
32763306 }
32773307
3278 const optional_abi_size: u32 = @intCast(optional_ty.abiSize(mod));
3279 const optional_abi_align = optional_ty.abiAlignment(mod);
3280 const offset: u32 = @intCast(payload_ty.abiSize(mod));
3308 const optional_abi_size: u32 = @intCast(optional_ty.abiSize(pt));
3309 const optional_abi_align = optional_ty.abiAlignment(pt);
3310 const offset: u32 = @intCast(payload_ty.abiSize(pt));
32813311
32823312 const stack_offset = try self.allocMem(optional_abi_size, optional_abi_align, inst);
32833313 try self.genSetStack(payload_ty, stack_offset, operand);
......@@ -3291,20 +3321,21 @@ fn airWrapOptional(self: *Self, inst: Air.Inst.Index) !void {
32913321
32923322/// T to E!T
32933323fn airWrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) !void {
3294 const mod = self.bin_file.comp.module.?;
3324 const pt = self.pt;
3325 const mod = pt.zcu;
32953326 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
32963327 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
32973328 const error_union_ty = ty_op.ty.toType();
32983329 const error_ty = error_union_ty.errorUnionSet(mod);
32993330 const payload_ty = error_union_ty.errorUnionPayload(mod);
33003331 const operand = try self.resolveInst(ty_op.operand);
3301 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result operand;
3332 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result operand;
33023333
3303 const abi_size = @as(u32, @intCast(error_union_ty.abiSize(mod)));
3304 const abi_align = error_union_ty.abiAlignment(mod);
3334 const abi_size = @as(u32, @intCast(error_union_ty.abiSize(pt)));
3335 const abi_align = error_union_ty.abiAlignment(pt);
33053336 const stack_offset = try self.allocMem(abi_size, abi_align, inst);
3306 const payload_off = errUnionPayloadOffset(payload_ty, mod);
3307 const err_off = errUnionErrorOffset(payload_ty, mod);
3337 const payload_off = errUnionPayloadOffset(payload_ty, pt);
3338 const err_off = errUnionErrorOffset(payload_ty, pt);
33083339 try self.genSetStack(payload_ty, stack_offset - @as(u32, @intCast(payload_off)), operand);
33093340 try self.genSetStack(error_ty, stack_offset - @as(u32, @intCast(err_off)), .{ .immediate = 0 });
33103341
......@@ -3317,18 +3348,19 @@ fn airWrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) !void {
33173348fn airWrapErrUnionErr(self: *Self, inst: Air.Inst.Index) !void {
33183349 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
33193350 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
3320 const mod = self.bin_file.comp.module.?;
3351 const pt = self.pt;
3352 const mod = pt.zcu;
33213353 const error_union_ty = ty_op.ty.toType();
33223354 const error_ty = error_union_ty.errorUnionSet(mod);
33233355 const payload_ty = error_union_ty.errorUnionPayload(mod);
33243356 const operand = try self.resolveInst(ty_op.operand);
3325 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result operand;
3357 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result operand;
33263358
3327 const abi_size = @as(u32, @intCast(error_union_ty.abiSize(mod)));
3328 const abi_align = error_union_ty.abiAlignment(mod);
3359 const abi_size = @as(u32, @intCast(error_union_ty.abiSize(pt)));
3360 const abi_align = error_union_ty.abiAlignment(pt);
33293361 const stack_offset = try self.allocMem(abi_size, abi_align, inst);
3330 const payload_off = errUnionPayloadOffset(payload_ty, mod);
3331 const err_off = errUnionErrorOffset(payload_ty, mod);
3362 const payload_off = errUnionPayloadOffset(payload_ty, pt);
3363 const err_off = errUnionErrorOffset(payload_ty, pt);
33323364 try self.genSetStack(error_ty, stack_offset - @as(u32, @intCast(err_off)), operand);
33333365 try self.genSetStack(payload_ty, stack_offset - @as(u32, @intCast(payload_off)), .undef);
33343366
......@@ -3420,7 +3452,8 @@ fn airPtrSlicePtrPtr(self: *Self, inst: Air.Inst.Index) !void {
34203452}
34213453
34223454fn airSliceElemVal(self: *Self, inst: Air.Inst.Index) !void {
3423 const mod = self.bin_file.comp.module.?;
3455 const pt = self.pt;
3456 const mod = pt.zcu;
34243457 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
34253458 const slice_ty = self.typeOf(bin_op.lhs);
34263459 const result: MCValue = if (!slice_ty.isVolatilePtr(mod) and self.liveness.isUnused(inst)) .dead else result: {
......@@ -3444,9 +3477,10 @@ fn ptrElemVal(
34443477 ptr_ty: Type,
34453478 maybe_inst: ?Air.Inst.Index,
34463479) !MCValue {
3447 const mod = self.bin_file.comp.module.?;
3480 const pt = self.pt;
3481 const mod = pt.zcu;
34483482 const elem_ty = ptr_ty.childType(mod);
3449 const elem_size = @as(u32, @intCast(elem_ty.abiSize(mod)));
3483 const elem_size = @as(u32, @intCast(elem_ty.abiSize(pt)));
34503484
34513485 // TODO optimize for elem_sizes of 1, 2, 4, 8
34523486 switch (elem_size) {
......@@ -3486,7 +3520,8 @@ fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
34863520}
34873521
34883522fn airPtrElemVal(self: *Self, inst: Air.Inst.Index) !void {
3489 const mod = self.bin_file.comp.module.?;
3523 const pt = self.pt;
3524 const mod = pt.zcu;
34903525 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
34913526 const ptr_ty = self.typeOf(bin_op.lhs);
34923527 const result: MCValue = if (!ptr_ty.isVolatilePtr(mod) and self.liveness.isUnused(inst)) .dead else result: {
......@@ -3609,9 +3644,10 @@ fn reuseOperand(
36093644}
36103645
36113646fn load(self: *Self, dst_mcv: MCValue, ptr: MCValue, ptr_ty: Type) InnerError!void {
3612 const mod = self.bin_file.comp.module.?;
3647 const pt = self.pt;
3648 const mod = pt.zcu;
36133649 const elem_ty = ptr_ty.childType(mod);
3614 const elem_size = elem_ty.abiSize(mod);
3650 const elem_size = elem_ty.abiSize(pt);
36153651
36163652 switch (ptr) {
36173653 .none => unreachable,
......@@ -3857,12 +3893,13 @@ fn genInlineMemsetCode(
38573893}
38583894
38593895fn airLoad(self: *Self, inst: Air.Inst.Index) !void {
3860 const mod = self.bin_file.comp.module.?;
3896 const pt = self.pt;
3897 const mod = pt.zcu;
38613898 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
38623899 const elem_ty = self.typeOfIndex(inst);
3863 const elem_size = elem_ty.abiSize(mod);
3900 const elem_size = elem_ty.abiSize(pt);
38643901 const result: MCValue = result: {
3865 if (!elem_ty.hasRuntimeBits(mod))
3902 if (!elem_ty.hasRuntimeBits(pt))
38663903 break :result MCValue.none;
38673904
38683905 const ptr = try self.resolveInst(ty_op.operand);
......@@ -3888,8 +3925,9 @@ fn airLoad(self: *Self, inst: Air.Inst.Index) !void {
38883925}
38893926
38903927fn genLdrRegister(self: *Self, value_reg: Register, addr_reg: Register, ty: Type) !void {
3891 const mod = self.bin_file.comp.module.?;
3892 const abi_size = ty.abiSize(mod);
3928 const pt = self.pt;
3929 const mod = pt.zcu;
3930 const abi_size = ty.abiSize(pt);
38933931
38943932 const tag: Mir.Inst.Tag = switch (abi_size) {
38953933 1 => if (ty.isSignedInt(mod)) Mir.Inst.Tag.ldrsb_immediate else .ldrb_immediate,
......@@ -3911,8 +3949,8 @@ fn genLdrRegister(self: *Self, value_reg: Register, addr_reg: Register, ty: Type
39113949}
39123950
39133951fn genStrRegister(self: *Self, value_reg: Register, addr_reg: Register, ty: Type) !void {
3914 const mod = self.bin_file.comp.module.?;
3915 const abi_size = ty.abiSize(mod);
3952 const pt = self.pt;
3953 const abi_size = ty.abiSize(pt);
39163954
39173955 const tag: Mir.Inst.Tag = switch (abi_size) {
39183956 1 => .strb_immediate,
......@@ -3933,9 +3971,9 @@ fn genStrRegister(self: *Self, value_reg: Register, addr_reg: Register, ty: Type
39333971}
39343972
39353973fn store(self: *Self, ptr: MCValue, value: MCValue, ptr_ty: Type, value_ty: Type) InnerError!void {
3936 const mod = self.bin_file.comp.module.?;
3974 const pt = self.pt;
39373975 log.debug("store: storing {} to {}", .{ value, ptr });
3938 const abi_size = value_ty.abiSize(mod);
3976 const abi_size = value_ty.abiSize(pt);
39393977
39403978 switch (ptr) {
39413979 .none => unreachable,
......@@ -4087,11 +4125,12 @@ fn airStructFieldPtrIndex(self: *Self, inst: Air.Inst.Index, index: u8) !void {
40874125
40884126fn structFieldPtr(self: *Self, inst: Air.Inst.Index, operand: Air.Inst.Ref, index: u32) !MCValue {
40894127 return if (self.liveness.isUnused(inst)) .dead else result: {
4090 const mod = self.bin_file.comp.module.?;
4128 const pt = self.pt;
4129 const mod = pt.zcu;
40914130 const mcv = try self.resolveInst(operand);
40924131 const ptr_ty = self.typeOf(operand);
40934132 const struct_ty = ptr_ty.childType(mod);
4094 const struct_field_offset = @as(u32, @intCast(struct_ty.structFieldOffset(index, mod)));
4133 const struct_field_offset = @as(u32, @intCast(struct_ty.structFieldOffset(index, pt)));
40954134 switch (mcv) {
40964135 .ptr_stack_offset => |off| {
40974136 break :result MCValue{ .ptr_stack_offset = off - struct_field_offset };
......@@ -4112,11 +4151,12 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
41124151 const operand = extra.struct_operand;
41134152 const index = extra.field_index;
41144153 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
4115 const mod = self.bin_file.comp.module.?;
4154 const pt = self.pt;
4155 const mod = pt.zcu;
41164156 const mcv = try self.resolveInst(operand);
41174157 const struct_ty = self.typeOf(operand);
41184158 const struct_field_ty = struct_ty.structFieldType(index, mod);
4119 const struct_field_offset = @as(u32, @intCast(struct_ty.structFieldOffset(index, mod)));
4159 const struct_field_offset = @as(u32, @intCast(struct_ty.structFieldOffset(index, pt)));
41204160
41214161 switch (mcv) {
41224162 .dead, .unreach => unreachable,
......@@ -4162,13 +4202,14 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
41624202}
41634203
41644204fn airFieldParentPtr(self: *Self, inst: Air.Inst.Index) !void {
4165 const mod = self.bin_file.comp.module.?;
4205 const pt = self.pt;
4206 const mod = pt.zcu;
41664207 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
41674208 const extra = self.air.extraData(Air.FieldParentPtr, ty_pl.payload).data;
41684209 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
41694210 const field_ptr = try self.resolveInst(extra.field_ptr);
41704211 const struct_ty = ty_pl.ty.toType().childType(mod);
4171 const struct_field_offset = @as(u32, @intCast(struct_ty.structFieldOffset(extra.field_index, mod)));
4212 const struct_field_offset = @as(u32, @intCast(struct_ty.structFieldOffset(extra.field_index, pt)));
41724213 switch (field_ptr) {
41734214 .ptr_stack_offset => |off| {
41744215 break :result MCValue{ .ptr_stack_offset = off + struct_field_offset };
......@@ -4190,7 +4231,8 @@ fn airArg(self: *Self, inst: Air.Inst.Index) !void {
41904231 while (self.args[arg_index] == .none) arg_index += 1;
41914232 self.arg_index = arg_index + 1;
41924233
4193 const mod = self.bin_file.comp.module.?;
4234 const pt = self.pt;
4235 const mod = pt.zcu;
41944236 const ty = self.typeOfIndex(inst);
41954237 const tag = self.air.instructions.items(.tag)[@intFromEnum(inst)];
41964238 const src_index = self.air.instructions.items(.data)[@intFromEnum(inst)].arg.src_index;
......@@ -4245,7 +4287,8 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
42454287 const extra = self.air.extraData(Air.Call, pl_op.payload);
42464288 const args = @as([]const Air.Inst.Ref, @ptrCast(self.air.extra[extra.end..][0..extra.data.args_len]));
42474289 const ty = self.typeOf(callee);
4248 const mod = self.bin_file.comp.module.?;
4290 const pt = self.pt;
4291 const mod = pt.zcu;
42494292
42504293 const fn_ty = switch (ty.zigTypeTag(mod)) {
42514294 .Fn => ty,
......@@ -4269,13 +4312,13 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
42694312 if (info.return_value == .stack_offset) {
42704313 log.debug("airCall: return by reference", .{});
42714314 const ret_ty = fn_ty.fnReturnType(mod);
4272 const ret_abi_size: u32 = @intCast(ret_ty.abiSize(mod));
4273 const ret_abi_align = ret_ty.abiAlignment(mod);
4315 const ret_abi_size: u32 = @intCast(ret_ty.abiSize(pt));
4316 const ret_abi_align = ret_ty.abiAlignment(pt);
42744317 const stack_offset = try self.allocMem(ret_abi_size, ret_abi_align, inst);
42754318
42764319 const ret_ptr_reg = self.registerAlias(.x0, Type.usize);
42774320
4278 const ptr_ty = try mod.singleMutPtrType(ret_ty);
4321 const ptr_ty = try pt.singleMutPtrType(ret_ty);
42794322 try self.register_manager.getReg(ret_ptr_reg, null);
42804323 try self.genSetReg(ptr_ty, ret_ptr_reg, .{ .ptr_stack_offset = stack_offset });
42814324
......@@ -4308,7 +4351,7 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
43084351
43094352 // Due to incremental compilation, how function calls are generated depends
43104353 // on linking.
4311 if (try self.air.value(callee, mod)) |func_value| {
4354 if (try self.air.value(callee, pt)) |func_value| {
43124355 if (func_value.getFunction(mod)) |func| {
43134356 if (self.bin_file.cast(link.File.Elf)) |elf_file| {
43144357 const sym_index = try elf_file.zigObjectPtr().?.getOrCreateMetadataForDecl(elf_file, func.owner_decl);
......@@ -4421,7 +4464,8 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
44214464}
44224465
44234466fn airRet(self: *Self, inst: Air.Inst.Index) !void {
4424 const mod = self.bin_file.comp.module.?;
4467 const pt = self.pt;
4468 const mod = pt.zcu;
44254469 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
44264470 const operand = try self.resolveInst(un_op);
44274471 const ret_ty = self.fn_type.fnReturnType(mod);
......@@ -4440,7 +4484,7 @@ fn airRet(self: *Self, inst: Air.Inst.Index) !void {
44404484 //
44414485 // self.ret_mcv is an address to where this function
44424486 // should store its result into
4443 const ptr_ty = try mod.singleMutPtrType(ret_ty);
4487 const ptr_ty = try pt.singleMutPtrType(ret_ty);
44444488 try self.store(self.ret_mcv, operand, ptr_ty, ret_ty);
44454489 },
44464490 else => unreachable,
......@@ -4453,7 +4497,8 @@ fn airRet(self: *Self, inst: Air.Inst.Index) !void {
44534497}
44544498
44554499fn airRetLoad(self: *Self, inst: Air.Inst.Index) !void {
4456 const mod = self.bin_file.comp.module.?;
4500 const pt = self.pt;
4501 const mod = pt.zcu;
44574502 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
44584503 const ptr = try self.resolveInst(un_op);
44594504 const ptr_ty = self.typeOf(un_op);
......@@ -4477,8 +4522,8 @@ fn airRetLoad(self: *Self, inst: Air.Inst.Index) !void {
44774522 // location.
44784523 const op_inst = un_op.toIndex().?;
44794524 if (self.air.instructions.items(.tag)[@intFromEnum(op_inst)] != .ret_ptr) {
4480 const abi_size = @as(u32, @intCast(ret_ty.abiSize(mod)));
4481 const abi_align = ret_ty.abiAlignment(mod);
4525 const abi_size = @as(u32, @intCast(ret_ty.abiSize(pt)));
4526 const abi_align = ret_ty.abiAlignment(pt);
44824527
44834528 const offset = try self.allocMem(abi_size, abi_align, null);
44844529
......@@ -4513,11 +4558,12 @@ fn cmp(
45134558 lhs_ty: Type,
45144559 op: math.CompareOperator,
45154560) !MCValue {
4516 const mod = self.bin_file.comp.module.?;
4561 const pt = self.pt;
4562 const mod = pt.zcu;
45174563 const int_ty = switch (lhs_ty.zigTypeTag(mod)) {
45184564 .Optional => blk: {
45194565 const payload_ty = lhs_ty.optionalChild(mod);
4520 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4566 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
45214567 break :blk Type.u1;
45224568 } else if (lhs_ty.isPtrLikeOptional(mod)) {
45234569 break :blk Type.usize;
......@@ -4620,7 +4666,8 @@ fn airDbgStmt(self: *Self, inst: Air.Inst.Index) !void {
46204666}
46214667
46224668fn airDbgInlineBlock(self: *Self, inst: Air.Inst.Index) !void {
4623 const mod = self.bin_file.comp.module.?;
4669 const pt = self.pt;
4670 const mod = pt.zcu;
46244671 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
46254672 const extra = self.air.extraData(Air.DbgInlineBlock, ty_pl.payload);
46264673 const func = mod.funcInfo(extra.data.func);
......@@ -4825,13 +4872,14 @@ fn airCondBr(self: *Self, inst: Air.Inst.Index) !void {
48254872}
48264873
48274874fn isNull(self: *Self, operand_bind: ReadArg.Bind, operand_ty: Type) !MCValue {
4828 const mod = self.bin_file.comp.module.?;
4875 const pt = self.pt;
4876 const mod = pt.zcu;
48294877 const sentinel: struct { ty: Type, bind: ReadArg.Bind } = if (!operand_ty.isPtrLikeOptional(mod)) blk: {
48304878 const payload_ty = operand_ty.optionalChild(mod);
4831 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod))
4879 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt))
48324880 break :blk .{ .ty = operand_ty, .bind = operand_bind };
48334881
4834 const offset = @as(u32, @intCast(payload_ty.abiSize(mod)));
4882 const offset = @as(u32, @intCast(payload_ty.abiSize(pt)));
48354883 const operand_mcv = try operand_bind.resolveToMcv(self);
48364884 const new_mcv: MCValue = switch (operand_mcv) {
48374885 .register => |source_reg| new: {
......@@ -4881,7 +4929,8 @@ fn isErr(
48814929 error_union_bind: ReadArg.Bind,
48824930 error_union_ty: Type,
48834931) !MCValue {
4884 const mod = self.bin_file.comp.module.?;
4932 const pt = self.pt;
4933 const mod = pt.zcu;
48854934 const error_type = error_union_ty.errorUnionSet(mod);
48864935
48874936 if (error_type.errorSetIsEmpty(mod)) {
......@@ -4923,7 +4972,8 @@ fn airIsNull(self: *Self, inst: Air.Inst.Index) !void {
49234972}
49244973
49254974fn airIsNullPtr(self: *Self, inst: Air.Inst.Index) !void {
4926 const mod = self.bin_file.comp.module.?;
4975 const pt = self.pt;
4976 const mod = pt.zcu;
49274977 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
49284978 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
49294979 const operand_ptr = try self.resolveInst(un_op);
......@@ -4950,7 +5000,8 @@ fn airIsNonNull(self: *Self, inst: Air.Inst.Index) !void {
49505000}
49515001
49525002fn airIsNonNullPtr(self: *Self, inst: Air.Inst.Index) !void {
4953 const mod = self.bin_file.comp.module.?;
5003 const pt = self.pt;
5004 const mod = pt.zcu;
49545005 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
49555006 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
49565007 const operand_ptr = try self.resolveInst(un_op);
......@@ -4977,7 +5028,8 @@ fn airIsErr(self: *Self, inst: Air.Inst.Index) !void {
49775028}
49785029
49795030fn airIsErrPtr(self: *Self, inst: Air.Inst.Index) !void {
4980 const mod = self.bin_file.comp.module.?;
5031 const pt = self.pt;
5032 const mod = pt.zcu;
49815033 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
49825034 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
49835035 const operand_ptr = try self.resolveInst(un_op);
......@@ -5004,7 +5056,8 @@ fn airIsNonErr(self: *Self, inst: Air.Inst.Index) !void {
50045056}
50055057
50065058fn airIsNonErrPtr(self: *Self, inst: Air.Inst.Index) !void {
5007 const mod = self.bin_file.comp.module.?;
5059 const pt = self.pt;
5060 const mod = pt.zcu;
50085061 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
50095062 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
50105063 const operand_ptr = try self.resolveInst(un_op);
......@@ -5225,10 +5278,10 @@ fn airBr(self: *Self, inst: Air.Inst.Index) !void {
52255278}
52265279
52275280fn br(self: *Self, block: Air.Inst.Index, operand: Air.Inst.Ref) !void {
5228 const mod = self.bin_file.comp.module.?;
5281 const pt = self.pt;
52295282 const block_data = self.blocks.getPtr(block).?;
52305283
5231 if (self.typeOf(operand).hasRuntimeBits(mod)) {
5284 if (self.typeOf(operand).hasRuntimeBits(pt)) {
52325285 const operand_mcv = try self.resolveInst(operand);
52335286 const block_mcv = block_data.mcv;
52345287 if (block_mcv == .none) {
......@@ -5402,8 +5455,9 @@ fn setRegOrMem(self: *Self, ty: Type, loc: MCValue, val: MCValue) !void {
54025455}
54035456
54045457fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerError!void {
5405 const mod = self.bin_file.comp.module.?;
5406 const abi_size = @as(u32, @intCast(ty.abiSize(mod)));
5458 const pt = self.pt;
5459 const mod = pt.zcu;
5460 const abi_size = @as(u32, @intCast(ty.abiSize(pt)));
54075461 switch (mcv) {
54085462 .dead => unreachable,
54095463 .unreach, .none => return, // Nothing to do.
......@@ -5462,7 +5516,7 @@ fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerErro
54625516 try self.genSetStack(wrapped_ty, stack_offset, .{ .register = rwo.reg });
54635517
54645518 const overflow_bit_ty = ty.structFieldType(1, mod);
5465 const overflow_bit_offset = @as(u32, @intCast(ty.structFieldOffset(1, mod)));
5519 const overflow_bit_offset = @as(u32, @intCast(ty.structFieldOffset(1, pt)));
54665520 const raw_cond_reg = try self.register_manager.allocReg(null, gp);
54675521 const cond_reg = self.registerAlias(raw_cond_reg, overflow_bit_ty);
54685522
......@@ -5495,7 +5549,7 @@ fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerErro
54955549 const reg = try self.copyToTmpRegister(ty, mcv);
54965550 return self.genSetStack(ty, stack_offset, MCValue{ .register = reg });
54975551 } else {
5498 const ptr_ty = try mod.singleMutPtrType(ty);
5552 const ptr_ty = try pt.singleMutPtrType(ty);
54995553
55005554 // TODO call extern memcpy
55015555 const regs = try self.register_manager.allocRegs(5, .{ null, null, null, null, null }, gp);
......@@ -5573,7 +5627,8 @@ fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerErro
55735627}
55745628
55755629fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void {
5576 const mod = self.bin_file.comp.module.?;
5630 const pt = self.pt;
5631 const mod = pt.zcu;
55775632 switch (mcv) {
55785633 .dead => unreachable,
55795634 .unreach, .none => return, // Nothing to do.
......@@ -5685,7 +5740,7 @@ fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void
56855740 try self.genLdrRegister(reg, reg.toX(), ty);
56865741 },
56875742 .stack_offset => |off| {
5688 const abi_size = ty.abiSize(mod);
5743 const abi_size = ty.abiSize(pt);
56895744
56905745 switch (abi_size) {
56915746 1, 2, 4, 8 => {
......@@ -5709,7 +5764,7 @@ fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void
57095764 }
57105765 },
57115766 .stack_argument_offset => |off| {
5712 const abi_size = ty.abiSize(mod);
5767 const abi_size = ty.abiSize(pt);
57135768
57145769 switch (abi_size) {
57155770 1, 2, 4, 8 => {
......@@ -5736,8 +5791,8 @@ fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void
57365791}
57375792
57385793fn genSetStackArgument(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerError!void {
5739 const mod = self.bin_file.comp.module.?;
5740 const abi_size = @as(u32, @intCast(ty.abiSize(mod)));
5794 const pt = self.pt;
5795 const abi_size = @as(u32, @intCast(ty.abiSize(pt)));
57415796 switch (mcv) {
57425797 .dead => unreachable,
57435798 .none, .unreach => return,
......@@ -5745,7 +5800,7 @@ fn genSetStackArgument(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) I
57455800 if (!self.wantSafety())
57465801 return; // The already existing value will do just fine.
57475802 // TODO Upgrade this to a memset call when we have that available.
5748 switch (ty.abiSize(mod)) {
5803 switch (ty.abiSize(pt)) {
57495804 1 => return self.genSetStack(ty, stack_offset, .{ .immediate = 0xaa }),
57505805 2 => return self.genSetStack(ty, stack_offset, .{ .immediate = 0xaaaa }),
57515806 4 => return self.genSetStack(ty, stack_offset, .{ .immediate = 0xaaaaaaaa }),
......@@ -5815,7 +5870,7 @@ fn genSetStackArgument(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) I
58155870 const reg = try self.copyToTmpRegister(ty, mcv);
58165871 return self.genSetStackArgument(ty, stack_offset, MCValue{ .register = reg });
58175872 } else {
5818 const ptr_ty = try mod.singleMutPtrType(ty);
5873 const ptr_ty = try pt.singleMutPtrType(ty);
58195874
58205875 // TODO call extern memcpy
58215876 const regs = try self.register_manager.allocRegs(5, .{ null, null, null, null, null }, gp);
......@@ -5936,7 +5991,8 @@ fn airBitCast(self: *Self, inst: Air.Inst.Index) !void {
59365991}
59375992
59385993fn airArrayToSlice(self: *Self, inst: Air.Inst.Index) !void {
5939 const mod = self.bin_file.comp.module.?;
5994 const pt = self.pt;
5995 const mod = pt.zcu;
59405996 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59415997 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
59425998 const ptr_ty = self.typeOf(ty_op.operand);
......@@ -6056,7 +6112,8 @@ fn airReduce(self: *Self, inst: Air.Inst.Index) !void {
60566112}
60576113
60586114fn airAggregateInit(self: *Self, inst: Air.Inst.Index) !void {
6059 const mod = self.bin_file.comp.module.?;
6115 const pt = self.pt;
6116 const mod = pt.zcu;
60606117 const vector_ty = self.typeOfIndex(inst);
60616118 const len = vector_ty.vectorLen(mod);
60626119 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
......@@ -6100,15 +6157,15 @@ fn airMulAdd(self: *Self, inst: Air.Inst.Index) !void {
61006157}
61016158
61026159fn airTry(self: *Self, inst: Air.Inst.Index) !void {
6103 const mod = self.bin_file.comp.module.?;
6160 const pt = self.pt;
61046161 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
61056162 const extra = self.air.extraData(Air.Try, pl_op.payload);
61066163 const body: []const Air.Inst.Index = @ptrCast(self.air.extra[extra.end..][0..extra.data.body_len]);
61076164 const result: MCValue = result: {
61086165 const error_union_bind: ReadArg.Bind = .{ .inst = pl_op.operand };
61096166 const error_union_ty = self.typeOf(pl_op.operand);
6110 const error_union_size = @as(u32, @intCast(error_union_ty.abiSize(mod)));
6111 const error_union_align = error_union_ty.abiAlignment(mod);
6167 const error_union_size = @as(u32, @intCast(error_union_ty.abiSize(pt)));
6168 const error_union_align = error_union_ty.abiAlignment(pt);
61126169
61136170 // The error union will die in the body. However, we need the
61146171 // error union after the body in order to extract the payload
......@@ -6137,14 +6194,15 @@ fn airTryPtr(self: *Self, inst: Air.Inst.Index) !void {
61376194}
61386195
61396196fn resolveInst(self: *Self, inst: Air.Inst.Ref) InnerError!MCValue {
6140 const mod = self.bin_file.comp.module.?;
6197 const pt = self.pt;
6198 const mod = pt.zcu;
61416199
61426200 // If the type has no codegen bits, no need to store it.
61436201 const inst_ty = self.typeOf(inst);
6144 if (!inst_ty.hasRuntimeBitsIgnoreComptime(mod) and !inst_ty.isError(mod))
6202 if (!inst_ty.hasRuntimeBitsIgnoreComptime(pt) and !inst_ty.isError(mod))
61456203 return MCValue{ .none = {} };
61466204
6147 const inst_index = inst.toIndex() orelse return self.genTypedValue((try self.air.value(inst, mod)).?);
6205 const inst_index = inst.toIndex() orelse return self.genTypedValue((try self.air.value(inst, pt)).?);
61486206
61496207 return self.getResolvedInstValue(inst_index);
61506208}
......@@ -6164,6 +6222,7 @@ fn getResolvedInstValue(self: *Self, inst: Air.Inst.Index) MCValue {
61646222fn genTypedValue(self: *Self, val: Value) InnerError!MCValue {
61656223 const mcv: MCValue = switch (try codegen.genTypedValue(
61666224 self.bin_file,
6225 self.pt,
61676226 self.src_loc,
61686227 val,
61696228 self.owner_decl,
......@@ -6199,7 +6258,8 @@ const CallMCValues = struct {
61996258
62006259/// Caller must call `CallMCValues.deinit`.
62016260fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
6202 const mod = self.bin_file.comp.module.?;
6261 const pt = self.pt;
6262 const mod = pt.zcu;
62036263 const ip = &mod.intern_pool;
62046264 const fn_info = mod.typeToFunc(fn_ty).?;
62056265 const cc = fn_info.cc;
......@@ -6229,10 +6289,10 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
62296289
62306290 if (ret_ty.zigTypeTag(mod) == .NoReturn) {
62316291 result.return_value = .{ .unreach = {} };
6232 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod) and !ret_ty.isError(mod)) {
6292 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt) and !ret_ty.isError(mod)) {
62336293 result.return_value = .{ .none = {} };
62346294 } else {
6235 const ret_ty_size = @as(u32, @intCast(ret_ty.abiSize(mod)));
6295 const ret_ty_size: u32 = @intCast(ret_ty.abiSize(pt));
62366296 if (ret_ty_size == 0) {
62376297 assert(ret_ty.isError(mod));
62386298 result.return_value = .{ .immediate = 0 };
......@@ -6244,7 +6304,7 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
62446304 }
62456305
62466306 for (fn_info.param_types.get(ip), result.args) |ty, *result_arg| {
6247 const param_size = @as(u32, @intCast(Type.fromInterned(ty).abiSize(mod)));
6307 const param_size = @as(u32, @intCast(Type.fromInterned(ty).abiSize(pt)));
62486308 if (param_size == 0) {
62496309 result_arg.* = .{ .none = {} };
62506310 continue;
......@@ -6252,7 +6312,7 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
62526312
62536313 // We round up NCRN only for non-Apple platforms which allow the 16-byte aligned
62546314 // values to spread across odd-numbered registers.
6255 if (Type.fromInterned(ty).abiAlignment(mod) == .@"16" and !self.target.isDarwin()) {
6315 if (Type.fromInterned(ty).abiAlignment(pt) == .@"16" and !self.target.isDarwin()) {
62566316 // Round up NCRN to the next even number
62576317 ncrn += ncrn % 2;
62586318 }
......@@ -6270,7 +6330,7 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
62706330 ncrn = 8;
62716331 // TODO Apple allows the arguments on the stack to be non-8-byte aligned provided
62726332 // that the entire stack space consumed by the arguments is 8-byte aligned.
6273 if (Type.fromInterned(ty).abiAlignment(mod) == .@"8") {
6333 if (Type.fromInterned(ty).abiAlignment(pt) == .@"8") {
62746334 if (nsaa % 8 != 0) {
62756335 nsaa += 8 - (nsaa % 8);
62766336 }
......@@ -6287,10 +6347,10 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
62876347 .Unspecified => {
62886348 if (ret_ty.zigTypeTag(mod) == .NoReturn) {
62896349 result.return_value = .{ .unreach = {} };
6290 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod) and !ret_ty.isError(mod)) {
6350 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt) and !ret_ty.isError(mod)) {
62916351 result.return_value = .{ .none = {} };
62926352 } else {
6293 const ret_ty_size = @as(u32, @intCast(ret_ty.abiSize(mod)));
6353 const ret_ty_size = @as(u32, @intCast(ret_ty.abiSize(pt)));
62946354 if (ret_ty_size == 0) {
62956355 assert(ret_ty.isError(mod));
62966356 result.return_value = .{ .immediate = 0 };
......@@ -6309,9 +6369,9 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
63096369 var stack_offset: u32 = 0;
63106370
63116371 for (fn_info.param_types.get(ip), result.args) |ty, *result_arg| {
6312 if (Type.fromInterned(ty).abiSize(mod) > 0) {
6313 const param_size: u32 = @intCast(Type.fromInterned(ty).abiSize(mod));
6314 const param_alignment = Type.fromInterned(ty).abiAlignment(mod);
6372 if (Type.fromInterned(ty).abiSize(pt) > 0) {
6373 const param_size: u32 = @intCast(Type.fromInterned(ty).abiSize(pt));
6374 const param_alignment = Type.fromInterned(ty).abiAlignment(pt);
63156375
63166376 stack_offset = @intCast(param_alignment.forward(stack_offset));
63176377 result_arg.* = .{ .stack_argument_offset = stack_offset };
......@@ -6330,7 +6390,7 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
63306390 return result;
63316391}
63326392
6333/// TODO support scope overrides. Also note this logic is duplicated with `Module.wantSafety`.
6393/// TODO support scope overrides. Also note this logic is duplicated with `Zcu.wantSafety`.
63346394fn wantSafety(self: *Self) bool {
63356395 return switch (self.bin_file.comp.root_mod.optimize_mode) {
63366396 .Debug => true,
......@@ -6362,8 +6422,7 @@ fn parseRegName(name: []const u8) ?Register {
63626422}
63636423
63646424fn registerAlias(self: *Self, reg: Register, ty: Type) Register {
6365 const mod = self.bin_file.comp.module.?;
6366 const abi_size = ty.abiSize(mod);
6425 const abi_size = ty.abiSize(self.pt);
63676426
63686427 switch (reg.class()) {
63696428 .general_purpose => {
......@@ -6391,11 +6450,9 @@ fn registerAlias(self: *Self, reg: Register, ty: Type) Register {
63916450}
63926451
63936452fn typeOf(self: *Self, inst: Air.Inst.Ref) Type {
6394 const mod = self.bin_file.comp.module.?;
6395 return self.air.typeOf(inst, &mod.intern_pool);
6453 return self.air.typeOf(inst, &self.pt.zcu.intern_pool);
63966454}
63976455
63986456fn typeOfIndex(self: *Self, inst: Air.Inst.Index) Type {
6399 const mod = self.bin_file.comp.module.?;
6400 return self.air.typeOfIndex(inst, &mod.intern_pool);
6457 return self.air.typeOfIndex(inst, &self.pt.zcu.intern_pool);
64016458}
src/arch/aarch64/Emit.zig+2-4
......@@ -8,9 +8,7 @@ const Mir = @import("Mir.zig");
88const bits = @import("bits.zig");
99const link = @import("../../link.zig");
1010const Zcu = @import("../../Zcu.zig");
11/// Deprecated.
12const Module = Zcu;
13const ErrorMsg = Module.ErrorMsg;
11const ErrorMsg = Zcu.ErrorMsg;
1412const assert = std.debug.assert;
1513const Instruction = bits.Instruction;
1614const Register = bits.Register;
......@@ -22,7 +20,7 @@ bin_file: *link.File,
2220debug_output: DebugInfoOutput,
2321target: *const std.Target,
2422err_msg: ?*ErrorMsg = null,
25src_loc: Module.LazySrcLoc,
23src_loc: Zcu.LazySrcLoc,
2624code: *std.ArrayList(u8),
2725
2826prev_di_line: u32,
src/arch/aarch64/abi.zig+29-31
......@@ -5,8 +5,6 @@ const Register = bits.Register;
55const RegisterManagerFn = @import("../../register_manager.zig").RegisterManager;
66const Type = @import("../../Type.zig");
77const Zcu = @import("../../Zcu.zig");
8/// Deprecated.
9const Module = Zcu;
108
119pub const Class = union(enum) {
1210 memory,
......@@ -17,44 +15,44 @@ pub const Class = union(enum) {
1715};
1816
1917/// For `float_array` the second element will be the amount of floats.
20pub fn classifyType(ty: Type, mod: *Module) Class {
21 std.debug.assert(ty.hasRuntimeBitsIgnoreComptime(mod));
18pub fn classifyType(ty: Type, pt: Zcu.PerThread) Class {
19 std.debug.assert(ty.hasRuntimeBitsIgnoreComptime(pt));
2220
2321 var maybe_float_bits: ?u16 = null;
24 switch (ty.zigTypeTag(mod)) {
22 switch (ty.zigTypeTag(pt.zcu)) {
2523 .Struct => {
26 if (ty.containerLayout(mod) == .@"packed") return .byval;
27 const float_count = countFloats(ty, mod, &maybe_float_bits);
24 if (ty.containerLayout(pt.zcu) == .@"packed") return .byval;
25 const float_count = countFloats(ty, pt.zcu, &maybe_float_bits);
2826 if (float_count <= sret_float_count) return .{ .float_array = float_count };
2927
30 const bit_size = ty.bitSize(mod);
28 const bit_size = ty.bitSize(pt);
3129 if (bit_size > 128) return .memory;
3230 if (bit_size > 64) return .double_integer;
3331 return .integer;
3432 },
3533 .Union => {
36 if (ty.containerLayout(mod) == .@"packed") return .byval;
37 const float_count = countFloats(ty, mod, &maybe_float_bits);
34 if (ty.containerLayout(pt.zcu) == .@"packed") return .byval;
35 const float_count = countFloats(ty, pt.zcu, &maybe_float_bits);
3836 if (float_count <= sret_float_count) return .{ .float_array = float_count };
3937
40 const bit_size = ty.bitSize(mod);
38 const bit_size = ty.bitSize(pt);
4139 if (bit_size > 128) return .memory;
4240 if (bit_size > 64) return .double_integer;
4341 return .integer;
4442 },
4543 .Int, .Enum, .ErrorSet, .Float, .Bool => return .byval,
4644 .Vector => {
47 const bit_size = ty.bitSize(mod);
45 const bit_size = ty.bitSize(pt);
4846 // TODO is this controlled by a cpu feature?
4947 if (bit_size > 128) return .memory;
5048 return .byval;
5149 },
5250 .Optional => {
53 std.debug.assert(ty.isPtrLikeOptional(mod));
51 std.debug.assert(ty.isPtrLikeOptional(pt.zcu));
5452 return .byval;
5553 },
5654 .Pointer => {
57 std.debug.assert(!ty.isSlice(mod));
55 std.debug.assert(!ty.isSlice(pt.zcu));
5856 return .byval;
5957 },
6058 .ErrorUnion,
......@@ -76,16 +74,16 @@ pub fn classifyType(ty: Type, mod: *Module) Class {
7674}
7775
7876const sret_float_count = 4;
79fn countFloats(ty: Type, mod: *Module, maybe_float_bits: *?u16) u8 {
80 const ip = &mod.intern_pool;
81 const target = mod.getTarget();
77fn countFloats(ty: Type, zcu: *Zcu, maybe_float_bits: *?u16) u8 {
78 const ip = &zcu.intern_pool;
79 const target = zcu.getTarget();
8280 const invalid = std.math.maxInt(u8);
83 switch (ty.zigTypeTag(mod)) {
81 switch (ty.zigTypeTag(zcu)) {
8482 .Union => {
85 const union_obj = mod.typeToUnion(ty).?;
83 const union_obj = zcu.typeToUnion(ty).?;
8684 var max_count: u8 = 0;
8785 for (union_obj.field_types.get(ip)) |field_ty| {
88 const field_count = countFloats(Type.fromInterned(field_ty), mod, maybe_float_bits);
86 const field_count = countFloats(Type.fromInterned(field_ty), zcu, maybe_float_bits);
8987 if (field_count == invalid) return invalid;
9088 if (field_count > max_count) max_count = field_count;
9189 if (max_count > sret_float_count) return invalid;
......@@ -93,12 +91,12 @@ fn countFloats(ty: Type, mod: *Module, maybe_float_bits: *?u16) u8 {
9391 return max_count;
9492 },
9593 .Struct => {
96 const fields_len = ty.structFieldCount(mod);
94 const fields_len = ty.structFieldCount(zcu);
9795 var count: u8 = 0;
9896 var i: u32 = 0;
9997 while (i < fields_len) : (i += 1) {
100 const field_ty = ty.structFieldType(i, mod);
101 const field_count = countFloats(field_ty, mod, maybe_float_bits);
98 const field_ty = ty.structFieldType(i, zcu);
99 const field_count = countFloats(field_ty, zcu, maybe_float_bits);
102100 if (field_count == invalid) return invalid;
103101 count += field_count;
104102 if (count > sret_float_count) return invalid;
......@@ -118,22 +116,22 @@ fn countFloats(ty: Type, mod: *Module, maybe_float_bits: *?u16) u8 {
118116 }
119117}
120118
121pub fn getFloatArrayType(ty: Type, mod: *Module) ?Type {
122 const ip = &mod.intern_pool;
123 switch (ty.zigTypeTag(mod)) {
119pub fn getFloatArrayType(ty: Type, zcu: *Zcu) ?Type {
120 const ip = &zcu.intern_pool;
121 switch (ty.zigTypeTag(zcu)) {
124122 .Union => {
125 const union_obj = mod.typeToUnion(ty).?;
123 const union_obj = zcu.typeToUnion(ty).?;
126124 for (union_obj.field_types.get(ip)) |field_ty| {
127 if (getFloatArrayType(Type.fromInterned(field_ty), mod)) |some| return some;
125 if (getFloatArrayType(Type.fromInterned(field_ty), zcu)) |some| return some;
128126 }
129127 return null;
130128 },
131129 .Struct => {
132 const fields_len = ty.structFieldCount(mod);
130 const fields_len = ty.structFieldCount(zcu);
133131 var i: u32 = 0;
134132 while (i < fields_len) : (i += 1) {
135 const field_ty = ty.structFieldType(i, mod);
136 if (getFloatArrayType(field_ty, mod)) |some| return some;
133 const field_ty = ty.structFieldType(i, zcu);
134 if (getFloatArrayType(field_ty, zcu)) |some| return some;
137135 }
138136 return null;
139137 },
src/arch/arm/CodeGen.zig+219-164
......@@ -12,11 +12,9 @@ const Type = @import("../../Type.zig");
1212const Value = @import("../../Value.zig");
1313const link = @import("../../link.zig");
1414const Zcu = @import("../../Zcu.zig");
15/// Deprecated.
16const Module = Zcu;
1715const InternPool = @import("../../InternPool.zig");
1816const Compilation = @import("../../Compilation.zig");
19const ErrorMsg = Module.ErrorMsg;
17const ErrorMsg = Zcu.ErrorMsg;
2018const Target = std.Target;
2119const Allocator = mem.Allocator;
2220const trace = @import("../../tracy.zig").trace;
......@@ -48,6 +46,7 @@ const gp = abi.RegisterClass.gp;
4846const InnerError = CodeGenError || error{OutOfRegisters};
4947
5048gpa: Allocator,
49pt: Zcu.PerThread,
5150air: Air,
5251liveness: Liveness,
5352bin_file: *link.File,
......@@ -59,7 +58,7 @@ args: []MCValue,
5958ret_mcv: MCValue,
6059fn_type: Type,
6160arg_index: u32,
62src_loc: Module.LazySrcLoc,
61src_loc: Zcu.LazySrcLoc,
6362stack_align: u32,
6463
6564/// MIR Instructions
......@@ -261,7 +260,6 @@ const DbgInfoReloc = struct {
261260 }
262261
263262 fn genArgDbgInfo(reloc: DbgInfoReloc, function: Self) error{OutOfMemory}!void {
264 const mod = function.bin_file.comp.module.?;
265263 switch (function.debug_output) {
266264 .dwarf => |dw| {
267265 const loc: link.File.Dwarf.DeclState.DbgInfoLoc = switch (reloc.mcv) {
......@@ -282,7 +280,7 @@ const DbgInfoReloc = struct {
282280 else => unreachable, // not a possible argument
283281 };
284282
285 try dw.genArgDbgInfo(reloc.name, reloc.ty, mod.funcOwnerDeclIndex(function.func_index), loc);
283 try dw.genArgDbgInfo(reloc.name, reloc.ty, function.pt.zcu.funcOwnerDeclIndex(function.func_index), loc);
286284 },
287285 .plan9 => {},
288286 .none => {},
......@@ -290,7 +288,6 @@ const DbgInfoReloc = struct {
290288 }
291289
292290 fn genVarDbgInfo(reloc: DbgInfoReloc, function: Self) !void {
293 const mod = function.bin_file.comp.module.?;
294291 const is_ptr = switch (reloc.tag) {
295292 .dbg_var_ptr => true,
296293 .dbg_var_val => false,
......@@ -326,7 +323,7 @@ const DbgInfoReloc = struct {
326323 break :blk .nop;
327324 },
328325 };
329 try dw.genVarDbgInfo(reloc.name, reloc.ty, mod.funcOwnerDeclIndex(function.func_index), is_ptr, loc);
326 try dw.genVarDbgInfo(reloc.name, reloc.ty, function.pt.zcu.funcOwnerDeclIndex(function.func_index), is_ptr, loc);
330327 },
331328 .plan9 => {},
332329 .none => {},
......@@ -338,15 +335,16 @@ const Self = @This();
338335
339336pub fn generate(
340337 lf: *link.File,
341 src_loc: Module.LazySrcLoc,
338 pt: Zcu.PerThread,
339 src_loc: Zcu.LazySrcLoc,
342340 func_index: InternPool.Index,
343341 air: Air,
344342 liveness: Liveness,
345343 code: *std.ArrayList(u8),
346344 debug_output: DebugInfoOutput,
347345) CodeGenError!Result {
348 const gpa = lf.comp.gpa;
349 const zcu = lf.comp.module.?;
346 const zcu = pt.zcu;
347 const gpa = zcu.gpa;
350348 const func = zcu.funcInfo(func_index);
351349 const fn_owner_decl = zcu.declPtr(func.owner_decl);
352350 assert(fn_owner_decl.has_tv);
......@@ -364,6 +362,7 @@ pub fn generate(
364362
365363 var function: Self = .{
366364 .gpa = gpa,
365 .pt = pt,
367366 .air = air,
368367 .liveness = liveness,
369368 .target = target,
......@@ -482,7 +481,8 @@ pub fn addExtraAssumeCapacity(self: *Self, extra: anytype) u32 {
482481}
483482
484483fn gen(self: *Self) !void {
485 const mod = self.bin_file.comp.module.?;
484 const pt = self.pt;
485 const mod = pt.zcu;
486486 const cc = self.fn_type.fnCallingConvention(mod);
487487 if (cc != .Naked) {
488488 // push {fp, lr}
......@@ -526,8 +526,8 @@ fn gen(self: *Self) !void {
526526
527527 const ty = self.typeOfIndex(inst);
528528
529 const abi_size: u32 = @intCast(ty.abiSize(mod));
530 const abi_align = ty.abiAlignment(mod);
529 const abi_size: u32 = @intCast(ty.abiSize(pt));
530 const abi_align = ty.abiAlignment(pt);
531531 const stack_offset = try self.allocMem(abi_size, abi_align, inst);
532532 try self.genSetStack(ty, stack_offset, MCValue{ .register = reg });
533533
......@@ -642,7 +642,8 @@ fn gen(self: *Self) !void {
642642}
643643
644644fn genBody(self: *Self, body: []const Air.Inst.Index) InnerError!void {
645 const mod = self.bin_file.comp.module.?;
645 const pt = self.pt;
646 const mod = pt.zcu;
646647 const ip = &mod.intern_pool;
647648 const air_tags = self.air.instructions.items(.tag);
648649
......@@ -1004,10 +1005,11 @@ fn allocMem(
10041005
10051006/// Use a pointer instruction as the basis for allocating stack memory.
10061007fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !u32 {
1007 const mod = self.bin_file.comp.module.?;
1008 const pt = self.pt;
1009 const mod = pt.zcu;
10081010 const elem_ty = self.typeOfIndex(inst).childType(mod);
10091011
1010 if (!elem_ty.hasRuntimeBits(mod)) {
1012 if (!elem_ty.hasRuntimeBits(pt)) {
10111013 // As this stack item will never be dereferenced at runtime,
10121014 // return the stack offset 0. Stack offset 0 will be where all
10131015 // zero-sized stack allocations live as non-zero-sized
......@@ -1015,21 +1017,21 @@ fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !u32 {
10151017 return 0;
10161018 }
10171019
1018 const abi_size = math.cast(u32, elem_ty.abiSize(mod)) orelse {
1019 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
1020 const abi_size = math.cast(u32, elem_ty.abiSize(pt)) orelse {
1021 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(pt)});
10201022 };
10211023 // TODO swap this for inst.ty.ptrAlign
1022 const abi_align = elem_ty.abiAlignment(mod);
1024 const abi_align = elem_ty.abiAlignment(pt);
10231025
10241026 return self.allocMem(abi_size, abi_align, inst);
10251027}
10261028
10271029fn allocRegOrMem(self: *Self, elem_ty: Type, reg_ok: bool, maybe_inst: ?Air.Inst.Index) !MCValue {
1028 const mod = self.bin_file.comp.module.?;
1029 const abi_size = math.cast(u32, elem_ty.abiSize(mod)) orelse {
1030 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
1030 const pt = self.pt;
1031 const abi_size = math.cast(u32, elem_ty.abiSize(pt)) orelse {
1032 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(pt)});
10311033 };
1032 const abi_align = elem_ty.abiAlignment(mod);
1034 const abi_align = elem_ty.abiAlignment(pt);
10331035
10341036 if (reg_ok) {
10351037 // Make sure the type can fit in a register before we try to allocate one.
......@@ -1112,14 +1114,15 @@ fn airAlloc(self: *Self, inst: Air.Inst.Index) !void {
11121114}
11131115
11141116fn airRetPtr(self: *Self, inst: Air.Inst.Index) !void {
1115 const mod = self.bin_file.comp.module.?;
1117 const pt = self.pt;
1118 const mod = pt.zcu;
11161119 const result: MCValue = switch (self.ret_mcv) {
11171120 .none, .register => .{ .ptr_stack_offset = try self.allocMemPtr(inst) },
11181121 .stack_offset => blk: {
11191122 // self.ret_mcv is an address to where this function
11201123 // should store its result into
11211124 const ret_ty = self.fn_type.fnReturnType(mod);
1122 const ptr_ty = try mod.singleMutPtrType(ret_ty);
1125 const ptr_ty = try pt.singleMutPtrType(ret_ty);
11231126
11241127 // addr_reg will contain the address of where to store the
11251128 // result into
......@@ -1145,7 +1148,8 @@ fn airFpext(self: *Self, inst: Air.Inst.Index) !void {
11451148}
11461149
11471150fn airIntCast(self: *Self, inst: Air.Inst.Index) !void {
1148 const mod = self.bin_file.comp.module.?;
1151 const pt = self.pt;
1152 const mod = pt.zcu;
11491153 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
11501154 if (self.liveness.isUnused(inst))
11511155 return self.finishAir(inst, .dead, .{ ty_op.operand, .none, .none });
......@@ -1154,8 +1158,8 @@ fn airIntCast(self: *Self, inst: Air.Inst.Index) !void {
11541158 const operand_ty = self.typeOf(ty_op.operand);
11551159 const dest_ty = self.typeOfIndex(inst);
11561160
1157 const operand_abi_size = operand_ty.abiSize(mod);
1158 const dest_abi_size = dest_ty.abiSize(mod);
1161 const operand_abi_size = operand_ty.abiSize(pt);
1162 const dest_abi_size = dest_ty.abiSize(pt);
11591163 const info_a = operand_ty.intInfo(mod);
11601164 const info_b = dest_ty.intInfo(mod);
11611165
......@@ -1211,7 +1215,8 @@ fn trunc(
12111215 operand_ty: Type,
12121216 dest_ty: Type,
12131217) !MCValue {
1214 const mod = self.bin_file.comp.module.?;
1218 const pt = self.pt;
1219 const mod = pt.zcu;
12151220 const info_a = operand_ty.intInfo(mod);
12161221 const info_b = dest_ty.intInfo(mod);
12171222
......@@ -1275,7 +1280,8 @@ fn airIntFromBool(self: *Self, inst: Air.Inst.Index) !void {
12751280
12761281fn airNot(self: *Self, inst: Air.Inst.Index) !void {
12771282 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
1278 const mod = self.bin_file.comp.module.?;
1283 const pt = self.pt;
1284 const mod = pt.zcu;
12791285 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
12801286 const operand_bind: ReadArg.Bind = .{ .inst = ty_op.operand };
12811287 const operand_ty = self.typeOf(ty_op.operand);
......@@ -1371,7 +1377,8 @@ fn minMax(
13711377 rhs_ty: Type,
13721378 maybe_inst: ?Air.Inst.Index,
13731379) !MCValue {
1374 const mod = self.bin_file.comp.module.?;
1380 const pt = self.pt;
1381 const mod = pt.zcu;
13751382 switch (lhs_ty.zigTypeTag(mod)) {
13761383 .Float => return self.fail("TODO ARM min/max on floats", .{}),
13771384 .Vector => return self.fail("TODO ARM min/max on vectors", .{}),
......@@ -1580,7 +1587,8 @@ fn airOverflow(self: *Self, inst: Air.Inst.Index) !void {
15801587 const tag = self.air.instructions.items(.tag)[@intFromEnum(inst)];
15811588 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
15821589 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
1583 const mod = self.bin_file.comp.module.?;
1590 const pt = self.pt;
1591 const mod = pt.zcu;
15841592 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
15851593 const lhs_bind: ReadArg.Bind = .{ .inst = extra.lhs };
15861594 const rhs_bind: ReadArg.Bind = .{ .inst = extra.rhs };
......@@ -1588,9 +1596,9 @@ fn airOverflow(self: *Self, inst: Air.Inst.Index) !void {
15881596 const rhs_ty = self.typeOf(extra.rhs);
15891597
15901598 const tuple_ty = self.typeOfIndex(inst);
1591 const tuple_size: u32 = @intCast(tuple_ty.abiSize(mod));
1592 const tuple_align = tuple_ty.abiAlignment(mod);
1593 const overflow_bit_offset: u32 = @intCast(tuple_ty.structFieldOffset(1, mod));
1599 const tuple_size: u32 = @intCast(tuple_ty.abiSize(pt));
1600 const tuple_align = tuple_ty.abiAlignment(pt);
1601 const overflow_bit_offset: u32 = @intCast(tuple_ty.structFieldOffset(1, pt));
15941602
15951603 switch (lhs_ty.zigTypeTag(mod)) {
15961604 .Vector => return self.fail("TODO implement add_with_overflow/sub_with_overflow for vectors", .{}),
......@@ -1693,7 +1701,8 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
16931701 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
16941702 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
16951703 if (self.liveness.isUnused(inst)) return self.finishAir(inst, .dead, .{ extra.lhs, extra.rhs, .none });
1696 const mod = self.bin_file.comp.module.?;
1704 const pt = self.pt;
1705 const mod = pt.zcu;
16971706 const result: MCValue = result: {
16981707 const lhs_bind: ReadArg.Bind = .{ .inst = extra.lhs };
16991708 const rhs_bind: ReadArg.Bind = .{ .inst = extra.rhs };
......@@ -1701,9 +1710,9 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
17011710 const rhs_ty = self.typeOf(extra.rhs);
17021711
17031712 const tuple_ty = self.typeOfIndex(inst);
1704 const tuple_size: u32 = @intCast(tuple_ty.abiSize(mod));
1705 const tuple_align = tuple_ty.abiAlignment(mod);
1706 const overflow_bit_offset: u32 = @intCast(tuple_ty.structFieldOffset(1, mod));
1713 const tuple_size: u32 = @intCast(tuple_ty.abiSize(pt));
1714 const tuple_align = tuple_ty.abiAlignment(pt);
1715 const overflow_bit_offset: u32 = @intCast(tuple_ty.structFieldOffset(1, pt));
17071716
17081717 switch (lhs_ty.zigTypeTag(mod)) {
17091718 .Vector => return self.fail("TODO implement mul_with_overflow for vectors", .{}),
......@@ -1857,15 +1866,16 @@ fn airShlWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
18571866 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
18581867 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
18591868 if (self.liveness.isUnused(inst)) return self.finishAir(inst, .dead, .{ extra.lhs, extra.rhs, .none });
1860 const mod = self.bin_file.comp.module.?;
1869 const pt = self.pt;
1870 const mod = pt.zcu;
18611871 const result: MCValue = result: {
18621872 const lhs_ty = self.typeOf(extra.lhs);
18631873 const rhs_ty = self.typeOf(extra.rhs);
18641874
18651875 const tuple_ty = self.typeOfIndex(inst);
1866 const tuple_size: u32 = @intCast(tuple_ty.abiSize(mod));
1867 const tuple_align = tuple_ty.abiAlignment(mod);
1868 const overflow_bit_offset: u32 = @intCast(tuple_ty.structFieldOffset(1, mod));
1876 const tuple_size: u32 = @intCast(tuple_ty.abiSize(pt));
1877 const tuple_align = tuple_ty.abiAlignment(pt);
1878 const overflow_bit_offset: u32 = @intCast(tuple_ty.structFieldOffset(1, pt));
18691879
18701880 switch (lhs_ty.zigTypeTag(mod)) {
18711881 .Vector => return self.fail("TODO implement shl_with_overflow for vectors", .{}),
......@@ -2013,11 +2023,11 @@ fn airOptionalPayloadPtrSet(self: *Self, inst: Air.Inst.Index) !void {
20132023}
20142024
20152025fn airWrapOptional(self: *Self, inst: Air.Inst.Index) !void {
2016 const mod = self.bin_file.comp.module.?;
2026 const pt = self.pt;
20172027 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
20182028 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
20192029 const optional_ty = self.typeOfIndex(inst);
2020 const abi_size: u32 = @intCast(optional_ty.abiSize(mod));
2030 const abi_size: u32 = @intCast(optional_ty.abiSize(pt));
20212031
20222032 // Optional with a zero-bit payload type is just a boolean true
20232033 if (abi_size == 1) {
......@@ -2036,17 +2046,18 @@ fn errUnionErr(
20362046 error_union_ty: Type,
20372047 maybe_inst: ?Air.Inst.Index,
20382048) !MCValue {
2039 const mod = self.bin_file.comp.module.?;
2049 const pt = self.pt;
2050 const mod = pt.zcu;
20402051 const err_ty = error_union_ty.errorUnionSet(mod);
20412052 const payload_ty = error_union_ty.errorUnionPayload(mod);
20422053 if (err_ty.errorSetIsEmpty(mod)) {
20432054 return MCValue{ .immediate = 0 };
20442055 }
2045 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
2056 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
20462057 return try error_union_bind.resolveToMcv(self);
20472058 }
20482059
2049 const err_offset: u32 = @intCast(errUnionErrorOffset(payload_ty, mod));
2060 const err_offset: u32 = @intCast(errUnionErrorOffset(payload_ty, pt));
20502061 switch (try error_union_bind.resolveToMcv(self)) {
20512062 .register => {
20522063 var operand_reg: Register = undefined;
......@@ -2068,7 +2079,7 @@ fn errUnionErr(
20682079 );
20692080
20702081 const err_bit_offset = err_offset * 8;
2071 const err_bit_size: u32 = @intCast(err_ty.abiSize(mod) * 8);
2082 const err_bit_size: u32 = @intCast(err_ty.abiSize(pt) * 8);
20722083
20732084 _ = try self.addInst(.{
20742085 .tag = .ubfx, // errors are unsigned integers
......@@ -2113,17 +2124,18 @@ fn errUnionPayload(
21132124 error_union_ty: Type,
21142125 maybe_inst: ?Air.Inst.Index,
21152126) !MCValue {
2116 const mod = self.bin_file.comp.module.?;
2127 const pt = self.pt;
2128 const mod = pt.zcu;
21172129 const err_ty = error_union_ty.errorUnionSet(mod);
21182130 const payload_ty = error_union_ty.errorUnionPayload(mod);
21192131 if (err_ty.errorSetIsEmpty(mod)) {
21202132 return try error_union_bind.resolveToMcv(self);
21212133 }
2122 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
2134 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
21232135 return MCValue.none;
21242136 }
21252137
2126 const payload_offset: u32 = @intCast(errUnionPayloadOffset(payload_ty, mod));
2138 const payload_offset: u32 = @intCast(errUnionPayloadOffset(payload_ty, pt));
21272139 switch (try error_union_bind.resolveToMcv(self)) {
21282140 .register => {
21292141 var operand_reg: Register = undefined;
......@@ -2145,7 +2157,7 @@ fn errUnionPayload(
21452157 );
21462158
21472159 const payload_bit_offset = payload_offset * 8;
2148 const payload_bit_size: u32 = @intCast(payload_ty.abiSize(mod) * 8);
2160 const payload_bit_size: u32 = @intCast(payload_ty.abiSize(pt) * 8);
21492161
21502162 _ = try self.addInst(.{
21512163 .tag = if (payload_ty.isSignedInt(mod)) Mir.Inst.Tag.sbfx else .ubfx,
......@@ -2223,20 +2235,21 @@ fn airSaveErrReturnTraceIndex(self: *Self, inst: Air.Inst.Index) !void {
22232235
22242236/// T to E!T
22252237fn airWrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) !void {
2226 const mod = self.bin_file.comp.module.?;
2238 const pt = self.pt;
2239 const mod = pt.zcu;
22272240 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
22282241 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
22292242 const error_union_ty = ty_op.ty.toType();
22302243 const error_ty = error_union_ty.errorUnionSet(mod);
22312244 const payload_ty = error_union_ty.errorUnionPayload(mod);
22322245 const operand = try self.resolveInst(ty_op.operand);
2233 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result operand;
2246 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result operand;
22342247
2235 const abi_size: u32 = @intCast(error_union_ty.abiSize(mod));
2236 const abi_align = error_union_ty.abiAlignment(mod);
2248 const abi_size: u32 = @intCast(error_union_ty.abiSize(pt));
2249 const abi_align = error_union_ty.abiAlignment(pt);
22372250 const stack_offset: u32 = @intCast(try self.allocMem(abi_size, abi_align, inst));
2238 const payload_off = errUnionPayloadOffset(payload_ty, mod);
2239 const err_off = errUnionErrorOffset(payload_ty, mod);
2251 const payload_off = errUnionPayloadOffset(payload_ty, pt);
2252 const err_off = errUnionErrorOffset(payload_ty, pt);
22402253 try self.genSetStack(payload_ty, stack_offset - @as(u32, @intCast(payload_off)), operand);
22412254 try self.genSetStack(error_ty, stack_offset - @as(u32, @intCast(err_off)), .{ .immediate = 0 });
22422255
......@@ -2247,20 +2260,21 @@ fn airWrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) !void {
22472260
22482261/// E to E!T
22492262fn airWrapErrUnionErr(self: *Self, inst: Air.Inst.Index) !void {
2250 const mod = self.bin_file.comp.module.?;
2263 const pt = self.pt;
2264 const mod = pt.zcu;
22512265 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
22522266 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
22532267 const error_union_ty = ty_op.ty.toType();
22542268 const error_ty = error_union_ty.errorUnionSet(mod);
22552269 const payload_ty = error_union_ty.errorUnionPayload(mod);
22562270 const operand = try self.resolveInst(ty_op.operand);
2257 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result operand;
2271 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result operand;
22582272
2259 const abi_size: u32 = @intCast(error_union_ty.abiSize(mod));
2260 const abi_align = error_union_ty.abiAlignment(mod);
2273 const abi_size: u32 = @intCast(error_union_ty.abiSize(pt));
2274 const abi_align = error_union_ty.abiAlignment(pt);
22612275 const stack_offset: u32 = @intCast(try self.allocMem(abi_size, abi_align, inst));
2262 const payload_off = errUnionPayloadOffset(payload_ty, mod);
2263 const err_off = errUnionErrorOffset(payload_ty, mod);
2276 const payload_off = errUnionPayloadOffset(payload_ty, pt);
2277 const err_off = errUnionErrorOffset(payload_ty, pt);
22642278 try self.genSetStack(error_ty, stack_offset - @as(u32, @intCast(err_off)), operand);
22652279 try self.genSetStack(payload_ty, stack_offset - @as(u32, @intCast(payload_off)), .undef);
22662280
......@@ -2364,9 +2378,10 @@ fn ptrElemVal(
23642378 ptr_ty: Type,
23652379 maybe_inst: ?Air.Inst.Index,
23662380) !MCValue {
2367 const mod = self.bin_file.comp.module.?;
2381 const pt = self.pt;
2382 const mod = pt.zcu;
23682383 const elem_ty = ptr_ty.childType(mod);
2369 const elem_size: u32 = @intCast(elem_ty.abiSize(mod));
2384 const elem_size: u32 = @intCast(elem_ty.abiSize(pt));
23702385
23712386 switch (elem_size) {
23722387 1, 4 => {
......@@ -2423,7 +2438,8 @@ fn ptrElemVal(
24232438}
24242439
24252440fn airSliceElemVal(self: *Self, inst: Air.Inst.Index) !void {
2426 const mod = self.bin_file.comp.module.?;
2441 const pt = self.pt;
2442 const mod = pt.zcu;
24272443 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
24282444 const slice_ty = self.typeOf(bin_op.lhs);
24292445 const result: MCValue = if (!slice_ty.isVolatilePtr(mod) and self.liveness.isUnused(inst)) .dead else result: {
......@@ -2466,7 +2482,8 @@ fn arrayElemVal(
24662482 array_ty: Type,
24672483 maybe_inst: ?Air.Inst.Index,
24682484) InnerError!MCValue {
2469 const mod = self.bin_file.comp.module.?;
2485 const pt = self.pt;
2486 const mod = pt.zcu;
24702487 const elem_ty = array_ty.childType(mod);
24712488
24722489 const mcv = try array_bind.resolveToMcv(self);
......@@ -2501,7 +2518,7 @@ fn arrayElemVal(
25012518
25022519 const base_bind: ReadArg.Bind = .{ .mcv = ptr_to_mcv };
25032520
2504 const ptr_ty = try mod.singleMutPtrType(elem_ty);
2521 const ptr_ty = try pt.singleMutPtrType(elem_ty);
25052522
25062523 return try self.ptrElemVal(base_bind, index_bind, ptr_ty, maybe_inst);
25072524 },
......@@ -2522,7 +2539,8 @@ fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
25222539}
25232540
25242541fn airPtrElemVal(self: *Self, inst: Air.Inst.Index) !void {
2525 const mod = self.bin_file.comp.module.?;
2542 const pt = self.pt;
2543 const mod = pt.zcu;
25262544 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
25272545 const ptr_ty = self.typeOf(bin_op.lhs);
25282546 const result: MCValue = if (!ptr_ty.isVolatilePtr(mod) and self.liveness.isUnused(inst)) .dead else result: {
......@@ -2656,9 +2674,10 @@ fn reuseOperand(
26562674}
26572675
26582676fn load(self: *Self, dst_mcv: MCValue, ptr: MCValue, ptr_ty: Type) InnerError!void {
2659 const mod = self.bin_file.comp.module.?;
2677 const pt = self.pt;
2678 const mod = pt.zcu;
26602679 const elem_ty = ptr_ty.childType(mod);
2661 const elem_size: u32 = @intCast(elem_ty.abiSize(mod));
2680 const elem_size: u32 = @intCast(elem_ty.abiSize(pt));
26622681
26632682 switch (ptr) {
26642683 .none => unreachable,
......@@ -2733,11 +2752,12 @@ fn load(self: *Self, dst_mcv: MCValue, ptr: MCValue, ptr_ty: Type) InnerError!vo
27332752}
27342753
27352754fn airLoad(self: *Self, inst: Air.Inst.Index) !void {
2736 const mod = self.bin_file.comp.module.?;
2755 const pt = self.pt;
2756 const mod = pt.zcu;
27372757 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
27382758 const elem_ty = self.typeOfIndex(inst);
27392759 const result: MCValue = result: {
2740 if (!elem_ty.hasRuntimeBits(mod))
2760 if (!elem_ty.hasRuntimeBits(pt))
27412761 break :result MCValue.none;
27422762
27432763 const ptr = try self.resolveInst(ty_op.operand);
......@@ -2746,7 +2766,7 @@ fn airLoad(self: *Self, inst: Air.Inst.Index) !void {
27462766 break :result MCValue.dead;
27472767
27482768 const dest_mcv: MCValue = blk: {
2749 const ptr_fits_dest = elem_ty.abiSize(mod) <= 4;
2769 const ptr_fits_dest = elem_ty.abiSize(pt) <= 4;
27502770 if (ptr_fits_dest and self.reuseOperand(inst, ty_op.operand, 0, ptr)) {
27512771 // The MCValue that holds the pointer can be re-used as the value.
27522772 break :blk ptr;
......@@ -2762,8 +2782,8 @@ fn airLoad(self: *Self, inst: Air.Inst.Index) !void {
27622782}
27632783
27642784fn store(self: *Self, ptr: MCValue, value: MCValue, ptr_ty: Type, value_ty: Type) InnerError!void {
2765 const mod = self.bin_file.comp.module.?;
2766 const elem_size: u32 = @intCast(value_ty.abiSize(mod));
2785 const pt = self.pt;
2786 const elem_size: u32 = @intCast(value_ty.abiSize(pt));
27672787
27682788 switch (ptr) {
27692789 .none => unreachable,
......@@ -2882,11 +2902,12 @@ fn airStructFieldPtrIndex(self: *Self, inst: Air.Inst.Index, index: u8) !void {
28822902
28832903fn structFieldPtr(self: *Self, inst: Air.Inst.Index, operand: Air.Inst.Ref, index: u32) !MCValue {
28842904 return if (self.liveness.isUnused(inst)) .dead else result: {
2885 const mod = self.bin_file.comp.module.?;
2905 const pt = self.pt;
2906 const mod = pt.zcu;
28862907 const mcv = try self.resolveInst(operand);
28872908 const ptr_ty = self.typeOf(operand);
28882909 const struct_ty = ptr_ty.childType(mod);
2889 const struct_field_offset: u32 = @intCast(struct_ty.structFieldOffset(index, mod));
2910 const struct_field_offset: u32 = @intCast(struct_ty.structFieldOffset(index, pt));
28902911 switch (mcv) {
28912912 .ptr_stack_offset => |off| {
28922913 break :result MCValue{ .ptr_stack_offset = off - struct_field_offset };
......@@ -2906,11 +2927,12 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
29062927 const extra = self.air.extraData(Air.StructField, ty_pl.payload).data;
29072928 const operand = extra.struct_operand;
29082929 const index = extra.field_index;
2909 const mod = self.bin_file.comp.module.?;
2930 const pt = self.pt;
2931 const mod = pt.zcu;
29102932 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
29112933 const mcv = try self.resolveInst(operand);
29122934 const struct_ty = self.typeOf(operand);
2913 const struct_field_offset: u32 = @intCast(struct_ty.structFieldOffset(index, mod));
2935 const struct_field_offset: u32 = @intCast(struct_ty.structFieldOffset(index, pt));
29142936 const struct_field_ty = struct_ty.structFieldType(index, mod);
29152937
29162938 switch (mcv) {
......@@ -2974,7 +2996,7 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
29742996 );
29752997
29762998 const field_bit_offset = struct_field_offset * 8;
2977 const field_bit_size: u32 = @intCast(struct_field_ty.abiSize(mod) * 8);
2999 const field_bit_size: u32 = @intCast(struct_field_ty.abiSize(pt) * 8);
29783000
29793001 _ = try self.addInst(.{
29803002 .tag = if (struct_field_ty.isSignedInt(mod)) Mir.Inst.Tag.sbfx else .ubfx,
......@@ -2996,7 +3018,8 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
29963018}
29973019
29983020fn airFieldParentPtr(self: *Self, inst: Air.Inst.Index) !void {
2999 const mod = self.bin_file.comp.module.?;
3021 const pt = self.pt;
3022 const mod = pt.zcu;
30003023 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
30013024 const extra = self.air.extraData(Air.FieldParentPtr, ty_pl.payload).data;
30023025 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
......@@ -3007,7 +3030,7 @@ fn airFieldParentPtr(self: *Self, inst: Air.Inst.Index) !void {
30073030 return self.fail("TODO implement @fieldParentPtr codegen for unions", .{});
30083031 }
30093032
3010 const struct_field_offset: u32 = @intCast(struct_ty.structFieldOffset(extra.field_index, mod));
3033 const struct_field_offset: u32 = @intCast(struct_ty.structFieldOffset(extra.field_index, pt));
30113034 switch (field_ptr) {
30123035 .ptr_stack_offset => |off| {
30133036 break :result MCValue{ .ptr_stack_offset = off + struct_field_offset };
......@@ -3390,7 +3413,8 @@ fn addSub(
33903413 rhs_ty: Type,
33913414 maybe_inst: ?Air.Inst.Index,
33923415) InnerError!MCValue {
3393 const mod = self.bin_file.comp.module.?;
3416 const pt = self.pt;
3417 const mod = pt.zcu;
33943418 switch (lhs_ty.zigTypeTag(mod)) {
33953419 .Float => return self.fail("TODO ARM binary operations on floats", .{}),
33963420 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
......@@ -3446,7 +3470,8 @@ fn mul(
34463470 rhs_ty: Type,
34473471 maybe_inst: ?Air.Inst.Index,
34483472) InnerError!MCValue {
3449 const mod = self.bin_file.comp.module.?;
3473 const pt = self.pt;
3474 const mod = pt.zcu;
34503475 switch (lhs_ty.zigTypeTag(mod)) {
34513476 .Float => return self.fail("TODO ARM binary operations on floats", .{}),
34523477 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
......@@ -3479,7 +3504,8 @@ fn divFloat(
34793504 _ = rhs_ty;
34803505 _ = maybe_inst;
34813506
3482 const mod = self.bin_file.comp.module.?;
3507 const pt = self.pt;
3508 const mod = pt.zcu;
34833509 switch (lhs_ty.zigTypeTag(mod)) {
34843510 .Float => return self.fail("TODO ARM binary operations on floats", .{}),
34853511 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
......@@ -3495,7 +3521,8 @@ fn divTrunc(
34953521 rhs_ty: Type,
34963522 maybe_inst: ?Air.Inst.Index,
34973523) InnerError!MCValue {
3498 const mod = self.bin_file.comp.module.?;
3524 const pt = self.pt;
3525 const mod = pt.zcu;
34993526 switch (lhs_ty.zigTypeTag(mod)) {
35003527 .Float => return self.fail("TODO ARM binary operations on floats", .{}),
35013528 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
......@@ -3538,7 +3565,8 @@ fn divFloor(
35383565 rhs_ty: Type,
35393566 maybe_inst: ?Air.Inst.Index,
35403567) InnerError!MCValue {
3541 const mod = self.bin_file.comp.module.?;
3568 const pt = self.pt;
3569 const mod = pt.zcu;
35423570 switch (lhs_ty.zigTypeTag(mod)) {
35433571 .Float => return self.fail("TODO ARM binary operations on floats", .{}),
35443572 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
......@@ -3586,7 +3614,8 @@ fn divExact(
35863614 _ = rhs_ty;
35873615 _ = maybe_inst;
35883616
3589 const mod = self.bin_file.comp.module.?;
3617 const pt = self.pt;
3618 const mod = pt.zcu;
35903619 switch (lhs_ty.zigTypeTag(mod)) {
35913620 .Float => return self.fail("TODO ARM binary operations on floats", .{}),
35923621 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
......@@ -3603,7 +3632,8 @@ fn rem(
36033632 rhs_ty: Type,
36043633 maybe_inst: ?Air.Inst.Index,
36053634) InnerError!MCValue {
3606 const mod = self.bin_file.comp.module.?;
3635 const pt = self.pt;
3636 const mod = pt.zcu;
36073637 switch (lhs_ty.zigTypeTag(mod)) {
36083638 .Float => return self.fail("TODO ARM binary operations on floats", .{}),
36093639 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
......@@ -3672,7 +3702,8 @@ fn modulo(
36723702 _ = rhs_ty;
36733703 _ = maybe_inst;
36743704
3675 const mod = self.bin_file.comp.module.?;
3705 const pt = self.pt;
3706 const mod = pt.zcu;
36763707 switch (lhs_ty.zigTypeTag(mod)) {
36773708 .Float => return self.fail("TODO ARM binary operations on floats", .{}),
36783709 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
......@@ -3690,7 +3721,8 @@ fn wrappingArithmetic(
36903721 rhs_ty: Type,
36913722 maybe_inst: ?Air.Inst.Index,
36923723) InnerError!MCValue {
3693 const mod = self.bin_file.comp.module.?;
3724 const pt = self.pt;
3725 const mod = pt.zcu;
36943726 switch (lhs_ty.zigTypeTag(mod)) {
36953727 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
36963728 .Int => {
......@@ -3728,7 +3760,8 @@ fn bitwise(
37283760 rhs_ty: Type,
37293761 maybe_inst: ?Air.Inst.Index,
37303762) InnerError!MCValue {
3731 const mod = self.bin_file.comp.module.?;
3763 const pt = self.pt;
3764 const mod = pt.zcu;
37323765 switch (lhs_ty.zigTypeTag(mod)) {
37333766 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
37343767 .Int => {
......@@ -3773,7 +3806,8 @@ fn shiftExact(
37733806 rhs_ty: Type,
37743807 maybe_inst: ?Air.Inst.Index,
37753808) InnerError!MCValue {
3776 const mod = self.bin_file.comp.module.?;
3809 const pt = self.pt;
3810 const mod = pt.zcu;
37773811 switch (lhs_ty.zigTypeTag(mod)) {
37783812 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
37793813 .Int => {
......@@ -3812,7 +3846,8 @@ fn shiftNormal(
38123846 rhs_ty: Type,
38133847 maybe_inst: ?Air.Inst.Index,
38143848) InnerError!MCValue {
3815 const mod = self.bin_file.comp.module.?;
3849 const pt = self.pt;
3850 const mod = pt.zcu;
38163851 switch (lhs_ty.zigTypeTag(mod)) {
38173852 .Vector => return self.fail("TODO ARM binary operations on vectors", .{}),
38183853 .Int => {
......@@ -3855,7 +3890,8 @@ fn booleanOp(
38553890 rhs_ty: Type,
38563891 maybe_inst: ?Air.Inst.Index,
38573892) InnerError!MCValue {
3858 const mod = self.bin_file.comp.module.?;
3893 const pt = self.pt;
3894 const mod = pt.zcu;
38593895 switch (lhs_ty.zigTypeTag(mod)) {
38603896 .Bool => {
38613897 const lhs_immediate = try lhs_bind.resolveToImmediate(self);
......@@ -3889,7 +3925,8 @@ fn ptrArithmetic(
38893925 rhs_ty: Type,
38903926 maybe_inst: ?Air.Inst.Index,
38913927) InnerError!MCValue {
3892 const mod = self.bin_file.comp.module.?;
3928 const pt = self.pt;
3929 const mod = pt.zcu;
38933930 switch (lhs_ty.zigTypeTag(mod)) {
38943931 .Pointer => {
38953932 assert(rhs_ty.eql(Type.usize, mod));
......@@ -3899,7 +3936,7 @@ fn ptrArithmetic(
38993936 .One => ptr_ty.childType(mod).childType(mod), // ptr to array, so get array element type
39003937 else => ptr_ty.childType(mod),
39013938 };
3902 const elem_size: u32 = @intCast(elem_ty.abiSize(mod));
3939 const elem_size: u32 = @intCast(elem_ty.abiSize(pt));
39033940
39043941 const base_tag: Air.Inst.Tag = switch (tag) {
39053942 .ptr_add => .add,
......@@ -3926,8 +3963,9 @@ fn ptrArithmetic(
39263963}
39273964
39283965fn genLdrRegister(self: *Self, dest_reg: Register, addr_reg: Register, ty: Type) !void {
3929 const mod = self.bin_file.comp.module.?;
3930 const abi_size = ty.abiSize(mod);
3966 const pt = self.pt;
3967 const mod = pt.zcu;
3968 const abi_size = ty.abiSize(pt);
39313969
39323970 const tag: Mir.Inst.Tag = switch (abi_size) {
39333971 1 => if (ty.isSignedInt(mod)) Mir.Inst.Tag.ldrsb else .ldrb,
......@@ -3961,8 +3999,8 @@ fn genLdrRegister(self: *Self, dest_reg: Register, addr_reg: Register, ty: Type)
39613999}
39624000
39634001fn genStrRegister(self: *Self, source_reg: Register, addr_reg: Register, ty: Type) !void {
3964 const mod = self.bin_file.comp.module.?;
3965 const abi_size = ty.abiSize(mod);
4002 const pt = self.pt;
4003 const abi_size = ty.abiSize(pt);
39664004
39674005 const tag: Mir.Inst.Tag = switch (abi_size) {
39684006 1 => .strb,
......@@ -4168,7 +4206,8 @@ fn airArg(self: *Self, inst: Air.Inst.Index) !void {
41684206 while (self.args[arg_index] == .none) arg_index += 1;
41694207 self.arg_index = arg_index + 1;
41704208
4171 const mod = self.bin_file.comp.module.?;
4209 const pt = self.pt;
4210 const mod = pt.zcu;
41724211 const ty = self.typeOfIndex(inst);
41734212 const tag = self.air.instructions.items(.tag)[@intFromEnum(inst)];
41744213 const src_index = self.air.instructions.items(.data)[@intFromEnum(inst)].arg.src_index;
......@@ -4223,7 +4262,8 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
42234262 const extra = self.air.extraData(Air.Call, pl_op.payload);
42244263 const args: []const Air.Inst.Ref = @ptrCast(self.air.extra[extra.end..][0..extra.data.args_len]);
42254264 const ty = self.typeOf(callee);
4226 const mod = self.bin_file.comp.module.?;
4265 const pt = self.pt;
4266 const mod = pt.zcu;
42274267
42284268 const fn_ty = switch (ty.zigTypeTag(mod)) {
42294269 .Fn => ty,
......@@ -4253,11 +4293,11 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
42534293 const r0_lock: ?RegisterLock = if (info.return_value == .stack_offset) blk: {
42544294 log.debug("airCall: return by reference", .{});
42554295 const ret_ty = fn_ty.fnReturnType(mod);
4256 const ret_abi_size: u32 = @intCast(ret_ty.abiSize(mod));
4257 const ret_abi_align = ret_ty.abiAlignment(mod);
4296 const ret_abi_size: u32 = @intCast(ret_ty.abiSize(pt));
4297 const ret_abi_align = ret_ty.abiAlignment(pt);
42584298 const stack_offset = try self.allocMem(ret_abi_size, ret_abi_align, inst);
42594299
4260 const ptr_ty = try mod.singleMutPtrType(ret_ty);
4300 const ptr_ty = try pt.singleMutPtrType(ret_ty);
42614301 try self.register_manager.getReg(.r0, null);
42624302 try self.genSetReg(ptr_ty, .r0, .{ .ptr_stack_offset = stack_offset });
42634303
......@@ -4293,7 +4333,7 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
42934333
42944334 // Due to incremental compilation, how function calls are generated depends
42954335 // on linking.
4296 if (try self.air.value(callee, mod)) |func_value| {
4336 if (try self.air.value(callee, pt)) |func_value| {
42974337 if (func_value.getFunction(mod)) |func| {
42984338 if (self.bin_file.cast(link.File.Elf)) |elf_file| {
42994339 const sym_index = try elf_file.zigObjectPtr().?.getOrCreateMetadataForDecl(elf_file, func.owner_decl);
......@@ -4374,7 +4414,8 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
43744414}
43754415
43764416fn airRet(self: *Self, inst: Air.Inst.Index) !void {
4377 const mod = self.bin_file.comp.module.?;
4417 const pt = self.pt;
4418 const mod = pt.zcu;
43784419 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
43794420 const operand = try self.resolveInst(un_op);
43804421 const ret_ty = self.fn_type.fnReturnType(mod);
......@@ -4393,7 +4434,7 @@ fn airRet(self: *Self, inst: Air.Inst.Index) !void {
43934434 //
43944435 // self.ret_mcv is an address to where this function
43954436 // should store its result into
4396 const ptr_ty = try mod.singleMutPtrType(ret_ty);
4437 const ptr_ty = try pt.singleMutPtrType(ret_ty);
43974438 try self.store(self.ret_mcv, operand, ptr_ty, ret_ty);
43984439 },
43994440 else => unreachable, // invalid return result
......@@ -4406,7 +4447,8 @@ fn airRet(self: *Self, inst: Air.Inst.Index) !void {
44064447}
44074448
44084449fn airRetLoad(self: *Self, inst: Air.Inst.Index) !void {
4409 const mod = self.bin_file.comp.module.?;
4450 const pt = self.pt;
4451 const mod = pt.zcu;
44104452 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
44114453 const ptr = try self.resolveInst(un_op);
44124454 const ptr_ty = self.typeOf(un_op);
......@@ -4430,8 +4472,8 @@ fn airRetLoad(self: *Self, inst: Air.Inst.Index) !void {
44304472 // location.
44314473 const op_inst = un_op.toIndex().?;
44324474 if (self.air.instructions.items(.tag)[@intFromEnum(op_inst)] != .ret_ptr) {
4433 const abi_size: u32 = @intCast(ret_ty.abiSize(mod));
4434 const abi_align = ret_ty.abiAlignment(mod);
4475 const abi_size: u32 = @intCast(ret_ty.abiSize(pt));
4476 const abi_align = ret_ty.abiAlignment(pt);
44354477
44364478 const offset = try self.allocMem(abi_size, abi_align, null);
44374479
......@@ -4467,11 +4509,12 @@ fn cmp(
44674509 lhs_ty: Type,
44684510 op: math.CompareOperator,
44694511) !MCValue {
4470 const mod = self.bin_file.comp.module.?;
4512 const pt = self.pt;
4513 const mod = pt.zcu;
44714514 const int_ty = switch (lhs_ty.zigTypeTag(mod)) {
44724515 .Optional => blk: {
44734516 const payload_ty = lhs_ty.optionalChild(mod);
4474 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4517 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
44754518 break :blk Type.u1;
44764519 } else if (lhs_ty.isPtrLikeOptional(mod)) {
44774520 break :blk Type.usize;
......@@ -4573,7 +4616,8 @@ fn airDbgStmt(self: *Self, inst: Air.Inst.Index) !void {
45734616}
45744617
45754618fn airDbgInlineBlock(self: *Self, inst: Air.Inst.Index) !void {
4576 const mod = self.bin_file.comp.module.?;
4619 const pt = self.pt;
4620 const mod = pt.zcu;
45774621 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
45784622 const extra = self.air.extraData(Air.DbgInlineBlock, ty_pl.payload);
45794623 const func = mod.funcInfo(extra.data.func);
......@@ -4785,9 +4829,10 @@ fn isNull(
47854829 operand_bind: ReadArg.Bind,
47864830 operand_ty: Type,
47874831) !MCValue {
4788 const mod = self.bin_file.comp.module.?;
4832 const pt = self.pt;
4833 const mod = pt.zcu;
47894834 if (operand_ty.isPtrLikeOptional(mod)) {
4790 assert(operand_ty.abiSize(mod) == 4);
4835 assert(operand_ty.abiSize(pt) == 4);
47914836
47924837 const imm_bind: ReadArg.Bind = .{ .mcv = .{ .immediate = 0 } };
47934838 return self.cmp(operand_bind, imm_bind, Type.usize, .eq);
......@@ -4819,7 +4864,8 @@ fn airIsNull(self: *Self, inst: Air.Inst.Index) !void {
48194864}
48204865
48214866fn airIsNullPtr(self: *Self, inst: Air.Inst.Index) !void {
4822 const mod = self.bin_file.comp.module.?;
4867 const pt = self.pt;
4868 const mod = pt.zcu;
48234869 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
48244870 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
48254871 const operand_ptr = try self.resolveInst(un_op);
......@@ -4846,7 +4892,8 @@ fn airIsNonNull(self: *Self, inst: Air.Inst.Index) !void {
48464892}
48474893
48484894fn airIsNonNullPtr(self: *Self, inst: Air.Inst.Index) !void {
4849 const mod = self.bin_file.comp.module.?;
4895 const pt = self.pt;
4896 const mod = pt.zcu;
48504897 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
48514898 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
48524899 const operand_ptr = try self.resolveInst(un_op);
......@@ -4866,7 +4913,8 @@ fn isErr(
48664913 error_union_bind: ReadArg.Bind,
48674914 error_union_ty: Type,
48684915) !MCValue {
4869 const mod = self.bin_file.comp.module.?;
4916 const pt = self.pt;
4917 const mod = pt.zcu;
48704918 const error_type = error_union_ty.errorUnionSet(mod);
48714919
48724920 if (error_type.errorSetIsEmpty(mod)) {
......@@ -4908,7 +4956,8 @@ fn airIsErr(self: *Self, inst: Air.Inst.Index) !void {
49084956}
49094957
49104958fn airIsErrPtr(self: *Self, inst: Air.Inst.Index) !void {
4911 const mod = self.bin_file.comp.module.?;
4959 const pt = self.pt;
4960 const mod = pt.zcu;
49124961 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
49134962 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
49144963 const operand_ptr = try self.resolveInst(un_op);
......@@ -4935,7 +4984,8 @@ fn airIsNonErr(self: *Self, inst: Air.Inst.Index) !void {
49354984}
49364985
49374986fn airIsNonErrPtr(self: *Self, inst: Air.Inst.Index) !void {
4938 const mod = self.bin_file.comp.module.?;
4987 const pt = self.pt;
4988 const mod = pt.zcu;
49394989 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
49404990 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
49414991 const operand_ptr = try self.resolveInst(un_op);
......@@ -5154,10 +5204,10 @@ fn airBr(self: *Self, inst: Air.Inst.Index) !void {
51545204}
51555205
51565206fn br(self: *Self, block: Air.Inst.Index, operand: Air.Inst.Ref) !void {
5157 const mod = self.bin_file.comp.module.?;
5207 const pt = self.pt;
51585208 const block_data = self.blocks.getPtr(block).?;
51595209
5160 if (self.typeOf(operand).hasRuntimeBits(mod)) {
5210 if (self.typeOf(operand).hasRuntimeBits(pt)) {
51615211 const operand_mcv = try self.resolveInst(operand);
51625212 const block_mcv = block_data.mcv;
51635213 if (block_mcv == .none) {
......@@ -5325,8 +5375,9 @@ fn setRegOrMem(self: *Self, ty: Type, loc: MCValue, val: MCValue) !void {
53255375}
53265376
53275377fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerError!void {
5328 const mod = self.bin_file.comp.module.?;
5329 const abi_size: u32 = @intCast(ty.abiSize(mod));
5378 const pt = self.pt;
5379 const mod = pt.zcu;
5380 const abi_size: u32 = @intCast(ty.abiSize(pt));
53305381 switch (mcv) {
53315382 .dead => unreachable,
53325383 .unreach, .none => return, // Nothing to do.
......@@ -5407,7 +5458,7 @@ fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerErro
54075458 try self.genSetStack(wrapped_ty, stack_offset, .{ .register = reg });
54085459
54095460 const overflow_bit_ty = ty.structFieldType(1, mod);
5410 const overflow_bit_offset: u32 = @intCast(ty.structFieldOffset(1, mod));
5461 const overflow_bit_offset: u32 = @intCast(ty.structFieldOffset(1, pt));
54115462 const cond_reg = try self.register_manager.allocReg(null, gp);
54125463
54135464 // C flag: movcs reg, #1
......@@ -5445,7 +5496,7 @@ fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerErro
54455496 const reg = try self.copyToTmpRegister(ty, mcv);
54465497 return self.genSetStack(ty, stack_offset, MCValue{ .register = reg });
54475498 } else {
5448 const ptr_ty = try mod.singleMutPtrType(ty);
5499 const ptr_ty = try pt.singleMutPtrType(ty);
54495500
54505501 // TODO call extern memcpy
54515502 const regs = try self.register_manager.allocRegs(5, .{ null, null, null, null, null }, gp);
......@@ -5487,7 +5538,8 @@ fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerErro
54875538}
54885539
54895540fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void {
5490 const mod = self.bin_file.comp.module.?;
5541 const pt = self.pt;
5542 const mod = pt.zcu;
54915543 switch (mcv) {
54925544 .dead => unreachable,
54935545 .unreach, .none => return, // Nothing to do.
......@@ -5662,7 +5714,7 @@ fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void
56625714 },
56635715 .stack_offset => |off| {
56645716 // TODO: maybe addressing from sp instead of fp
5665 const abi_size: u32 = @intCast(ty.abiSize(mod));
5717 const abi_size: u32 = @intCast(ty.abiSize(pt));
56665718
56675719 const tag: Mir.Inst.Tag = switch (abi_size) {
56685720 1 => if (ty.isSignedInt(mod)) Mir.Inst.Tag.ldrsb else .ldrb,
......@@ -5713,7 +5765,7 @@ fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void
57135765 }
57145766 },
57155767 .stack_argument_offset => |off| {
5716 const abi_size = ty.abiSize(mod);
5768 const abi_size = ty.abiSize(pt);
57175769
57185770 const tag: Mir.Inst.Tag = switch (abi_size) {
57195771 1 => if (ty.isSignedInt(mod)) Mir.Inst.Tag.ldrsb_stack_argument else .ldrb_stack_argument,
......@@ -5734,8 +5786,8 @@ fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void
57345786}
57355787
57365788fn genSetStackArgument(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerError!void {
5737 const mod = self.bin_file.comp.module.?;
5738 const abi_size: u32 = @intCast(ty.abiSize(mod));
5789 const pt = self.pt;
5790 const abi_size: u32 = @intCast(ty.abiSize(pt));
57395791 switch (mcv) {
57405792 .dead => unreachable,
57415793 .none, .unreach => return,
......@@ -5802,7 +5854,7 @@ fn genSetStackArgument(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) I
58025854 const reg = try self.copyToTmpRegister(ty, mcv);
58035855 return self.genSetStackArgument(ty, stack_offset, MCValue{ .register = reg });
58045856 } else {
5805 const ptr_ty = try mod.singleMutPtrType(ty);
5857 const ptr_ty = try pt.singleMutPtrType(ty);
58065858
58075859 // TODO call extern memcpy
58085860 const regs = try self.register_manager.allocRegs(5, .{ null, null, null, null, null }, gp);
......@@ -5890,7 +5942,8 @@ fn airBitCast(self: *Self, inst: Air.Inst.Index) !void {
58905942}
58915943
58925944fn airArrayToSlice(self: *Self, inst: Air.Inst.Index) !void {
5893 const mod = self.bin_file.comp.module.?;
5945 const pt = self.pt;
5946 const mod = pt.zcu;
58945947 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
58955948 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
58965949 const ptr_ty = self.typeOf(ty_op.operand);
......@@ -6009,7 +6062,8 @@ fn airReduce(self: *Self, inst: Air.Inst.Index) !void {
60096062}
60106063
60116064fn airAggregateInit(self: *Self, inst: Air.Inst.Index) !void {
6012 const mod = self.bin_file.comp.module.?;
6065 const pt = self.pt;
6066 const mod = pt.zcu;
60136067 const vector_ty = self.typeOfIndex(inst);
60146068 const len = vector_ty.vectorLen(mod);
60156069 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
......@@ -6054,15 +6108,15 @@ fn airMulAdd(self: *Self, inst: Air.Inst.Index) !void {
60546108}
60556109
60566110fn airTry(self: *Self, inst: Air.Inst.Index) !void {
6111 const pt = self.pt;
60576112 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
60586113 const extra = self.air.extraData(Air.Try, pl_op.payload);
60596114 const body: []const Air.Inst.Index = @ptrCast(self.air.extra[extra.end..][0..extra.data.body_len]);
60606115 const result: MCValue = result: {
60616116 const error_union_bind: ReadArg.Bind = .{ .inst = pl_op.operand };
60626117 const error_union_ty = self.typeOf(pl_op.operand);
6063 const mod = self.bin_file.comp.module.?;
6064 const error_union_size: u32 = @intCast(error_union_ty.abiSize(mod));
6065 const error_union_align = error_union_ty.abiAlignment(mod);
6118 const error_union_size: u32 = @intCast(error_union_ty.abiSize(pt));
6119 const error_union_align = error_union_ty.abiAlignment(pt);
60666120
60676121 // The error union will die in the body. However, we need the
60686122 // error union after the body in order to extract the payload
......@@ -6091,14 +6145,15 @@ fn airTryPtr(self: *Self, inst: Air.Inst.Index) !void {
60916145}
60926146
60936147fn resolveInst(self: *Self, inst: Air.Inst.Ref) InnerError!MCValue {
6094 const mod = self.bin_file.comp.module.?;
6148 const pt = self.pt;
6149 const mod = pt.zcu;
60956150
60966151 // If the type has no codegen bits, no need to store it.
60976152 const inst_ty = self.typeOf(inst);
6098 if (!inst_ty.hasRuntimeBitsIgnoreComptime(mod) and !inst_ty.isError(mod))
6153 if (!inst_ty.hasRuntimeBitsIgnoreComptime(pt) and !inst_ty.isError(mod))
60996154 return MCValue{ .none = {} };
61006155
6101 const inst_index = inst.toIndex() orelse return self.genTypedValue((try self.air.value(inst, mod)).?);
6156 const inst_index = inst.toIndex() orelse return self.genTypedValue((try self.air.value(inst, pt)).?);
61026157
61036158 return self.getResolvedInstValue(inst_index);
61046159}
......@@ -6116,12 +6171,13 @@ fn getResolvedInstValue(self: *Self, inst: Air.Inst.Index) MCValue {
61166171}
61176172
61186173fn genTypedValue(self: *Self, val: Value) InnerError!MCValue {
6119 const mod = self.bin_file.comp.module.?;
6174 const pt = self.pt;
61206175 const mcv: MCValue = switch (try codegen.genTypedValue(
61216176 self.bin_file,
6177 pt,
61226178 self.src_loc,
61236179 val,
6124 mod.funcOwnerDeclIndex(self.func_index),
6180 pt.zcu.funcOwnerDeclIndex(self.func_index),
61256181 )) {
61266182 .mcv => |mcv| switch (mcv) {
61276183 .none => .none,
......@@ -6152,7 +6208,8 @@ const CallMCValues = struct {
61526208
61536209/// Caller must call `CallMCValues.deinit`.
61546210fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
6155 const mod = self.bin_file.comp.module.?;
6211 const pt = self.pt;
6212 const mod = pt.zcu;
61566213 const ip = &mod.intern_pool;
61576214 const fn_info = mod.typeToFunc(fn_ty).?;
61586215 const cc = fn_info.cc;
......@@ -6182,10 +6239,10 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
61826239
61836240 if (ret_ty.zigTypeTag(mod) == .NoReturn) {
61846241 result.return_value = .{ .unreach = {} };
6185 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
6242 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
61866243 result.return_value = .{ .none = {} };
61876244 } else {
6188 const ret_ty_size: u32 = @intCast(ret_ty.abiSize(mod));
6245 const ret_ty_size: u32 = @intCast(ret_ty.abiSize(pt));
61896246 // TODO handle cases where multiple registers are used
61906247 if (ret_ty_size <= 4) {
61916248 result.return_value = .{ .register = c_abi_int_return_regs[0] };
......@@ -6200,10 +6257,10 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
62006257 }
62016258
62026259 for (fn_info.param_types.get(ip), result.args) |ty, *result_arg| {
6203 if (Type.fromInterned(ty).abiAlignment(mod) == .@"8")
6260 if (Type.fromInterned(ty).abiAlignment(pt) == .@"8")
62046261 ncrn = std.mem.alignForward(usize, ncrn, 2);
62056262
6206 const param_size: u32 = @intCast(Type.fromInterned(ty).abiSize(mod));
6263 const param_size: u32 = @intCast(Type.fromInterned(ty).abiSize(pt));
62076264 if (std.math.divCeil(u32, param_size, 4) catch unreachable <= 4 - ncrn) {
62086265 if (param_size <= 4) {
62096266 result_arg.* = .{ .register = c_abi_int_param_regs[ncrn] };
......@@ -6215,7 +6272,7 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
62156272 return self.fail("TODO MCValues split between registers and stack", .{});
62166273 } else {
62176274 ncrn = 4;
6218 if (Type.fromInterned(ty).abiAlignment(mod) == .@"8")
6275 if (Type.fromInterned(ty).abiAlignment(pt) == .@"8")
62196276 nsaa = std.mem.alignForward(u32, nsaa, 8);
62206277
62216278 result_arg.* = .{ .stack_argument_offset = nsaa };
......@@ -6229,10 +6286,10 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
62296286 .Unspecified => {
62306287 if (ret_ty.zigTypeTag(mod) == .NoReturn) {
62316288 result.return_value = .{ .unreach = {} };
6232 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod) and !ret_ty.isError(mod)) {
6289 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt) and !ret_ty.isError(mod)) {
62336290 result.return_value = .{ .none = {} };
62346291 } else {
6235 const ret_ty_size: u32 = @intCast(ret_ty.abiSize(mod));
6292 const ret_ty_size: u32 = @intCast(ret_ty.abiSize(pt));
62366293 if (ret_ty_size == 0) {
62376294 assert(ret_ty.isError(mod));
62386295 result.return_value = .{ .immediate = 0 };
......@@ -6250,9 +6307,9 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
62506307 var stack_offset: u32 = 0;
62516308
62526309 for (fn_info.param_types.get(ip), result.args) |ty, *result_arg| {
6253 if (Type.fromInterned(ty).abiSize(mod) > 0) {
6254 const param_size: u32 = @intCast(Type.fromInterned(ty).abiSize(mod));
6255 const param_alignment = Type.fromInterned(ty).abiAlignment(mod);
6310 if (Type.fromInterned(ty).abiSize(pt) > 0) {
6311 const param_size: u32 = @intCast(Type.fromInterned(ty).abiSize(pt));
6312 const param_alignment = Type.fromInterned(ty).abiAlignment(pt);
62566313
62576314 stack_offset = @intCast(param_alignment.forward(stack_offset));
62586315 result_arg.* = .{ .stack_argument_offset = stack_offset };
......@@ -6271,7 +6328,7 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type) !CallMCValues {
62716328 return result;
62726329}
62736330
6274/// TODO support scope overrides. Also note this logic is duplicated with `Module.wantSafety`.
6331/// TODO support scope overrides. Also note this logic is duplicated with `Zcu.wantSafety`.
62756332fn wantSafety(self: *Self) bool {
62766333 return switch (self.bin_file.comp.root_mod.optimize_mode) {
62776334 .Debug => true,
......@@ -6305,11 +6362,9 @@ fn parseRegName(name: []const u8) ?Register {
63056362}
63066363
63076364fn typeOf(self: *Self, inst: Air.Inst.Ref) Type {
6308 const mod = self.bin_file.comp.module.?;
6309 return self.air.typeOf(inst, &mod.intern_pool);
6365 return self.air.typeOf(inst, &self.pt.zcu.intern_pool);
63106366}
63116367
63126368fn typeOfIndex(self: *Self, inst: Air.Inst.Index) Type {
6313 const mod = self.bin_file.comp.module.?;
6314 return self.air.typeOfIndex(inst, &mod.intern_pool);
6369 return self.air.typeOfIndex(inst, &self.pt.zcu.intern_pool);
63156370}
src/arch/arm/Emit.zig+2-4
......@@ -9,10 +9,8 @@ const Mir = @import("Mir.zig");
99const bits = @import("bits.zig");
1010const link = @import("../../link.zig");
1111const Zcu = @import("../../Zcu.zig");
12/// Deprecated.
13const Module = Zcu;
1412const Type = @import("../../Type.zig");
15const ErrorMsg = Module.ErrorMsg;
13const ErrorMsg = Zcu.ErrorMsg;
1614const Target = std.Target;
1715const assert = std.debug.assert;
1816const Instruction = bits.Instruction;
......@@ -26,7 +24,7 @@ bin_file: *link.File,
2624debug_output: DebugInfoOutput,
2725target: *const std.Target,
2826err_msg: ?*ErrorMsg = null,
29src_loc: Module.LazySrcLoc,
27src_loc: Zcu.LazySrcLoc,
3028code: *std.ArrayList(u8),
3129
3230prev_di_line: u32,
src/arch/arm/abi.zig+30-32
......@@ -5,8 +5,6 @@ const Register = bits.Register;
55const RegisterManagerFn = @import("../../register_manager.zig").RegisterManager;
66const Type = @import("../../Type.zig");
77const Zcu = @import("../../Zcu.zig");
8/// Deprecated.
9const Module = Zcu;
108
119pub const Class = union(enum) {
1210 memory,
......@@ -26,29 +24,29 @@ pub const Class = union(enum) {
2624
2725pub const Context = enum { ret, arg };
2826
29pub fn classifyType(ty: Type, mod: *Module, ctx: Context) Class {
30 assert(ty.hasRuntimeBitsIgnoreComptime(mod));
27pub fn classifyType(ty: Type, pt: Zcu.PerThread, ctx: Context) Class {
28 assert(ty.hasRuntimeBitsIgnoreComptime(pt));
3129
3230 var maybe_float_bits: ?u16 = null;
3331 const max_byval_size = 512;
34 const ip = &mod.intern_pool;
35 switch (ty.zigTypeTag(mod)) {
32 const ip = &pt.zcu.intern_pool;
33 switch (ty.zigTypeTag(pt.zcu)) {
3634 .Struct => {
37 const bit_size = ty.bitSize(mod);
38 if (ty.containerLayout(mod) == .@"packed") {
35 const bit_size = ty.bitSize(pt);
36 if (ty.containerLayout(pt.zcu) == .@"packed") {
3937 if (bit_size > 64) return .memory;
4038 return .byval;
4139 }
4240 if (bit_size > max_byval_size) return .memory;
43 const float_count = countFloats(ty, mod, &maybe_float_bits);
41 const float_count = countFloats(ty, pt.zcu, &maybe_float_bits);
4442 if (float_count <= byval_float_count) return .byval;
4543
46 const fields = ty.structFieldCount(mod);
44 const fields = ty.structFieldCount(pt.zcu);
4745 var i: u32 = 0;
4846 while (i < fields) : (i += 1) {
49 const field_ty = ty.structFieldType(i, mod);
50 const field_alignment = ty.structFieldAlign(i, mod);
51 const field_size = field_ty.bitSize(mod);
47 const field_ty = ty.structFieldType(i, pt.zcu);
48 const field_alignment = ty.structFieldAlign(i, pt);
49 const field_size = field_ty.bitSize(pt);
5250 if (field_size > 32 or field_alignment.compare(.gt, .@"32")) {
5351 return Class.arrSize(bit_size, 64);
5452 }
......@@ -56,19 +54,19 @@ pub fn classifyType(ty: Type, mod: *Module, ctx: Context) Class {
5654 return Class.arrSize(bit_size, 32);
5755 },
5856 .Union => {
59 const bit_size = ty.bitSize(mod);
60 const union_obj = mod.typeToUnion(ty).?;
57 const bit_size = ty.bitSize(pt);
58 const union_obj = pt.zcu.typeToUnion(ty).?;
6159 if (union_obj.getLayout(ip) == .@"packed") {
6260 if (bit_size > 64) return .memory;
6361 return .byval;
6462 }
6563 if (bit_size > max_byval_size) return .memory;
66 const float_count = countFloats(ty, mod, &maybe_float_bits);
64 const float_count = countFloats(ty, pt.zcu, &maybe_float_bits);
6765 if (float_count <= byval_float_count) return .byval;
6866
6967 for (union_obj.field_types.get(ip), 0..) |field_ty, field_index| {
70 if (Type.fromInterned(field_ty).bitSize(mod) > 32 or
71 mod.unionFieldNormalAlignment(union_obj, @intCast(field_index)).compare(.gt, .@"32"))
68 if (Type.fromInterned(field_ty).bitSize(pt) > 32 or
69 pt.unionFieldNormalAlignment(union_obj, @intCast(field_index)).compare(.gt, .@"32"))
7270 {
7371 return Class.arrSize(bit_size, 64);
7472 }
......@@ -79,28 +77,28 @@ pub fn classifyType(ty: Type, mod: *Module, ctx: Context) Class {
7977 .Int => {
8078 // TODO this is incorrect for _BitInt(128) but implementing
8179 // this correctly makes implementing compiler-rt impossible.
82 // const bit_size = ty.bitSize(mod);
80 // const bit_size = ty.bitSize(pt);
8381 // if (bit_size > 64) return .memory;
8482 return .byval;
8583 },
8684 .Enum, .ErrorSet => {
87 const bit_size = ty.bitSize(mod);
85 const bit_size = ty.bitSize(pt);
8886 if (bit_size > 64) return .memory;
8987 return .byval;
9088 },
9189 .Vector => {
92 const bit_size = ty.bitSize(mod);
90 const bit_size = ty.bitSize(pt);
9391 // TODO is this controlled by a cpu feature?
9492 if (ctx == .ret and bit_size > 128) return .memory;
9593 if (bit_size > 512) return .memory;
9694 return .byval;
9795 },
9896 .Optional => {
99 assert(ty.isPtrLikeOptional(mod));
97 assert(ty.isPtrLikeOptional(pt.zcu));
10098 return .byval;
10199 },
102100 .Pointer => {
103 assert(!ty.isSlice(mod));
101 assert(!ty.isSlice(pt.zcu));
104102 return .byval;
105103 },
106104 .ErrorUnion,
......@@ -122,16 +120,16 @@ pub fn classifyType(ty: Type, mod: *Module, ctx: Context) Class {
122120}
123121
124122const byval_float_count = 4;
125fn countFloats(ty: Type, mod: *Module, maybe_float_bits: *?u16) u32 {
126 const ip = &mod.intern_pool;
127 const target = mod.getTarget();
123fn countFloats(ty: Type, zcu: *Zcu, maybe_float_bits: *?u16) u32 {
124 const ip = &zcu.intern_pool;
125 const target = zcu.getTarget();
128126 const invalid = std.math.maxInt(u32);
129 switch (ty.zigTypeTag(mod)) {
127 switch (ty.zigTypeTag(zcu)) {
130128 .Union => {
131 const union_obj = mod.typeToUnion(ty).?;
129 const union_obj = zcu.typeToUnion(ty).?;
132130 var max_count: u32 = 0;
133131 for (union_obj.field_types.get(ip)) |field_ty| {
134 const field_count = countFloats(Type.fromInterned(field_ty), mod, maybe_float_bits);
132 const field_count = countFloats(Type.fromInterned(field_ty), zcu, maybe_float_bits);
135133 if (field_count == invalid) return invalid;
136134 if (field_count > max_count) max_count = field_count;
137135 if (max_count > byval_float_count) return invalid;
......@@ -139,12 +137,12 @@ fn countFloats(ty: Type, mod: *Module, maybe_float_bits: *?u16) u32 {
139137 return max_count;
140138 },
141139 .Struct => {
142 const fields_len = ty.structFieldCount(mod);
140 const fields_len = ty.structFieldCount(zcu);
143141 var count: u32 = 0;
144142 var i: u32 = 0;
145143 while (i < fields_len) : (i += 1) {
146 const field_ty = ty.structFieldType(i, mod);
147 const field_count = countFloats(field_ty, mod, maybe_float_bits);
144 const field_ty = ty.structFieldType(i, zcu);
145 const field_count = countFloats(field_ty, zcu, maybe_float_bits);
148146 if (field_count == invalid) return invalid;
149147 count += field_count;
150148 if (count > byval_float_count) return invalid;
src/arch/riscv64/CodeGen.zig+267-216
......@@ -46,6 +46,7 @@ const RegisterLock = RegisterManager.RegisterLock;
4646const InnerError = CodeGenError || error{OutOfRegisters};
4747
4848gpa: Allocator,
49pt: Zcu.PerThread,
4950air: Air,
5051mod: *Package.Module,
5152liveness: Liveness,
......@@ -541,14 +542,14 @@ const FrameAlloc = struct {
541542 .ref_count = 0,
542543 };
543544 }
544 fn initType(ty: Type, zcu: *Zcu) FrameAlloc {
545 fn initType(ty: Type, pt: Zcu.PerThread) FrameAlloc {
545546 return init(.{
546 .size = ty.abiSize(zcu),
547 .alignment = ty.abiAlignment(zcu),
547 .size = ty.abiSize(pt),
548 .alignment = ty.abiAlignment(pt),
548549 });
549550 }
550 fn initSpill(ty: Type, zcu: *Zcu) FrameAlloc {
551 const abi_size = ty.abiSize(zcu);
551 fn initSpill(ty: Type, pt: Zcu.PerThread) FrameAlloc {
552 const abi_size = ty.abiSize(pt);
552553 const spill_size = if (abi_size < 8)
553554 math.ceilPowerOfTwoAssert(u64, abi_size)
554555 else
......@@ -556,7 +557,7 @@ const FrameAlloc = struct {
556557 return init(.{
557558 .size = spill_size,
558559 .pad = @intCast(spill_size - abi_size),
559 .alignment = ty.abiAlignment(zcu).maxStrict(
560 .alignment = ty.abiAlignment(pt).maxStrict(
560561 Alignment.fromNonzeroByteUnits(@min(spill_size, 8)),
561562 ),
562563 });
......@@ -696,6 +697,7 @@ const CallView = enum(u1) {
696697
697698pub fn generate(
698699 bin_file: *link.File,
700 pt: Zcu.PerThread,
699701 src_loc: Zcu.LazySrcLoc,
700702 func_index: InternPool.Index,
701703 air: Air,
......@@ -703,9 +705,9 @@ pub fn generate(
703705 code: *std.ArrayList(u8),
704706 debug_output: DebugInfoOutput,
705707) CodeGenError!Result {
706 const comp = bin_file.comp;
707 const gpa = comp.gpa;
708 const zcu = comp.module.?;
708 const zcu = pt.zcu;
709 const comp = zcu.comp;
710 const gpa = zcu.gpa;
709711 const ip = &zcu.intern_pool;
710712 const func = zcu.funcInfo(func_index);
711713 const fn_owner_decl = zcu.declPtr(func.owner_decl);
......@@ -726,6 +728,7 @@ pub fn generate(
726728 var function = Func{
727729 .gpa = gpa,
728730 .air = air,
731 .pt = pt,
729732 .mod = mod,
730733 .liveness = liveness,
731734 .target = target,
......@@ -787,11 +790,11 @@ pub fn generate(
787790 function.args = call_info.args;
788791 function.ret_mcv = call_info.return_value;
789792 function.frame_allocs.set(@intFromEnum(FrameIndex.ret_addr), FrameAlloc.init(.{
790 .size = Type.usize.abiSize(zcu),
791 .alignment = Type.usize.abiAlignment(zcu).min(call_info.stack_align),
793 .size = Type.usize.abiSize(pt),
794 .alignment = Type.usize.abiAlignment(pt).min(call_info.stack_align),
792795 }));
793796 function.frame_allocs.set(@intFromEnum(FrameIndex.base_ptr), FrameAlloc.init(.{
794 .size = Type.usize.abiSize(zcu),
797 .size = Type.usize.abiSize(pt),
795798 .alignment = Alignment.min(
796799 call_info.stack_align,
797800 Alignment.fromNonzeroByteUnits(function.target.stackAlignment()),
......@@ -803,7 +806,7 @@ pub fn generate(
803806 }));
804807 function.frame_allocs.set(@intFromEnum(FrameIndex.spill_frame), FrameAlloc.init(.{
805808 .size = 0,
806 .alignment = Type.usize.abiAlignment(zcu),
809 .alignment = Type.usize.abiAlignment(pt),
807810 }));
808811
809812 function.gen() catch |err| switch (err) {
......@@ -821,9 +824,10 @@ pub fn generate(
821824 };
822825 defer mir.deinit(gpa);
823826
824 var emit = Emit{
827 var emit: Emit = .{
828 .bin_file = bin_file,
825829 .lower = .{
826 .bin_file = bin_file,
830 .pt = pt,
827831 .allocator = gpa,
828832 .mir = mir,
829833 .cc = fn_info.cc,
......@@ -875,10 +879,10 @@ fn formatWipMir(
875879 _: std.fmt.FormatOptions,
876880 writer: anytype,
877881) @TypeOf(writer).Error!void {
878 const comp = data.func.bin_file.comp;
879 const mod = comp.root_mod;
880 var lower = Lower{
881 .bin_file = data.func.bin_file,
882 const pt = data.func.pt;
883 const comp = pt.zcu.comp;
884 var lower: Lower = .{
885 .pt = pt,
882886 .allocator = data.func.gpa,
883887 .mir = .{
884888 .instructions = data.func.mir_instructions.slice(),
......@@ -889,7 +893,7 @@ fn formatWipMir(
889893 .src_loc = data.func.src_loc,
890894 .output_mode = comp.config.output_mode,
891895 .link_mode = comp.config.link_mode,
892 .pic = mod.pic,
896 .pic = comp.root_mod.pic,
893897 };
894898 var first = true;
895899 for ((lower.lowerMir(data.inst) catch |err| switch (err) {
......@@ -933,7 +937,7 @@ fn formatDecl(
933937}
934938fn fmtDecl(func: *Func, decl_index: InternPool.DeclIndex) std.fmt.Formatter(formatDecl) {
935939 return .{ .data = .{
936 .mod = func.bin_file.comp.module.?,
940 .mod = func.pt.zcu,
937941 .decl_index = decl_index,
938942 } };
939943}
......@@ -950,7 +954,7 @@ fn formatAir(
950954) @TypeOf(writer).Error!void {
951955 @import("../../print_air.zig").dumpInst(
952956 data.inst,
953 data.func.bin_file.comp.module.?,
957 data.func.pt,
954958 data.func.air,
955959 data.func.liveness,
956960 );
......@@ -1044,8 +1048,9 @@ const required_features = [_]Target.riscv.Feature{
10441048};
10451049
10461050fn gen(func: *Func) !void {
1047 const mod = func.bin_file.comp.module.?;
1048 const fn_info = mod.typeToFunc(func.fn_type).?;
1051 const pt = func.pt;
1052 const zcu = pt.zcu;
1053 const fn_info = zcu.typeToFunc(func.fn_type).?;
10491054
10501055 inline for (required_features) |feature| {
10511056 if (!func.hasFeature(feature)) {
......@@ -1071,7 +1076,7 @@ fn gen(func: *Func) !void {
10711076 // The address where to store the return value for the caller is in a
10721077 // register which the callee is free to clobber. Therefore, we purposely
10731078 // spill it to stack immediately.
1074 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(Type.usize, mod));
1079 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(Type.usize, pt));
10751080 try func.genSetMem(
10761081 .{ .frame = frame_index },
10771082 0,
......@@ -1205,7 +1210,8 @@ fn gen(func: *Func) !void {
12051210}
12061211
12071212fn genBody(func: *Func, body: []const Air.Inst.Index) InnerError!void {
1208 const zcu = func.bin_file.comp.module.?;
1213 const pt = func.pt;
1214 const zcu = pt.zcu;
12091215 const ip = &zcu.intern_pool;
12101216 const air_tags = func.air.instructions.items(.tag);
12111217
......@@ -1672,44 +1678,46 @@ fn ensureProcessDeathCapacity(func: *Func, additional_count: usize) !void {
16721678}
16731679
16741680fn memSize(func: *Func, ty: Type) Memory.Size {
1675 const mod = func.bin_file.comp.module.?;
1676 return switch (ty.zigTypeTag(mod)) {
1681 const pt = func.pt;
1682 const zcu = pt.zcu;
1683 return switch (ty.zigTypeTag(zcu)) {
16771684 .Float => Memory.Size.fromBitSize(ty.floatBits(func.target.*)),
1678 else => Memory.Size.fromByteSize(ty.abiSize(mod)),
1685 else => Memory.Size.fromByteSize(ty.abiSize(pt)),
16791686 };
16801687}
16811688
16821689fn splitType(func: *Func, ty: Type) ![2]Type {
1683 const zcu = func.bin_file.comp.module.?;
1684 const classes = mem.sliceTo(&abi.classifySystem(ty, zcu), .none);
1690 const pt = func.pt;
1691 const classes = mem.sliceTo(&abi.classifySystem(ty, pt), .none);
16851692 var parts: [2]Type = undefined;
16861693 if (classes.len == 2) for (&parts, classes, 0..) |*part, class, part_i| {
16871694 part.* = switch (class) {
16881695 .integer => switch (part_i) {
16891696 0 => Type.u64,
16901697 1 => part: {
1691 const elem_size = ty.abiAlignment(zcu).minStrict(.@"8").toByteUnits().?;
1692 const elem_ty = try zcu.intType(.unsigned, @intCast(elem_size * 8));
1693 break :part switch (@divExact(ty.abiSize(zcu) - 8, elem_size)) {
1698 const elem_size = ty.abiAlignment(pt).minStrict(.@"8").toByteUnits().?;
1699 const elem_ty = try pt.intType(.unsigned, @intCast(elem_size * 8));
1700 break :part switch (@divExact(ty.abiSize(pt) - 8, elem_size)) {
16941701 1 => elem_ty,
1695 else => |len| try zcu.arrayType(.{ .len = len, .child = elem_ty.toIntern() }),
1702 else => |len| try pt.arrayType(.{ .len = len, .child = elem_ty.toIntern() }),
16961703 };
16971704 },
16981705 else => unreachable,
16991706 },
17001707 else => return func.fail("TODO: splitType class {}", .{class}),
17011708 };
1702 } else if (parts[0].abiSize(zcu) + parts[1].abiSize(zcu) == ty.abiSize(zcu)) return parts;
1703 return func.fail("TODO implement splitType for {}", .{ty.fmt(zcu)});
1709 } else if (parts[0].abiSize(pt) + parts[1].abiSize(pt) == ty.abiSize(pt)) return parts;
1710 return func.fail("TODO implement splitType for {}", .{ty.fmt(pt)});
17041711}
17051712
17061713/// Truncates the value in the register in place.
17071714/// Clobbers any remaining bits.
17081715fn truncateRegister(func: *Func, ty: Type, reg: Register) !void {
1709 const mod = func.bin_file.comp.module.?;
1710 const int_info = if (ty.isAbiInt(mod)) ty.intInfo(mod) else std.builtin.Type.Int{
1716 const pt = func.pt;
1717 const zcu = pt.zcu;
1718 const int_info = if (ty.isAbiInt(zcu)) ty.intInfo(zcu) else std.builtin.Type.Int{
17111719 .signedness = .unsigned,
1712 .bits = @intCast(ty.bitSize(mod)),
1720 .bits = @intCast(ty.bitSize(pt)),
17131721 };
17141722 const shift = math.cast(u6, 64 - int_info.bits % 64) orelse return;
17151723 switch (int_info.signedness) {
......@@ -1780,7 +1788,8 @@ fn truncateRegister(func: *Func, ty: Type, reg: Register) !void {
17801788}
17811789
17821790fn symbolIndex(func: *Func) !u32 {
1783 const zcu = func.bin_file.comp.module.?;
1791 const pt = func.pt;
1792 const zcu = pt.zcu;
17841793 const decl_index = zcu.funcOwnerDeclIndex(func.func_index);
17851794 return switch (func.bin_file.tag) {
17861795 .elf => blk: {
......@@ -1817,19 +1826,21 @@ fn allocFrameIndex(func: *Func, alloc: FrameAlloc) !FrameIndex {
18171826
18181827/// Use a pointer instruction as the basis for allocating stack memory.
18191828fn allocMemPtr(func: *Func, inst: Air.Inst.Index) !FrameIndex {
1820 const zcu = func.bin_file.comp.module.?;
1829 const pt = func.pt;
1830 const zcu = pt.zcu;
18211831 const ptr_ty = func.typeOfIndex(inst);
18221832 const val_ty = ptr_ty.childType(zcu);
18231833 return func.allocFrameIndex(FrameAlloc.init(.{
1824 .size = math.cast(u32, val_ty.abiSize(zcu)) orelse {
1825 return func.fail("type '{}' too big to fit into stack frame", .{val_ty.fmt(zcu)});
1834 .size = math.cast(u32, val_ty.abiSize(pt)) orelse {
1835 return func.fail("type '{}' too big to fit into stack frame", .{val_ty.fmt(pt)});
18261836 },
1827 .alignment = ptr_ty.ptrAlignment(zcu).max(.@"1"),
1837 .alignment = ptr_ty.ptrAlignment(pt).max(.@"1"),
18281838 }));
18291839}
18301840
18311841fn typeRegClass(func: *Func, ty: Type) abi.RegisterClass {
1832 const zcu = func.bin_file.comp.module.?;
1842 const pt = func.pt;
1843 const zcu = pt.zcu;
18331844 return switch (ty.zigTypeTag(zcu)) {
18341845 .Float => .float,
18351846 .Vector => @panic("TODO: typeRegClass for Vectors"),
......@@ -1838,7 +1849,8 @@ fn typeRegClass(func: *Func, ty: Type) abi.RegisterClass {
18381849}
18391850
18401851fn regGeneralClassForType(func: *Func, ty: Type) RegisterManager.RegisterBitSet {
1841 const zcu = func.bin_file.comp.module.?;
1852 const pt = func.pt;
1853 const zcu = pt.zcu;
18421854 return switch (ty.zigTypeTag(zcu)) {
18431855 .Float => abi.Registers.Float.general_purpose,
18441856 .Vector => @panic("TODO: regGeneralClassForType for Vectors"),
......@@ -1847,7 +1859,8 @@ fn regGeneralClassForType(func: *Func, ty: Type) RegisterManager.RegisterBitSet
18471859}
18481860
18491861fn regTempClassForType(func: *Func, ty: Type) RegisterManager.RegisterBitSet {
1850 const zcu = func.bin_file.comp.module.?;
1862 const pt = func.pt;
1863 const zcu = pt.zcu;
18511864 return switch (ty.zigTypeTag(zcu)) {
18521865 .Float => abi.Registers.Float.temporary,
18531866 .Vector => @panic("TODO: regTempClassForType for Vectors"),
......@@ -1856,13 +1869,13 @@ fn regTempClassForType(func: *Func, ty: Type) RegisterManager.RegisterBitSet {
18561869}
18571870
18581871fn allocRegOrMem(func: *Func, elem_ty: Type, inst: ?Air.Inst.Index, reg_ok: bool) !MCValue {
1859 const zcu = func.bin_file.comp.module.?;
1872 const pt = func.pt;
18601873
1861 const abi_size = math.cast(u32, elem_ty.abiSize(zcu)) orelse {
1862 return func.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(zcu)});
1874 const abi_size = math.cast(u32, elem_ty.abiSize(pt)) orelse {
1875 return func.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(pt)});
18631876 };
18641877
1865 const min_size: u32 = switch (elem_ty.zigTypeTag(zcu)) {
1878 const min_size: u32 = switch (elem_ty.zigTypeTag(pt.zcu)) {
18661879 .Float => 4,
18671880 .Vector => @panic("allocRegOrMem Vector"),
18681881 else => 8,
......@@ -1874,7 +1887,7 @@ fn allocRegOrMem(func: *Func, elem_ty: Type, inst: ?Air.Inst.Index, reg_ok: bool
18741887 }
18751888 }
18761889
1877 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(elem_ty, zcu));
1890 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(elem_ty, pt));
18781891 return .{ .load_frame = .{ .index = frame_index } };
18791892}
18801893
......@@ -1955,7 +1968,7 @@ pub fn spillInstruction(func: *Func, reg: Register, inst: Air.Inst.Index) !void
19551968/// allocated. A second call to `copyToTmpRegister` may return the same register.
19561969/// This can have a side effect of spilling instructions to the stack to free up a register.
19571970fn copyToTmpRegister(func: *Func, ty: Type, mcv: MCValue) !Register {
1958 log.debug("copyToTmpRegister ty: {}", .{ty.fmt(func.bin_file.comp.module.?)});
1971 log.debug("copyToTmpRegister ty: {}", .{ty.fmt(func.pt)});
19591972 const reg = try func.register_manager.allocReg(null, func.regTempClassForType(ty));
19601973 try func.genSetReg(ty, reg, mcv);
19611974 return reg;
......@@ -2004,7 +2017,8 @@ fn airFpext(func: *Func, inst: Air.Inst.Index) !void {
20042017}
20052018
20062019fn airIntCast(func: *Func, inst: Air.Inst.Index) !void {
2007 const zcu = func.bin_file.comp.module.?;
2020 const pt = func.pt;
2021 const zcu = pt.zcu;
20082022 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
20092023 const src_ty = func.typeOf(ty_op.operand);
20102024 const dst_ty = func.typeOfIndex(inst);
......@@ -2040,7 +2054,7 @@ fn airIntCast(func: *Func, inst: Air.Inst.Index) !void {
20402054
20412055 break :result dst_mcv;
20422056 } orelse return func.fail("TODO: implement airIntCast from {} to {}", .{
2043 src_ty.fmt(zcu), dst_ty.fmt(zcu),
2057 src_ty.fmt(pt), dst_ty.fmt(pt),
20442058 });
20452059
20462060 return func.finishAir(inst, result, .{ ty_op.operand, .none, .none });
......@@ -2067,7 +2081,8 @@ fn airIntFromBool(func: *Func, inst: Air.Inst.Index) !void {
20672081fn airNot(func: *Func, inst: Air.Inst.Index) !void {
20682082 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
20692083 const result: MCValue = if (func.liveness.isUnused(inst)) .unreach else result: {
2070 const zcu = func.bin_file.comp.module.?;
2084 const pt = func.pt;
2085 const zcu = pt.zcu;
20712086
20722087 const operand = try func.resolveInst(ty_op.operand);
20732088 const ty = func.typeOf(ty_op.operand);
......@@ -2106,12 +2121,12 @@ fn airNot(func: *Func, inst: Air.Inst.Index) !void {
21062121}
21072122
21082123fn airSlice(func: *Func, inst: Air.Inst.Index) !void {
2109 const zcu = func.bin_file.comp.module.?;
2124 const pt = func.pt;
21102125 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
21112126 const bin_op = func.air.extraData(Air.Bin, ty_pl.payload).data;
21122127
21132128 const slice_ty = func.typeOfIndex(inst);
2114 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(slice_ty, zcu));
2129 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(slice_ty, pt));
21152130
21162131 const ptr_ty = func.typeOf(bin_op.lhs);
21172132 try func.genSetMem(.{ .frame = frame_index }, 0, ptr_ty, .{ .air_ref = bin_op.lhs });
......@@ -2119,7 +2134,7 @@ fn airSlice(func: *Func, inst: Air.Inst.Index) !void {
21192134 const len_ty = func.typeOf(bin_op.rhs);
21202135 try func.genSetMem(
21212136 .{ .frame = frame_index },
2122 @intCast(ptr_ty.abiSize(zcu)),
2137 @intCast(ptr_ty.abiSize(pt)),
21232138 len_ty,
21242139 .{ .air_ref = bin_op.rhs },
21252140 );
......@@ -2129,14 +2144,15 @@ fn airSlice(func: *Func, inst: Air.Inst.Index) !void {
21292144}
21302145
21312146fn airBinOp(func: *Func, inst: Air.Inst.Index, tag: Air.Inst.Tag) !void {
2132 const zcu = func.bin_file.comp.module.?;
2147 const pt = func.pt;
2148 const zcu = pt.zcu;
21332149 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
21342150 const dst_mcv = try func.binOp(inst, tag, bin_op.lhs, bin_op.rhs);
21352151
21362152 const dst_ty = func.typeOfIndex(inst);
21372153 if (dst_ty.isAbiInt(zcu)) {
2138 const abi_size: u32 = @intCast(dst_ty.abiSize(zcu));
2139 const bit_size: u32 = @intCast(dst_ty.bitSize(zcu));
2154 const abi_size: u32 = @intCast(dst_ty.abiSize(pt));
2155 const bit_size: u32 = @intCast(dst_ty.bitSize(pt));
21402156 if (abi_size * 8 > bit_size) {
21412157 const dst_lock = switch (dst_mcv) {
21422158 .register => |dst_reg| func.register_manager.lockRegAssumeUnused(dst_reg),
......@@ -2150,7 +2166,7 @@ fn airBinOp(func: *Func, inst: Air.Inst.Index, tag: Air.Inst.Tag) !void {
21502166 const tmp_reg, const tmp_lock = try func.allocReg(.int);
21512167 defer func.register_manager.unlockReg(tmp_lock);
21522168
2153 const hi_ty = try zcu.intType(.unsigned, @intCast((dst_ty.bitSize(zcu) - 1) % 64 + 1));
2169 const hi_ty = try pt.intType(.unsigned, @intCast((dst_ty.bitSize(pt) - 1) % 64 + 1));
21542170 const hi_mcv = dst_mcv.address().offset(@intCast(bit_size / 64 * 8)).deref();
21552171 try func.genSetReg(hi_ty, tmp_reg, hi_mcv);
21562172 try func.truncateRegister(dst_ty, tmp_reg);
......@@ -2170,7 +2186,7 @@ fn binOp(
21702186 rhs_air: Air.Inst.Ref,
21712187) !MCValue {
21722188 _ = maybe_inst;
2173 const zcu = func.bin_file.comp.module.?;
2189 const pt = func.pt;
21742190 const lhs_ty = func.typeOf(lhs_air);
21752191 const rhs_ty = func.typeOf(rhs_air);
21762192
......@@ -2189,7 +2205,7 @@ fn binOp(
21892205 return func.fail("binOp libcall runtime-float ops", .{});
21902206 }
21912207
2192 if (lhs_ty.bitSize(zcu) > 64) return func.fail("TODO: binOp >= 64 bits", .{});
2208 if (lhs_ty.bitSize(pt) > 64) return func.fail("TODO: binOp >= 64 bits", .{});
21932209
21942210 const lhs_mcv = try func.resolveInst(lhs_air);
21952211 const rhs_mcv = try func.resolveInst(rhs_air);
......@@ -2237,8 +2253,9 @@ fn genBinOp(
22372253 rhs_ty: Type,
22382254 dst_reg: Register,
22392255) !void {
2240 const zcu = func.bin_file.comp.module.?;
2241 const bit_size = lhs_ty.bitSize(zcu);
2256 const pt = func.pt;
2257 const zcu = pt.zcu;
2258 const bit_size = lhs_ty.bitSize(pt);
22422259 assert(bit_size <= 64);
22432260
22442261 const is_unsigned = lhs_ty.isUnsignedInt(zcu);
......@@ -2349,7 +2366,7 @@ fn genBinOp(
23492366 defer func.register_manager.unlockReg(tmp_lock);
23502367
23512368 // RISC-V has no immediate mul, so we copy the size to a temporary register
2352 const elem_size = lhs_ty.elemType2(zcu).abiSize(zcu);
2369 const elem_size = lhs_ty.elemType2(zcu).abiSize(pt);
23532370 const elem_size_reg = try func.copyToTmpRegister(Type.usize, .{ .immediate = elem_size });
23542371
23552372 try func.genBinOp(
......@@ -2613,7 +2630,8 @@ fn airPtrArithmetic(func: *Func, inst: Air.Inst.Index, tag: Air.Inst.Tag) !void
26132630}
26142631
26152632fn airAddWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
2616 const zcu = func.bin_file.comp.module.?;
2633 const pt = func.pt;
2634 const zcu = pt.zcu;
26172635 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
26182636 const extra = func.air.extraData(Air.Bin, ty_pl.payload).data;
26192637
......@@ -2632,7 +2650,7 @@ fn airAddWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
26322650 const add_result_reg_lock = func.register_manager.lockRegAssumeUnused(add_result_reg);
26332651 defer func.register_manager.unlockReg(add_result_reg_lock);
26342652
2635 const shift_amount: u6 = @intCast(Type.usize.bitSize(zcu) - int_info.bits);
2653 const shift_amount: u6 = @intCast(Type.usize.bitSize(pt) - int_info.bits);
26362654
26372655 const shift_reg, const shift_lock = try func.allocReg(.int);
26382656 defer func.register_manager.unlockReg(shift_lock);
......@@ -2663,7 +2681,7 @@ fn airAddWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
26632681
26642682 try func.genSetMem(
26652683 .{ .frame = offset.index },
2666 offset.off + @as(i32, @intCast(tuple_ty.structFieldOffset(0, zcu))),
2684 offset.off + @as(i32, @intCast(tuple_ty.structFieldOffset(0, pt))),
26672685 lhs_ty,
26682686 add_result,
26692687 );
......@@ -2682,7 +2700,7 @@ fn airAddWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
26822700
26832701 try func.genSetMem(
26842702 .{ .frame = offset.index },
2685 offset.off + @as(i32, @intCast(tuple_ty.structFieldOffset(1, zcu))),
2703 offset.off + @as(i32, @intCast(tuple_ty.structFieldOffset(1, pt))),
26862704 Type.u1,
26872705 .{ .register = overflow_reg },
26882706 );
......@@ -2697,7 +2715,8 @@ fn airAddWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
26972715}
26982716
26992717fn airSubWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
2700 const zcu = func.bin_file.comp.module.?;
2718 const pt = func.pt;
2719 const zcu = pt.zcu;
27012720 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
27022721 const extra = func.air.extraData(Air.Bin, ty_pl.payload).data;
27032722
......@@ -2727,7 +2746,7 @@ fn airSubWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
27272746
27282747 try func.genSetMem(
27292748 .{ .frame = offset.index },
2730 offset.off + @as(i32, @intCast(tuple_ty.structFieldOffset(0, zcu))),
2749 offset.off + @as(i32, @intCast(tuple_ty.structFieldOffset(0, pt))),
27312750 lhs_ty,
27322751 .{ .register = dest_reg },
27332752 );
......@@ -2757,7 +2776,7 @@ fn airSubWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
27572776
27582777 try func.genSetMem(
27592778 .{ .frame = offset.index },
2760 offset.off + @as(i32, @intCast(tuple_ty.structFieldOffset(1, zcu))),
2779 offset.off + @as(i32, @intCast(tuple_ty.structFieldOffset(1, pt))),
27612780 Type.u1,
27622781 .{ .register = overflow_reg },
27632782 );
......@@ -2808,7 +2827,7 @@ fn airSubWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
28082827
28092828 try func.genSetMem(
28102829 .{ .frame = offset.index },
2811 offset.off + @as(i32, @intCast(tuple_ty.structFieldOffset(1, zcu))),
2830 offset.off + @as(i32, @intCast(tuple_ty.structFieldOffset(1, pt))),
28122831 Type.u1,
28132832 .{ .register = overflow_reg },
28142833 );
......@@ -2825,7 +2844,8 @@ fn airSubWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
28252844}
28262845
28272846fn airMulWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
2828 const zcu = func.bin_file.comp.module.?;
2847 const pt = func.pt;
2848 const zcu = pt.zcu;
28292849 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
28302850 const extra = func.air.extraData(Air.Bin, ty_pl.payload).data;
28312851
......@@ -2840,8 +2860,8 @@ fn airMulWithOverflow(func: *Func, inst: Air.Inst.Index) !void {
28402860 // genSetReg needs to support register_offset src_mcv for this to be true.
28412861 const result_mcv = try func.allocRegOrMem(tuple_ty, inst, false);
28422862
2843 const result_off: i32 = @intCast(tuple_ty.structFieldOffset(0, zcu));
2844 const overflow_off: i32 = @intCast(tuple_ty.structFieldOffset(1, zcu));
2863 const result_off: i32 = @intCast(tuple_ty.structFieldOffset(0, pt));
2864 const overflow_off: i32 = @intCast(tuple_ty.structFieldOffset(1, pt));
28452865
28462866 const dest_reg, const dest_lock = try func.allocReg(.int);
28472867 defer func.register_manager.unlockReg(dest_lock);
......@@ -2957,11 +2977,11 @@ fn airShlSat(func: *Func, inst: Air.Inst.Index) !void {
29572977}
29582978
29592979fn airOptionalPayload(func: *Func, inst: Air.Inst.Index) !void {
2960 const zcu = func.bin_file.comp.module.?;
2980 const pt = func.pt;
29612981 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
29622982 const result: MCValue = result: {
29632983 const pl_ty = func.typeOfIndex(inst);
2964 if (!pl_ty.hasRuntimeBitsIgnoreComptime(zcu)) break :result .none;
2984 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .none;
29652985
29662986 const opt_mcv = try func.resolveInst(ty_op.operand);
29672987 if (func.reuseOperand(inst, ty_op.operand, 0, opt_mcv)) {
......@@ -2993,7 +3013,8 @@ fn airOptionalPayloadPtrSet(func: *Func, inst: Air.Inst.Index) !void {
29933013
29943014fn airUnwrapErrErr(func: *Func, inst: Air.Inst.Index) !void {
29953015 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
2996 const zcu = func.bin_file.comp.module.?;
3016 const pt = func.pt;
3017 const zcu = pt.zcu;
29973018 const err_union_ty = func.typeOf(ty_op.operand);
29983019 const err_ty = err_union_ty.errorUnionSet(zcu);
29993020 const payload_ty = err_union_ty.errorUnionPayload(zcu);
......@@ -3004,11 +3025,11 @@ fn airUnwrapErrErr(func: *Func, inst: Air.Inst.Index) !void {
30043025 break :result .{ .immediate = 0 };
30053026 }
30063027
3007 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
3028 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
30083029 break :result operand;
30093030 }
30103031
3011 const err_off: u32 = @intCast(errUnionErrorOffset(payload_ty, zcu));
3032 const err_off: u32 = @intCast(errUnionErrorOffset(payload_ty, pt));
30123033
30133034 switch (operand) {
30143035 .register => |reg| {
......@@ -3052,13 +3073,14 @@ fn genUnwrapErrUnionPayloadMir(
30523073 err_union_ty: Type,
30533074 err_union: MCValue,
30543075) !MCValue {
3055 const zcu = func.bin_file.comp.module.?;
3076 const pt = func.pt;
3077 const zcu = pt.zcu;
30563078 const payload_ty = err_union_ty.errorUnionPayload(zcu);
30573079
30583080 const result: MCValue = result: {
3059 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) break :result .none;
3081 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .none;
30603082
3061 const payload_off: u31 = @intCast(errUnionPayloadOffset(payload_ty, zcu));
3083 const payload_off: u31 = @intCast(errUnionPayloadOffset(payload_ty, pt));
30623084 switch (err_union) {
30633085 .load_frame => |frame_addr| break :result .{ .load_frame = .{
30643086 .index = frame_addr.index,
......@@ -3127,11 +3149,12 @@ fn airSaveErrReturnTraceIndex(func: *Func, inst: Air.Inst.Index) !void {
31273149}
31283150
31293151fn airWrapOptional(func: *Func, inst: Air.Inst.Index) !void {
3130 const zcu = func.bin_file.comp.module.?;
3152 const pt = func.pt;
3153 const zcu = pt.zcu;
31313154 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
31323155 const result: MCValue = result: {
31333156 const pl_ty = func.typeOf(ty_op.operand);
3134 if (!pl_ty.hasRuntimeBits(zcu)) break :result .{ .immediate = 1 };
3157 if (!pl_ty.hasRuntimeBits(pt)) break :result .{ .immediate = 1 };
31353158
31363159 const opt_ty = func.typeOfIndex(inst);
31373160 const pl_mcv = try func.resolveInst(ty_op.operand);
......@@ -3148,7 +3171,7 @@ fn airWrapOptional(func: *Func, inst: Air.Inst.Index) !void {
31483171 try func.genCopy(pl_ty, opt_mcv, pl_mcv);
31493172
31503173 if (!same_repr) {
3151 const pl_abi_size: i32 = @intCast(pl_ty.abiSize(zcu));
3174 const pl_abi_size: i32 = @intCast(pl_ty.abiSize(pt));
31523175 switch (opt_mcv) {
31533176 .load_frame => |frame_addr| try func.genSetMem(
31543177 .{ .frame = frame_addr.index },
......@@ -3167,7 +3190,8 @@ fn airWrapOptional(func: *Func, inst: Air.Inst.Index) !void {
31673190
31683191/// T to E!T
31693192fn airWrapErrUnionPayload(func: *Func, inst: Air.Inst.Index) !void {
3170 const zcu = func.bin_file.comp.module.?;
3193 const pt = func.pt;
3194 const zcu = pt.zcu;
31713195 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
31723196
31733197 const eu_ty = ty_op.ty.toType();
......@@ -3176,11 +3200,11 @@ fn airWrapErrUnionPayload(func: *Func, inst: Air.Inst.Index) !void {
31763200 const operand = try func.resolveInst(ty_op.operand);
31773201
31783202 const result: MCValue = result: {
3179 if (!pl_ty.hasRuntimeBitsIgnoreComptime(zcu)) break :result .{ .immediate = 0 };
3203 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .{ .immediate = 0 };
31803204
3181 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(eu_ty, zcu));
3182 const pl_off: i32 = @intCast(errUnionPayloadOffset(pl_ty, zcu));
3183 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, zcu));
3205 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(eu_ty, pt));
3206 const pl_off: i32 = @intCast(errUnionPayloadOffset(pl_ty, pt));
3207 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, pt));
31843208 try func.genSetMem(.{ .frame = frame_index }, pl_off, pl_ty, operand);
31853209 try func.genSetMem(.{ .frame = frame_index }, err_off, err_ty, .{ .immediate = 0 });
31863210 break :result .{ .load_frame = .{ .index = frame_index } };
......@@ -3191,7 +3215,8 @@ fn airWrapErrUnionPayload(func: *Func, inst: Air.Inst.Index) !void {
31913215
31923216/// E to E!T
31933217fn airWrapErrUnionErr(func: *Func, inst: Air.Inst.Index) !void {
3194 const zcu = func.bin_file.comp.module.?;
3218 const pt = func.pt;
3219 const zcu = pt.zcu;
31953220 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
31963221
31973222 const eu_ty = ty_op.ty.toType();
......@@ -3199,11 +3224,11 @@ fn airWrapErrUnionErr(func: *Func, inst: Air.Inst.Index) !void {
31993224 const err_ty = eu_ty.errorUnionSet(zcu);
32003225
32013226 const result: MCValue = result: {
3202 if (!pl_ty.hasRuntimeBitsIgnoreComptime(zcu)) break :result try func.resolveInst(ty_op.operand);
3227 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result try func.resolveInst(ty_op.operand);
32033228
3204 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(eu_ty, zcu));
3205 const pl_off: i32 = @intCast(errUnionPayloadOffset(pl_ty, zcu));
3206 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, zcu));
3229 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(eu_ty, pt));
3230 const pl_off: i32 = @intCast(errUnionPayloadOffset(pl_ty, pt));
3231 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, pt));
32073232 try func.genSetMem(.{ .frame = frame_index }, pl_off, pl_ty, .undef);
32083233 const operand = try func.resolveInst(ty_op.operand);
32093234 try func.genSetMem(.{ .frame = frame_index }, err_off, err_ty, operand);
......@@ -3327,15 +3352,16 @@ fn airPtrSlicePtrPtr(func: *Func, inst: Air.Inst.Index) !void {
33273352}
33283353
33293354fn airSliceElemVal(func: *Func, inst: Air.Inst.Index) !void {
3330 const mod = func.bin_file.comp.module.?;
3355 const pt = func.pt;
3356 const zcu = pt.zcu;
33313357 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
33323358
33333359 const result: MCValue = result: {
33343360 const elem_ty = func.typeOfIndex(inst);
3335 if (!elem_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result .none;
3361 if (!elem_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .none;
33363362
33373363 const slice_ty = func.typeOf(bin_op.lhs);
3338 const slice_ptr_field_type = slice_ty.slicePtrFieldType(mod);
3364 const slice_ptr_field_type = slice_ty.slicePtrFieldType(zcu);
33393365 const elem_ptr = try func.genSliceElemPtr(bin_op.lhs, bin_op.rhs);
33403366 const dst_mcv = try func.allocRegOrMem(elem_ty, inst, false);
33413367 try func.load(dst_mcv, elem_ptr, slice_ptr_field_type);
......@@ -3352,7 +3378,8 @@ fn airSliceElemPtr(func: *Func, inst: Air.Inst.Index) !void {
33523378}
33533379
33543380fn genSliceElemPtr(func: *Func, lhs: Air.Inst.Ref, rhs: Air.Inst.Ref) !MCValue {
3355 const zcu = func.bin_file.comp.module.?;
3381 const pt = func.pt;
3382 const zcu = pt.zcu;
33563383 const slice_ty = func.typeOf(lhs);
33573384 const slice_mcv = try func.resolveInst(lhs);
33583385 const slice_mcv_lock: ?RegisterLock = switch (slice_mcv) {
......@@ -3362,7 +3389,7 @@ fn genSliceElemPtr(func: *Func, lhs: Air.Inst.Ref, rhs: Air.Inst.Ref) !MCValue {
33623389 defer if (slice_mcv_lock) |lock| func.register_manager.unlockReg(lock);
33633390
33643391 const elem_ty = slice_ty.childType(zcu);
3365 const elem_size = elem_ty.abiSize(zcu);
3392 const elem_size = elem_ty.abiSize(pt);
33663393
33673394 const index_ty = func.typeOf(rhs);
33683395 const index_mcv = try func.resolveInst(rhs);
......@@ -3394,7 +3421,8 @@ fn genSliceElemPtr(func: *Func, lhs: Air.Inst.Ref, rhs: Air.Inst.Ref) !MCValue {
33943421}
33953422
33963423fn airArrayElemVal(func: *Func, inst: Air.Inst.Index) !void {
3397 const zcu = func.bin_file.comp.module.?;
3424 const pt = func.pt;
3425 const zcu = pt.zcu;
33983426 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
33993427 const result: MCValue = if (func.liveness.isUnused(inst)) .unreach else result: {
34003428 const result_ty = func.typeOfIndex(inst);
......@@ -3406,14 +3434,14 @@ fn airArrayElemVal(func: *Func, inst: Air.Inst.Index) !void {
34063434 const index_ty = func.typeOf(bin_op.rhs);
34073435
34083436 const elem_ty = array_ty.childType(zcu);
3409 const elem_abi_size = elem_ty.abiSize(zcu);
3437 const elem_abi_size = elem_ty.abiSize(pt);
34103438
34113439 const addr_reg, const addr_reg_lock = try func.allocReg(.int);
34123440 defer func.register_manager.unlockReg(addr_reg_lock);
34133441
34143442 switch (array_mcv) {
34153443 .register => {
3416 const frame_index = try func.allocFrameIndex(FrameAlloc.initType(array_ty, zcu));
3444 const frame_index = try func.allocFrameIndex(FrameAlloc.initType(array_ty, pt));
34173445 try func.genSetMem(.{ .frame = frame_index }, 0, array_ty, array_mcv);
34183446 try func.genSetReg(Type.usize, addr_reg, .{ .lea_frame = .{ .index = frame_index } });
34193447 },
......@@ -3451,7 +3479,8 @@ fn airPtrElemVal(func: *Func, inst: Air.Inst.Index) !void {
34513479}
34523480
34533481fn airPtrElemPtr(func: *Func, inst: Air.Inst.Index) !void {
3454 const zcu = func.bin_file.comp.module.?;
3482 const pt = func.pt;
3483 const zcu = pt.zcu;
34553484 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
34563485 const extra = func.air.extraData(Air.Bin, ty_pl.payload).data;
34573486
......@@ -3474,7 +3503,7 @@ fn airPtrElemPtr(func: *Func, inst: Air.Inst.Index) !void {
34743503 }
34753504
34763505 const elem_ty = base_ptr_ty.elemType2(zcu);
3477 const elem_abi_size = elem_ty.abiSize(zcu);
3506 const elem_abi_size = elem_ty.abiSize(pt);
34783507 const index_ty = func.typeOf(extra.rhs);
34793508 const index_mcv = try func.resolveInst(extra.rhs);
34803509 const index_lock: ?RegisterLock = switch (index_mcv) {
......@@ -3536,7 +3565,8 @@ fn airPopcount(func: *Func, inst: Air.Inst.Index) !void {
35363565}
35373566
35383567fn airAbs(func: *Func, inst: Air.Inst.Index) !void {
3539 const zcu = func.bin_file.comp.module.?;
3568 const pt = func.pt;
3569 const zcu = pt.zcu;
35403570 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
35413571 const result: MCValue = if (func.liveness.isUnused(inst)) .unreach else result: {
35423572 const ty = func.typeOf(ty_op.operand);
......@@ -3545,7 +3575,7 @@ fn airAbs(func: *Func, inst: Air.Inst.Index) !void {
35453575
35463576 switch (scalar_ty.zigTypeTag(zcu)) {
35473577 .Int => if (ty.zigTypeTag(zcu) == .Vector) {
3548 return func.fail("TODO implement airAbs for {}", .{ty.fmt(zcu)});
3578 return func.fail("TODO implement airAbs for {}", .{ty.fmt(pt)});
35493579 } else {
35503580 const return_mcv = try func.copyToNewRegister(inst, operand);
35513581 const operand_reg = return_mcv.register;
......@@ -3615,7 +3645,7 @@ fn airAbs(func: *Func, inst: Air.Inst.Index) !void {
36153645
36163646 break :result return_mcv;
36173647 },
3618 else => return func.fail("TODO: implement airAbs {}", .{scalar_ty.fmt(zcu)}),
3648 else => return func.fail("TODO: implement airAbs {}", .{scalar_ty.fmt(pt)}),
36193649 }
36203650
36213651 break :result .unreach;
......@@ -3626,7 +3656,8 @@ fn airAbs(func: *Func, inst: Air.Inst.Index) !void {
36263656fn airByteSwap(func: *Func, inst: Air.Inst.Index) !void {
36273657 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
36283658 const result: MCValue = if (func.liveness.isUnused(inst)) .unreach else result: {
3629 const zcu = func.bin_file.comp.module.?;
3659 const pt = func.pt;
3660 const zcu = pt.zcu;
36303661 const ty = func.typeOf(ty_op.operand);
36313662 const operand = try func.resolveInst(ty_op.operand);
36323663
......@@ -3746,12 +3777,13 @@ fn reuseOperandAdvanced(
37463777}
37473778
37483779fn airLoad(func: *Func, inst: Air.Inst.Index) !void {
3749 const zcu = func.bin_file.comp.module.?;
3780 const pt = func.pt;
3781 const zcu = pt.zcu;
37503782 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
37513783 const elem_ty = func.typeOfIndex(inst);
37523784
37533785 const result: MCValue = result: {
3754 if (!elem_ty.hasRuntimeBits(zcu))
3786 if (!elem_ty.hasRuntimeBits(pt))
37553787 break :result .none;
37563788
37573789 const ptr = try func.resolveInst(ty_op.operand);
......@@ -3759,7 +3791,7 @@ fn airLoad(func: *Func, inst: Air.Inst.Index) !void {
37593791 if (func.liveness.isUnused(inst) and !is_volatile)
37603792 break :result .unreach;
37613793
3762 const elem_size = elem_ty.abiSize(zcu);
3794 const elem_size = elem_ty.abiSize(pt);
37633795
37643796 const dst_mcv: MCValue = blk: {
37653797 // Pointer is 8 bytes, and if the element is more than that, we cannot reuse it.
......@@ -3778,10 +3810,11 @@ fn airLoad(func: *Func, inst: Air.Inst.Index) !void {
37783810}
37793811
37803812fn load(func: *Func, dst_mcv: MCValue, ptr_mcv: MCValue, ptr_ty: Type) InnerError!void {
3781 const zcu = func.bin_file.comp.module.?;
3813 const pt = func.pt;
3814 const zcu = pt.zcu;
37823815 const dst_ty = ptr_ty.childType(zcu);
37833816
3784 log.debug("loading {}:{} into {}", .{ ptr_mcv, ptr_ty.fmt(zcu), dst_mcv });
3817 log.debug("loading {}:{} into {}", .{ ptr_mcv, ptr_ty.fmt(pt), dst_mcv });
37853818
37863819 switch (ptr_mcv) {
37873820 .none,
......@@ -3833,9 +3866,7 @@ fn airStore(func: *Func, inst: Air.Inst.Index, safety: bool) !void {
38333866
38343867/// Loads `value` into the "payload" of `pointer`.
38353868fn store(func: *Func, ptr_mcv: MCValue, src_mcv: MCValue, ptr_ty: Type, src_ty: Type) !void {
3836 const zcu = func.bin_file.comp.module.?;
3837
3838 log.debug("storing {}:{} in {}:{}", .{ src_mcv, src_ty.fmt(zcu), ptr_mcv, ptr_ty.fmt(zcu) });
3869 log.debug("storing {}:{} in {}:{}", .{ src_mcv, src_ty.fmt(func.pt), ptr_mcv, ptr_ty.fmt(func.pt) });
38393870
38403871 switch (ptr_mcv) {
38413872 .none => unreachable,
......@@ -3881,7 +3912,8 @@ fn airStructFieldPtrIndex(func: *Func, inst: Air.Inst.Index, index: u8) !void {
38813912}
38823913
38833914fn structFieldPtr(func: *Func, inst: Air.Inst.Index, operand: Air.Inst.Ref, index: u32) !MCValue {
3884 const zcu = func.bin_file.comp.module.?;
3915 const pt = func.pt;
3916 const zcu = pt.zcu;
38853917 const ptr_field_ty = func.typeOfIndex(inst);
38863918 const ptr_container_ty = func.typeOf(operand);
38873919 const ptr_container_ty_info = ptr_container_ty.ptrInfo(zcu);
......@@ -3889,12 +3921,12 @@ fn structFieldPtr(func: *Func, inst: Air.Inst.Index, operand: Air.Inst.Ref, inde
38893921
38903922 const field_offset: i32 = if (zcu.typeToPackedStruct(container_ty)) |struct_obj|
38913923 if (ptr_field_ty.ptrInfo(zcu).packed_offset.host_size == 0)
3892 @divExact(zcu.structPackedFieldBitOffset(struct_obj, index) +
3924 @divExact(pt.structPackedFieldBitOffset(struct_obj, index) +
38933925 ptr_container_ty_info.packed_offset.bit_offset, 8)
38943926 else
38953927 0
38963928 else
3897 @intCast(container_ty.structFieldOffset(index, zcu));
3929 @intCast(container_ty.structFieldOffset(index, pt));
38983930
38993931 const src_mcv = try func.resolveInst(operand);
39003932 const dst_mcv = if (switch (src_mcv) {
......@@ -3906,7 +3938,8 @@ fn structFieldPtr(func: *Func, inst: Air.Inst.Index, operand: Air.Inst.Ref, inde
39063938}
39073939
39083940fn airStructFieldVal(func: *Func, inst: Air.Inst.Index) !void {
3909 const mod = func.bin_file.comp.module.?;
3941 const pt = func.pt;
3942 const zcu = pt.zcu;
39103943
39113944 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
39123945 const extra = func.air.extraData(Air.StructField, ty_pl.payload).data;
......@@ -3914,16 +3947,15 @@ fn airStructFieldVal(func: *Func, inst: Air.Inst.Index) !void {
39143947 const index = extra.field_index;
39153948
39163949 const result: MCValue = if (func.liveness.isUnused(inst)) .unreach else result: {
3917 const zcu = func.bin_file.comp.module.?;
39183950 const src_mcv = try func.resolveInst(operand);
39193951 const struct_ty = func.typeOf(operand);
39203952 const field_ty = struct_ty.structFieldType(index, zcu);
3921 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) break :result .none;
3953 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .none;
39223954
39233955 const field_off: u32 = switch (struct_ty.containerLayout(zcu)) {
3924 .auto, .@"extern" => @intCast(struct_ty.structFieldOffset(index, zcu) * 8),
3956 .auto, .@"extern" => @intCast(struct_ty.structFieldOffset(index, pt) * 8),
39253957 .@"packed" => if (zcu.typeToStruct(struct_ty)) |struct_type|
3926 zcu.structPackedFieldBitOffset(struct_type, index)
3958 pt.structPackedFieldBitOffset(struct_type, index)
39273959 else
39283960 0,
39293961 };
......@@ -3958,15 +3990,15 @@ fn airStructFieldVal(func: *Func, inst: Air.Inst.Index) !void {
39583990 break :result if (field_off == 0) dst_mcv else try func.copyToNewRegister(inst, dst_mcv);
39593991 },
39603992 .load_frame => {
3961 const field_abi_size: u32 = @intCast(field_ty.abiSize(mod));
3993 const field_abi_size: u32 = @intCast(field_ty.abiSize(pt));
39623994 if (field_off % 8 == 0) {
39633995 const field_byte_off = @divExact(field_off, 8);
39643996 const off_mcv = src_mcv.address().offset(@intCast(field_byte_off)).deref();
3965 const field_bit_size = field_ty.bitSize(mod);
3997 const field_bit_size = field_ty.bitSize(pt);
39663998
39673999 if (field_abi_size <= 8) {
3968 const int_ty = try mod.intType(
3969 if (field_ty.isAbiInt(mod)) field_ty.intInfo(mod).signedness else .unsigned,
4000 const int_ty = try pt.intType(
4001 if (field_ty.isAbiInt(zcu)) field_ty.intInfo(zcu).signedness else .unsigned,
39704002 @intCast(field_bit_size),
39714003 );
39724004
......@@ -3978,7 +4010,7 @@ fn airStructFieldVal(func: *Func, inst: Air.Inst.Index) !void {
39784010 break :result try func.copyToNewRegister(inst, dst_mcv);
39794011 }
39804012
3981 const container_abi_size: u32 = @intCast(struct_ty.abiSize(mod));
4013 const container_abi_size: u32 = @intCast(struct_ty.abiSize(pt));
39824014 const dst_mcv = if (field_byte_off + field_abi_size <= container_abi_size and
39834015 func.reuseOperand(inst, operand, 0, src_mcv))
39844016 off_mcv
......@@ -4014,7 +4046,8 @@ fn airFieldParentPtr(func: *Func, inst: Air.Inst.Index) !void {
40144046}
40154047
40164048fn genArgDbgInfo(func: Func, inst: Air.Inst.Index, mcv: MCValue) !void {
4017 const zcu = func.bin_file.comp.module.?;
4049 const pt = func.pt;
4050 const zcu = pt.zcu;
40184051 const arg = func.air.instructions.items(.data)[@intFromEnum(inst)].arg;
40194052 const ty = arg.ty.toType();
40204053 const owner_decl = zcu.funcOwnerDeclIndex(func.func_index);
......@@ -4139,7 +4172,8 @@ fn genCall(
41394172 arg_tys: []const Type,
41404173 args: []const MCValue,
41414174) !MCValue {
4142 const zcu = func.bin_file.comp.module.?;
4175 const pt = func.pt;
4176 const zcu = pt.zcu;
41434177
41444178 const fn_ty = switch (info) {
41454179 .air => |callee| fn_info: {
......@@ -4150,7 +4184,7 @@ fn genCall(
41504184 else => unreachable,
41514185 };
41524186 },
4153 .lib => |lib| try zcu.funcType(.{
4187 .lib => |lib| try pt.funcType(.{
41544188 .param_types = lib.param_types,
41554189 .return_type = lib.return_type,
41564190 .cc = .C,
......@@ -4208,7 +4242,7 @@ fn genCall(
42084242 try reg_locks.appendSlice(&func.register_manager.lockRegs(2, regs));
42094243 },
42104244 .indirect => |reg_off| {
4211 frame_index.* = try func.allocFrameIndex(FrameAlloc.initType(arg_ty, zcu));
4245 frame_index.* = try func.allocFrameIndex(FrameAlloc.initType(arg_ty, pt));
42124246 try func.genSetMem(.{ .frame = frame_index.* }, 0, arg_ty, src_arg);
42134247 try func.register_manager.getReg(reg_off.reg, null);
42144248 try reg_locks.append(func.register_manager.lockReg(reg_off.reg));
......@@ -4221,7 +4255,7 @@ fn genCall(
42214255 .none, .unreach => {},
42224256 .indirect => |reg_off| {
42234257 const ret_ty = Type.fromInterned(fn_info.return_type);
4224 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(ret_ty, zcu));
4258 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(ret_ty, pt));
42254259 try func.genSetReg(Type.usize, reg_off.reg, .{
42264260 .lea_frame = .{ .index = frame_index, .off = -reg_off.off },
42274261 });
......@@ -4251,7 +4285,7 @@ fn genCall(
42514285 // on linking.
42524286 switch (info) {
42534287 .air => |callee| {
4254 if (try func.air.value(callee, zcu)) |func_value| {
4288 if (try func.air.value(callee, pt)) |func_value| {
42554289 const func_key = zcu.intern_pool.indexToKey(func_value.ip_index);
42564290 switch (switch (func_key) {
42574291 else => func_key,
......@@ -4324,7 +4358,8 @@ fn genCall(
43244358}
43254359
43264360fn airRet(func: *Func, inst: Air.Inst.Index, safety: bool) !void {
4327 const zcu = func.bin_file.comp.module.?;
4361 const pt = func.pt;
4362 const zcu = pt.zcu;
43284363 const un_op = func.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
43294364
43304365 if (safety) {
......@@ -4394,7 +4429,8 @@ fn airRetLoad(func: *Func, inst: Air.Inst.Index) !void {
43944429
43954430fn airCmp(func: *Func, inst: Air.Inst.Index, tag: Air.Inst.Tag) !void {
43964431 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
4397 const zcu = func.bin_file.comp.module.?;
4432 const pt = func.pt;
4433 const zcu = pt.zcu;
43984434
43994435 const result: MCValue = if (func.liveness.isUnused(inst)) .unreach else result: {
44004436 const lhs_ty = func.typeOf(bin_op.lhs);
......@@ -4415,7 +4451,7 @@ fn airCmp(func: *Func, inst: Air.Inst.Index, tag: Air.Inst.Tag) !void {
44154451 .ErrorSet => Type.anyerror,
44164452 .Optional => blk: {
44174453 const payload_ty = lhs_ty.optionalChild(zcu);
4418 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
4454 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
44194455 break :blk Type.u1;
44204456 } else if (lhs_ty.isPtrLikeOptional(zcu)) {
44214457 break :blk Type.usize;
......@@ -4503,7 +4539,8 @@ fn genVarDbgInfo(
45034539 mcv: MCValue,
45044540 name: [:0]const u8,
45054541) !void {
4506 const zcu = func.bin_file.comp.module.?;
4542 const pt = func.pt;
4543 const zcu = pt.zcu;
45074544 const is_ptr = switch (tag) {
45084545 .dbg_var_ptr => true,
45094546 .dbg_var_val => false,
......@@ -4595,13 +4632,14 @@ fn condBr(func: *Func, cond_ty: Type, condition: MCValue) !Mir.Inst.Index {
45954632}
45964633
45974634fn isNull(func: *Func, inst: Air.Inst.Index, opt_ty: Type, opt_mcv: MCValue) !MCValue {
4598 const zcu = func.bin_file.comp.module.?;
4635 const pt = func.pt;
4636 const zcu = pt.zcu;
45994637 const pl_ty = opt_ty.optionalChild(zcu);
46004638
46014639 const some_info: struct { off: i32, ty: Type } = if (opt_ty.optionalReprIsPayload(zcu))
46024640 .{ .off = 0, .ty = if (pl_ty.isSlice(zcu)) pl_ty.slicePtrFieldType(zcu) else pl_ty }
46034641 else
4604 .{ .off = @intCast(pl_ty.abiSize(zcu)), .ty = Type.bool };
4642 .{ .off = @intCast(pl_ty.abiSize(pt)), .ty = Type.bool };
46054643
46064644 const return_mcv = try func.allocRegOrMem(func.typeOfIndex(inst), inst, true);
46074645 assert(return_mcv == .register); // should not be larger 8 bytes
......@@ -4642,7 +4680,7 @@ fn isNull(func: *Func, inst: Air.Inst.Index, opt_ty: Type, opt_mcv: MCValue) !MC
46424680 return return_mcv;
46434681 }
46444682 assert(some_info.ty.ip_index == .bool_type);
4645 const opt_abi_size: u32 = @intCast(opt_ty.abiSize(zcu));
4683 const opt_abi_size: u32 = @intCast(opt_ty.abiSize(pt));
46464684 _ = opt_abi_size;
46474685 return func.fail("TODO: isNull some_info.off != 0 register", .{});
46484686 },
......@@ -4742,7 +4780,8 @@ fn airIsErr(func: *Func, inst: Air.Inst.Index) !void {
47424780}
47434781
47444782fn airIsErrPtr(func: *Func, inst: Air.Inst.Index) !void {
4745 const zcu = func.bin_file.comp.module.?;
4783 const pt = func.pt;
4784 const zcu = pt.zcu;
47464785 const un_op = func.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
47474786 const result: MCValue = if (func.liveness.isUnused(inst)) .unreach else result: {
47484787 const operand_ptr = try func.resolveInst(un_op);
......@@ -4768,10 +4807,11 @@ fn airIsErrPtr(func: *Func, inst: Air.Inst.Index) !void {
47684807/// Result is in the return register.
47694808fn isErr(func: *Func, maybe_inst: ?Air.Inst.Index, eu_ty: Type, eu_mcv: MCValue) !MCValue {
47704809 _ = maybe_inst;
4771 const zcu = func.bin_file.comp.module.?;
4810 const pt = func.pt;
4811 const zcu = pt.zcu;
47724812 const err_ty = eu_ty.errorUnionSet(zcu);
47734813 if (err_ty.errorSetIsEmpty(zcu)) return MCValue{ .immediate = 0 }; // always false
4774 const err_off: u31 = @intCast(errUnionErrorOffset(eu_ty.errorUnionPayload(zcu), zcu));
4814 const err_off: u31 = @intCast(errUnionErrorOffset(eu_ty.errorUnionPayload(zcu), pt));
47754815
47764816 const return_reg, const return_lock = try func.allocReg(.int);
47774817 defer func.register_manager.unlockReg(return_lock);
......@@ -4858,7 +4898,8 @@ fn isNonErr(func: *Func, inst: Air.Inst.Index, eu_ty: Type, eu_mcv: MCValue) !MC
48584898}
48594899
48604900fn airIsNonErrPtr(func: *Func, inst: Air.Inst.Index) !void {
4861 const zcu = func.bin_file.comp.module.?;
4901 const pt = func.pt;
4902 const zcu = pt.zcu;
48624903 const un_op = func.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
48634904 const result: MCValue = if (func.liveness.isUnused(inst)) .unreach else result: {
48644905 const operand_ptr = try func.resolveInst(un_op);
......@@ -5063,12 +5104,12 @@ fn performReloc(func: *Func, inst: Mir.Inst.Index) void {
50635104}
50645105
50655106fn airBr(func: *Func, inst: Air.Inst.Index) !void {
5066 const mod = func.bin_file.comp.module.?;
5107 const pt = func.pt;
50675108 const br = func.air.instructions.items(.data)[@intFromEnum(inst)].br;
50685109
50695110 const block_ty = func.typeOfIndex(br.block_inst);
50705111 const block_unused =
5071 !block_ty.hasRuntimeBitsIgnoreComptime(mod) or func.liveness.isUnused(br.block_inst);
5112 !block_ty.hasRuntimeBitsIgnoreComptime(pt) or func.liveness.isUnused(br.block_inst);
50725113 const block_tracking = func.inst_tracking.getPtr(br.block_inst).?;
50735114 const block_data = func.blocks.getPtr(br.block_inst).?;
50745115 const first_br = block_data.relocs.items.len == 0;
......@@ -5288,8 +5329,6 @@ fn airAsm(func: *Func, inst: Air.Inst.Index) !void {
52885329
52895330/// Sets the value of `dst_mcv` to the value of `src_mcv`.
52905331fn genCopy(func: *Func, ty: Type, dst_mcv: MCValue, src_mcv: MCValue) !void {
5291 const zcu = func.bin_file.comp.module.?;
5292
52935332 // There isn't anything to store
52945333 if (dst_mcv == .none) return;
52955334
......@@ -5362,7 +5401,7 @@ fn genCopy(func: *Func, ty: Type, dst_mcv: MCValue, src_mcv: MCValue) !void {
53625401 } },
53635402 else => unreachable,
53645403 });
5365 part_disp += @intCast(dst_ty.abiSize(zcu));
5404 part_disp += @intCast(dst_ty.abiSize(func.pt));
53665405 }
53675406 },
53685407 else => return func.fail("TODO: genCopy to {s} from {s}", .{ @tagName(dst_mcv), @tagName(src_mcv) }),
......@@ -5555,8 +5594,9 @@ fn genInlineMemset(
55555594
55565595/// Sets the value of `src_mcv` into `reg`. Assumes you have a lock on it.
55575596fn genSetReg(func: *Func, ty: Type, reg: Register, src_mcv: MCValue) InnerError!void {
5558 const zcu = func.bin_file.comp.module.?;
5559 const abi_size: u32 = @intCast(ty.abiSize(zcu));
5597 const pt = func.pt;
5598 const zcu = pt.zcu;
5599 const abi_size: u32 = @intCast(ty.abiSize(pt));
55605600
55615601 if (abi_size > 8) return std.debug.panic("tried to set reg with size {}", .{abi_size});
55625602
......@@ -5784,8 +5824,8 @@ fn genSetMem(
57845824 ty: Type,
57855825 src_mcv: MCValue,
57865826) InnerError!void {
5787 const mod = func.bin_file.comp.module.?;
5788 const abi_size: u32 = @intCast(ty.abiSize(mod));
5827 const pt = func.pt;
5828 const abi_size: u32 = @intCast(ty.abiSize(pt));
57895829 const dst_ptr_mcv: MCValue = switch (base) {
57905830 .reg => |base_reg| .{ .register_offset = .{ .reg = base_reg, .off = disp } },
57915831 .frame => |base_frame_index| .{ .lea_frame = .{ .index = base_frame_index, .off = disp } },
......@@ -5883,7 +5923,7 @@ fn genSetMem(
58835923 var part_disp: i32 = disp;
58845924 for (try func.splitType(ty), src_regs) |src_ty, src_reg| {
58855925 try func.genSetMem(base, part_disp, src_ty, .{ .register = src_reg });
5886 part_disp += @intCast(src_ty.abiSize(mod));
5926 part_disp += @intCast(src_ty.abiSize(pt));
58875927 }
58885928 },
58895929 .immediate => {
......@@ -5914,7 +5954,8 @@ fn airIntFromPtr(func: *Func, inst: Air.Inst.Index) !void {
59145954}
59155955
59165956fn airBitCast(func: *Func, inst: Air.Inst.Index) !void {
5917 const zcu = func.bin_file.comp.module.?;
5957 const pt = func.pt;
5958 const zcu = pt.zcu;
59185959
59195960 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59205961 const result = if (func.liveness.isUnused(inst)) .unreach else result: {
......@@ -5926,10 +5967,10 @@ fn airBitCast(func: *Func, inst: Air.Inst.Index) !void {
59265967 const src_lock = if (src_mcv.getReg()) |reg| func.register_manager.lockReg(reg) else null;
59275968 defer if (src_lock) |lock| func.register_manager.unlockReg(lock);
59285969
5929 const dst_mcv = if (dst_ty.abiSize(zcu) <= src_ty.abiSize(zcu) and
5970 const dst_mcv = if (dst_ty.abiSize(pt) <= src_ty.abiSize(pt) and
59305971 func.reuseOperand(inst, ty_op.operand, 0, src_mcv)) src_mcv else dst: {
59315972 const dst_mcv = try func.allocRegOrMem(dst_ty, inst, true);
5932 try func.genCopy(switch (math.order(dst_ty.abiSize(zcu), src_ty.abiSize(zcu))) {
5973 try func.genCopy(switch (math.order(dst_ty.abiSize(pt), src_ty.abiSize(pt))) {
59335974 .lt => dst_ty,
59345975 .eq => if (!dst_mcv.isMemory() or src_mcv.isMemory()) dst_ty else src_ty,
59355976 .gt => src_ty,
......@@ -5940,17 +5981,18 @@ fn airBitCast(func: *Func, inst: Air.Inst.Index) !void {
59405981 if (dst_ty.isAbiInt(zcu) and src_ty.isAbiInt(zcu) and
59415982 dst_ty.intInfo(zcu).signedness == src_ty.intInfo(zcu).signedness) break :result dst_mcv;
59425983
5943 const abi_size = dst_ty.abiSize(zcu);
5944 const bit_size = dst_ty.bitSize(zcu);
5984 const abi_size = dst_ty.abiSize(pt);
5985 const bit_size = dst_ty.bitSize(pt);
59455986 if (abi_size * 8 <= bit_size) break :result dst_mcv;
59465987
5947 return func.fail("TODO: airBitCast {} to {}", .{ src_ty.fmt(zcu), dst_ty.fmt(zcu) });
5988 return func.fail("TODO: airBitCast {} to {}", .{ src_ty.fmt(pt), dst_ty.fmt(pt) });
59485989 };
59495990 return func.finishAir(inst, result, .{ ty_op.operand, .none, .none });
59505991}
59515992
59525993fn airArrayToSlice(func: *Func, inst: Air.Inst.Index) !void {
5953 const zcu = func.bin_file.comp.module.?;
5994 const pt = func.pt;
5995 const zcu = pt.zcu;
59545996 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59555997
59565998 const slice_ty = func.typeOfIndex(inst);
......@@ -5959,11 +6001,11 @@ fn airArrayToSlice(func: *Func, inst: Air.Inst.Index) !void {
59596001 const array_ty = ptr_ty.childType(zcu);
59606002 const array_len = array_ty.arrayLen(zcu);
59616003
5962 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(slice_ty, zcu));
6004 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(slice_ty, pt));
59636005 try func.genSetMem(.{ .frame = frame_index }, 0, ptr_ty, ptr);
59646006 try func.genSetMem(
59656007 .{ .frame = frame_index },
5966 @intCast(ptr_ty.abiSize(zcu)),
6008 @intCast(ptr_ty.abiSize(pt)),
59676009 Type.usize,
59686010 .{ .immediate = array_len },
59696011 );
......@@ -6015,7 +6057,8 @@ fn airAtomicStore(func: *Func, inst: Air.Inst.Index, order: std.builtin.AtomicOr
60156057}
60166058
60176059fn airMemset(func: *Func, inst: Air.Inst.Index, safety: bool) !void {
6018 const zcu = func.bin_file.comp.module.?;
6060 const pt = func.pt;
6061 const zcu = pt.zcu;
60196062 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
60206063
60216064 result: {
......@@ -6037,7 +6080,7 @@ fn airMemset(func: *Func, inst: Air.Inst.Index, safety: bool) !void {
60376080 };
60386081 defer if (src_val_lock) |lock| func.register_manager.unlockReg(lock);
60396082
6040 const elem_abi_size: u31 = @intCast(elem_ty.abiSize(zcu));
6083 const elem_abi_size: u31 = @intCast(elem_ty.abiSize(pt));
60416084
60426085 if (elem_abi_size == 1) {
60436086 const ptr: MCValue = switch (dst_ptr_ty.ptrSize(zcu)) {
......@@ -6068,7 +6111,7 @@ fn airMemset(func: *Func, inst: Air.Inst.Index, safety: bool) !void {
60686111 switch (dst_ptr_ty.ptrSize(zcu)) {
60696112 .Slice => return func.fail("TODO: airMemset Slices", .{}),
60706113 .One => {
6071 const elem_ptr_ty = try zcu.singleMutPtrType(elem_ty);
6114 const elem_ptr_ty = try pt.singleMutPtrType(elem_ty);
60726115
60736116 const len = dst_ptr_ty.childType(zcu).arrayLen(zcu);
60746117
......@@ -6110,7 +6153,8 @@ fn airTagName(func: *Func, inst: Air.Inst.Index) !void {
61106153}
61116154
61126155fn airErrorName(func: *Func, inst: Air.Inst.Index) !void {
6113 const zcu = func.bin_file.comp.module.?;
6156 const pt = func.pt;
6157 const zcu = pt.zcu;
61146158 const un_op = func.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
61156159
61166160 const err_ty = func.typeOf(un_op);
......@@ -6126,7 +6170,7 @@ fn airErrorName(func: *Func, inst: Air.Inst.Index) !void {
61266170 // this is now the base address of the error name table
61276171 const lazy_sym = link.File.LazySymbol.initDecl(.const_data, null, zcu);
61286172 if (func.bin_file.cast(link.File.Elf)) |elf_file| {
6129 const sym_index = elf_file.zigObjectPtr().?.getOrCreateMetadataForLazySymbol(elf_file, lazy_sym) catch |err|
6173 const sym_index = elf_file.zigObjectPtr().?.getOrCreateMetadataForLazySymbol(elf_file, pt, lazy_sym) catch |err|
61306174 return func.fail("{s} creating lazy symbol", .{@errorName(err)});
61316175 const sym = elf_file.symbol(sym_index);
61326176 try func.genSetReg(Type.usize, addr_reg, .{ .load_symbol = .{ .sym = sym.esym_index } });
......@@ -6239,7 +6283,8 @@ fn airReduce(func: *Func, inst: Air.Inst.Index) !void {
62396283}
62406284
62416285fn airAggregateInit(func: *Func, inst: Air.Inst.Index) !void {
6242 const zcu = func.bin_file.comp.module.?;
6286 const pt = func.pt;
6287 const zcu = pt.zcu;
62436288 const result_ty = func.typeOfIndex(inst);
62446289 const len: usize = @intCast(result_ty.arrayLen(zcu));
62456290 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
......@@ -6248,21 +6293,21 @@ fn airAggregateInit(func: *Func, inst: Air.Inst.Index) !void {
62486293 const result: MCValue = result: {
62496294 switch (result_ty.zigTypeTag(zcu)) {
62506295 .Struct => {
6251 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(result_ty, zcu));
6296 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(result_ty, pt));
62526297 if (result_ty.containerLayout(zcu) == .@"packed") {
62536298 const struct_obj = zcu.typeToStruct(result_ty).?;
62546299 try func.genInlineMemset(
62556300 .{ .lea_frame = .{ .index = frame_index } },
62566301 .{ .immediate = 0 },
6257 .{ .immediate = result_ty.abiSize(zcu) },
6302 .{ .immediate = result_ty.abiSize(pt) },
62586303 );
62596304
62606305 for (elements, 0..) |elem, elem_i_usize| {
62616306 const elem_i: u32 = @intCast(elem_i_usize);
6262 if ((try result_ty.structFieldValueComptime(zcu, elem_i)) != null) continue;
6307 if ((try result_ty.structFieldValueComptime(pt, elem_i)) != null) continue;
62636308
62646309 const elem_ty = result_ty.structFieldType(elem_i, zcu);
6265 const elem_bit_size: u32 = @intCast(elem_ty.bitSize(zcu));
6310 const elem_bit_size: u32 = @intCast(elem_ty.bitSize(pt));
62666311 if (elem_bit_size > 64) {
62676312 return func.fail(
62686313 "TODO airAggregateInit implement packed structs with large fields",
......@@ -6270,9 +6315,9 @@ fn airAggregateInit(func: *Func, inst: Air.Inst.Index) !void {
62706315 );
62716316 }
62726317
6273 const elem_abi_size: u32 = @intCast(elem_ty.abiSize(zcu));
6318 const elem_abi_size: u32 = @intCast(elem_ty.abiSize(pt));
62746319 const elem_abi_bits = elem_abi_size * 8;
6275 const elem_off = zcu.structPackedFieldBitOffset(struct_obj, elem_i);
6320 const elem_off = pt.structPackedFieldBitOffset(struct_obj, elem_i);
62766321 const elem_byte_off: i32 = @intCast(elem_off / elem_abi_bits * elem_abi_size);
62776322 const elem_bit_off = elem_off % elem_abi_bits;
62786323 const elem_mcv = try func.resolveInst(elem);
......@@ -6293,10 +6338,10 @@ fn airAggregateInit(func: *Func, inst: Air.Inst.Index) !void {
62936338 return func.fail("TODO: airAggregateInit packed structs", .{});
62946339 }
62956340 } else for (elements, 0..) |elem, elem_i| {
6296 if ((try result_ty.structFieldValueComptime(zcu, elem_i)) != null) continue;
6341 if ((try result_ty.structFieldValueComptime(pt, elem_i)) != null) continue;
62976342
62986343 const elem_ty = result_ty.structFieldType(elem_i, zcu);
6299 const elem_off: i32 = @intCast(result_ty.structFieldOffset(elem_i, zcu));
6344 const elem_off: i32 = @intCast(result_ty.structFieldOffset(elem_i, pt));
63006345 const elem_mcv = try func.resolveInst(elem);
63016346 try func.genSetMem(.{ .frame = frame_index }, elem_off, elem_ty, elem_mcv);
63026347 }
......@@ -6304,8 +6349,8 @@ fn airAggregateInit(func: *Func, inst: Air.Inst.Index) !void {
63046349 },
63056350 .Array => {
63066351 const elem_ty = result_ty.childType(zcu);
6307 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(result_ty, zcu));
6308 const elem_size: u32 = @intCast(elem_ty.abiSize(zcu));
6352 const frame_index = try func.allocFrameIndex(FrameAlloc.initSpill(result_ty, pt));
6353 const elem_size: u32 = @intCast(elem_ty.abiSize(pt));
63096354
63106355 for (elements, 0..) |elem, elem_i| {
63116356 const elem_mcv = try func.resolveInst(elem);
......@@ -6325,7 +6370,7 @@ fn airAggregateInit(func: *Func, inst: Air.Inst.Index) !void {
63256370 );
63266371 break :result .{ .load_frame = .{ .index = frame_index } };
63276372 },
6328 else => return func.fail("TODO: airAggregate {}", .{result_ty.fmt(zcu)}),
6373 else => return func.fail("TODO: airAggregate {}", .{result_ty.fmt(pt)}),
63296374 }
63306375 };
63316376
......@@ -6364,11 +6409,11 @@ fn airMulAdd(func: *Func, inst: Air.Inst.Index) !void {
63646409}
63656410
63666411fn resolveInst(func: *Func, ref: Air.Inst.Ref) InnerError!MCValue {
6367 const zcu = func.bin_file.comp.module.?;
6412 const pt = func.pt;
63686413
63696414 // If the type has no codegen bits, no need to store it.
63706415 const inst_ty = func.typeOf(ref);
6371 if (!inst_ty.hasRuntimeBits(zcu))
6416 if (!inst_ty.hasRuntimeBits(pt))
63726417 return .none;
63736418
63746419 const mcv = if (ref.toIndex()) |inst| mcv: {
......@@ -6394,9 +6439,11 @@ fn getResolvedInstValue(func: *Func, inst: Air.Inst.Index) *InstTracking {
63946439}
63956440
63966441fn genTypedValue(func: *Func, val: Value) InnerError!MCValue {
6397 const zcu = func.bin_file.comp.module.?;
6442 const pt = func.pt;
6443 const zcu = pt.zcu;
63986444 const result = try codegen.genTypedValue(
63996445 func.bin_file,
6446 pt,
64006447 func.src_loc,
64016448 val,
64026449 zcu.funcOwnerDeclIndex(func.func_index),
......@@ -6438,7 +6485,8 @@ fn resolveCallingConventionValues(
64386485 fn_info: InternPool.Key.FuncType,
64396486 var_args: []const Type,
64406487) !CallMCValues {
6441 const zcu = func.bin_file.comp.module.?;
6488 const pt = func.pt;
6489 const zcu = pt.zcu;
64426490 const ip = &zcu.intern_pool;
64436491
64446492 const param_types = try func.gpa.alloc(Type, fn_info.param_types.len + var_args.len);
......@@ -6481,14 +6529,14 @@ fn resolveCallingConventionValues(
64816529 // Return values
64826530 if (ret_ty.zigTypeTag(zcu) == .NoReturn) {
64836531 result.return_value = InstTracking.init(.unreach);
6484 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
6532 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
64856533 result.return_value = InstTracking.init(.none);
64866534 } else {
64876535 var ret_tracking: [2]InstTracking = undefined;
64886536 var ret_tracking_i: usize = 0;
64896537 var ret_float_reg_i: usize = 0;
64906538
6491 const classes = mem.sliceTo(&abi.classifySystem(ret_ty, zcu), .none);
6539 const classes = mem.sliceTo(&abi.classifySystem(ret_ty, pt), .none);
64926540
64936541 for (classes) |class| switch (class) {
64946542 .integer => {
......@@ -6521,7 +6569,7 @@ fn resolveCallingConventionValues(
65216569 };
65226570
65236571 result.return_value = switch (ret_tracking_i) {
6524 else => return func.fail("ty {} took {} tracking return indices", .{ ret_ty.fmt(zcu), ret_tracking_i }),
6572 else => return func.fail("ty {} took {} tracking return indices", .{ ret_ty.fmt(pt), ret_tracking_i }),
65256573 1 => ret_tracking[0],
65266574 2 => InstTracking.init(.{ .register_pair = .{
65276575 ret_tracking[0].short.register, ret_tracking[1].short.register,
......@@ -6532,7 +6580,7 @@ fn resolveCallingConventionValues(
65326580 var param_float_reg_i: usize = 0;
65336581
65346582 for (param_types, result.args) |ty, *arg| {
6535 if (!ty.hasRuntimeBitsIgnoreComptime(zcu)) {
6583 if (!ty.hasRuntimeBitsIgnoreComptime(pt)) {
65366584 assert(cc == .Unspecified);
65376585 arg.* = .none;
65386586 continue;
......@@ -6541,7 +6589,7 @@ fn resolveCallingConventionValues(
65416589 var arg_mcv: [2]MCValue = undefined;
65426590 var arg_mcv_i: usize = 0;
65436591
6544 const classes = mem.sliceTo(&abi.classifySystem(ty, zcu), .none);
6592 const classes = mem.sliceTo(&abi.classifySystem(ty, pt), .none);
65456593
65466594 for (classes) |class| switch (class) {
65476595 .integer => {
......@@ -6576,7 +6624,7 @@ fn resolveCallingConventionValues(
65766624 else => return func.fail("TODO: C calling convention arg class {}", .{class}),
65776625 } else {
65786626 arg.* = switch (arg_mcv_i) {
6579 else => return func.fail("ty {} took {} tracking arg indices", .{ ty.fmt(zcu), arg_mcv_i }),
6627 else => return func.fail("ty {} took {} tracking arg indices", .{ ty.fmt(pt), arg_mcv_i }),
65806628 1 => arg_mcv[0],
65816629 2 => .{ .register_pair = .{ arg_mcv[0].register, arg_mcv[1].register } },
65826630 };
......@@ -6621,12 +6669,14 @@ fn parseRegName(name: []const u8) ?Register {
66216669}
66226670
66236671fn typeOf(func: *Func, inst: Air.Inst.Ref) Type {
6624 const zcu = func.bin_file.comp.module.?;
6672 const pt = func.pt;
6673 const zcu = pt.zcu;
66256674 return func.air.typeOf(inst, &zcu.intern_pool);
66266675}
66276676
66286677fn typeOfIndex(func: *Func, inst: Air.Inst.Index) Type {
6629 const zcu = func.bin_file.comp.module.?;
6678 const pt = func.pt;
6679 const zcu = pt.zcu;
66306680 return func.air.typeOfIndex(inst, &zcu.intern_pool);
66316681}
66326682
......@@ -6634,40 +6684,41 @@ fn hasFeature(func: *Func, feature: Target.riscv.Feature) bool {
66346684 return Target.riscv.featureSetHas(func.target.cpu.features, feature);
66356685}
66366686
6637pub fn errUnionPayloadOffset(payload_ty: Type, zcu: *Zcu) u64 {
6638 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) return 0;
6639 const payload_align = payload_ty.abiAlignment(zcu);
6640 const error_align = Type.anyerror.abiAlignment(zcu);
6641 if (payload_align.compare(.gte, error_align) or !payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
6687pub fn errUnionPayloadOffset(payload_ty: Type, pt: Zcu.PerThread) u64 {
6688 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) return 0;
6689 const payload_align = payload_ty.abiAlignment(pt);
6690 const error_align = Type.anyerror.abiAlignment(pt);
6691 if (payload_align.compare(.gte, error_align) or !payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
66426692 return 0;
66436693 } else {
6644 return payload_align.forward(Type.anyerror.abiSize(zcu));
6694 return payload_align.forward(Type.anyerror.abiSize(pt));
66456695 }
66466696}
66476697
6648pub fn errUnionErrorOffset(payload_ty: Type, zcu: *Zcu) u64 {
6649 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) return 0;
6650 const payload_align = payload_ty.abiAlignment(zcu);
6651 const error_align = Type.anyerror.abiAlignment(zcu);
6652 if (payload_align.compare(.gte, error_align) and payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
6653 return error_align.forward(payload_ty.abiSize(zcu));
6698pub fn errUnionErrorOffset(payload_ty: Type, pt: Zcu.PerThread) u64 {
6699 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) return 0;
6700 const payload_align = payload_ty.abiAlignment(pt);
6701 const error_align = Type.anyerror.abiAlignment(pt);
6702 if (payload_align.compare(.gte, error_align) and payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
6703 return error_align.forward(payload_ty.abiSize(pt));
66546704 } else {
66556705 return 0;
66566706 }
66576707}
66586708
66596709fn promoteInt(func: *Func, ty: Type) Type {
6660 const mod = func.bin_file.comp.module.?;
6710 const pt = func.pt;
6711 const zcu = pt.zcu;
66616712 const int_info: InternPool.Key.IntType = switch (ty.toIntern()) {
66626713 .bool_type => .{ .signedness = .unsigned, .bits = 1 },
6663 else => if (ty.isAbiInt(mod)) ty.intInfo(mod) else return ty,
6714 else => if (ty.isAbiInt(zcu)) ty.intInfo(zcu) else return ty,
66646715 };
66656716 for ([_]Type{
66666717 Type.c_int, Type.c_uint,
66676718 Type.c_long, Type.c_ulong,
66686719 Type.c_longlong, Type.c_ulonglong,
66696720 }) |promote_ty| {
6670 const promote_info = promote_ty.intInfo(mod);
6721 const promote_info = promote_ty.intInfo(zcu);
66716722 if (int_info.signedness == .signed and promote_info.signedness == .unsigned) continue;
66726723 if (int_info.bits + @intFromBool(int_info.signedness == .unsigned and
66736724 promote_info.signedness == .signed) <= promote_info.bits) return promote_ty;
src/arch/riscv64/Emit.zig+3-2
......@@ -1,5 +1,6 @@
11//! This file contains the functionality for emitting RISC-V MIR as machine code
22
3bin_file: *link.File,
34lower: Lower,
45debug_output: DebugInfoOutput,
56code: *std.ArrayList(u8),
......@@ -48,7 +49,7 @@ pub fn emitMir(emit: *Emit) Error!void {
4849 .Lib => emit.lower.link_mode == .static,
4950 };
5051
51 if (emit.lower.bin_file.cast(link.File.Elf)) |elf_file| {
52 if (emit.bin_file.cast(link.File.Elf)) |elf_file| {
5253 const atom_ptr = elf_file.symbol(symbol.atom_index).atom(elf_file).?;
5354 const sym_index = elf_file.zigObjectPtr().?.symbol(symbol.sym_index);
5455 const sym = elf_file.symbol(sym_index);
......@@ -77,7 +78,7 @@ pub fn emitMir(emit: *Emit) Error!void {
7778 } else return emit.fail("TODO: load_symbol_reloc non-ELF", .{});
7879 },
7980 .call_extern_fn_reloc => |symbol| {
80 if (emit.lower.bin_file.cast(link.File.Elf)) |elf_file| {
81 if (emit.bin_file.cast(link.File.Elf)) |elf_file| {
8182 const atom_ptr = elf_file.symbol(symbol.atom_index).atom(elf_file).?;
8283
8384 const r_type: u32 = @intFromEnum(std.elf.R_RISCV.CALL_PLT);
src/arch/riscv64/Lower.zig+6-6
......@@ -1,6 +1,6 @@
11//! This file contains the functionality for lowering RISC-V MIR to Instructions
22
3bin_file: *link.File,
3pt: Zcu.PerThread,
44output_mode: std.builtin.OutputMode,
55link_mode: std.builtin.LinkMode,
66pic: bool,
......@@ -44,7 +44,7 @@ pub fn lowerMir(lower: *Lower, index: Mir.Inst.Index) Error!struct {
4444 insts: []const Instruction,
4545 relocs: []const Reloc,
4646} {
47 const zcu = lower.bin_file.comp.module.?;
47 const pt = lower.pt;
4848
4949 lower.result_insts = undefined;
5050 lower.result_relocs = undefined;
......@@ -243,11 +243,11 @@ pub fn lowerMir(lower: *Lower, index: Mir.Inst.Index) Error!struct {
243243
244244 const class = rs1.class();
245245 const ty = compare.ty;
246 const size = std.math.ceilPowerOfTwo(u64, ty.bitSize(zcu)) catch {
247 return lower.fail("pseudo_compare size {}", .{ty.bitSize(zcu)});
246 const size = std.math.ceilPowerOfTwo(u64, ty.bitSize(pt)) catch {
247 return lower.fail("pseudo_compare size {}", .{ty.bitSize(pt)});
248248 };
249249
250 const is_unsigned = ty.isUnsignedInt(zcu);
250 const is_unsigned = ty.isUnsignedInt(pt.zcu);
251251
252252 const less_than: Encoding.Mnemonic = if (is_unsigned) .sltu else .slt;
253253
......@@ -502,7 +502,7 @@ pub fn fail(lower: *Lower, comptime format: []const u8, args: anytype) Error {
502502}
503503
504504fn hasFeature(lower: *Lower, feature: std.Target.riscv.Feature) bool {
505 const target = lower.bin_file.comp.module.?.getTarget();
505 const target = lower.pt.zcu.getTarget();
506506 const features = target.cpu.features;
507507 return std.Target.riscv.featureSetHas(features, feature);
508508}
src/arch/riscv64/abi.zig+28-27
......@@ -9,15 +9,15 @@ const assert = std.debug.assert;
99
1010pub const Class = enum { memory, byval, integer, double_integer, fields };
1111
12pub fn classifyType(ty: Type, mod: *Zcu) Class {
13 const target = mod.getTarget();
14 std.debug.assert(ty.hasRuntimeBitsIgnoreComptime(mod));
12pub fn classifyType(ty: Type, pt: Zcu.PerThread) Class {
13 const target = pt.zcu.getTarget();
14 std.debug.assert(ty.hasRuntimeBitsIgnoreComptime(pt));
1515
1616 const max_byval_size = target.ptrBitWidth() * 2;
17 switch (ty.zigTypeTag(mod)) {
17 switch (ty.zigTypeTag(pt.zcu)) {
1818 .Struct => {
19 const bit_size = ty.bitSize(mod);
20 if (ty.containerLayout(mod) == .@"packed") {
19 const bit_size = ty.bitSize(pt);
20 if (ty.containerLayout(pt.zcu) == .@"packed") {
2121 if (bit_size > max_byval_size) return .memory;
2222 return .byval;
2323 }
......@@ -25,12 +25,12 @@ pub fn classifyType(ty: Type, mod: *Zcu) Class {
2525 if (std.Target.riscv.featureSetHas(target.cpu.features, .d)) fields: {
2626 var any_fp = false;
2727 var field_count: usize = 0;
28 for (0..ty.structFieldCount(mod)) |field_index| {
29 const field_ty = ty.structFieldType(field_index, mod);
30 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
28 for (0..ty.structFieldCount(pt.zcu)) |field_index| {
29 const field_ty = ty.structFieldType(field_index, pt.zcu);
30 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
3131 if (field_ty.isRuntimeFloat())
3232 any_fp = true
33 else if (!field_ty.isAbiInt(mod))
33 else if (!field_ty.isAbiInt(pt.zcu))
3434 break :fields;
3535 field_count += 1;
3636 if (field_count > 2) break :fields;
......@@ -45,8 +45,8 @@ pub fn classifyType(ty: Type, mod: *Zcu) Class {
4545 return .integer;
4646 },
4747 .Union => {
48 const bit_size = ty.bitSize(mod);
49 if (ty.containerLayout(mod) == .@"packed") {
48 const bit_size = ty.bitSize(pt);
49 if (ty.containerLayout(pt.zcu) == .@"packed") {
5050 if (bit_size > max_byval_size) return .memory;
5151 return .byval;
5252 }
......@@ -58,21 +58,21 @@ pub fn classifyType(ty: Type, mod: *Zcu) Class {
5858 .Bool => return .integer,
5959 .Float => return .byval,
6060 .Int, .Enum, .ErrorSet => {
61 const bit_size = ty.bitSize(mod);
61 const bit_size = ty.bitSize(pt);
6262 if (bit_size > max_byval_size) return .memory;
6363 return .byval;
6464 },
6565 .Vector => {
66 const bit_size = ty.bitSize(mod);
66 const bit_size = ty.bitSize(pt);
6767 if (bit_size > max_byval_size) return .memory;
6868 return .integer;
6969 },
7070 .Optional => {
71 std.debug.assert(ty.isPtrLikeOptional(mod));
71 std.debug.assert(ty.isPtrLikeOptional(pt.zcu));
7272 return .byval;
7373 },
7474 .Pointer => {
75 std.debug.assert(!ty.isSlice(mod));
75 std.debug.assert(!ty.isSlice(pt.zcu));
7676 return .byval;
7777 },
7878 .ErrorUnion,
......@@ -97,18 +97,19 @@ pub const SystemClass = enum { integer, float, memory, none };
9797
9898/// There are a maximum of 8 possible return slots. Returned values are in
9999/// the beginning of the array; unused slots are filled with .none.
100pub fn classifySystem(ty: Type, zcu: *Zcu) [8]SystemClass {
100pub fn classifySystem(ty: Type, pt: Zcu.PerThread) [8]SystemClass {
101 const zcu = pt.zcu;
101102 var result = [1]SystemClass{.none} ** 8;
102103 const memory_class = [_]SystemClass{
103104 .memory, .none, .none, .none,
104105 .none, .none, .none, .none,
105106 };
106 switch (ty.zigTypeTag(zcu)) {
107 switch (ty.zigTypeTag(pt.zcu)) {
107108 .Bool, .Void, .NoReturn => {
108109 result[0] = .integer;
109110 return result;
110111 },
111 .Pointer => switch (ty.ptrSize(zcu)) {
112 .Pointer => switch (ty.ptrSize(pt.zcu)) {
112113 .Slice => {
113114 result[0] = .integer;
114115 result[1] = .integer;
......@@ -120,17 +121,17 @@ pub fn classifySystem(ty: Type, zcu: *Zcu) [8]SystemClass {
120121 },
121122 },
122123 .Optional => {
123 if (ty.isPtrLikeOptional(zcu)) {
124 if (ty.isPtrLikeOptional(pt.zcu)) {
124125 result[0] = .integer;
125126 return result;
126127 }
127128 result[0] = .integer;
128 if (ty.optionalChild(zcu).abiSize(zcu) == 0) return result;
129 if (ty.optionalChild(zcu).abiSize(pt) == 0) return result;
129130 result[1] = .integer;
130131 return result;
131132 },
132133 .Int, .Enum, .ErrorSet => {
133 const int_bits = ty.intInfo(zcu).bits;
134 const int_bits = ty.intInfo(pt.zcu).bits;
134135 if (int_bits <= 64) {
135136 result[0] = .integer;
136137 return result;
......@@ -155,8 +156,8 @@ pub fn classifySystem(ty: Type, zcu: *Zcu) [8]SystemClass {
155156 unreachable; // support split float args
156157 },
157158 .ErrorUnion => {
158 const payload_ty = ty.errorUnionPayload(zcu);
159 const payload_bits = payload_ty.bitSize(zcu);
159 const payload_ty = ty.errorUnionPayload(pt.zcu);
160 const payload_bits = payload_ty.bitSize(pt);
160161
161162 // the error union itself
162163 result[0] = .integer;
......@@ -167,8 +168,8 @@ pub fn classifySystem(ty: Type, zcu: *Zcu) [8]SystemClass {
167168 return memory_class;
168169 },
169170 .Struct => {
170 const layout = ty.containerLayout(zcu);
171 const ty_size = ty.abiSize(zcu);
171 const layout = ty.containerLayout(pt.zcu);
172 const ty_size = ty.abiSize(pt);
172173
173174 if (layout == .@"packed") {
174175 assert(ty_size <= 16);
......@@ -180,7 +181,7 @@ pub fn classifySystem(ty: Type, zcu: *Zcu) [8]SystemClass {
180181 return memory_class;
181182 },
182183 .Array => {
183 const ty_size = ty.abiSize(zcu);
184 const ty_size = ty.abiSize(pt);
184185 if (ty_size <= 8) {
185186 result[0] = .integer;
186187 return result;
src/arch/sparc64/CodeGen.zig+125-95
......@@ -11,11 +11,9 @@ const Allocator = mem.Allocator;
1111const builtin = @import("builtin");
1212const link = @import("../../link.zig");
1313const Zcu = @import("../../Zcu.zig");
14/// Deprecated.
15const Module = Zcu;
1614const InternPool = @import("../../InternPool.zig");
1715const Value = @import("../../Value.zig");
18const ErrorMsg = Module.ErrorMsg;
16const ErrorMsg = Zcu.ErrorMsg;
1917const codegen = @import("../../codegen.zig");
2018const Air = @import("../../Air.zig");
2119const Mir = @import("Mir.zig");
......@@ -52,6 +50,7 @@ const RegisterView = enum(u1) {
5250};
5351
5452gpa: Allocator,
53pt: Zcu.PerThread,
5554air: Air,
5655liveness: Liveness,
5756bin_file: *link.File,
......@@ -64,7 +63,7 @@ args: []MCValue,
6463ret_mcv: MCValue,
6564fn_type: Type,
6665arg_index: usize,
67src_loc: Module.LazySrcLoc,
66src_loc: Zcu.LazySrcLoc,
6867stack_align: Alignment,
6968
7069/// MIR Instructions
......@@ -263,15 +262,16 @@ const BigTomb = struct {
263262
264263pub fn generate(
265264 lf: *link.File,
266 src_loc: Module.LazySrcLoc,
265 pt: Zcu.PerThread,
266 src_loc: Zcu.LazySrcLoc,
267267 func_index: InternPool.Index,
268268 air: Air,
269269 liveness: Liveness,
270270 code: *std.ArrayList(u8),
271271 debug_output: DebugInfoOutput,
272272) CodeGenError!Result {
273 const gpa = lf.comp.gpa;
274 const zcu = lf.comp.module.?;
273 const zcu = pt.zcu;
274 const gpa = zcu.gpa;
275275 const func = zcu.funcInfo(func_index);
276276 const fn_owner_decl = zcu.declPtr(func.owner_decl);
277277 assert(fn_owner_decl.has_tv);
......@@ -289,11 +289,12 @@ pub fn generate(
289289
290290 var function = Self{
291291 .gpa = gpa,
292 .pt = pt,
292293 .air = air,
293294 .liveness = liveness,
294295 .target = target,
295 .func_index = func_index,
296296 .bin_file = lf,
297 .func_index = func_index,
297298 .code = code,
298299 .debug_output = debug_output,
299300 .err_msg = null,
......@@ -365,7 +366,8 @@ pub fn generate(
365366}
366367
367368fn gen(self: *Self) !void {
368 const mod = self.bin_file.comp.module.?;
369 const pt = self.pt;
370 const mod = pt.zcu;
369371 const cc = self.fn_type.fnCallingConvention(mod);
370372 if (cc != .Naked) {
371373 // TODO Finish function prologue and epilogue for sparc64.
......@@ -493,7 +495,8 @@ fn gen(self: *Self) !void {
493495}
494496
495497fn genBody(self: *Self, body: []const Air.Inst.Index) InnerError!void {
496 const mod = self.bin_file.comp.module.?;
498 const pt = self.pt;
499 const mod = pt.zcu;
497500 const ip = &mod.intern_pool;
498501 const air_tags = self.air.instructions.items(.tag);
499502
......@@ -757,7 +760,8 @@ fn airAddSubWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
757760 const tag = self.air.instructions.items(.tag)[@intFromEnum(inst)];
758761 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
759762 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
760 const mod = self.bin_file.comp.module.?;
763 const pt = self.pt;
764 const mod = pt.zcu;
761765 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
762766 const lhs = try self.resolveInst(extra.lhs);
763767 const rhs = try self.resolveInst(extra.rhs);
......@@ -835,7 +839,8 @@ fn airAddSubWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
835839}
836840
837841fn airAggregateInit(self: *Self, inst: Air.Inst.Index) !void {
838 const mod = self.bin_file.comp.module.?;
842 const pt = self.pt;
843 const mod = pt.zcu;
839844 const vector_ty = self.typeOfIndex(inst);
840845 const len = vector_ty.vectorLen(mod);
841846 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
......@@ -869,7 +874,8 @@ fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
869874}
870875
871876fn airArrayToSlice(self: *Self, inst: Air.Inst.Index) !void {
872 const mod = self.bin_file.comp.module.?;
877 const pt = self.pt;
878 const mod = pt.zcu;
873879 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
874880 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
875881 const ptr_ty = self.typeOf(ty_op.operand);
......@@ -1006,7 +1012,7 @@ fn airAsm(self: *Self, inst: Air.Inst.Index) !void {
10061012}
10071013
10081014fn airArg(self: *Self, inst: Air.Inst.Index) !void {
1009 const mod = self.bin_file.comp.module.?;
1015 const pt = self.pt;
10101016 const arg_index = self.arg_index;
10111017 self.arg_index += 1;
10121018
......@@ -1016,8 +1022,8 @@ fn airArg(self: *Self, inst: Air.Inst.Index) !void {
10161022 const mcv = blk: {
10171023 switch (arg) {
10181024 .stack_offset => |off| {
1019 const abi_size = math.cast(u32, ty.abiSize(mod)) orelse {
1020 return self.fail("type '{}' too big to fit into stack frame", .{ty.fmt(mod)});
1025 const abi_size = math.cast(u32, ty.abiSize(pt)) orelse {
1026 return self.fail("type '{}' too big to fit into stack frame", .{ty.fmt(pt)});
10211027 };
10221028 const offset = off + abi_size;
10231029 break :blk MCValue{ .stack_offset = offset };
......@@ -1205,7 +1211,8 @@ fn airBreakpoint(self: *Self) !void {
12051211}
12061212
12071213fn airByteSwap(self: *Self, inst: Air.Inst.Index) !void {
1208 const mod = self.bin_file.comp.module.?;
1214 const pt = self.pt;
1215 const mod = pt.zcu;
12091216 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
12101217
12111218 // We have hardware byteswapper in SPARCv9, don't let mainstream compilers mislead you.
......@@ -1228,7 +1235,7 @@ fn airByteSwap(self: *Self, inst: Air.Inst.Index) !void {
12281235 if (int_info.bits == 8) break :result operand;
12291236
12301237 const abi_size = int_info.bits >> 3;
1231 const abi_align = operand_ty.abiAlignment(mod);
1238 const abi_align = operand_ty.abiAlignment(pt);
12321239 const opposite_endian_asi = switch (self.target.cpu.arch.endian()) {
12331240 Endian.big => ASI.asi_primary_little,
12341241 Endian.little => ASI.asi_primary,
......@@ -1297,7 +1304,8 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
12971304 const extra = self.air.extraData(Air.Call, pl_op.payload);
12981305 const args = @as([]const Air.Inst.Ref, @ptrCast(self.air.extra[extra.end .. extra.end + extra.data.args_len]));
12991306 const ty = self.typeOf(callee);
1300 const mod = self.bin_file.comp.module.?;
1307 const pt = self.pt;
1308 const mod = pt.zcu;
13011309 const fn_ty = switch (ty.zigTypeTag(mod)) {
13021310 .Fn => ty,
13031311 .Pointer => ty.childType(mod),
......@@ -1341,7 +1349,7 @@ fn airCall(self: *Self, inst: Air.Inst.Index, modifier: std.builtin.CallModifier
13411349
13421350 // Due to incremental compilation, how function calls are generated depends
13431351 // on linking.
1344 if (try self.air.value(callee, mod)) |func_value| {
1352 if (try self.air.value(callee, pt)) |func_value| {
13451353 if (self.bin_file.tag == link.File.Elf.base_tag) {
13461354 switch (mod.intern_pool.indexToKey(func_value.ip_index)) {
13471355 .func => |func| {
......@@ -1429,7 +1437,8 @@ fn airClz(self: *Self, inst: Air.Inst.Index) !void {
14291437
14301438fn airCmp(self: *Self, inst: Air.Inst.Index, op: math.CompareOperator) !void {
14311439 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
1432 const mod = self.bin_file.comp.module.?;
1440 const pt = self.pt;
1441 const mod = pt.zcu;
14331442 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
14341443 const lhs = try self.resolveInst(bin_op.lhs);
14351444 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -1444,7 +1453,7 @@ fn airCmp(self: *Self, inst: Air.Inst.Index, op: math.CompareOperator) !void {
14441453 .ErrorSet => Type.u16,
14451454 .Optional => blk: {
14461455 const payload_ty = lhs_ty.optionalChild(mod);
1447 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
1456 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
14481457 break :blk Type.u1;
14491458 } else if (lhs_ty.isPtrLikeOptional(mod)) {
14501459 break :blk Type.usize;
......@@ -1655,7 +1664,8 @@ fn airCtz(self: *Self, inst: Air.Inst.Index) !void {
16551664}
16561665
16571666fn airDbgInlineBlock(self: *Self, inst: Air.Inst.Index) !void {
1658 const mod = self.bin_file.comp.module.?;
1667 const pt = self.pt;
1668 const mod = pt.zcu;
16591669 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
16601670 const extra = self.air.extraData(Air.DbgInlineBlock, ty_pl.payload);
16611671 const func = mod.funcInfo(extra.data.func);
......@@ -1753,7 +1763,8 @@ fn airIntCast(self: *Self, inst: Air.Inst.Index) !void {
17531763 if (self.liveness.isUnused(inst))
17541764 return self.finishAir(inst, .dead, .{ ty_op.operand, .none, .none });
17551765
1756 const mod = self.bin_file.comp.module.?;
1766 const pt = self.pt;
1767 const mod = pt.zcu;
17571768 const operand_ty = self.typeOf(ty_op.operand);
17581769 const operand = try self.resolveInst(ty_op.operand);
17591770 const info_a = operand_ty.intInfo(mod);
......@@ -1814,12 +1825,13 @@ fn airIsNonNull(self: *Self, inst: Air.Inst.Index) !void {
18141825}
18151826
18161827fn airLoad(self: *Self, inst: Air.Inst.Index) !void {
1817 const mod = self.bin_file.comp.module.?;
1828 const pt = self.pt;
1829 const mod = pt.zcu;
18181830 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
18191831 const elem_ty = self.typeOfIndex(inst);
1820 const elem_size = elem_ty.abiSize(mod);
1832 const elem_size = elem_ty.abiSize(pt);
18211833 const result: MCValue = result: {
1822 if (!elem_ty.hasRuntimeBits(mod))
1834 if (!elem_ty.hasRuntimeBits(pt))
18231835 break :result MCValue.none;
18241836
18251837 const ptr = try self.resolveInst(ty_op.operand);
......@@ -1898,7 +1910,7 @@ fn airMod(self: *Self, inst: Air.Inst.Index) !void {
18981910 const rhs = try self.resolveInst(bin_op.rhs);
18991911 const lhs_ty = self.typeOf(bin_op.lhs);
19001912 const rhs_ty = self.typeOf(bin_op.rhs);
1901 assert(lhs_ty.eql(rhs_ty, self.bin_file.comp.module.?));
1913 assert(lhs_ty.eql(rhs_ty, self.pt.zcu));
19021914
19031915 if (self.liveness.isUnused(inst))
19041916 return self.finishAir(inst, .dead, .{ bin_op.lhs, bin_op.rhs, .none });
......@@ -2040,7 +2052,8 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
20402052 //const tag = self.air.instructions.items(.tag)[@intFromEnum(inst)];
20412053 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
20422054 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
2043 const mod = self.bin_file.comp.module.?;
2055 const pt = self.pt;
2056 const mod = pt.zcu;
20442057 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
20452058 const lhs = try self.resolveInst(extra.lhs);
20462059 const rhs = try self.resolveInst(extra.rhs);
......@@ -2104,7 +2117,8 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
21042117
21052118fn airNot(self: *Self, inst: Air.Inst.Index) !void {
21062119 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
2107 const mod = self.bin_file.comp.module.?;
2120 const pt = self.pt;
2121 const mod = pt.zcu;
21082122 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
21092123 const operand = try self.resolveInst(ty_op.operand);
21102124 const operand_ty = self.typeOf(ty_op.operand);
......@@ -2336,7 +2350,8 @@ fn airShlSat(self: *Self, inst: Air.Inst.Index) !void {
23362350fn airShlWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
23372351 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
23382352 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
2339 const mod = self.bin_file.comp.module.?;
2353 const pt = self.pt;
2354 const mod = pt.zcu;
23402355 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
23412356 const lhs = try self.resolveInst(extra.lhs);
23422357 const rhs = try self.resolveInst(extra.rhs);
......@@ -2441,7 +2456,8 @@ fn airSlice(self: *Self, inst: Air.Inst.Index) !void {
24412456}
24422457
24432458fn airSliceElemVal(self: *Self, inst: Air.Inst.Index) !void {
2444 const mod = self.bin_file.comp.module.?;
2459 const pt = self.pt;
2460 const mod = pt.zcu;
24452461 const is_volatile = false; // TODO
24462462 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
24472463
......@@ -2452,7 +2468,7 @@ fn airSliceElemVal(self: *Self, inst: Air.Inst.Index) !void {
24522468
24532469 const slice_ty = self.typeOf(bin_op.lhs);
24542470 const elem_ty = slice_ty.childType(mod);
2455 const elem_size = elem_ty.abiSize(mod);
2471 const elem_size = elem_ty.abiSize(pt);
24562472
24572473 const slice_ptr_field_type = slice_ty.slicePtrFieldType(mod);
24582474
......@@ -2566,10 +2582,10 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
25662582 const operand = extra.struct_operand;
25672583 const index = extra.field_index;
25682584 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
2569 const mod = self.bin_file.comp.module.?;
2585 const pt = self.pt;
25702586 const mcv = try self.resolveInst(operand);
25712587 const struct_ty = self.typeOf(operand);
2572 const struct_field_offset = @as(u32, @intCast(struct_ty.structFieldOffset(index, mod)));
2588 const struct_field_offset = @as(u32, @intCast(struct_ty.structFieldOffset(index, pt)));
25732589
25742590 switch (mcv) {
25752591 .dead, .unreach => unreachable,
......@@ -2699,13 +2715,14 @@ fn airUnionInit(self: *Self, inst: Air.Inst.Index) !void {
26992715}
27002716
27012717fn airUnwrapErrErr(self: *Self, inst: Air.Inst.Index) !void {
2702 const mod = self.bin_file.comp.module.?;
2718 const pt = self.pt;
2719 const mod = pt.zcu;
27032720 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
27042721 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
27052722 const error_union_ty = self.typeOf(ty_op.operand);
27062723 const payload_ty = error_union_ty.errorUnionPayload(mod);
27072724 const mcv = try self.resolveInst(ty_op.operand);
2708 if (!payload_ty.hasRuntimeBits(mod)) break :result mcv;
2725 if (!payload_ty.hasRuntimeBits(pt)) break :result mcv;
27092726
27102727 return self.fail("TODO implement unwrap error union error for non-empty payloads", .{});
27112728 };
......@@ -2713,12 +2730,13 @@ fn airUnwrapErrErr(self: *Self, inst: Air.Inst.Index) !void {
27132730}
27142731
27152732fn airUnwrapErrPayload(self: *Self, inst: Air.Inst.Index) !void {
2716 const mod = self.bin_file.comp.module.?;
2733 const pt = self.pt;
2734 const mod = pt.zcu;
27172735 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
27182736 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
27192737 const error_union_ty = self.typeOf(ty_op.operand);
27202738 const payload_ty = error_union_ty.errorUnionPayload(mod);
2721 if (!payload_ty.hasRuntimeBits(mod)) break :result MCValue.none;
2739 if (!payload_ty.hasRuntimeBits(pt)) break :result MCValue.none;
27222740
27232741 return self.fail("TODO implement unwrap error union payload for non-empty payloads", .{});
27242742 };
......@@ -2727,13 +2745,14 @@ fn airUnwrapErrPayload(self: *Self, inst: Air.Inst.Index) !void {
27272745
27282746/// E to E!T
27292747fn airWrapErrUnionErr(self: *Self, inst: Air.Inst.Index) !void {
2730 const mod = self.bin_file.comp.module.?;
2748 const pt = self.pt;
2749 const mod = pt.zcu;
27312750 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
27322751 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
27332752 const error_union_ty = ty_op.ty.toType();
27342753 const payload_ty = error_union_ty.errorUnionPayload(mod);
27352754 const mcv = try self.resolveInst(ty_op.operand);
2736 if (!payload_ty.hasRuntimeBits(mod)) break :result mcv;
2755 if (!payload_ty.hasRuntimeBits(pt)) break :result mcv;
27372756
27382757 return self.fail("TODO implement wrap errunion error for non-empty payloads", .{});
27392758 };
......@@ -2748,13 +2767,13 @@ fn airWrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) !void {
27482767}
27492768
27502769fn airWrapOptional(self: *Self, inst: Air.Inst.Index) !void {
2751 const mod = self.bin_file.comp.module.?;
2770 const pt = self.pt;
27522771 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
27532772 const result: MCValue = if (self.liveness.isUnused(inst)) .dead else result: {
27542773 const optional_ty = self.typeOfIndex(inst);
27552774
27562775 // Optional with a zero-bit payload type is just a boolean true
2757 if (optional_ty.abiSize(mod) == 1)
2776 if (optional_ty.abiSize(pt) == 1)
27582777 break :result MCValue{ .immediate = 1 };
27592778
27602779 return self.fail("TODO implement wrap optional for {}", .{self.target.cpu.arch});
......@@ -2788,10 +2807,11 @@ fn allocMem(self: *Self, inst: Air.Inst.Index, abi_size: u32, abi_align: Alignme
27882807
27892808/// Use a pointer instruction as the basis for allocating stack memory.
27902809fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !u32 {
2791 const mod = self.bin_file.comp.module.?;
2810 const pt = self.pt;
2811 const mod = pt.zcu;
27922812 const elem_ty = self.typeOfIndex(inst).childType(mod);
27932813
2794 if (!elem_ty.hasRuntimeBits(mod)) {
2814 if (!elem_ty.hasRuntimeBits(pt)) {
27952815 // As this stack item will never be dereferenced at runtime,
27962816 // return the stack offset 0. Stack offset 0 will be where all
27972817 // zero-sized stack allocations live as non-zero-sized
......@@ -2799,21 +2819,21 @@ fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !u32 {
27992819 return @as(u32, 0);
28002820 }
28012821
2802 const abi_size = math.cast(u32, elem_ty.abiSize(mod)) orelse {
2803 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
2822 const abi_size = math.cast(u32, elem_ty.abiSize(pt)) orelse {
2823 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(pt)});
28042824 };
28052825 // TODO swap this for inst.ty.ptrAlign
2806 const abi_align = elem_ty.abiAlignment(mod);
2826 const abi_align = elem_ty.abiAlignment(pt);
28072827 return self.allocMem(inst, abi_size, abi_align);
28082828}
28092829
28102830fn allocRegOrMem(self: *Self, inst: Air.Inst.Index, reg_ok: bool) !MCValue {
2811 const mod = self.bin_file.comp.module.?;
2831 const pt = self.pt;
28122832 const elem_ty = self.typeOfIndex(inst);
2813 const abi_size = math.cast(u32, elem_ty.abiSize(mod)) orelse {
2814 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(mod)});
2833 const abi_size = math.cast(u32, elem_ty.abiSize(pt)) orelse {
2834 return self.fail("type '{}' too big to fit into stack frame", .{elem_ty.fmt(pt)});
28152835 };
2816 const abi_align = elem_ty.abiAlignment(mod);
2836 const abi_align = elem_ty.abiAlignment(pt);
28172837 self.stack_align = self.stack_align.max(abi_align);
28182838
28192839 if (reg_ok) {
......@@ -2855,7 +2875,8 @@ fn binOp(
28552875 rhs_ty: Type,
28562876 metadata: ?BinOpMetadata,
28572877) InnerError!MCValue {
2858 const mod = self.bin_file.comp.module.?;
2878 const pt = self.pt;
2879 const mod = pt.zcu;
28592880 switch (tag) {
28602881 .add,
28612882 .sub,
......@@ -2996,7 +3017,7 @@ fn binOp(
29963017 .One => ptr_ty.childType(mod).childType(mod), // ptr to array, so get array element type
29973018 else => ptr_ty.childType(mod),
29983019 };
2999 const elem_size = elem_ty.abiSize(mod);
3020 const elem_size = elem_ty.abiSize(pt);
30003021
30013022 if (elem_size == 1) {
30023023 const base_tag: Mir.Inst.Tag = switch (tag) {
......@@ -3396,8 +3417,8 @@ fn binOpRegister(
33963417fn br(self: *Self, block: Air.Inst.Index, operand: Air.Inst.Ref) !void {
33973418 const block_data = self.blocks.getPtr(block).?;
33983419
3399 const mod = self.bin_file.comp.module.?;
3400 if (self.typeOf(operand).hasRuntimeBits(mod)) {
3420 const pt = self.pt;
3421 if (self.typeOf(operand).hasRuntimeBits(pt)) {
34013422 const operand_mcv = try self.resolveInst(operand);
34023423 const block_mcv = block_data.mcv;
34033424 if (block_mcv == .none) {
......@@ -3516,17 +3537,18 @@ fn ensureProcessDeathCapacity(self: *Self, additional_count: usize) !void {
35163537
35173538/// Given an error union, returns the payload
35183539fn errUnionPayload(self: *Self, error_union_mcv: MCValue, error_union_ty: Type) !MCValue {
3519 const mod = self.bin_file.comp.module.?;
3540 const pt = self.pt;
3541 const mod = pt.zcu;
35203542 const err_ty = error_union_ty.errorUnionSet(mod);
35213543 const payload_ty = error_union_ty.errorUnionPayload(mod);
35223544 if (err_ty.errorSetIsEmpty(mod)) {
35233545 return error_union_mcv;
35243546 }
3525 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
3547 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
35263548 return MCValue.none;
35273549 }
35283550
3529 const payload_offset = @as(u32, @intCast(errUnionPayloadOffset(payload_ty, mod)));
3551 const payload_offset = @as(u32, @intCast(errUnionPayloadOffset(payload_ty, pt)));
35303552 switch (error_union_mcv) {
35313553 .register => return self.fail("TODO errUnionPayload for registers", .{}),
35323554 .stack_offset => |off| {
......@@ -3587,7 +3609,8 @@ fn finishAir(self: *Self, inst: Air.Inst.Index, result: MCValue, operands: [Live
35873609}
35883610
35893611fn genArgDbgInfo(self: Self, inst: Air.Inst.Index, mcv: MCValue) !void {
3590 const mod = self.bin_file.comp.module.?;
3612 const pt = self.pt;
3613 const mod = pt.zcu;
35913614 const arg = self.air.instructions.items(.data)[@intFromEnum(inst)].arg;
35923615 const ty = arg.ty.toType();
35933616 const owner_decl = mod.funcOwnerDeclIndex(self.func_index);
......@@ -3736,7 +3759,7 @@ fn genLoadASI(self: *Self, value_reg: Register, addr_reg: Register, off_reg: Reg
37363759}
37373760
37383761fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void {
3739 const mod = self.bin_file.comp.module.?;
3762 const pt = self.pt;
37403763 switch (mcv) {
37413764 .dead => unreachable,
37423765 .unreach, .none => return, // Nothing to do.
......@@ -3935,20 +3958,21 @@ fn genSetReg(self: *Self, ty: Type, reg: Register, mcv: MCValue) InnerError!void
39353958 // The value is in memory at a hard-coded address.
39363959 // If the type is a pointer, it means the pointer address is at this memory location.
39373960 try self.genSetReg(ty, reg, .{ .immediate = addr });
3938 try self.genLoad(reg, reg, i13, 0, ty.abiSize(mod));
3961 try self.genLoad(reg, reg, i13, 0, ty.abiSize(pt));
39393962 },
39403963 .stack_offset => |off| {
39413964 const real_offset = realStackOffset(off);
39423965 const simm13 = math.cast(i13, real_offset) orelse
39433966 return self.fail("TODO larger stack offsets: {}", .{real_offset});
3944 try self.genLoad(reg, .sp, i13, simm13, ty.abiSize(mod));
3967 try self.genLoad(reg, .sp, i13, simm13, ty.abiSize(pt));
39453968 },
39463969 }
39473970}
39483971
39493972fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerError!void {
3950 const mod = self.bin_file.comp.module.?;
3951 const abi_size = ty.abiSize(mod);
3973 const pt = self.pt;
3974 const mod = pt.zcu;
3975 const abi_size = ty.abiSize(pt);
39523976 switch (mcv) {
39533977 .dead => unreachable,
39543978 .unreach, .none => return, // Nothing to do.
......@@ -3956,7 +3980,7 @@ fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerErro
39563980 if (!self.wantSafety())
39573981 return; // The already existing value will do just fine.
39583982 // TODO Upgrade this to a memset call when we have that available.
3959 switch (ty.abiSize(mod)) {
3983 switch (ty.abiSize(pt)) {
39603984 1 => return self.genSetStack(ty, stack_offset, .{ .immediate = 0xaa }),
39613985 2 => return self.genSetStack(ty, stack_offset, .{ .immediate = 0xaaaa }),
39623986 4 => return self.genSetStack(ty, stack_offset, .{ .immediate = 0xaaaaaaaa }),
......@@ -3986,7 +4010,7 @@ fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerErro
39864010 try self.genSetStack(wrapped_ty, stack_offset, .{ .register = rwo.reg });
39874011
39884012 const overflow_bit_ty = ty.structFieldType(1, mod);
3989 const overflow_bit_offset = @as(u32, @intCast(ty.structFieldOffset(1, mod)));
4013 const overflow_bit_offset = @as(u32, @intCast(ty.structFieldOffset(1, pt)));
39904014 const cond_reg = try self.register_manager.allocReg(null, gp);
39914015
39924016 // TODO handle floating point CCRs
......@@ -4032,7 +4056,7 @@ fn genSetStack(self: *Self, ty: Type, stack_offset: u32, mcv: MCValue) InnerErro
40324056 const reg = try self.copyToTmpRegister(ty, mcv);
40334057 return self.genSetStack(ty, stack_offset, MCValue{ .register = reg });
40344058 } else {
4035 const ptr_ty = try mod.singleMutPtrType(ty);
4059 const ptr_ty = try pt.singleMutPtrType(ty);
40364060
40374061 const regs = try self.register_manager.allocRegs(4, .{ null, null, null, null }, gp);
40384062 const regs_locks = self.register_manager.lockRegsAssumeUnused(4, regs);
......@@ -4121,12 +4145,13 @@ fn genStoreASI(self: *Self, value_reg: Register, addr_reg: Register, off_reg: Re
41214145}
41224146
41234147fn genTypedValue(self: *Self, val: Value) InnerError!MCValue {
4124 const mod = self.bin_file.comp.module.?;
4148 const pt = self.pt;
41254149 const mcv: MCValue = switch (try codegen.genTypedValue(
41264150 self.bin_file,
4151 pt,
41274152 self.src_loc,
41284153 val,
4129 mod.funcOwnerDeclIndex(self.func_index),
4154 pt.zcu.funcOwnerDeclIndex(self.func_index),
41304155 )) {
41314156 .mcv => |mcv| switch (mcv) {
41324157 .none => .none,
......@@ -4157,14 +4182,15 @@ fn getResolvedInstValue(self: *Self, inst: Air.Inst.Index) MCValue {
41574182}
41584183
41594184fn isErr(self: *Self, ty: Type, operand: MCValue) !MCValue {
4160 const mod = self.bin_file.comp.module.?;
4185 const pt = self.pt;
4186 const mod = pt.zcu;
41614187 const error_type = ty.errorUnionSet(mod);
41624188 const payload_type = ty.errorUnionPayload(mod);
41634189
4164 if (!error_type.hasRuntimeBits(mod)) {
4190 if (!error_type.hasRuntimeBits(pt)) {
41654191 return MCValue{ .immediate = 0 }; // always false
4166 } else if (!payload_type.hasRuntimeBits(mod)) {
4167 if (error_type.abiSize(mod) <= 8) {
4192 } else if (!payload_type.hasRuntimeBits(pt)) {
4193 if (error_type.abiSize(pt) <= 8) {
41684194 const reg_mcv: MCValue = switch (operand) {
41694195 .register => operand,
41704196 else => .{ .register = try self.copyToTmpRegister(error_type, operand) },
......@@ -4255,9 +4281,10 @@ fn jump(self: *Self, inst: Mir.Inst.Index) !void {
42554281}
42564282
42574283fn load(self: *Self, dst_mcv: MCValue, ptr: MCValue, ptr_ty: Type) InnerError!void {
4258 const mod = self.bin_file.comp.module.?;
4284 const pt = self.pt;
4285 const mod = pt.zcu;
42594286 const elem_ty = ptr_ty.childType(mod);
4260 const elem_size = elem_ty.abiSize(mod);
4287 const elem_size = elem_ty.abiSize(pt);
42614288
42624289 switch (ptr) {
42634290 .none => unreachable,
......@@ -4326,7 +4353,8 @@ fn minMax(
43264353 lhs_ty: Type,
43274354 rhs_ty: Type,
43284355) InnerError!MCValue {
4329 const mod = self.bin_file.comp.module.?;
4356 const pt = self.pt;
4357 const mod = pt.zcu;
43304358 assert(lhs_ty.eql(rhs_ty, mod));
43314359 switch (lhs_ty.zigTypeTag(mod)) {
43324360 .Float => return self.fail("TODO min/max on floats", .{}),
......@@ -4446,7 +4474,8 @@ fn realStackOffset(off: u32) u32 {
44464474
44474475/// Caller must call `CallMCValues.deinit`.
44484476fn resolveCallingConventionValues(self: *Self, fn_ty: Type, role: RegisterView) !CallMCValues {
4449 const mod = self.bin_file.comp.module.?;
4477 const pt = self.pt;
4478 const mod = pt.zcu;
44504479 const ip = &mod.intern_pool;
44514480 const fn_info = mod.typeToFunc(fn_ty).?;
44524481 const cc = fn_info.cc;
......@@ -4487,7 +4516,7 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type, role: RegisterView)
44874516 };
44884517
44894518 for (fn_info.param_types.get(ip), result.args) |ty, *result_arg| {
4490 const param_size = @as(u32, @intCast(Type.fromInterned(ty).abiSize(mod)));
4519 const param_size = @as(u32, @intCast(Type.fromInterned(ty).abiSize(pt)));
44914520 if (param_size <= 8) {
44924521 if (next_register < argument_registers.len) {
44934522 result_arg.* = .{ .register = argument_registers[next_register] };
......@@ -4516,10 +4545,10 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type, role: RegisterView)
45164545
45174546 if (ret_ty.zigTypeTag(mod) == .NoReturn) {
45184547 result.return_value = .{ .unreach = {} };
4519 } else if (!ret_ty.hasRuntimeBits(mod)) {
4548 } else if (!ret_ty.hasRuntimeBits(pt)) {
45204549 result.return_value = .{ .none = {} };
45214550 } else {
4522 const ret_ty_size = @as(u32, @intCast(ret_ty.abiSize(mod)));
4551 const ret_ty_size: u32 = @intCast(ret_ty.abiSize(pt));
45234552 // The callee puts the return values in %i0-%i3, which becomes %o0-%o3 inside the caller.
45244553 if (ret_ty_size <= 8) {
45254554 result.return_value = switch (role) {
......@@ -4538,21 +4567,22 @@ fn resolveCallingConventionValues(self: *Self, fn_ty: Type, role: RegisterView)
45384567}
45394568
45404569fn resolveInst(self: *Self, ref: Air.Inst.Ref) InnerError!MCValue {
4541 const mod = self.bin_file.comp.module.?;
4570 const pt = self.pt;
45424571 const ty = self.typeOf(ref);
45434572
45444573 // If the type has no codegen bits, no need to store it.
4545 if (!ty.hasRuntimeBitsIgnoreComptime(mod)) return .none;
4574 if (!ty.hasRuntimeBitsIgnoreComptime(pt)) return .none;
45464575
45474576 if (ref.toIndex()) |inst| {
45484577 return self.getResolvedInstValue(inst);
45494578 }
45504579
4551 return self.genTypedValue((try self.air.value(ref, mod)).?);
4580 return self.genTypedValue((try self.air.value(ref, pt)).?);
45524581}
45534582
45544583fn ret(self: *Self, mcv: MCValue) !void {
4555 const mod = self.bin_file.comp.module.?;
4584 const pt = self.pt;
4585 const mod = pt.zcu;
45564586 const ret_ty = self.fn_type.fnReturnType(mod);
45574587 try self.setRegOrMem(ret_ty, self.ret_mcv, mcv);
45584588
......@@ -4654,8 +4684,8 @@ pub fn spillInstruction(self: *Self, reg: Register, inst: Air.Inst.Index) !void
46544684}
46554685
46564686fn store(self: *Self, ptr: MCValue, value: MCValue, ptr_ty: Type, value_ty: Type) InnerError!void {
4657 const mod = self.bin_file.comp.module.?;
4658 const abi_size = value_ty.abiSize(mod);
4687 const pt = self.pt;
4688 const abi_size = value_ty.abiSize(pt);
46594689
46604690 switch (ptr) {
46614691 .none => unreachable,
......@@ -4696,11 +4726,12 @@ fn store(self: *Self, ptr: MCValue, value: MCValue, ptr_ty: Type, value_ty: Type
46964726
46974727fn structFieldPtr(self: *Self, inst: Air.Inst.Index, operand: Air.Inst.Ref, index: u32) !MCValue {
46984728 return if (self.liveness.isUnused(inst)) .dead else result: {
4699 const mod = self.bin_file.comp.module.?;
4729 const pt = self.pt;
4730 const mod = pt.zcu;
47004731 const mcv = try self.resolveInst(operand);
47014732 const ptr_ty = self.typeOf(operand);
47024733 const struct_ty = ptr_ty.childType(mod);
4703 const struct_field_offset = @as(u32, @intCast(struct_ty.structFieldOffset(index, mod)));
4734 const struct_field_offset = @as(u32, @intCast(struct_ty.structFieldOffset(index, pt)));
47044735 switch (mcv) {
47054736 .ptr_stack_offset => |off| {
47064737 break :result MCValue{ .ptr_stack_offset = off - struct_field_offset };
......@@ -4738,7 +4769,8 @@ fn trunc(
47384769 operand_ty: Type,
47394770 dest_ty: Type,
47404771) !MCValue {
4741 const mod = self.bin_file.comp.module.?;
4772 const pt = self.pt;
4773 const mod = pt.zcu;
47424774 const info_a = operand_ty.intInfo(mod);
47434775 const info_b = dest_ty.intInfo(mod);
47444776
......@@ -4848,7 +4880,7 @@ fn truncRegister(
48484880 }
48494881}
48504882
4851/// TODO support scope overrides. Also note this logic is duplicated with `Module.wantSafety`.
4883/// TODO support scope overrides. Also note this logic is duplicated with `Zcu.wantSafety`.
48524884fn wantSafety(self: *Self) bool {
48534885 return switch (self.bin_file.comp.root_mod.optimize_mode) {
48544886 .Debug => true,
......@@ -4859,11 +4891,9 @@ fn wantSafety(self: *Self) bool {
48594891}
48604892
48614893fn typeOf(self: *Self, inst: Air.Inst.Ref) Type {
4862 const mod = self.bin_file.comp.module.?;
4863 return self.air.typeOf(inst, &mod.intern_pool);
4894 return self.air.typeOf(inst, &self.pt.zcu.intern_pool);
48644895}
48654896
48664897fn typeOfIndex(self: *Self, inst: Air.Inst.Index) Type {
4867 const mod = self.bin_file.comp.module.?;
4868 return self.air.typeOfIndex(inst, &mod.intern_pool);
4898 return self.air.typeOfIndex(inst, &self.pt.zcu.intern_pool);
48694899}
src/arch/sparc64/Emit.zig+2-4
......@@ -6,9 +6,7 @@ const Endian = std.builtin.Endian;
66const assert = std.debug.assert;
77const link = @import("../../link.zig");
88const Zcu = @import("../../Zcu.zig");
9/// Deprecated.
10const Module = Zcu;
11const ErrorMsg = Module.ErrorMsg;
9const ErrorMsg = Zcu.ErrorMsg;
1210const Liveness = @import("../../Liveness.zig");
1311const log = std.log.scoped(.sparcv9_emit);
1412const DebugInfoOutput = @import("../../codegen.zig").DebugInfoOutput;
......@@ -24,7 +22,7 @@ bin_file: *link.File,
2422debug_output: DebugInfoOutput,
2523target: *const std.Target,
2624err_msg: ?*ErrorMsg = null,
27src_loc: Module.LazySrcLoc,
25src_loc: Zcu.LazySrcLoc,
2826code: *std.ArrayList(u8),
2927
3028prev_di_line: u32,
src/arch/wasm/CodeGen.zig+537-434
......@@ -684,6 +684,7 @@ simd_immediates: std.ArrayListUnmanaged([16]u8) = .{},
684684target: std.Target,
685685/// Represents the wasm binary file that is being linked.
686686bin_file: *link.File.Wasm,
687pt: Zcu.PerThread,
687688/// List of MIR Instructions
688689mir_instructions: std.MultiArrayList(Mir.Inst) = .{},
689690/// Contains extra data for MIR
......@@ -764,8 +765,7 @@ pub fn deinit(func: *CodeGen) void {
764765
765766/// Sets `err_msg` on `CodeGen` and returns `error.CodegenFail` which is caught in link/Wasm.zig
766767fn fail(func: *CodeGen, comptime fmt: []const u8, args: anytype) InnerError {
767 const mod = func.bin_file.base.comp.module.?;
768 const src_loc = func.decl.navSrcLoc(mod);
768 const src_loc = func.decl.navSrcLoc(func.pt.zcu);
769769 func.err_msg = try Zcu.ErrorMsg.create(func.gpa, src_loc, fmt, args);
770770 return error.CodegenFail;
771771}
......@@ -788,10 +788,11 @@ fn resolveInst(func: *CodeGen, ref: Air.Inst.Ref) InnerError!WValue {
788788 const gop = try func.branches.items[0].values.getOrPut(func.gpa, ref);
789789 assert(!gop.found_existing);
790790
791 const mod = func.bin_file.base.comp.module.?;
792 const val = (try func.air.value(ref, mod)).?;
791 const pt = func.pt;
792 const mod = pt.zcu;
793 const val = (try func.air.value(ref, pt)).?;
793794 const ty = func.typeOf(ref);
794 if (!ty.hasRuntimeBitsIgnoreComptime(mod) and !ty.isInt(mod) and !ty.isError(mod)) {
795 if (!ty.hasRuntimeBitsIgnoreComptime(pt) and !ty.isInt(mod) and !ty.isError(mod)) {
795796 gop.value_ptr.* = WValue{ .none = {} };
796797 return gop.value_ptr.*;
797798 }
......@@ -802,8 +803,8 @@ fn resolveInst(func: *CodeGen, ref: Air.Inst.Ref) InnerError!WValue {
802803 //
803804 // In the other cases, we will simply lower the constant to a value that fits
804805 // into a single local (such as a pointer, integer, bool, etc).
805 const result = if (isByRef(ty, mod)) blk: {
806 const sym_index = try func.bin_file.lowerUnnamedConst(val, func.decl_index);
806 const result = if (isByRef(ty, pt)) blk: {
807 const sym_index = try func.bin_file.lowerUnnamedConst(pt, val, func.decl_index);
807808 break :blk WValue{ .memory = sym_index };
808809 } else try func.lowerConstant(val, ty);
809810
......@@ -990,7 +991,8 @@ fn addExtraAssumeCapacity(func: *CodeGen, extra: anytype) error{OutOfMemory}!u32
990991}
991992
992993/// Using a given `Type`, returns the corresponding type
993fn typeToValtype(ty: Type, mod: *Zcu) wasm.Valtype {
994fn typeToValtype(ty: Type, pt: Zcu.PerThread) wasm.Valtype {
995 const mod = pt.zcu;
994996 const target = mod.getTarget();
995997 const ip = &mod.intern_pool;
996998 return switch (ty.zigTypeTag(mod)) {
......@@ -1002,26 +1004,26 @@ fn typeToValtype(ty: Type, mod: *Zcu) wasm.Valtype {
10021004 else => unreachable,
10031005 },
10041006 .Int, .Enum => blk: {
1005 const info = ty.intInfo(mod);
1007 const info = ty.intInfo(pt.zcu);
10061008 if (info.bits <= 32) break :blk wasm.Valtype.i32;
10071009 if (info.bits > 32 and info.bits <= 128) break :blk wasm.Valtype.i64;
10081010 break :blk wasm.Valtype.i32; // represented as pointer to stack
10091011 },
10101012 .Struct => {
1011 if (mod.typeToPackedStruct(ty)) |packed_struct| {
1012 return typeToValtype(Type.fromInterned(packed_struct.backingIntType(ip).*), mod);
1013 if (pt.zcu.typeToPackedStruct(ty)) |packed_struct| {
1014 return typeToValtype(Type.fromInterned(packed_struct.backingIntType(ip).*), pt);
10131015 } else {
10141016 return wasm.Valtype.i32;
10151017 }
10161018 },
1017 .Vector => switch (determineSimdStoreStrategy(ty, mod)) {
1019 .Vector => switch (determineSimdStoreStrategy(ty, pt)) {
10181020 .direct => wasm.Valtype.v128,
10191021 .unrolled => wasm.Valtype.i32,
10201022 },
1021 .Union => switch (ty.containerLayout(mod)) {
1023 .Union => switch (ty.containerLayout(pt.zcu)) {
10221024 .@"packed" => {
1023 const int_ty = mod.intType(.unsigned, @as(u16, @intCast(ty.bitSize(mod)))) catch @panic("out of memory");
1024 return typeToValtype(int_ty, mod);
1025 const int_ty = pt.intType(.unsigned, @as(u16, @intCast(ty.bitSize(pt)))) catch @panic("out of memory");
1026 return typeToValtype(int_ty, pt);
10251027 },
10261028 else => wasm.Valtype.i32,
10271029 },
......@@ -1030,17 +1032,17 @@ fn typeToValtype(ty: Type, mod: *Zcu) wasm.Valtype {
10301032}
10311033
10321034/// Using a given `Type`, returns the byte representation of its wasm value type
1033fn genValtype(ty: Type, mod: *Zcu) u8 {
1034 return wasm.valtype(typeToValtype(ty, mod));
1035fn genValtype(ty: Type, pt: Zcu.PerThread) u8 {
1036 return wasm.valtype(typeToValtype(ty, pt));
10351037}
10361038
10371039/// Using a given `Type`, returns the corresponding wasm value type
10381040/// Differently from `genValtype` this also allows `void` to create a block
10391041/// with no return type
1040fn genBlockType(ty: Type, mod: *Zcu) u8 {
1042fn genBlockType(ty: Type, pt: Zcu.PerThread) u8 {
10411043 return switch (ty.ip_index) {
10421044 .void_type, .noreturn_type => wasm.block_empty,
1043 else => genValtype(ty, mod),
1045 else => genValtype(ty, pt),
10441046 };
10451047}
10461048
......@@ -1101,8 +1103,8 @@ fn getResolvedInst(func: *CodeGen, ref: Air.Inst.Ref) *WValue {
11011103/// Creates one locals for a given `Type`.
11021104/// Returns a corresponding `Wvalue` with `local` as active tag
11031105fn allocLocal(func: *CodeGen, ty: Type) InnerError!WValue {
1104 const mod = func.bin_file.base.comp.module.?;
1105 const valtype = typeToValtype(ty, mod);
1106 const pt = func.pt;
1107 const valtype = typeToValtype(ty, pt);
11061108 switch (valtype) {
11071109 .i32 => if (func.free_locals_i32.popOrNull()) |index| {
11081110 log.debug("reusing local ({d}) of type {}", .{ index, valtype });
......@@ -1133,8 +1135,8 @@ fn allocLocal(func: *CodeGen, ty: Type) InnerError!WValue {
11331135/// Ensures a new local will be created. This is useful when it's useful
11341136/// to use a zero-initialized local.
11351137fn ensureAllocLocal(func: *CodeGen, ty: Type) InnerError!WValue {
1136 const mod = func.bin_file.base.comp.module.?;
1137 try func.locals.append(func.gpa, genValtype(ty, mod));
1138 const pt = func.pt;
1139 try func.locals.append(func.gpa, genValtype(ty, pt));
11381140 const initial_index = func.local_index;
11391141 func.local_index += 1;
11401142 return WValue{ .local = .{ .value = initial_index, .references = 1 } };
......@@ -1147,23 +1149,24 @@ fn genFunctype(
11471149 cc: std.builtin.CallingConvention,
11481150 params: []const InternPool.Index,
11491151 return_type: Type,
1150 mod: *Zcu,
1152 pt: Zcu.PerThread,
11511153) !wasm.Type {
1154 const mod = pt.zcu;
11521155 var temp_params = std.ArrayList(wasm.Valtype).init(gpa);
11531156 defer temp_params.deinit();
11541157 var returns = std.ArrayList(wasm.Valtype).init(gpa);
11551158 defer returns.deinit();
11561159
1157 if (firstParamSRet(cc, return_type, mod)) {
1160 if (firstParamSRet(cc, return_type, pt)) {
11581161 try temp_params.append(.i32); // memory address is always a 32-bit handle
1159 } else if (return_type.hasRuntimeBitsIgnoreComptime(mod)) {
1162 } else if (return_type.hasRuntimeBitsIgnoreComptime(pt)) {
11601163 if (cc == .C) {
1161 const res_classes = abi.classifyType(return_type, mod);
1164 const res_classes = abi.classifyType(return_type, pt);
11621165 assert(res_classes[0] == .direct and res_classes[1] == .none);
1163 const scalar_type = abi.scalarType(return_type, mod);
1164 try returns.append(typeToValtype(scalar_type, mod));
1166 const scalar_type = abi.scalarType(return_type, pt);
1167 try returns.append(typeToValtype(scalar_type, pt));
11651168 } else {
1166 try returns.append(typeToValtype(return_type, mod));
1169 try returns.append(typeToValtype(return_type, pt));
11671170 }
11681171 } else if (return_type.isError(mod)) {
11691172 try returns.append(.i32);
......@@ -1172,25 +1175,25 @@ fn genFunctype(
11721175 // param types
11731176 for (params) |param_type_ip| {
11741177 const param_type = Type.fromInterned(param_type_ip);
1175 if (!param_type.hasRuntimeBitsIgnoreComptime(mod)) continue;
1178 if (!param_type.hasRuntimeBitsIgnoreComptime(pt)) continue;
11761179
11771180 switch (cc) {
11781181 .C => {
1179 const param_classes = abi.classifyType(param_type, mod);
1182 const param_classes = abi.classifyType(param_type, pt);
11801183 for (param_classes) |class| {
11811184 if (class == .none) continue;
11821185 if (class == .direct) {
1183 const scalar_type = abi.scalarType(param_type, mod);
1184 try temp_params.append(typeToValtype(scalar_type, mod));
1186 const scalar_type = abi.scalarType(param_type, pt);
1187 try temp_params.append(typeToValtype(scalar_type, pt));
11851188 } else {
1186 try temp_params.append(typeToValtype(param_type, mod));
1189 try temp_params.append(typeToValtype(param_type, pt));
11871190 }
11881191 }
11891192 },
1190 else => if (isByRef(param_type, mod))
1193 else => if (isByRef(param_type, pt))
11911194 try temp_params.append(.i32)
11921195 else
1193 try temp_params.append(typeToValtype(param_type, mod)),
1196 try temp_params.append(typeToValtype(param_type, pt)),
11941197 }
11951198 }
11961199
......@@ -1202,6 +1205,7 @@ fn genFunctype(
12021205
12031206pub fn generate(
12041207 bin_file: *link.File,
1208 pt: Zcu.PerThread,
12051209 src_loc: Zcu.LazySrcLoc,
12061210 func_index: InternPool.Index,
12071211 air: Air,
......@@ -1210,15 +1214,15 @@ pub fn generate(
12101214 debug_output: codegen.DebugInfoOutput,
12111215) codegen.CodeGenError!codegen.Result {
12121216 _ = src_loc;
1213 const comp = bin_file.comp;
1214 const gpa = comp.gpa;
1215 const zcu = comp.module.?;
1217 const zcu = pt.zcu;
1218 const gpa = zcu.gpa;
12161219 const func = zcu.funcInfo(func_index);
12171220 const decl = zcu.declPtr(func.owner_decl);
12181221 const namespace = zcu.namespacePtr(decl.src_namespace);
12191222 const target = namespace.fileScope(zcu).mod.resolved_target.result;
12201223 var code_gen: CodeGen = .{
12211224 .gpa = gpa,
1225 .pt = pt,
12221226 .air = air,
12231227 .liveness = liveness,
12241228 .code = code,
......@@ -1242,10 +1246,11 @@ pub fn generate(
12421246}
12431247
12441248fn genFunc(func: *CodeGen) InnerError!void {
1245 const mod = func.bin_file.base.comp.module.?;
1249 const pt = func.pt;
1250 const mod = pt.zcu;
12461251 const ip = &mod.intern_pool;
12471252 const fn_info = mod.typeToFunc(func.decl.typeOf(mod)).?;
1248 var func_type = try genFunctype(func.gpa, fn_info.cc, fn_info.param_types.get(ip), Type.fromInterned(fn_info.return_type), mod);
1253 var func_type = try genFunctype(func.gpa, fn_info.cc, fn_info.param_types.get(ip), Type.fromInterned(fn_info.return_type), pt);
12491254 defer func_type.deinit(func.gpa);
12501255 _ = try func.bin_file.storeDeclType(func.decl_index, func_type);
12511256
......@@ -1272,7 +1277,7 @@ fn genFunc(func: *CodeGen) InnerError!void {
12721277 if (func_type.returns.len != 0 and func.air.instructions.len > 0) {
12731278 const inst: Air.Inst.Index = @enumFromInt(func.air.instructions.len - 1);
12741279 const last_inst_ty = func.typeOfIndex(inst);
1275 if (!last_inst_ty.hasRuntimeBitsIgnoreComptime(mod) or last_inst_ty.isNoReturn(mod)) {
1280 if (!last_inst_ty.hasRuntimeBitsIgnoreComptime(pt) or last_inst_ty.isNoReturn(mod)) {
12761281 try func.addTag(.@"unreachable");
12771282 }
12781283 }
......@@ -1354,7 +1359,8 @@ const CallWValues = struct {
13541359};
13551360
13561361fn resolveCallingConventionValues(func: *CodeGen, fn_ty: Type) InnerError!CallWValues {
1357 const mod = func.bin_file.base.comp.module.?;
1362 const pt = func.pt;
1363 const mod = pt.zcu;
13581364 const ip = &mod.intern_pool;
13591365 const fn_info = mod.typeToFunc(fn_ty).?;
13601366 const cc = fn_info.cc;
......@@ -1369,7 +1375,7 @@ fn resolveCallingConventionValues(func: *CodeGen, fn_ty: Type) InnerError!CallWV
13691375
13701376 // Check if we store the result as a pointer to the stack rather than
13711377 // by value
1372 if (firstParamSRet(fn_info.cc, Type.fromInterned(fn_info.return_type), mod)) {
1378 if (firstParamSRet(fn_info.cc, Type.fromInterned(fn_info.return_type), pt)) {
13731379 // the sret arg will be passed as first argument, therefore we
13741380 // set the `return_value` before allocating locals for regular args.
13751381 result.return_value = .{ .local = .{ .value = func.local_index, .references = 1 } };
......@@ -1379,7 +1385,7 @@ fn resolveCallingConventionValues(func: *CodeGen, fn_ty: Type) InnerError!CallWV
13791385 switch (cc) {
13801386 .Unspecified => {
13811387 for (fn_info.param_types.get(ip)) |ty| {
1382 if (!Type.fromInterned(ty).hasRuntimeBitsIgnoreComptime(mod)) {
1388 if (!Type.fromInterned(ty).hasRuntimeBitsIgnoreComptime(pt)) {
13831389 continue;
13841390 }
13851391
......@@ -1389,7 +1395,7 @@ fn resolveCallingConventionValues(func: *CodeGen, fn_ty: Type) InnerError!CallWV
13891395 },
13901396 .C => {
13911397 for (fn_info.param_types.get(ip)) |ty| {
1392 const ty_classes = abi.classifyType(Type.fromInterned(ty), mod);
1398 const ty_classes = abi.classifyType(Type.fromInterned(ty), pt);
13931399 for (ty_classes) |class| {
13941400 if (class == .none) continue;
13951401 try args.append(.{ .local = .{ .value = func.local_index, .references = 1 } });
......@@ -1403,11 +1409,11 @@ fn resolveCallingConventionValues(func: *CodeGen, fn_ty: Type) InnerError!CallWV
14031409 return result;
14041410}
14051411
1406fn firstParamSRet(cc: std.builtin.CallingConvention, return_type: Type, mod: *Zcu) bool {
1412fn firstParamSRet(cc: std.builtin.CallingConvention, return_type: Type, pt: Zcu.PerThread) bool {
14071413 switch (cc) {
1408 .Unspecified, .Inline => return isByRef(return_type, mod),
1414 .Unspecified, .Inline => return isByRef(return_type, pt),
14091415 .C => {
1410 const ty_classes = abi.classifyType(return_type, mod);
1416 const ty_classes = abi.classifyType(return_type, pt);
14111417 if (ty_classes[0] == .indirect) return true;
14121418 if (ty_classes[0] == .direct and ty_classes[1] == .direct) return true;
14131419 return false;
......@@ -1423,8 +1429,9 @@ fn lowerArg(func: *CodeGen, cc: std.builtin.CallingConvention, ty: Type, value:
14231429 return func.lowerToStack(value);
14241430 }
14251431
1426 const mod = func.bin_file.base.comp.module.?;
1427 const ty_classes = abi.classifyType(ty, mod);
1432 const pt = func.pt;
1433 const mod = pt.zcu;
1434 const ty_classes = abi.classifyType(ty, pt);
14281435 assert(ty_classes[0] != .none);
14291436 switch (ty.zigTypeTag(mod)) {
14301437 .Struct, .Union => {
......@@ -1432,7 +1439,7 @@ fn lowerArg(func: *CodeGen, cc: std.builtin.CallingConvention, ty: Type, value:
14321439 return func.lowerToStack(value);
14331440 }
14341441 assert(ty_classes[0] == .direct);
1435 const scalar_type = abi.scalarType(ty, mod);
1442 const scalar_type = abi.scalarType(ty, pt);
14361443 switch (value) {
14371444 .memory,
14381445 .memory_offset,
......@@ -1447,7 +1454,7 @@ fn lowerArg(func: *CodeGen, cc: std.builtin.CallingConvention, ty: Type, value:
14471454 return func.lowerToStack(value);
14481455 }
14491456 assert(ty_classes[0] == .direct and ty_classes[1] == .direct);
1450 assert(ty.abiSize(mod) == 16);
1457 assert(ty.abiSize(pt) == 16);
14511458 // in this case we have an integer or float that must be lowered as 2 i64's.
14521459 try func.emitWValue(value);
14531460 try func.addMemArg(.i64_load, .{ .offset = value.offset(), .alignment = 8 });
......@@ -1514,18 +1521,18 @@ fn restoreStackPointer(func: *CodeGen) !void {
15141521///
15151522/// Asserts Type has codegenbits
15161523fn allocStack(func: *CodeGen, ty: Type) !WValue {
1517 const mod = func.bin_file.base.comp.module.?;
1518 assert(ty.hasRuntimeBitsIgnoreComptime(mod));
1524 const pt = func.pt;
1525 assert(ty.hasRuntimeBitsIgnoreComptime(pt));
15191526 if (func.initial_stack_value == .none) {
15201527 try func.initializeStack();
15211528 }
15221529
1523 const abi_size = std.math.cast(u32, ty.abiSize(mod)) orelse {
1530 const abi_size = std.math.cast(u32, ty.abiSize(pt)) orelse {
15241531 return func.fail("Type {} with ABI size of {d} exceeds stack frame size", .{
1525 ty.fmt(mod), ty.abiSize(mod),
1532 ty.fmt(pt), ty.abiSize(pt),
15261533 });
15271534 };
1528 const abi_align = ty.abiAlignment(mod);
1535 const abi_align = ty.abiAlignment(pt);
15291536
15301537 func.stack_alignment = func.stack_alignment.max(abi_align);
15311538
......@@ -1540,7 +1547,8 @@ fn allocStack(func: *CodeGen, ty: Type) !WValue {
15401547/// This is different from allocStack where this will use the pointer's alignment
15411548/// if it is set, to ensure the stack alignment will be set correctly.
15421549fn allocStackPtr(func: *CodeGen, inst: Air.Inst.Index) !WValue {
1543 const mod = func.bin_file.base.comp.module.?;
1550 const pt = func.pt;
1551 const mod = pt.zcu;
15441552 const ptr_ty = func.typeOfIndex(inst);
15451553 const pointee_ty = ptr_ty.childType(mod);
15461554
......@@ -1548,14 +1556,14 @@ fn allocStackPtr(func: *CodeGen, inst: Air.Inst.Index) !WValue {
15481556 try func.initializeStack();
15491557 }
15501558
1551 if (!pointee_ty.hasRuntimeBitsIgnoreComptime(mod)) {
1559 if (!pointee_ty.hasRuntimeBitsIgnoreComptime(pt)) {
15521560 return func.allocStack(Type.usize); // create a value containing just the stack pointer.
15531561 }
15541562
1555 const abi_alignment = ptr_ty.ptrAlignment(mod);
1556 const abi_size = std.math.cast(u32, pointee_ty.abiSize(mod)) orelse {
1563 const abi_alignment = ptr_ty.ptrAlignment(pt);
1564 const abi_size = std.math.cast(u32, pointee_ty.abiSize(pt)) orelse {
15571565 return func.fail("Type {} with ABI size of {d} exceeds stack frame size", .{
1558 pointee_ty.fmt(mod), pointee_ty.abiSize(mod),
1566 pointee_ty.fmt(pt), pointee_ty.abiSize(pt),
15591567 });
15601568 };
15611569 func.stack_alignment = func.stack_alignment.max(abi_alignment);
......@@ -1711,7 +1719,8 @@ fn arch(func: *const CodeGen) std.Target.Cpu.Arch {
17111719
17121720/// For a given `Type`, will return true when the type will be passed
17131721/// by reference, rather than by value
1714fn isByRef(ty: Type, mod: *Zcu) bool {
1722fn isByRef(ty: Type, pt: Zcu.PerThread) bool {
1723 const mod = pt.zcu;
17151724 const ip = &mod.intern_pool;
17161725 const target = mod.getTarget();
17171726 switch (ty.zigTypeTag(mod)) {
......@@ -1734,28 +1743,28 @@ fn isByRef(ty: Type, mod: *Zcu) bool {
17341743
17351744 .Array,
17361745 .Frame,
1737 => return ty.hasRuntimeBitsIgnoreComptime(mod),
1746 => return ty.hasRuntimeBitsIgnoreComptime(pt),
17381747 .Union => {
17391748 if (mod.typeToUnion(ty)) |union_obj| {
17401749 if (union_obj.getLayout(ip) == .@"packed") {
1741 return ty.abiSize(mod) > 8;
1750 return ty.abiSize(pt) > 8;
17421751 }
17431752 }
1744 return ty.hasRuntimeBitsIgnoreComptime(mod);
1753 return ty.hasRuntimeBitsIgnoreComptime(pt);
17451754 },
17461755 .Struct => {
17471756 if (mod.typeToPackedStruct(ty)) |packed_struct| {
1748 return isByRef(Type.fromInterned(packed_struct.backingIntType(ip).*), mod);
1757 return isByRef(Type.fromInterned(packed_struct.backingIntType(ip).*), pt);
17491758 }
1750 return ty.hasRuntimeBitsIgnoreComptime(mod);
1759 return ty.hasRuntimeBitsIgnoreComptime(pt);
17511760 },
1752 .Vector => return determineSimdStoreStrategy(ty, mod) == .unrolled,
1761 .Vector => return determineSimdStoreStrategy(ty, pt) == .unrolled,
17531762 .Int => return ty.intInfo(mod).bits > 64,
17541763 .Enum => return ty.intInfo(mod).bits > 64,
17551764 .Float => return ty.floatBits(target) > 64,
17561765 .ErrorUnion => {
17571766 const pl_ty = ty.errorUnionPayload(mod);
1758 if (!pl_ty.hasRuntimeBitsIgnoreComptime(mod)) {
1767 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) {
17591768 return false;
17601769 }
17611770 return true;
......@@ -1764,7 +1773,7 @@ fn isByRef(ty: Type, mod: *Zcu) bool {
17641773 if (ty.isPtrLikeOptional(mod)) return false;
17651774 const pl_type = ty.optionalChild(mod);
17661775 if (pl_type.zigTypeTag(mod) == .ErrorSet) return false;
1767 return pl_type.hasRuntimeBitsIgnoreComptime(mod);
1776 return pl_type.hasRuntimeBitsIgnoreComptime(pt);
17681777 },
17691778 .Pointer => {
17701779 // Slices act like struct and will be passed by reference
......@@ -1783,11 +1792,11 @@ const SimdStoreStrategy = enum {
17831792/// This means when a given type is 128 bits and either the simd128 or relaxed-simd
17841793/// features are enabled, the function will return `.direct`. This would allow to store
17851794/// it using a instruction, rather than an unrolled version.
1786fn determineSimdStoreStrategy(ty: Type, mod: *Zcu) SimdStoreStrategy {
1787 std.debug.assert(ty.zigTypeTag(mod) == .Vector);
1788 if (ty.bitSize(mod) != 128) return .unrolled;
1795fn determineSimdStoreStrategy(ty: Type, pt: Zcu.PerThread) SimdStoreStrategy {
1796 std.debug.assert(ty.zigTypeTag(pt.zcu) == .Vector);
1797 if (ty.bitSize(pt) != 128) return .unrolled;
17891798 const hasFeature = std.Target.wasm.featureSetHas;
1790 const target = mod.getTarget();
1799 const target = pt.zcu.getTarget();
17911800 const features = target.cpu.features;
17921801 if (hasFeature(features, .relaxed_simd) or hasFeature(features, .simd128)) {
17931802 return .direct;
......@@ -2064,7 +2073,8 @@ fn genInst(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
20642073}
20652074
20662075fn genBody(func: *CodeGen, body: []const Air.Inst.Index) InnerError!void {
2067 const mod = func.bin_file.base.comp.module.?;
2076 const pt = func.pt;
2077 const mod = pt.zcu;
20682078 const ip = &mod.intern_pool;
20692079
20702080 for (body) |inst| {
......@@ -2085,7 +2095,8 @@ fn genBody(func: *CodeGen, body: []const Air.Inst.Index) InnerError!void {
20852095}
20862096
20872097fn airRet(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
2088 const mod = func.bin_file.base.comp.module.?;
2098 const pt = func.pt;
2099 const mod = pt.zcu;
20892100 const un_op = func.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
20902101 const operand = try func.resolveInst(un_op);
20912102 const fn_info = mod.typeToFunc(func.decl.typeOf(mod)).?;
......@@ -2095,27 +2106,27 @@ fn airRet(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
20952106 // to the stack instead
20962107 if (func.return_value != .none) {
20972108 try func.store(func.return_value, operand, ret_ty, 0);
2098 } else if (fn_info.cc == .C and ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
2109 } else if (fn_info.cc == .C and ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
20992110 switch (ret_ty.zigTypeTag(mod)) {
21002111 // Aggregate types can be lowered as a singular value
21012112 .Struct, .Union => {
2102 const scalar_type = abi.scalarType(ret_ty, mod);
2113 const scalar_type = abi.scalarType(ret_ty, pt);
21032114 try func.emitWValue(operand);
21042115 const opcode = buildOpcode(.{
21052116 .op = .load,
2106 .width = @as(u8, @intCast(scalar_type.abiSize(mod) * 8)),
2117 .width = @as(u8, @intCast(scalar_type.abiSize(pt) * 8)),
21072118 .signedness = if (scalar_type.isSignedInt(mod)) .signed else .unsigned,
2108 .valtype1 = typeToValtype(scalar_type, mod),
2119 .valtype1 = typeToValtype(scalar_type, pt),
21092120 });
21102121 try func.addMemArg(Mir.Inst.Tag.fromOpcode(opcode), .{
21112122 .offset = operand.offset(),
2112 .alignment = @intCast(scalar_type.abiAlignment(mod).toByteUnits().?),
2123 .alignment = @intCast(scalar_type.abiAlignment(pt).toByteUnits().?),
21132124 });
21142125 },
21152126 else => try func.emitWValue(operand),
21162127 }
21172128 } else {
2118 if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod) and ret_ty.isError(mod)) {
2129 if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt) and ret_ty.isError(mod)) {
21192130 try func.addImm32(0);
21202131 } else {
21212132 try func.emitWValue(operand);
......@@ -2128,16 +2139,17 @@ fn airRet(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
21282139}
21292140
21302141fn airRetPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
2131 const mod = func.bin_file.base.comp.module.?;
2142 const pt = func.pt;
2143 const mod = pt.zcu;
21322144 const child_type = func.typeOfIndex(inst).childType(mod);
21332145
21342146 const result = result: {
2135 if (!child_type.isFnOrHasRuntimeBitsIgnoreComptime(mod)) {
2147 if (!child_type.isFnOrHasRuntimeBitsIgnoreComptime(pt)) {
21362148 break :result try func.allocStack(Type.usize); // create pointer to void
21372149 }
21382150
21392151 const fn_info = mod.typeToFunc(func.decl.typeOf(mod)).?;
2140 if (firstParamSRet(fn_info.cc, Type.fromInterned(fn_info.return_type), mod)) {
2152 if (firstParamSRet(fn_info.cc, Type.fromInterned(fn_info.return_type), pt)) {
21412153 break :result func.return_value;
21422154 }
21432155
......@@ -2148,17 +2160,18 @@ fn airRetPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
21482160}
21492161
21502162fn airRetLoad(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
2151 const mod = func.bin_file.base.comp.module.?;
2163 const pt = func.pt;
2164 const mod = pt.zcu;
21522165 const un_op = func.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
21532166 const operand = try func.resolveInst(un_op);
21542167 const ret_ty = func.typeOf(un_op).childType(mod);
21552168
21562169 const fn_info = mod.typeToFunc(func.decl.typeOf(mod)).?;
2157 if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
2170 if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
21582171 if (ret_ty.isError(mod)) {
21592172 try func.addImm32(0);
21602173 }
2161 } else if (!firstParamSRet(fn_info.cc, Type.fromInterned(fn_info.return_type), mod)) {
2174 } else if (!firstParamSRet(fn_info.cc, Type.fromInterned(fn_info.return_type), pt)) {
21622175 // leave on the stack
21632176 _ = try func.load(operand, ret_ty, 0);
21642177 }
......@@ -2175,7 +2188,8 @@ fn airCall(func: *CodeGen, inst: Air.Inst.Index, modifier: std.builtin.CallModif
21752188 const args = @as([]const Air.Inst.Ref, @ptrCast(func.air.extra[extra.end..][0..extra.data.args_len]));
21762189 const ty = func.typeOf(pl_op.operand);
21772190
2178 const mod = func.bin_file.base.comp.module.?;
2191 const pt = func.pt;
2192 const mod = pt.zcu;
21792193 const ip = &mod.intern_pool;
21802194 const fn_ty = switch (ty.zigTypeTag(mod)) {
21812195 .Fn => ty,
......@@ -2184,20 +2198,20 @@ fn airCall(func: *CodeGen, inst: Air.Inst.Index, modifier: std.builtin.CallModif
21842198 };
21852199 const ret_ty = fn_ty.fnReturnType(mod);
21862200 const fn_info = mod.typeToFunc(fn_ty).?;
2187 const first_param_sret = firstParamSRet(fn_info.cc, Type.fromInterned(fn_info.return_type), mod);
2201 const first_param_sret = firstParamSRet(fn_info.cc, Type.fromInterned(fn_info.return_type), pt);
21882202
21892203 const callee: ?InternPool.DeclIndex = blk: {
2190 const func_val = (try func.air.value(pl_op.operand, mod)) orelse break :blk null;
2204 const func_val = (try func.air.value(pl_op.operand, pt)) orelse break :blk null;
21912205
21922206 if (func_val.getFunction(mod)) |function| {
2193 _ = try func.bin_file.getOrCreateAtomForDecl(function.owner_decl);
2207 _ = try func.bin_file.getOrCreateAtomForDecl(pt, function.owner_decl);
21942208 break :blk function.owner_decl;
21952209 } else if (func_val.getExternFunc(mod)) |extern_func| {
21962210 const ext_decl = mod.declPtr(extern_func.decl);
21972211 const ext_info = mod.typeToFunc(ext_decl.typeOf(mod)).?;
2198 var func_type = try genFunctype(func.gpa, ext_info.cc, ext_info.param_types.get(ip), Type.fromInterned(ext_info.return_type), mod);
2212 var func_type = try genFunctype(func.gpa, ext_info.cc, ext_info.param_types.get(ip), Type.fromInterned(ext_info.return_type), pt);
21992213 defer func_type.deinit(func.gpa);
2200 const atom_index = try func.bin_file.getOrCreateAtomForDecl(extern_func.decl);
2214 const atom_index = try func.bin_file.getOrCreateAtomForDecl(pt, extern_func.decl);
22012215 const atom = func.bin_file.getAtomPtr(atom_index);
22022216 const type_index = try func.bin_file.storeDeclType(extern_func.decl, func_type);
22032217 try func.bin_file.addOrUpdateImport(
......@@ -2210,7 +2224,7 @@ fn airCall(func: *CodeGen, inst: Air.Inst.Index, modifier: std.builtin.CallModif
22102224 } else switch (mod.intern_pool.indexToKey(func_val.ip_index)) {
22112225 .ptr => |ptr| if (ptr.byte_offset == 0) switch (ptr.base_addr) {
22122226 .decl => |decl| {
2213 _ = try func.bin_file.getOrCreateAtomForDecl(decl);
2227 _ = try func.bin_file.getOrCreateAtomForDecl(pt, decl);
22142228 break :blk decl;
22152229 },
22162230 else => {},
......@@ -2230,7 +2244,7 @@ fn airCall(func: *CodeGen, inst: Air.Inst.Index, modifier: std.builtin.CallModif
22302244 const arg_val = try func.resolveInst(arg);
22312245
22322246 const arg_ty = func.typeOf(arg);
2233 if (!arg_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
2247 if (!arg_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
22342248
22352249 try func.lowerArg(mod.typeToFunc(fn_ty).?.cc, arg_ty, arg_val);
22362250 }
......@@ -2245,7 +2259,7 @@ fn airCall(func: *CodeGen, inst: Air.Inst.Index, modifier: std.builtin.CallModif
22452259 const operand = try func.resolveInst(pl_op.operand);
22462260 try func.emitWValue(operand);
22472261
2248 var fn_type = try genFunctype(func.gpa, fn_info.cc, fn_info.param_types.get(ip), Type.fromInterned(fn_info.return_type), mod);
2262 var fn_type = try genFunctype(func.gpa, fn_info.cc, fn_info.param_types.get(ip), Type.fromInterned(fn_info.return_type), pt);
22492263 defer fn_type.deinit(func.gpa);
22502264
22512265 const fn_type_index = try func.bin_file.zigObjectPtr().?.putOrGetFuncType(func.gpa, fn_type);
......@@ -2253,7 +2267,7 @@ fn airCall(func: *CodeGen, inst: Air.Inst.Index, modifier: std.builtin.CallModif
22532267 }
22542268
22552269 const result_value = result_value: {
2256 if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod) and !ret_ty.isError(mod)) {
2270 if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt) and !ret_ty.isError(mod)) {
22572271 break :result_value WValue{ .none = {} };
22582272 } else if (ret_ty.isNoReturn(mod)) {
22592273 try func.addTag(.@"unreachable");
......@@ -2264,7 +2278,7 @@ fn airCall(func: *CodeGen, inst: Air.Inst.Index, modifier: std.builtin.CallModif
22642278 } else if (mod.typeToFunc(fn_ty).?.cc == .C and ret_ty.zigTypeTag(mod) == .Struct or ret_ty.zigTypeTag(mod) == .Union) {
22652279 const result_local = try func.allocLocal(ret_ty);
22662280 try func.addLabel(.local_set, result_local.local.value);
2267 const scalar_type = abi.scalarType(ret_ty, mod);
2281 const scalar_type = abi.scalarType(ret_ty, pt);
22682282 const result = try func.allocStack(scalar_type);
22692283 try func.store(result, result_local, scalar_type, 0);
22702284 break :result_value result;
......@@ -2287,7 +2301,8 @@ fn airAlloc(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
22872301}
22882302
22892303fn airStore(func: *CodeGen, inst: Air.Inst.Index, safety: bool) InnerError!void {
2290 const mod = func.bin_file.base.comp.module.?;
2304 const pt = func.pt;
2305 const mod = pt.zcu;
22912306 if (safety) {
22922307 // TODO if the value is undef, write 0xaa bytes to dest
22932308 } else {
......@@ -2306,13 +2321,13 @@ fn airStore(func: *CodeGen, inst: Air.Inst.Index, safety: bool) InnerError!void
23062321 } else {
23072322 // at this point we have a non-natural alignment, we must
23082323 // load the value, and then shift+or the rhs into the result location.
2309 const int_elem_ty = try mod.intType(.unsigned, ptr_info.packed_offset.host_size * 8);
2324 const int_elem_ty = try pt.intType(.unsigned, ptr_info.packed_offset.host_size * 8);
23102325
2311 if (isByRef(int_elem_ty, mod)) {
2326 if (isByRef(int_elem_ty, pt)) {
23122327 return func.fail("TODO: airStore for pointers to bitfields with backing type larger than 64bits", .{});
23132328 }
23142329
2315 var mask = @as(u64, @intCast((@as(u65, 1) << @as(u7, @intCast(ty.bitSize(mod)))) - 1));
2330 var mask = @as(u64, @intCast((@as(u65, 1) << @as(u7, @intCast(ty.bitSize(pt)))) - 1));
23162331 mask <<= @as(u6, @intCast(ptr_info.packed_offset.bit_offset));
23172332 mask ^= ~@as(u64, 0);
23182333 const shift_val = if (ptr_info.packed_offset.host_size <= 4)
......@@ -2324,9 +2339,9 @@ fn airStore(func: *CodeGen, inst: Air.Inst.Index, safety: bool) InnerError!void
23242339 else
23252340 WValue{ .imm64 = mask };
23262341 const wrap_mask_val = if (ptr_info.packed_offset.host_size <= 4)
2327 WValue{ .imm32 = @truncate(~@as(u64, 0) >> @intCast(64 - ty.bitSize(mod))) }
2342 WValue{ .imm32 = @truncate(~@as(u64, 0) >> @intCast(64 - ty.bitSize(pt))) }
23282343 else
2329 WValue{ .imm64 = ~@as(u64, 0) >> @intCast(64 - ty.bitSize(mod)) };
2344 WValue{ .imm64 = ~@as(u64, 0) >> @intCast(64 - ty.bitSize(pt)) };
23302345
23312346 try func.emitWValue(lhs);
23322347 const loaded = try func.load(lhs, int_elem_ty, 0);
......@@ -2346,12 +2361,13 @@ fn airStore(func: *CodeGen, inst: Air.Inst.Index, safety: bool) InnerError!void
23462361
23472362fn store(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, offset: u32) InnerError!void {
23482363 assert(!(lhs != .stack and rhs == .stack));
2349 const mod = func.bin_file.base.comp.module.?;
2350 const abi_size = ty.abiSize(mod);
2364 const pt = func.pt;
2365 const mod = pt.zcu;
2366 const abi_size = ty.abiSize(pt);
23512367 switch (ty.zigTypeTag(mod)) {
23522368 .ErrorUnion => {
23532369 const pl_ty = ty.errorUnionPayload(mod);
2354 if (!pl_ty.hasRuntimeBitsIgnoreComptime(mod)) {
2370 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) {
23552371 return func.store(lhs, rhs, Type.anyerror, 0);
23562372 }
23572373
......@@ -2363,7 +2379,7 @@ fn store(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, offset: u32) InnerE
23632379 return func.store(lhs, rhs, Type.usize, 0);
23642380 }
23652381 const pl_ty = ty.optionalChild(mod);
2366 if (!pl_ty.hasRuntimeBitsIgnoreComptime(mod)) {
2382 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) {
23672383 return func.store(lhs, rhs, Type.u8, 0);
23682384 }
23692385 if (pl_ty.zigTypeTag(mod) == .ErrorSet) {
......@@ -2373,11 +2389,11 @@ fn store(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, offset: u32) InnerE
23732389 const len = @as(u32, @intCast(abi_size));
23742390 return func.memcpy(lhs, rhs, .{ .imm32 = len });
23752391 },
2376 .Struct, .Array, .Union => if (isByRef(ty, mod)) {
2392 .Struct, .Array, .Union => if (isByRef(ty, pt)) {
23772393 const len = @as(u32, @intCast(abi_size));
23782394 return func.memcpy(lhs, rhs, .{ .imm32 = len });
23792395 },
2380 .Vector => switch (determineSimdStoreStrategy(ty, mod)) {
2396 .Vector => switch (determineSimdStoreStrategy(ty, pt)) {
23812397 .unrolled => {
23822398 const len: u32 = @intCast(abi_size);
23832399 return func.memcpy(lhs, rhs, .{ .imm32 = len });
......@@ -2391,7 +2407,7 @@ fn store(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, offset: u32) InnerE
23912407 try func.mir_extra.appendSlice(func.gpa, &[_]u32{
23922408 std.wasm.simdOpcode(.v128_store),
23932409 offset + lhs.offset(),
2394 @intCast(ty.abiAlignment(mod).toByteUnits() orelse 0),
2410 @intCast(ty.abiAlignment(pt).toByteUnits() orelse 0),
23952411 });
23962412 return func.addInst(.{ .tag = .simd_prefix, .data = .{ .payload = extra_index } });
23972413 },
......@@ -2421,11 +2437,11 @@ fn store(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, offset: u32) InnerE
24212437 try func.store(.{ .stack = {} }, msb, Type.u64, 8 + lhs.offset());
24222438 return;
24232439 } else if (abi_size > 16) {
2424 try func.memcpy(lhs, rhs, .{ .imm32 = @as(u32, @intCast(ty.abiSize(mod))) });
2440 try func.memcpy(lhs, rhs, .{ .imm32 = @as(u32, @intCast(ty.abiSize(pt))) });
24252441 },
24262442 else => if (abi_size > 8) {
24272443 return func.fail("TODO: `store` for type `{}` with abisize `{d}`", .{
2428 ty.fmt(func.bin_file.base.comp.module.?),
2444 ty.fmt(pt),
24292445 abi_size,
24302446 });
24312447 },
......@@ -2435,7 +2451,7 @@ fn store(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, offset: u32) InnerE
24352451 // into lhs, so we calculate that and emit that instead
24362452 try func.lowerToStack(rhs);
24372453
2438 const valtype = typeToValtype(ty, mod);
2454 const valtype = typeToValtype(ty, pt);
24392455 const opcode = buildOpcode(.{
24402456 .valtype1 = valtype,
24412457 .width = @as(u8, @intCast(abi_size * 8)),
......@@ -2447,23 +2463,24 @@ fn store(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, offset: u32) InnerE
24472463 Mir.Inst.Tag.fromOpcode(opcode),
24482464 .{
24492465 .offset = offset + lhs.offset(),
2450 .alignment = @intCast(ty.abiAlignment(mod).toByteUnits().?),
2466 .alignment = @intCast(ty.abiAlignment(pt).toByteUnits().?),
24512467 },
24522468 );
24532469}
24542470
24552471fn airLoad(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
2456 const mod = func.bin_file.base.comp.module.?;
2472 const pt = func.pt;
2473 const mod = pt.zcu;
24572474 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
24582475 const operand = try func.resolveInst(ty_op.operand);
24592476 const ty = ty_op.ty.toType();
24602477 const ptr_ty = func.typeOf(ty_op.operand);
24612478 const ptr_info = ptr_ty.ptrInfo(mod);
24622479
2463 if (!ty.hasRuntimeBitsIgnoreComptime(mod)) return func.finishAir(inst, .none, &.{ty_op.operand});
2480 if (!ty.hasRuntimeBitsIgnoreComptime(pt)) return func.finishAir(inst, .none, &.{ty_op.operand});
24642481
24652482 const result = result: {
2466 if (isByRef(ty, mod)) {
2483 if (isByRef(ty, pt)) {
24672484 const new_local = try func.allocStack(ty);
24682485 try func.store(new_local, operand, ty, 0);
24692486 break :result new_local;
......@@ -2476,7 +2493,7 @@ fn airLoad(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
24762493
24772494 // at this point we have a non-natural alignment, we must
24782495 // shift the value to obtain the correct bit.
2479 const int_elem_ty = try mod.intType(.unsigned, ptr_info.packed_offset.host_size * 8);
2496 const int_elem_ty = try pt.intType(.unsigned, ptr_info.packed_offset.host_size * 8);
24802497 const shift_val = if (ptr_info.packed_offset.host_size <= 4)
24812498 WValue{ .imm32 = ptr_info.packed_offset.bit_offset }
24822499 else if (ptr_info.packed_offset.host_size <= 8)
......@@ -2496,7 +2513,8 @@ fn airLoad(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
24962513/// Loads an operand from the linear memory section.
24972514/// NOTE: Leaves the value on the stack.
24982515fn load(func: *CodeGen, operand: WValue, ty: Type, offset: u32) InnerError!WValue {
2499 const mod = func.bin_file.base.comp.module.?;
2516 const pt = func.pt;
2517 const mod = pt.zcu;
25002518 // load local's value from memory by its stack position
25012519 try func.emitWValue(operand);
25022520
......@@ -2507,15 +2525,15 @@ fn load(func: *CodeGen, operand: WValue, ty: Type, offset: u32) InnerError!WValu
25072525 try func.mir_extra.appendSlice(func.gpa, &[_]u32{
25082526 std.wasm.simdOpcode(.v128_load),
25092527 offset + operand.offset(),
2510 @intCast(ty.abiAlignment(mod).toByteUnits().?),
2528 @intCast(ty.abiAlignment(pt).toByteUnits().?),
25112529 });
25122530 try func.addInst(.{ .tag = .simd_prefix, .data = .{ .payload = extra_index } });
25132531 return WValue{ .stack = {} };
25142532 }
25152533
2516 const abi_size: u8 = @intCast(ty.abiSize(mod));
2534 const abi_size: u8 = @intCast(ty.abiSize(pt));
25172535 const opcode = buildOpcode(.{
2518 .valtype1 = typeToValtype(ty, mod),
2536 .valtype1 = typeToValtype(ty, pt),
25192537 .width = abi_size * 8,
25202538 .op = .load,
25212539 .signedness = if (ty.isSignedInt(mod)) .signed else .unsigned,
......@@ -2525,7 +2543,7 @@ fn load(func: *CodeGen, operand: WValue, ty: Type, offset: u32) InnerError!WValu
25252543 Mir.Inst.Tag.fromOpcode(opcode),
25262544 .{
25272545 .offset = offset + operand.offset(),
2528 .alignment = @intCast(ty.abiAlignment(mod).toByteUnits().?),
2546 .alignment = @intCast(ty.abiAlignment(pt).toByteUnits().?),
25292547 },
25302548 );
25312549
......@@ -2533,13 +2551,14 @@ fn load(func: *CodeGen, operand: WValue, ty: Type, offset: u32) InnerError!WValu
25332551}
25342552
25352553fn airArg(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
2536 const mod = func.bin_file.base.comp.module.?;
2554 const pt = func.pt;
2555 const mod = pt.zcu;
25372556 const arg_index = func.arg_index;
25382557 const arg = func.args[arg_index];
25392558 const cc = mod.typeToFunc(func.decl.typeOf(mod)).?.cc;
25402559 const arg_ty = func.typeOfIndex(inst);
25412560 if (cc == .C) {
2542 const arg_classes = abi.classifyType(arg_ty, mod);
2561 const arg_classes = abi.classifyType(arg_ty, pt);
25432562 for (arg_classes) |class| {
25442563 if (class != .none) {
25452564 func.arg_index += 1;
......@@ -2552,7 +2571,7 @@ fn airArg(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
25522571 if (arg_ty.zigTypeTag(mod) != .Int and arg_ty.zigTypeTag(mod) != .Float) {
25532572 return func.fail(
25542573 "TODO: Implement C-ABI argument for type '{}'",
2555 .{arg_ty.fmt(func.bin_file.base.comp.module.?)},
2574 .{arg_ty.fmt(pt)},
25562575 );
25572576 }
25582577 const result = try func.allocStack(arg_ty);
......@@ -2579,7 +2598,7 @@ fn airArg(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
25792598}
25802599
25812600fn airBinOp(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
2582 const mod = func.bin_file.base.comp.module.?;
2601 const pt = func.pt;
25832602 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
25842603 const lhs = try func.resolveInst(bin_op.lhs);
25852604 const rhs = try func.resolveInst(bin_op.rhs);
......@@ -2593,10 +2612,10 @@ fn airBinOp(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
25932612 // For big integers we can ignore this as we will call into compiler-rt which handles this.
25942613 const result = switch (op) {
25952614 .shr, .shl => res: {
2596 const lhs_wasm_bits = toWasmBits(@as(u16, @intCast(lhs_ty.bitSize(mod)))) orelse {
2615 const lhs_wasm_bits = toWasmBits(@intCast(lhs_ty.bitSize(pt))) orelse {
25972616 return func.fail("TODO: implement '{s}' for types larger than 128 bits", .{@tagName(op)});
25982617 };
2599 const rhs_wasm_bits = toWasmBits(@as(u16, @intCast(rhs_ty.bitSize(mod)))).?;
2618 const rhs_wasm_bits = toWasmBits(@intCast(rhs_ty.bitSize(pt))).?;
26002619 const new_rhs = if (lhs_wasm_bits != rhs_wasm_bits and lhs_wasm_bits != 128) blk: {
26012620 const tmp = try func.intcast(rhs, rhs_ty, lhs_ty);
26022621 break :blk try tmp.toLocal(func, lhs_ty);
......@@ -2616,7 +2635,8 @@ fn airBinOp(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
26162635/// Performs a binary operation on the given `WValue`'s
26172636/// NOTE: THis leaves the value on top of the stack.
26182637fn binOp(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, op: Op) InnerError!WValue {
2619 const mod = func.bin_file.base.comp.module.?;
2638 const pt = func.pt;
2639 const mod = pt.zcu;
26202640 assert(!(lhs != .stack and rhs == .stack));
26212641
26222642 if (ty.isAnyFloat()) {
......@@ -2624,20 +2644,20 @@ fn binOp(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, op: Op) InnerError!
26242644 return func.floatOp(float_op, ty, &.{ lhs, rhs });
26252645 }
26262646
2627 if (isByRef(ty, mod)) {
2647 if (isByRef(ty, pt)) {
26282648 if (ty.zigTypeTag(mod) == .Int) {
26292649 return func.binOpBigInt(lhs, rhs, ty, op);
26302650 } else {
26312651 return func.fail(
26322652 "TODO: Implement binary operation for type: {}",
2633 .{ty.fmt(func.bin_file.base.comp.module.?)},
2653 .{ty.fmt(pt)},
26342654 );
26352655 }
26362656 }
26372657
26382658 const opcode: wasm.Opcode = buildOpcode(.{
26392659 .op = op,
2640 .valtype1 = typeToValtype(ty, mod),
2660 .valtype1 = typeToValtype(ty, pt),
26412661 .signedness = if (ty.isSignedInt(mod)) .signed else .unsigned,
26422662 });
26432663 try func.emitWValue(lhs);
......@@ -2649,7 +2669,8 @@ fn binOp(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, op: Op) InnerError!
26492669}
26502670
26512671fn binOpBigInt(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, op: Op) InnerError!WValue {
2652 const mod = func.bin_file.base.comp.module.?;
2672 const pt = func.pt;
2673 const mod = pt.zcu;
26532674 const int_info = ty.intInfo(mod);
26542675 if (int_info.bits > 128) {
26552676 return func.fail("TODO: Implement binary operation for big integers larger than 128 bits", .{});
......@@ -2785,7 +2806,8 @@ const FloatOp = enum {
27852806};
27862807
27872808fn airAbs(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
2788 const mod = func.bin_file.base.comp.module.?;
2809 const pt = func.pt;
2810 const mod = pt.zcu;
27892811 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
27902812 const operand = try func.resolveInst(ty_op.operand);
27912813 const ty = func.typeOf(ty_op.operand);
......@@ -2793,7 +2815,7 @@ fn airAbs(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
27932815
27942816 switch (scalar_ty.zigTypeTag(mod)) {
27952817 .Int => if (ty.zigTypeTag(mod) == .Vector) {
2796 return func.fail("TODO implement airAbs for {}", .{ty.fmt(mod)});
2818 return func.fail("TODO implement airAbs for {}", .{ty.fmt(pt)});
27972819 } else {
27982820 const int_bits = ty.intInfo(mod).bits;
27992821 const wasm_bits = toWasmBits(int_bits) orelse {
......@@ -2877,7 +2899,8 @@ fn airUnaryFloatOp(func: *CodeGen, inst: Air.Inst.Index, op: FloatOp) InnerError
28772899}
28782900
28792901fn floatOp(func: *CodeGen, float_op: FloatOp, ty: Type, args: []const WValue) InnerError!WValue {
2880 const mod = func.bin_file.base.comp.module.?;
2902 const pt = func.pt;
2903 const mod = pt.zcu;
28812904 if (ty.zigTypeTag(mod) == .Vector) {
28822905 return func.fail("TODO: Implement floatOps for vectors", .{});
28832906 }
......@@ -2893,7 +2916,7 @@ fn floatOp(func: *CodeGen, float_op: FloatOp, ty: Type, args: []const WValue) In
28932916 for (args) |operand| {
28942917 try func.emitWValue(operand);
28952918 }
2896 const opcode = buildOpcode(.{ .op = op, .valtype1 = typeToValtype(ty, mod) });
2919 const opcode = buildOpcode(.{ .op = op, .valtype1 = typeToValtype(ty, pt) });
28972920 try func.addTag(Mir.Inst.Tag.fromOpcode(opcode));
28982921 return .stack;
28992922 }
......@@ -2983,7 +3006,8 @@ fn floatNeg(func: *CodeGen, ty: Type, arg: WValue) InnerError!WValue {
29833006}
29843007
29853008fn airWrapBinOp(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
2986 const mod = func.bin_file.base.comp.module.?;
3009 const pt = func.pt;
3010 const mod = pt.zcu;
29873011 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
29883012
29893013 const lhs = try func.resolveInst(bin_op.lhs);
......@@ -3002,10 +3026,10 @@ fn airWrapBinOp(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
30023026 // For big integers we can ignore this as we will call into compiler-rt which handles this.
30033027 const result = switch (op) {
30043028 .shr, .shl => res: {
3005 const lhs_wasm_bits = toWasmBits(@as(u16, @intCast(lhs_ty.bitSize(mod)))) orelse {
3029 const lhs_wasm_bits = toWasmBits(@intCast(lhs_ty.bitSize(pt))) orelse {
30063030 return func.fail("TODO: implement '{s}' for types larger than 128 bits", .{@tagName(op)});
30073031 };
3008 const rhs_wasm_bits = toWasmBits(@as(u16, @intCast(rhs_ty.bitSize(mod)))).?;
3032 const rhs_wasm_bits = toWasmBits(@intCast(rhs_ty.bitSize(pt))).?;
30093033 const new_rhs = if (lhs_wasm_bits != rhs_wasm_bits and lhs_wasm_bits != 128) blk: {
30103034 const tmp = try func.intcast(rhs, rhs_ty, lhs_ty);
30113035 break :blk try tmp.toLocal(func, lhs_ty);
......@@ -3034,9 +3058,10 @@ fn wrapBinOp(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, op: Op) InnerEr
30343058/// Asserts `Type` is <= 128 bits.
30353059/// NOTE: When the Type is <= 64 bits, leaves the value on top of the stack, if wrapping was needed.
30363060fn wrapOperand(func: *CodeGen, operand: WValue, ty: Type) InnerError!WValue {
3037 const mod = func.bin_file.base.comp.module.?;
3038 assert(ty.abiSize(mod) <= 16);
3039 const int_bits = @as(u16, @intCast(ty.bitSize(mod))); // TODO use ty.intInfo(mod).bits
3061 const pt = func.pt;
3062 const mod = pt.zcu;
3063 assert(ty.abiSize(pt) <= 16);
3064 const int_bits: u16 = @intCast(ty.bitSize(pt)); // TODO use ty.intInfo(mod).bits
30403065 const wasm_bits = toWasmBits(int_bits) orelse {
30413066 return func.fail("TODO: Implement wrapOperand for bitsize '{d}'", .{int_bits});
30423067 };
......@@ -3098,13 +3123,14 @@ fn wrapOperand(func: *CodeGen, operand: WValue, ty: Type) InnerError!WValue {
30983123}
30993124
31003125fn lowerPtr(func: *CodeGen, ptr_val: InternPool.Index, prev_offset: u64) InnerError!WValue {
3101 const zcu = func.bin_file.base.comp.module.?;
3126 const pt = func.pt;
3127 const zcu = pt.zcu;
31023128 const ptr = zcu.intern_pool.indexToKey(ptr_val).ptr;
31033129 const offset: u64 = prev_offset + ptr.byte_offset;
31043130 return switch (ptr.base_addr) {
31053131 .decl => |decl| return func.lowerDeclRefValue(decl, @intCast(offset)),
31063132 .anon_decl => |ad| return func.lowerAnonDeclRef(ad, @intCast(offset)),
3107 .int => return func.lowerConstant(try zcu.intValue(Type.usize, offset), Type.usize),
3133 .int => return func.lowerConstant(try pt.intValue(Type.usize, offset), Type.usize),
31083134 .eu_payload => return func.fail("Wasm TODO: lower error union payload pointer", .{}),
31093135 .opt_payload => |opt_ptr| return func.lowerPtr(opt_ptr, offset),
31103136 .field => |field| {
......@@ -3120,13 +3146,13 @@ fn lowerPtr(func: *CodeGen, ptr_val: InternPool.Index, prev_offset: u64) InnerEr
31203146 };
31213147 },
31223148 .Struct => switch (base_ty.containerLayout(zcu)) {
3123 .auto => base_ty.structFieldOffset(@intCast(field.index), zcu),
3149 .auto => base_ty.structFieldOffset(@intCast(field.index), pt),
31243150 .@"extern", .@"packed" => unreachable,
31253151 },
31263152 .Union => switch (base_ty.containerLayout(zcu)) {
31273153 .auto => off: {
31283154 // Keep in sync with the `un` case of `generateSymbol`.
3129 const layout = base_ty.unionGetLayout(zcu);
3155 const layout = base_ty.unionGetLayout(pt);
31303156 if (layout.payload_size == 0) break :off 0;
31313157 if (layout.tag_size == 0) break :off 0;
31323158 if (layout.tag_align.compare(.gte, layout.payload_align)) {
......@@ -3152,17 +3178,18 @@ fn lowerAnonDeclRef(
31523178 anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl,
31533179 offset: u32,
31543180) InnerError!WValue {
3155 const mod = func.bin_file.base.comp.module.?;
3181 const pt = func.pt;
3182 const mod = pt.zcu;
31563183 const decl_val = anon_decl.val;
31573184 const ty = Type.fromInterned(mod.intern_pool.typeOf(decl_val));
31583185
31593186 const is_fn_body = ty.zigTypeTag(mod) == .Fn;
3160 if (!is_fn_body and !ty.hasRuntimeBitsIgnoreComptime(mod)) {
3187 if (!is_fn_body and !ty.hasRuntimeBitsIgnoreComptime(pt)) {
31613188 return WValue{ .imm32 = 0xaaaaaaaa };
31623189 }
31633190
31643191 const decl_align = mod.intern_pool.indexToKey(anon_decl.orig_ty).ptr_type.flags.alignment;
3165 const res = try func.bin_file.lowerAnonDecl(decl_val, decl_align, func.decl.navSrcLoc(mod));
3192 const res = try func.bin_file.lowerAnonDecl(pt, decl_val, decl_align, func.decl.navSrcLoc(mod));
31663193 switch (res) {
31673194 .ok => {},
31683195 .fail => |em| {
......@@ -3180,7 +3207,8 @@ fn lowerAnonDeclRef(
31803207}
31813208
31823209fn lowerDeclRefValue(func: *CodeGen, decl_index: InternPool.DeclIndex, offset: u32) InnerError!WValue {
3183 const mod = func.bin_file.base.comp.module.?;
3210 const pt = func.pt;
3211 const mod = pt.zcu;
31843212
31853213 const decl = mod.declPtr(decl_index);
31863214 // check if decl is an alias to a function, in which case we
......@@ -3195,11 +3223,11 @@ fn lowerDeclRefValue(func: *CodeGen, decl_index: InternPool.DeclIndex, offset: u
31953223 }
31963224 }
31973225 const decl_ty = decl.typeOf(mod);
3198 if (decl_ty.zigTypeTag(mod) != .Fn and !decl_ty.hasRuntimeBitsIgnoreComptime(mod)) {
3226 if (decl_ty.zigTypeTag(mod) != .Fn and !decl_ty.hasRuntimeBitsIgnoreComptime(pt)) {
31993227 return WValue{ .imm32 = 0xaaaaaaaa };
32003228 }
32013229
3202 const atom_index = try func.bin_file.getOrCreateAtomForDecl(decl_index);
3230 const atom_index = try func.bin_file.getOrCreateAtomForDecl(pt, decl_index);
32033231 const atom = func.bin_file.getAtom(atom_index);
32043232
32053233 const target_sym_index = @intFromEnum(atom.sym_index);
......@@ -3212,8 +3240,9 @@ fn lowerDeclRefValue(func: *CodeGen, decl_index: InternPool.DeclIndex, offset: u
32123240
32133241/// Asserts that `isByRef` returns `false` for `ty`.
32143242fn lowerConstant(func: *CodeGen, val: Value, ty: Type) InnerError!WValue {
3215 const mod = func.bin_file.base.comp.module.?;
3216 assert(!isByRef(ty, mod));
3243 const pt = func.pt;
3244 const mod = pt.zcu;
3245 assert(!isByRef(ty, pt));
32173246 const ip = &mod.intern_pool;
32183247 if (val.isUndefDeep(mod)) return func.emitUndefined(ty);
32193248
......@@ -3261,13 +3290,13 @@ fn lowerConstant(func: *CodeGen, val: Value, ty: Type) InnerError!WValue {
32613290 const int_info = ty.intInfo(mod);
32623291 switch (int_info.signedness) {
32633292 .signed => switch (int_info.bits) {
3264 0...32 => return WValue{ .imm32 = @bitCast(@as(i32, @intCast(val.toSignedInt(mod)))) },
3265 33...64 => return WValue{ .imm64 = @bitCast(val.toSignedInt(mod)) },
3293 0...32 => return WValue{ .imm32 = @bitCast(@as(i32, @intCast(val.toSignedInt(pt)))) },
3294 33...64 => return WValue{ .imm64 = @bitCast(val.toSignedInt(pt)) },
32663295 else => unreachable,
32673296 },
32683297 .unsigned => switch (int_info.bits) {
3269 0...32 => return WValue{ .imm32 = @intCast(val.toUnsignedInt(mod)) },
3270 33...64 => return WValue{ .imm64 = val.toUnsignedInt(mod) },
3298 0...32 => return WValue{ .imm32 = @intCast(val.toUnsignedInt(pt)) },
3299 33...64 => return WValue{ .imm64 = val.toUnsignedInt(pt) },
32713300 else => unreachable,
32723301 },
32733302 }
......@@ -3277,22 +3306,22 @@ fn lowerConstant(func: *CodeGen, val: Value, ty: Type) InnerError!WValue {
32773306 return WValue{ .imm32 = int };
32783307 },
32793308 .error_union => |error_union| {
3280 const err_int_ty = try mod.errorIntType();
3309 const err_int_ty = try pt.errorIntType();
32813310 const err_ty, const err_val = switch (error_union.val) {
32823311 .err_name => |err_name| .{
32833312 ty.errorUnionSet(mod),
3284 Value.fromInterned((try mod.intern(.{ .err = .{
3313 Value.fromInterned(try pt.intern(.{ .err = .{
32853314 .ty = ty.errorUnionSet(mod).toIntern(),
32863315 .name = err_name,
3287 } }))),
3316 } })),
32883317 },
32893318 .payload => .{
32903319 err_int_ty,
3291 try mod.intValue(err_int_ty, 0),
3320 try pt.intValue(err_int_ty, 0),
32923321 },
32933322 };
32943323 const payload_type = ty.errorUnionPayload(mod);
3295 if (!payload_type.hasRuntimeBitsIgnoreComptime(mod)) {
3324 if (!payload_type.hasRuntimeBitsIgnoreComptime(pt)) {
32963325 // We use the error type directly as the type.
32973326 return func.lowerConstant(err_val, err_ty);
32983327 }
......@@ -3318,7 +3347,7 @@ fn lowerConstant(func: *CodeGen, val: Value, ty: Type) InnerError!WValue {
33183347 .field => |base_index| ptr = ip.indexToKey(base_index.base).ptr,
33193348 .arr_elem, .comptime_field, .comptime_alloc => unreachable,
33203349 };
3321 return .{ .memory = try func.bin_file.lowerUnnamedConst(val, owner_decl) };
3350 return .{ .memory = try func.bin_file.lowerUnnamedConst(pt, val, owner_decl) };
33223351 },
33233352 .ptr => return func.lowerPtr(val.toIntern(), 0),
33243353 .opt => if (ty.optionalReprIsPayload(mod)) {
......@@ -3332,11 +3361,11 @@ fn lowerConstant(func: *CodeGen, val: Value, ty: Type) InnerError!WValue {
33323361 return WValue{ .imm32 = @intFromBool(!val.isNull(mod)) };
33333362 },
33343363 .aggregate => switch (ip.indexToKey(ty.ip_index)) {
3335 .array_type => return func.fail("Wasm TODO: LowerConstant for {}", .{ty.fmt(mod)}),
3364 .array_type => return func.fail("Wasm TODO: LowerConstant for {}", .{ty.fmt(pt)}),
33363365 .vector_type => {
3337 assert(determineSimdStoreStrategy(ty, mod) == .direct);
3366 assert(determineSimdStoreStrategy(ty, pt) == .direct);
33383367 var buf: [16]u8 = undefined;
3339 val.writeToMemory(ty, mod, &buf) catch unreachable;
3368 val.writeToMemory(ty, pt, &buf) catch unreachable;
33403369 return func.storeSimdImmd(buf);
33413370 },
33423371 .struct_type => {
......@@ -3345,9 +3374,9 @@ fn lowerConstant(func: *CodeGen, val: Value, ty: Type) InnerError!WValue {
33453374 // are by-ref types.
33463375 assert(struct_type.layout == .@"packed");
33473376 var buf: [8]u8 = .{0} ** 8; // zero the buffer so we do not read 0xaa as integer
3348 val.writeToPackedMemory(ty, mod, &buf, 0) catch unreachable;
3377 val.writeToPackedMemory(ty, pt, &buf, 0) catch unreachable;
33493378 const backing_int_ty = Type.fromInterned(struct_type.backingIntType(ip).*);
3350 const int_val = try mod.intValue(
3379 const int_val = try pt.intValue(
33513380 backing_int_ty,
33523381 mem.readInt(u64, &buf, .little),
33533382 );
......@@ -3358,7 +3387,7 @@ fn lowerConstant(func: *CodeGen, val: Value, ty: Type) InnerError!WValue {
33583387 .un => |un| {
33593388 // in this case we have a packed union which will not be passed by reference.
33603389 const constant_ty = if (un.tag == .none)
3361 try ty.unionBackingType(mod)
3390 try ty.unionBackingType(pt)
33623391 else field_ty: {
33633392 const union_obj = mod.typeToUnion(ty).?;
33643393 const field_index = mod.unionTagFieldIndex(union_obj, Value.fromInterned(un.tag)).?;
......@@ -3379,7 +3408,8 @@ fn storeSimdImmd(func: *CodeGen, value: [16]u8) !WValue {
33793408}
33803409
33813410fn emitUndefined(func: *CodeGen, ty: Type) InnerError!WValue {
3382 const mod = func.bin_file.base.comp.module.?;
3411 const pt = func.pt;
3412 const mod = pt.zcu;
33833413 const ip = &mod.intern_pool;
33843414 switch (ty.zigTypeTag(mod)) {
33853415 .Bool, .ErrorSet => return WValue{ .imm32 = 0xaaaaaaaa },
......@@ -3421,15 +3451,16 @@ fn emitUndefined(func: *CodeGen, ty: Type) InnerError!WValue {
34213451/// It's illegal to provide a value with a type that cannot be represented
34223452/// as an integer value.
34233453fn valueAsI32(func: *const CodeGen, val: Value, ty: Type) i32 {
3424 const mod = func.bin_file.base.comp.module.?;
3454 const pt = func.pt;
3455 const mod = pt.zcu;
34253456
34263457 switch (val.ip_index) {
34273458 .none => {},
34283459 .bool_true => return 1,
34293460 .bool_false => return 0,
34303461 else => return switch (mod.intern_pool.indexToKey(val.ip_index)) {
3431 .enum_tag => |enum_tag| intIndexAsI32(&mod.intern_pool, enum_tag.int, mod),
3432 .int => |int| intStorageAsI32(int.storage, mod),
3462 .enum_tag => |enum_tag| intIndexAsI32(&mod.intern_pool, enum_tag.int, pt),
3463 .int => |int| intStorageAsI32(int.storage, pt),
34333464 .ptr => |ptr| {
34343465 assert(ptr.base_addr == .int);
34353466 return @intCast(ptr.byte_offset);
......@@ -3445,17 +3476,17 @@ fn valueAsI32(func: *const CodeGen, val: Value, ty: Type) i32 {
34453476 };
34463477}
34473478
3448fn intIndexAsI32(ip: *const InternPool, int: InternPool.Index, mod: *Zcu) i32 {
3449 return intStorageAsI32(ip.indexToKey(int).int.storage, mod);
3479fn intIndexAsI32(ip: *const InternPool, int: InternPool.Index, pt: Zcu.PerThread) i32 {
3480 return intStorageAsI32(ip.indexToKey(int).int.storage, pt);
34503481}
34513482
3452fn intStorageAsI32(storage: InternPool.Key.Int.Storage, mod: *Zcu) i32 {
3483fn intStorageAsI32(storage: InternPool.Key.Int.Storage, pt: Zcu.PerThread) i32 {
34533484 return switch (storage) {
34543485 .i64 => |x| @as(i32, @intCast(x)),
34553486 .u64 => |x| @as(i32, @bitCast(@as(u32, @intCast(x)))),
34563487 .big_int => unreachable,
3457 .lazy_align => |ty| @as(i32, @bitCast(@as(u32, @intCast(Type.fromInterned(ty).abiAlignment(mod).toByteUnits() orelse 0)))),
3458 .lazy_size => |ty| @as(i32, @bitCast(@as(u32, @intCast(Type.fromInterned(ty).abiSize(mod))))),
3488 .lazy_align => |ty| @as(i32, @bitCast(@as(u32, @intCast(Type.fromInterned(ty).abiAlignment(pt).toByteUnits() orelse 0)))),
3489 .lazy_size => |ty| @as(i32, @bitCast(@as(u32, @intCast(Type.fromInterned(ty).abiSize(pt))))),
34593490 };
34603491}
34613492
......@@ -3466,12 +3497,12 @@ fn airBlock(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
34663497}
34673498
34683499fn lowerBlock(func: *CodeGen, inst: Air.Inst.Index, block_ty: Type, body: []const Air.Inst.Index) InnerError!void {
3469 const mod = func.bin_file.base.comp.module.?;
3470 const wasm_block_ty = genBlockType(block_ty, mod);
3500 const pt = func.pt;
3501 const wasm_block_ty = genBlockType(block_ty, pt);
34713502
34723503 // if wasm_block_ty is non-empty, we create a register to store the temporary value
34733504 const block_result: WValue = if (wasm_block_ty != wasm.block_empty) blk: {
3474 const ty: Type = if (isByRef(block_ty, mod)) Type.u32 else block_ty;
3505 const ty: Type = if (isByRef(block_ty, pt)) Type.u32 else block_ty;
34753506 break :blk try func.ensureAllocLocal(ty); // make sure it's a clean local as it may never get overwritten
34763507 } else WValue.none;
34773508
......@@ -3583,10 +3614,11 @@ fn airCmp(func: *CodeGen, inst: Air.Inst.Index, op: std.math.CompareOperator) In
35833614/// NOTE: This leaves the result on top of the stack, rather than a new local.
35843615fn cmp(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, op: std.math.CompareOperator) InnerError!WValue {
35853616 assert(!(lhs != .stack and rhs == .stack));
3586 const mod = func.bin_file.base.comp.module.?;
3617 const pt = func.pt;
3618 const mod = pt.zcu;
35873619 if (ty.zigTypeTag(mod) == .Optional and !ty.optionalReprIsPayload(mod)) {
35883620 const payload_ty = ty.optionalChild(mod);
3589 if (payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
3621 if (payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
35903622 // When we hit this case, we must check the value of optionals
35913623 // that are not pointers. This means first checking against non-null for
35923624 // both lhs and rhs, as well as checking the payload are matching of lhs and rhs
......@@ -3594,7 +3626,7 @@ fn cmp(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, op: std.math.CompareO
35943626 }
35953627 } else if (ty.isAnyFloat()) {
35963628 return func.cmpFloat(ty, lhs, rhs, op);
3597 } else if (isByRef(ty, mod)) {
3629 } else if (isByRef(ty, pt)) {
35983630 return func.cmpBigInt(lhs, rhs, ty, op);
35993631 }
36003632
......@@ -3612,7 +3644,7 @@ fn cmp(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, op: std.math.CompareO
36123644 try func.lowerToStack(rhs);
36133645
36143646 const opcode: wasm.Opcode = buildOpcode(.{
3615 .valtype1 = typeToValtype(ty, mod),
3647 .valtype1 = typeToValtype(ty, pt),
36163648 .op = switch (op) {
36173649 .lt => .lt,
36183650 .lte => .le,
......@@ -3683,8 +3715,8 @@ fn airCmpLtErrorsLen(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
36833715 const errors_len = WValue{ .memory = @intFromEnum(sym_index) };
36843716
36853717 try func.emitWValue(operand);
3686 const mod = func.bin_file.base.comp.module.?;
3687 const err_int_ty = try mod.errorIntType();
3718 const pt = func.pt;
3719 const err_int_ty = try pt.errorIntType();
36883720 const errors_len_val = try func.load(errors_len, err_int_ty, 0);
36893721 const result = try func.cmp(.stack, errors_len_val, err_int_ty, .lt);
36903722
......@@ -3692,12 +3724,12 @@ fn airCmpLtErrorsLen(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
36923724}
36933725
36943726fn airBr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
3695 const mod = func.bin_file.base.comp.module.?;
3727 const pt = func.pt;
36963728 const br = func.air.instructions.items(.data)[@intFromEnum(inst)].br;
36973729 const block = func.blocks.get(br.block_inst).?;
36983730
36993731 // if operand has codegen bits we should break with a value
3700 if (func.typeOf(br.operand).hasRuntimeBitsIgnoreComptime(mod)) {
3732 if (func.typeOf(br.operand).hasRuntimeBitsIgnoreComptime(pt)) {
37013733 const operand = try func.resolveInst(br.operand);
37023734 try func.lowerToStack(operand);
37033735
......@@ -3719,7 +3751,8 @@ fn airNot(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
37193751
37203752 const operand = try func.resolveInst(ty_op.operand);
37213753 const operand_ty = func.typeOf(ty_op.operand);
3722 const mod = func.bin_file.base.comp.module.?;
3754 const pt = func.pt;
3755 const mod = pt.zcu;
37233756
37243757 const result = result: {
37253758 if (operand_ty.zigTypeTag(mod) == .Bool) {
......@@ -3731,7 +3764,7 @@ fn airNot(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
37313764 } else {
37323765 const int_info = operand_ty.intInfo(mod);
37333766 const wasm_bits = toWasmBits(int_info.bits) orelse {
3734 return func.fail("TODO: Implement binary NOT for {}", .{operand_ty.fmt(mod)});
3767 return func.fail("TODO: Implement binary NOT for {}", .{operand_ty.fmt(pt)});
37353768 };
37363769
37373770 switch (wasm_bits) {
......@@ -3798,13 +3831,14 @@ fn airUnreachable(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
37983831}
37993832
38003833fn airBitcast(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
3801 const mod = func.bin_file.base.comp.module.?;
3834 const pt = func.pt;
3835 const mod = pt.zcu;
38023836 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
38033837 const operand = try func.resolveInst(ty_op.operand);
38043838 const wanted_ty = func.typeOfIndex(inst);
38053839 const given_ty = func.typeOf(ty_op.operand);
38063840
3807 const bit_size = given_ty.bitSize(mod);
3841 const bit_size = given_ty.bitSize(pt);
38083842 const needs_wrapping = (given_ty.isSignedInt(mod) != wanted_ty.isSignedInt(mod)) and
38093843 bit_size != 32 and bit_size != 64 and bit_size != 128;
38103844
......@@ -3814,7 +3848,7 @@ fn airBitcast(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
38143848 break :result try bitcast_result.toLocal(func, wanted_ty);
38153849 }
38163850
3817 if (isByRef(given_ty, mod) and !isByRef(wanted_ty, mod)) {
3851 if (isByRef(given_ty, pt) and !isByRef(wanted_ty, pt)) {
38183852 const loaded_memory = try func.load(operand, wanted_ty, 0);
38193853 if (needs_wrapping) {
38203854 break :result try (try func.wrapOperand(loaded_memory, wanted_ty)).toLocal(func, wanted_ty);
......@@ -3822,7 +3856,7 @@ fn airBitcast(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
38223856 break :result try loaded_memory.toLocal(func, wanted_ty);
38233857 }
38243858 }
3825 if (!isByRef(given_ty, mod) and isByRef(wanted_ty, mod)) {
3859 if (!isByRef(given_ty, pt) and isByRef(wanted_ty, pt)) {
38263860 const stack_memory = try func.allocStack(wanted_ty);
38273861 try func.store(stack_memory, operand, given_ty, 0);
38283862 if (needs_wrapping) {
......@@ -3842,17 +3876,18 @@ fn airBitcast(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
38423876}
38433877
38443878fn bitcast(func: *CodeGen, wanted_ty: Type, given_ty: Type, operand: WValue) InnerError!WValue {
3845 const mod = func.bin_file.base.comp.module.?;
3879 const pt = func.pt;
3880 const mod = pt.zcu;
38463881 // if we bitcast a float to or from an integer we must use the 'reinterpret' instruction
38473882 if (!(wanted_ty.isAnyFloat() or given_ty.isAnyFloat())) return operand;
38483883 if (wanted_ty.ip_index == .f16_type or given_ty.ip_index == .f16_type) return operand;
3849 if (wanted_ty.bitSize(mod) > 64) return operand;
3884 if (wanted_ty.bitSize(pt) > 64) return operand;
38503885 assert((wanted_ty.isInt(mod) and given_ty.isAnyFloat()) or (wanted_ty.isAnyFloat() and given_ty.isInt(mod)));
38513886
38523887 const opcode = buildOpcode(.{
38533888 .op = .reinterpret,
3854 .valtype1 = typeToValtype(wanted_ty, mod),
3855 .valtype2 = typeToValtype(given_ty, mod),
3889 .valtype1 = typeToValtype(wanted_ty, pt),
3890 .valtype2 = typeToValtype(given_ty, pt),
38563891 });
38573892 try func.emitWValue(operand);
38583893 try func.addTag(Mir.Inst.Tag.fromOpcode(opcode));
......@@ -3860,7 +3895,8 @@ fn bitcast(func: *CodeGen, wanted_ty: Type, given_ty: Type, operand: WValue) Inn
38603895}
38613896
38623897fn airStructFieldPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
3863 const mod = func.bin_file.base.comp.module.?;
3898 const pt = func.pt;
3899 const mod = pt.zcu;
38643900 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
38653901 const extra = func.air.extraData(Air.StructField, ty_pl.payload);
38663902
......@@ -3872,7 +3908,8 @@ fn airStructFieldPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
38723908}
38733909
38743910fn airStructFieldPtrIndex(func: *CodeGen, inst: Air.Inst.Index, index: u32) InnerError!void {
3875 const mod = func.bin_file.base.comp.module.?;
3911 const pt = func.pt;
3912 const mod = pt.zcu;
38763913 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
38773914 const struct_ptr = try func.resolveInst(ty_op.operand);
38783915 const struct_ptr_ty = func.typeOf(ty_op.operand);
......@@ -3891,7 +3928,8 @@ fn structFieldPtr(
38913928 struct_ty: Type,
38923929 index: u32,
38933930) InnerError!WValue {
3894 const mod = func.bin_file.base.comp.module.?;
3931 const pt = func.pt;
3932 const mod = pt.zcu;
38953933 const result_ty = func.typeOfIndex(inst);
38963934 const struct_ptr_ty_info = struct_ptr_ty.ptrInfo(mod);
38973935
......@@ -3902,12 +3940,12 @@ fn structFieldPtr(
39023940 break :offset @as(u32, 0);
39033941 }
39043942 const struct_type = mod.typeToStruct(struct_ty).?;
3905 break :offset @divExact(mod.structPackedFieldBitOffset(struct_type, index) + struct_ptr_ty_info.packed_offset.bit_offset, 8);
3943 break :offset @divExact(pt.structPackedFieldBitOffset(struct_type, index) + struct_ptr_ty_info.packed_offset.bit_offset, 8);
39063944 },
39073945 .Union => 0,
39083946 else => unreachable,
39093947 },
3910 else => struct_ty.structFieldOffset(index, mod),
3948 else => struct_ty.structFieldOffset(index, pt),
39113949 };
39123950 // save a load and store when we can simply reuse the operand
39133951 if (offset == 0) {
......@@ -3922,7 +3960,8 @@ fn structFieldPtr(
39223960}
39233961
39243962fn airStructFieldVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
3925 const mod = func.bin_file.base.comp.module.?;
3963 const pt = func.pt;
3964 const mod = pt.zcu;
39263965 const ip = &mod.intern_pool;
39273966 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
39283967 const struct_field = func.air.extraData(Air.StructField, ty_pl.payload).data;
......@@ -3931,13 +3970,13 @@ fn airStructFieldVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
39313970 const operand = try func.resolveInst(struct_field.struct_operand);
39323971 const field_index = struct_field.field_index;
39333972 const field_ty = struct_ty.structFieldType(field_index, mod);
3934 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) return func.finishAir(inst, .none, &.{struct_field.struct_operand});
3973 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) return func.finishAir(inst, .none, &.{struct_field.struct_operand});
39353974
39363975 const result = switch (struct_ty.containerLayout(mod)) {
39373976 .@"packed" => switch (struct_ty.zigTypeTag(mod)) {
39383977 .Struct => result: {
39393978 const packed_struct = mod.typeToPackedStruct(struct_ty).?;
3940 const offset = mod.structPackedFieldBitOffset(packed_struct, field_index);
3979 const offset = pt.structPackedFieldBitOffset(packed_struct, field_index);
39413980 const backing_ty = Type.fromInterned(packed_struct.backingIntType(ip).*);
39423981 const wasm_bits = toWasmBits(backing_ty.intInfo(mod).bits) orelse {
39433982 return func.fail("TODO: airStructFieldVal for packed structs larger than 128 bits", .{});
......@@ -3956,7 +3995,7 @@ fn airStructFieldVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
39563995 try func.binOp(operand, const_wvalue, backing_ty, .shr);
39573996
39583997 if (field_ty.zigTypeTag(mod) == .Float) {
3959 const int_type = try mod.intType(.unsigned, @as(u16, @intCast(field_ty.bitSize(mod))));
3998 const int_type = try pt.intType(.unsigned, @as(u16, @intCast(field_ty.bitSize(pt))));
39603999 const truncated = try func.trunc(shifted_value, int_type, backing_ty);
39614000 const bitcasted = try func.bitcast(field_ty, int_type, truncated);
39624001 break :result try bitcasted.toLocal(func, field_ty);
......@@ -3965,7 +4004,7 @@ fn airStructFieldVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
39654004 // we can simply reuse the operand.
39664005 break :result func.reuseOperand(struct_field.struct_operand, operand);
39674006 } else if (field_ty.isPtrAtRuntime(mod)) {
3968 const int_type = try mod.intType(.unsigned, @as(u16, @intCast(field_ty.bitSize(mod))));
4007 const int_type = try pt.intType(.unsigned, @as(u16, @intCast(field_ty.bitSize(pt))));
39694008 const truncated = try func.trunc(shifted_value, int_type, backing_ty);
39704009 break :result try truncated.toLocal(func, field_ty);
39714010 }
......@@ -3973,8 +4012,8 @@ fn airStructFieldVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
39734012 break :result try truncated.toLocal(func, field_ty);
39744013 },
39754014 .Union => result: {
3976 if (isByRef(struct_ty, mod)) {
3977 if (!isByRef(field_ty, mod)) {
4015 if (isByRef(struct_ty, pt)) {
4016 if (!isByRef(field_ty, pt)) {
39784017 const val = try func.load(operand, field_ty, 0);
39794018 break :result try val.toLocal(func, field_ty);
39804019 } else {
......@@ -3984,14 +4023,14 @@ fn airStructFieldVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
39844023 }
39854024 }
39864025
3987 const union_int_type = try mod.intType(.unsigned, @as(u16, @intCast(struct_ty.bitSize(mod))));
4026 const union_int_type = try pt.intType(.unsigned, @as(u16, @intCast(struct_ty.bitSize(pt))));
39884027 if (field_ty.zigTypeTag(mod) == .Float) {
3989 const int_type = try mod.intType(.unsigned, @as(u16, @intCast(field_ty.bitSize(mod))));
4028 const int_type = try pt.intType(.unsigned, @as(u16, @intCast(field_ty.bitSize(pt))));
39904029 const truncated = try func.trunc(operand, int_type, union_int_type);
39914030 const bitcasted = try func.bitcast(field_ty, int_type, truncated);
39924031 break :result try bitcasted.toLocal(func, field_ty);
39934032 } else if (field_ty.isPtrAtRuntime(mod)) {
3994 const int_type = try mod.intType(.unsigned, @as(u16, @intCast(field_ty.bitSize(mod))));
4033 const int_type = try pt.intType(.unsigned, @as(u16, @intCast(field_ty.bitSize(pt))));
39954034 const truncated = try func.trunc(operand, int_type, union_int_type);
39964035 break :result try truncated.toLocal(func, field_ty);
39974036 }
......@@ -4001,10 +4040,10 @@ fn airStructFieldVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
40014040 else => unreachable,
40024041 },
40034042 else => result: {
4004 const offset = std.math.cast(u32, struct_ty.structFieldOffset(field_index, mod)) orelse {
4005 return func.fail("Field type '{}' too big to fit into stack frame", .{field_ty.fmt(mod)});
4043 const offset = std.math.cast(u32, struct_ty.structFieldOffset(field_index, pt)) orelse {
4044 return func.fail("Field type '{}' too big to fit into stack frame", .{field_ty.fmt(pt)});
40064045 };
4007 if (isByRef(field_ty, mod)) {
4046 if (isByRef(field_ty, pt)) {
40084047 switch (operand) {
40094048 .stack_offset => |stack_offset| {
40104049 break :result WValue{ .stack_offset = .{ .value = stack_offset.value + offset, .references = 1 } };
......@@ -4021,7 +4060,8 @@ fn airStructFieldVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
40214060}
40224061
40234062fn airSwitchBr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4024 const mod = func.bin_file.base.comp.module.?;
4063 const pt = func.pt;
4064 const mod = pt.zcu;
40254065 // result type is always 'noreturn'
40264066 const blocktype = wasm.block_empty;
40274067 const pl_op = func.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
......@@ -4055,7 +4095,7 @@ fn airSwitchBr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
40554095 errdefer func.gpa.free(values);
40564096
40574097 for (items, 0..) |ref, i| {
4058 const item_val = (try func.air.value(ref, mod)).?;
4098 const item_val = (try func.air.value(ref, pt)).?;
40594099 const int_val = func.valueAsI32(item_val, target_ty);
40604100 if (lowest_maybe == null or int_val < lowest_maybe.?) {
40614101 lowest_maybe = int_val;
......@@ -4078,7 +4118,7 @@ fn airSwitchBr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
40784118 // When the target is an integer size larger than u32, we have no way to use the value
40794119 // as an index, therefore we also use an if/else-chain for those cases.
40804120 // TODO: Benchmark this to find a proper value, LLVM seems to draw the line at '40~45'.
4081 const is_sparse = highest - lowest > 50 or target_ty.bitSize(mod) > 32;
4121 const is_sparse = highest - lowest > 50 or target_ty.bitSize(pt) > 32;
40824122
40834123 const else_body: []const Air.Inst.Index = @ptrCast(func.air.extra[extra_index..][0..switch_br.data.else_body_len]);
40844124 const has_else_body = else_body.len != 0;
......@@ -4150,7 +4190,7 @@ fn airSwitchBr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
41504190 const val = try func.lowerConstant(case.values[0].value, target_ty);
41514191 try func.emitWValue(val);
41524192 const opcode = buildOpcode(.{
4153 .valtype1 = typeToValtype(target_ty, mod),
4193 .valtype1 = typeToValtype(target_ty, pt),
41544194 .op = .ne, // not equal, because we want to jump out of this block if it does not match the condition.
41554195 .signedness = signedness,
41564196 });
......@@ -4164,7 +4204,7 @@ fn airSwitchBr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
41644204 const val = try func.lowerConstant(value.value, target_ty);
41654205 try func.emitWValue(val);
41664206 const opcode = buildOpcode(.{
4167 .valtype1 = typeToValtype(target_ty, mod),
4207 .valtype1 = typeToValtype(target_ty, pt),
41684208 .op = .eq,
41694209 .signedness = signedness,
41704210 });
......@@ -4201,7 +4241,8 @@ fn airSwitchBr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
42014241}
42024242
42034243fn airIsErr(func: *CodeGen, inst: Air.Inst.Index, opcode: wasm.Opcode) InnerError!void {
4204 const mod = func.bin_file.base.comp.module.?;
4244 const pt = func.pt;
4245 const mod = pt.zcu;
42054246 const un_op = func.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
42064247 const operand = try func.resolveInst(un_op);
42074248 const err_union_ty = func.typeOf(un_op);
......@@ -4217,10 +4258,10 @@ fn airIsErr(func: *CodeGen, inst: Air.Inst.Index, opcode: wasm.Opcode) InnerErro
42174258 }
42184259
42194260 try func.emitWValue(operand);
4220 if (pl_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4261 if (pl_ty.hasRuntimeBitsIgnoreComptime(pt)) {
42214262 try func.addMemArg(.i32_load16_u, .{
4222 .offset = operand.offset() + @as(u32, @intCast(errUnionErrorOffset(pl_ty, mod))),
4223 .alignment = @intCast(Type.anyerror.abiAlignment(mod).toByteUnits().?),
4263 .offset = operand.offset() + @as(u32, @intCast(errUnionErrorOffset(pl_ty, pt))),
4264 .alignment = @intCast(Type.anyerror.abiAlignment(pt).toByteUnits().?),
42244265 });
42254266 }
42264267
......@@ -4236,7 +4277,8 @@ fn airIsErr(func: *CodeGen, inst: Air.Inst.Index, opcode: wasm.Opcode) InnerErro
42364277}
42374278
42384279fn airUnwrapErrUnionPayload(func: *CodeGen, inst: Air.Inst.Index, op_is_ptr: bool) InnerError!void {
4239 const mod = func.bin_file.base.comp.module.?;
4280 const pt = func.pt;
4281 const mod = pt.zcu;
42404282 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
42414283
42424284 const operand = try func.resolveInst(ty_op.operand);
......@@ -4245,15 +4287,15 @@ fn airUnwrapErrUnionPayload(func: *CodeGen, inst: Air.Inst.Index, op_is_ptr: boo
42454287 const payload_ty = err_ty.errorUnionPayload(mod);
42464288
42474289 const result = result: {
4248 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4290 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
42494291 if (op_is_ptr) {
42504292 break :result func.reuseOperand(ty_op.operand, operand);
42514293 }
42524294 break :result WValue{ .none = {} };
42534295 }
42544296
4255 const pl_offset = @as(u32, @intCast(errUnionPayloadOffset(payload_ty, mod)));
4256 if (op_is_ptr or isByRef(payload_ty, mod)) {
4297 const pl_offset = @as(u32, @intCast(errUnionPayloadOffset(payload_ty, pt)));
4298 if (op_is_ptr or isByRef(payload_ty, pt)) {
42574299 break :result try func.buildPointerOffset(operand, pl_offset, .new);
42584300 }
42594301
......@@ -4264,7 +4306,8 @@ fn airUnwrapErrUnionPayload(func: *CodeGen, inst: Air.Inst.Index, op_is_ptr: boo
42644306}
42654307
42664308fn airUnwrapErrUnionError(func: *CodeGen, inst: Air.Inst.Index, op_is_ptr: bool) InnerError!void {
4267 const mod = func.bin_file.base.comp.module.?;
4309 const pt = func.pt;
4310 const mod = pt.zcu;
42684311 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
42694312
42704313 const operand = try func.resolveInst(ty_op.operand);
......@@ -4277,18 +4320,18 @@ fn airUnwrapErrUnionError(func: *CodeGen, inst: Air.Inst.Index, op_is_ptr: bool)
42774320 break :result WValue{ .imm32 = 0 };
42784321 }
42794322
4280 if (op_is_ptr or !payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4323 if (op_is_ptr or !payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
42814324 break :result func.reuseOperand(ty_op.operand, operand);
42824325 }
42834326
4284 const error_val = try func.load(operand, Type.anyerror, @as(u32, @intCast(errUnionErrorOffset(payload_ty, mod))));
4327 const error_val = try func.load(operand, Type.anyerror, @intCast(errUnionErrorOffset(payload_ty, pt)));
42854328 break :result try error_val.toLocal(func, Type.anyerror);
42864329 };
42874330 func.finishAir(inst, result, &.{ty_op.operand});
42884331}
42894332
42904333fn airWrapErrUnionPayload(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4291 const mod = func.bin_file.base.comp.module.?;
4334 const pt = func.pt;
42924335 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
42934336
42944337 const operand = try func.resolveInst(ty_op.operand);
......@@ -4296,18 +4339,18 @@ fn airWrapErrUnionPayload(func: *CodeGen, inst: Air.Inst.Index) InnerError!void
42964339
42974340 const pl_ty = func.typeOf(ty_op.operand);
42984341 const result = result: {
4299 if (!pl_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4342 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) {
43004343 break :result func.reuseOperand(ty_op.operand, operand);
43014344 }
43024345
43034346 const err_union = try func.allocStack(err_ty);
4304 const payload_ptr = try func.buildPointerOffset(err_union, @as(u32, @intCast(errUnionPayloadOffset(pl_ty, mod))), .new);
4347 const payload_ptr = try func.buildPointerOffset(err_union, @as(u32, @intCast(errUnionPayloadOffset(pl_ty, pt))), .new);
43054348 try func.store(payload_ptr, operand, pl_ty, 0);
43064349
43074350 // ensure we also write '0' to the error part, so any present stack value gets overwritten by it.
43084351 try func.emitWValue(err_union);
43094352 try func.addImm32(0);
4310 const err_val_offset = @as(u32, @intCast(errUnionErrorOffset(pl_ty, mod)));
4353 const err_val_offset: u32 = @intCast(errUnionErrorOffset(pl_ty, pt));
43114354 try func.addMemArg(.i32_store16, .{
43124355 .offset = err_union.offset() + err_val_offset,
43134356 .alignment = 2,
......@@ -4318,7 +4361,8 @@ fn airWrapErrUnionPayload(func: *CodeGen, inst: Air.Inst.Index) InnerError!void
43184361}
43194362
43204363fn airWrapErrUnionErr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4321 const mod = func.bin_file.base.comp.module.?;
4364 const pt = func.pt;
4365 const mod = pt.zcu;
43224366 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
43234367
43244368 const operand = try func.resolveInst(ty_op.operand);
......@@ -4326,17 +4370,17 @@ fn airWrapErrUnionErr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
43264370 const pl_ty = err_ty.errorUnionPayload(mod);
43274371
43284372 const result = result: {
4329 if (!pl_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4373 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) {
43304374 break :result func.reuseOperand(ty_op.operand, operand);
43314375 }
43324376
43334377 const err_union = try func.allocStack(err_ty);
43344378 // store error value
4335 try func.store(err_union, operand, Type.anyerror, @as(u32, @intCast(errUnionErrorOffset(pl_ty, mod))));
4379 try func.store(err_union, operand, Type.anyerror, @intCast(errUnionErrorOffset(pl_ty, pt)));
43364380
43374381 // write 'undefined' to the payload
4338 const payload_ptr = try func.buildPointerOffset(err_union, @as(u32, @intCast(errUnionPayloadOffset(pl_ty, mod))), .new);
4339 const len = @as(u32, @intCast(err_ty.errorUnionPayload(mod).abiSize(mod)));
4382 const payload_ptr = try func.buildPointerOffset(err_union, @as(u32, @intCast(errUnionPayloadOffset(pl_ty, pt))), .new);
4383 const len = @as(u32, @intCast(err_ty.errorUnionPayload(mod).abiSize(pt)));
43404384 try func.memset(Type.u8, payload_ptr, .{ .imm32 = len }, .{ .imm32 = 0xaa });
43414385
43424386 break :result err_union;
......@@ -4350,16 +4394,17 @@ fn airIntcast(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
43504394 const ty = ty_op.ty.toType();
43514395 const operand = try func.resolveInst(ty_op.operand);
43524396 const operand_ty = func.typeOf(ty_op.operand);
4353 const mod = func.bin_file.base.comp.module.?;
4397 const pt = func.pt;
4398 const mod = pt.zcu;
43544399 if (ty.zigTypeTag(mod) == .Vector or operand_ty.zigTypeTag(mod) == .Vector) {
43554400 return func.fail("todo Wasm intcast for vectors", .{});
43564401 }
4357 if (ty.abiSize(mod) > 16 or operand_ty.abiSize(mod) > 16) {
4402 if (ty.abiSize(pt) > 16 or operand_ty.abiSize(pt) > 16) {
43584403 return func.fail("todo Wasm intcast for bitsize > 128", .{});
43594404 }
43604405
4361 const op_bits = toWasmBits(@as(u16, @intCast(operand_ty.bitSize(mod)))).?;
4362 const wanted_bits = toWasmBits(@as(u16, @intCast(ty.bitSize(mod)))).?;
4406 const op_bits = toWasmBits(@intCast(operand_ty.bitSize(pt))).?;
4407 const wanted_bits = toWasmBits(@intCast(ty.bitSize(pt))).?;
43634408 const result = if (op_bits == wanted_bits)
43644409 func.reuseOperand(ty_op.operand, operand)
43654410 else
......@@ -4373,9 +4418,10 @@ fn airIntcast(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
43734418/// Asserts type's bitsize <= 128
43744419/// NOTE: May leave the result on the top of the stack.
43754420fn intcast(func: *CodeGen, operand: WValue, given: Type, wanted: Type) InnerError!WValue {
4376 const mod = func.bin_file.base.comp.module.?;
4377 const given_bitsize = @as(u16, @intCast(given.bitSize(mod)));
4378 const wanted_bitsize = @as(u16, @intCast(wanted.bitSize(mod)));
4421 const pt = func.pt;
4422 const mod = pt.zcu;
4423 const given_bitsize = @as(u16, @intCast(given.bitSize(pt)));
4424 const wanted_bitsize = @as(u16, @intCast(wanted.bitSize(pt)));
43794425 assert(given_bitsize <= 128);
43804426 assert(wanted_bitsize <= 128);
43814427
......@@ -4422,7 +4468,8 @@ fn intcast(func: *CodeGen, operand: WValue, given: Type, wanted: Type) InnerErro
44224468}
44234469
44244470fn airIsNull(func: *CodeGen, inst: Air.Inst.Index, opcode: wasm.Opcode, op_kind: enum { value, ptr }) InnerError!void {
4425 const mod = func.bin_file.base.comp.module.?;
4471 const pt = func.pt;
4472 const mod = pt.zcu;
44264473 const un_op = func.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
44274474 const operand = try func.resolveInst(un_op);
44284475
......@@ -4436,15 +4483,16 @@ fn airIsNull(func: *CodeGen, inst: Air.Inst.Index, opcode: wasm.Opcode, op_kind:
44364483/// For a given type and operand, checks if it's considered `null`.
44374484/// NOTE: Leaves the result on the stack
44384485fn isNull(func: *CodeGen, operand: WValue, optional_ty: Type, opcode: wasm.Opcode) InnerError!WValue {
4439 const mod = func.bin_file.base.comp.module.?;
4486 const pt = func.pt;
4487 const mod = pt.zcu;
44404488 try func.emitWValue(operand);
44414489 const payload_ty = optional_ty.optionalChild(mod);
44424490 if (!optional_ty.optionalReprIsPayload(mod)) {
44434491 // When payload is zero-bits, we can treat operand as a value, rather than
44444492 // a pointer to the stack value
4445 if (payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4446 const offset = std.math.cast(u32, payload_ty.abiSize(mod)) orelse {
4447 return func.fail("Optional type {} too big to fit into stack frame", .{optional_ty.fmt(mod)});
4493 if (payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
4494 const offset = std.math.cast(u32, payload_ty.abiSize(pt)) orelse {
4495 return func.fail("Optional type {} too big to fit into stack frame", .{optional_ty.fmt(pt)});
44484496 };
44494497 try func.addMemArg(.i32_load8_u, .{ .offset = operand.offset() + offset, .alignment = 1 });
44504498 }
......@@ -4464,11 +4512,12 @@ fn isNull(func: *CodeGen, operand: WValue, optional_ty: Type, opcode: wasm.Opcod
44644512}
44654513
44664514fn airOptionalPayload(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4467 const mod = func.bin_file.base.comp.module.?;
4515 const pt = func.pt;
4516 const mod = pt.zcu;
44684517 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
44694518 const opt_ty = func.typeOf(ty_op.operand);
44704519 const payload_ty = func.typeOfIndex(inst);
4471 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4520 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
44724521 return func.finishAir(inst, .none, &.{ty_op.operand});
44734522 }
44744523
......@@ -4476,7 +4525,7 @@ fn airOptionalPayload(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
44764525 const operand = try func.resolveInst(ty_op.operand);
44774526 if (opt_ty.optionalReprIsPayload(mod)) break :result func.reuseOperand(ty_op.operand, operand);
44784527
4479 if (isByRef(payload_ty, mod)) {
4528 if (isByRef(payload_ty, pt)) {
44804529 break :result try func.buildPointerOffset(operand, 0, .new);
44814530 }
44824531
......@@ -4487,14 +4536,15 @@ fn airOptionalPayload(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
44874536}
44884537
44894538fn airOptionalPayloadPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4490 const mod = func.bin_file.base.comp.module.?;
4539 const pt = func.pt;
4540 const mod = pt.zcu;
44914541 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
44924542 const operand = try func.resolveInst(ty_op.operand);
44934543 const opt_ty = func.typeOf(ty_op.operand).childType(mod);
44944544
44954545 const result = result: {
44964546 const payload_ty = opt_ty.optionalChild(mod);
4497 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod) or opt_ty.optionalReprIsPayload(mod)) {
4547 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt) or opt_ty.optionalReprIsPayload(mod)) {
44984548 break :result func.reuseOperand(ty_op.operand, operand);
44994549 }
45004550
......@@ -4504,12 +4554,13 @@ fn airOptionalPayloadPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
45044554}
45054555
45064556fn airOptionalPayloadPtrSet(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4507 const mod = func.bin_file.base.comp.module.?;
4557 const pt = func.pt;
4558 const mod = pt.zcu;
45084559 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
45094560 const operand = try func.resolveInst(ty_op.operand);
45104561 const opt_ty = func.typeOf(ty_op.operand).childType(mod);
45114562 const payload_ty = opt_ty.optionalChild(mod);
4512 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4563 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
45134564 return func.fail("TODO: Implement OptionalPayloadPtrSet for optional with zero-sized type {}", .{payload_ty.fmtDebug()});
45144565 }
45154566
......@@ -4517,8 +4568,8 @@ fn airOptionalPayloadPtrSet(func: *CodeGen, inst: Air.Inst.Index) InnerError!voi
45174568 return func.finishAir(inst, operand, &.{ty_op.operand});
45184569 }
45194570
4520 const offset = std.math.cast(u32, payload_ty.abiSize(mod)) orelse {
4521 return func.fail("Optional type {} too big to fit into stack frame", .{opt_ty.fmt(mod)});
4571 const offset = std.math.cast(u32, payload_ty.abiSize(pt)) orelse {
4572 return func.fail("Optional type {} too big to fit into stack frame", .{opt_ty.fmt(pt)});
45224573 };
45234574
45244575 try func.emitWValue(operand);
......@@ -4532,10 +4583,11 @@ fn airOptionalPayloadPtrSet(func: *CodeGen, inst: Air.Inst.Index) InnerError!voi
45324583fn airWrapOptional(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
45334584 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
45344585 const payload_ty = func.typeOf(ty_op.operand);
4535 const mod = func.bin_file.base.comp.module.?;
4586 const pt = func.pt;
4587 const mod = pt.zcu;
45364588
45374589 const result = result: {
4538 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4590 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
45394591 const non_null_bit = try func.allocStack(Type.u1);
45404592 try func.emitWValue(non_null_bit);
45414593 try func.addImm32(1);
......@@ -4548,8 +4600,8 @@ fn airWrapOptional(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
45484600 if (op_ty.optionalReprIsPayload(mod)) {
45494601 break :result func.reuseOperand(ty_op.operand, operand);
45504602 }
4551 const offset = std.math.cast(u32, payload_ty.abiSize(mod)) orelse {
4552 return func.fail("Optional type {} too big to fit into stack frame", .{op_ty.fmt(mod)});
4603 const offset = std.math.cast(u32, payload_ty.abiSize(pt)) orelse {
4604 return func.fail("Optional type {} too big to fit into stack frame", .{op_ty.fmt(pt)});
45534605 };
45544606
45554607 // Create optional type, set the non-null bit, and store the operand inside the optional type
......@@ -4589,14 +4641,15 @@ fn airSliceLen(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
45894641}
45904642
45914643fn airSliceElemVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4592 const mod = func.bin_file.base.comp.module.?;
4644 const pt = func.pt;
4645 const mod = pt.zcu;
45934646 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
45944647
45954648 const slice_ty = func.typeOf(bin_op.lhs);
45964649 const slice = try func.resolveInst(bin_op.lhs);
45974650 const index = try func.resolveInst(bin_op.rhs);
45984651 const elem_ty = slice_ty.childType(mod);
4599 const elem_size = elem_ty.abiSize(mod);
4652 const elem_size = elem_ty.abiSize(pt);
46004653
46014654 // load pointer onto stack
46024655 _ = try func.load(slice, Type.usize, 0);
......@@ -4610,7 +4663,7 @@ fn airSliceElemVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
46104663 const result_ptr = try func.allocLocal(Type.usize);
46114664 try func.addLabel(.local_set, result_ptr.local.value);
46124665
4613 const result = if (!isByRef(elem_ty, mod)) result: {
4666 const result = if (!isByRef(elem_ty, pt)) result: {
46144667 const elem_val = try func.load(result_ptr, elem_ty, 0);
46154668 break :result try elem_val.toLocal(func, elem_ty);
46164669 } else result_ptr;
......@@ -4619,12 +4672,13 @@ fn airSliceElemVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
46194672}
46204673
46214674fn airSliceElemPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4622 const mod = func.bin_file.base.comp.module.?;
4675 const pt = func.pt;
4676 const mod = pt.zcu;
46234677 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
46244678 const bin_op = func.air.extraData(Air.Bin, ty_pl.payload).data;
46254679
46264680 const elem_ty = ty_pl.ty.toType().childType(mod);
4627 const elem_size = elem_ty.abiSize(mod);
4681 const elem_size = elem_ty.abiSize(pt);
46284682
46294683 const slice = try func.resolveInst(bin_op.lhs);
46304684 const index = try func.resolveInst(bin_op.rhs);
......@@ -4672,14 +4726,14 @@ fn airTrunc(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
46724726/// Truncates a given operand to a given type, discarding any overflown bits.
46734727/// NOTE: Resulting value is left on the stack.
46744728fn trunc(func: *CodeGen, operand: WValue, wanted_ty: Type, given_ty: Type) InnerError!WValue {
4675 const mod = func.bin_file.base.comp.module.?;
4676 const given_bits = @as(u16, @intCast(given_ty.bitSize(mod)));
4729 const pt = func.pt;
4730 const given_bits = @as(u16, @intCast(given_ty.bitSize(pt)));
46774731 if (toWasmBits(given_bits) == null) {
46784732 return func.fail("TODO: Implement wasm integer truncation for integer bitsize: {d}", .{given_bits});
46794733 }
46804734
46814735 var result = try func.intcast(operand, given_ty, wanted_ty);
4682 const wanted_bits = @as(u16, @intCast(wanted_ty.bitSize(mod)));
4736 const wanted_bits = @as(u16, @intCast(wanted_ty.bitSize(pt)));
46834737 const wasm_bits = toWasmBits(wanted_bits).?;
46844738 if (wasm_bits != wanted_bits) {
46854739 result = try func.wrapOperand(result, wanted_ty);
......@@ -4696,7 +4750,8 @@ fn airIntFromBool(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
46964750}
46974751
46984752fn airArrayToSlice(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4699 const mod = func.bin_file.base.comp.module.?;
4753 const pt = func.pt;
4754 const mod = pt.zcu;
47004755 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
47014756
47024757 const operand = try func.resolveInst(ty_op.operand);
......@@ -4707,7 +4762,7 @@ fn airArrayToSlice(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
47074762 const slice_local = try func.allocStack(slice_ty);
47084763
47094764 // store the array ptr in the slice
4710 if (array_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4765 if (array_ty.hasRuntimeBitsIgnoreComptime(pt)) {
47114766 try func.store(slice_local, operand, Type.usize, 0);
47124767 }
47134768
......@@ -4719,7 +4774,8 @@ fn airArrayToSlice(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
47194774}
47204775
47214776fn airIntFromPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4722 const mod = func.bin_file.base.comp.module.?;
4777 const pt = func.pt;
4778 const mod = pt.zcu;
47234779 const un_op = func.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
47244780 const operand = try func.resolveInst(un_op);
47254781 const ptr_ty = func.typeOf(un_op);
......@@ -4734,14 +4790,15 @@ fn airIntFromPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
47344790}
47354791
47364792fn airPtrElemVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4737 const mod = func.bin_file.base.comp.module.?;
4793 const pt = func.pt;
4794 const mod = pt.zcu;
47384795 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
47394796
47404797 const ptr_ty = func.typeOf(bin_op.lhs);
47414798 const ptr = try func.resolveInst(bin_op.lhs);
47424799 const index = try func.resolveInst(bin_op.rhs);
47434800 const elem_ty = ptr_ty.childType(mod);
4744 const elem_size = elem_ty.abiSize(mod);
4801 const elem_size = elem_ty.abiSize(pt);
47454802
47464803 // load pointer onto the stack
47474804 if (ptr_ty.isSlice(mod)) {
......@@ -4759,7 +4816,7 @@ fn airPtrElemVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
47594816 const elem_result = val: {
47604817 var result = try func.allocLocal(Type.usize);
47614818 try func.addLabel(.local_set, result.local.value);
4762 if (isByRef(elem_ty, mod)) {
4819 if (isByRef(elem_ty, pt)) {
47634820 break :val result;
47644821 }
47654822 defer result.free(func); // only free if it's not returned like above
......@@ -4771,13 +4828,14 @@ fn airPtrElemVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
47714828}
47724829
47734830fn airPtrElemPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4774 const mod = func.bin_file.base.comp.module.?;
4831 const pt = func.pt;
4832 const mod = pt.zcu;
47754833 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
47764834 const bin_op = func.air.extraData(Air.Bin, ty_pl.payload).data;
47774835
47784836 const ptr_ty = func.typeOf(bin_op.lhs);
47794837 const elem_ty = ty_pl.ty.toType().childType(mod);
4780 const elem_size = elem_ty.abiSize(mod);
4838 const elem_size = elem_ty.abiSize(pt);
47814839
47824840 const ptr = try func.resolveInst(bin_op.lhs);
47834841 const index = try func.resolveInst(bin_op.rhs);
......@@ -4801,7 +4859,8 @@ fn airPtrElemPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
48014859}
48024860
48034861fn airPtrBinOp(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
4804 const mod = func.bin_file.base.comp.module.?;
4862 const pt = func.pt;
4863 const mod = pt.zcu;
48054864 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
48064865 const bin_op = func.air.extraData(Air.Bin, ty_pl.payload).data;
48074866
......@@ -4813,13 +4872,13 @@ fn airPtrBinOp(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
48134872 else => ptr_ty.childType(mod),
48144873 };
48154874
4816 const valtype = typeToValtype(Type.usize, mod);
4875 const valtype = typeToValtype(Type.usize, pt);
48174876 const mul_opcode = buildOpcode(.{ .valtype1 = valtype, .op = .mul });
48184877 const bin_opcode = buildOpcode(.{ .valtype1 = valtype, .op = op });
48194878
48204879 try func.lowerToStack(ptr);
48214880 try func.emitWValue(offset);
4822 try func.addImm32(@intCast(pointee_ty.abiSize(mod)));
4881 try func.addImm32(@intCast(pointee_ty.abiSize(pt)));
48234882 try func.addTag(Mir.Inst.Tag.fromOpcode(mul_opcode));
48244883 try func.addTag(Mir.Inst.Tag.fromOpcode(bin_opcode));
48254884
......@@ -4829,7 +4888,8 @@ fn airPtrBinOp(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
48294888}
48304889
48314890fn airMemset(func: *CodeGen, inst: Air.Inst.Index, safety: bool) InnerError!void {
4832 const mod = func.bin_file.base.comp.module.?;
4891 const pt = func.pt;
4892 const mod = pt.zcu;
48334893 if (safety) {
48344894 // TODO if the value is undef, write 0xaa bytes to dest
48354895 } else {
......@@ -4862,8 +4922,8 @@ fn airMemset(func: *CodeGen, inst: Air.Inst.Index, safety: bool) InnerError!void
48624922/// this to wasm's memset instruction. When the feature is not present,
48634923/// we implement it manually.
48644924fn memset(func: *CodeGen, elem_ty: Type, ptr: WValue, len: WValue, value: WValue) InnerError!void {
4865 const mod = func.bin_file.base.comp.module.?;
4866 const abi_size = @as(u32, @intCast(elem_ty.abiSize(mod)));
4925 const pt = func.pt;
4926 const abi_size = @as(u32, @intCast(elem_ty.abiSize(pt)));
48674927
48684928 // When bulk_memory is enabled, we lower it to wasm's memset instruction.
48694929 // If not, we lower it ourselves.
......@@ -4951,16 +5011,17 @@ fn memset(func: *CodeGen, elem_ty: Type, ptr: WValue, len: WValue, value: WValue
49515011}
49525012
49535013fn airArrayElemVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
4954 const mod = func.bin_file.base.comp.module.?;
5014 const pt = func.pt;
5015 const mod = pt.zcu;
49555016 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
49565017
49575018 const array_ty = func.typeOf(bin_op.lhs);
49585019 const array = try func.resolveInst(bin_op.lhs);
49595020 const index = try func.resolveInst(bin_op.rhs);
49605021 const elem_ty = array_ty.childType(mod);
4961 const elem_size = elem_ty.abiSize(mod);
5022 const elem_size = elem_ty.abiSize(pt);
49625023
4963 if (isByRef(array_ty, mod)) {
5024 if (isByRef(array_ty, pt)) {
49645025 try func.lowerToStack(array);
49655026 try func.emitWValue(index);
49665027 try func.addImm32(@intCast(elem_size));
......@@ -4971,7 +5032,7 @@ fn airArrayElemVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
49715032
49725033 switch (index) {
49735034 inline .imm32, .imm64 => |lane| {
4974 const opcode: wasm.SimdOpcode = switch (elem_ty.bitSize(mod)) {
5035 const opcode: wasm.SimdOpcode = switch (elem_ty.bitSize(pt)) {
49755036 8 => if (elem_ty.isSignedInt(mod)) .i8x16_extract_lane_s else .i8x16_extract_lane_u,
49765037 16 => if (elem_ty.isSignedInt(mod)) .i16x8_extract_lane_s else .i16x8_extract_lane_u,
49775038 32 => if (elem_ty.isInt(mod)) .i32x4_extract_lane else .f32x4_extract_lane,
......@@ -5007,7 +5068,7 @@ fn airArrayElemVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
50075068 var result = try func.allocLocal(Type.usize);
50085069 try func.addLabel(.local_set, result.local.value);
50095070
5010 if (isByRef(elem_ty, mod)) {
5071 if (isByRef(elem_ty, pt)) {
50115072 break :val result;
50125073 }
50135074 defer result.free(func); // only free if no longer needed and not returned like above
......@@ -5020,7 +5081,8 @@ fn airArrayElemVal(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
50205081}
50215082
50225083fn airIntFromFloat(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5023 const mod = func.bin_file.base.comp.module.?;
5084 const pt = func.pt;
5085 const mod = pt.zcu;
50245086 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
50255087
50265088 const operand = try func.resolveInst(ty_op.operand);
......@@ -5054,8 +5116,8 @@ fn airIntFromFloat(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
50545116 try func.emitWValue(operand);
50555117 const op = buildOpcode(.{
50565118 .op = .trunc,
5057 .valtype1 = typeToValtype(dest_ty, mod),
5058 .valtype2 = typeToValtype(op_ty, mod),
5119 .valtype1 = typeToValtype(dest_ty, pt),
5120 .valtype2 = typeToValtype(op_ty, pt),
50595121 .signedness = dest_info.signedness,
50605122 });
50615123 try func.addTag(Mir.Inst.Tag.fromOpcode(op));
......@@ -5065,7 +5127,8 @@ fn airIntFromFloat(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
50655127}
50665128
50675129fn airFloatFromInt(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5068 const mod = func.bin_file.base.comp.module.?;
5130 const pt = func.pt;
5131 const mod = pt.zcu;
50695132 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
50705133
50715134 const operand = try func.resolveInst(ty_op.operand);
......@@ -5099,8 +5162,8 @@ fn airFloatFromInt(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
50995162 try func.emitWValue(operand);
51005163 const op = buildOpcode(.{
51015164 .op = .convert,
5102 .valtype1 = typeToValtype(dest_ty, mod),
5103 .valtype2 = typeToValtype(op_ty, mod),
5165 .valtype1 = typeToValtype(dest_ty, pt),
5166 .valtype2 = typeToValtype(op_ty, pt),
51045167 .signedness = op_info.signedness,
51055168 });
51065169 try func.addTag(Mir.Inst.Tag.fromOpcode(op));
......@@ -5111,19 +5174,20 @@ fn airFloatFromInt(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
51115174}
51125175
51135176fn airSplat(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5114 const mod = func.bin_file.base.comp.module.?;
5177 const pt = func.pt;
5178 const mod = pt.zcu;
51155179 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
51165180 const operand = try func.resolveInst(ty_op.operand);
51175181 const ty = func.typeOfIndex(inst);
51185182 const elem_ty = ty.childType(mod);
51195183
5120 if (determineSimdStoreStrategy(ty, mod) == .direct) blk: {
5184 if (determineSimdStoreStrategy(ty, pt) == .direct) blk: {
51215185 switch (operand) {
51225186 // when the operand lives in the linear memory section, we can directly
51235187 // load and splat the value at once. Meaning we do not first have to load
51245188 // the scalar value onto the stack.
51255189 .stack_offset, .memory, .memory_offset => {
5126 const opcode = switch (elem_ty.bitSize(mod)) {
5190 const opcode = switch (elem_ty.bitSize(pt)) {
51275191 8 => std.wasm.simdOpcode(.v128_load8_splat),
51285192 16 => std.wasm.simdOpcode(.v128_load16_splat),
51295193 32 => std.wasm.simdOpcode(.v128_load32_splat),
......@@ -5138,14 +5202,14 @@ fn airSplat(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
51385202 try func.mir_extra.appendSlice(func.gpa, &[_]u32{
51395203 opcode,
51405204 operand.offset(),
5141 @intCast(elem_ty.abiAlignment(mod).toByteUnits().?),
5205 @intCast(elem_ty.abiAlignment(pt).toByteUnits().?),
51425206 });
51435207 try func.addInst(.{ .tag = .simd_prefix, .data = .{ .payload = extra_index } });
51445208 try func.addLabel(.local_set, result.local.value);
51455209 return func.finishAir(inst, result, &.{ty_op.operand});
51465210 },
51475211 .local => {
5148 const opcode = switch (elem_ty.bitSize(mod)) {
5212 const opcode = switch (elem_ty.bitSize(pt)) {
51495213 8 => std.wasm.simdOpcode(.i8x16_splat),
51505214 16 => std.wasm.simdOpcode(.i16x8_splat),
51515215 32 => if (elem_ty.isInt(mod)) std.wasm.simdOpcode(.i32x4_splat) else std.wasm.simdOpcode(.f32x4_splat),
......@@ -5163,14 +5227,14 @@ fn airSplat(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
51635227 else => unreachable,
51645228 }
51655229 }
5166 const elem_size = elem_ty.bitSize(mod);
5230 const elem_size = elem_ty.bitSize(pt);
51675231 const vector_len = @as(usize, @intCast(ty.vectorLen(mod)));
51685232 if ((!std.math.isPowerOfTwo(elem_size) or elem_size % 8 != 0) and vector_len > 1) {
51695233 return func.fail("TODO: WebAssembly `@splat` for arbitrary element bitsize {d}", .{elem_size});
51705234 }
51715235
51725236 const result = try func.allocStack(ty);
5173 const elem_byte_size = @as(u32, @intCast(elem_ty.abiSize(mod)));
5237 const elem_byte_size = @as(u32, @intCast(elem_ty.abiSize(pt)));
51745238 var index: usize = 0;
51755239 var offset: u32 = 0;
51765240 while (index < vector_len) : (index += 1) {
......@@ -5190,7 +5254,8 @@ fn airSelect(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
51905254}
51915255
51925256fn airShuffle(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5193 const mod = func.bin_file.base.comp.module.?;
5257 const pt = func.pt;
5258 const mod = pt.zcu;
51945259 const inst_ty = func.typeOfIndex(inst);
51955260 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
51965261 const extra = func.air.extraData(Air.Shuffle, ty_pl.payload).data;
......@@ -5201,14 +5266,14 @@ fn airShuffle(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
52015266 const mask_len = extra.mask_len;
52025267
52035268 const child_ty = inst_ty.childType(mod);
5204 const elem_size = child_ty.abiSize(mod);
5269 const elem_size = child_ty.abiSize(pt);
52055270
52065271 // TODO: One of them could be by ref; handle in loop
5207 if (isByRef(func.typeOf(extra.a), mod) or isByRef(inst_ty, mod)) {
5272 if (isByRef(func.typeOf(extra.a), pt) or isByRef(inst_ty, pt)) {
52085273 const result = try func.allocStack(inst_ty);
52095274
52105275 for (0..mask_len) |index| {
5211 const value = (try mask.elemValue(mod, index)).toSignedInt(mod);
5276 const value = (try mask.elemValue(pt, index)).toSignedInt(pt);
52125277
52135278 try func.emitWValue(result);
52145279
......@@ -5228,7 +5293,7 @@ fn airShuffle(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
52285293
52295294 var lanes = mem.asBytes(operands[1..]);
52305295 for (0..@as(usize, @intCast(mask_len))) |index| {
5231 const mask_elem = (try mask.elemValue(mod, index)).toSignedInt(mod);
5296 const mask_elem = (try mask.elemValue(pt, index)).toSignedInt(pt);
52325297 const base_index = if (mask_elem >= 0)
52335298 @as(u8, @intCast(@as(i64, @intCast(elem_size)) * mask_elem))
52345299 else
......@@ -5259,7 +5324,8 @@ fn airReduce(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
52595324}
52605325
52615326fn airAggregateInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5262 const mod = func.bin_file.base.comp.module.?;
5327 const pt = func.pt;
5328 const mod = pt.zcu;
52635329 const ip = &mod.intern_pool;
52645330 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
52655331 const result_ty = func.typeOfIndex(inst);
......@@ -5271,7 +5337,7 @@ fn airAggregateInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
52715337 .Array => {
52725338 const result = try func.allocStack(result_ty);
52735339 const elem_ty = result_ty.childType(mod);
5274 const elem_size = @as(u32, @intCast(elem_ty.abiSize(mod)));
5340 const elem_size = @as(u32, @intCast(elem_ty.abiSize(pt)));
52755341 const sentinel = if (result_ty.sentinel(mod)) |sent| blk: {
52765342 break :blk try func.lowerConstant(sent, elem_ty);
52775343 } else null;
......@@ -5279,7 +5345,7 @@ fn airAggregateInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
52795345 // When the element type is by reference, we must copy the entire
52805346 // value. It is therefore safer to move the offset pointer and store
52815347 // each value individually, instead of using store offsets.
5282 if (isByRef(elem_ty, mod)) {
5348 if (isByRef(elem_ty, pt)) {
52835349 // copy stack pointer into a temporary local, which is
52845350 // moved for each element to store each value in the right position.
52855351 const offset = try func.buildPointerOffset(result, 0, .new);
......@@ -5309,7 +5375,7 @@ fn airAggregateInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
53095375 },
53105376 .Struct => switch (result_ty.containerLayout(mod)) {
53115377 .@"packed" => {
5312 if (isByRef(result_ty, mod)) {
5378 if (isByRef(result_ty, pt)) {
53135379 return func.fail("TODO: airAggregateInit for packed structs larger than 64 bits", .{});
53145380 }
53155381 const packed_struct = mod.typeToPackedStruct(result_ty).?;
......@@ -5318,7 +5384,7 @@ fn airAggregateInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
53185384
53195385 // ensure the result is zero'd
53205386 const result = try func.allocLocal(backing_type);
5321 if (backing_type.bitSize(mod) <= 32)
5387 if (backing_type.bitSize(pt) <= 32)
53225388 try func.addImm32(0)
53235389 else
53245390 try func.addImm64(0);
......@@ -5327,16 +5393,16 @@ fn airAggregateInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
53275393 var current_bit: u16 = 0;
53285394 for (elements, 0..) |elem, elem_index| {
53295395 const field_ty = Type.fromInterned(field_types.get(ip)[elem_index]);
5330 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
5396 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
53315397
5332 const shift_val = if (backing_type.bitSize(mod) <= 32)
5398 const shift_val = if (backing_type.bitSize(pt) <= 32)
53335399 WValue{ .imm32 = current_bit }
53345400 else
53355401 WValue{ .imm64 = current_bit };
53365402
53375403 const value = try func.resolveInst(elem);
5338 const value_bit_size: u16 = @intCast(field_ty.bitSize(mod));
5339 const int_ty = try mod.intType(.unsigned, value_bit_size);
5404 const value_bit_size: u16 = @intCast(field_ty.bitSize(pt));
5405 const int_ty = try pt.intType(.unsigned, value_bit_size);
53405406
53415407 // load our current result on stack so we can perform all transformations
53425408 // using only stack values. Saving the cost of loads and stores.
......@@ -5359,10 +5425,10 @@ fn airAggregateInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
53595425 const offset = try func.buildPointerOffset(result, 0, .new); // pointer to offset
53605426 var prev_field_offset: u64 = 0;
53615427 for (elements, 0..) |elem, elem_index| {
5362 if ((try result_ty.structFieldValueComptime(mod, elem_index)) != null) continue;
5428 if (try result_ty.structFieldValueComptime(pt, elem_index) != null) continue;
53635429
53645430 const elem_ty = result_ty.structFieldType(elem_index, mod);
5365 const field_offset = result_ty.structFieldOffset(elem_index, mod);
5431 const field_offset = result_ty.structFieldOffset(elem_index, pt);
53665432 _ = try func.buildPointerOffset(offset, @intCast(field_offset - prev_field_offset), .modify);
53675433 prev_field_offset = field_offset;
53685434
......@@ -5389,14 +5455,15 @@ fn airAggregateInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
53895455}
53905456
53915457fn airUnionInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5392 const mod = func.bin_file.base.comp.module.?;
5458 const pt = func.pt;
5459 const mod = pt.zcu;
53935460 const ip = &mod.intern_pool;
53945461 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
53955462 const extra = func.air.extraData(Air.UnionInit, ty_pl.payload).data;
53965463
53975464 const result = result: {
53985465 const union_ty = func.typeOfIndex(inst);
5399 const layout = union_ty.unionGetLayout(mod);
5466 const layout = union_ty.unionGetLayout(pt);
54005467 const union_obj = mod.typeToUnion(union_ty).?;
54015468 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[extra.field_index]);
54025469 const field_name = union_obj.loadTagType(ip).names.get(ip)[extra.field_index];
......@@ -5404,22 +5471,22 @@ fn airUnionInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
54045471 const tag_int = blk: {
54055472 const tag_ty = union_ty.unionTagTypeHypothetical(mod);
54065473 const enum_field_index = tag_ty.enumFieldIndex(field_name, mod).?;
5407 const tag_val = try mod.enumValueFieldIndex(tag_ty, enum_field_index);
5474 const tag_val = try pt.enumValueFieldIndex(tag_ty, enum_field_index);
54085475 break :blk try func.lowerConstant(tag_val, tag_ty);
54095476 };
54105477 if (layout.payload_size == 0) {
54115478 if (layout.tag_size == 0) {
54125479 break :result WValue{ .none = {} };
54135480 }
5414 assert(!isByRef(union_ty, mod));
5481 assert(!isByRef(union_ty, pt));
54155482 break :result tag_int;
54165483 }
54175484
5418 if (isByRef(union_ty, mod)) {
5485 if (isByRef(union_ty, pt)) {
54195486 const result_ptr = try func.allocStack(union_ty);
54205487 const payload = try func.resolveInst(extra.init);
54215488 if (layout.tag_align.compare(.gte, layout.payload_align)) {
5422 if (isByRef(field_ty, mod)) {
5489 if (isByRef(field_ty, pt)) {
54235490 const payload_ptr = try func.buildPointerOffset(result_ptr, layout.tag_size, .new);
54245491 try func.store(payload_ptr, payload, field_ty, 0);
54255492 } else {
......@@ -5443,14 +5510,14 @@ fn airUnionInit(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
54435510 break :result result_ptr;
54445511 } else {
54455512 const operand = try func.resolveInst(extra.init);
5446 const union_int_type = try mod.intType(.unsigned, @as(u16, @intCast(union_ty.bitSize(mod))));
5513 const union_int_type = try pt.intType(.unsigned, @as(u16, @intCast(union_ty.bitSize(pt))));
54475514 if (field_ty.zigTypeTag(mod) == .Float) {
5448 const int_type = try mod.intType(.unsigned, @intCast(field_ty.bitSize(mod)));
5515 const int_type = try pt.intType(.unsigned, @intCast(field_ty.bitSize(pt)));
54495516 const bitcasted = try func.bitcast(field_ty, int_type, operand);
54505517 const casted = try func.trunc(bitcasted, int_type, union_int_type);
54515518 break :result try casted.toLocal(func, field_ty);
54525519 } else if (field_ty.isPtrAtRuntime(mod)) {
5453 const int_type = try mod.intType(.unsigned, @intCast(field_ty.bitSize(mod)));
5520 const int_type = try pt.intType(.unsigned, @intCast(field_ty.bitSize(pt)));
54545521 const casted = try func.intcast(operand, int_type, union_int_type);
54555522 break :result try casted.toLocal(func, field_ty);
54565523 }
......@@ -5488,8 +5555,9 @@ fn airWasmMemoryGrow(func: *CodeGen, inst: Air.Inst.Index) !void {
54885555}
54895556
54905557fn cmpOptionals(func: *CodeGen, lhs: WValue, rhs: WValue, operand_ty: Type, op: std.math.CompareOperator) InnerError!WValue {
5491 const mod = func.bin_file.base.comp.module.?;
5492 assert(operand_ty.hasRuntimeBitsIgnoreComptime(mod));
5558 const pt = func.pt;
5559 const mod = pt.zcu;
5560 assert(operand_ty.hasRuntimeBitsIgnoreComptime(pt));
54935561 assert(op == .eq or op == .neq);
54945562 const payload_ty = operand_ty.optionalChild(mod);
54955563
......@@ -5506,7 +5574,7 @@ fn cmpOptionals(func: *CodeGen, lhs: WValue, rhs: WValue, operand_ty: Type, op:
55065574
55075575 _ = try func.load(lhs, payload_ty, 0);
55085576 _ = try func.load(rhs, payload_ty, 0);
5509 const opcode = buildOpcode(.{ .op = .ne, .valtype1 = typeToValtype(payload_ty, mod) });
5577 const opcode = buildOpcode(.{ .op = .ne, .valtype1 = typeToValtype(payload_ty, pt) });
55105578 try func.addTag(Mir.Inst.Tag.fromOpcode(opcode));
55115579 try func.addLabel(.br_if, 0);
55125580
......@@ -5524,11 +5592,12 @@ fn cmpOptionals(func: *CodeGen, lhs: WValue, rhs: WValue, operand_ty: Type, op:
55245592/// NOTE: Leaves the result of the comparison on top of the stack.
55255593/// TODO: Lower this to compiler_rt call when bitsize > 128
55265594fn cmpBigInt(func: *CodeGen, lhs: WValue, rhs: WValue, operand_ty: Type, op: std.math.CompareOperator) InnerError!WValue {
5527 const mod = func.bin_file.base.comp.module.?;
5528 assert(operand_ty.abiSize(mod) >= 16);
5595 const pt = func.pt;
5596 const mod = pt.zcu;
5597 assert(operand_ty.abiSize(pt) >= 16);
55295598 assert(!(lhs != .stack and rhs == .stack));
5530 if (operand_ty.bitSize(mod) > 128) {
5531 return func.fail("TODO: Support cmpBigInt for integer bitsize: '{d}'", .{operand_ty.bitSize(mod)});
5599 if (operand_ty.bitSize(pt) > 128) {
5600 return func.fail("TODO: Support cmpBigInt for integer bitsize: '{d}'", .{operand_ty.bitSize(pt)});
55325601 }
55335602
55345603 var lhs_high_bit = try (try func.load(lhs, Type.u64, 0)).toLocal(func, Type.u64);
......@@ -5566,11 +5635,12 @@ fn cmpBigInt(func: *CodeGen, lhs: WValue, rhs: WValue, operand_ty: Type, op: std
55665635}
55675636
55685637fn airSetUnionTag(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5569 const mod = func.bin_file.base.comp.module.?;
5638 const pt = func.pt;
5639 const mod = pt.zcu;
55705640 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
55715641 const un_ty = func.typeOf(bin_op.lhs).childType(mod);
55725642 const tag_ty = func.typeOf(bin_op.rhs);
5573 const layout = un_ty.unionGetLayout(mod);
5643 const layout = un_ty.unionGetLayout(pt);
55745644 if (layout.tag_size == 0) return func.finishAir(inst, .none, &.{ bin_op.lhs, bin_op.rhs });
55755645
55765646 const union_ptr = try func.resolveInst(bin_op.lhs);
......@@ -5590,12 +5660,12 @@ fn airSetUnionTag(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
55905660}
55915661
55925662fn airGetUnionTag(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5593 const mod = func.bin_file.base.comp.module.?;
5663 const pt = func.pt;
55945664 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
55955665
55965666 const un_ty = func.typeOf(ty_op.operand);
55975667 const tag_ty = func.typeOfIndex(inst);
5598 const layout = un_ty.unionGetLayout(mod);
5668 const layout = un_ty.unionGetLayout(pt);
55995669 if (layout.tag_size == 0) return func.finishAir(inst, .none, &.{ty_op.operand});
56005670
56015671 const operand = try func.resolveInst(ty_op.operand);
......@@ -5695,7 +5765,8 @@ fn fptrunc(func: *CodeGen, operand: WValue, given: Type, wanted: Type) InnerErro
56955765}
56965766
56975767fn airErrUnionPayloadPtrSet(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5698 const mod = func.bin_file.base.comp.module.?;
5768 const pt = func.pt;
5769 const mod = pt.zcu;
56995770 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
57005771
57015772 const err_set_ty = func.typeOf(ty_op.operand).childType(mod);
......@@ -5707,27 +5778,28 @@ fn airErrUnionPayloadPtrSet(func: *CodeGen, inst: Air.Inst.Index) InnerError!voi
57075778 operand,
57085779 .{ .imm32 = 0 },
57095780 Type.anyerror,
5710 @as(u32, @intCast(errUnionErrorOffset(payload_ty, mod))),
5781 @intCast(errUnionErrorOffset(payload_ty, pt)),
57115782 );
57125783
57135784 const result = result: {
5714 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
5785 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
57155786 break :result func.reuseOperand(ty_op.operand, operand);
57165787 }
57175788
5718 break :result try func.buildPointerOffset(operand, @as(u32, @intCast(errUnionPayloadOffset(payload_ty, mod))), .new);
5789 break :result try func.buildPointerOffset(operand, @as(u32, @intCast(errUnionPayloadOffset(payload_ty, pt))), .new);
57195790 };
57205791 func.finishAir(inst, result, &.{ty_op.operand});
57215792}
57225793
57235794fn airFieldParentPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5724 const mod = func.bin_file.base.comp.module.?;
5795 const pt = func.pt;
5796 const mod = pt.zcu;
57255797 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
57265798 const extra = func.air.extraData(Air.FieldParentPtr, ty_pl.payload).data;
57275799
57285800 const field_ptr = try func.resolveInst(extra.field_ptr);
57295801 const parent_ty = ty_pl.ty.toType().childType(mod);
5730 const field_offset = parent_ty.structFieldOffset(extra.field_index, mod);
5802 const field_offset = parent_ty.structFieldOffset(extra.field_index, pt);
57315803
57325804 const result = if (field_offset != 0) result: {
57335805 const base = try func.buildPointerOffset(field_ptr, 0, .new);
......@@ -5742,7 +5814,8 @@ fn airFieldParentPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
57425814}
57435815
57445816fn sliceOrArrayPtr(func: *CodeGen, ptr: WValue, ptr_ty: Type) InnerError!WValue {
5745 const mod = func.bin_file.base.comp.module.?;
5817 const pt = func.pt;
5818 const mod = pt.zcu;
57465819 if (ptr_ty.isSlice(mod)) {
57475820 return func.slicePtr(ptr);
57485821 } else {
......@@ -5751,7 +5824,8 @@ fn sliceOrArrayPtr(func: *CodeGen, ptr: WValue, ptr_ty: Type) InnerError!WValue
57515824}
57525825
57535826fn airMemcpy(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5754 const mod = func.bin_file.base.comp.module.?;
5827 const pt = func.pt;
5828 const mod = pt.zcu;
57555829 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
57565830 const dst = try func.resolveInst(bin_op.lhs);
57575831 const dst_ty = func.typeOf(bin_op.lhs);
......@@ -5761,16 +5835,16 @@ fn airMemcpy(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
57615835 const len = switch (dst_ty.ptrSize(mod)) {
57625836 .Slice => blk: {
57635837 const slice_len = try func.sliceLen(dst);
5764 if (ptr_elem_ty.abiSize(mod) != 1) {
5838 if (ptr_elem_ty.abiSize(pt) != 1) {
57655839 try func.emitWValue(slice_len);
5766 try func.emitWValue(.{ .imm32 = @as(u32, @intCast(ptr_elem_ty.abiSize(mod))) });
5840 try func.emitWValue(.{ .imm32 = @as(u32, @intCast(ptr_elem_ty.abiSize(pt))) });
57675841 try func.addTag(.i32_mul);
57685842 try func.addLabel(.local_set, slice_len.local.value);
57695843 }
57705844 break :blk slice_len;
57715845 },
57725846 .One => @as(WValue, .{
5773 .imm32 = @as(u32, @intCast(ptr_elem_ty.arrayLen(mod) * ptr_elem_ty.childType(mod).abiSize(mod))),
5847 .imm32 = @as(u32, @intCast(ptr_elem_ty.arrayLen(mod) * ptr_elem_ty.childType(mod).abiSize(pt))),
57745848 }),
57755849 .C, .Many => unreachable,
57765850 };
......@@ -5791,7 +5865,8 @@ fn airRetAddr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
57915865}
57925866
57935867fn airPopcount(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5794 const mod = func.bin_file.base.comp.module.?;
5868 const pt = func.pt;
5869 const mod = pt.zcu;
57955870 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
57965871
57975872 const operand = try func.resolveInst(ty_op.operand);
......@@ -5812,14 +5887,14 @@ fn airPopcount(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
58125887 32 => {
58135888 try func.emitWValue(operand);
58145889 if (op_ty.isSignedInt(mod) and bits != wasm_bits) {
5815 _ = try func.wrapOperand(.stack, try mod.intType(.unsigned, bits));
5890 _ = try func.wrapOperand(.stack, try pt.intType(.unsigned, bits));
58165891 }
58175892 try func.addTag(.i32_popcnt);
58185893 },
58195894 64 => {
58205895 try func.emitWValue(operand);
58215896 if (op_ty.isSignedInt(mod) and bits != wasm_bits) {
5822 _ = try func.wrapOperand(.stack, try mod.intType(.unsigned, bits));
5897 _ = try func.wrapOperand(.stack, try pt.intType(.unsigned, bits));
58235898 }
58245899 try func.addTag(.i64_popcnt);
58255900 try func.addTag(.i32_wrap_i64);
......@@ -5830,7 +5905,7 @@ fn airPopcount(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
58305905 try func.addTag(.i64_popcnt);
58315906 _ = try func.load(operand, Type.u64, 8);
58325907 if (op_ty.isSignedInt(mod) and bits != wasm_bits) {
5833 _ = try func.wrapOperand(.stack, try mod.intType(.unsigned, bits - 64));
5908 _ = try func.wrapOperand(.stack, try pt.intType(.unsigned, bits - 64));
58345909 }
58355910 try func.addTag(.i64_popcnt);
58365911 try func.addTag(.i64_add);
......@@ -5845,7 +5920,8 @@ fn airPopcount(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
58455920}
58465921
58475922fn airBitReverse(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
5848 const mod = func.bin_file.base.comp.module.?;
5923 const pt = func.pt;
5924 const mod = pt.zcu;
58495925 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
58505926
58515927 const operand = try func.resolveInst(ty_op.operand);
......@@ -5956,10 +6032,10 @@ fn airErrorName(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
59566032 //
59576033 // As the names are global and the slice elements are constant, we do not have
59586034 // to make a copy of the ptr+value but can point towards them directly.
5959 const error_table_symbol = try func.bin_file.getErrorTableSymbol();
6035 const pt = func.pt;
6036 const error_table_symbol = try func.bin_file.getErrorTableSymbol(pt);
59606037 const name_ty = Type.slice_const_u8_sentinel_0;
5961 const mod = func.bin_file.base.comp.module.?;
5962 const abi_size = name_ty.abiSize(mod);
6038 const abi_size = name_ty.abiSize(pt);
59636039
59646040 const error_name_value: WValue = .{ .memory = error_table_symbol }; // emitting this will create a relocation
59656041 try func.emitWValue(error_name_value);
......@@ -5998,7 +6074,8 @@ fn airAddSubWithOverflow(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerErro
59986074 const lhs = try func.resolveInst(extra.lhs);
59996075 const rhs = try func.resolveInst(extra.rhs);
60006076 const lhs_ty = func.typeOf(extra.lhs);
6001 const mod = func.bin_file.base.comp.module.?;
6077 const pt = func.pt;
6078 const mod = pt.zcu;
60026079
60036080 if (lhs_ty.zigTypeTag(mod) == .Vector) {
60046081 return func.fail("TODO: Implement overflow arithmetic for vectors", .{});
......@@ -6044,14 +6121,15 @@ fn airAddSubWithOverflow(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerErro
60446121
60456122 const result_ptr = try func.allocStack(func.typeOfIndex(inst));
60466123 try func.store(result_ptr, result, lhs_ty, 0);
6047 const offset = @as(u32, @intCast(lhs_ty.abiSize(mod)));
6124 const offset = @as(u32, @intCast(lhs_ty.abiSize(pt)));
60486125 try func.store(result_ptr, overflow_local, Type.u1, offset);
60496126
60506127 func.finishAir(inst, result_ptr, &.{ extra.lhs, extra.rhs });
60516128}
60526129
60536130fn addSubWithOverflowBigInt(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, result_ty: Type, op: Op) InnerError!WValue {
6054 const mod = func.bin_file.base.comp.module.?;
6131 const pt = func.pt;
6132 const mod = pt.zcu;
60556133 assert(op == .add or op == .sub);
60566134 const int_info = ty.intInfo(mod);
60576135 const is_signed = int_info.signedness == .signed;
......@@ -6116,7 +6194,8 @@ fn addSubWithOverflowBigInt(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type,
61166194}
61176195
61186196fn airShlWithOverflow(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
6119 const mod = func.bin_file.base.comp.module.?;
6197 const pt = func.pt;
6198 const mod = pt.zcu;
61206199 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
61216200 const extra = func.air.extraData(Air.Bin, ty_pl.payload).data;
61226201
......@@ -6159,7 +6238,7 @@ fn airShlWithOverflow(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
61596238
61606239 const result_ptr = try func.allocStack(func.typeOfIndex(inst));
61616240 try func.store(result_ptr, result, lhs_ty, 0);
6162 const offset = @as(u32, @intCast(lhs_ty.abiSize(mod)));
6241 const offset = @as(u32, @intCast(lhs_ty.abiSize(pt)));
61636242 try func.store(result_ptr, overflow_local, Type.u1, offset);
61646243
61656244 func.finishAir(inst, result_ptr, &.{ extra.lhs, extra.rhs });
......@@ -6172,7 +6251,8 @@ fn airMulWithOverflow(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
61726251 const lhs = try func.resolveInst(extra.lhs);
61736252 const rhs = try func.resolveInst(extra.rhs);
61746253 const lhs_ty = func.typeOf(extra.lhs);
6175 const mod = func.bin_file.base.comp.module.?;
6254 const pt = func.pt;
6255 const mod = pt.zcu;
61766256
61776257 if (lhs_ty.zigTypeTag(mod) == .Vector) {
61786258 return func.fail("TODO: Implement overflow arithmetic for vectors", .{});
......@@ -6332,7 +6412,7 @@ fn airMulWithOverflow(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
63326412
63336413 const result_ptr = try func.allocStack(func.typeOfIndex(inst));
63346414 try func.store(result_ptr, bin_op_local, lhs_ty, 0);
6335 const offset = @as(u32, @intCast(lhs_ty.abiSize(mod)));
6415 const offset = @as(u32, @intCast(lhs_ty.abiSize(pt)));
63366416 try func.store(result_ptr, overflow_bit, Type.u1, offset);
63376417
63386418 func.finishAir(inst, result_ptr, &.{ extra.lhs, extra.rhs });
......@@ -6340,7 +6420,8 @@ fn airMulWithOverflow(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
63406420
63416421fn airMaxMin(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
63426422 assert(op == .max or op == .min);
6343 const mod = func.bin_file.base.comp.module.?;
6423 const pt = func.pt;
6424 const mod = pt.zcu;
63446425 const target = mod.getTarget();
63456426 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
63466427
......@@ -6349,7 +6430,7 @@ fn airMaxMin(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
63496430 return func.fail("TODO: `@maximum` and `@minimum` for vectors", .{});
63506431 }
63516432
6352 if (ty.abiSize(mod) > 16) {
6433 if (ty.abiSize(pt) > 16) {
63536434 return func.fail("TODO: `@maximum` and `@minimum` for types larger than 16 bytes", .{});
63546435 }
63556436
......@@ -6377,14 +6458,15 @@ fn airMaxMin(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
63776458 }
63786459
63796460 // store result in local
6380 const result_ty = if (isByRef(ty, mod)) Type.u32 else ty;
6461 const result_ty = if (isByRef(ty, pt)) Type.u32 else ty;
63816462 const result = try func.allocLocal(result_ty);
63826463 try func.addLabel(.local_set, result.local.value);
63836464 func.finishAir(inst, result, &.{ bin_op.lhs, bin_op.rhs });
63846465}
63856466
63866467fn airMulAdd(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
6387 const mod = func.bin_file.base.comp.module.?;
6468 const pt = func.pt;
6469 const mod = pt.zcu;
63886470 const pl_op = func.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
63896471 const bin_op = func.air.extraData(Air.Bin, pl_op.payload).data;
63906472
......@@ -6418,7 +6500,8 @@ fn airMulAdd(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
64186500}
64196501
64206502fn airClz(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
6421 const mod = func.bin_file.base.comp.module.?;
6503 const pt = func.pt;
6504 const mod = pt.zcu;
64226505 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
64236506
64246507 const ty = func.typeOf(ty_op.operand);
......@@ -6471,7 +6554,8 @@ fn airClz(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
64716554}
64726555
64736556fn airCtz(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
6474 const mod = func.bin_file.base.comp.module.?;
6557 const pt = func.pt;
6558 const mod = pt.zcu;
64756559 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
64766560
64776561 const ty = func.typeOf(ty_op.operand);
......@@ -6558,7 +6642,8 @@ fn airDbgInlineBlock(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
65586642fn airDbgVar(func: *CodeGen, inst: Air.Inst.Index, is_ptr: bool) InnerError!void {
65596643 if (func.debug_output != .dwarf) return func.finishAir(inst, .none, &.{});
65606644
6561 const mod = func.bin_file.base.comp.module.?;
6645 const pt = func.pt;
6646 const mod = pt.zcu;
65626647 const pl_op = func.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
65636648 const ty = func.typeOf(pl_op.operand);
65646649 const operand = try func.resolveInst(pl_op.operand);
......@@ -6591,7 +6676,8 @@ fn airTry(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
65916676}
65926677
65936678fn airTryPtr(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
6594 const mod = func.bin_file.base.comp.module.?;
6679 const pt = func.pt;
6680 const mod = pt.zcu;
65956681 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
65966682 const extra = func.air.extraData(Air.TryPtr, ty_pl.payload);
65976683 const err_union_ptr = try func.resolveInst(extra.data.ptr);
......@@ -6609,13 +6695,14 @@ fn lowerTry(
66096695 err_union_ty: Type,
66106696 operand_is_ptr: bool,
66116697) InnerError!WValue {
6612 const mod = func.bin_file.base.comp.module.?;
6698 const pt = func.pt;
6699 const mod = pt.zcu;
66136700 if (operand_is_ptr) {
66146701 return func.fail("TODO: lowerTry for pointers", .{});
66156702 }
66166703
66176704 const pl_ty = err_union_ty.errorUnionPayload(mod);
6618 const pl_has_bits = pl_ty.hasRuntimeBitsIgnoreComptime(mod);
6705 const pl_has_bits = pl_ty.hasRuntimeBitsIgnoreComptime(pt);
66196706
66206707 if (!err_union_ty.errorUnionSet(mod).errorSetIsEmpty(mod)) {
66216708 // Block we can jump out of when error is not set
......@@ -6624,10 +6711,10 @@ fn lowerTry(
66246711 // check if the error tag is set for the error union.
66256712 try func.emitWValue(err_union);
66266713 if (pl_has_bits) {
6627 const err_offset = @as(u32, @intCast(errUnionErrorOffset(pl_ty, mod)));
6714 const err_offset: u32 = @intCast(errUnionErrorOffset(pl_ty, pt));
66286715 try func.addMemArg(.i32_load16_u, .{
66296716 .offset = err_union.offset() + err_offset,
6630 .alignment = @intCast(Type.anyerror.abiAlignment(mod).toByteUnits().?),
6717 .alignment = @intCast(Type.anyerror.abiAlignment(pt).toByteUnits().?),
66316718 });
66326719 }
66336720 try func.addTag(.i32_eqz);
......@@ -6649,8 +6736,8 @@ fn lowerTry(
66496736 return WValue{ .none = {} };
66506737 }
66516738
6652 const pl_offset = @as(u32, @intCast(errUnionPayloadOffset(pl_ty, mod)));
6653 if (isByRef(pl_ty, mod)) {
6739 const pl_offset: u32 = @intCast(errUnionPayloadOffset(pl_ty, pt));
6740 if (isByRef(pl_ty, pt)) {
66546741 return buildPointerOffset(func, err_union, pl_offset, .new);
66556742 }
66566743 const payload = try func.load(err_union, pl_ty, pl_offset);
......@@ -6658,7 +6745,8 @@ fn lowerTry(
66586745}
66596746
66606747fn airByteSwap(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
6661 const mod = func.bin_file.base.comp.module.?;
6748 const pt = func.pt;
6749 const mod = pt.zcu;
66626750 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
66636751
66646752 const ty = func.typeOfIndex(inst);
......@@ -6744,7 +6832,8 @@ fn airDivTrunc(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
67446832fn airDivFloor(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
67456833 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
67466834
6747 const mod = func.bin_file.base.comp.module.?;
6835 const pt = func.pt;
6836 const mod = pt.zcu;
67486837 const ty = func.typeOfIndex(inst);
67496838 const lhs = try func.resolveInst(bin_op.lhs);
67506839 const rhs = try func.resolveInst(bin_op.rhs);
......@@ -6864,7 +6953,8 @@ fn airRem(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
68646953fn airMod(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
68656954 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
68666955
6867 const mod = func.bin_file.base.comp.module.?;
6956 const pt = func.pt;
6957 const mod = pt.zcu;
68686958 const ty = func.typeOfIndex(inst);
68696959 const lhs = try func.resolveInst(bin_op.lhs);
68706960 const rhs = try func.resolveInst(bin_op.rhs);
......@@ -6901,7 +6991,8 @@ fn airSatBinOp(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
69016991 assert(op == .add or op == .sub);
69026992 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
69036993
6904 const mod = func.bin_file.base.comp.module.?;
6994 const pt = func.pt;
6995 const mod = pt.zcu;
69056996 const ty = func.typeOfIndex(inst);
69066997 const lhs = try func.resolveInst(bin_op.lhs);
69076998 const rhs = try func.resolveInst(bin_op.rhs);
......@@ -6949,11 +7040,12 @@ fn airSatBinOp(func: *CodeGen, inst: Air.Inst.Index, op: Op) InnerError!void {
69497040}
69507041
69517042fn signedSat(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, op: Op) InnerError!WValue {
6952 const mod = func.bin_file.base.comp.module.?;
7043 const pt = func.pt;
7044 const mod = pt.zcu;
69537045 const int_info = ty.intInfo(mod);
69547046 const wasm_bits = toWasmBits(int_info.bits).?;
69557047 const is_wasm_bits = wasm_bits == int_info.bits;
6956 const ext_ty = if (!is_wasm_bits) try mod.intType(int_info.signedness, wasm_bits) else ty;
7048 const ext_ty = if (!is_wasm_bits) try pt.intType(int_info.signedness, wasm_bits) else ty;
69577049
69587050 const max_val: u64 = @as(u64, @intCast((@as(u65, 1) << @as(u7, @intCast(int_info.bits - 1))) - 1));
69597051 const min_val: i64 = (-@as(i64, @intCast(@as(u63, @intCast(max_val))))) - 1;
......@@ -7007,7 +7099,8 @@ fn signedSat(func: *CodeGen, lhs: WValue, rhs: WValue, ty: Type, op: Op) InnerEr
70077099fn airShlSat(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
70087100 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
70097101
7010 const mod = func.bin_file.base.comp.module.?;
7102 const pt = func.pt;
7103 const mod = pt.zcu;
70117104 const ty = func.typeOfIndex(inst);
70127105 const int_info = ty.intInfo(mod);
70137106 const is_signed = int_info.signedness == .signed;
......@@ -7061,7 +7154,7 @@ fn airShlSat(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
70617154 64 => WValue{ .imm64 = shift_size },
70627155 else => unreachable,
70637156 };
7064 const ext_ty = try mod.intType(int_info.signedness, wasm_bits);
7157 const ext_ty = try pt.intType(int_info.signedness, wasm_bits);
70657158
70667159 var shl_res = try (try func.binOp(lhs, shift_value, ext_ty, .shl)).toLocal(func, ext_ty);
70677160 defer shl_res.free(func);
......@@ -7128,13 +7221,14 @@ fn callIntrinsic(
71287221 };
71297222
71307223 // Always pass over C-ABI
7131 const mod = func.bin_file.base.comp.module.?;
7132 var func_type = try genFunctype(func.gpa, .C, param_types, return_type, mod);
7224 const pt = func.pt;
7225 const mod = pt.zcu;
7226 var func_type = try genFunctype(func.gpa, .C, param_types, return_type, pt);
71337227 defer func_type.deinit(func.gpa);
71347228 const func_type_index = try func.bin_file.zigObjectPtr().?.putOrGetFuncType(func.gpa, func_type);
71357229 try func.bin_file.addOrUpdateImport(name, symbol_index, null, func_type_index);
71367230
7137 const want_sret_param = firstParamSRet(.C, return_type, mod);
7231 const want_sret_param = firstParamSRet(.C, return_type, pt);
71387232 // if we want return as first param, we allocate a pointer to stack,
71397233 // and emit it as our first argument
71407234 const sret = if (want_sret_param) blk: {
......@@ -7146,14 +7240,14 @@ fn callIntrinsic(
71467240 // Lower all arguments to the stack before we call our function
71477241 for (args, 0..) |arg, arg_i| {
71487242 assert(!(want_sret_param and arg == .stack));
7149 assert(Type.fromInterned(param_types[arg_i]).hasRuntimeBitsIgnoreComptime(mod));
7243 assert(Type.fromInterned(param_types[arg_i]).hasRuntimeBitsIgnoreComptime(pt));
71507244 try func.lowerArg(.C, Type.fromInterned(param_types[arg_i]), arg);
71517245 }
71527246
71537247 // Actually call our intrinsic
71547248 try func.addLabel(.call, @intFromEnum(symbol_index));
71557249
7156 if (!return_type.hasRuntimeBitsIgnoreComptime(mod)) {
7250 if (!return_type.hasRuntimeBitsIgnoreComptime(pt)) {
71577251 return WValue.none;
71587252 } else if (return_type.isNoReturn(mod)) {
71597253 try func.addTag(.@"unreachable");
......@@ -7181,7 +7275,8 @@ fn airTagName(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
71817275}
71827276
71837277fn getTagNameFunction(func: *CodeGen, enum_ty: Type) InnerError!u32 {
7184 const mod = func.bin_file.base.comp.module.?;
7278 const pt = func.pt;
7279 const mod = pt.zcu;
71857280 const ip = &mod.intern_pool;
71867281 const enum_decl_index = enum_ty.getOwnerDecl(mod);
71877282
......@@ -7189,7 +7284,7 @@ fn getTagNameFunction(func: *CodeGen, enum_ty: Type) InnerError!u32 {
71897284 defer arena_allocator.deinit();
71907285 const arena = arena_allocator.allocator();
71917286
7192 const fqn = try mod.declPtr(enum_decl_index).fullyQualifiedName(mod);
7287 const fqn = try mod.declPtr(enum_decl_index).fullyQualifiedName(pt);
71937288 const func_name = try std.fmt.allocPrintZ(arena, "__zig_tag_name_{}", .{fqn.fmt(ip)});
71947289
71957290 // check if we already generated code for this.
......@@ -7199,7 +7294,7 @@ fn getTagNameFunction(func: *CodeGen, enum_ty: Type) InnerError!u32 {
71997294
72007295 const int_tag_ty = enum_ty.intTagType(mod);
72017296
7202 if (int_tag_ty.bitSize(mod) > 64) {
7297 if (int_tag_ty.bitSize(pt) > 64) {
72037298 return func.fail("TODO: Implement @tagName for enums with tag size larger than 64 bits", .{});
72047299 }
72057300
......@@ -7225,16 +7320,17 @@ fn getTagNameFunction(func: *CodeGen, enum_ty: Type) InnerError!u32 {
72257320 const tag_name_len = tag_name.length(ip);
72267321 // for each tag name, create an unnamed const,
72277322 // and then get a pointer to its value.
7228 const name_ty = try mod.arrayType(.{
7323 const name_ty = try pt.arrayType(.{
72297324 .len = tag_name_len,
72307325 .child = .u8_type,
72317326 .sentinel = .zero_u8,
72327327 });
7233 const name_val = try mod.intern(.{ .aggregate = .{
7328 const name_val = try pt.intern(.{ .aggregate = .{
72347329 .ty = name_ty.toIntern(),
72357330 .storage = .{ .bytes = tag_name.toString() },
72367331 } });
72377332 const tag_sym_index = try func.bin_file.lowerUnnamedConst(
7333 pt,
72387334 Value.fromInterned(name_val),
72397335 enum_decl_index,
72407336 );
......@@ -7247,7 +7343,7 @@ fn getTagNameFunction(func: *CodeGen, enum_ty: Type) InnerError!u32 {
72477343 try writer.writeByte(std.wasm.opcode(.local_get));
72487344 try leb.writeUleb128(writer, @as(u32, 1));
72497345
7250 const tag_val = try mod.enumValueFieldIndex(enum_ty, @intCast(tag_index));
7346 const tag_val = try pt.enumValueFieldIndex(enum_ty, @intCast(tag_index));
72517347 const tag_value = try func.lowerConstant(tag_val, enum_ty);
72527348
72537349 switch (tag_value) {
......@@ -7334,13 +7430,14 @@ fn getTagNameFunction(func: *CodeGen, enum_ty: Type) InnerError!u32 {
73347430 try writer.writeByte(std.wasm.opcode(.end));
73357431
73367432 const slice_ty = Type.slice_const_u8_sentinel_0;
7337 const func_type = try genFunctype(arena, .Unspecified, &.{int_tag_ty.ip_index}, slice_ty, mod);
7433 const func_type = try genFunctype(arena, .Unspecified, &.{int_tag_ty.ip_index}, slice_ty, pt);
73387434 const sym_index = try func.bin_file.createFunction(func_name, func_type, &body_list, &relocs);
73397435 return @intFromEnum(sym_index);
73407436}
73417437
73427438fn airErrorSetHasValue(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
7343 const mod = func.bin_file.base.comp.module.?;
7439 const pt = func.pt;
7440 const mod = pt.zcu;
73447441 const ip = &mod.intern_pool;
73457442 const ty_op = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
73467443
......@@ -7426,7 +7523,8 @@ inline fn useAtomicFeature(func: *const CodeGen) bool {
74267523}
74277524
74287525fn airCmpxchg(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
7429 const mod = func.bin_file.base.comp.module.?;
7526 const pt = func.pt;
7527 const mod = pt.zcu;
74307528 const ty_pl = func.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
74317529 const extra = func.air.extraData(Air.Cmpxchg, ty_pl.payload).data;
74327530
......@@ -7445,7 +7543,7 @@ fn airCmpxchg(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
74457543 try func.emitWValue(ptr_operand);
74467544 try func.lowerToStack(expected_val);
74477545 try func.lowerToStack(new_val);
7448 try func.addAtomicMemArg(switch (ty.abiSize(mod)) {
7546 try func.addAtomicMemArg(switch (ty.abiSize(pt)) {
74497547 1 => .i32_atomic_rmw8_cmpxchg_u,
74507548 2 => .i32_atomic_rmw16_cmpxchg_u,
74517549 4 => .i32_atomic_rmw_cmpxchg,
......@@ -7453,14 +7551,14 @@ fn airCmpxchg(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
74537551 else => |size| return func.fail("TODO: implement `@cmpxchg` for types with abi size '{d}'", .{size}),
74547552 }, .{
74557553 .offset = ptr_operand.offset(),
7456 .alignment = @intCast(ty.abiAlignment(mod).toByteUnits().?),
7554 .alignment = @intCast(ty.abiAlignment(pt).toByteUnits().?),
74577555 });
74587556 try func.addLabel(.local_tee, val_local.local.value);
74597557 _ = try func.cmp(.stack, expected_val, ty, .eq);
74607558 try func.addLabel(.local_set, cmp_result.local.value);
74617559 break :val val_local;
74627560 } else val: {
7463 if (ty.abiSize(mod) > 8) {
7561 if (ty.abiSize(pt) > 8) {
74647562 return func.fail("TODO: Implement `@cmpxchg` for types larger than abi size of 8 bytes", .{});
74657563 }
74667564 const ptr_val = try WValue.toLocal(try func.load(ptr_operand, ty, 0), func, ty);
......@@ -7476,7 +7574,7 @@ fn airCmpxchg(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
74767574 break :val ptr_val;
74777575 };
74787576
7479 const result_ptr = if (isByRef(result_ty, mod)) val: {
7577 const result_ptr = if (isByRef(result_ty, pt)) val: {
74807578 try func.emitWValue(cmp_result);
74817579 try func.addImm32(~@as(u32, 0));
74827580 try func.addTag(.i32_xor);
......@@ -7484,7 +7582,7 @@ fn airCmpxchg(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
74847582 try func.addTag(.i32_and);
74857583 const and_result = try WValue.toLocal(.stack, func, Type.bool);
74867584 const result_ptr = try func.allocStack(result_ty);
7487 try func.store(result_ptr, and_result, Type.bool, @as(u32, @intCast(ty.abiSize(mod))));
7585 try func.store(result_ptr, and_result, Type.bool, @as(u32, @intCast(ty.abiSize(pt))));
74887586 try func.store(result_ptr, ptr_val, ty, 0);
74897587 break :val result_ptr;
74907588 } else val: {
......@@ -7499,13 +7597,13 @@ fn airCmpxchg(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
74997597}
75007598
75017599fn airAtomicLoad(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
7502 const mod = func.bin_file.base.comp.module.?;
7600 const pt = func.pt;
75037601 const atomic_load = func.air.instructions.items(.data)[@intFromEnum(inst)].atomic_load;
75047602 const ptr = try func.resolveInst(atomic_load.ptr);
75057603 const ty = func.typeOfIndex(inst);
75067604
75077605 if (func.useAtomicFeature()) {
7508 const tag: wasm.AtomicsOpcode = switch (ty.abiSize(mod)) {
7606 const tag: wasm.AtomicsOpcode = switch (ty.abiSize(pt)) {
75097607 1 => .i32_atomic_load8_u,
75107608 2 => .i32_atomic_load16_u,
75117609 4 => .i32_atomic_load,
......@@ -7515,7 +7613,7 @@ fn airAtomicLoad(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
75157613 try func.emitWValue(ptr);
75167614 try func.addAtomicMemArg(tag, .{
75177615 .offset = ptr.offset(),
7518 .alignment = @intCast(ty.abiAlignment(mod).toByteUnits().?),
7616 .alignment = @intCast(ty.abiAlignment(pt).toByteUnits().?),
75197617 });
75207618 } else {
75217619 _ = try func.load(ptr, ty, 0);
......@@ -7526,7 +7624,8 @@ fn airAtomicLoad(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
75267624}
75277625
75287626fn airAtomicRmw(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
7529 const mod = func.bin_file.base.comp.module.?;
7627 const pt = func.pt;
7628 const mod = pt.zcu;
75307629 const pl_op = func.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
75317630 const extra = func.air.extraData(Air.AtomicRmw, pl_op.payload).data;
75327631
......@@ -7550,7 +7649,7 @@ fn airAtomicRmw(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
75507649 try func.emitWValue(ptr);
75517650 try func.emitWValue(value);
75527651 if (op == .Nand) {
7553 const wasm_bits = toWasmBits(@as(u16, @intCast(ty.bitSize(mod)))).?;
7652 const wasm_bits = toWasmBits(@intCast(ty.bitSize(pt))).?;
75547653
75557654 const and_res = try func.binOp(value, operand, ty, .@"and");
75567655 if (wasm_bits == 32)
......@@ -7567,7 +7666,7 @@ fn airAtomicRmw(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
75677666 try func.addTag(.select);
75687667 }
75697668 try func.addAtomicMemArg(
7570 switch (ty.abiSize(mod)) {
7669 switch (ty.abiSize(pt)) {
75717670 1 => .i32_atomic_rmw8_cmpxchg_u,
75727671 2 => .i32_atomic_rmw16_cmpxchg_u,
75737672 4 => .i32_atomic_rmw_cmpxchg,
......@@ -7576,7 +7675,7 @@ fn airAtomicRmw(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
75767675 },
75777676 .{
75787677 .offset = ptr.offset(),
7579 .alignment = @intCast(ty.abiAlignment(mod).toByteUnits().?),
7678 .alignment = @intCast(ty.abiAlignment(pt).toByteUnits().?),
75807679 },
75817680 );
75827681 const select_res = try func.allocLocal(ty);
......@@ -7595,7 +7694,7 @@ fn airAtomicRmw(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
75957694 else => {
75967695 try func.emitWValue(ptr);
75977696 try func.emitWValue(operand);
7598 const tag: wasm.AtomicsOpcode = switch (ty.abiSize(mod)) {
7697 const tag: wasm.AtomicsOpcode = switch (ty.abiSize(pt)) {
75997698 1 => switch (op) {
76007699 .Xchg => .i32_atomic_rmw8_xchg_u,
76017700 .Add => .i32_atomic_rmw8_add_u,
......@@ -7636,7 +7735,7 @@ fn airAtomicRmw(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
76367735 };
76377736 try func.addAtomicMemArg(tag, .{
76387737 .offset = ptr.offset(),
7639 .alignment = @intCast(ty.abiAlignment(mod).toByteUnits().?),
7738 .alignment = @intCast(ty.abiAlignment(pt).toByteUnits().?),
76407739 });
76417740 const result = try WValue.toLocal(.stack, func, ty);
76427741 return func.finishAir(inst, result, &.{ pl_op.operand, extra.operand });
......@@ -7681,7 +7780,7 @@ fn airAtomicRmw(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
76817780 try func.store(.stack, .stack, ty, ptr.offset());
76827781 },
76837782 .Nand => {
7684 const wasm_bits = toWasmBits(@as(u16, @intCast(ty.bitSize(mod)))).?;
7783 const wasm_bits = toWasmBits(@intCast(ty.bitSize(pt))).?;
76857784
76867785 try func.emitWValue(ptr);
76877786 const and_res = try func.binOp(result, operand, ty, .@"and");
......@@ -7701,7 +7800,8 @@ fn airAtomicRmw(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
77017800}
77027801
77037802fn airFence(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
7704 const zcu = func.bin_file.base.comp.module.?;
7803 const pt = func.pt;
7804 const zcu = pt.zcu;
77057805 // Only when the atomic feature is enabled, and we're not building
77067806 // for a single-threaded build, can we emit the `fence` instruction.
77077807 // In all other cases, we emit no instructions for a fence.
......@@ -7715,7 +7815,8 @@ fn airFence(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
77157815}
77167816
77177817fn airAtomicStore(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
7718 const mod = func.bin_file.base.comp.module.?;
7818 const pt = func.pt;
7819 const mod = pt.zcu;
77197820 const bin_op = func.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
77207821
77217822 const ptr = try func.resolveInst(bin_op.lhs);
......@@ -7724,7 +7825,7 @@ fn airAtomicStore(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
77247825 const ty = ptr_ty.childType(mod);
77257826
77267827 if (func.useAtomicFeature()) {
7727 const tag: wasm.AtomicsOpcode = switch (ty.abiSize(mod)) {
7828 const tag: wasm.AtomicsOpcode = switch (ty.abiSize(pt)) {
77287829 1 => .i32_atomic_store8,
77297830 2 => .i32_atomic_store16,
77307831 4 => .i32_atomic_store,
......@@ -7735,7 +7836,7 @@ fn airAtomicStore(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
77357836 try func.lowerToStack(operand);
77367837 try func.addAtomicMemArg(tag, .{
77377838 .offset = ptr.offset(),
7738 .alignment = @intCast(ty.abiAlignment(mod).toByteUnits().?),
7839 .alignment = @intCast(ty.abiAlignment(pt).toByteUnits().?),
77397840 });
77407841 } else {
77417842 try func.store(ptr, operand, ty, 0);
......@@ -7754,11 +7855,13 @@ fn airFrameAddress(func: *CodeGen, inst: Air.Inst.Index) InnerError!void {
77547855}
77557856
77567857fn typeOf(func: *CodeGen, inst: Air.Inst.Ref) Type {
7757 const mod = func.bin_file.base.comp.module.?;
7858 const pt = func.pt;
7859 const mod = pt.zcu;
77587860 return func.air.typeOf(inst, &mod.intern_pool);
77597861}
77607862
77617863fn typeOfIndex(func: *CodeGen, inst: Air.Inst.Index) Type {
7762 const mod = func.bin_file.base.comp.module.?;
7864 const pt = func.pt;
7865 const mod = pt.zcu;
77637866 return func.air.typeOfIndex(inst, &mod.intern_pool);
77647867}
src/arch/wasm/abi.zig+21-19
......@@ -22,15 +22,16 @@ const direct: [2]Class = .{ .direct, .none };
2222/// Classifies a given Zig type to determine how they must be passed
2323/// or returned as value within a wasm function.
2424/// When all elements result in `.none`, no value must be passed in or returned.
25pub fn classifyType(ty: Type, mod: *Zcu) [2]Class {
25pub fn classifyType(ty: Type, pt: Zcu.PerThread) [2]Class {
26 const mod = pt.zcu;
2627 const ip = &mod.intern_pool;
2728 const target = mod.getTarget();
28 if (!ty.hasRuntimeBitsIgnoreComptime(mod)) return none;
29 if (!ty.hasRuntimeBitsIgnoreComptime(pt)) return none;
2930 switch (ty.zigTypeTag(mod)) {
3031 .Struct => {
31 const struct_type = mod.typeToStruct(ty).?;
32 const struct_type = pt.zcu.typeToStruct(ty).?;
3233 if (struct_type.layout == .@"packed") {
33 if (ty.bitSize(mod) <= 64) return direct;
34 if (ty.bitSize(pt) <= 64) return direct;
3435 return .{ .direct, .direct };
3536 }
3637 if (struct_type.field_types.len > 1) {
......@@ -40,13 +41,13 @@ pub fn classifyType(ty: Type, mod: *Zcu) [2]Class {
4041 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[0]);
4142 const explicit_align = struct_type.fieldAlign(ip, 0);
4243 if (explicit_align != .none) {
43 if (explicit_align.compareStrict(.gt, field_ty.abiAlignment(mod)))
44 if (explicit_align.compareStrict(.gt, field_ty.abiAlignment(pt)))
4445 return memory;
4546 }
46 return classifyType(field_ty, mod);
47 return classifyType(field_ty, pt);
4748 },
4849 .Int, .Enum, .ErrorSet => {
49 const int_bits = ty.intInfo(mod).bits;
50 const int_bits = ty.intInfo(pt.zcu).bits;
5051 if (int_bits <= 64) return direct;
5152 if (int_bits <= 128) return .{ .direct, .direct };
5253 return memory;
......@@ -61,24 +62,24 @@ pub fn classifyType(ty: Type, mod: *Zcu) [2]Class {
6162 .Vector => return direct,
6263 .Array => return memory,
6364 .Optional => {
64 assert(ty.isPtrLikeOptional(mod));
65 assert(ty.isPtrLikeOptional(pt.zcu));
6566 return direct;
6667 },
6768 .Pointer => {
68 assert(!ty.isSlice(mod));
69 assert(!ty.isSlice(pt.zcu));
6970 return direct;
7071 },
7172 .Union => {
72 const union_obj = mod.typeToUnion(ty).?;
73 const union_obj = pt.zcu.typeToUnion(ty).?;
7374 if (union_obj.getLayout(ip) == .@"packed") {
74 if (ty.bitSize(mod) <= 64) return direct;
75 if (ty.bitSize(pt) <= 64) return direct;
7576 return .{ .direct, .direct };
7677 }
77 const layout = ty.unionGetLayout(mod);
78 const layout = ty.unionGetLayout(pt);
7879 assert(layout.tag_size == 0);
7980 if (union_obj.field_types.len > 1) return memory;
8081 const first_field_ty = Type.fromInterned(union_obj.field_types.get(ip)[0]);
81 return classifyType(first_field_ty, mod);
82 return classifyType(first_field_ty, pt);
8283 },
8384 .ErrorUnion,
8485 .Frame,
......@@ -100,28 +101,29 @@ pub fn classifyType(ty: Type, mod: *Zcu) [2]Class {
100101/// Returns the scalar type a given type can represent.
101102/// Asserts given type can be represented as scalar, such as
102103/// a struct with a single scalar field.
103pub fn scalarType(ty: Type, mod: *Zcu) Type {
104pub fn scalarType(ty: Type, pt: Zcu.PerThread) Type {
105 const mod = pt.zcu;
104106 const ip = &mod.intern_pool;
105107 switch (ty.zigTypeTag(mod)) {
106108 .Struct => {
107109 if (mod.typeToPackedStruct(ty)) |packed_struct| {
108 return scalarType(Type.fromInterned(packed_struct.backingIntType(ip).*), mod);
110 return scalarType(Type.fromInterned(packed_struct.backingIntType(ip).*), pt);
109111 } else {
110112 assert(ty.structFieldCount(mod) == 1);
111 return scalarType(ty.structFieldType(0, mod), mod);
113 return scalarType(ty.structFieldType(0, mod), pt);
112114 }
113115 },
114116 .Union => {
115117 const union_obj = mod.typeToUnion(ty).?;
116118 if (union_obj.getLayout(ip) != .@"packed") {
117 const layout = mod.getUnionLayout(union_obj);
119 const layout = pt.getUnionLayout(union_obj);
118120 if (layout.payload_size == 0 and layout.tag_size != 0) {
119 return scalarType(ty.unionTagTypeSafety(mod).?, mod);
121 return scalarType(ty.unionTagTypeSafety(mod).?, pt);
120122 }
121123 assert(union_obj.field_types.len == 1);
122124 }
123125 const first_field_ty = Type.fromInterned(union_obj.field_types.get(ip)[0]);
124 return scalarType(first_field_ty, mod);
126 return scalarType(first_field_ty, pt);
125127 },
126128 else => return ty,
127129 }
src/arch/x86_64/CodeGen.zig+655-551
......@@ -19,7 +19,7 @@ const CodeGenError = codegen.CodeGenError;
1919const Compilation = @import("../../Compilation.zig");
2020const DebugInfoOutput = codegen.DebugInfoOutput;
2121const DW = std.dwarf;
22const ErrorMsg = Module.ErrorMsg;
22const ErrorMsg = Zcu.ErrorMsg;
2323const Result = codegen.Result;
2424const Emit = @import("Emit.zig");
2525const Liveness = @import("../../Liveness.zig");
......@@ -27,8 +27,6 @@ const Lower = @import("Lower.zig");
2727const Mir = @import("Mir.zig");
2828const Package = @import("../../Package.zig");
2929const Zcu = @import("../../Zcu.zig");
30/// Deprecated.
31const Module = Zcu;
3230const InternPool = @import("../../InternPool.zig");
3331const Alignment = InternPool.Alignment;
3432const Target = std.Target;
......@@ -52,6 +50,7 @@ const FrameIndex = bits.FrameIndex;
5250const InnerError = CodeGenError || error{OutOfRegisters};
5351
5452gpa: Allocator,
53pt: Zcu.PerThread,
5554air: Air,
5655liveness: Liveness,
5756bin_file: *link.File,
......@@ -74,7 +73,7 @@ va_info: union {
7473ret_mcv: InstTracking,
7574fn_type: Type,
7675arg_index: u32,
77src_loc: Module.LazySrcLoc,
76src_loc: Zcu.LazySrcLoc,
7877
7978eflags_inst: ?Air.Inst.Index = null,
8079
......@@ -120,18 +119,18 @@ const Owner = union(enum) {
120119 func_index: InternPool.Index,
121120 lazy_sym: link.File.LazySymbol,
122121
123 fn getDecl(owner: Owner, mod: *Module) InternPool.DeclIndex {
122 fn getDecl(owner: Owner, zcu: *Zcu) InternPool.DeclIndex {
124123 return switch (owner) {
125 .func_index => |func_index| mod.funcOwnerDeclIndex(func_index),
126 .lazy_sym => |lazy_sym| lazy_sym.ty.getOwnerDecl(mod),
124 .func_index => |func_index| zcu.funcOwnerDeclIndex(func_index),
125 .lazy_sym => |lazy_sym| lazy_sym.ty.getOwnerDecl(zcu),
127126 };
128127 }
129128
130129 fn getSymbolIndex(owner: Owner, ctx: *Self) !u32 {
130 const pt = ctx.pt;
131131 switch (owner) {
132132 .func_index => |func_index| {
133 const mod = ctx.bin_file.comp.module.?;
134 const decl_index = mod.funcOwnerDeclIndex(func_index);
133 const decl_index = ctx.pt.zcu.funcOwnerDeclIndex(func_index);
135134 if (ctx.bin_file.cast(link.File.Elf)) |elf_file| {
136135 return elf_file.zigObjectPtr().?.getOrCreateMetadataForDecl(elf_file, decl_index);
137136 } else if (ctx.bin_file.cast(link.File.MachO)) |macho_file| {
......@@ -145,17 +144,17 @@ const Owner = union(enum) {
145144 },
146145 .lazy_sym => |lazy_sym| {
147146 if (ctx.bin_file.cast(link.File.Elf)) |elf_file| {
148 return elf_file.zigObjectPtr().?.getOrCreateMetadataForLazySymbol(elf_file, lazy_sym) catch |err|
147 return elf_file.zigObjectPtr().?.getOrCreateMetadataForLazySymbol(elf_file, pt, lazy_sym) catch |err|
149148 ctx.fail("{s} creating lazy symbol", .{@errorName(err)});
150149 } else if (ctx.bin_file.cast(link.File.MachO)) |macho_file| {
151 return macho_file.getZigObject().?.getOrCreateMetadataForLazySymbol(macho_file, lazy_sym) catch |err|
150 return macho_file.getZigObject().?.getOrCreateMetadataForLazySymbol(macho_file, pt, lazy_sym) catch |err|
152151 ctx.fail("{s} creating lazy symbol", .{@errorName(err)});
153152 } else if (ctx.bin_file.cast(link.File.Coff)) |coff_file| {
154 const atom = coff_file.getOrCreateAtomForLazySymbol(lazy_sym) catch |err|
153 const atom = coff_file.getOrCreateAtomForLazySymbol(pt, lazy_sym) catch |err|
155154 return ctx.fail("{s} creating lazy symbol", .{@errorName(err)});
156155 return coff_file.getAtom(atom).getSymbolIndex().?;
157156 } else if (ctx.bin_file.cast(link.File.Plan9)) |p9_file| {
158 return p9_file.getOrCreateAtomForLazySymbol(lazy_sym) catch |err|
157 return p9_file.getOrCreateAtomForLazySymbol(pt, lazy_sym) catch |err|
159158 return ctx.fail("{s} creating lazy symbol", .{@errorName(err)});
160159 } else unreachable;
161160 },
......@@ -753,14 +752,14 @@ const FrameAlloc = struct {
753752 .ref_count = 0,
754753 };
755754 }
756 fn initType(ty: Type, mod: *Module) FrameAlloc {
755 fn initType(ty: Type, pt: Zcu.PerThread) FrameAlloc {
757756 return init(.{
758 .size = ty.abiSize(mod),
759 .alignment = ty.abiAlignment(mod),
757 .size = ty.abiSize(pt),
758 .alignment = ty.abiAlignment(pt),
760759 });
761760 }
762 fn initSpill(ty: Type, mod: *Module) FrameAlloc {
763 const abi_size = ty.abiSize(mod);
761 fn initSpill(ty: Type, pt: Zcu.PerThread) FrameAlloc {
762 const abi_size = ty.abiSize(pt);
764763 const spill_size = if (abi_size < 8)
765764 math.ceilPowerOfTwoAssert(u64, abi_size)
766765 else
......@@ -768,7 +767,7 @@ const FrameAlloc = struct {
768767 return init(.{
769768 .size = spill_size,
770769 .pad = @intCast(spill_size - abi_size),
771 .alignment = ty.abiAlignment(mod).maxStrict(
770 .alignment = ty.abiAlignment(pt).maxStrict(
772771 Alignment.fromNonzeroByteUnits(@min(spill_size, 8)),
773772 ),
774773 });
......@@ -777,7 +776,7 @@ const FrameAlloc = struct {
777776
778777const StackAllocation = struct {
779778 inst: ?Air.Inst.Index,
780 /// TODO do we need size? should be determined by inst.ty.abiSize(mod)
779 /// TODO do we need size? should be determined by inst.ty.abiSize(pt)
781780 size: u32,
782781};
783782
......@@ -795,16 +794,17 @@ const Self = @This();
795794
796795pub fn generate(
797796 bin_file: *link.File,
798 src_loc: Module.LazySrcLoc,
797 pt: Zcu.PerThread,
798 src_loc: Zcu.LazySrcLoc,
799799 func_index: InternPool.Index,
800800 air: Air,
801801 liveness: Liveness,
802802 code: *std.ArrayList(u8),
803803 debug_output: DebugInfoOutput,
804804) CodeGenError!Result {
805 const comp = bin_file.comp;
806 const gpa = comp.gpa;
807 const zcu = comp.module.?;
805 const zcu = pt.zcu;
806 const gpa = zcu.gpa;
807 const comp = zcu.comp;
808808 const func = zcu.funcInfo(func_index);
809809 const fn_owner_decl = zcu.declPtr(func.owner_decl);
810810 assert(fn_owner_decl.has_tv);
......@@ -812,8 +812,9 @@ pub fn generate(
812812 const namespace = zcu.namespacePtr(fn_owner_decl.src_namespace);
813813 const mod = namespace.fileScope(zcu).mod;
814814
815 var function = Self{
815 var function: Self = .{
816816 .gpa = gpa,
817 .pt = pt,
817818 .air = air,
818819 .liveness = liveness,
819820 .target = &mod.resolved_target.result,
......@@ -882,11 +883,11 @@ pub fn generate(
882883 function.args = call_info.args;
883884 function.ret_mcv = call_info.return_value;
884885 function.frame_allocs.set(@intFromEnum(FrameIndex.ret_addr), FrameAlloc.init(.{
885 .size = Type.usize.abiSize(zcu),
886 .alignment = Type.usize.abiAlignment(zcu).min(call_info.stack_align),
886 .size = Type.usize.abiSize(pt),
887 .alignment = Type.usize.abiAlignment(pt).min(call_info.stack_align),
887888 }));
888889 function.frame_allocs.set(@intFromEnum(FrameIndex.base_ptr), FrameAlloc.init(.{
889 .size = Type.usize.abiSize(zcu),
890 .size = Type.usize.abiSize(pt),
890891 .alignment = Alignment.min(
891892 call_info.stack_align,
892893 Alignment.fromNonzeroByteUnits(function.target.stackAlignment()),
......@@ -971,7 +972,8 @@ pub fn generate(
971972
972973pub fn generateLazy(
973974 bin_file: *link.File,
974 src_loc: Module.LazySrcLoc,
975 pt: Zcu.PerThread,
976 src_loc: Zcu.LazySrcLoc,
975977 lazy_sym: link.File.LazySymbol,
976978 code: *std.ArrayList(u8),
977979 debug_output: DebugInfoOutput,
......@@ -980,8 +982,9 @@ pub fn generateLazy(
980982 const gpa = comp.gpa;
981983 // This function is for generating global code, so we use the root module.
982984 const mod = comp.root_mod;
983 var function = Self{
985 var function: Self = .{
984986 .gpa = gpa,
987 .pt = pt,
985988 .air = undefined,
986989 .liveness = undefined,
987990 .target = &mod.resolved_target.result,
......@@ -1065,7 +1068,7 @@ pub fn generateLazy(
10651068}
10661069
10671070const FormatDeclData = struct {
1068 mod: *Module,
1071 zcu: *Zcu,
10691072 decl_index: InternPool.DeclIndex,
10701073};
10711074fn formatDecl(
......@@ -1074,11 +1077,11 @@ fn formatDecl(
10741077 _: std.fmt.FormatOptions,
10751078 writer: anytype,
10761079) @TypeOf(writer).Error!void {
1077 try data.mod.declPtr(data.decl_index).renderFullyQualifiedName(data.mod, writer);
1080 try data.zcu.declPtr(data.decl_index).renderFullyQualifiedName(data.zcu, writer);
10781081}
10791082fn fmtDecl(self: *Self, decl_index: InternPool.DeclIndex) std.fmt.Formatter(formatDecl) {
10801083 return .{ .data = .{
1081 .mod = self.bin_file.comp.module.?,
1084 .zcu = self.pt.zcu,
10821085 .decl_index = decl_index,
10831086 } };
10841087}
......@@ -1095,7 +1098,7 @@ fn formatAir(
10951098) @TypeOf(writer).Error!void {
10961099 @import("../../print_air.zig").dumpInst(
10971100 data.inst,
1098 data.self.bin_file.comp.module.?,
1101 data.self.pt,
10991102 data.self.air,
11001103 data.self.liveness,
11011104 );
......@@ -1746,7 +1749,8 @@ fn asmMemoryRegisterImmediate(
17461749}
17471750
17481751fn gen(self: *Self) InnerError!void {
1749 const mod = self.bin_file.comp.module.?;
1752 const pt = self.pt;
1753 const mod = pt.zcu;
17501754 const fn_info = mod.typeToFunc(self.fn_type).?;
17511755 const cc = abi.resolveCallingConvention(fn_info.cc, self.target.*);
17521756 if (cc != .Naked) {
......@@ -1764,7 +1768,7 @@ fn gen(self: *Self) InnerError!void {
17641768 // The address where to store the return value for the caller is in a
17651769 // register which the callee is free to clobber. Therefore, we purposely
17661770 // spill it to stack immediately.
1767 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(Type.usize, mod));
1771 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(Type.usize, pt));
17681772 try self.genSetMem(
17691773 .{ .frame = frame_index },
17701774 0,
......@@ -1800,7 +1804,7 @@ fn gen(self: *Self) InnerError!void {
18001804 try self.asmRegisterImmediate(.{ ._, .cmp }, .al, Immediate.u(info.fp_count));
18011805 const skip_sse_reloc = try self.asmJccReloc(.na, undefined);
18021806
1803 const vec_2_f64 = try mod.vectorType(.{ .len = 2, .child = .f64_type });
1807 const vec_2_f64 = try pt.vectorType(.{ .len = 2, .child = .f64_type });
18041808 for (abi.SysV.c_abi_sse_param_regs[info.fp_count..], info.fp_count..) |reg, reg_i|
18051809 try self.genSetMem(
18061810 .{ .frame = reg_save_area_fi },
......@@ -1951,7 +1955,8 @@ fn gen(self: *Self) InnerError!void {
19511955}
19521956
19531957fn genBody(self: *Self, body: []const Air.Inst.Index) InnerError!void {
1954 const mod = self.bin_file.comp.module.?;
1958 const pt = self.pt;
1959 const mod = pt.zcu;
19551960 const ip = &mod.intern_pool;
19561961 const air_tags = self.air.instructions.items(.tag);
19571962
......@@ -2222,12 +2227,13 @@ fn genBody(self: *Self, body: []const Air.Inst.Index) InnerError!void {
22222227}
22232228
22242229fn genLazy(self: *Self, lazy_sym: link.File.LazySymbol) InnerError!void {
2225 const mod = self.bin_file.comp.module.?;
2230 const pt = self.pt;
2231 const mod = pt.zcu;
22262232 const ip = &mod.intern_pool;
22272233 switch (lazy_sym.ty.zigTypeTag(mod)) {
22282234 .Enum => {
22292235 const enum_ty = lazy_sym.ty;
2230 wip_mir_log.debug("{}.@tagName:", .{enum_ty.fmt(mod)});
2236 wip_mir_log.debug("{}.@tagName:", .{enum_ty.fmt(pt)});
22312237
22322238 const resolved_cc = abi.resolveCallingConvention(.Unspecified, self.target.*);
22332239 const param_regs = abi.getCAbiIntParamRegs(resolved_cc);
......@@ -2249,7 +2255,7 @@ fn genLazy(self: *Self, lazy_sym: link.File.LazySymbol) InnerError!void {
22492255 const tag_names = enum_ty.enumFields(mod);
22502256 for (exitlude_jump_relocs, 0..) |*exitlude_jump_reloc, tag_index| {
22512257 const tag_name_len = tag_names.get(ip)[tag_index].length(ip);
2252 const tag_val = try mod.enumValueFieldIndex(enum_ty, @intCast(tag_index));
2258 const tag_val = try pt.enumValueFieldIndex(enum_ty, @intCast(tag_index));
22532259 const tag_mcv = try self.genTypedValue(tag_val);
22542260 try self.genBinOpMir(.{ ._, .cmp }, enum_ty, enum_mcv, tag_mcv);
22552261 const skip_reloc = try self.asmJccReloc(.ne, undefined);
......@@ -2282,7 +2288,7 @@ fn genLazy(self: *Self, lazy_sym: link.File.LazySymbol) InnerError!void {
22822288 },
22832289 else => return self.fail(
22842290 "TODO implement {s} for {}",
2285 .{ @tagName(lazy_sym.kind), lazy_sym.ty.fmt(mod) },
2291 .{ @tagName(lazy_sym.kind), lazy_sym.ty.fmt(pt) },
22862292 ),
22872293 }
22882294}
......@@ -2481,14 +2487,15 @@ fn allocFrameIndex(self: *Self, alloc: FrameAlloc) !FrameIndex {
24812487
24822488/// Use a pointer instruction as the basis for allocating stack memory.
24832489fn allocMemPtr(self: *Self, inst: Air.Inst.Index) !FrameIndex {
2484 const mod = self.bin_file.comp.module.?;
2490 const pt = self.pt;
2491 const mod = pt.zcu;
24852492 const ptr_ty = self.typeOfIndex(inst);
24862493 const val_ty = ptr_ty.childType(mod);
24872494 return self.allocFrameIndex(FrameAlloc.init(.{
2488 .size = math.cast(u32, val_ty.abiSize(mod)) orelse {
2489 return self.fail("type '{}' too big to fit into stack frame", .{val_ty.fmt(mod)});
2495 .size = math.cast(u32, val_ty.abiSize(pt)) orelse {
2496 return self.fail("type '{}' too big to fit into stack frame", .{val_ty.fmt(pt)});
24902497 },
2491 .alignment = ptr_ty.ptrAlignment(mod).max(.@"1"),
2498 .alignment = ptr_ty.ptrAlignment(pt).max(.@"1"),
24922499 }));
24932500}
24942501
......@@ -2501,9 +2508,10 @@ fn allocTempRegOrMem(self: *Self, elem_ty: Type, reg_ok: bool) !MCValue {
25012508}
25022509
25032510fn allocRegOrMemAdvanced(self: *Self, ty: Type, inst: ?Air.Inst.Index, reg_ok: bool) !MCValue {
2504 const mod = self.bin_file.comp.module.?;
2505 const abi_size = math.cast(u32, ty.abiSize(mod)) orelse {
2506 return self.fail("type '{}' too big to fit into stack frame", .{ty.fmt(mod)});
2511 const pt = self.pt;
2512 const mod = pt.zcu;
2513 const abi_size = math.cast(u32, ty.abiSize(pt)) orelse {
2514 return self.fail("type '{}' too big to fit into stack frame", .{ty.fmt(pt)});
25072515 };
25082516
25092517 if (reg_ok) need_mem: {
......@@ -2529,12 +2537,13 @@ fn allocRegOrMemAdvanced(self: *Self, ty: Type, inst: ?Air.Inst.Index, reg_ok: b
25292537 }
25302538 }
25312539
2532 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(ty, mod));
2540 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(ty, pt));
25332541 return .{ .load_frame = .{ .index = frame_index } };
25342542}
25352543
25362544fn regClassForType(self: *Self, ty: Type) RegisterManager.RegisterBitSet {
2537 const mod = self.bin_file.comp.module.?;
2545 const pt = self.pt;
2546 const mod = pt.zcu;
25382547 return switch (ty.zigTypeTag(mod)) {
25392548 .Float => switch (ty.floatBits(self.target.*)) {
25402549 80 => abi.RegisterClass.x87,
......@@ -2849,7 +2858,8 @@ fn airFptrunc(self: *Self, inst: Air.Inst.Index) !void {
28492858}
28502859
28512860fn airFpext(self: *Self, inst: Air.Inst.Index) !void {
2852 const mod = self.bin_file.comp.module.?;
2861 const pt = self.pt;
2862 const mod = pt.zcu;
28532863 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
28542864 const dst_ty = self.typeOfIndex(inst);
28552865 const dst_scalar_ty = dst_ty.scalarType(mod);
......@@ -2892,14 +2902,14 @@ fn airFpext(self: *Self, inst: Air.Inst.Index) !void {
28922902 } }, &.{src_scalar_ty}, &.{.{ .air_ref = ty_op.operand }});
28932903 }
28942904
2895 const src_abi_size: u32 = @intCast(src_ty.abiSize(mod));
2905 const src_abi_size: u32 = @intCast(src_ty.abiSize(pt));
28962906 const src_mcv = try self.resolveInst(ty_op.operand);
28972907 const dst_mcv = if (src_mcv.isRegister() and self.reuseOperand(inst, ty_op.operand, 0, src_mcv))
28982908 src_mcv
28992909 else
29002910 try self.copyToRegisterWithInstTracking(inst, dst_ty, src_mcv);
29012911 const dst_reg = dst_mcv.getReg().?;
2902 const dst_alias = registerAlias(dst_reg, @intCast(@max(dst_ty.abiSize(mod), 16)));
2912 const dst_alias = registerAlias(dst_reg, @intCast(@max(dst_ty.abiSize(pt), 16)));
29032913 const dst_lock = self.register_manager.lockReg(dst_reg);
29042914 defer if (dst_lock) |lock| self.register_manager.unlockReg(lock);
29052915
......@@ -2978,19 +2988,20 @@ fn airFpext(self: *Self, inst: Air.Inst.Index) !void {
29782988 }
29792989 break :result dst_mcv;
29802990 } orelse return self.fail("TODO implement airFpext from {} to {}", .{
2981 src_ty.fmt(mod), dst_ty.fmt(mod),
2991 src_ty.fmt(pt), dst_ty.fmt(pt),
29822992 });
29832993 return self.finishAir(inst, result, .{ ty_op.operand, .none, .none });
29842994}
29852995
29862996fn airIntCast(self: *Self, inst: Air.Inst.Index) !void {
2987 const mod = self.bin_file.comp.module.?;
2997 const pt = self.pt;
2998 const mod = pt.zcu;
29882999 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
29893000 const src_ty = self.typeOf(ty_op.operand);
29903001 const dst_ty = self.typeOfIndex(inst);
29913002
29923003 const result = @as(?MCValue, result: {
2993 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(mod));
3004 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(pt));
29943005
29953006 const src_int_info = src_ty.intInfo(mod);
29963007 const dst_int_info = dst_ty.intInfo(mod);
......@@ -3001,13 +3012,13 @@ fn airIntCast(self: *Self, inst: Air.Inst.Index) !void {
30013012
30023013 const src_mcv = try self.resolveInst(ty_op.operand);
30033014 if (dst_ty.isVector(mod)) {
3004 const src_abi_size: u32 = @intCast(src_ty.abiSize(mod));
3015 const src_abi_size: u32 = @intCast(src_ty.abiSize(pt));
30053016 const max_abi_size = @max(dst_abi_size, src_abi_size);
30063017 if (max_abi_size > @as(u32, if (self.hasFeature(.avx2)) 32 else 16)) break :result null;
30073018 const has_avx = self.hasFeature(.avx);
30083019
3009 const dst_elem_abi_size = dst_ty.childType(mod).abiSize(mod);
3010 const src_elem_abi_size = src_ty.childType(mod).abiSize(mod);
3020 const dst_elem_abi_size = dst_ty.childType(mod).abiSize(pt);
3021 const src_elem_abi_size = src_ty.childType(mod).abiSize(pt);
30113022 switch (math.order(dst_elem_abi_size, src_elem_abi_size)) {
30123023 .lt => {
30133024 const mir_tag: Mir.Inst.FixedTag = switch (dst_elem_abi_size) {
......@@ -3236,19 +3247,20 @@ fn airIntCast(self: *Self, inst: Air.Inst.Index) !void {
32363247
32373248 break :result dst_mcv;
32383249 }) orelse return self.fail("TODO implement airIntCast from {} to {}", .{
3239 src_ty.fmt(mod), dst_ty.fmt(mod),
3250 src_ty.fmt(pt), dst_ty.fmt(pt),
32403251 });
32413252 return self.finishAir(inst, result, .{ ty_op.operand, .none, .none });
32423253}
32433254
32443255fn airTrunc(self: *Self, inst: Air.Inst.Index) !void {
3245 const mod = self.bin_file.comp.module.?;
3256 const pt = self.pt;
3257 const mod = pt.zcu;
32463258 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
32473259
32483260 const dst_ty = self.typeOfIndex(inst);
3249 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(mod));
3261 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(pt));
32503262 const src_ty = self.typeOf(ty_op.operand);
3251 const src_abi_size: u32 = @intCast(src_ty.abiSize(mod));
3263 const src_abi_size: u32 = @intCast(src_ty.abiSize(pt));
32523264
32533265 const result = result: {
32543266 const src_mcv = try self.resolveInst(ty_op.operand);
......@@ -3278,9 +3290,9 @@ fn airTrunc(self: *Self, inst: Air.Inst.Index) !void {
32783290 if (dst_ty.zigTypeTag(mod) == .Vector) {
32793291 assert(src_ty.zigTypeTag(mod) == .Vector and dst_ty.vectorLen(mod) == src_ty.vectorLen(mod));
32803292 const dst_elem_ty = dst_ty.childType(mod);
3281 const dst_elem_abi_size: u32 = @intCast(dst_elem_ty.abiSize(mod));
3293 const dst_elem_abi_size: u32 = @intCast(dst_elem_ty.abiSize(pt));
32823294 const src_elem_ty = src_ty.childType(mod);
3283 const src_elem_abi_size: u32 = @intCast(src_elem_ty.abiSize(mod));
3295 const src_elem_abi_size: u32 = @intCast(src_elem_ty.abiSize(pt));
32843296
32853297 const mir_tag = @as(?Mir.Inst.FixedTag, switch (dst_elem_abi_size) {
32863298 1 => switch (src_elem_abi_size) {
......@@ -3305,20 +3317,20 @@ fn airTrunc(self: *Self, inst: Air.Inst.Index) !void {
33053317 else => null,
33063318 },
33073319 else => null,
3308 }) orelse return self.fail("TODO implement airTrunc for {}", .{dst_ty.fmt(mod)});
3320 }) orelse return self.fail("TODO implement airTrunc for {}", .{dst_ty.fmt(pt)});
33093321
33103322 const dst_info = dst_elem_ty.intInfo(mod);
33113323 const src_info = src_elem_ty.intInfo(mod);
33123324
3313 const mask_val = try mod.intValue(src_elem_ty, @as(u64, math.maxInt(u64)) >> @intCast(64 - dst_info.bits));
3325 const mask_val = try pt.intValue(src_elem_ty, @as(u64, math.maxInt(u64)) >> @intCast(64 - dst_info.bits));
33143326
3315 const splat_ty = try mod.vectorType(.{
3327 const splat_ty = try pt.vectorType(.{
33163328 .len = @intCast(@divExact(@as(u64, if (src_abi_size > 16) 256 else 128), src_info.bits)),
33173329 .child = src_elem_ty.ip_index,
33183330 });
3319 const splat_abi_size: u32 = @intCast(splat_ty.abiSize(mod));
3331 const splat_abi_size: u32 = @intCast(splat_ty.abiSize(pt));
33203332
3321 const splat_val = try mod.intern(.{ .aggregate = .{
3333 const splat_val = try pt.intern(.{ .aggregate = .{
33223334 .ty = splat_ty.ip_index,
33233335 .storage = .{ .repeated_elem = mask_val.ip_index },
33243336 } });
......@@ -3375,7 +3387,7 @@ fn airTrunc(self: *Self, inst: Air.Inst.Index) !void {
33753387 }
33763388 } else if (dst_abi_size <= 16) {
33773389 const dst_info = dst_ty.intInfo(mod);
3378 const high_ty = try mod.intType(dst_info.signedness, dst_info.bits - 64);
3390 const high_ty = try pt.intType(dst_info.signedness, dst_info.bits - 64);
33793391 if (self.regExtraBits(high_ty) > 0) {
33803392 try self.truncateRegister(high_ty, dst_mcv.register_pair[1].to64());
33813393 }
......@@ -3400,12 +3412,12 @@ fn airIntFromBool(self: *Self, inst: Air.Inst.Index) !void {
34003412}
34013413
34023414fn airSlice(self: *Self, inst: Air.Inst.Index) !void {
3403 const mod = self.bin_file.comp.module.?;
3415 const pt = self.pt;
34043416 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
34053417 const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data;
34063418
34073419 const slice_ty = self.typeOfIndex(inst);
3408 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(slice_ty, mod));
3420 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(slice_ty, pt));
34093421
34103422 const ptr_ty = self.typeOf(bin_op.lhs);
34113423 try self.genSetMem(.{ .frame = frame_index }, 0, ptr_ty, .{ .air_ref = bin_op.lhs }, .{});
......@@ -3413,7 +3425,7 @@ fn airSlice(self: *Self, inst: Air.Inst.Index) !void {
34133425 const len_ty = self.typeOf(bin_op.rhs);
34143426 try self.genSetMem(
34153427 .{ .frame = frame_index },
3416 @intCast(ptr_ty.abiSize(mod)),
3428 @intCast(ptr_ty.abiSize(pt)),
34173429 len_ty,
34183430 .{ .air_ref = bin_op.rhs },
34193431 .{},
......@@ -3430,14 +3442,15 @@ fn airUnOp(self: *Self, inst: Air.Inst.Index, tag: Air.Inst.Tag) !void {
34303442}
34313443
34323444fn airBinOp(self: *Self, inst: Air.Inst.Index, tag: Air.Inst.Tag) !void {
3433 const mod = self.bin_file.comp.module.?;
3445 const pt = self.pt;
3446 const mod = pt.zcu;
34343447 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
34353448 const dst_mcv = try self.genBinOp(inst, tag, bin_op.lhs, bin_op.rhs);
34363449
34373450 const dst_ty = self.typeOfIndex(inst);
34383451 if (dst_ty.isAbiInt(mod)) {
3439 const abi_size: u32 = @intCast(dst_ty.abiSize(mod));
3440 const bit_size: u32 = @intCast(dst_ty.bitSize(mod));
3452 const abi_size: u32 = @intCast(dst_ty.abiSize(pt));
3453 const bit_size: u32 = @intCast(dst_ty.bitSize(pt));
34413454 if (abi_size * 8 > bit_size) {
34423455 const dst_lock = switch (dst_mcv) {
34433456 .register => |dst_reg| self.register_manager.lockRegAssumeUnused(dst_reg),
......@@ -3452,7 +3465,7 @@ fn airBinOp(self: *Self, inst: Air.Inst.Index, tag: Air.Inst.Tag) !void {
34523465 const tmp_lock = self.register_manager.lockRegAssumeUnused(tmp_reg);
34533466 defer self.register_manager.unlockReg(tmp_lock);
34543467
3455 const hi_ty = try mod.intType(.unsigned, @intCast((dst_ty.bitSize(mod) - 1) % 64 + 1));
3468 const hi_ty = try pt.intType(.unsigned, @intCast((dst_ty.bitSize(pt) - 1) % 64 + 1));
34563469 const hi_mcv = dst_mcv.address().offset(@intCast(bit_size / 64 * 8)).deref();
34573470 try self.genSetReg(tmp_reg, hi_ty, hi_mcv, .{});
34583471 try self.truncateRegister(dst_ty, tmp_reg);
......@@ -3471,7 +3484,8 @@ fn airPtrArithmetic(self: *Self, inst: Air.Inst.Index, tag: Air.Inst.Tag) !void
34713484}
34723485
34733486fn activeIntBits(self: *Self, dst_air: Air.Inst.Ref) u16 {
3474 const mod = self.bin_file.comp.module.?;
3487 const pt = self.pt;
3488 const mod = pt.zcu;
34753489 const air_tag = self.air.instructions.items(.tag);
34763490 const air_data = self.air.instructions.items(.data);
34773491
......@@ -3497,7 +3511,7 @@ fn activeIntBits(self: *Self, dst_air: Air.Inst.Ref) u16 {
34973511 }
34983512 } else if (dst_air.toInterned()) |ip_index| {
34993513 var space: Value.BigIntSpace = undefined;
3500 const src_int = Value.fromInterned(ip_index).toBigInt(&space, mod);
3514 const src_int = Value.fromInterned(ip_index).toBigInt(&space, pt);
35013515 return @as(u16, @intCast(src_int.bitCountTwosComp())) +
35023516 @intFromBool(src_int.positive and dst_info.signedness == .signed);
35033517 }
......@@ -3505,7 +3519,8 @@ fn activeIntBits(self: *Self, dst_air: Air.Inst.Ref) u16 {
35053519}
35063520
35073521fn airMulDivBinOp(self: *Self, inst: Air.Inst.Index) !void {
3508 const mod = self.bin_file.comp.module.?;
3522 const pt = self.pt;
3523 const mod = pt.zcu;
35093524 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
35103525 const result = result: {
35113526 const tag = self.air.instructions.items(.tag)[@intFromEnum(inst)];
......@@ -3514,10 +3529,10 @@ fn airMulDivBinOp(self: *Self, inst: Air.Inst.Index) !void {
35143529 .Float, .Vector => break :result try self.genBinOp(inst, tag, bin_op.lhs, bin_op.rhs),
35153530 else => {},
35163531 }
3517 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(mod));
3532 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(pt));
35183533
35193534 const dst_info = dst_ty.intInfo(mod);
3520 const src_ty = try mod.intType(dst_info.signedness, switch (tag) {
3535 const src_ty = try pt.intType(dst_info.signedness, switch (tag) {
35213536 else => unreachable,
35223537 .mul, .mul_wrap => @max(
35233538 self.activeIntBits(bin_op.lhs),
......@@ -3526,7 +3541,7 @@ fn airMulDivBinOp(self: *Self, inst: Air.Inst.Index) !void {
35263541 ),
35273542 .div_trunc, .div_floor, .div_exact, .rem, .mod => dst_info.bits,
35283543 });
3529 const src_abi_size: u32 = @intCast(src_ty.abiSize(mod));
3544 const src_abi_size: u32 = @intCast(src_ty.abiSize(pt));
35303545
35313546 if (dst_abi_size == 16 and src_abi_size == 16) switch (tag) {
35323547 else => unreachable,
......@@ -3539,7 +3554,7 @@ fn airMulDivBinOp(self: *Self, inst: Air.Inst.Index) !void {
35393554 state: State,
35403555 reloc: Mir.Inst.Index,
35413556 } = if (signed and tag == .div_floor) state: {
3542 const frame_index = try self.allocFrameIndex(FrameAlloc.initType(Type.usize, mod));
3557 const frame_index = try self.allocFrameIndex(FrameAlloc.initType(Type.usize, pt));
35433558 try self.asmMemoryImmediate(
35443559 .{ ._, .mov },
35453560 .{ .base = .{ .frame = frame_index }, .mod = .{ .rm = .{ .size = .qword } } },
......@@ -3614,7 +3629,7 @@ fn airMulDivBinOp(self: *Self, inst: Air.Inst.Index) !void {
36143629 .rem, .mod => "mod",
36153630 else => unreachable,
36163631 },
3617 intCompilerRtAbiName(@intCast(dst_ty.bitSize(mod))),
3632 intCompilerRtAbiName(@intCast(dst_ty.bitSize(pt))),
36183633 }) catch unreachable,
36193634 } },
36203635 &.{ src_ty, src_ty },
......@@ -3643,7 +3658,7 @@ fn airMulDivBinOp(self: *Self, inst: Air.Inst.Index) !void {
36433658 .return_type = dst_ty.toIntern(),
36443659 .param_types = &.{ src_ty.toIntern(), src_ty.toIntern() },
36453660 .callee = std.fmt.bufPrint(&callee_buf, "__div{c}i3", .{
3646 intCompilerRtAbiName(@intCast(dst_ty.bitSize(mod))),
3661 intCompilerRtAbiName(@intCast(dst_ty.bitSize(pt))),
36473662 }) catch unreachable,
36483663 } },
36493664 &.{ src_ty, src_ty },
......@@ -3734,12 +3749,13 @@ fn airMulDivBinOp(self: *Self, inst: Air.Inst.Index) !void {
37343749}
37353750
37363751fn airAddSat(self: *Self, inst: Air.Inst.Index) !void {
3737 const mod = self.bin_file.comp.module.?;
3752 const pt = self.pt;
3753 const mod = pt.zcu;
37383754 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
37393755 const ty = self.typeOf(bin_op.lhs);
3740 if (ty.zigTypeTag(mod) == .Vector or ty.abiSize(mod) > 8) return self.fail(
3756 if (ty.zigTypeTag(mod) == .Vector or ty.abiSize(pt) > 8) return self.fail(
37413757 "TODO implement airAddSat for {}",
3742 .{ty.fmt(mod)},
3758 .{ty.fmt(pt)},
37433759 );
37443760
37453761 const lhs_mcv = try self.resolveInst(bin_op.lhs);
......@@ -3804,7 +3820,7 @@ fn airAddSat(self: *Self, inst: Air.Inst.Index) !void {
38043820 break :cc .o;
38053821 } else cc: {
38063822 try self.genSetReg(limit_reg, ty, .{
3807 .immediate = @as(u64, math.maxInt(u64)) >> @intCast(64 - ty.bitSize(mod)),
3823 .immediate = @as(u64, math.maxInt(u64)) >> @intCast(64 - ty.bitSize(pt)),
38083824 }, .{});
38093825
38103826 try self.genBinOpMir(.{ ._, .add }, ty, dst_mcv, rhs_mcv);
......@@ -3815,7 +3831,7 @@ fn airAddSat(self: *Self, inst: Air.Inst.Index) !void {
38153831 break :cc .c;
38163832 };
38173833
3818 const cmov_abi_size = @max(@as(u32, @intCast(ty.abiSize(mod))), 2);
3834 const cmov_abi_size = @max(@as(u32, @intCast(ty.abiSize(pt))), 2);
38193835 try self.asmCmovccRegisterRegister(
38203836 cc,
38213837 registerAlias(dst_reg, cmov_abi_size),
......@@ -3834,12 +3850,13 @@ fn airAddSat(self: *Self, inst: Air.Inst.Index) !void {
38343850}
38353851
38363852fn airSubSat(self: *Self, inst: Air.Inst.Index) !void {
3837 const mod = self.bin_file.comp.module.?;
3853 const pt = self.pt;
3854 const mod = pt.zcu;
38383855 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
38393856 const ty = self.typeOf(bin_op.lhs);
3840 if (ty.zigTypeTag(mod) == .Vector or ty.abiSize(mod) > 8) return self.fail(
3857 if (ty.zigTypeTag(mod) == .Vector or ty.abiSize(pt) > 8) return self.fail(
38413858 "TODO implement airSubSat for {}",
3842 .{ty.fmt(mod)},
3859 .{ty.fmt(pt)},
38433860 );
38443861
38453862 const lhs_mcv = try self.resolveInst(bin_op.lhs);
......@@ -3908,7 +3925,7 @@ fn airSubSat(self: *Self, inst: Air.Inst.Index) !void {
39083925 break :cc .c;
39093926 };
39103927
3911 const cmov_abi_size = @max(@as(u32, @intCast(ty.abiSize(mod))), 2);
3928 const cmov_abi_size = @max(@as(u32, @intCast(ty.abiSize(pt))), 2);
39123929 try self.asmCmovccRegisterRegister(
39133930 cc,
39143931 registerAlias(dst_reg, cmov_abi_size),
......@@ -3927,13 +3944,14 @@ fn airSubSat(self: *Self, inst: Air.Inst.Index) !void {
39273944}
39283945
39293946fn airMulSat(self: *Self, inst: Air.Inst.Index) !void {
3930 const mod = self.bin_file.comp.module.?;
3947 const pt = self.pt;
3948 const mod = pt.zcu;
39313949 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
39323950 const ty = self.typeOf(bin_op.lhs);
39333951
39343952 const result = result: {
39353953 if (ty.toIntern() == .i128_type) {
3936 const ptr_c_int = try mod.singleMutPtrType(Type.c_int);
3954 const ptr_c_int = try pt.singleMutPtrType(Type.c_int);
39373955 const overflow = try self.allocTempRegOrMem(Type.c_int, false);
39383956
39393957 const dst_mcv = try self.genCall(.{ .lib = .{
......@@ -4010,9 +4028,9 @@ fn airMulSat(self: *Self, inst: Air.Inst.Index) !void {
40104028 break :result dst_mcv;
40114029 }
40124030
4013 if (ty.zigTypeTag(mod) == .Vector or ty.abiSize(mod) > 8) return self.fail(
4031 if (ty.zigTypeTag(mod) == .Vector or ty.abiSize(pt) > 8) return self.fail(
40144032 "TODO implement airMulSat for {}",
4015 .{ty.fmt(mod)},
4033 .{ty.fmt(pt)},
40164034 );
40174035
40184036 try self.spillRegisters(&.{ .rax, .rcx, .rdx });
......@@ -4061,7 +4079,7 @@ fn airMulSat(self: *Self, inst: Air.Inst.Index) !void {
40614079 };
40624080
40634081 const dst_mcv = try self.genMulDivBinOp(.mul, inst, ty, ty, lhs_mcv, rhs_mcv);
4064 const cmov_abi_size = @max(@as(u32, @intCast(ty.abiSize(mod))), 2);
4082 const cmov_abi_size = @max(@as(u32, @intCast(ty.abiSize(pt))), 2);
40654083 try self.asmCmovccRegisterRegister(
40664084 cc,
40674085 registerAlias(dst_mcv.register, cmov_abi_size),
......@@ -4073,7 +4091,8 @@ fn airMulSat(self: *Self, inst: Air.Inst.Index) !void {
40734091}
40744092
40754093fn airAddSubWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
4076 const mod = self.bin_file.comp.module.?;
4094 const pt = self.pt;
4095 const mod = pt.zcu;
40774096 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
40784097 const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data;
40794098 const result: MCValue = result: {
......@@ -4109,17 +4128,17 @@ fn airAddSubWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
41094128 }
41104129
41114130 const frame_index =
4112 try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, mod));
4131 try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, pt));
41134132 try self.genSetMem(
41144133 .{ .frame = frame_index },
4115 @intCast(tuple_ty.structFieldOffset(1, mod)),
4134 @intCast(tuple_ty.structFieldOffset(1, pt)),
41164135 Type.u1,
41174136 .{ .eflags = cc },
41184137 .{},
41194138 );
41204139 try self.genSetMem(
41214140 .{ .frame = frame_index },
4122 @intCast(tuple_ty.structFieldOffset(0, mod)),
4141 @intCast(tuple_ty.structFieldOffset(0, pt)),
41234142 ty,
41244143 partial_mcv,
41254144 .{},
......@@ -4128,7 +4147,7 @@ fn airAddSubWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
41284147 }
41294148
41304149 const frame_index =
4131 try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, mod));
4150 try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, pt));
41324151 try self.genSetFrameTruncatedOverflowCompare(tuple_ty, frame_index, partial_mcv, cc);
41334152 break :result .{ .load_frame = .{ .index = frame_index } };
41344153 },
......@@ -4139,7 +4158,8 @@ fn airAddSubWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
41394158}
41404159
41414160fn airShlWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
4142 const mod = self.bin_file.comp.module.?;
4161 const pt = self.pt;
4162 const mod = pt.zcu;
41434163 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
41444164 const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data;
41454165 const result: MCValue = result: {
......@@ -4186,17 +4206,17 @@ fn airShlWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
41864206 }
41874207
41884208 const frame_index =
4189 try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, mod));
4209 try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, pt));
41904210 try self.genSetMem(
41914211 .{ .frame = frame_index },
4192 @intCast(tuple_ty.structFieldOffset(1, mod)),
4212 @intCast(tuple_ty.structFieldOffset(1, pt)),
41934213 tuple_ty.structFieldType(1, mod),
41944214 .{ .eflags = cc },
41954215 .{},
41964216 );
41974217 try self.genSetMem(
41984218 .{ .frame = frame_index },
4199 @intCast(tuple_ty.structFieldOffset(0, mod)),
4219 @intCast(tuple_ty.structFieldOffset(0, pt)),
42004220 tuple_ty.structFieldType(0, mod),
42014221 partial_mcv,
42024222 .{},
......@@ -4205,7 +4225,7 @@ fn airShlWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
42054225 }
42064226
42074227 const frame_index =
4208 try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, mod));
4228 try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, pt));
42094229 try self.genSetFrameTruncatedOverflowCompare(tuple_ty, frame_index, partial_mcv, cc);
42104230 break :result .{ .load_frame = .{ .index = frame_index } };
42114231 },
......@@ -4222,7 +4242,8 @@ fn genSetFrameTruncatedOverflowCompare(
42224242 src_mcv: MCValue,
42234243 overflow_cc: ?Condition,
42244244) !void {
4225 const mod = self.bin_file.comp.module.?;
4245 const pt = self.pt;
4246 const mod = pt.zcu;
42264247 const src_lock = switch (src_mcv) {
42274248 .register => |reg| self.register_manager.lockReg(reg),
42284249 else => null,
......@@ -4233,12 +4254,12 @@ fn genSetFrameTruncatedOverflowCompare(
42334254 const int_info = ty.intInfo(mod);
42344255
42354256 const hi_bits = (int_info.bits - 1) % 64 + 1;
4236 const hi_ty = try mod.intType(int_info.signedness, hi_bits);
4257 const hi_ty = try pt.intType(int_info.signedness, hi_bits);
42374258
42384259 const limb_bits: u16 = @intCast(if (int_info.bits <= 64) self.regBitSize(ty) else 64);
4239 const limb_ty = try mod.intType(int_info.signedness, limb_bits);
4260 const limb_ty = try pt.intType(int_info.signedness, limb_bits);
42404261
4241 const rest_ty = try mod.intType(.unsigned, int_info.bits - hi_bits);
4262 const rest_ty = try pt.intType(.unsigned, int_info.bits - hi_bits);
42424263
42434264 const temp_regs =
42444265 try self.register_manager.allocRegs(3, .{null} ** 3, abi.RegisterClass.gp);
......@@ -4269,7 +4290,7 @@ fn genSetFrameTruncatedOverflowCompare(
42694290 );
42704291 }
42714292
4272 const payload_off: i32 = @intCast(tuple_ty.structFieldOffset(0, mod));
4293 const payload_off: i32 = @intCast(tuple_ty.structFieldOffset(0, pt));
42734294 if (hi_limb_off > 0) try self.genSetMem(
42744295 .{ .frame = frame_index },
42754296 payload_off,
......@@ -4286,7 +4307,7 @@ fn genSetFrameTruncatedOverflowCompare(
42864307 );
42874308 try self.genSetMem(
42884309 .{ .frame = frame_index },
4289 @intCast(tuple_ty.structFieldOffset(1, mod)),
4310 @intCast(tuple_ty.structFieldOffset(1, pt)),
42904311 tuple_ty.structFieldType(1, mod),
42914312 if (overflow_cc) |_| .{ .register = overflow_reg.to8() } else .{ .eflags = .ne },
42924313 .{},
......@@ -4294,18 +4315,19 @@ fn genSetFrameTruncatedOverflowCompare(
42944315}
42954316
42964317fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
4297 const mod = self.bin_file.comp.module.?;
4318 const pt = self.pt;
4319 const mod = pt.zcu;
42984320 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
42994321 const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data;
43004322 const tuple_ty = self.typeOfIndex(inst);
43014323 const dst_ty = self.typeOf(bin_op.lhs);
43024324 const result: MCValue = switch (dst_ty.zigTypeTag(mod)) {
4303 .Vector => return self.fail("TODO implement airMulWithOverflow for {}", .{dst_ty.fmt(mod)}),
4325 .Vector => return self.fail("TODO implement airMulWithOverflow for {}", .{dst_ty.fmt(pt)}),
43044326 .Int => result: {
43054327 const dst_info = dst_ty.intInfo(mod);
43064328 if (dst_info.bits > 128 and dst_info.signedness == .unsigned) {
43074329 const slow_inc = self.hasFeature(.slow_incdec);
4308 const abi_size: u32 = @intCast(dst_ty.abiSize(mod));
4330 const abi_size: u32 = @intCast(dst_ty.abiSize(pt));
43094331 const limb_len = math.divCeil(u32, abi_size, 8) catch unreachable;
43104332
43114333 try self.spillRegisters(&.{ .rax, .rcx, .rdx });
......@@ -4316,7 +4338,7 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
43164338 try self.genInlineMemset(
43174339 dst_mcv.address(),
43184340 .{ .immediate = 0 },
4319 .{ .immediate = tuple_ty.abiSize(mod) },
4341 .{ .immediate = tuple_ty.abiSize(pt) },
43204342 .{},
43214343 );
43224344 const lhs_mcv = try self.resolveInst(bin_op.lhs);
......@@ -4356,7 +4378,7 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
43564378 .index = temp_regs[3].to64(),
43574379 .scale = .@"8",
43584380 .disp = dst_mcv.load_frame.off +
4359 @as(i32, @intCast(tuple_ty.structFieldOffset(0, mod))),
4381 @as(i32, @intCast(tuple_ty.structFieldOffset(0, pt))),
43604382 } },
43614383 }, .rdx);
43624384 try self.asmSetccRegister(.c, .cl);
......@@ -4380,7 +4402,7 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
43804402 .index = temp_regs[3].to64(),
43814403 .scale = .@"8",
43824404 .disp = dst_mcv.load_frame.off +
4383 @as(i32, @intCast(tuple_ty.structFieldOffset(0, mod))),
4405 @as(i32, @intCast(tuple_ty.structFieldOffset(0, pt))),
43844406 } },
43854407 }, .rax);
43864408 try self.asmSetccRegister(.c, .ch);
......@@ -4429,7 +4451,7 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
44294451 .mod = .{ .rm = .{
44304452 .size = .byte,
44314453 .disp = dst_mcv.load_frame.off +
4432 @as(i32, @intCast(tuple_ty.structFieldOffset(1, mod))),
4454 @as(i32, @intCast(tuple_ty.structFieldOffset(1, pt))),
44334455 } },
44344456 }, Immediate.u(1));
44354457 self.performReloc(no_overflow);
......@@ -4453,11 +4475,11 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
44534475 const lhs_active_bits = self.activeIntBits(bin_op.lhs);
44544476 const rhs_active_bits = self.activeIntBits(bin_op.rhs);
44554477 const src_bits = @max(lhs_active_bits, rhs_active_bits, dst_info.bits / 2);
4456 const src_ty = try mod.intType(dst_info.signedness, src_bits);
4478 const src_ty = try pt.intType(dst_info.signedness, src_bits);
44574479 if (src_bits > 64 and src_bits <= 128 and
44584480 dst_info.bits > 64 and dst_info.bits <= 128) switch (dst_info.signedness) {
44594481 .signed => {
4460 const ptr_c_int = try mod.singleMutPtrType(Type.c_int);
4482 const ptr_c_int = try pt.singleMutPtrType(Type.c_int);
44614483 const overflow = try self.allocTempRegOrMem(Type.c_int, false);
44624484 const result = try self.genCall(.{ .lib = .{
44634485 .return_type = .i128_type,
......@@ -4472,7 +4494,7 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
44724494 const dst_mcv = try self.allocRegOrMem(inst, false);
44734495 try self.genSetMem(
44744496 .{ .frame = dst_mcv.load_frame.index },
4475 @intCast(tuple_ty.structFieldOffset(0, mod)),
4497 @intCast(tuple_ty.structFieldOffset(0, pt)),
44764498 tuple_ty.structFieldType(0, mod),
44774499 result,
44784500 .{},
......@@ -4484,7 +4506,7 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
44844506 );
44854507 try self.genSetMem(
44864508 .{ .frame = dst_mcv.load_frame.index },
4487 @intCast(tuple_ty.structFieldOffset(1, mod)),
4509 @intCast(tuple_ty.structFieldOffset(1, pt)),
44884510 tuple_ty.structFieldType(1, mod),
44894511 .{ .eflags = .ne },
44904512 .{},
......@@ -4596,14 +4618,14 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
45964618 const dst_mcv = try self.allocRegOrMem(inst, false);
45974619 try self.genSetMem(
45984620 .{ .frame = dst_mcv.load_frame.index },
4599 @intCast(tuple_ty.structFieldOffset(0, mod)),
4621 @intCast(tuple_ty.structFieldOffset(0, pt)),
46004622 tuple_ty.structFieldType(0, mod),
46014623 .{ .register_pair = .{ .rax, .rdx } },
46024624 .{},
46034625 );
46044626 try self.genSetMem(
46054627 .{ .frame = dst_mcv.load_frame.index },
4606 @intCast(tuple_ty.structFieldOffset(1, mod)),
4628 @intCast(tuple_ty.structFieldOffset(1, pt)),
46074629 tuple_ty.structFieldType(1, mod),
46084630 .{ .register = tmp_regs[1] },
46094631 .{},
......@@ -4636,7 +4658,7 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
46364658 self.eflags_inst = inst;
46374659 break :result .{ .register_overflow = .{ .reg = reg, .eflags = cc } };
46384660 } else {
4639 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, mod));
4661 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, pt));
46404662 try self.genSetFrameTruncatedOverflowCompare(tuple_ty, frame_index, partial_mcv, cc);
46414663 break :result .{ .load_frame = .{ .index = frame_index } };
46424664 },
......@@ -4644,21 +4666,21 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
46444666 // For now, this is the only supported multiply that doesn't fit in a register.
46454667 if (dst_info.bits > 128 or src_bits != 64)
46464668 return self.fail("TODO implement airWithOverflow from {} to {}", .{
4647 src_ty.fmt(mod), dst_ty.fmt(mod),
4669 src_ty.fmt(pt), dst_ty.fmt(pt),
46484670 });
46494671
4650 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, mod));
4672 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(tuple_ty, pt));
46514673 if (dst_info.bits >= lhs_active_bits + rhs_active_bits) {
46524674 try self.genSetMem(
46534675 .{ .frame = frame_index },
4654 @intCast(tuple_ty.structFieldOffset(0, mod)),
4676 @intCast(tuple_ty.structFieldOffset(0, pt)),
46554677 tuple_ty.structFieldType(0, mod),
46564678 partial_mcv,
46574679 .{},
46584680 );
46594681 try self.genSetMem(
46604682 .{ .frame = frame_index },
4661 @intCast(tuple_ty.structFieldOffset(1, mod)),
4683 @intCast(tuple_ty.structFieldOffset(1, pt)),
46624684 tuple_ty.structFieldType(1, mod),
46634685 .{ .immediate = 0 }, // cc being set is impossible
46644686 .{},
......@@ -4682,8 +4704,8 @@ fn airMulWithOverflow(self: *Self, inst: Air.Inst.Index) !void {
46824704/// Clobbers .rax and .rdx registers.
46834705/// Quotient is saved in .rax and remainder in .rdx.
46844706fn genIntMulDivOpMir(self: *Self, tag: Mir.Inst.FixedTag, ty: Type, lhs: MCValue, rhs: MCValue) !void {
4685 const mod = self.bin_file.comp.module.?;
4686 const abi_size: u32 = @intCast(ty.abiSize(mod));
4707 const pt = self.pt;
4708 const abi_size: u32 = @intCast(ty.abiSize(pt));
46874709 const bit_size: u32 = @intCast(self.regBitSize(ty));
46884710 if (abi_size > 8) {
46894711 return self.fail("TODO implement genIntMulDivOpMir for ABI size larger than 8", .{});
......@@ -4732,8 +4754,9 @@ fn genIntMulDivOpMir(self: *Self, tag: Mir.Inst.FixedTag, ty: Type, lhs: MCValue
47324754/// Always returns a register.
47334755/// Clobbers .rax and .rdx registers.
47344756fn genInlineIntDivFloor(self: *Self, ty: Type, lhs: MCValue, rhs: MCValue) !MCValue {
4735 const mod = self.bin_file.comp.module.?;
4736 const abi_size: u32 = @intCast(ty.abiSize(mod));
4757 const pt = self.pt;
4758 const mod = pt.zcu;
4759 const abi_size: u32 = @intCast(ty.abiSize(pt));
47374760 const int_info = ty.intInfo(mod);
47384761 const dividend = switch (lhs) {
47394762 .register => |reg| reg,
......@@ -4784,7 +4807,8 @@ fn genInlineIntDivFloor(self: *Self, ty: Type, lhs: MCValue, rhs: MCValue) !MCVa
47844807}
47854808
47864809fn airShlShrBinOp(self: *Self, inst: Air.Inst.Index) !void {
4787 const mod = self.bin_file.comp.module.?;
4810 const pt = self.pt;
4811 const mod = pt.zcu;
47884812 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
47894813
47904814 const air_tags = self.air.instructions.items(.tag);
......@@ -4811,7 +4835,7 @@ fn airShlShrBinOp(self: *Self, inst: Air.Inst.Index) !void {
48114835 const tmp_lock = self.register_manager.lockRegAssumeUnused(tmp_reg);
48124836 defer self.register_manager.unlockReg(tmp_lock);
48134837
4814 const lhs_bits: u31 = @intCast(lhs_ty.bitSize(mod));
4838 const lhs_bits: u31 = @intCast(lhs_ty.bitSize(pt));
48154839 const tmp_ty = if (lhs_bits > 64) Type.usize else lhs_ty;
48164840 const off = frame_addr.off + (lhs_bits - 1) / 64 * 8;
48174841 try self.genSetReg(
......@@ -4922,11 +4946,11 @@ fn airShlShrBinOp(self: *Self, inst: Air.Inst.Index) !void {
49224946 .shl, .shl_exact => if (self.hasFeature(.avx2)) .{ .vp_q, .sll } else null,
49234947 },
49244948 },
4925 })) |mir_tag| if (try self.air.value(bin_op.rhs, mod)) |rhs_val| {
4949 })) |mir_tag| if (try self.air.value(bin_op.rhs, pt)) |rhs_val| {
49264950 switch (mod.intern_pool.indexToKey(rhs_val.toIntern())) {
49274951 .aggregate => |rhs_aggregate| switch (rhs_aggregate.storage) {
49284952 .repeated_elem => |rhs_elem| {
4929 const abi_size: u32 = @intCast(lhs_ty.abiSize(mod));
4953 const abi_size: u32 = @intCast(lhs_ty.abiSize(pt));
49304954
49314955 const lhs_mcv = try self.resolveInst(bin_op.lhs);
49324956 const dst_reg, const lhs_reg = if (lhs_mcv.isRegister() and
......@@ -4946,7 +4970,7 @@ fn airShlShrBinOp(self: *Self, inst: Air.Inst.Index) !void {
49464970 self.register_manager.unlockReg(lock);
49474971
49484972 const shift_imm =
4949 Immediate.u(@intCast(Value.fromInterned(rhs_elem).toUnsignedInt(mod)));
4973 Immediate.u(@intCast(Value.fromInterned(rhs_elem).toUnsignedInt(pt)));
49504974 if (self.hasFeature(.avx)) try self.asmRegisterRegisterImmediate(
49514975 mir_tag,
49524976 registerAlias(dst_reg, abi_size),
......@@ -4968,7 +4992,7 @@ fn airShlShrBinOp(self: *Self, inst: Air.Inst.Index) !void {
49684992 }
49694993 } else if (bin_op.rhs.toIndex()) |rhs_inst| switch (air_tags[@intFromEnum(rhs_inst)]) {
49704994 .splat => {
4971 const abi_size: u32 = @intCast(lhs_ty.abiSize(mod));
4995 const abi_size: u32 = @intCast(lhs_ty.abiSize(pt));
49724996
49734997 const lhs_mcv = try self.resolveInst(bin_op.lhs);
49744998 const dst_reg, const lhs_reg = if (lhs_mcv.isRegister() and
......@@ -4991,13 +5015,13 @@ fn airShlShrBinOp(self: *Self, inst: Air.Inst.Index) !void {
49915015 const shift_lock = self.register_manager.lockRegAssumeUnused(shift_reg);
49925016 defer self.register_manager.unlockReg(shift_lock);
49935017
4994 const mask_ty = try mod.vectorType(.{ .len = 16, .child = .u8_type });
4995 const mask_mcv = try self.genTypedValue(Value.fromInterned(try mod.intern(.{ .aggregate = .{
5018 const mask_ty = try pt.vectorType(.{ .len = 16, .child = .u8_type });
5019 const mask_mcv = try self.genTypedValue(Value.fromInterned(try pt.intern(.{ .aggregate = .{
49965020 .ty = mask_ty.toIntern(),
49975021 .storage = .{ .elems = &([1]InternPool.Index{
4998 (try rhs_ty.childType(mod).maxIntScalar(mod, Type.u8)).toIntern(),
5022 (try rhs_ty.childType(mod).maxIntScalar(pt, Type.u8)).toIntern(),
49995023 } ++ [1]InternPool.Index{
5000 (try mod.intValue(Type.u8, 0)).toIntern(),
5024 (try pt.intValue(Type.u8, 0)).toIntern(),
50015025 } ** 15) },
50025026 } })));
50035027 const mask_addr_reg =
......@@ -5045,7 +5069,7 @@ fn airShlShrBinOp(self: *Self, inst: Air.Inst.Index) !void {
50455069 },
50465070 else => {},
50475071 }
5048 return self.fail("TODO implement airShlShrBinOp for {}", .{lhs_ty.fmt(mod)});
5072 return self.fail("TODO implement airShlShrBinOp for {}", .{lhs_ty.fmt(pt)});
50495073 };
50505074 return self.finishAir(inst, result, .{ bin_op.lhs, bin_op.rhs, .none });
50515075}
......@@ -5058,11 +5082,11 @@ fn airShlSat(self: *Self, inst: Air.Inst.Index) !void {
50585082}
50595083
50605084fn airOptionalPayload(self: *Self, inst: Air.Inst.Index) !void {
5061 const mod = self.bin_file.comp.module.?;
5085 const pt = self.pt;
50625086 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
50635087 const result: MCValue = result: {
50645088 const pl_ty = self.typeOfIndex(inst);
5065 if (!pl_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result .none;
5089 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .none;
50665090
50675091 const opt_mcv = try self.resolveInst(ty_op.operand);
50685092 if (self.reuseOperand(inst, ty_op.operand, 0, opt_mcv)) {
......@@ -5104,7 +5128,8 @@ fn airOptionalPayloadPtr(self: *Self, inst: Air.Inst.Index) !void {
51045128}
51055129
51065130fn airOptionalPayloadPtrSet(self: *Self, inst: Air.Inst.Index) !void {
5107 const mod = self.bin_file.comp.module.?;
5131 const pt = self.pt;
5132 const mod = pt.zcu;
51085133 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
51095134 const result = result: {
51105135 const dst_ty = self.typeOfIndex(inst);
......@@ -5130,7 +5155,7 @@ fn airOptionalPayloadPtrSet(self: *Self, inst: Air.Inst.Index) !void {
51305155 try self.copyToRegisterWithInstTracking(inst, dst_ty, src_mcv);
51315156
51325157 const pl_ty = dst_ty.childType(mod);
5133 const pl_abi_size: i32 = @intCast(pl_ty.abiSize(mod));
5158 const pl_abi_size: i32 = @intCast(pl_ty.abiSize(pt));
51345159 try self.genSetMem(
51355160 .{ .reg = dst_mcv.getReg().? },
51365161 pl_abi_size,
......@@ -5144,7 +5169,8 @@ fn airOptionalPayloadPtrSet(self: *Self, inst: Air.Inst.Index) !void {
51445169}
51455170
51465171fn airUnwrapErrUnionErr(self: *Self, inst: Air.Inst.Index) !void {
5147 const mod = self.bin_file.comp.module.?;
5172 const pt = self.pt;
5173 const mod = pt.zcu;
51485174 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
51495175 const err_union_ty = self.typeOf(ty_op.operand);
51505176 const err_ty = err_union_ty.errorUnionSet(mod);
......@@ -5156,11 +5182,11 @@ fn airUnwrapErrUnionErr(self: *Self, inst: Air.Inst.Index) !void {
51565182 break :result MCValue{ .immediate = 0 };
51575183 }
51585184
5159 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
5185 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
51605186 break :result operand;
51615187 }
51625188
5163 const err_off = errUnionErrorOffset(payload_ty, mod);
5189 const err_off = errUnionErrorOffset(payload_ty, pt);
51645190 switch (operand) {
51655191 .register => |reg| {
51665192 // TODO reuse operand
......@@ -5197,7 +5223,8 @@ fn airUnwrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) !void {
51975223
51985224// *(E!T) -> E
51995225fn airUnwrapErrUnionErrPtr(self: *Self, inst: Air.Inst.Index) !void {
5200 const mod = self.bin_file.comp.module.?;
5226 const pt = self.pt;
5227 const mod = pt.zcu;
52015228 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
52025229
52035230 const src_ty = self.typeOf(ty_op.operand);
......@@ -5217,8 +5244,8 @@ fn airUnwrapErrUnionErrPtr(self: *Self, inst: Air.Inst.Index) !void {
52175244 const eu_ty = src_ty.childType(mod);
52185245 const pl_ty = eu_ty.errorUnionPayload(mod);
52195246 const err_ty = eu_ty.errorUnionSet(mod);
5220 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, mod));
5221 const err_abi_size: u32 = @intCast(err_ty.abiSize(mod));
5247 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, pt));
5248 const err_abi_size: u32 = @intCast(err_ty.abiSize(pt));
52225249 try self.asmRegisterMemory(
52235250 .{ ._, .mov },
52245251 registerAlias(dst_reg, err_abi_size),
......@@ -5244,7 +5271,8 @@ fn airUnwrapErrUnionPayloadPtr(self: *Self, inst: Air.Inst.Index) !void {
52445271}
52455272
52465273fn airErrUnionPayloadPtrSet(self: *Self, inst: Air.Inst.Index) !void {
5247 const mod = self.bin_file.comp.module.?;
5274 const pt = self.pt;
5275 const mod = pt.zcu;
52485276 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
52495277 const result: MCValue = result: {
52505278 const src_ty = self.typeOf(ty_op.operand);
......@@ -5259,8 +5287,8 @@ fn airErrUnionPayloadPtrSet(self: *Self, inst: Air.Inst.Index) !void {
52595287 const eu_ty = src_ty.childType(mod);
52605288 const pl_ty = eu_ty.errorUnionPayload(mod);
52615289 const err_ty = eu_ty.errorUnionSet(mod);
5262 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, mod));
5263 const err_abi_size: u32 = @intCast(err_ty.abiSize(mod));
5290 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, pt));
5291 const err_abi_size: u32 = @intCast(err_ty.abiSize(pt));
52645292 try self.asmMemoryImmediate(
52655293 .{ ._, .mov },
52665294 .{
......@@ -5283,8 +5311,8 @@ fn airErrUnionPayloadPtrSet(self: *Self, inst: Air.Inst.Index) !void {
52835311 const dst_lock = self.register_manager.lockReg(dst_reg);
52845312 defer if (dst_lock) |lock| self.register_manager.unlockReg(lock);
52855313
5286 const pl_off: i32 = @intCast(errUnionPayloadOffset(pl_ty, mod));
5287 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(mod));
5314 const pl_off: i32 = @intCast(errUnionPayloadOffset(pl_ty, pt));
5315 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(pt));
52885316 try self.asmRegisterMemory(
52895317 .{ ._, .lea },
52905318 registerAlias(dst_reg, dst_abi_size),
......@@ -5304,13 +5332,14 @@ fn genUnwrapErrUnionPayloadMir(
53045332 err_union_ty: Type,
53055333 err_union: MCValue,
53065334) !MCValue {
5307 const mod = self.bin_file.comp.module.?;
5335 const pt = self.pt;
5336 const mod = pt.zcu;
53085337 const payload_ty = err_union_ty.errorUnionPayload(mod);
53095338
53105339 const result: MCValue = result: {
5311 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result .none;
5340 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .none;
53125341
5313 const payload_off: u31 = @intCast(errUnionPayloadOffset(payload_ty, mod));
5342 const payload_off: u31 = @intCast(errUnionPayloadOffset(payload_ty, pt));
53145343 switch (err_union) {
53155344 .load_frame => |frame_addr| break :result .{ .load_frame = .{
53165345 .index = frame_addr.index,
......@@ -5353,12 +5382,13 @@ fn genUnwrapErrUnionPayloadPtrMir(
53535382 ptr_ty: Type,
53545383 ptr_mcv: MCValue,
53555384) !MCValue {
5356 const mod = self.bin_file.comp.module.?;
5385 const pt = self.pt;
5386 const mod = pt.zcu;
53575387 const err_union_ty = ptr_ty.childType(mod);
53585388 const payload_ty = err_union_ty.errorUnionPayload(mod);
53595389
53605390 const result: MCValue = result: {
5361 const payload_off = errUnionPayloadOffset(payload_ty, mod);
5391 const payload_off = errUnionPayloadOffset(payload_ty, pt);
53625392 const result_mcv: MCValue = if (maybe_inst) |inst|
53635393 try self.copyToRegisterWithInstTracking(inst, ptr_ty, ptr_mcv)
53645394 else
......@@ -5387,11 +5417,12 @@ fn airSaveErrReturnTraceIndex(self: *Self, inst: Air.Inst.Index) !void {
53875417}
53885418
53895419fn airWrapOptional(self: *Self, inst: Air.Inst.Index) !void {
5390 const mod = self.bin_file.comp.module.?;
5420 const pt = self.pt;
5421 const mod = pt.zcu;
53915422 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
53925423 const result: MCValue = result: {
53935424 const pl_ty = self.typeOf(ty_op.operand);
5394 if (!pl_ty.hasRuntimeBits(mod)) break :result .{ .immediate = 1 };
5425 if (!pl_ty.hasRuntimeBits(pt)) break :result .{ .immediate = 1 };
53955426
53965427 const opt_ty = self.typeOfIndex(inst);
53975428 const pl_mcv = try self.resolveInst(ty_op.operand);
......@@ -5408,7 +5439,7 @@ fn airWrapOptional(self: *Self, inst: Air.Inst.Index) !void {
54085439 try self.genCopy(pl_ty, opt_mcv, pl_mcv, .{});
54095440
54105441 if (!same_repr) {
5411 const pl_abi_size: i32 = @intCast(pl_ty.abiSize(mod));
5442 const pl_abi_size: i32 = @intCast(pl_ty.abiSize(pt));
54125443 switch (opt_mcv) {
54135444 else => unreachable,
54145445
......@@ -5441,7 +5472,8 @@ fn airWrapOptional(self: *Self, inst: Air.Inst.Index) !void {
54415472
54425473/// T to E!T
54435474fn airWrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) !void {
5444 const mod = self.bin_file.comp.module.?;
5475 const pt = self.pt;
5476 const mod = pt.zcu;
54455477 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
54465478
54475479 const eu_ty = ty_op.ty.toType();
......@@ -5450,11 +5482,11 @@ fn airWrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) !void {
54505482 const operand = try self.resolveInst(ty_op.operand);
54515483
54525484 const result: MCValue = result: {
5453 if (!pl_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result .{ .immediate = 0 };
5485 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .{ .immediate = 0 };
54545486
5455 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(eu_ty, mod));
5456 const pl_off: i32 = @intCast(errUnionPayloadOffset(pl_ty, mod));
5457 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, mod));
5487 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(eu_ty, pt));
5488 const pl_off: i32 = @intCast(errUnionPayloadOffset(pl_ty, pt));
5489 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, pt));
54585490 try self.genSetMem(.{ .frame = frame_index }, pl_off, pl_ty, operand, .{});
54595491 try self.genSetMem(.{ .frame = frame_index }, err_off, err_ty, .{ .immediate = 0 }, .{});
54605492 break :result .{ .load_frame = .{ .index = frame_index } };
......@@ -5464,7 +5496,8 @@ fn airWrapErrUnionPayload(self: *Self, inst: Air.Inst.Index) !void {
54645496
54655497/// E to E!T
54665498fn airWrapErrUnionErr(self: *Self, inst: Air.Inst.Index) !void {
5467 const mod = self.bin_file.comp.module.?;
5499 const pt = self.pt;
5500 const mod = pt.zcu;
54685501 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
54695502
54705503 const eu_ty = ty_op.ty.toType();
......@@ -5472,11 +5505,11 @@ fn airWrapErrUnionErr(self: *Self, inst: Air.Inst.Index) !void {
54725505 const err_ty = eu_ty.errorUnionSet(mod);
54735506
54745507 const result: MCValue = result: {
5475 if (!pl_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result try self.resolveInst(ty_op.operand);
5508 if (!pl_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result try self.resolveInst(ty_op.operand);
54765509
5477 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(eu_ty, mod));
5478 const pl_off: i32 = @intCast(errUnionPayloadOffset(pl_ty, mod));
5479 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, mod));
5510 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(eu_ty, pt));
5511 const pl_off: i32 = @intCast(errUnionPayloadOffset(pl_ty, pt));
5512 const err_off: i32 = @intCast(errUnionErrorOffset(pl_ty, pt));
54805513 try self.genSetMem(.{ .frame = frame_index }, pl_off, pl_ty, .undef, .{});
54815514 const operand = try self.resolveInst(ty_op.operand);
54825515 try self.genSetMem(.{ .frame = frame_index }, err_off, err_ty, operand, .{});
......@@ -5523,7 +5556,7 @@ fn airSliceLen(self: *Self, inst: Air.Inst.Index) !void {
55235556}
55245557
55255558fn airPtrSliceLenPtr(self: *Self, inst: Air.Inst.Index) !void {
5526 const mod = self.bin_file.comp.module.?;
5559 const pt = self.pt;
55275560 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
55285561
55295562 const src_ty = self.typeOf(ty_op.operand);
......@@ -5544,7 +5577,7 @@ fn airPtrSliceLenPtr(self: *Self, inst: Air.Inst.Index) !void {
55445577 const dst_lock = self.register_manager.lockReg(dst_reg);
55455578 defer if (dst_lock) |lock| self.register_manager.unlockReg(lock);
55465579
5547 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(mod));
5580 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(pt));
55485581 try self.asmRegisterMemory(
55495582 .{ ._, .lea },
55505583 registerAlias(dst_reg, dst_abi_size),
......@@ -5591,7 +5624,8 @@ fn elemOffset(self: *Self, index_ty: Type, index: MCValue, elem_size: u64) !Regi
55915624}
55925625
55935626fn genSliceElemPtr(self: *Self, lhs: Air.Inst.Ref, rhs: Air.Inst.Ref) !MCValue {
5594 const mod = self.bin_file.comp.module.?;
5627 const pt = self.pt;
5628 const mod = pt.zcu;
55955629 const slice_ty = self.typeOf(lhs);
55965630 const slice_mcv = try self.resolveInst(lhs);
55975631 const slice_mcv_lock: ?RegisterLock = switch (slice_mcv) {
......@@ -5601,7 +5635,7 @@ fn genSliceElemPtr(self: *Self, lhs: Air.Inst.Ref, rhs: Air.Inst.Ref) !MCValue {
56015635 defer if (slice_mcv_lock) |lock| self.register_manager.unlockReg(lock);
56025636
56035637 const elem_ty = slice_ty.childType(mod);
5604 const elem_size = elem_ty.abiSize(mod);
5638 const elem_size = elem_ty.abiSize(pt);
56055639 const slice_ptr_field_type = slice_ty.slicePtrFieldType(mod);
56065640
56075641 const index_ty = self.typeOf(rhs);
......@@ -5627,12 +5661,13 @@ fn genSliceElemPtr(self: *Self, lhs: Air.Inst.Ref, rhs: Air.Inst.Ref) !MCValue {
56275661}
56285662
56295663fn airSliceElemVal(self: *Self, inst: Air.Inst.Index) !void {
5630 const mod = self.bin_file.comp.module.?;
5664 const pt = self.pt;
5665 const mod = pt.zcu;
56315666 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
56325667
56335668 const result: MCValue = result: {
56345669 const elem_ty = self.typeOfIndex(inst);
5635 if (!elem_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result .none;
5670 if (!elem_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .none;
56365671
56375672 const slice_ty = self.typeOf(bin_op.lhs);
56385673 const slice_ptr_field_type = slice_ty.slicePtrFieldType(mod);
......@@ -5652,7 +5687,8 @@ fn airSliceElemPtr(self: *Self, inst: Air.Inst.Index) !void {
56525687}
56535688
56545689fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
5655 const mod = self.bin_file.comp.module.?;
5690 const pt = self.pt;
5691 const mod = pt.zcu;
56565692 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
56575693
56585694 const result: MCValue = result: {
......@@ -5675,7 +5711,7 @@ fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
56755711 defer if (index_lock) |lock| self.register_manager.unlockReg(lock);
56765712
56775713 try self.spillEflagsIfOccupied();
5678 if (array_ty.isVector(mod) and elem_ty.bitSize(mod) == 1) {
5714 if (array_ty.isVector(mod) and elem_ty.bitSize(pt) == 1) {
56795715 const index_reg = switch (index_mcv) {
56805716 .register => |reg| reg,
56815717 else => try self.copyToTmpRegister(index_ty, index_mcv),
......@@ -5688,7 +5724,7 @@ fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
56885724 index_reg.to64(),
56895725 ),
56905726 .sse => {
5691 const frame_index = try self.allocFrameIndex(FrameAlloc.initType(array_ty, mod));
5727 const frame_index = try self.allocFrameIndex(FrameAlloc.initType(array_ty, pt));
56925728 try self.genSetMem(.{ .frame = frame_index }, 0, array_ty, array_mcv, .{});
56935729 try self.asmMemoryRegister(
56945730 .{ ._, .bt },
......@@ -5717,7 +5753,7 @@ fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
57175753 index_reg.to64(),
57185754 ),
57195755 else => return self.fail("TODO airArrayElemVal for {s} of {}", .{
5720 @tagName(array_mcv), array_ty.fmt(mod),
5756 @tagName(array_mcv), array_ty.fmt(pt),
57215757 }),
57225758 }
57235759
......@@ -5726,14 +5762,14 @@ fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
57265762 break :result .{ .register = dst_reg };
57275763 }
57285764
5729 const elem_abi_size = elem_ty.abiSize(mod);
5765 const elem_abi_size = elem_ty.abiSize(pt);
57305766 const addr_reg = try self.register_manager.allocReg(null, abi.RegisterClass.gp);
57315767 const addr_lock = self.register_manager.lockRegAssumeUnused(addr_reg);
57325768 defer self.register_manager.unlockReg(addr_lock);
57335769
57345770 switch (array_mcv) {
57355771 .register => {
5736 const frame_index = try self.allocFrameIndex(FrameAlloc.initType(array_ty, mod));
5772 const frame_index = try self.allocFrameIndex(FrameAlloc.initType(array_ty, pt));
57375773 try self.genSetMem(.{ .frame = frame_index }, 0, array_ty, array_mcv, .{});
57385774 try self.asmRegisterMemory(
57395775 .{ ._, .lea },
......@@ -5757,7 +5793,7 @@ fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
57575793 => try self.genSetReg(addr_reg, Type.usize, array_mcv.address(), .{}),
57585794 .lea_symbol, .lea_direct, .lea_tlv => unreachable,
57595795 else => return self.fail("TODO airArrayElemVal_val for {s} of {}", .{
5760 @tagName(array_mcv), array_ty.fmt(mod),
5796 @tagName(array_mcv), array_ty.fmt(pt),
57615797 }),
57625798 }
57635799
......@@ -5781,7 +5817,8 @@ fn airArrayElemVal(self: *Self, inst: Air.Inst.Index) !void {
57815817}
57825818
57835819fn airPtrElemVal(self: *Self, inst: Air.Inst.Index) !void {
5784 const mod = self.bin_file.comp.module.?;
5820 const pt = self.pt;
5821 const mod = pt.zcu;
57855822 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
57865823 const ptr_ty = self.typeOf(bin_op.lhs);
57875824
......@@ -5790,9 +5827,9 @@ fn airPtrElemVal(self: *Self, inst: Air.Inst.Index) !void {
57905827
57915828 const result = result: {
57925829 const elem_ty = ptr_ty.elemType2(mod);
5793 if (!elem_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result .none;
5830 if (!elem_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .none;
57945831
5795 const elem_abi_size: u32 = @intCast(elem_ty.abiSize(mod));
5832 const elem_abi_size: u32 = @intCast(elem_ty.abiSize(pt));
57965833 const index_ty = self.typeOf(bin_op.rhs);
57975834 const index_mcv = try self.resolveInst(bin_op.rhs);
57985835 const index_lock = switch (index_mcv) {
......@@ -5831,7 +5868,8 @@ fn airPtrElemVal(self: *Self, inst: Air.Inst.Index) !void {
58315868}
58325869
58335870fn airPtrElemPtr(self: *Self, inst: Air.Inst.Index) !void {
5834 const mod = self.bin_file.comp.module.?;
5871 const pt = self.pt;
5872 const mod = pt.zcu;
58355873 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
58365874 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
58375875
......@@ -5854,7 +5892,7 @@ fn airPtrElemPtr(self: *Self, inst: Air.Inst.Index) !void {
58545892 }
58555893
58565894 const elem_ty = base_ptr_ty.elemType2(mod);
5857 const elem_abi_size = elem_ty.abiSize(mod);
5895 const elem_abi_size = elem_ty.abiSize(pt);
58585896 const index_ty = self.typeOf(extra.rhs);
58595897 const index_mcv = try self.resolveInst(extra.rhs);
58605898 const index_lock: ?RegisterLock = switch (index_mcv) {
......@@ -5876,12 +5914,13 @@ fn airPtrElemPtr(self: *Self, inst: Air.Inst.Index) !void {
58765914}
58775915
58785916fn airSetUnionTag(self: *Self, inst: Air.Inst.Index) !void {
5879 const mod = self.bin_file.comp.module.?;
5917 const pt = self.pt;
5918 const mod = pt.zcu;
58805919 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
58815920 const ptr_union_ty = self.typeOf(bin_op.lhs);
58825921 const union_ty = ptr_union_ty.childType(mod);
58835922 const tag_ty = self.typeOf(bin_op.rhs);
5884 const layout = union_ty.unionGetLayout(mod);
5923 const layout = union_ty.unionGetLayout(pt);
58855924
58865925 if (layout.tag_size == 0) {
58875926 return self.finishAir(inst, .none, .{ bin_op.lhs, bin_op.rhs, .none });
......@@ -5913,19 +5952,19 @@ fn airSetUnionTag(self: *Self, inst: Air.Inst.Index) !void {
59135952 break :blk MCValue{ .register = reg };
59145953 } else ptr;
59155954
5916 const ptr_tag_ty = try mod.adjustPtrTypeChild(ptr_union_ty, tag_ty);
5955 const ptr_tag_ty = try pt.adjustPtrTypeChild(ptr_union_ty, tag_ty);
59175956 try self.store(ptr_tag_ty, adjusted_ptr, tag, .{});
59185957
59195958 return self.finishAir(inst, .none, .{ bin_op.lhs, bin_op.rhs, .none });
59205959}
59215960
59225961fn airGetUnionTag(self: *Self, inst: Air.Inst.Index) !void {
5923 const mod = self.bin_file.comp.module.?;
5962 const pt = self.pt;
59245963 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59255964
59265965 const tag_ty = self.typeOfIndex(inst);
59275966 const union_ty = self.typeOf(ty_op.operand);
5928 const layout = union_ty.unionGetLayout(mod);
5967 const layout = union_ty.unionGetLayout(pt);
59295968
59305969 if (layout.tag_size == 0) {
59315970 return self.finishAir(inst, .none, .{ ty_op.operand, .none, .none });
......@@ -5939,7 +5978,7 @@ fn airGetUnionTag(self: *Self, inst: Air.Inst.Index) !void {
59395978 };
59405979 defer if (operand_lock) |lock| self.register_manager.unlockReg(lock);
59415980
5942 const tag_abi_size = tag_ty.abiSize(mod);
5981 const tag_abi_size = tag_ty.abiSize(pt);
59435982 const dst_mcv: MCValue = blk: {
59445983 switch (operand) {
59455984 .load_frame => |frame_addr| {
......@@ -5983,7 +6022,8 @@ fn airGetUnionTag(self: *Self, inst: Air.Inst.Index) !void {
59836022}
59846023
59856024fn airClz(self: *Self, inst: Air.Inst.Index) !void {
5986 const mod = self.bin_file.comp.module.?;
6025 const pt = self.pt;
6026 const mod = pt.zcu;
59876027 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59886028 const result = result: {
59896029 try self.spillEflagsIfOccupied();
......@@ -5991,7 +6031,7 @@ fn airClz(self: *Self, inst: Air.Inst.Index) !void {
59916031 const dst_ty = self.typeOfIndex(inst);
59926032 const src_ty = self.typeOf(ty_op.operand);
59936033 if (src_ty.zigTypeTag(mod) == .Vector) return self.fail("TODO implement airClz for {}", .{
5994 src_ty.fmt(mod),
6034 src_ty.fmt(pt),
59956035 });
59966036
59976037 const src_mcv = try self.resolveInst(ty_op.operand);
......@@ -6010,8 +6050,8 @@ fn airClz(self: *Self, inst: Air.Inst.Index) !void {
60106050 const dst_lock = self.register_manager.lockRegAssumeUnused(dst_reg);
60116051 defer self.register_manager.unlockReg(dst_lock);
60126052
6013 const abi_size: u31 = @intCast(src_ty.abiSize(mod));
6014 const src_bits: u31 = @intCast(src_ty.bitSize(mod));
6053 const abi_size: u31 = @intCast(src_ty.abiSize(pt));
6054 const src_bits: u31 = @intCast(src_ty.bitSize(pt));
60156055 const has_lzcnt = self.hasFeature(.lzcnt);
60166056 if (src_bits > @as(u32, if (has_lzcnt) 128 else 64)) {
60176057 const limbs_len = math.divCeil(u32, abi_size, 8) catch unreachable;
......@@ -6121,7 +6161,7 @@ fn airClz(self: *Self, inst: Air.Inst.Index) !void {
61216161 }
61226162
61236163 assert(src_bits <= 64);
6124 const cmov_abi_size = @max(@as(u32, @intCast(dst_ty.abiSize(mod))), 2);
6164 const cmov_abi_size = @max(@as(u32, @intCast(dst_ty.abiSize(pt))), 2);
61256165 if (math.isPowerOfTwo(src_bits)) {
61266166 const imm_reg = try self.copyToTmpRegister(dst_ty, .{
61276167 .immediate = src_bits ^ (src_bits - 1),
......@@ -6179,7 +6219,8 @@ fn airClz(self: *Self, inst: Air.Inst.Index) !void {
61796219}
61806220
61816221fn airCtz(self: *Self, inst: Air.Inst.Index) !void {
6182 const mod = self.bin_file.comp.module.?;
6222 const pt = self.pt;
6223 const mod = pt.zcu;
61836224 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
61846225 const result = result: {
61856226 try self.spillEflagsIfOccupied();
......@@ -6187,7 +6228,7 @@ fn airCtz(self: *Self, inst: Air.Inst.Index) !void {
61876228 const dst_ty = self.typeOfIndex(inst);
61886229 const src_ty = self.typeOf(ty_op.operand);
61896230 if (src_ty.zigTypeTag(mod) == .Vector) return self.fail("TODO implement airCtz for {}", .{
6190 src_ty.fmt(mod),
6231 src_ty.fmt(pt),
61916232 });
61926233
61936234 const src_mcv = try self.resolveInst(ty_op.operand);
......@@ -6206,8 +6247,8 @@ fn airCtz(self: *Self, inst: Air.Inst.Index) !void {
62066247 const dst_lock = self.register_manager.lockReg(dst_reg);
62076248 defer if (dst_lock) |lock| self.register_manager.unlockReg(lock);
62086249
6209 const abi_size: u31 = @intCast(src_ty.abiSize(mod));
6210 const src_bits: u31 = @intCast(src_ty.bitSize(mod));
6250 const abi_size: u31 = @intCast(src_ty.abiSize(pt));
6251 const src_bits: u31 = @intCast(src_ty.bitSize(pt));
62116252 const has_bmi = self.hasFeature(.bmi);
62126253 if (src_bits > @as(u32, if (has_bmi) 128 else 64)) {
62136254 const limbs_len = math.divCeil(u32, abi_size, 8) catch unreachable;
......@@ -6328,7 +6369,7 @@ fn airCtz(self: *Self, inst: Air.Inst.Index) !void {
63286369 try self.genBinOpMir(.{ ._, .bsf }, wide_ty, dst_mcv, .{ .register = wide_reg });
63296370 } else try self.genBinOpMir(.{ ._, .bsf }, src_ty, dst_mcv, mat_src_mcv);
63306371
6331 const cmov_abi_size = @max(@as(u32, @intCast(dst_ty.abiSize(mod))), 2);
6372 const cmov_abi_size = @max(@as(u32, @intCast(dst_ty.abiSize(pt))), 2);
63326373 try self.asmCmovccRegisterRegister(
63336374 .z,
63346375 registerAlias(dst_reg, cmov_abi_size),
......@@ -6340,15 +6381,16 @@ fn airCtz(self: *Self, inst: Air.Inst.Index) !void {
63406381}
63416382
63426383fn airPopCount(self: *Self, inst: Air.Inst.Index) !void {
6343 const mod = self.bin_file.comp.module.?;
6384 const pt = self.pt;
6385 const mod = pt.zcu;
63446386 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
63456387 const result: MCValue = result: {
63466388 try self.spillEflagsIfOccupied();
63476389
63486390 const src_ty = self.typeOf(ty_op.operand);
6349 const src_abi_size: u32 = @intCast(src_ty.abiSize(mod));
6391 const src_abi_size: u32 = @intCast(src_ty.abiSize(pt));
63506392 if (src_ty.zigTypeTag(mod) == .Vector or src_abi_size > 16)
6351 return self.fail("TODO implement airPopCount for {}", .{src_ty.fmt(mod)});
6393 return self.fail("TODO implement airPopCount for {}", .{src_ty.fmt(pt)});
63526394 const src_mcv = try self.resolveInst(ty_op.operand);
63536395
63546396 const mat_src_mcv = switch (src_mcv) {
......@@ -6385,7 +6427,7 @@ fn airPopCount(self: *Self, inst: Air.Inst.Index) !void {
63856427 else
63866428 .{ .register = mat_src_mcv.register_pair[0] }, false);
63876429 const src_info = src_ty.intInfo(mod);
6388 const hi_ty = try mod.intType(src_info.signedness, (src_info.bits - 1) % 64 + 1);
6430 const hi_ty = try pt.intType(src_info.signedness, (src_info.bits - 1) % 64 + 1);
63896431 try self.genPopCount(tmp_regs[1], hi_ty, if (mat_src_mcv.isMemory())
63906432 mat_src_mcv.address().offset(8).deref()
63916433 else
......@@ -6403,16 +6445,16 @@ fn genPopCount(
64036445 src_mcv: MCValue,
64046446 dst_contains_src: bool,
64056447) !void {
6406 const mod = self.bin_file.comp.module.?;
6448 const pt = self.pt;
64076449
6408 const src_abi_size: u32 = @intCast(src_ty.abiSize(mod));
6450 const src_abi_size: u32 = @intCast(src_ty.abiSize(pt));
64096451 if (self.hasFeature(.popcnt)) return self.genBinOpMir(
64106452 .{ ._, .popcnt },
64116453 if (src_abi_size > 1) src_ty else Type.u32,
64126454 .{ .register = dst_reg },
64136455 if (src_abi_size > 1) src_mcv else src: {
64146456 if (!dst_contains_src) try self.genSetReg(dst_reg, src_ty, src_mcv, .{});
6415 try self.truncateRegister(try src_ty.toUnsigned(mod), dst_reg);
6457 try self.truncateRegister(try src_ty.toUnsigned(pt), dst_reg);
64166458 break :src .{ .register = dst_reg };
64176459 },
64186460 );
......@@ -6495,13 +6537,14 @@ fn genByteSwap(
64956537 src_mcv: MCValue,
64966538 mem_ok: bool,
64976539) !MCValue {
6498 const mod = self.bin_file.comp.module.?;
6540 const pt = self.pt;
6541 const mod = pt.zcu;
64996542 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
65006543 const has_movbe = self.hasFeature(.movbe);
65016544
65026545 if (src_ty.zigTypeTag(mod) == .Vector) return self.fail(
65036546 "TODO implement genByteSwap for {}",
6504 .{src_ty.fmt(mod)},
6547 .{src_ty.fmt(pt)},
65056548 );
65066549
65076550 const src_lock = switch (src_mcv) {
......@@ -6510,7 +6553,7 @@ fn genByteSwap(
65106553 };
65116554 defer if (src_lock) |lock| self.register_manager.unlockReg(lock);
65126555
6513 const abi_size: u32 = @intCast(src_ty.abiSize(mod));
6556 const abi_size: u32 = @intCast(src_ty.abiSize(pt));
65146557 switch (abi_size) {
65156558 0 => unreachable,
65166559 1 => return if ((mem_ok or src_mcv.isRegister()) and
......@@ -6658,11 +6701,12 @@ fn genByteSwap(
66586701}
66596702
66606703fn airByteSwap(self: *Self, inst: Air.Inst.Index) !void {
6661 const mod = self.bin_file.comp.module.?;
6704 const pt = self.pt;
6705 const mod = pt.zcu;
66626706 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
66636707
66646708 const src_ty = self.typeOf(ty_op.operand);
6665 const src_bits: u32 = @intCast(src_ty.bitSize(mod));
6709 const src_bits: u32 = @intCast(src_ty.bitSize(pt));
66666710 const src_mcv = try self.resolveInst(ty_op.operand);
66676711
66686712 const dst_mcv = try self.genByteSwap(inst, src_ty, src_mcv, true);
......@@ -6674,18 +6718,19 @@ fn airByteSwap(self: *Self, inst: Air.Inst.Index) !void {
66746718 src_ty,
66756719 dst_mcv,
66766720 if (src_bits > 256) Type.u16 else Type.u8,
6677 .{ .immediate = src_ty.abiSize(mod) * 8 - src_bits },
6721 .{ .immediate = src_ty.abiSize(pt) * 8 - src_bits },
66786722 );
66796723 return self.finishAir(inst, dst_mcv, .{ ty_op.operand, .none, .none });
66806724}
66816725
66826726fn airBitReverse(self: *Self, inst: Air.Inst.Index) !void {
6683 const mod = self.bin_file.comp.module.?;
6727 const pt = self.pt;
6728 const mod = pt.zcu;
66846729 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
66856730
66866731 const src_ty = self.typeOf(ty_op.operand);
6687 const abi_size: u32 = @intCast(src_ty.abiSize(mod));
6688 const bit_size: u32 = @intCast(src_ty.bitSize(mod));
6732 const abi_size: u32 = @intCast(src_ty.abiSize(pt));
6733 const bit_size: u32 = @intCast(src_ty.bitSize(pt));
66896734 const src_mcv = try self.resolveInst(ty_op.operand);
66906735
66916736 const dst_mcv = try self.genByteSwap(inst, src_ty, src_mcv, false);
......@@ -6802,14 +6847,15 @@ fn airBitReverse(self: *Self, inst: Air.Inst.Index) !void {
68026847}
68036848
68046849fn floatSign(self: *Self, inst: Air.Inst.Index, operand: Air.Inst.Ref, ty: Type) !void {
6805 const mod = self.bin_file.comp.module.?;
6850 const pt = self.pt;
6851 const mod = pt.zcu;
68066852 const tag = self.air.instructions.items(.tag)[@intFromEnum(inst)];
68076853
68086854 const result = result: {
68096855 const scalar_bits = ty.scalarType(mod).floatBits(self.target.*);
68106856 if (scalar_bits == 80) {
68116857 if (ty.zigTypeTag(mod) != .Float) return self.fail("TODO implement floatSign for {}", .{
6812 ty.fmt(mod),
6858 ty.fmt(pt),
68136859 });
68146860
68156861 const src_mcv = try self.resolveInst(operand);
......@@ -6829,11 +6875,11 @@ fn floatSign(self: *Self, inst: Air.Inst.Index, operand: Air.Inst.Ref, ty: Type)
68296875 break :result dst_mcv;
68306876 }
68316877
6832 const abi_size: u32 = switch (ty.abiSize(mod)) {
6878 const abi_size: u32 = switch (ty.abiSize(pt)) {
68336879 1...16 => 16,
68346880 17...32 => 32,
68356881 else => return self.fail("TODO implement floatSign for {}", .{
6836 ty.fmt(mod),
6882 ty.fmt(pt),
68376883 }),
68386884 };
68396885
......@@ -6852,14 +6898,14 @@ fn floatSign(self: *Self, inst: Air.Inst.Index, operand: Air.Inst.Ref, ty: Type)
68526898 const dst_lock = self.register_manager.lockReg(dst_reg);
68536899 defer if (dst_lock) |lock| self.register_manager.unlockReg(lock);
68546900
6855 const vec_ty = try mod.vectorType(.{
6901 const vec_ty = try pt.vectorType(.{
68566902 .len = @divExact(abi_size * 8, scalar_bits),
6857 .child = (try mod.intType(.signed, scalar_bits)).ip_index,
6903 .child = (try pt.intType(.signed, scalar_bits)).ip_index,
68586904 });
68596905
68606906 const sign_mcv = try self.genTypedValue(switch (tag) {
6861 .neg => try vec_ty.minInt(mod, vec_ty),
6862 .abs => try vec_ty.maxInt(mod, vec_ty),
6907 .neg => try vec_ty.minInt(pt, vec_ty),
6908 .abs => try vec_ty.maxInt(pt, vec_ty),
68636909 else => unreachable,
68646910 });
68656911 const sign_mem: Memory = if (sign_mcv.isMemory())
......@@ -6891,7 +6937,7 @@ fn floatSign(self: *Self, inst: Air.Inst.Index, operand: Air.Inst.Ref, ty: Type)
68916937 .abs => .{ .v_pd, .@"and" },
68926938 else => unreachable,
68936939 },
6894 80 => return self.fail("TODO implement floatSign for {}", .{ty.fmt(mod)}),
6940 80 => return self.fail("TODO implement floatSign for {}", .{ty.fmt(pt)}),
68956941 else => unreachable,
68966942 },
68976943 registerAlias(dst_reg, abi_size),
......@@ -6917,7 +6963,7 @@ fn floatSign(self: *Self, inst: Air.Inst.Index, operand: Air.Inst.Ref, ty: Type)
69176963 .abs => .{ ._pd, .@"and" },
69186964 else => unreachable,
69196965 },
6920 80 => return self.fail("TODO implement floatSign for {}", .{ty.fmt(mod)}),
6966 80 => return self.fail("TODO implement floatSign for {}", .{ty.fmt(pt)}),
69216967 else => unreachable,
69226968 },
69236969 registerAlias(dst_reg, abi_size),
......@@ -6978,7 +7024,8 @@ fn airRound(self: *Self, inst: Air.Inst.Index, mode: RoundMode) !void {
69787024}
69797025
69807026fn getRoundTag(self: *Self, ty: Type) ?Mir.Inst.FixedTag {
6981 const mod = self.bin_file.comp.module.?;
7027 const pt = self.pt;
7028 const mod = pt.zcu;
69827029 return if (self.hasFeature(.sse4_1)) switch (ty.zigTypeTag(mod)) {
69837030 .Float => switch (ty.floatBits(self.target.*)) {
69847031 32 => if (self.hasFeature(.avx)) .{ .v_ss, .round } else .{ ._ss, .round },
......@@ -7010,11 +7057,12 @@ fn getRoundTag(self: *Self, ty: Type) ?Mir.Inst.FixedTag {
70107057}
70117058
70127059fn genRoundLibcall(self: *Self, ty: Type, src_mcv: MCValue, mode: RoundMode) !MCValue {
7013 const mod = self.bin_file.comp.module.?;
7060 const pt = self.pt;
7061 const mod = pt.zcu;
70147062 if (self.getRoundTag(ty)) |_| return .none;
70157063
70167064 if (ty.zigTypeTag(mod) != .Float)
7017 return self.fail("TODO implement genRound for {}", .{ty.fmt(mod)});
7065 return self.fail("TODO implement genRound for {}", .{ty.fmt(pt)});
70187066
70197067 var callee_buf: ["__trunc?".len]u8 = undefined;
70207068 return try self.genCall(.{ .lib = .{
......@@ -7034,12 +7082,12 @@ fn genRoundLibcall(self: *Self, ty: Type, src_mcv: MCValue, mode: RoundMode) !MC
70347082}
70357083
70367084fn genRound(self: *Self, ty: Type, dst_reg: Register, src_mcv: MCValue, mode: RoundMode) !void {
7037 const mod = self.bin_file.comp.module.?;
7085 const pt = self.pt;
70387086 const mir_tag = self.getRoundTag(ty) orelse {
70397087 const result = try self.genRoundLibcall(ty, src_mcv, mode);
70407088 return self.genSetReg(dst_reg, ty, result, .{});
70417089 };
7042 const abi_size: u32 = @intCast(ty.abiSize(mod));
7090 const abi_size: u32 = @intCast(ty.abiSize(pt));
70437091 const dst_alias = registerAlias(dst_reg, abi_size);
70447092 switch (mir_tag[0]) {
70457093 .v_ss, .v_sd => if (src_mcv.isMemory()) try self.asmRegisterRegisterMemoryImmediate(
......@@ -7076,14 +7124,15 @@ fn genRound(self: *Self, ty: Type, dst_reg: Register, src_mcv: MCValue, mode: Ro
70767124}
70777125
70787126fn airAbs(self: *Self, inst: Air.Inst.Index) !void {
7079 const mod = self.bin_file.comp.module.?;
7127 const pt = self.pt;
7128 const mod = pt.zcu;
70807129 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
70817130 const ty = self.typeOf(ty_op.operand);
70827131
70837132 const result: MCValue = result: {
70847133 const mir_tag = @as(?Mir.Inst.FixedTag, switch (ty.zigTypeTag(mod)) {
70857134 else => null,
7086 .Int => switch (ty.abiSize(mod)) {
7135 .Int => switch (ty.abiSize(pt)) {
70877136 0 => unreachable,
70887137 1...8 => {
70897138 try self.spillEflagsIfOccupied();
......@@ -7092,7 +7141,7 @@ fn airAbs(self: *Self, inst: Air.Inst.Index) !void {
70927141
70937142 try self.genUnOpMir(.{ ._, .neg }, ty, dst_mcv);
70947143
7095 const cmov_abi_size = @max(@as(u32, @intCast(ty.abiSize(mod))), 2);
7144 const cmov_abi_size = @max(@as(u32, @intCast(ty.abiSize(pt))), 2);
70967145 switch (src_mcv) {
70977146 .register => |val_reg| try self.asmCmovccRegisterRegister(
70987147 .l,
......@@ -7151,7 +7200,7 @@ fn airAbs(self: *Self, inst: Air.Inst.Index) !void {
71517200 break :result dst_mcv;
71527201 },
71537202 else => {
7154 const abi_size: u31 = @intCast(ty.abiSize(mod));
7203 const abi_size: u31 = @intCast(ty.abiSize(pt));
71557204 const limb_len = math.divCeil(u31, abi_size, 8) catch unreachable;
71567205
71577206 const tmp_regs =
......@@ -7249,9 +7298,9 @@ fn airAbs(self: *Self, inst: Air.Inst.Index) !void {
72497298 },
72507299 .Float => return self.floatSign(inst, ty_op.operand, ty),
72517300 },
7252 }) orelse return self.fail("TODO implement airAbs for {}", .{ty.fmt(mod)});
7301 }) orelse return self.fail("TODO implement airAbs for {}", .{ty.fmt(pt)});
72537302
7254 const abi_size: u32 = @intCast(ty.abiSize(mod));
7303 const abi_size: u32 = @intCast(ty.abiSize(pt));
72557304 const src_mcv = try self.resolveInst(ty_op.operand);
72567305 const dst_reg = if (src_mcv.isRegister() and self.reuseOperand(inst, ty_op.operand, 0, src_mcv))
72577306 src_mcv.getReg().?
......@@ -7276,10 +7325,11 @@ fn airAbs(self: *Self, inst: Air.Inst.Index) !void {
72767325}
72777326
72787327fn airSqrt(self: *Self, inst: Air.Inst.Index) !void {
7279 const mod = self.bin_file.comp.module.?;
7328 const pt = self.pt;
7329 const mod = pt.zcu;
72807330 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
72817331 const ty = self.typeOf(un_op);
7282 const abi_size: u32 = @intCast(ty.abiSize(mod));
7332 const abi_size: u32 = @intCast(ty.abiSize(pt));
72837333
72847334 const result: MCValue = result: {
72857335 switch (ty.zigTypeTag(mod)) {
......@@ -7408,7 +7458,7 @@ fn airSqrt(self: *Self, inst: Air.Inst.Index) !void {
74087458 },
74097459 else => unreachable,
74107460 }) orelse return self.fail("TODO implement airSqrt for {}", .{
7411 ty.fmt(mod),
7461 ty.fmt(pt),
74127462 });
74137463 switch (mir_tag[0]) {
74147464 .v_ss, .v_sd => if (src_mcv.isMemory()) try self.asmRegisterRegisterMemory(
......@@ -7521,14 +7571,15 @@ fn reuseOperandAdvanced(
75217571}
75227572
75237573fn packedLoad(self: *Self, dst_mcv: MCValue, ptr_ty: Type, ptr_mcv: MCValue) InnerError!void {
7524 const mod = self.bin_file.comp.module.?;
7574 const pt = self.pt;
7575 const mod = pt.zcu;
75257576
75267577 const ptr_info = ptr_ty.ptrInfo(mod);
75277578 const val_ty = Type.fromInterned(ptr_info.child);
7528 if (!val_ty.hasRuntimeBitsIgnoreComptime(mod)) return;
7529 const val_abi_size: u32 = @intCast(val_ty.abiSize(mod));
7579 if (!val_ty.hasRuntimeBitsIgnoreComptime(pt)) return;
7580 const val_abi_size: u32 = @intCast(val_ty.abiSize(pt));
75307581
7531 const val_bit_size: u32 = @intCast(val_ty.bitSize(mod));
7582 const val_bit_size: u32 = @intCast(val_ty.bitSize(pt));
75327583 const ptr_bit_off = ptr_info.packed_offset.bit_offset + switch (ptr_info.flags.vector_index) {
75337584 .none => 0,
75347585 .runtime => unreachable,
......@@ -7566,7 +7617,7 @@ fn packedLoad(self: *Self, dst_mcv: MCValue, ptr_ty: Type, ptr_mcv: MCValue) Inn
75667617 return;
75677618 }
75687619
7569 if (val_abi_size > 8) return self.fail("TODO implement packed load of {}", .{val_ty.fmt(mod)});
7620 if (val_abi_size > 8) return self.fail("TODO implement packed load of {}", .{val_ty.fmt(pt)});
75707621
75717622 const limb_abi_size: u31 = @min(val_abi_size, 8);
75727623 const limb_abi_bits = limb_abi_size * 8;
......@@ -7633,9 +7684,10 @@ fn packedLoad(self: *Self, dst_mcv: MCValue, ptr_ty: Type, ptr_mcv: MCValue) Inn
76337684}
76347685
76357686fn load(self: *Self, dst_mcv: MCValue, ptr_ty: Type, ptr_mcv: MCValue) InnerError!void {
7636 const mod = self.bin_file.comp.module.?;
7687 const pt = self.pt;
7688 const mod = pt.zcu;
76377689 const dst_ty = ptr_ty.childType(mod);
7638 if (!dst_ty.hasRuntimeBitsIgnoreComptime(mod)) return;
7690 if (!dst_ty.hasRuntimeBitsIgnoreComptime(pt)) return;
76397691 switch (ptr_mcv) {
76407692 .none,
76417693 .unreach,
......@@ -7675,18 +7727,19 @@ fn load(self: *Self, dst_mcv: MCValue, ptr_ty: Type, ptr_mcv: MCValue) InnerErro
76757727}
76767728
76777729fn airLoad(self: *Self, inst: Air.Inst.Index) !void {
7678 const mod = self.bin_file.comp.module.?;
7730 const pt = self.pt;
7731 const mod = pt.zcu;
76797732 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
76807733 const elem_ty = self.typeOfIndex(inst);
76817734 const result: MCValue = result: {
7682 if (!elem_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result .none;
7735 if (!elem_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .none;
76837736
76847737 try self.spillRegisters(&.{ .rdi, .rsi, .rcx });
76857738 const reg_locks = self.register_manager.lockRegsAssumeUnused(3, .{ .rdi, .rsi, .rcx });
76867739 defer for (reg_locks) |lock| self.register_manager.unlockReg(lock);
76877740
76887741 const ptr_ty = self.typeOf(ty_op.operand);
7689 const elem_size = elem_ty.abiSize(mod);
7742 const elem_size = elem_ty.abiSize(pt);
76907743
76917744 const elem_rc = self.regClassForType(elem_ty);
76927745 const ptr_rc = self.regClassForType(ptr_ty);
......@@ -7706,7 +7759,7 @@ fn airLoad(self: *Self, inst: Air.Inst.Index) !void {
77067759 try self.load(dst_mcv, ptr_ty, ptr_mcv);
77077760 }
77087761
7709 if (elem_ty.isAbiInt(mod) and elem_size * 8 > elem_ty.bitSize(mod)) {
7762 if (elem_ty.isAbiInt(mod) and elem_size * 8 > elem_ty.bitSize(pt)) {
77107763 const high_mcv: MCValue = switch (dst_mcv) {
77117764 .register => |dst_reg| .{ .register = dst_reg },
77127765 .register_pair => |dst_regs| .{ .register = dst_regs[1] },
......@@ -7733,16 +7786,17 @@ fn airLoad(self: *Self, inst: Air.Inst.Index) !void {
77337786}
77347787
77357788fn packedStore(self: *Self, ptr_ty: Type, ptr_mcv: MCValue, src_mcv: MCValue) InnerError!void {
7736 const mod = self.bin_file.comp.module.?;
7789 const pt = self.pt;
7790 const mod = pt.zcu;
77377791 const ptr_info = ptr_ty.ptrInfo(mod);
77387792 const src_ty = Type.fromInterned(ptr_info.child);
7739 if (!src_ty.hasRuntimeBitsIgnoreComptime(mod)) return;
7793 if (!src_ty.hasRuntimeBitsIgnoreComptime(pt)) return;
77407794
77417795 const limb_abi_size: u16 = @min(ptr_info.packed_offset.host_size, 8);
77427796 const limb_abi_bits = limb_abi_size * 8;
7743 const limb_ty = try mod.intType(.unsigned, limb_abi_bits);
7797 const limb_ty = try pt.intType(.unsigned, limb_abi_bits);
77447798
7745 const src_bit_size = src_ty.bitSize(mod);
7799 const src_bit_size = src_ty.bitSize(pt);
77467800 const ptr_bit_off = ptr_info.packed_offset.bit_offset + switch (ptr_info.flags.vector_index) {
77477801 .none => 0,
77487802 .runtime => unreachable,
......@@ -7827,7 +7881,7 @@ fn packedStore(self: *Self, ptr_ty: Type, ptr_mcv: MCValue, src_mcv: MCValue) In
78277881 limb_mem,
78287882 registerAlias(tmp_reg, limb_abi_size),
78297883 );
7830 } else return self.fail("TODO: implement packed store of {}", .{src_ty.fmt(mod)});
7884 } else return self.fail("TODO: implement packed store of {}", .{src_ty.fmt(pt)});
78317885 }
78327886}
78337887
......@@ -7838,9 +7892,10 @@ fn store(
78387892 src_mcv: MCValue,
78397893 opts: CopyOptions,
78407894) InnerError!void {
7841 const mod = self.bin_file.comp.module.?;
7895 const pt = self.pt;
7896 const mod = pt.zcu;
78427897 const src_ty = ptr_ty.childType(mod);
7843 if (!src_ty.hasRuntimeBitsIgnoreComptime(mod)) return;
7898 if (!src_ty.hasRuntimeBitsIgnoreComptime(pt)) return;
78447899 switch (ptr_mcv) {
78457900 .none,
78467901 .unreach,
......@@ -7880,7 +7935,8 @@ fn store(
78807935}
78817936
78827937fn airStore(self: *Self, inst: Air.Inst.Index, safety: bool) !void {
7883 const mod = self.bin_file.comp.module.?;
7938 const pt = self.pt;
7939 const mod = pt.zcu;
78847940 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
78857941
78867942 result: {
......@@ -7918,15 +7974,16 @@ fn airStructFieldPtrIndex(self: *Self, inst: Air.Inst.Index, index: u8) !void {
79187974}
79197975
79207976fn fieldPtr(self: *Self, inst: Air.Inst.Index, operand: Air.Inst.Ref, index: u32) !MCValue {
7921 const mod = self.bin_file.comp.module.?;
7977 const pt = self.pt;
7978 const mod = pt.zcu;
79227979 const ptr_field_ty = self.typeOfIndex(inst);
79237980 const ptr_container_ty = self.typeOf(operand);
79247981 const container_ty = ptr_container_ty.childType(mod);
79257982
79267983 const field_off: i32 = switch (container_ty.containerLayout(mod)) {
7927 .auto, .@"extern" => @intCast(container_ty.structFieldOffset(index, mod)),
7984 .auto, .@"extern" => @intCast(container_ty.structFieldOffset(index, pt)),
79287985 .@"packed" => @divExact(@as(i32, ptr_container_ty.ptrInfo(mod).packed_offset.bit_offset) +
7929 (if (mod.typeToStruct(container_ty)) |struct_obj| mod.structPackedFieldBitOffset(struct_obj, index) else 0) -
7986 (if (mod.typeToStruct(container_ty)) |struct_obj| pt.structPackedFieldBitOffset(struct_obj, index) else 0) -
79307987 ptr_field_ty.ptrInfo(mod).packed_offset.bit_offset, 8),
79317988 };
79327989
......@@ -7940,7 +7997,8 @@ fn fieldPtr(self: *Self, inst: Air.Inst.Index, operand: Air.Inst.Ref, index: u32
79407997}
79417998
79427999fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
7943 const mod = self.bin_file.comp.module.?;
8000 const pt = self.pt;
8001 const mod = pt.zcu;
79448002 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
79458003 const extra = self.air.extraData(Air.StructField, ty_pl.payload).data;
79468004 const result: MCValue = result: {
......@@ -7950,14 +8008,14 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
79508008 const container_ty = self.typeOf(operand);
79518009 const container_rc = self.regClassForType(container_ty);
79528010 const field_ty = container_ty.structFieldType(index, mod);
7953 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) break :result .none;
8011 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) break :result .none;
79548012 const field_rc = self.regClassForType(field_ty);
79558013 const field_is_gp = field_rc.supersetOf(abi.RegisterClass.gp);
79568014
79578015 const src_mcv = try self.resolveInst(operand);
79588016 const field_off: u32 = switch (container_ty.containerLayout(mod)) {
7959 .auto, .@"extern" => @intCast(container_ty.structFieldOffset(extra.field_index, mod) * 8),
7960 .@"packed" => if (mod.typeToStruct(container_ty)) |struct_obj| mod.structPackedFieldBitOffset(struct_obj, extra.field_index) else 0,
8017 .auto, .@"extern" => @intCast(container_ty.structFieldOffset(extra.field_index, pt) * 8),
8018 .@"packed" => if (mod.typeToStruct(container_ty)) |struct_obj| pt.structPackedFieldBitOffset(struct_obj, extra.field_index) else 0,
79618019 };
79628020
79638021 switch (src_mcv) {
......@@ -7988,7 +8046,7 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
79888046 );
79898047 }
79908048 if (abi.RegisterClass.gp.isSet(RegisterManager.indexOfRegIntoTracked(dst_reg).?) and
7991 container_ty.abiSize(mod) * 8 > field_ty.bitSize(mod))
8049 container_ty.abiSize(pt) * 8 > field_ty.bitSize(pt))
79928050 try self.truncateRegister(field_ty, dst_reg);
79938051
79948052 break :result if (field_off == 0 or field_rc.supersetOf(abi.RegisterClass.gp))
......@@ -8000,7 +8058,7 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
80008058 const src_regs_lock = self.register_manager.lockRegsAssumeUnused(2, src_regs);
80018059 defer for (src_regs_lock) |lock| self.register_manager.unlockReg(lock);
80028060
8003 const field_bit_size: u32 = @intCast(field_ty.bitSize(mod));
8061 const field_bit_size: u32 = @intCast(field_ty.bitSize(pt));
80048062 const src_reg = if (field_off + field_bit_size <= 64)
80058063 src_regs[0]
80068064 else if (field_off >= 64)
......@@ -8044,7 +8102,7 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
80448102 }
80458103
80468104 if (field_bit_size < 128) try self.truncateRegister(
8047 try mod.intType(.unsigned, @intCast(field_bit_size - 64)),
8105 try pt.intType(.unsigned, @intCast(field_bit_size - 64)),
80488106 dst_regs[1],
80498107 );
80508108 break :result if (field_rc.supersetOf(abi.RegisterClass.gp))
......@@ -8099,14 +8157,14 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
80998157 }
81008158 },
81018159 .load_frame => |frame_addr| {
8102 const field_abi_size: u32 = @intCast(field_ty.abiSize(mod));
8160 const field_abi_size: u32 = @intCast(field_ty.abiSize(pt));
81038161 if (field_off % 8 == 0) {
81048162 const field_byte_off = @divExact(field_off, 8);
81058163 const off_mcv = src_mcv.address().offset(@intCast(field_byte_off)).deref();
8106 const field_bit_size = field_ty.bitSize(mod);
8164 const field_bit_size = field_ty.bitSize(pt);
81078165
81088166 if (field_abi_size <= 8) {
8109 const int_ty = try mod.intType(
8167 const int_ty = try pt.intType(
81108168 if (field_ty.isAbiInt(mod)) field_ty.intInfo(mod).signedness else .unsigned,
81118169 @intCast(field_bit_size),
81128170 );
......@@ -8127,7 +8185,7 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
81278185 try self.copyToRegisterWithInstTracking(inst, field_ty, dst_mcv);
81288186 }
81298187
8130 const container_abi_size: u32 = @intCast(container_ty.abiSize(mod));
8188 const container_abi_size: u32 = @intCast(container_ty.abiSize(pt));
81318189 const dst_mcv = if (field_byte_off + field_abi_size <= container_abi_size and
81328190 self.reuseOperand(inst, operand, 0, src_mcv))
81338191 off_mcv
......@@ -8228,16 +8286,17 @@ fn airStructFieldVal(self: *Self, inst: Air.Inst.Index) !void {
82288286}
82298287
82308288fn airFieldParentPtr(self: *Self, inst: Air.Inst.Index) !void {
8231 const mod = self.bin_file.comp.module.?;
8289 const pt = self.pt;
8290 const mod = pt.zcu;
82328291 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
82338292 const extra = self.air.extraData(Air.FieldParentPtr, ty_pl.payload).data;
82348293
82358294 const inst_ty = self.typeOfIndex(inst);
82368295 const parent_ty = inst_ty.childType(mod);
82378296 const field_off: i32 = switch (parent_ty.containerLayout(mod)) {
8238 .auto, .@"extern" => @intCast(parent_ty.structFieldOffset(extra.field_index, mod)),
8297 .auto, .@"extern" => @intCast(parent_ty.structFieldOffset(extra.field_index, pt)),
82398298 .@"packed" => @divExact(@as(i32, inst_ty.ptrInfo(mod).packed_offset.bit_offset) +
8240 (if (mod.typeToStruct(parent_ty)) |struct_obj| mod.structPackedFieldBitOffset(struct_obj, extra.field_index) else 0) -
8299 (if (mod.typeToStruct(parent_ty)) |struct_obj| pt.structPackedFieldBitOffset(struct_obj, extra.field_index) else 0) -
82418300 self.typeOf(extra.field_ptr).ptrInfo(mod).packed_offset.bit_offset, 8),
82428301 };
82438302
......@@ -8252,10 +8311,11 @@ fn airFieldParentPtr(self: *Self, inst: Air.Inst.Index) !void {
82528311}
82538312
82548313fn genUnOp(self: *Self, maybe_inst: ?Air.Inst.Index, tag: Air.Inst.Tag, src_air: Air.Inst.Ref) !MCValue {
8255 const mod = self.bin_file.comp.module.?;
8314 const pt = self.pt;
8315 const mod = pt.zcu;
82568316 const src_ty = self.typeOf(src_air);
82578317 if (src_ty.zigTypeTag(mod) == .Vector)
8258 return self.fail("TODO implement genUnOp for {}", .{src_ty.fmt(mod)});
8318 return self.fail("TODO implement genUnOp for {}", .{src_ty.fmt(pt)});
82598319
82608320 var src_mcv = try self.resolveInst(src_air);
82618321 switch (src_mcv) {
......@@ -8290,7 +8350,7 @@ fn genUnOp(self: *Self, maybe_inst: ?Air.Inst.Index, tag: Air.Inst.Tag, src_air:
82908350 };
82918351 defer if (dst_lock) |lock| self.register_manager.unlockReg(lock);
82928352
8293 const abi_size: u16 = @intCast(src_ty.abiSize(mod));
8353 const abi_size: u16 = @intCast(src_ty.abiSize(pt));
82948354 switch (tag) {
82958355 .not => {
82968356 const limb_abi_size: u16 = @min(abi_size, 8);
......@@ -8304,7 +8364,7 @@ fn genUnOp(self: *Self, maybe_inst: ?Air.Inst.Index, tag: Air.Inst.Tag, src_air:
83048364 .signed => abi_size * 8,
83058365 .unsigned => int_info.bits,
83068366 } - byte_off * 8, limb_abi_size * 8));
8307 const limb_ty = try mod.intType(int_info.signedness, limb_bits);
8367 const limb_ty = try pt.intType(int_info.signedness, limb_bits);
83088368 const limb_mcv = switch (byte_off) {
83098369 0 => dst_mcv,
83108370 else => dst_mcv.address().offset(byte_off).deref(),
......@@ -8340,9 +8400,9 @@ fn genUnOp(self: *Self, maybe_inst: ?Air.Inst.Index, tag: Air.Inst.Tag, src_air:
83408400}
83418401
83428402fn genUnOpMir(self: *Self, mir_tag: Mir.Inst.FixedTag, dst_ty: Type, dst_mcv: MCValue) !void {
8343 const mod = self.bin_file.comp.module.?;
8344 const abi_size: u32 = @intCast(dst_ty.abiSize(mod));
8345 if (abi_size > 8) return self.fail("TODO implement {} for {}", .{ mir_tag, dst_ty.fmt(mod) });
8403 const pt = self.pt;
8404 const abi_size: u32 = @intCast(dst_ty.abiSize(pt));
8405 if (abi_size > 8) return self.fail("TODO implement {} for {}", .{ mir_tag, dst_ty.fmt(pt) });
83468406 switch (dst_mcv) {
83478407 .none,
83488408 .unreach,
......@@ -8389,9 +8449,9 @@ fn genShiftBinOpMir(
83898449 rhs_ty: Type,
83908450 rhs_mcv: MCValue,
83918451) !void {
8392 const mod = self.bin_file.comp.module.?;
8393 const abi_size: u32 = @intCast(lhs_ty.abiSize(mod));
8394 const shift_abi_size: u32 = @intCast(rhs_ty.abiSize(mod));
8452 const pt = self.pt;
8453 const abi_size: u32 = @intCast(lhs_ty.abiSize(pt));
8454 const shift_abi_size: u32 = @intCast(rhs_ty.abiSize(pt));
83958455 try self.spillEflagsIfOccupied();
83968456
83978457 if (abi_size > 16) {
......@@ -9046,9 +9106,10 @@ fn genShiftBinOp(
90469106 lhs_ty: Type,
90479107 rhs_ty: Type,
90489108) !MCValue {
9049 const mod = self.bin_file.comp.module.?;
9109 const pt = self.pt;
9110 const mod = pt.zcu;
90509111 if (lhs_ty.zigTypeTag(mod) == .Vector) return self.fail("TODO implement genShiftBinOp for {}", .{
9051 lhs_ty.fmt(mod),
9112 lhs_ty.fmt(pt),
90529113 });
90539114
90549115 try self.register_manager.getKnownReg(.rcx, null);
......@@ -9104,13 +9165,14 @@ fn genMulDivBinOp(
91049165 lhs_mcv: MCValue,
91059166 rhs_mcv: MCValue,
91069167) !MCValue {
9107 const mod = self.bin_file.comp.module.?;
9168 const pt = self.pt;
9169 const mod = pt.zcu;
91089170 if (dst_ty.zigTypeTag(mod) == .Vector or dst_ty.zigTypeTag(mod) == .Float) return self.fail(
91099171 "TODO implement genMulDivBinOp for {s} from {} to {}",
9110 .{ @tagName(tag), src_ty.fmt(mod), dst_ty.fmt(mod) },
9172 .{ @tagName(tag), src_ty.fmt(pt), dst_ty.fmt(pt) },
91119173 );
9112 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(mod));
9113 const src_abi_size: u32 = @intCast(src_ty.abiSize(mod));
9174 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(pt));
9175 const src_abi_size: u32 = @intCast(src_ty.abiSize(pt));
91149176
91159177 assert(self.register_manager.isRegFree(.rax));
91169178 assert(self.register_manager.isRegFree(.rcx));
......@@ -9299,13 +9361,13 @@ fn genMulDivBinOp(
92999361 .signed => {},
93009362 .unsigned => {
93019363 const dst_mcv = try self.allocRegOrMemAdvanced(dst_ty, maybe_inst, false);
9302 const manyptr_u32_ty = try mod.ptrType(.{
9364 const manyptr_u32_ty = try pt.ptrType(.{
93039365 .child = .u32_type,
93049366 .flags = .{
93059367 .size = .Many,
93069368 },
93079369 });
9308 const manyptr_const_u32_ty = try mod.ptrType(.{
9370 const manyptr_const_u32_ty = try pt.ptrType(.{
93099371 .child = .u32_type,
93109372 .flags = .{
93119373 .size = .Many,
......@@ -9348,7 +9410,7 @@ fn genMulDivBinOp(
93489410 }
93499411 return self.fail(
93509412 "TODO implement genMulDivBinOp for {s} from {} to {}",
9351 .{ @tagName(tag), src_ty.fmt(mod), dst_ty.fmt(mod) },
9413 .{ @tagName(tag), src_ty.fmt(pt), dst_ty.fmt(pt) },
93529414 );
93539415 }
93549416 const ty = if (dst_abi_size <= 8) dst_ty else src_ty;
......@@ -9515,10 +9577,11 @@ fn genBinOp(
95159577 lhs_air: Air.Inst.Ref,
95169578 rhs_air: Air.Inst.Ref,
95179579) !MCValue {
9518 const mod = self.bin_file.comp.module.?;
9580 const pt = self.pt;
9581 const mod = pt.zcu;
95199582 const lhs_ty = self.typeOf(lhs_air);
95209583 const rhs_ty = self.typeOf(rhs_air);
9521 const abi_size: u32 = @intCast(lhs_ty.abiSize(mod));
9584 const abi_size: u32 = @intCast(lhs_ty.abiSize(pt));
95229585
95239586 if (lhs_ty.isRuntimeFloat()) libcall: {
95249587 const float_bits = lhs_ty.floatBits(self.target.*);
......@@ -9556,7 +9619,7 @@ fn genBinOp(
95569619 floatLibcAbiSuffix(lhs_ty),
95579620 }),
95589621 else => return self.fail("TODO implement genBinOp for {s} {}", .{
9559 @tagName(air_tag), lhs_ty.fmt(mod),
9622 @tagName(air_tag), lhs_ty.fmt(pt),
95609623 }),
95619624 } catch unreachable;
95629625 const result = try self.genCall(.{ .lib = .{
......@@ -9668,7 +9731,7 @@ fn genBinOp(
96689731 break :adjusted .{ .register = dst_reg };
96699732 },
96709733 80, 128 => return self.fail("TODO implement genBinOp for {s} of {}", .{
9671 @tagName(air_tag), lhs_ty.fmt(mod),
9734 @tagName(air_tag), lhs_ty.fmt(pt),
96729735 }),
96739736 else => unreachable,
96749737 };
......@@ -9700,8 +9763,8 @@ fn genBinOp(
97009763 };
97019764 if (sse_op and ((lhs_ty.scalarType(mod).isRuntimeFloat() and
97029765 lhs_ty.scalarType(mod).floatBits(self.target.*) == 80) or
9703 lhs_ty.abiSize(mod) > @as(u6, if (self.hasFeature(.avx)) 32 else 16)))
9704 return self.fail("TODO implement genBinOp for {s} {}", .{ @tagName(air_tag), lhs_ty.fmt(mod) });
9766 lhs_ty.abiSize(pt) > @as(u6, if (self.hasFeature(.avx)) 32 else 16)))
9767 return self.fail("TODO implement genBinOp for {s} {}", .{ @tagName(air_tag), lhs_ty.fmt(pt) });
97059768
97069769 const maybe_mask_reg = switch (air_tag) {
97079770 else => null,
......@@ -9857,7 +9920,7 @@ fn genBinOp(
98579920 const tmp_lock = self.register_manager.lockRegAssumeUnused(tmp_reg);
98589921 defer self.register_manager.unlockReg(tmp_lock);
98599922
9860 const elem_size = lhs_ty.elemType2(mod).abiSize(mod);
9923 const elem_size = lhs_ty.elemType2(mod).abiSize(pt);
98619924 try self.genIntMulComplexOpMir(rhs_ty, tmp_mcv, .{ .immediate = elem_size });
98629925 try self.genBinOpMir(
98639926 switch (air_tag) {
......@@ -10003,7 +10066,7 @@ fn genBinOp(
1000310066 },
1000410067 };
1000510068
10006 const cmov_abi_size = @max(@as(u32, @intCast(lhs_ty.abiSize(mod))), 2);
10069 const cmov_abi_size = @max(@as(u32, @intCast(lhs_ty.abiSize(pt))), 2);
1000710070 const tmp_reg = switch (dst_mcv) {
1000810071 .register => |reg| reg,
1000910072 else => try self.copyToTmpRegister(lhs_ty, dst_mcv),
......@@ -10082,7 +10145,7 @@ fn genBinOp(
1008210145 },
1008310146
1008410147 else => return self.fail("TODO implement genBinOp for {s} {}", .{
10085 @tagName(air_tag), lhs_ty.fmt(mod),
10148 @tagName(air_tag), lhs_ty.fmt(pt),
1008610149 }),
1008710150 }
1008810151 return dst_mcv;
......@@ -10835,7 +10898,7 @@ fn genBinOp(
1083510898 },
1083610899 },
1083710900 }) orelse return self.fail("TODO implement genBinOp for {s} {}", .{
10838 @tagName(air_tag), lhs_ty.fmt(mod),
10901 @tagName(air_tag), lhs_ty.fmt(pt),
1083910902 });
1084010903
1084110904 const lhs_copy_reg = if (maybe_mask_reg) |_| registerAlias(
......@@ -10978,7 +11041,7 @@ fn genBinOp(
1097811041 },
1097911042 else => unreachable,
1098011043 }) orelse return self.fail("TODO implement genBinOp for {s} {}", .{
10981 @tagName(air_tag), lhs_ty.fmt(mod),
11044 @tagName(air_tag), lhs_ty.fmt(pt),
1098211045 }),
1098311046 mask_reg,
1098411047 rhs_copy_reg,
......@@ -11010,7 +11073,7 @@ fn genBinOp(
1101011073 },
1101111074 else => unreachable,
1101211075 }) orelse return self.fail("TODO implement genBinOp for {s} {}", .{
11013 @tagName(air_tag), lhs_ty.fmt(mod),
11076 @tagName(air_tag), lhs_ty.fmt(pt),
1101411077 }),
1101511078 dst_reg,
1101611079 dst_reg,
......@@ -11046,7 +11109,7 @@ fn genBinOp(
1104611109 },
1104711110 else => unreachable,
1104811111 }) orelse return self.fail("TODO implement genBinOp for {s} {}", .{
11049 @tagName(air_tag), lhs_ty.fmt(mod),
11112 @tagName(air_tag), lhs_ty.fmt(pt),
1105011113 }),
1105111114 mask_reg,
1105211115 mask_reg,
......@@ -11077,7 +11140,7 @@ fn genBinOp(
1107711140 },
1107811141 else => unreachable,
1107911142 }) orelse return self.fail("TODO implement genBinOp for {s} {}", .{
11080 @tagName(air_tag), lhs_ty.fmt(mod),
11143 @tagName(air_tag), lhs_ty.fmt(pt),
1108111144 }),
1108211145 dst_reg,
1108311146 lhs_copy_reg.?,
......@@ -11107,7 +11170,7 @@ fn genBinOp(
1110711170 },
1110811171 else => unreachable,
1110911172 }) orelse return self.fail("TODO implement genBinOp for {s} {}", .{
11110 @tagName(air_tag), lhs_ty.fmt(mod),
11173 @tagName(air_tag), lhs_ty.fmt(pt),
1111111174 });
1111211175 try self.asmRegisterRegister(.{ mir_fixes, .@"and" }, dst_reg, mask_reg);
1111311176 try self.asmRegisterRegister(.{ mir_fixes, .andn }, mask_reg, lhs_copy_reg.?);
......@@ -11125,8 +11188,8 @@ fn genBinOp(
1112511188 .cmp_gte,
1112611189 .cmp_neq,
1112711190 => {
11128 const unsigned_ty = try lhs_ty.toUnsigned(mod);
11129 const not_mcv = try self.genTypedValue(try unsigned_ty.maxInt(mod, unsigned_ty));
11191 const unsigned_ty = try lhs_ty.toUnsigned(pt);
11192 const not_mcv = try self.genTypedValue(try unsigned_ty.maxInt(pt, unsigned_ty));
1113011193 const not_mem: Memory = if (not_mcv.isMemory())
1113111194 try not_mcv.mem(self, Memory.Size.fromSize(abi_size))
1113211195 else
......@@ -11195,8 +11258,9 @@ fn genBinOpMir(
1119511258 dst_mcv: MCValue,
1119611259 src_mcv: MCValue,
1119711260) !void {
11198 const mod = self.bin_file.comp.module.?;
11199 const abi_size: u32 = @intCast(ty.abiSize(mod));
11261 const pt = self.pt;
11262 const mod = pt.zcu;
11263 const abi_size: u32 = @intCast(ty.abiSize(pt));
1120011264 try self.spillEflagsIfOccupied();
1120111265 switch (dst_mcv) {
1120211266 .none,
......@@ -11358,7 +11422,7 @@ fn genBinOpMir(
1135811422 .load_got,
1135911423 .load_tlv,
1136011424 => {
11361 const ptr_ty = try mod.singleConstPtrType(ty);
11425 const ptr_ty = try pt.singleConstPtrType(ty);
1136211426 const addr_reg = try self.copyToTmpRegister(ptr_ty, src_mcv.address());
1136311427 return self.genBinOpMir(mir_limb_tag, ty, dst_mcv, .{
1136411428 .indirect = .{ .reg = addr_reg, .off = off },
......@@ -11619,8 +11683,8 @@ fn genBinOpMir(
1161911683/// Performs multi-operand integer multiplication between dst_mcv and src_mcv, storing the result in dst_mcv.
1162011684/// Does not support byte-size operands.
1162111685fn genIntMulComplexOpMir(self: *Self, dst_ty: Type, dst_mcv: MCValue, src_mcv: MCValue) InnerError!void {
11622 const mod = self.bin_file.comp.module.?;
11623 const abi_size: u32 = @intCast(dst_ty.abiSize(mod));
11686 const pt = self.pt;
11687 const abi_size: u32 = @intCast(dst_ty.abiSize(pt));
1162411688 try self.spillEflagsIfOccupied();
1162511689 switch (dst_mcv) {
1162611690 .none,
......@@ -11746,7 +11810,8 @@ fn genIntMulComplexOpMir(self: *Self, dst_ty: Type, dst_mcv: MCValue, src_mcv: M
1174611810}
1174711811
1174811812fn airArg(self: *Self, inst: Air.Inst.Index) !void {
11749 const mod = self.bin_file.comp.module.?;
11813 const pt = self.pt;
11814 const mod = pt.zcu;
1175011815 // skip zero-bit arguments as they don't have a corresponding arg instruction
1175111816 var arg_index = self.arg_index;
1175211817 while (self.args[arg_index] == .none) arg_index += 1;
......@@ -11808,7 +11873,7 @@ fn airArg(self: *Self, inst: Air.Inst.Index) !void {
1180811873 try self.genInlineMemset(
1180911874 dst_mcv.address().offset(@intFromBool(regs_frame_addr.regs > 0)),
1181011875 .{ .immediate = 0 },
11811 .{ .immediate = arg_ty.abiSize(mod) - @intFromBool(regs_frame_addr.regs > 0) },
11876 .{ .immediate = arg_ty.abiSize(pt) - @intFromBool(regs_frame_addr.regs > 0) },
1181211877 .{},
1181311878 );
1181411879
......@@ -11865,7 +11930,8 @@ fn airArg(self: *Self, inst: Air.Inst.Index) !void {
1186511930}
1186611931
1186711932fn genArgDbgInfo(self: Self, ty: Type, name: [:0]const u8, mcv: MCValue) !void {
11868 const mod = self.bin_file.comp.module.?;
11933 const pt = self.pt;
11934 const mod = pt.zcu;
1186911935 switch (self.debug_output) {
1187011936 .dwarf => |dw| {
1187111937 const loc: link.File.Dwarf.DeclState.DbgInfoLoc = switch (mcv) {
......@@ -11901,7 +11967,8 @@ fn genVarDbgInfo(
1190111967 mcv: MCValue,
1190211968 name: [:0]const u8,
1190311969) !void {
11904 const mod = self.bin_file.comp.module.?;
11970 const pt = self.pt;
11971 const mod = pt.zcu;
1190511972 const is_ptr = switch (tag) {
1190611973 .dbg_var_ptr => true,
1190711974 .dbg_var_val => false,
......@@ -12020,7 +12087,8 @@ fn genCall(self: *Self, info: union(enum) {
1202012087 callee: []const u8,
1202112088 },
1202212089}, arg_types: []const Type, args: []const MCValue) !MCValue {
12023 const mod = self.bin_file.comp.module.?;
12090 const pt = self.pt;
12091 const mod = pt.zcu;
1202412092
1202512093 const fn_ty = switch (info) {
1202612094 .air => |callee| fn_info: {
......@@ -12031,7 +12099,7 @@ fn genCall(self: *Self, info: union(enum) {
1203112099 else => unreachable,
1203212100 };
1203312101 },
12034 .lib => |lib| try mod.funcType(.{
12102 .lib => |lib| try pt.funcType(.{
1203512103 .param_types = lib.param_types,
1203612104 .return_type = lib.return_type,
1203712105 .cc = .C,
......@@ -12101,7 +12169,7 @@ fn genCall(self: *Self, info: union(enum) {
1210112169 try reg_locks.appendSlice(&self.register_manager.lockRegs(2, regs));
1210212170 },
1210312171 .indirect => |reg_off| {
12104 frame_index.* = try self.allocFrameIndex(FrameAlloc.initType(arg_ty, mod));
12172 frame_index.* = try self.allocFrameIndex(FrameAlloc.initType(arg_ty, pt));
1210512173 try self.genSetMem(.{ .frame = frame_index.* }, 0, arg_ty, src_arg, .{});
1210612174 try self.register_manager.getReg(reg_off.reg, null);
1210712175 try reg_locks.append(self.register_manager.lockReg(reg_off.reg));
......@@ -12173,7 +12241,7 @@ fn genCall(self: *Self, info: union(enum) {
1217312241 .none, .unreach => {},
1217412242 .indirect => |reg_off| {
1217512243 const ret_ty = Type.fromInterned(fn_info.return_type);
12176 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(ret_ty, mod));
12244 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(ret_ty, pt));
1217712245 try self.genSetReg(reg_off.reg, Type.usize, .{
1217812246 .lea_frame = .{ .index = frame_index, .off = -reg_off.off },
1217912247 }, .{});
......@@ -12188,14 +12256,14 @@ fn genCall(self: *Self, info: union(enum) {
1218812256 .none, .load_frame => {},
1218912257 .register => |dst_reg| switch (fn_info.cc) {
1219012258 else => try self.genSetReg(
12191 registerAlias(dst_reg, @intCast(arg_ty.abiSize(mod))),
12259 registerAlias(dst_reg, @intCast(arg_ty.abiSize(pt))),
1219212260 arg_ty,
1219312261 src_arg,
1219412262 .{},
1219512263 ),
1219612264 .C, .SysV, .Win64 => {
1219712265 const promoted_ty = self.promoteInt(arg_ty);
12198 const promoted_abi_size: u32 = @intCast(promoted_ty.abiSize(mod));
12266 const promoted_abi_size: u32 = @intCast(promoted_ty.abiSize(pt));
1219912267 const dst_alias = registerAlias(dst_reg, promoted_abi_size);
1220012268 try self.genSetReg(dst_alias, promoted_ty, src_arg, .{});
1220112269 if (promoted_ty.toIntern() != arg_ty.toIntern())
......@@ -12246,7 +12314,7 @@ fn genCall(self: *Self, info: union(enum) {
1224612314 // Due to incremental compilation, how function calls are generated depends
1224712315 // on linking.
1224812316 switch (info) {
12249 .air => |callee| if (try self.air.value(callee, mod)) |func_value| {
12317 .air => |callee| if (try self.air.value(callee, pt)) |func_value| {
1225012318 const func_key = mod.intern_pool.indexToKey(func_value.ip_index);
1225112319 switch (switch (func_key) {
1225212320 else => func_key,
......@@ -12332,7 +12400,8 @@ fn genCall(self: *Self, info: union(enum) {
1233212400}
1233312401
1233412402fn airRet(self: *Self, inst: Air.Inst.Index, safety: bool) !void {
12335 const mod = self.bin_file.comp.module.?;
12403 const pt = self.pt;
12404 const mod = pt.zcu;
1233612405 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
1233712406
1233812407 const ret_ty = self.fn_type.fnReturnType(mod);
......@@ -12387,7 +12456,8 @@ fn airRetLoad(self: *Self, inst: Air.Inst.Index) !void {
1238712456}
1238812457
1238912458fn airCmp(self: *Self, inst: Air.Inst.Index, op: math.CompareOperator) !void {
12390 const mod = self.bin_file.comp.module.?;
12459 const pt = self.pt;
12460 const mod = pt.zcu;
1239112461 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
1239212462 var ty = self.typeOf(bin_op.lhs);
1239312463 var null_compare: ?Mir.Inst.Index = null;
......@@ -12457,9 +12527,9 @@ fn airCmp(self: *Self, inst: Air.Inst.Index, op: math.CompareOperator) !void {
1245712527 },
1245812528 .Optional => if (!ty.optionalReprIsPayload(mod)) {
1245912529 const opt_ty = ty;
12460 const opt_abi_size: u31 = @intCast(opt_ty.abiSize(mod));
12530 const opt_abi_size: u31 = @intCast(opt_ty.abiSize(pt));
1246112531 ty = opt_ty.optionalChild(mod);
12462 const payload_abi_size: u31 = @intCast(ty.abiSize(mod));
12532 const payload_abi_size: u31 = @intCast(ty.abiSize(pt));
1246312533
1246412534 const temp_lhs_reg = try self.register_manager.allocReg(null, abi.RegisterClass.gp);
1246512535 const temp_lhs_lock = self.register_manager.lockRegAssumeUnused(temp_lhs_reg);
......@@ -12518,7 +12588,7 @@ fn airCmp(self: *Self, inst: Air.Inst.Index, op: math.CompareOperator) !void {
1251812588
1251912589 switch (ty.zigTypeTag(mod)) {
1252012590 else => {
12521 const abi_size: u16 = @intCast(ty.abiSize(mod));
12591 const abi_size: u16 = @intCast(ty.abiSize(pt));
1252212592 const may_flip: enum {
1252312593 may_flip,
1252412594 must_flip,
......@@ -12845,7 +12915,8 @@ fn airCmpVector(self: *Self, inst: Air.Inst.Index) !void {
1284512915}
1284612916
1284712917fn airCmpLtErrorsLen(self: *Self, inst: Air.Inst.Index) !void {
12848 const mod = self.bin_file.comp.module.?;
12918 const pt = self.pt;
12919 const mod = pt.zcu;
1284912920 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
1285012921
1285112922 const addr_reg = try self.register_manager.allocReg(null, abi.RegisterClass.gp);
......@@ -12856,7 +12927,7 @@ fn airCmpLtErrorsLen(self: *Self, inst: Air.Inst.Index) !void {
1285612927 try self.spillEflagsIfOccupied();
1285712928
1285812929 const op_ty = self.typeOf(un_op);
12859 const op_abi_size: u32 = @intCast(op_ty.abiSize(mod));
12930 const op_abi_size: u32 = @intCast(op_ty.abiSize(pt));
1286012931 const op_mcv = try self.resolveInst(un_op);
1286112932 const dst_reg = switch (op_mcv) {
1286212933 .register => |reg| reg,
......@@ -12987,8 +13058,8 @@ fn airDbgVar(self: *Self, inst: Air.Inst.Index) !void {
1298713058}
1298813059
1298913060fn genCondBrMir(self: *Self, ty: Type, mcv: MCValue) !Mir.Inst.Index {
12990 const mod = self.bin_file.comp.module.?;
12991 const abi_size = ty.abiSize(mod);
13061 const pt = self.pt;
13062 const abi_size = ty.abiSize(pt);
1299213063 switch (mcv) {
1299313064 .eflags => |cc| {
1299413065 // Here we map the opposites since the jump is to the false branch.
......@@ -13060,7 +13131,8 @@ fn airCondBr(self: *Self, inst: Air.Inst.Index) !void {
1306013131}
1306113132
1306213133fn isNull(self: *Self, inst: Air.Inst.Index, opt_ty: Type, opt_mcv: MCValue) !MCValue {
13063 const mod = self.bin_file.comp.module.?;
13134 const pt = self.pt;
13135 const mod = pt.zcu;
1306413136 switch (opt_mcv) {
1306513137 .register_overflow => |ro| return .{ .eflags = ro.eflags.negate() },
1306613138 else => {},
......@@ -13073,7 +13145,7 @@ fn isNull(self: *Self, inst: Air.Inst.Index, opt_ty: Type, opt_mcv: MCValue) !MC
1307313145 const some_info: struct { off: i32, ty: Type } = if (opt_ty.optionalReprIsPayload(mod))
1307413146 .{ .off = 0, .ty = if (pl_ty.isSlice(mod)) pl_ty.slicePtrFieldType(mod) else pl_ty }
1307513147 else
13076 .{ .off = @intCast(pl_ty.abiSize(mod)), .ty = Type.bool };
13148 .{ .off = @intCast(pl_ty.abiSize(pt)), .ty = Type.bool };
1307713149
1307813150 self.eflags_inst = inst;
1307913151 switch (opt_mcv) {
......@@ -13098,14 +13170,14 @@ fn isNull(self: *Self, inst: Air.Inst.Index, opt_ty: Type, opt_mcv: MCValue) !MC
1309813170
1309913171 .register => |opt_reg| {
1310013172 if (some_info.off == 0) {
13101 const some_abi_size: u32 = @intCast(some_info.ty.abiSize(mod));
13173 const some_abi_size: u32 = @intCast(some_info.ty.abiSize(pt));
1310213174 const alias_reg = registerAlias(opt_reg, some_abi_size);
1310313175 assert(some_abi_size * 8 == alias_reg.bitSize());
1310413176 try self.asmRegisterRegister(.{ ._, .@"test" }, alias_reg, alias_reg);
1310513177 return .{ .eflags = .z };
1310613178 }
1310713179 assert(some_info.ty.ip_index == .bool_type);
13108 const opt_abi_size: u32 = @intCast(opt_ty.abiSize(mod));
13180 const opt_abi_size: u32 = @intCast(opt_ty.abiSize(pt));
1310913181 try self.asmRegisterImmediate(
1311013182 .{ ._, .bt },
1311113183 registerAlias(opt_reg, opt_abi_size),
......@@ -13125,7 +13197,7 @@ fn isNull(self: *Self, inst: Air.Inst.Index, opt_ty: Type, opt_mcv: MCValue) !MC
1312513197 defer self.register_manager.unlockReg(addr_reg_lock);
1312613198
1312713199 try self.genSetReg(addr_reg, Type.usize, opt_mcv.address(), .{});
13128 const some_abi_size: u32 = @intCast(some_info.ty.abiSize(mod));
13200 const some_abi_size: u32 = @intCast(some_info.ty.abiSize(pt));
1312913201 try self.asmMemoryImmediate(
1313013202 .{ ._, .cmp },
1313113203 .{
......@@ -13141,7 +13213,7 @@ fn isNull(self: *Self, inst: Air.Inst.Index, opt_ty: Type, opt_mcv: MCValue) !MC
1314113213 },
1314213214
1314313215 .indirect, .load_frame => {
13144 const some_abi_size: u32 = @intCast(some_info.ty.abiSize(mod));
13216 const some_abi_size: u32 = @intCast(some_info.ty.abiSize(pt));
1314513217 try self.asmMemoryImmediate(
1314613218 .{ ._, .cmp },
1314713219 switch (opt_mcv) {
......@@ -13169,7 +13241,8 @@ fn isNull(self: *Self, inst: Air.Inst.Index, opt_ty: Type, opt_mcv: MCValue) !MC
1316913241}
1317013242
1317113243fn isNullPtr(self: *Self, inst: Air.Inst.Index, ptr_ty: Type, ptr_mcv: MCValue) !MCValue {
13172 const mod = self.bin_file.comp.module.?;
13244 const pt = self.pt;
13245 const mod = pt.zcu;
1317313246 const opt_ty = ptr_ty.childType(mod);
1317413247 const pl_ty = opt_ty.optionalChild(mod);
1317513248
......@@ -13178,7 +13251,7 @@ fn isNullPtr(self: *Self, inst: Air.Inst.Index, ptr_ty: Type, ptr_mcv: MCValue)
1317813251 const some_info: struct { off: i32, ty: Type } = if (opt_ty.optionalReprIsPayload(mod))
1317913252 .{ .off = 0, .ty = if (pl_ty.isSlice(mod)) pl_ty.slicePtrFieldType(mod) else pl_ty }
1318013253 else
13181 .{ .off = @intCast(pl_ty.abiSize(mod)), .ty = Type.bool };
13254 .{ .off = @intCast(pl_ty.abiSize(pt)), .ty = Type.bool };
1318213255
1318313256 const ptr_reg = switch (ptr_mcv) {
1318413257 .register => |reg| reg,
......@@ -13187,7 +13260,7 @@ fn isNullPtr(self: *Self, inst: Air.Inst.Index, ptr_ty: Type, ptr_mcv: MCValue)
1318713260 const ptr_lock = self.register_manager.lockReg(ptr_reg);
1318813261 defer if (ptr_lock) |lock| self.register_manager.unlockReg(lock);
1318913262
13190 const some_abi_size: u32 = @intCast(some_info.ty.abiSize(mod));
13263 const some_abi_size: u32 = @intCast(some_info.ty.abiSize(pt));
1319113264 try self.asmMemoryImmediate(
1319213265 .{ ._, .cmp },
1319313266 .{
......@@ -13205,13 +13278,14 @@ fn isNullPtr(self: *Self, inst: Air.Inst.Index, ptr_ty: Type, ptr_mcv: MCValue)
1320513278}
1320613279
1320713280fn isErr(self: *Self, maybe_inst: ?Air.Inst.Index, eu_ty: Type, eu_mcv: MCValue) !MCValue {
13208 const mod = self.bin_file.comp.module.?;
13281 const pt = self.pt;
13282 const mod = pt.zcu;
1320913283 const err_ty = eu_ty.errorUnionSet(mod);
1321013284 if (err_ty.errorSetIsEmpty(mod)) return MCValue{ .immediate = 0 }; // always false
1321113285
1321213286 try self.spillEflagsIfOccupied();
1321313287
13214 const err_off: u31 = @intCast(errUnionErrorOffset(eu_ty.errorUnionPayload(mod), mod));
13288 const err_off: u31 = @intCast(errUnionErrorOffset(eu_ty.errorUnionPayload(mod), pt));
1321513289 switch (eu_mcv) {
1321613290 .register => |reg| {
1321713291 const eu_lock = self.register_manager.lockReg(reg);
......@@ -13253,7 +13327,8 @@ fn isErr(self: *Self, maybe_inst: ?Air.Inst.Index, eu_ty: Type, eu_mcv: MCValue)
1325313327}
1325413328
1325513329fn isErrPtr(self: *Self, maybe_inst: ?Air.Inst.Index, ptr_ty: Type, ptr_mcv: MCValue) !MCValue {
13256 const mod = self.bin_file.comp.module.?;
13330 const pt = self.pt;
13331 const mod = pt.zcu;
1325713332 const eu_ty = ptr_ty.childType(mod);
1325813333 const err_ty = eu_ty.errorUnionSet(mod);
1325913334 if (err_ty.errorSetIsEmpty(mod)) return MCValue{ .immediate = 0 }; // always false
......@@ -13267,7 +13342,7 @@ fn isErrPtr(self: *Self, maybe_inst: ?Air.Inst.Index, ptr_ty: Type, ptr_mcv: MCV
1326713342 const ptr_lock = self.register_manager.lockReg(ptr_reg);
1326813343 defer if (ptr_lock) |lock| self.register_manager.unlockReg(lock);
1326913344
13270 const err_off: u31 = @intCast(errUnionErrorOffset(eu_ty.errorUnionPayload(mod), mod));
13345 const err_off: u31 = @intCast(errUnionErrorOffset(eu_ty.errorUnionPayload(mod), pt));
1327113346 try self.asmMemoryImmediate(
1327213347 .{ ._, .cmp },
1327313348 .{
......@@ -13539,12 +13614,12 @@ fn performReloc(self: *Self, reloc: Mir.Inst.Index) void {
1353913614}
1354013615
1354113616fn airBr(self: *Self, inst: Air.Inst.Index) !void {
13542 const mod = self.bin_file.comp.module.?;
13617 const pt = self.pt;
1354313618 const br = self.air.instructions.items(.data)[@intFromEnum(inst)].br;
1354413619
1354513620 const block_ty = self.typeOfIndex(br.block_inst);
1354613621 const block_unused =
13547 !block_ty.hasRuntimeBitsIgnoreComptime(mod) or self.liveness.isUnused(br.block_inst);
13622 !block_ty.hasRuntimeBitsIgnoreComptime(pt) or self.liveness.isUnused(br.block_inst);
1354813623 const block_tracking = self.inst_tracking.getPtr(br.block_inst).?;
1354913624 const block_data = self.blocks.getPtr(br.block_inst).?;
1355013625 const first_br = block_data.relocs.items.len == 0;
......@@ -13600,7 +13675,8 @@ fn airBr(self: *Self, inst: Air.Inst.Index) !void {
1360013675}
1360113676
1360213677fn airAsm(self: *Self, inst: Air.Inst.Index) !void {
13603 const mod = self.bin_file.comp.module.?;
13678 const pt = self.pt;
13679 const mod = pt.zcu;
1360413680 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
1360513681 const extra = self.air.extraData(Air.Asm, ty_pl.payload);
1360613682 const clobbers_len: u31 = @truncate(extra.data.flags);
......@@ -13664,7 +13740,7 @@ fn airAsm(self: *Self, inst: Air.Inst.Index) !void {
1366413740 'x' => abi.RegisterClass.sse,
1366513741 else => unreachable,
1366613742 }) orelse return self.fail("ran out of registers lowering inline asm", .{}),
13667 @intCast(ty.abiSize(mod)),
13743 @intCast(ty.abiSize(pt)),
1366813744 )
1366913745 else if (mem.eql(u8, rest, "m"))
1367013746 if (output != .none) null else return self.fail(
......@@ -13734,7 +13810,7 @@ fn airAsm(self: *Self, inst: Air.Inst.Index) !void {
1373413810 break :arg input_mcv;
1373513811 const reg = try self.register_manager.allocReg(null, rc);
1373613812 try self.genSetReg(reg, ty, input_mcv, .{});
13737 break :arg .{ .register = registerAlias(reg, @intCast(ty.abiSize(mod))) };
13813 break :arg .{ .register = registerAlias(reg, @intCast(ty.abiSize(pt))) };
1373813814 } else if (mem.eql(u8, constraint, "i") or mem.eql(u8, constraint, "n"))
1373913815 switch (input_mcv) {
1374013816 .immediate => |imm| .{ .immediate = imm },
......@@ -14310,18 +14386,19 @@ const MoveStrategy = union(enum) {
1431014386 }
1431114387};
1431214388fn moveStrategy(self: *Self, ty: Type, class: Register.Class, aligned: bool) !MoveStrategy {
14313 const mod = self.bin_file.comp.module.?;
14389 const pt = self.pt;
14390 const mod = pt.zcu;
1431414391 switch (class) {
1431514392 .general_purpose, .segment => return .{ .move = .{ ._, .mov } },
1431614393 .x87 => return .x87_load_store,
1431714394 .mmx => {},
1431814395 .sse => switch (ty.zigTypeTag(mod)) {
1431914396 else => {
14320 const classes = mem.sliceTo(&abi.classifySystemV(ty, mod, self.target.*, .other), .none);
14397 const classes = mem.sliceTo(&abi.classifySystemV(ty, pt, self.target.*, .other), .none);
1432114398 assert(std.mem.indexOfNone(abi.Class, classes, &.{
1432214399 .integer, .sse, .sseup, .memory, .float, .float_combine,
1432314400 }) == null);
14324 const abi_size = ty.abiSize(mod);
14401 const abi_size = ty.abiSize(pt);
1432514402 if (abi_size < 4 or
1432614403 std.mem.indexOfScalar(abi.Class, classes, .integer) != null) switch (abi_size) {
1432714404 1 => if (self.hasFeature(.avx)) return .{ .vex_insert_extract = .{
......@@ -14532,7 +14609,7 @@ fn moveStrategy(self: *Self, ty: Type, class: Register.Class, aligned: bool) !Mo
1453214609 },
1453314610 .ip => {},
1453414611 }
14535 return self.fail("TODO moveStrategy for {}", .{ty.fmt(mod)});
14612 return self.fail("TODO moveStrategy for {}", .{ty.fmt(pt)});
1453614613}
1453714614
1453814615const CopyOptions = struct {
......@@ -14540,7 +14617,7 @@ const CopyOptions = struct {
1454014617};
1454114618
1454214619fn genCopy(self: *Self, ty: Type, dst_mcv: MCValue, src_mcv: MCValue, opts: CopyOptions) InnerError!void {
14543 const mod = self.bin_file.comp.module.?;
14620 const pt = self.pt;
1454414621
1454514622 const src_lock = if (src_mcv.getReg()) |reg| self.register_manager.lockReg(reg) else null;
1454614623 defer if (src_lock) |lock| self.register_manager.unlockReg(lock);
......@@ -14601,7 +14678,7 @@ fn genCopy(self: *Self, ty: Type, dst_mcv: MCValue, src_mcv: MCValue, opts: Copy
1460114678 opts,
1460214679 ),
1460314680 else => return self.fail("TODO implement genCopy for {s} of {}", .{
14604 @tagName(src_mcv), ty.fmt(mod),
14681 @tagName(src_mcv), ty.fmt(pt),
1460514682 }),
1460614683 };
1460714684 defer if (src_info) |info| self.register_manager.unlockReg(info.addr_lock);
......@@ -14617,7 +14694,7 @@ fn genCopy(self: *Self, ty: Type, dst_mcv: MCValue, src_mcv: MCValue, opts: Copy
1461714694 } },
1461814695 else => unreachable,
1461914696 }, opts);
14620 part_disp += @intCast(dst_ty.abiSize(mod));
14697 part_disp += @intCast(dst_ty.abiSize(pt));
1462114698 }
1462214699 },
1462314700 .indirect => |reg_off| try self.genSetMem(
......@@ -14658,9 +14735,10 @@ fn genSetReg(
1465814735 src_mcv: MCValue,
1465914736 opts: CopyOptions,
1466014737) InnerError!void {
14661 const mod = self.bin_file.comp.module.?;
14662 const abi_size: u32 = @intCast(ty.abiSize(mod));
14663 if (ty.bitSize(mod) > dst_reg.bitSize())
14738 const pt = self.pt;
14739 const mod = pt.zcu;
14740 const abi_size: u32 = @intCast(ty.abiSize(pt));
14741 if (ty.bitSize(pt) > dst_reg.bitSize())
1466414742 return self.fail("genSetReg called with a value larger than dst_reg", .{});
1466514743 switch (src_mcv) {
1466614744 .none,
......@@ -14686,7 +14764,7 @@ fn genSetReg(
1468614764 ),
1468714765 else => unreachable,
1468814766 },
14689 .segment, .x87, .mmx, .sse => try self.genSetReg(dst_reg, ty, try self.genTypedValue(try mod.undefValue(ty)), opts),
14767 .segment, .x87, .mmx, .sse => try self.genSetReg(dst_reg, ty, try self.genTypedValue(try pt.undefValue(ty)), opts),
1469014768 .ip => unreachable,
1469114769 },
1469214770 .eflags => |cc| try self.asmSetccRegister(cc, dst_reg.to8()),
......@@ -14797,7 +14875,7 @@ fn genSetReg(
1479714875 80 => null,
1479814876 else => unreachable,
1479914877 },
14800 }) orelse return self.fail("TODO implement genSetReg for {}", .{ty.fmt(mod)}),
14878 }) orelse return self.fail("TODO implement genSetReg for {}", .{ty.fmt(pt)}),
1480114879 registerAlias(dst_reg, abi_size),
1480214880 registerAlias(src_reg, abi_size),
1480314881 ),
......@@ -14847,7 +14925,7 @@ fn genSetReg(
1484714925 return (try self.moveStrategy(
1484814926 ty,
1484914927 dst_reg.class(),
14850 ty.abiAlignment(mod).check(@as(u32, @bitCast(small_addr))),
14928 ty.abiAlignment(pt).check(@as(u32, @bitCast(small_addr))),
1485114929 )).read(self, registerAlias(dst_reg, abi_size), .{
1485214930 .base = .{ .reg = .ds },
1485314931 .mod = .{ .rm = .{
......@@ -14967,8 +15045,9 @@ fn genSetMem(
1496715045 src_mcv: MCValue,
1496815046 opts: CopyOptions,
1496915047) InnerError!void {
14970 const mod = self.bin_file.comp.module.?;
14971 const abi_size: u32 = @intCast(ty.abiSize(mod));
15048 const pt = self.pt;
15049 const mod = pt.zcu;
15050 const abi_size: u32 = @intCast(ty.abiSize(pt));
1497215051 const dst_ptr_mcv: MCValue = switch (base) {
1497315052 .none => .{ .immediate = @bitCast(@as(i64, disp)) },
1497415053 .reg => |base_reg| .{ .register_offset = .{ .reg = base_reg, .off = disp } },
......@@ -15094,21 +15173,21 @@ fn genSetMem(
1509415173 var part_disp: i32 = disp;
1509515174 for (try self.splitType(ty), src_regs) |src_ty, src_reg| {
1509615175 try self.genSetMem(base, part_disp, src_ty, .{ .register = src_reg }, opts);
15097 part_disp += @intCast(src_ty.abiSize(mod));
15176 part_disp += @intCast(src_ty.abiSize(pt));
1509815177 }
1509915178 },
1510015179 .register_overflow => |ro| switch (ty.zigTypeTag(mod)) {
1510115180 .Struct => {
1510215181 try self.genSetMem(
1510315182 base,
15104 disp + @as(i32, @intCast(ty.structFieldOffset(0, mod))),
15183 disp + @as(i32, @intCast(ty.structFieldOffset(0, pt))),
1510515184 ty.structFieldType(0, mod),
1510615185 .{ .register = ro.reg },
1510715186 opts,
1510815187 );
1510915188 try self.genSetMem(
1511015189 base,
15111 disp + @as(i32, @intCast(ty.structFieldOffset(1, mod))),
15190 disp + @as(i32, @intCast(ty.structFieldOffset(1, pt))),
1511215191 ty.structFieldType(1, mod),
1511315192 .{ .eflags = ro.eflags },
1511415193 opts,
......@@ -15120,14 +15199,14 @@ fn genSetMem(
1512015199 try self.genSetMem(base, disp, child_ty, .{ .register = ro.reg }, opts);
1512115200 try self.genSetMem(
1512215201 base,
15123 disp + @as(i32, @intCast(child_ty.abiSize(mod))),
15202 disp + @as(i32, @intCast(child_ty.abiSize(pt))),
1512415203 Type.bool,
1512515204 .{ .eflags = ro.eflags },
1512615205 opts,
1512715206 );
1512815207 },
1512915208 else => return self.fail("TODO implement genSetMem for {s} of {}", .{
15130 @tagName(src_mcv), ty.fmt(mod),
15209 @tagName(src_mcv), ty.fmt(pt),
1513115210 }),
1513215211 },
1513315212 .register_offset,
......@@ -15236,8 +15315,9 @@ fn genLazySymbolRef(
1523615315 reg: Register,
1523715316 lazy_sym: link.File.LazySymbol,
1523815317) InnerError!void {
15318 const pt = self.pt;
1523915319 if (self.bin_file.cast(link.File.Elf)) |elf_file| {
15240 const sym_index = elf_file.zigObjectPtr().?.getOrCreateMetadataForLazySymbol(elf_file, lazy_sym) catch |err|
15320 const sym_index = elf_file.zigObjectPtr().?.getOrCreateMetadataForLazySymbol(elf_file, pt, lazy_sym) catch |err|
1524115321 return self.fail("{s} creating lazy symbol", .{@errorName(err)});
1524215322 const sym = elf_file.symbol(sym_index);
1524315323 if (self.mod.pic) {
......@@ -15273,7 +15353,7 @@ fn genLazySymbolRef(
1527315353 }
1527415354 }
1527515355 } else if (self.bin_file.cast(link.File.Plan9)) |p9_file| {
15276 const atom_index = p9_file.getOrCreateAtomForLazySymbol(lazy_sym) catch |err|
15356 const atom_index = p9_file.getOrCreateAtomForLazySymbol(pt, lazy_sym) catch |err|
1527715357 return self.fail("{s} creating lazy symbol", .{@errorName(err)});
1527815358 var atom = p9_file.getAtom(atom_index);
1527915359 _ = atom.getOrCreateOffsetTableEntry(p9_file);
......@@ -15300,7 +15380,7 @@ fn genLazySymbolRef(
1530015380 else => unreachable,
1530115381 }
1530215382 } else if (self.bin_file.cast(link.File.Coff)) |coff_file| {
15303 const atom_index = coff_file.getOrCreateAtomForLazySymbol(lazy_sym) catch |err|
15383 const atom_index = coff_file.getOrCreateAtomForLazySymbol(pt, lazy_sym) catch |err|
1530415384 return self.fail("{s} creating lazy symbol", .{@errorName(err)});
1530515385 const sym_index = coff_file.getAtom(atom_index).getSymbolIndex().?;
1530615386 switch (tag) {
......@@ -15314,7 +15394,7 @@ fn genLazySymbolRef(
1531415394 else => unreachable,
1531515395 }
1531615396 } else if (self.bin_file.cast(link.File.MachO)) |macho_file| {
15317 const sym_index = macho_file.getZigObject().?.getOrCreateMetadataForLazySymbol(macho_file, lazy_sym) catch |err|
15397 const sym_index = macho_file.getZigObject().?.getOrCreateMetadataForLazySymbol(macho_file, pt, lazy_sym) catch |err|
1531815398 return self.fail("{s} creating lazy symbol", .{@errorName(err)});
1531915399 const sym = macho_file.getSymbol(sym_index);
1532015400 switch (tag) {
......@@ -15353,7 +15433,8 @@ fn airIntFromPtr(self: *Self, inst: Air.Inst.Index) !void {
1535315433}
1535415434
1535515435fn airBitCast(self: *Self, inst: Air.Inst.Index) !void {
15356 const mod = self.bin_file.comp.module.?;
15436 const pt = self.pt;
15437 const mod = pt.zcu;
1535715438 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
1535815439 const dst_ty = self.typeOfIndex(inst);
1535915440 const src_ty = self.typeOf(ty_op.operand);
......@@ -15366,10 +15447,10 @@ fn airBitCast(self: *Self, inst: Air.Inst.Index) !void {
1536615447 const src_lock = if (src_mcv.getReg()) |reg| self.register_manager.lockReg(reg) else null;
1536715448 defer if (src_lock) |lock| self.register_manager.unlockReg(lock);
1536815449
15369 const dst_mcv = if (dst_rc.supersetOf(src_rc) and dst_ty.abiSize(mod) <= src_ty.abiSize(mod) and
15450 const dst_mcv = if (dst_rc.supersetOf(src_rc) and dst_ty.abiSize(pt) <= src_ty.abiSize(pt) and
1537015451 self.reuseOperand(inst, ty_op.operand, 0, src_mcv)) src_mcv else dst: {
1537115452 const dst_mcv = try self.allocRegOrMem(inst, true);
15372 try self.genCopy(switch (math.order(dst_ty.abiSize(mod), src_ty.abiSize(mod))) {
15453 try self.genCopy(switch (math.order(dst_ty.abiSize(pt), src_ty.abiSize(pt))) {
1537315454 .lt => dst_ty,
1537415455 .eq => if (!dst_mcv.isMemory() or src_mcv.isMemory()) dst_ty else src_ty,
1537515456 .gt => src_ty,
......@@ -15382,8 +15463,8 @@ fn airBitCast(self: *Self, inst: Air.Inst.Index) !void {
1538215463 if (dst_ty.isAbiInt(mod) and src_ty.isAbiInt(mod) and
1538315464 dst_ty.intInfo(mod).signedness == src_ty.intInfo(mod).signedness) break :result dst_mcv;
1538415465
15385 const abi_size = dst_ty.abiSize(mod);
15386 const bit_size = dst_ty.bitSize(mod);
15466 const abi_size = dst_ty.abiSize(pt);
15467 const bit_size = dst_ty.bitSize(pt);
1538715468 if (abi_size * 8 <= bit_size or dst_ty.isVector(mod)) break :result dst_mcv;
1538815469
1538915470 const dst_limbs_len = math.divCeil(i32, @intCast(bit_size), 64) catch unreachable;
......@@ -15412,7 +15493,8 @@ fn airBitCast(self: *Self, inst: Air.Inst.Index) !void {
1541215493}
1541315494
1541415495fn airArrayToSlice(self: *Self, inst: Air.Inst.Index) !void {
15415 const mod = self.bin_file.comp.module.?;
15496 const pt = self.pt;
15497 const mod = pt.zcu;
1541615498 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
1541715499
1541815500 const slice_ty = self.typeOfIndex(inst);
......@@ -15421,11 +15503,11 @@ fn airArrayToSlice(self: *Self, inst: Air.Inst.Index) !void {
1542115503 const array_ty = ptr_ty.childType(mod);
1542215504 const array_len = array_ty.arrayLen(mod);
1542315505
15424 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(slice_ty, mod));
15506 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(slice_ty, pt));
1542515507 try self.genSetMem(.{ .frame = frame_index }, 0, ptr_ty, ptr, .{});
1542615508 try self.genSetMem(
1542715509 .{ .frame = frame_index },
15428 @intCast(ptr_ty.abiSize(mod)),
15510 @intCast(ptr_ty.abiSize(pt)),
1542915511 Type.usize,
1543015512 .{ .immediate = array_len },
1543115513 .{},
......@@ -15436,14 +15518,15 @@ fn airArrayToSlice(self: *Self, inst: Air.Inst.Index) !void {
1543615518}
1543715519
1543815520fn airFloatFromInt(self: *Self, inst: Air.Inst.Index) !void {
15439 const mod = self.bin_file.comp.module.?;
15521 const pt = self.pt;
15522 const mod = pt.zcu;
1544015523 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
1544115524
1544215525 const dst_ty = self.typeOfIndex(inst);
1544315526 const dst_bits = dst_ty.floatBits(self.target.*);
1544415527
1544515528 const src_ty = self.typeOf(ty_op.operand);
15446 const src_bits: u32 = @intCast(src_ty.bitSize(mod));
15529 const src_bits: u32 = @intCast(src_ty.bitSize(pt));
1544715530 const src_signedness =
1544815531 if (src_ty.isAbiInt(mod)) src_ty.intInfo(mod).signedness else .unsigned;
1544915532 const src_size = math.divCeil(u32, @max(switch (src_signedness) {
......@@ -15458,7 +15541,7 @@ fn airFloatFromInt(self: *Self, inst: Air.Inst.Index) !void {
1545815541 else => unreachable,
1545915542 }) {
1546015543 if (src_bits > 128) return self.fail("TODO implement airFloatFromInt from {} to {}", .{
15461 src_ty.fmt(mod), dst_ty.fmt(mod),
15544 src_ty.fmt(pt), dst_ty.fmt(pt),
1546215545 });
1546315546
1546415547 var callee_buf: ["__floatun?i?f".len]u8 = undefined;
......@@ -15500,7 +15583,7 @@ fn airFloatFromInt(self: *Self, inst: Air.Inst.Index) !void {
1550015583 },
1550115584 else => null,
1550215585 }) orelse return self.fail("TODO implement airFloatFromInt from {} to {}", .{
15503 src_ty.fmt(mod), dst_ty.fmt(mod),
15586 src_ty.fmt(pt), dst_ty.fmt(pt),
1550415587 });
1550515588 const dst_alias = dst_reg.to128();
1550615589 const src_alias = registerAlias(src_reg, src_size);
......@@ -15515,11 +15598,12 @@ fn airFloatFromInt(self: *Self, inst: Air.Inst.Index) !void {
1551515598}
1551615599
1551715600fn airIntFromFloat(self: *Self, inst: Air.Inst.Index) !void {
15518 const mod = self.bin_file.comp.module.?;
15601 const pt = self.pt;
15602 const mod = pt.zcu;
1551915603 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
1552015604
1552115605 const dst_ty = self.typeOfIndex(inst);
15522 const dst_bits: u32 = @intCast(dst_ty.bitSize(mod));
15606 const dst_bits: u32 = @intCast(dst_ty.bitSize(pt));
1552315607 const dst_signedness =
1552415608 if (dst_ty.isAbiInt(mod)) dst_ty.intInfo(mod).signedness else .unsigned;
1552515609 const dst_size = math.divCeil(u32, @max(switch (dst_signedness) {
......@@ -15537,7 +15621,7 @@ fn airIntFromFloat(self: *Self, inst: Air.Inst.Index) !void {
1553715621 else => unreachable,
1553815622 }) {
1553915623 if (dst_bits > 128) return self.fail("TODO implement airIntFromFloat from {} to {}", .{
15540 src_ty.fmt(mod), dst_ty.fmt(mod),
15624 src_ty.fmt(pt), dst_ty.fmt(pt),
1554115625 });
1554215626
1554315627 var callee_buf: ["__fixuns?f?i".len]u8 = undefined;
......@@ -15586,13 +15670,13 @@ fn airIntFromFloat(self: *Self, inst: Air.Inst.Index) !void {
1558615670}
1558715671
1558815672fn airCmpxchg(self: *Self, inst: Air.Inst.Index) !void {
15589 const mod = self.bin_file.comp.module.?;
15673 const pt = self.pt;
1559015674 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
1559115675 const extra = self.air.extraData(Air.Cmpxchg, ty_pl.payload).data;
1559215676
1559315677 const ptr_ty = self.typeOf(extra.ptr);
1559415678 const val_ty = self.typeOf(extra.expected_value);
15595 const val_abi_size: u32 = @intCast(val_ty.abiSize(mod));
15679 const val_abi_size: u32 = @intCast(val_ty.abiSize(pt));
1559615680
1559715681 try self.spillRegisters(&.{ .rax, .rdx, .rbx, .rcx });
1559815682 const regs_lock = self.register_manager.lockRegsAssumeUnused(4, .{ .rax, .rdx, .rbx, .rcx });
......@@ -15682,7 +15766,8 @@ fn atomicOp(
1568215766 rmw_op: ?std.builtin.AtomicRmwOp,
1568315767 order: std.builtin.AtomicOrder,
1568415768) InnerError!MCValue {
15685 const mod = self.bin_file.comp.module.?;
15769 const pt = self.pt;
15770 const mod = pt.zcu;
1568615771 const ptr_lock = switch (ptr_mcv) {
1568715772 .register => |reg| self.register_manager.lockReg(reg),
1568815773 else => null,
......@@ -15695,7 +15780,7 @@ fn atomicOp(
1569515780 };
1569615781 defer if (val_lock) |lock| self.register_manager.unlockReg(lock);
1569715782
15698 const val_abi_size: u32 = @intCast(val_ty.abiSize(mod));
15783 const val_abi_size: u32 = @intCast(val_ty.abiSize(pt));
1569915784 const mem_size = Memory.Size.fromSize(val_abi_size);
1570015785 const ptr_mem: Memory = switch (ptr_mcv) {
1570115786 .immediate, .register, .register_offset, .lea_frame => try ptr_mcv.deref().mem(self, mem_size),
......@@ -15809,7 +15894,7 @@ fn atomicOp(
1580915894 },
1581015895 else => unreachable,
1581115896 }) orelse return self.fail("TODO implement atomicOp of {s} for {}", .{
15812 @tagName(op), val_ty.fmt(mod),
15897 @tagName(op), val_ty.fmt(pt),
1581315898 });
1581415899 try self.genSetReg(sse_reg, val_ty, .{ .register = .rax }, .{});
1581515900 switch (mir_tag[0]) {
......@@ -16086,7 +16171,8 @@ fn airAtomicStore(self: *Self, inst: Air.Inst.Index, order: std.builtin.AtomicOr
1608616171}
1608716172
1608816173fn airMemset(self: *Self, inst: Air.Inst.Index, safety: bool) !void {
16089 const mod = self.bin_file.comp.module.?;
16174 const pt = self.pt;
16175 const mod = pt.zcu;
1609016176 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
1609116177
1609216178 result: {
......@@ -16112,7 +16198,7 @@ fn airMemset(self: *Self, inst: Air.Inst.Index, safety: bool) !void {
1611216198 };
1611316199 defer if (src_val_lock) |lock| self.register_manager.unlockReg(lock);
1611416200
16115 const elem_abi_size: u31 = @intCast(elem_ty.abiSize(mod));
16201 const elem_abi_size: u31 = @intCast(elem_ty.abiSize(pt));
1611616202
1611716203 if (elem_abi_size == 1) {
1611816204 const ptr: MCValue = switch (dst_ptr_ty.ptrSize(mod)) {
......@@ -16185,7 +16271,7 @@ fn airMemset(self: *Self, inst: Air.Inst.Index, safety: bool) !void {
1618516271 self.performReloc(skip_reloc);
1618616272 },
1618716273 .One => {
16188 const elem_ptr_ty = try mod.singleMutPtrType(elem_ty);
16274 const elem_ptr_ty = try pt.singleMutPtrType(elem_ty);
1618916275
1619016276 const len = dst_ptr_ty.childType(mod).arrayLen(mod);
1619116277
......@@ -16214,7 +16300,8 @@ fn airMemset(self: *Self, inst: Air.Inst.Index, safety: bool) !void {
1621416300}
1621516301
1621616302fn airMemcpy(self: *Self, inst: Air.Inst.Index) !void {
16217 const mod = self.bin_file.comp.module.?;
16303 const pt = self.pt;
16304 const mod = pt.zcu;
1621816305 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
1621916306
1622016307 try self.spillRegisters(&.{ .rdi, .rsi, .rcx });
......@@ -16246,13 +16333,13 @@ fn airMemcpy(self: *Self, inst: Air.Inst.Index) !void {
1624616333 .{ .i_, .mul },
1624716334 len_reg,
1624816335 try dst_ptr.address().offset(8).deref().mem(self, .qword),
16249 Immediate.s(@intCast(dst_ptr_ty.childType(mod).abiSize(mod))),
16336 Immediate.s(@intCast(dst_ptr_ty.childType(mod).abiSize(pt))),
1625016337 );
1625116338 break :len .{ .register = len_reg };
1625216339 },
1625316340 .One => len: {
1625416341 const array_ty = dst_ptr_ty.childType(mod);
16255 break :len .{ .immediate = array_ty.arrayLen(mod) * array_ty.childType(mod).abiSize(mod) };
16342 break :len .{ .immediate = array_ty.arrayLen(mod) * array_ty.childType(mod).abiSize(pt) };
1625616343 },
1625716344 .C, .Many => unreachable,
1625816345 };
......@@ -16269,7 +16356,8 @@ fn airMemcpy(self: *Self, inst: Air.Inst.Index) !void {
1626916356}
1627016357
1627116358fn airTagName(self: *Self, inst: Air.Inst.Index) !void {
16272 const mod = self.bin_file.comp.module.?;
16359 const pt = self.pt;
16360 const mod = pt.zcu;
1627316361 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
1627416362 const inst_ty = self.typeOfIndex(inst);
1627516363 const enum_ty = self.typeOf(un_op);
......@@ -16278,8 +16366,8 @@ fn airTagName(self: *Self, inst: Air.Inst.Index) !void {
1627816366 // We need a properly aligned and sized call frame to be able to call this function.
1627916367 {
1628016368 const needed_call_frame = FrameAlloc.init(.{
16281 .size = inst_ty.abiSize(mod),
16282 .alignment = inst_ty.abiAlignment(mod),
16369 .size = inst_ty.abiSize(pt),
16370 .alignment = inst_ty.abiAlignment(pt),
1628316371 });
1628416372 const frame_allocs_slice = self.frame_allocs.slice();
1628516373 const stack_frame_size =
......@@ -16311,7 +16399,8 @@ fn airTagName(self: *Self, inst: Air.Inst.Index) !void {
1631116399}
1631216400
1631316401fn airErrorName(self: *Self, inst: Air.Inst.Index) !void {
16314 const mod = self.bin_file.comp.module.?;
16402 const pt = self.pt;
16403 const mod = pt.zcu;
1631516404 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
1631616405
1631716406 const err_ty = self.typeOf(un_op);
......@@ -16413,7 +16502,8 @@ fn airErrorName(self: *Self, inst: Air.Inst.Index) !void {
1641316502}
1641416503
1641516504fn airSplat(self: *Self, inst: Air.Inst.Index) !void {
16416 const mod = self.bin_file.comp.module.?;
16505 const pt = self.pt;
16506 const mod = pt.zcu;
1641716507 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
1641816508 const vector_ty = self.typeOfIndex(inst);
1641916509 const vector_len = vector_ty.vectorLen(mod);
......@@ -16495,15 +16585,15 @@ fn airSplat(self: *Self, inst: Air.Inst.Index) !void {
1649516585 const src_mcv = try self.resolveInst(ty_op.operand);
1649616586 if (src_mcv.isMemory()) try self.asmRegisterMemory(
1649716587 mir_tag,
16498 registerAlias(dst_reg, @intCast(vector_ty.abiSize(mod))),
16588 registerAlias(dst_reg, @intCast(vector_ty.abiSize(pt))),
1649916589 try src_mcv.mem(self, self.memSize(scalar_ty)),
1650016590 ) else {
1650116591 if (mir_tag[0] == .v_i128) break :avx2;
1650216592 try self.genSetReg(dst_reg, scalar_ty, src_mcv, .{});
1650316593 try self.asmRegisterRegister(
1650416594 mir_tag,
16505 registerAlias(dst_reg, @intCast(vector_ty.abiSize(mod))),
16506 registerAlias(dst_reg, @intCast(scalar_ty.abiSize(mod))),
16595 registerAlias(dst_reg, @intCast(vector_ty.abiSize(pt))),
16596 registerAlias(dst_reg, @intCast(scalar_ty.abiSize(pt))),
1650716597 );
1650816598 }
1650916599 break :result .{ .register = dst_reg };
......@@ -16515,7 +16605,7 @@ fn airSplat(self: *Self, inst: Air.Inst.Index) !void {
1651516605 try self.genSetReg(dst_reg, scalar_ty, .{ .air_ref = ty_op.operand }, .{});
1651616606 if (vector_len == 1) break :result .{ .register = dst_reg };
1651716607
16518 const dst_alias = registerAlias(dst_reg, @intCast(vector_ty.abiSize(mod)));
16608 const dst_alias = registerAlias(dst_reg, @intCast(vector_ty.abiSize(pt)));
1651916609 const scalar_bits = scalar_ty.intInfo(mod).bits;
1652016610 if (switch (scalar_bits) {
1652116611 1...8 => true,
......@@ -16745,20 +16835,21 @@ fn airSplat(self: *Self, inst: Air.Inst.Index) !void {
1674516835 else => unreachable,
1674616836 },
1674716837 }
16748 return self.fail("TODO implement airSplat for {}", .{vector_ty.fmt(mod)});
16838 return self.fail("TODO implement airSplat for {}", .{vector_ty.fmt(pt)});
1674916839 };
1675016840 return self.finishAir(inst, result, .{ ty_op.operand, .none, .none });
1675116841}
1675216842
1675316843fn airSelect(self: *Self, inst: Air.Inst.Index) !void {
16754 const mod = self.bin_file.comp.module.?;
16844 const pt = self.pt;
16845 const mod = pt.zcu;
1675516846 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
1675616847 const extra = self.air.extraData(Air.Bin, pl_op.payload).data;
1675716848 const ty = self.typeOfIndex(inst);
1675816849 const vec_len = ty.vectorLen(mod);
1675916850 const elem_ty = ty.childType(mod);
16760 const elem_abi_size: u32 = @intCast(elem_ty.abiSize(mod));
16761 const abi_size: u32 = @intCast(ty.abiSize(mod));
16851 const elem_abi_size: u32 = @intCast(elem_ty.abiSize(pt));
16852 const abi_size: u32 = @intCast(ty.abiSize(pt));
1676216853 const pred_ty = self.typeOf(pl_op.operand);
1676316854
1676416855 const result = result: {
......@@ -16878,17 +16969,17 @@ fn airSelect(self: *Self, inst: Air.Inst.Index) !void {
1687816969 else => unreachable,
1687916970 }),
1688016971 );
16881 } else return self.fail("TODO implement airSelect for {}", .{ty.fmt(mod)});
16972 } else return self.fail("TODO implement airSelect for {}", .{ty.fmt(pt)});
1688216973 const elem_bits: u16 = @intCast(elem_abi_size * 8);
16883 const mask_elem_ty = try mod.intType(.unsigned, elem_bits);
16884 const mask_ty = try mod.vectorType(.{ .len = vec_len, .child = mask_elem_ty.toIntern() });
16974 const mask_elem_ty = try pt.intType(.unsigned, elem_bits);
16975 const mask_ty = try pt.vectorType(.{ .len = vec_len, .child = mask_elem_ty.toIntern() });
1688516976 if (!pred_fits_in_elem) if (self.hasFeature(.ssse3)) {
1688616977 var mask_elems: [32]InternPool.Index = undefined;
16887 for (mask_elems[0..vec_len], 0..) |*elem, bit| elem.* = try mod.intern(.{ .int = .{
16978 for (mask_elems[0..vec_len], 0..) |*elem, bit| elem.* = try pt.intern(.{ .int = .{
1688816979 .ty = mask_elem_ty.toIntern(),
1688916980 .storage = .{ .u64 = bit / elem_bits },
1689016981 } });
16891 const mask_mcv = try self.genTypedValue(Value.fromInterned(try mod.intern(.{ .aggregate = .{
16982 const mask_mcv = try self.genTypedValue(Value.fromInterned(try pt.intern(.{ .aggregate = .{
1689216983 .ty = mask_ty.toIntern(),
1689316984 .storage = .{ .elems = mask_elems[0..vec_len] },
1689416985 } })));
......@@ -16906,14 +16997,14 @@ fn airSelect(self: *Self, inst: Air.Inst.Index) !void {
1690616997 mask_alias,
1690716998 mask_mem,
1690816999 );
16909 } else return self.fail("TODO implement airSelect for {}", .{ty.fmt(mod)});
17000 } else return self.fail("TODO implement airSelect for {}", .{ty.fmt(pt)});
1691017001 {
1691117002 var mask_elems: [32]InternPool.Index = undefined;
16912 for (mask_elems[0..vec_len], 0..) |*elem, bit| elem.* = try mod.intern(.{ .int = .{
17003 for (mask_elems[0..vec_len], 0..) |*elem, bit| elem.* = try pt.intern(.{ .int = .{
1691317004 .ty = mask_elem_ty.toIntern(),
1691417005 .storage = .{ .u64 = @as(u32, 1) << @intCast(bit & (elem_bits - 1)) },
1691517006 } });
16916 const mask_mcv = try self.genTypedValue(Value.fromInterned(try mod.intern(.{ .aggregate = .{
17007 const mask_mcv = try self.genTypedValue(Value.fromInterned(try pt.intern(.{ .aggregate = .{
1691717008 .ty = mask_ty.toIntern(),
1691817009 .storage = .{ .elems = mask_elems[0..vec_len] },
1691917010 } })));
......@@ -17014,7 +17105,7 @@ fn airSelect(self: *Self, inst: Air.Inst.Index) !void {
1701417105 else => null,
1701517106 },
1701617107 },
17017 }) orelse return self.fail("TODO implement airSelect for {}", .{ty.fmt(mod)});
17108 }) orelse return self.fail("TODO implement airSelect for {}", .{ty.fmt(pt)});
1701817109 if (has_avx) {
1701917110 const rhs_alias = if (rhs_mcv.isRegister())
1702017111 registerAlias(rhs_mcv.getReg().?, abi_size)
......@@ -17061,7 +17152,7 @@ fn airSelect(self: *Self, inst: Air.Inst.Index) !void {
1706117152 16, 80, 128 => null,
1706217153 else => unreachable,
1706317154 },
17064 }) orelse return self.fail("TODO implement airSelect for {}", .{ty.fmt(mod)});
17155 }) orelse return self.fail("TODO implement airSelect for {}", .{ty.fmt(pt)});
1706517156 try self.asmRegisterRegister(.{ mir_fixes, .@"and" }, dst_alias, mask_alias);
1706617157 if (rhs_mcv.isMemory()) try self.asmRegisterMemory(
1706717158 .{ mir_fixes, .andn },
......@@ -17083,18 +17174,19 @@ fn airSelect(self: *Self, inst: Air.Inst.Index) !void {
1708317174}
1708417175
1708517176fn airShuffle(self: *Self, inst: Air.Inst.Index) !void {
17086 const mod = self.bin_file.comp.module.?;
17177 const pt = self.pt;
17178 const mod = pt.zcu;
1708717179 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
1708817180 const extra = self.air.extraData(Air.Shuffle, ty_pl.payload).data;
1708917181
1709017182 const dst_ty = self.typeOfIndex(inst);
1709117183 const elem_ty = dst_ty.childType(mod);
17092 const elem_abi_size: u16 = @intCast(elem_ty.abiSize(mod));
17093 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(mod));
17184 const elem_abi_size: u16 = @intCast(elem_ty.abiSize(pt));
17185 const dst_abi_size: u32 = @intCast(dst_ty.abiSize(pt));
1709417186 const lhs_ty = self.typeOf(extra.a);
17095 const lhs_abi_size: u32 = @intCast(lhs_ty.abiSize(mod));
17187 const lhs_abi_size: u32 = @intCast(lhs_ty.abiSize(pt));
1709617188 const rhs_ty = self.typeOf(extra.b);
17097 const rhs_abi_size: u32 = @intCast(rhs_ty.abiSize(mod));
17189 const rhs_abi_size: u32 = @intCast(rhs_ty.abiSize(pt));
1709817190 const max_abi_size = @max(dst_abi_size, lhs_abi_size, rhs_abi_size);
1709917191
1710017192 const ExpectedContents = [32]?i32;
......@@ -17106,11 +17198,11 @@ fn airShuffle(self: *Self, inst: Air.Inst.Index) !void {
1710617198 defer allocator.free(mask_elems);
1710717199 for (mask_elems, 0..) |*mask_elem, elem_index| {
1710817200 const mask_elem_val =
17109 Value.fromInterned(extra.mask).elemValue(mod, elem_index) catch unreachable;
17201 Value.fromInterned(extra.mask).elemValue(pt, elem_index) catch unreachable;
1711017202 mask_elem.* = if (mask_elem_val.isUndef(mod))
1711117203 null
1711217204 else
17113 @intCast(mask_elem_val.toSignedInt(mod));
17205 @intCast(mask_elem_val.toSignedInt(pt));
1711417206 }
1711517207
1711617208 const has_avx = self.hasFeature(.avx);
......@@ -17626,8 +17718,8 @@ fn airShuffle(self: *Self, inst: Air.Inst.Index) !void {
1762617718 else
1762717719 self.hasFeature(.avx2)) 32 else 16)) break :blendv;
1762817720
17629 const select_mask_elem_ty = try mod.intType(.unsigned, elem_abi_size * 8);
17630 const select_mask_ty = try mod.vectorType(.{
17721 const select_mask_elem_ty = try pt.intType(.unsigned, elem_abi_size * 8);
17722 const select_mask_ty = try pt.vectorType(.{
1763117723 .len = @intCast(mask_elems.len),
1763217724 .child = select_mask_elem_ty.toIntern(),
1763317725 });
......@@ -17643,11 +17735,11 @@ fn airShuffle(self: *Self, inst: Air.Inst.Index) !void {
1764317735 if (mask_elem_index != elem_index) break :blendv;
1764417736
1764517737 select_mask_elem.* = (if (mask_elem < 0)
17646 try select_mask_elem_ty.maxIntScalar(mod, select_mask_elem_ty)
17738 try select_mask_elem_ty.maxIntScalar(pt, select_mask_elem_ty)
1764717739 else
17648 try select_mask_elem_ty.minIntScalar(mod, select_mask_elem_ty)).toIntern();
17740 try select_mask_elem_ty.minIntScalar(pt, select_mask_elem_ty)).toIntern();
1764917741 }
17650 const select_mask_mcv = try self.genTypedValue(Value.fromInterned(try mod.intern(.{ .aggregate = .{
17742 const select_mask_mcv = try self.genTypedValue(Value.fromInterned(try pt.intern(.{ .aggregate = .{
1765117743 .ty = select_mask_ty.toIntern(),
1765217744 .storage = .{ .elems = select_mask_elems[0..mask_elems.len] },
1765317745 } })));
......@@ -17783,7 +17875,7 @@ fn airShuffle(self: *Self, inst: Air.Inst.Index) !void {
1778317875 var lhs_mask_elems: [16]InternPool.Index = undefined;
1778417876 for (lhs_mask_elems[0..max_abi_size], 0..) |*lhs_mask_elem, byte_index| {
1778517877 const elem_index = byte_index / elem_abi_size;
17786 lhs_mask_elem.* = try mod.intern(.{ .int = .{
17878 lhs_mask_elem.* = try pt.intern(.{ .int = .{
1778717879 .ty = .u8_type,
1778817880 .storage = .{ .u64 = if (elem_index >= mask_elems.len) 0b1_00_00000 else elem: {
1778917881 const mask_elem = mask_elems[elem_index] orelse break :elem 0b1_00_00000;
......@@ -17794,8 +17886,8 @@ fn airShuffle(self: *Self, inst: Air.Inst.Index) !void {
1779417886 } },
1779517887 } });
1779617888 }
17797 const lhs_mask_ty = try mod.vectorType(.{ .len = max_abi_size, .child = .u8_type });
17798 const lhs_mask_mcv = try self.genTypedValue(Value.fromInterned(try mod.intern(.{ .aggregate = .{
17889 const lhs_mask_ty = try pt.vectorType(.{ .len = max_abi_size, .child = .u8_type });
17890 const lhs_mask_mcv = try self.genTypedValue(Value.fromInterned(try pt.intern(.{ .aggregate = .{
1779917891 .ty = lhs_mask_ty.toIntern(),
1780017892 .storage = .{ .elems = lhs_mask_elems[0..max_abi_size] },
1780117893 } })));
......@@ -17817,7 +17909,7 @@ fn airShuffle(self: *Self, inst: Air.Inst.Index) !void {
1781717909 var rhs_mask_elems: [16]InternPool.Index = undefined;
1781817910 for (rhs_mask_elems[0..max_abi_size], 0..) |*rhs_mask_elem, byte_index| {
1781917911 const elem_index = byte_index / elem_abi_size;
17820 rhs_mask_elem.* = try mod.intern(.{ .int = .{
17912 rhs_mask_elem.* = try pt.intern(.{ .int = .{
1782117913 .ty = .u8_type,
1782217914 .storage = .{ .u64 = if (elem_index >= mask_elems.len) 0b1_00_00000 else elem: {
1782317915 const mask_elem = mask_elems[elem_index] orelse break :elem 0b1_00_00000;
......@@ -17828,8 +17920,8 @@ fn airShuffle(self: *Self, inst: Air.Inst.Index) !void {
1782817920 } },
1782917921 } });
1783017922 }
17831 const rhs_mask_ty = try mod.vectorType(.{ .len = max_abi_size, .child = .u8_type });
17832 const rhs_mask_mcv = try self.genTypedValue(Value.fromInterned(try mod.intern(.{ .aggregate = .{
17923 const rhs_mask_ty = try pt.vectorType(.{ .len = max_abi_size, .child = .u8_type });
17924 const rhs_mask_mcv = try self.genTypedValue(Value.fromInterned(try pt.intern(.{ .aggregate = .{
1783317925 .ty = rhs_mask_ty.toIntern(),
1783417926 .storage = .{ .elems = rhs_mask_elems[0..max_abi_size] },
1783517927 } })));
......@@ -17881,14 +17973,15 @@ fn airShuffle(self: *Self, inst: Air.Inst.Index) !void {
1788117973
1788217974 break :result null;
1788317975 }) orelse return self.fail("TODO implement airShuffle from {} and {} to {} with {}", .{
17884 lhs_ty.fmt(mod), rhs_ty.fmt(mod), dst_ty.fmt(mod),
17885 Value.fromInterned(extra.mask).fmtValue(mod, null),
17976 lhs_ty.fmt(pt), rhs_ty.fmt(pt), dst_ty.fmt(pt),
17977 Value.fromInterned(extra.mask).fmtValue(pt, null),
1788617978 });
1788717979 return self.finishAir(inst, result, .{ extra.a, extra.b, .none });
1788817980}
1788917981
1789017982fn airReduce(self: *Self, inst: Air.Inst.Index) !void {
17891 const mod = self.bin_file.comp.module.?;
17983 const pt = self.pt;
17984 const mod = pt.zcu;
1789217985 const reduce = self.air.instructions.items(.data)[@intFromEnum(inst)].reduce;
1789317986
1789417987 const result: MCValue = result: {
......@@ -17898,9 +17991,9 @@ fn airReduce(self: *Self, inst: Air.Inst.Index) !void {
1789817991
1789917992 const operand_mcv = try self.resolveInst(reduce.operand);
1790017993 const mask_len = (math.cast(u6, operand_ty.vectorLen(mod)) orelse
17901 return self.fail("TODO implement airReduce for {}", .{operand_ty.fmt(mod)}));
17994 return self.fail("TODO implement airReduce for {}", .{operand_ty.fmt(pt)}));
1790217995 const mask = (@as(u64, 1) << mask_len) - 1;
17903 const abi_size: u32 = @intCast(operand_ty.abiSize(mod));
17996 const abi_size: u32 = @intCast(operand_ty.abiSize(pt));
1790417997 switch (reduce.operation) {
1790517998 .Or => {
1790617999 if (operand_mcv.isMemory()) try self.asmMemoryImmediate(
......@@ -17936,16 +18029,17 @@ fn airReduce(self: *Self, inst: Air.Inst.Index) !void {
1793618029 try self.asmRegisterRegister(.{ ._, .@"test" }, tmp_reg, tmp_reg);
1793718030 break :result .{ .eflags = .z };
1793818031 },
17939 else => return self.fail("TODO implement airReduce for {}", .{operand_ty.fmt(mod)}),
18032 else => return self.fail("TODO implement airReduce for {}", .{operand_ty.fmt(pt)}),
1794018033 }
1794118034 }
17942 return self.fail("TODO implement airReduce for {}", .{operand_ty.fmt(mod)});
18035 return self.fail("TODO implement airReduce for {}", .{operand_ty.fmt(pt)});
1794318036 };
1794418037 return self.finishAir(inst, result, .{ reduce.operand, .none, .none });
1794518038}
1794618039
1794718040fn airAggregateInit(self: *Self, inst: Air.Inst.Index) !void {
17948 const mod = self.bin_file.comp.module.?;
18041 const pt = self.pt;
18042 const mod = pt.zcu;
1794918043 const result_ty = self.typeOfIndex(inst);
1795018044 const len: usize = @intCast(result_ty.arrayLen(mod));
1795118045 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
......@@ -17953,30 +18047,30 @@ fn airAggregateInit(self: *Self, inst: Air.Inst.Index) !void {
1795318047 const result: MCValue = result: {
1795418048 switch (result_ty.zigTypeTag(mod)) {
1795518049 .Struct => {
17956 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(result_ty, mod));
18050 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(result_ty, pt));
1795718051 if (result_ty.containerLayout(mod) == .@"packed") {
1795818052 const struct_obj = mod.typeToStruct(result_ty).?;
1795918053 try self.genInlineMemset(
1796018054 .{ .lea_frame = .{ .index = frame_index } },
1796118055 .{ .immediate = 0 },
17962 .{ .immediate = result_ty.abiSize(mod) },
18056 .{ .immediate = result_ty.abiSize(pt) },
1796318057 .{},
1796418058 );
1796518059 for (elements, 0..) |elem, elem_i_usize| {
1796618060 const elem_i: u32 = @intCast(elem_i_usize);
17967 if ((try result_ty.structFieldValueComptime(mod, elem_i)) != null) continue;
18061 if ((try result_ty.structFieldValueComptime(pt, elem_i)) != null) continue;
1796818062
1796918063 const elem_ty = result_ty.structFieldType(elem_i, mod);
17970 const elem_bit_size: u32 = @intCast(elem_ty.bitSize(mod));
18064 const elem_bit_size: u32 = @intCast(elem_ty.bitSize(pt));
1797118065 if (elem_bit_size > 64) {
1797218066 return self.fail(
1797318067 "TODO airAggregateInit implement packed structs with large fields",
1797418068 .{},
1797518069 );
1797618070 }
17977 const elem_abi_size: u32 = @intCast(elem_ty.abiSize(mod));
18071 const elem_abi_size: u32 = @intCast(elem_ty.abiSize(pt));
1797818072 const elem_abi_bits = elem_abi_size * 8;
17979 const elem_off = mod.structPackedFieldBitOffset(struct_obj, elem_i);
18073 const elem_off = pt.structPackedFieldBitOffset(struct_obj, elem_i);
1798018074 const elem_byte_off: i32 = @intCast(elem_off / elem_abi_bits * elem_abi_size);
1798118075 const elem_bit_off = elem_off % elem_abi_bits;
1798218076 const elem_mcv = try self.resolveInst(elem);
......@@ -18046,10 +18140,10 @@ fn airAggregateInit(self: *Self, inst: Air.Inst.Index) !void {
1804618140 }
1804718141 }
1804818142 } else for (elements, 0..) |elem, elem_i| {
18049 if ((try result_ty.structFieldValueComptime(mod, elem_i)) != null) continue;
18143 if ((try result_ty.structFieldValueComptime(pt, elem_i)) != null) continue;
1805018144
1805118145 const elem_ty = result_ty.structFieldType(elem_i, mod);
18052 const elem_off: i32 = @intCast(result_ty.structFieldOffset(elem_i, mod));
18146 const elem_off: i32 = @intCast(result_ty.structFieldOffset(elem_i, pt));
1805318147 const elem_mcv = try self.resolveInst(elem);
1805418148 const mat_elem_mcv = switch (elem_mcv) {
1805518149 .load_tlv => |sym_index| MCValue{ .lea_tlv = sym_index },
......@@ -18062,7 +18156,7 @@ fn airAggregateInit(self: *Self, inst: Air.Inst.Index) !void {
1806218156 .Array, .Vector => {
1806318157 const elem_ty = result_ty.childType(mod);
1806418158 if (result_ty.isVector(mod) and elem_ty.toIntern() == .bool_type) {
18065 const result_size: u32 = @intCast(result_ty.abiSize(mod));
18159 const result_size: u32 = @intCast(result_ty.abiSize(pt));
1806618160 const dst_reg = try self.register_manager.allocReg(inst, abi.RegisterClass.gp);
1806718161 try self.asmRegisterRegister(
1806818162 .{ ._, .xor },
......@@ -18093,8 +18187,8 @@ fn airAggregateInit(self: *Self, inst: Air.Inst.Index) !void {
1809318187 }
1809418188 break :result .{ .register = dst_reg };
1809518189 } else {
18096 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(result_ty, mod));
18097 const elem_size: u32 = @intCast(elem_ty.abiSize(mod));
18190 const frame_index = try self.allocFrameIndex(FrameAlloc.initSpill(result_ty, pt));
18191 const elem_size: u32 = @intCast(elem_ty.abiSize(pt));
1809818192
1809918193 for (elements, 0..) |elem, elem_i| {
1810018194 const elem_mcv = try self.resolveInst(elem);
......@@ -18136,18 +18230,19 @@ fn airAggregateInit(self: *Self, inst: Air.Inst.Index) !void {
1813618230}
1813718231
1813818232fn airUnionInit(self: *Self, inst: Air.Inst.Index) !void {
18139 const mod = self.bin_file.comp.module.?;
18233 const pt = self.pt;
18234 const mod = pt.zcu;
1814018235 const ip = &mod.intern_pool;
1814118236 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
1814218237 const extra = self.air.extraData(Air.UnionInit, ty_pl.payload).data;
1814318238 const result: MCValue = result: {
1814418239 const union_ty = self.typeOfIndex(inst);
18145 const layout = union_ty.unionGetLayout(mod);
18240 const layout = union_ty.unionGetLayout(pt);
1814618241
1814718242 const src_ty = self.typeOf(extra.init);
1814818243 const src_mcv = try self.resolveInst(extra.init);
1814918244 if (layout.tag_size == 0) {
18150 if (layout.abi_size <= src_ty.abiSize(mod) and
18245 if (layout.abi_size <= src_ty.abiSize(pt) and
1815118246 self.reuseOperand(inst, extra.init, 0, src_mcv)) break :result src_mcv;
1815218247
1815318248 const dst_mcv = try self.allocRegOrMem(inst, true);
......@@ -18161,9 +18256,9 @@ fn airUnionInit(self: *Self, inst: Air.Inst.Index) !void {
1816118256 const field_name = union_obj.loadTagType(ip).names.get(ip)[extra.field_index];
1816218257 const tag_ty = Type.fromInterned(union_obj.enum_tag_ty);
1816318258 const field_index = tag_ty.enumFieldIndex(field_name, mod).?;
18164 const tag_val = try mod.enumValueFieldIndex(tag_ty, field_index);
18165 const tag_int_val = try tag_val.intFromEnum(tag_ty, mod);
18166 const tag_int = tag_int_val.toUnsignedInt(mod);
18259 const tag_val = try pt.enumValueFieldIndex(tag_ty, field_index);
18260 const tag_int_val = try tag_val.intFromEnum(tag_ty, pt);
18261 const tag_int = tag_int_val.toUnsignedInt(pt);
1816718262 const tag_off: i32 = if (layout.tag_align.compare(.lt, layout.payload_align))
1816818263 @intCast(layout.payload_size)
1816918264 else
......@@ -18192,7 +18287,8 @@ fn airPrefetch(self: *Self, inst: Air.Inst.Index) !void {
1819218287}
1819318288
1819418289fn airMulAdd(self: *Self, inst: Air.Inst.Index) !void {
18195 const mod = self.bin_file.comp.module.?;
18290 const pt = self.pt;
18291 const mod = pt.zcu;
1819618292 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
1819718293 const extra = self.air.extraData(Air.Bin, pl_op.payload).data;
1819818294 const ty = self.typeOfIndex(inst);
......@@ -18205,7 +18301,7 @@ fn airMulAdd(self: *Self, inst: Air.Inst.Index) !void {
1820518301 else => unreachable,
1820618302 }) {
1820718303 if (ty.zigTypeTag(mod) != .Float) return self.fail("TODO implement airMulAdd for {}", .{
18208 ty.fmt(mod),
18304 ty.fmt(pt),
1820918305 });
1821018306
1821118307 var callee_buf: ["__fma?".len]u8 = undefined;
......@@ -18334,12 +18430,12 @@ fn airMulAdd(self: *Self, inst: Air.Inst.Index) !void {
1833418430 else => unreachable,
1833518431 }
1833618432 else
18337 unreachable) orelse return self.fail("TODO implement airMulAdd for {}", .{ty.fmt(mod)});
18433 unreachable) orelse return self.fail("TODO implement airMulAdd for {}", .{ty.fmt(pt)});
1833818434
1833918435 var mops: [3]MCValue = undefined;
1834018436 for (order, mcvs) |mop_index, mcv| mops[mop_index - 1] = mcv;
1834118437
18342 const abi_size: u32 = @intCast(ty.abiSize(mod));
18438 const abi_size: u32 = @intCast(ty.abiSize(pt));
1834318439 const mop1_reg = registerAlias(mops[0].getReg().?, abi_size);
1834418440 const mop2_reg = registerAlias(mops[1].getReg().?, abi_size);
1834518441 if (mops[2].isRegister()) try self.asmRegisterRegisterRegister(
......@@ -18359,9 +18455,10 @@ fn airMulAdd(self: *Self, inst: Air.Inst.Index) !void {
1835918455}
1836018456
1836118457fn airVaStart(self: *Self, inst: Air.Inst.Index) !void {
18362 const mod = self.bin_file.comp.module.?;
18458 const pt = self.pt;
18459 const mod = pt.zcu;
1836318460 const va_list_ty = self.air.instructions.items(.data)[@intFromEnum(inst)].ty;
18364 const ptr_anyopaque_ty = try mod.singleMutPtrType(Type.anyopaque);
18461 const ptr_anyopaque_ty = try pt.singleMutPtrType(Type.anyopaque);
1836518462
1836618463 const result: MCValue = switch (abi.resolveCallingConvention(
1836718464 self.fn_type.fnCallingConvention(mod),
......@@ -18369,7 +18466,7 @@ fn airVaStart(self: *Self, inst: Air.Inst.Index) !void {
1836918466 )) {
1837018467 .SysV => result: {
1837118468 const info = self.va_info.sysv;
18372 const dst_fi = try self.allocFrameIndex(FrameAlloc.initSpill(va_list_ty, mod));
18469 const dst_fi = try self.allocFrameIndex(FrameAlloc.initSpill(va_list_ty, pt));
1837318470 var field_off: u31 = 0;
1837418471 // gp_offset: c_uint,
1837518472 try self.genSetMem(
......@@ -18379,7 +18476,7 @@ fn airVaStart(self: *Self, inst: Air.Inst.Index) !void {
1837918476 .{ .immediate = info.gp_count * 8 },
1838018477 .{},
1838118478 );
18382 field_off += @intCast(Type.c_uint.abiSize(mod));
18479 field_off += @intCast(Type.c_uint.abiSize(pt));
1838318480 // fp_offset: c_uint,
1838418481 try self.genSetMem(
1838518482 .{ .frame = dst_fi },
......@@ -18388,7 +18485,7 @@ fn airVaStart(self: *Self, inst: Air.Inst.Index) !void {
1838818485 .{ .immediate = abi.SysV.c_abi_int_param_regs.len * 8 + info.fp_count * 16 },
1838918486 .{},
1839018487 );
18391 field_off += @intCast(Type.c_uint.abiSize(mod));
18488 field_off += @intCast(Type.c_uint.abiSize(pt));
1839218489 // overflow_arg_area: *anyopaque,
1839318490 try self.genSetMem(
1839418491 .{ .frame = dst_fi },
......@@ -18397,7 +18494,7 @@ fn airVaStart(self: *Self, inst: Air.Inst.Index) !void {
1839718494 .{ .lea_frame = info.overflow_arg_area },
1839818495 .{},
1839918496 );
18400 field_off += @intCast(ptr_anyopaque_ty.abiSize(mod));
18497 field_off += @intCast(ptr_anyopaque_ty.abiSize(pt));
1840118498 // reg_save_area: *anyopaque,
1840218499 try self.genSetMem(
1840318500 .{ .frame = dst_fi },
......@@ -18406,7 +18503,7 @@ fn airVaStart(self: *Self, inst: Air.Inst.Index) !void {
1840618503 .{ .lea_frame = info.reg_save_area },
1840718504 .{},
1840818505 );
18409 field_off += @intCast(ptr_anyopaque_ty.abiSize(mod));
18506 field_off += @intCast(ptr_anyopaque_ty.abiSize(pt));
1841018507 break :result .{ .load_frame = .{ .index = dst_fi } };
1841118508 },
1841218509 .Win64 => return self.fail("TODO implement c_va_start for Win64", .{}),
......@@ -18416,11 +18513,12 @@ fn airVaStart(self: *Self, inst: Air.Inst.Index) !void {
1841618513}
1841718514
1841818515fn airVaArg(self: *Self, inst: Air.Inst.Index) !void {
18419 const mod = self.bin_file.comp.module.?;
18516 const pt = self.pt;
18517 const mod = pt.zcu;
1842018518 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
1842118519 const ty = self.typeOfIndex(inst);
1842218520 const promote_ty = self.promoteVarArg(ty);
18423 const ptr_anyopaque_ty = try mod.singleMutPtrType(Type.anyopaque);
18521 const ptr_anyopaque_ty = try pt.singleMutPtrType(Type.anyopaque);
1842418522 const unused = self.liveness.isUnused(inst);
1842518523
1842618524 const result: MCValue = switch (abi.resolveCallingConvention(
......@@ -18454,7 +18552,7 @@ fn airVaArg(self: *Self, inst: Air.Inst.Index) !void {
1845418552 const overflow_arg_area: MCValue = .{ .indirect = .{ .reg = ptr_arg_list_reg, .off = 8 } };
1845518553 const reg_save_area: MCValue = .{ .indirect = .{ .reg = ptr_arg_list_reg, .off = 16 } };
1845618554
18457 const classes = mem.sliceTo(&abi.classifySystemV(promote_ty, mod, self.target.*, .arg), .none);
18555 const classes = mem.sliceTo(&abi.classifySystemV(promote_ty, pt, self.target.*, .arg), .none);
1845818556 switch (classes[0]) {
1845918557 .integer => {
1846018558 assert(classes.len == 1);
......@@ -18489,7 +18587,7 @@ fn airVaArg(self: *Self, inst: Air.Inst.Index) !void {
1848918587 .base = .{ .reg = addr_reg },
1849018588 .mod = .{ .rm = .{
1849118589 .size = .qword,
18492 .disp = @intCast(@max(promote_ty.abiSize(mod), 8)),
18590 .disp = @intCast(@max(promote_ty.abiSize(pt), 8)),
1849318591 } },
1849418592 });
1849518593 try self.genCopy(
......@@ -18537,7 +18635,7 @@ fn airVaArg(self: *Self, inst: Air.Inst.Index) !void {
1853718635 .base = .{ .reg = addr_reg },
1853818636 .mod = .{ .rm = .{
1853918637 .size = .qword,
18540 .disp = @intCast(@max(promote_ty.abiSize(mod), 8)),
18638 .disp = @intCast(@max(promote_ty.abiSize(pt), 8)),
1854118639 } },
1854218640 });
1854318641 try self.genCopy(
......@@ -18557,7 +18655,7 @@ fn airVaArg(self: *Self, inst: Air.Inst.Index) !void {
1855718655 unreachable;
1855818656 },
1855918657 else => return self.fail("TODO implement c_va_arg for {} on SysV", .{
18560 promote_ty.fmt(mod),
18658 promote_ty.fmt(pt),
1856118659 }),
1856218660 }
1856318661
......@@ -18627,11 +18725,11 @@ fn airVaEnd(self: *Self, inst: Air.Inst.Index) !void {
1862718725}
1862818726
1862918727fn resolveInst(self: *Self, ref: Air.Inst.Ref) InnerError!MCValue {
18630 const mod = self.bin_file.comp.module.?;
18728 const pt = self.pt;
1863118729 const ty = self.typeOf(ref);
1863218730
1863318731 // If the type has no codegen bits, no need to store it.
18634 if (!ty.hasRuntimeBitsIgnoreComptime(mod)) return .none;
18732 if (!ty.hasRuntimeBitsIgnoreComptime(pt)) return .none;
1863518733
1863618734 const mcv = if (ref.toIndex()) |inst| mcv: {
1863718735 break :mcv self.inst_tracking.getPtr(inst).?.short;
......@@ -18705,8 +18803,8 @@ fn limitImmediateType(self: *Self, operand: Air.Inst.Ref, comptime T: type) !MCV
1870518803}
1870618804
1870718805fn genTypedValue(self: *Self, val: Value) InnerError!MCValue {
18708 const mod = self.bin_file.comp.module.?;
18709 return switch (try codegen.genTypedValue(self.bin_file, self.src_loc, val, self.owner.getDecl(mod))) {
18806 const pt = self.pt;
18807 return switch (try codegen.genTypedValue(self.bin_file, pt, self.src_loc, val, self.owner.getDecl(pt.zcu))) {
1871018808 .mcv => |mcv| switch (mcv) {
1871118809 .none => .none,
1871218810 .undef => .undef,
......@@ -18745,7 +18843,8 @@ fn resolveCallingConventionValues(
1874518843 var_args: []const Type,
1874618844 stack_frame_base: FrameIndex,
1874718845) !CallMCValues {
18748 const mod = self.bin_file.comp.module.?;
18846 const pt = self.pt;
18847 const mod = pt.zcu;
1874918848 const ip = &mod.intern_pool;
1875018849 const cc = fn_info.cc;
1875118850 const param_types = try self.gpa.alloc(Type, fn_info.param_types.len + var_args.len);
......@@ -18788,7 +18887,7 @@ fn resolveCallingConventionValues(
1878818887 .SysV => {},
1878918888 .Win64 => {
1879018889 // Align the stack to 16bytes before allocating shadow stack space (if any).
18791 result.stack_byte_count += @intCast(4 * Type.usize.abiSize(mod));
18890 result.stack_byte_count += @intCast(4 * Type.usize.abiSize(pt));
1879218891 },
1879318892 else => unreachable,
1879418893 }
......@@ -18796,7 +18895,7 @@ fn resolveCallingConventionValues(
1879618895 // Return values
1879718896 if (ret_ty.zigTypeTag(mod) == .NoReturn) {
1879818897 result.return_value = InstTracking.init(.unreach);
18799 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
18898 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
1880018899 // TODO: is this even possible for C calling convention?
1880118900 result.return_value = InstTracking.init(.none);
1880218901 } else {
......@@ -18804,15 +18903,15 @@ fn resolveCallingConventionValues(
1880418903 var ret_tracking_i: usize = 0;
1880518904
1880618905 const classes = switch (resolved_cc) {
18807 .SysV => mem.sliceTo(&abi.classifySystemV(ret_ty, mod, self.target.*, .ret), .none),
18808 .Win64 => &.{abi.classifyWindows(ret_ty, mod)},
18906 .SysV => mem.sliceTo(&abi.classifySystemV(ret_ty, pt, self.target.*, .ret), .none),
18907 .Win64 => &.{abi.classifyWindows(ret_ty, pt)},
1880918908 else => unreachable,
1881018909 };
1881118910 for (classes) |class| switch (class) {
1881218911 .integer => {
1881318912 const ret_int_reg = registerAlias(
1881418913 abi.getCAbiIntReturnRegs(resolved_cc)[ret_int_reg_i],
18815 @intCast(@min(ret_ty.abiSize(mod), 8)),
18914 @intCast(@min(ret_ty.abiSize(pt), 8)),
1881618915 );
1881718916 ret_int_reg_i += 1;
1881818917
......@@ -18822,7 +18921,7 @@ fn resolveCallingConventionValues(
1882218921 .sse, .float, .float_combine, .win_i128 => {
1882318922 const ret_sse_reg = registerAlias(
1882418923 abi.getCAbiSseReturnRegs(resolved_cc)[ret_sse_reg_i],
18825 @intCast(ret_ty.abiSize(mod)),
18924 @intCast(ret_ty.abiSize(pt)),
1882618925 );
1882718926 ret_sse_reg_i += 1;
1882818927
......@@ -18865,7 +18964,7 @@ fn resolveCallingConventionValues(
1886518964
1886618965 // Input params
1886718966 for (param_types, result.args) |ty, *arg| {
18868 assert(ty.hasRuntimeBitsIgnoreComptime(mod));
18967 assert(ty.hasRuntimeBitsIgnoreComptime(pt));
1886918968 switch (resolved_cc) {
1887018969 .SysV => {},
1887118970 .Win64 => {
......@@ -18879,8 +18978,8 @@ fn resolveCallingConventionValues(
1887918978 var arg_mcv_i: usize = 0;
1888018979
1888118980 const classes = switch (resolved_cc) {
18882 .SysV => mem.sliceTo(&abi.classifySystemV(ty, mod, self.target.*, .arg), .none),
18883 .Win64 => &.{abi.classifyWindows(ty, mod)},
18981 .SysV => mem.sliceTo(&abi.classifySystemV(ty, pt, self.target.*, .arg), .none),
18982 .Win64 => &.{abi.classifyWindows(ty, pt)},
1888418983 else => unreachable,
1888518984 };
1888618985 for (classes) |class| switch (class) {
......@@ -18890,7 +18989,7 @@ fn resolveCallingConventionValues(
1889018989
1889118990 const param_int_reg = registerAlias(
1889218991 abi.getCAbiIntParamRegs(resolved_cc)[param_int_reg_i],
18893 @intCast(@min(ty.abiSize(mod), 8)),
18992 @intCast(@min(ty.abiSize(pt), 8)),
1889418993 );
1889518994 param_int_reg_i += 1;
1889618995
......@@ -18903,7 +19002,7 @@ fn resolveCallingConventionValues(
1890319002
1890419003 const param_sse_reg = registerAlias(
1890519004 abi.getCAbiSseParamRegs(resolved_cc)[param_sse_reg_i],
18906 @intCast(ty.abiSize(mod)),
19005 @intCast(ty.abiSize(pt)),
1890719006 );
1890819007 param_sse_reg_i += 1;
1890919008
......@@ -18916,7 +19015,7 @@ fn resolveCallingConventionValues(
1891619015 .x87, .x87up, .complex_x87, .memory => break,
1891719016 else => unreachable,
1891819017 },
18919 .Win64 => if (ty.abiSize(mod) > 8) {
19018 .Win64 => if (ty.abiSize(pt) > 8) {
1892019019 const param_int_reg =
1892119020 abi.getCAbiIntParamRegs(resolved_cc)[param_int_reg_i].to64();
1892219021 param_int_reg_i += 1;
......@@ -18938,7 +19037,7 @@ fn resolveCallingConventionValues(
1893819037 const frame_elems_len = ty.vectorLen(mod) - remaining_param_int_regs;
1893919038 const frame_elem_size = mem.alignForward(
1894019039 u64,
18941 ty.childType(mod).abiSize(mod),
19040 ty.childType(mod).abiSize(pt),
1894219041 frame_elem_align,
1894319042 );
1894419043 const frame_size: u31 = @intCast(frame_elems_len * frame_elem_size);
......@@ -18962,9 +19061,9 @@ fn resolveCallingConventionValues(
1896219061 continue;
1896319062 }
1896419063
18965 const param_size: u31 = @intCast(ty.abiSize(mod));
19064 const param_size: u31 = @intCast(ty.abiSize(pt));
1896619065 const param_align: u31 =
18967 @intCast(@max(ty.abiAlignment(mod).toByteUnits().?, 8));
19066 @intCast(@max(ty.abiAlignment(pt).toByteUnits().?, 8));
1896819067 result.stack_byte_count =
1896919068 mem.alignForward(u31, result.stack_byte_count, param_align);
1897019069 arg.* = .{ .load_frame = .{
......@@ -18984,11 +19083,11 @@ fn resolveCallingConventionValues(
1898419083 // Return values
1898519084 if (ret_ty.zigTypeTag(mod) == .NoReturn) {
1898619085 result.return_value = InstTracking.init(.unreach);
18987 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
19086 } else if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
1898819087 result.return_value = InstTracking.init(.none);
1898919088 } else {
1899019089 const ret_reg = abi.getCAbiIntReturnRegs(resolved_cc)[0];
18991 const ret_ty_size: u31 = @intCast(ret_ty.abiSize(mod));
19090 const ret_ty_size: u31 = @intCast(ret_ty.abiSize(pt));
1899219091 if (ret_ty_size <= 8 and !ret_ty.isRuntimeFloat()) {
1899319092 const aliased_reg = registerAlias(ret_reg, ret_ty_size);
1899419093 result.return_value = .{ .short = .{ .register = aliased_reg }, .long = .none };
......@@ -19003,12 +19102,12 @@ fn resolveCallingConventionValues(
1900319102
1900419103 // Input params
1900519104 for (param_types, result.args) |ty, *arg| {
19006 if (!ty.hasRuntimeBitsIgnoreComptime(mod)) {
19105 if (!ty.hasRuntimeBitsIgnoreComptime(pt)) {
1900719106 arg.* = .none;
1900819107 continue;
1900919108 }
19010 const param_size: u31 = @intCast(ty.abiSize(mod));
19011 const param_align: u31 = @intCast(ty.abiAlignment(mod).toByteUnits().?);
19109 const param_size: u31 = @intCast(ty.abiSize(pt));
19110 const param_align: u31 = @intCast(ty.abiAlignment(pt).toByteUnits().?);
1901219111 result.stack_byte_count =
1901319112 mem.alignForward(u31, result.stack_byte_count, param_align);
1901419113 arg.* = .{ .load_frame = .{
......@@ -19093,47 +19192,49 @@ fn registerAlias(reg: Register, size_bytes: u32) Register {
1909319192}
1909419193
1909519194fn memSize(self: *Self, ty: Type) Memory.Size {
19096 const mod = self.bin_file.comp.module.?;
19195 const pt = self.pt;
19196 const mod = pt.zcu;
1909719197 return switch (ty.zigTypeTag(mod)) {
1909819198 .Float => Memory.Size.fromBitSize(ty.floatBits(self.target.*)),
19099 else => Memory.Size.fromSize(@intCast(ty.abiSize(mod))),
19199 else => Memory.Size.fromSize(@intCast(ty.abiSize(pt))),
1910019200 };
1910119201}
1910219202
1910319203fn splitType(self: *Self, ty: Type) ![2]Type {
19104 const mod = self.bin_file.comp.module.?;
19105 const classes = mem.sliceTo(&abi.classifySystemV(ty, mod, self.target.*, .other), .none);
19204 const pt = self.pt;
19205 const classes = mem.sliceTo(&abi.classifySystemV(ty, pt, self.target.*, .other), .none);
1910619206 var parts: [2]Type = undefined;
1910719207 if (classes.len == 2) for (&parts, classes, 0..) |*part, class, part_i| {
1910819208 part.* = switch (class) {
1910919209 .integer => switch (part_i) {
1911019210 0 => Type.u64,
1911119211 1 => part: {
19112 const elem_size = ty.abiAlignment(mod).minStrict(.@"8").toByteUnits().?;
19113 const elem_ty = try mod.intType(.unsigned, @intCast(elem_size * 8));
19114 break :part switch (@divExact(ty.abiSize(mod) - 8, elem_size)) {
19212 const elem_size = ty.abiAlignment(pt).minStrict(.@"8").toByteUnits().?;
19213 const elem_ty = try pt.intType(.unsigned, @intCast(elem_size * 8));
19214 break :part switch (@divExact(ty.abiSize(pt) - 8, elem_size)) {
1911519215 1 => elem_ty,
19116 else => |len| try mod.arrayType(.{ .len = len, .child = elem_ty.toIntern() }),
19216 else => |len| try pt.arrayType(.{ .len = len, .child = elem_ty.toIntern() }),
1911719217 };
1911819218 },
1911919219 else => unreachable,
1912019220 },
1912119221 .float => Type.f32,
19122 .float_combine => try mod.arrayType(.{ .len = 2, .child = .f32_type }),
19222 .float_combine => try pt.arrayType(.{ .len = 2, .child = .f32_type }),
1912319223 .sse => Type.f64,
1912419224 else => break,
1912519225 };
19126 } else if (parts[0].abiSize(mod) + parts[1].abiSize(mod) == ty.abiSize(mod)) return parts;
19127 return self.fail("TODO implement splitType for {}", .{ty.fmt(mod)});
19226 } else if (parts[0].abiSize(pt) + parts[1].abiSize(pt) == ty.abiSize(pt)) return parts;
19227 return self.fail("TODO implement splitType for {}", .{ty.fmt(pt)});
1912819228}
1912919229
1913019230/// Truncates the value in the register in place.
1913119231/// Clobbers any remaining bits.
1913219232fn truncateRegister(self: *Self, ty: Type, reg: Register) !void {
19133 const mod = self.bin_file.comp.module.?;
19233 const pt = self.pt;
19234 const mod = pt.zcu;
1913419235 const int_info = if (ty.isAbiInt(mod)) ty.intInfo(mod) else std.builtin.Type.Int{
1913519236 .signedness = .unsigned,
19136 .bits = @intCast(ty.bitSize(mod)),
19237 .bits = @intCast(ty.bitSize(pt)),
1913719238 };
1913819239 const shift = math.cast(u6, 64 - int_info.bits % 64) orelse return;
1913919240 try self.spillEflagsIfOccupied();
......@@ -19177,8 +19278,9 @@ fn truncateRegister(self: *Self, ty: Type, reg: Register) !void {
1917719278}
1917819279
1917919280fn regBitSize(self: *Self, ty: Type) u64 {
19180 const mod = self.bin_file.comp.module.?;
19181 const abi_size = ty.abiSize(mod);
19281 const pt = self.pt;
19282 const mod = pt.zcu;
19283 const abi_size = ty.abiSize(pt);
1918219284 return switch (ty.zigTypeTag(mod)) {
1918319285 else => switch (abi_size) {
1918419286 1 => 8,
......@@ -19196,8 +19298,7 @@ fn regBitSize(self: *Self, ty: Type) u64 {
1919619298}
1919719299
1919819300fn regExtraBits(self: *Self, ty: Type) u64 {
19199 const mod = self.bin_file.comp.module.?;
19200 return self.regBitSize(ty) - ty.bitSize(mod);
19301 return self.regBitSize(ty) - ty.bitSize(self.pt);
1920119302}
1920219303
1920319304fn hasFeature(self: *Self, feature: Target.x86.Feature) bool {
......@@ -19211,12 +19312,14 @@ fn hasAllFeatures(self: *Self, features: anytype) bool {
1921119312}
1921219313
1921319314fn typeOf(self: *Self, inst: Air.Inst.Ref) Type {
19214 const mod = self.bin_file.comp.module.?;
19315 const pt = self.pt;
19316 const mod = pt.zcu;
1921519317 return self.air.typeOf(inst, &mod.intern_pool);
1921619318}
1921719319
1921819320fn typeOfIndex(self: *Self, inst: Air.Inst.Index) Type {
19219 const mod = self.bin_file.comp.module.?;
19321 const pt = self.pt;
19322 const mod = pt.zcu;
1922019323 return self.air.typeOfIndex(inst, &mod.intern_pool);
1922119324}
1922219325
......@@ -19268,7 +19371,8 @@ fn floatLibcAbiSuffix(ty: Type) []const u8 {
1926819371}
1926919372
1927019373fn promoteInt(self: *Self, ty: Type) Type {
19271 const mod = self.bin_file.comp.module.?;
19374 const pt = self.pt;
19375 const mod = pt.zcu;
1927219376 const int_info: InternPool.Key.IntType = switch (ty.toIntern()) {
1927319377 .bool_type => .{ .signedness = .unsigned, .bits = 1 },
1927419378 else => if (ty.isAbiInt(mod)) ty.intInfo(mod) else return ty,
src/arch/x86_64/Lower.zig+2-4
......@@ -8,7 +8,7 @@ allocator: Allocator,
88mir: Mir,
99cc: std.builtin.CallingConvention,
1010err_msg: ?*ErrorMsg = null,
11src_loc: Module.LazySrcLoc,
11src_loc: Zcu.LazySrcLoc,
1212result_insts_len: u8 = undefined,
1313result_relocs_len: u8 = undefined,
1414result_insts: [
......@@ -657,7 +657,7 @@ const std = @import("std");
657657
658658const Air = @import("../../Air.zig");
659659const Allocator = std.mem.Allocator;
660const ErrorMsg = Module.ErrorMsg;
660const ErrorMsg = Zcu.ErrorMsg;
661661const Immediate = bits.Immediate;
662662const Instruction = encoder.Instruction;
663663const Lower = @This();
......@@ -665,8 +665,6 @@ const Memory = Instruction.Memory;
665665const Mir = @import("Mir.zig");
666666const Mnemonic = Instruction.Mnemonic;
667667const Zcu = @import("../../Zcu.zig");
668/// Deprecated.
669const Module = Zcu;
670668const Operand = Instruction.Operand;
671669const Prefix = Instruction.Prefix;
672670const Register = bits.Register;
src/arch/x86_64/abi.zig+35-35
......@@ -44,7 +44,7 @@ pub const Class = enum {
4444 }
4545};
4646
47pub fn classifyWindows(ty: Type, zcu: *Zcu) Class {
47pub fn classifyWindows(ty: Type, pt: Zcu.PerThread) Class {
4848 // https://docs.microsoft.com/en-gb/cpp/build/x64-calling-convention?view=vs-2017
4949 // "There's a strict one-to-one correspondence between a function call's arguments
5050 // and the registers used for those arguments. Any argument that doesn't fit in 8
......@@ -53,7 +53,7 @@ pub fn classifyWindows(ty: Type, zcu: *Zcu) Class {
5353 // "All floating point operations are done using the 16 XMM registers."
5454 // "Structs and unions of size 8, 16, 32, or 64 bits, and __m64 types, are passed
5555 // as if they were integers of the same size."
56 switch (ty.zigTypeTag(zcu)) {
56 switch (ty.zigTypeTag(pt.zcu)) {
5757 .Pointer,
5858 .Int,
5959 .Bool,
......@@ -68,12 +68,12 @@ pub fn classifyWindows(ty: Type, zcu: *Zcu) Class {
6868 .ErrorUnion,
6969 .AnyFrame,
7070 .Frame,
71 => switch (ty.abiSize(zcu)) {
71 => switch (ty.abiSize(pt)) {
7272 0 => unreachable,
7373 1, 2, 4, 8 => return .integer,
74 else => switch (ty.zigTypeTag(zcu)) {
74 else => switch (ty.zigTypeTag(pt.zcu)) {
7575 .Int => return .win_i128,
76 .Struct, .Union => if (ty.containerLayout(zcu) == .@"packed") {
76 .Struct, .Union => if (ty.containerLayout(pt.zcu) == .@"packed") {
7777 return .win_i128;
7878 } else {
7979 return .memory;
......@@ -100,14 +100,14 @@ pub const Context = enum { ret, arg, field, other };
100100
101101/// There are a maximum of 8 possible return slots. Returned values are in
102102/// the beginning of the array; unused slots are filled with .none.
103pub fn classifySystemV(ty: Type, zcu: *Zcu, target: std.Target, ctx: Context) [8]Class {
103pub fn classifySystemV(ty: Type, pt: Zcu.PerThread, target: std.Target, ctx: Context) [8]Class {
104104 const memory_class = [_]Class{
105105 .memory, .none, .none, .none,
106106 .none, .none, .none, .none,
107107 };
108108 var result = [1]Class{.none} ** 8;
109 switch (ty.zigTypeTag(zcu)) {
110 .Pointer => switch (ty.ptrSize(zcu)) {
109 switch (ty.zigTypeTag(pt.zcu)) {
110 .Pointer => switch (ty.ptrSize(pt.zcu)) {
111111 .Slice => {
112112 result[0] = .integer;
113113 result[1] = .integer;
......@@ -119,7 +119,7 @@ pub fn classifySystemV(ty: Type, zcu: *Zcu, target: std.Target, ctx: Context) [8
119119 },
120120 },
121121 .Int, .Enum, .ErrorSet => {
122 const bits = ty.intInfo(zcu).bits;
122 const bits = ty.intInfo(pt.zcu).bits;
123123 if (bits <= 64) {
124124 result[0] = .integer;
125125 return result;
......@@ -185,8 +185,8 @@ pub fn classifySystemV(ty: Type, zcu: *Zcu, target: std.Target, ctx: Context) [8
185185 else => unreachable,
186186 },
187187 .Vector => {
188 const elem_ty = ty.childType(zcu);
189 const bits = elem_ty.bitSize(zcu) * ty.arrayLen(zcu);
188 const elem_ty = ty.childType(pt.zcu);
189 const bits = elem_ty.bitSize(pt) * ty.arrayLen(pt.zcu);
190190 if (elem_ty.toIntern() == .bool_type) {
191191 if (bits <= 32) return .{
192192 .integer, .none, .none, .none,
......@@ -250,7 +250,7 @@ pub fn classifySystemV(ty: Type, zcu: *Zcu, target: std.Target, ctx: Context) [8
250250 return memory_class;
251251 },
252252 .Optional => {
253 if (ty.isPtrLikeOptional(zcu)) {
253 if (ty.isPtrLikeOptional(pt.zcu)) {
254254 result[0] = .integer;
255255 return result;
256256 }
......@@ -261,8 +261,8 @@ pub fn classifySystemV(ty: Type, zcu: *Zcu, target: std.Target, ctx: Context) [8
261261 // it contains unaligned fields, it has class MEMORY"
262262 // "If the size of the aggregate exceeds a single eightbyte, each is classified
263263 // separately.".
264 const ty_size = ty.abiSize(zcu);
265 switch (ty.containerLayout(zcu)) {
264 const ty_size = ty.abiSize(pt);
265 switch (ty.containerLayout(pt.zcu)) {
266266 .auto, .@"extern" => {},
267267 .@"packed" => {
268268 assert(ty_size <= 16);
......@@ -274,10 +274,10 @@ pub fn classifySystemV(ty: Type, zcu: *Zcu, target: std.Target, ctx: Context) [8
274274 if (ty_size > 64)
275275 return memory_class;
276276
277 _ = if (zcu.typeToStruct(ty)) |loaded_struct|
278 classifySystemVStruct(&result, 0, loaded_struct, zcu, target)
279 else if (zcu.typeToUnion(ty)) |loaded_union|
280 classifySystemVUnion(&result, 0, loaded_union, zcu, target)
277 _ = if (pt.zcu.typeToStruct(ty)) |loaded_struct|
278 classifySystemVStruct(&result, 0, loaded_struct, pt, target)
279 else if (pt.zcu.typeToUnion(ty)) |loaded_union|
280 classifySystemVUnion(&result, 0, loaded_union, pt, target)
281281 else
282282 unreachable;
283283
......@@ -306,7 +306,7 @@ pub fn classifySystemV(ty: Type, zcu: *Zcu, target: std.Target, ctx: Context) [8
306306 return result;
307307 },
308308 .Array => {
309 const ty_size = ty.abiSize(zcu);
309 const ty_size = ty.abiSize(pt);
310310 if (ty_size <= 8) {
311311 result[0] = .integer;
312312 return result;
......@@ -326,10 +326,10 @@ fn classifySystemVStruct(
326326 result: *[8]Class,
327327 starting_byte_offset: u64,
328328 loaded_struct: InternPool.LoadedStructType,
329 zcu: *Zcu,
329 pt: Zcu.PerThread,
330330 target: std.Target,
331331) u64 {
332 const ip = &zcu.intern_pool;
332 const ip = &pt.zcu.intern_pool;
333333 var byte_offset = starting_byte_offset;
334334 var field_it = loaded_struct.iterateRuntimeOrder(ip);
335335 while (field_it.next()) |field_index| {
......@@ -338,29 +338,29 @@ fn classifySystemVStruct(
338338 byte_offset = std.mem.alignForward(
339339 u64,
340340 byte_offset,
341 field_align.toByteUnits() orelse field_ty.abiAlignment(zcu).toByteUnits().?,
341 field_align.toByteUnits() orelse field_ty.abiAlignment(pt).toByteUnits().?,
342342 );
343 if (zcu.typeToStruct(field_ty)) |field_loaded_struct| {
343 if (pt.zcu.typeToStruct(field_ty)) |field_loaded_struct| {
344344 switch (field_loaded_struct.layout) {
345345 .auto, .@"extern" => {
346 byte_offset = classifySystemVStruct(result, byte_offset, field_loaded_struct, zcu, target);
346 byte_offset = classifySystemVStruct(result, byte_offset, field_loaded_struct, pt, target);
347347 continue;
348348 },
349349 .@"packed" => {},
350350 }
351 } else if (zcu.typeToUnion(field_ty)) |field_loaded_union| {
351 } else if (pt.zcu.typeToUnion(field_ty)) |field_loaded_union| {
352352 switch (field_loaded_union.getLayout(ip)) {
353353 .auto, .@"extern" => {
354 byte_offset = classifySystemVUnion(result, byte_offset, field_loaded_union, zcu, target);
354 byte_offset = classifySystemVUnion(result, byte_offset, field_loaded_union, pt, target);
355355 continue;
356356 },
357357 .@"packed" => {},
358358 }
359359 }
360 const field_classes = std.mem.sliceTo(&classifySystemV(field_ty, zcu, target, .field), .none);
360 const field_classes = std.mem.sliceTo(&classifySystemV(field_ty, pt, target, .field), .none);
361361 for (result[@intCast(byte_offset / 8)..][0..field_classes.len], field_classes) |*result_class, field_class|
362362 result_class.* = result_class.combineSystemV(field_class);
363 byte_offset += field_ty.abiSize(zcu);
363 byte_offset += field_ty.abiSize(pt);
364364 }
365365 const final_byte_offset = starting_byte_offset + loaded_struct.size(ip).*;
366366 std.debug.assert(final_byte_offset == std.mem.alignForward(
......@@ -375,30 +375,30 @@ fn classifySystemVUnion(
375375 result: *[8]Class,
376376 starting_byte_offset: u64,
377377 loaded_union: InternPool.LoadedUnionType,
378 zcu: *Zcu,
378 pt: Zcu.PerThread,
379379 target: std.Target,
380380) u64 {
381 const ip = &zcu.intern_pool;
381 const ip = &pt.zcu.intern_pool;
382382 for (0..loaded_union.field_types.len) |field_index| {
383383 const field_ty = Type.fromInterned(loaded_union.field_types.get(ip)[field_index]);
384 if (zcu.typeToStruct(field_ty)) |field_loaded_struct| {
384 if (pt.zcu.typeToStruct(field_ty)) |field_loaded_struct| {
385385 switch (field_loaded_struct.layout) {
386386 .auto, .@"extern" => {
387 _ = classifySystemVStruct(result, starting_byte_offset, field_loaded_struct, zcu, target);
387 _ = classifySystemVStruct(result, starting_byte_offset, field_loaded_struct, pt, target);
388388 continue;
389389 },
390390 .@"packed" => {},
391391 }
392 } else if (zcu.typeToUnion(field_ty)) |field_loaded_union| {
392 } else if (pt.zcu.typeToUnion(field_ty)) |field_loaded_union| {
393393 switch (field_loaded_union.getLayout(ip)) {
394394 .auto, .@"extern" => {
395 _ = classifySystemVUnion(result, starting_byte_offset, field_loaded_union, zcu, target);
395 _ = classifySystemVUnion(result, starting_byte_offset, field_loaded_union, pt, target);
396396 continue;
397397 },
398398 .@"packed" => {},
399399 }
400400 }
401 const field_classes = std.mem.sliceTo(&classifySystemV(field_ty, zcu, target, .field), .none);
401 const field_classes = std.mem.sliceTo(&classifySystemV(field_ty, pt, target, .field), .none);
402402 for (result[@intCast(starting_byte_offset / 8)..][0..field_classes.len], field_classes) |*result_class, field_class|
403403 result_class.* = result_class.combineSystemV(field_class);
404404 }
src/codegen.zig+141-130
......@@ -13,12 +13,10 @@ const trace = @import("tracy.zig").trace;
1313const Air = @import("Air.zig");
1414const Allocator = mem.Allocator;
1515const Compilation = @import("Compilation.zig");
16const ErrorMsg = Module.ErrorMsg;
16const ErrorMsg = Zcu.ErrorMsg;
1717const InternPool = @import("InternPool.zig");
1818const Liveness = @import("Liveness.zig");
1919const Zcu = @import("Zcu.zig");
20/// Deprecated.
21const Module = Zcu;
2220const Target = std.Target;
2321const Type = @import("Type.zig");
2422const Value = @import("Value.zig");
......@@ -47,14 +45,15 @@ pub const DebugInfoOutput = union(enum) {
4745
4846pub fn generateFunction(
4947 lf: *link.File,
50 src_loc: Module.LazySrcLoc,
48 pt: Zcu.PerThread,
49 src_loc: Zcu.LazySrcLoc,
5150 func_index: InternPool.Index,
5251 air: Air,
5352 liveness: Liveness,
5453 code: *std.ArrayList(u8),
5554 debug_output: DebugInfoOutput,
5655) CodeGenError!Result {
57 const zcu = lf.comp.module.?;
56 const zcu = pt.zcu;
5857 const func = zcu.funcInfo(func_index);
5958 const decl = zcu.declPtr(func.owner_decl);
6059 const namespace = zcu.namespacePtr(decl.src_namespace);
......@@ -62,35 +61,36 @@ pub fn generateFunction(
6261 switch (target.cpu.arch) {
6362 .arm,
6463 .armeb,
65 => return @import("arch/arm/CodeGen.zig").generate(lf, src_loc, func_index, air, liveness, code, debug_output),
64 => return @import("arch/arm/CodeGen.zig").generate(lf, pt, src_loc, func_index, air, liveness, code, debug_output),
6665 .aarch64,
6766 .aarch64_be,
6867 .aarch64_32,
69 => return @import("arch/aarch64/CodeGen.zig").generate(lf, src_loc, func_index, air, liveness, code, debug_output),
70 .riscv64 => return @import("arch/riscv64/CodeGen.zig").generate(lf, src_loc, func_index, air, liveness, code, debug_output),
71 .sparc64 => return @import("arch/sparc64/CodeGen.zig").generate(lf, src_loc, func_index, air, liveness, code, debug_output),
72 .x86_64 => return @import("arch/x86_64/CodeGen.zig").generate(lf, src_loc, func_index, air, liveness, code, debug_output),
68 => return @import("arch/aarch64/CodeGen.zig").generate(lf, pt, src_loc, func_index, air, liveness, code, debug_output),
69 .riscv64 => return @import("arch/riscv64/CodeGen.zig").generate(lf, pt, src_loc, func_index, air, liveness, code, debug_output),
70 .sparc64 => return @import("arch/sparc64/CodeGen.zig").generate(lf, pt, src_loc, func_index, air, liveness, code, debug_output),
71 .x86_64 => return @import("arch/x86_64/CodeGen.zig").generate(lf, pt, src_loc, func_index, air, liveness, code, debug_output),
7372 .wasm32,
7473 .wasm64,
75 => return @import("arch/wasm/CodeGen.zig").generate(lf, src_loc, func_index, air, liveness, code, debug_output),
74 => return @import("arch/wasm/CodeGen.zig").generate(lf, pt, src_loc, func_index, air, liveness, code, debug_output),
7675 else => unreachable,
7776 }
7877}
7978
8079pub fn generateLazyFunction(
8180 lf: *link.File,
82 src_loc: Module.LazySrcLoc,
81 pt: Zcu.PerThread,
82 src_loc: Zcu.LazySrcLoc,
8383 lazy_sym: link.File.LazySymbol,
8484 code: *std.ArrayList(u8),
8585 debug_output: DebugInfoOutput,
8686) CodeGenError!Result {
87 const zcu = lf.comp.module.?;
87 const zcu = pt.zcu;
8888 const decl_index = lazy_sym.ty.getOwnerDecl(zcu);
8989 const decl = zcu.declPtr(decl_index);
9090 const namespace = zcu.namespacePtr(decl.src_namespace);
9191 const target = namespace.fileScope(zcu).mod.resolved_target.result;
9292 switch (target.cpu.arch) {
93 .x86_64 => return @import("arch/x86_64/CodeGen.zig").generateLazy(lf, src_loc, lazy_sym, code, debug_output),
93 .x86_64 => return @import("arch/x86_64/CodeGen.zig").generateLazy(lf, pt, src_loc, lazy_sym, code, debug_output),
9494 else => unreachable,
9595 }
9696}
......@@ -105,7 +105,8 @@ fn writeFloat(comptime F: type, f: F, target: Target, endian: std.builtin.Endian
105105
106106pub fn generateLazySymbol(
107107 bin_file: *link.File,
108 src_loc: Module.LazySrcLoc,
108 pt: Zcu.PerThread,
109 src_loc: Zcu.LazySrcLoc,
109110 lazy_sym: link.File.LazySymbol,
110111 // TODO don't use an "out" parameter like this; put it in the result instead
111112 alignment: *Alignment,
......@@ -119,25 +120,24 @@ pub fn generateLazySymbol(
119120 defer tracy.end();
120121
121122 const comp = bin_file.comp;
122 const zcu = comp.module.?;
123 const ip = &zcu.intern_pool;
123 const ip = &pt.zcu.intern_pool;
124124 const target = comp.root_mod.resolved_target.result;
125125 const endian = target.cpu.arch.endian();
126126 const gpa = comp.gpa;
127127
128128 log.debug("generateLazySymbol: kind = {s}, ty = {}", .{
129129 @tagName(lazy_sym.kind),
130 lazy_sym.ty.fmt(zcu),
130 lazy_sym.ty.fmt(pt),
131131 });
132132
133133 if (lazy_sym.kind == .code) {
134134 alignment.* = target_util.defaultFunctionAlignment(target);
135 return generateLazyFunction(bin_file, src_loc, lazy_sym, code, debug_output);
135 return generateLazyFunction(bin_file, pt, src_loc, lazy_sym, code, debug_output);
136136 }
137137
138 if (lazy_sym.ty.isAnyError(zcu)) {
138 if (lazy_sym.ty.isAnyError(pt.zcu)) {
139139 alignment.* = .@"4";
140 const err_names = zcu.global_error_set.keys();
140 const err_names = pt.zcu.global_error_set.keys();
141141 mem.writeInt(u32, try code.addManyAsArray(4), @intCast(err_names.len), endian);
142142 var offset = code.items.len;
143143 try code.resize((1 + err_names.len + 1) * 4);
......@@ -151,9 +151,9 @@ pub fn generateLazySymbol(
151151 }
152152 mem.writeInt(u32, code.items[offset..][0..4], @intCast(code.items.len), endian);
153153 return Result.ok;
154 } else if (lazy_sym.ty.zigTypeTag(zcu) == .Enum) {
154 } else if (lazy_sym.ty.zigTypeTag(pt.zcu) == .Enum) {
155155 alignment.* = .@"1";
156 const tag_names = lazy_sym.ty.enumFields(zcu);
156 const tag_names = lazy_sym.ty.enumFields(pt.zcu);
157157 for (0..tag_names.len) |tag_index| {
158158 const tag_name = tag_names.get(ip)[tag_index].toSlice(ip);
159159 try code.ensureUnusedCapacity(tag_name.len + 1);
......@@ -165,13 +165,14 @@ pub fn generateLazySymbol(
165165 gpa,
166166 src_loc,
167167 "TODO implement generateLazySymbol for {s} {}",
168 .{ @tagName(lazy_sym.kind), lazy_sym.ty.fmt(zcu) },
168 .{ @tagName(lazy_sym.kind), lazy_sym.ty.fmt(pt) },
169169 ) };
170170}
171171
172172pub fn generateSymbol(
173173 bin_file: *link.File,
174 src_loc: Module.LazySrcLoc,
174 pt: Zcu.PerThread,
175 src_loc: Zcu.LazySrcLoc,
175176 val: Value,
176177 code: *std.ArrayList(u8),
177178 debug_output: DebugInfoOutput,
......@@ -180,17 +181,17 @@ pub fn generateSymbol(
180181 const tracy = trace(@src());
181182 defer tracy.end();
182183
183 const mod = bin_file.comp.module.?;
184 const mod = pt.zcu;
184185 const ip = &mod.intern_pool;
185186 const ty = val.typeOf(mod);
186187
187188 const target = mod.getTarget();
188189 const endian = target.cpu.arch.endian();
189190
190 log.debug("generateSymbol: val = {}", .{val.fmtValue(mod, null)});
191 log.debug("generateSymbol: val = {}", .{val.fmtValue(pt, null)});
191192
192193 if (val.isUndefDeep(mod)) {
193 const abi_size = math.cast(usize, ty.abiSize(mod)) orelse return error.Overflow;
194 const abi_size = math.cast(usize, ty.abiSize(pt)) orelse return error.Overflow;
194195 try code.appendNTimes(0xaa, abi_size);
195196 return .ok;
196197 }
......@@ -236,9 +237,9 @@ pub fn generateSymbol(
236237 .empty_enum_value,
237238 => unreachable, // non-runtime values
238239 .int => {
239 const abi_size = math.cast(usize, ty.abiSize(mod)) orelse return error.Overflow;
240 const abi_size = math.cast(usize, ty.abiSize(pt)) orelse return error.Overflow;
240241 var space: Value.BigIntSpace = undefined;
241 const int_val = val.toBigInt(&space, mod);
242 const int_val = val.toBigInt(&space, pt);
242243 int_val.writeTwosComplement(try code.addManyAsSlice(abi_size), endian);
243244 },
244245 .err => |err| {
......@@ -252,14 +253,14 @@ pub fn generateSymbol(
252253 .payload => 0,
253254 };
254255
255 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
256 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
256257 try code.writer().writeInt(u16, err_val, endian);
257258 return .ok;
258259 }
259260
260 const payload_align = payload_ty.abiAlignment(mod);
261 const error_align = Type.anyerror.abiAlignment(mod);
262 const abi_align = ty.abiAlignment(mod);
261 const payload_align = payload_ty.abiAlignment(pt);
262 const error_align = Type.anyerror.abiAlignment(pt);
263 const abi_align = ty.abiAlignment(pt);
263264
264265 // error value first when its type is larger than the error union's payload
265266 if (error_align.order(payload_align) == .gt) {
......@@ -269,8 +270,8 @@ pub fn generateSymbol(
269270 // emit payload part of the error union
270271 {
271272 const begin = code.items.len;
272 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(switch (error_union.val) {
273 .err_name => try mod.intern(.{ .undef = payload_ty.toIntern() }),
273 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(switch (error_union.val) {
274 .err_name => try pt.intern(.{ .undef = payload_ty.toIntern() }),
274275 .payload => |payload| payload,
275276 }), code, debug_output, reloc_info)) {
276277 .ok => {},
......@@ -300,7 +301,7 @@ pub fn generateSymbol(
300301 },
301302 .enum_tag => |enum_tag| {
302303 const int_tag_ty = ty.intTagType(mod);
303 switch (try generateSymbol(bin_file, src_loc, try mod.getCoerced(Value.fromInterned(enum_tag.int), int_tag_ty), code, debug_output, reloc_info)) {
304 switch (try generateSymbol(bin_file, pt, src_loc, try pt.getCoerced(Value.fromInterned(enum_tag.int), int_tag_ty), code, debug_output, reloc_info)) {
304305 .ok => {},
305306 .fail => |em| return .{ .fail = em },
306307 }
......@@ -311,21 +312,21 @@ pub fn generateSymbol(
311312 .f64 => |f64_val| writeFloat(f64, f64_val, target, endian, try code.addManyAsArray(8)),
312313 .f80 => |f80_val| {
313314 writeFloat(f80, f80_val, target, endian, try code.addManyAsArray(10));
314 const abi_size = math.cast(usize, ty.abiSize(mod)) orelse return error.Overflow;
315 const abi_size = math.cast(usize, ty.abiSize(pt)) orelse return error.Overflow;
315316 try code.appendNTimes(0, abi_size - 10);
316317 },
317318 .f128 => |f128_val| writeFloat(f128, f128_val, target, endian, try code.addManyAsArray(16)),
318319 },
319 .ptr => switch (try lowerPtr(bin_file, src_loc, val.toIntern(), code, debug_output, reloc_info, 0)) {
320 .ptr => switch (try lowerPtr(bin_file, pt, src_loc, val.toIntern(), code, debug_output, reloc_info, 0)) {
320321 .ok => {},
321322 .fail => |em| return .{ .fail = em },
322323 },
323324 .slice => |slice| {
324 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(slice.ptr), code, debug_output, reloc_info)) {
325 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(slice.ptr), code, debug_output, reloc_info)) {
325326 .ok => {},
326327 .fail => |em| return .{ .fail = em },
327328 }
328 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(slice.len), code, debug_output, reloc_info)) {
329 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(slice.len), code, debug_output, reloc_info)) {
329330 .ok => {},
330331 .fail => |em| return .{ .fail = em },
331332 }
......@@ -333,11 +334,11 @@ pub fn generateSymbol(
333334 .opt => {
334335 const payload_type = ty.optionalChild(mod);
335336 const payload_val = val.optionalValue(mod);
336 const abi_size = math.cast(usize, ty.abiSize(mod)) orelse return error.Overflow;
337 const abi_size = math.cast(usize, ty.abiSize(pt)) orelse return error.Overflow;
337338
338339 if (ty.optionalReprIsPayload(mod)) {
339340 if (payload_val) |value| {
340 switch (try generateSymbol(bin_file, src_loc, value, code, debug_output, reloc_info)) {
341 switch (try generateSymbol(bin_file, pt, src_loc, value, code, debug_output, reloc_info)) {
341342 .ok => {},
342343 .fail => |em| return Result{ .fail = em },
343344 }
......@@ -345,10 +346,12 @@ pub fn generateSymbol(
345346 try code.appendNTimes(0, abi_size);
346347 }
347348 } else {
348 const padding = abi_size - (math.cast(usize, payload_type.abiSize(mod)) orelse return error.Overflow) - 1;
349 if (payload_type.hasRuntimeBits(mod)) {
350 const value = payload_val orelse Value.fromInterned((try mod.intern(.{ .undef = payload_type.toIntern() })));
351 switch (try generateSymbol(bin_file, src_loc, value, code, debug_output, reloc_info)) {
349 const padding = abi_size - (math.cast(usize, payload_type.abiSize(pt)) orelse return error.Overflow) - 1;
350 if (payload_type.hasRuntimeBits(pt)) {
351 const value = payload_val orelse Value.fromInterned(try pt.intern(.{
352 .undef = payload_type.toIntern(),
353 }));
354 switch (try generateSymbol(bin_file, pt, src_loc, value, code, debug_output, reloc_info)) {
352355 .ok => {},
353356 .fail => |em| return Result{ .fail = em },
354357 }
......@@ -363,7 +366,7 @@ pub fn generateSymbol(
363366 .elems, .repeated_elem => {
364367 var index: u64 = 0;
365368 while (index < array_type.lenIncludingSentinel()) : (index += 1) {
366 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(switch (aggregate.storage) {
369 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(switch (aggregate.storage) {
367370 .bytes => unreachable,
368371 .elems => |elems| elems[@intCast(index)],
369372 .repeated_elem => |elem| if (index < array_type.len)
......@@ -378,8 +381,7 @@ pub fn generateSymbol(
378381 },
379382 },
380383 .vector_type => |vector_type| {
381 const abi_size = math.cast(usize, ty.abiSize(mod)) orelse
382 return error.Overflow;
384 const abi_size = math.cast(usize, ty.abiSize(pt)) orelse return error.Overflow;
383385 if (vector_type.child == .bool_type) {
384386 const bytes = try code.addManyAsSlice(abi_size);
385387 @memset(bytes, 0xaa);
......@@ -424,7 +426,7 @@ pub fn generateSymbol(
424426 .elems, .repeated_elem => {
425427 var index: u64 = 0;
426428 while (index < vector_type.len) : (index += 1) {
427 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(switch (aggregate.storage) {
429 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(switch (aggregate.storage) {
428430 .bytes => unreachable,
429431 .elems => |elems| elems[
430432 math.cast(usize, index) orelse return error.Overflow
......@@ -439,7 +441,7 @@ pub fn generateSymbol(
439441 }
440442
441443 const padding = abi_size -
442 (math.cast(usize, Type.fromInterned(vector_type.child).abiSize(mod) * vector_type.len) orelse
444 (math.cast(usize, Type.fromInterned(vector_type.child).abiSize(pt) * vector_type.len) orelse
443445 return error.Overflow);
444446 if (padding > 0) try code.appendNTimes(0, padding);
445447 }
......@@ -452,10 +454,10 @@ pub fn generateSymbol(
452454 0..,
453455 ) |field_ty, comptime_val, index| {
454456 if (comptime_val != .none) continue;
455 if (!Type.fromInterned(field_ty).hasRuntimeBits(mod)) continue;
457 if (!Type.fromInterned(field_ty).hasRuntimeBits(pt)) continue;
456458
457459 const field_val = switch (aggregate.storage) {
458 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{
460 .bytes => |bytes| try pt.intern(.{ .int = .{
459461 .ty = field_ty,
460462 .storage = .{ .u64 = bytes.at(index, ip) },
461463 } }),
......@@ -463,14 +465,14 @@ pub fn generateSymbol(
463465 .repeated_elem => |elem| elem,
464466 };
465467
466 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(field_val), code, debug_output, reloc_info)) {
468 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(field_val), code, debug_output, reloc_info)) {
467469 .ok => {},
468470 .fail => |em| return Result{ .fail = em },
469471 }
470472 const unpadded_field_end = code.items.len - struct_begin;
471473
472474 // Pad struct members if required
473 const padded_field_end = ty.structFieldOffset(index + 1, mod);
475 const padded_field_end = ty.structFieldOffset(index + 1, pt);
474476 const padding = math.cast(usize, padded_field_end - unpadded_field_end) orelse
475477 return error.Overflow;
476478
......@@ -483,15 +485,14 @@ pub fn generateSymbol(
483485 const struct_type = ip.loadStructType(ty.toIntern());
484486 switch (struct_type.layout) {
485487 .@"packed" => {
486 const abi_size = math.cast(usize, ty.abiSize(mod)) orelse
487 return error.Overflow;
488 const abi_size = math.cast(usize, ty.abiSize(pt)) orelse return error.Overflow;
488489 const current_pos = code.items.len;
489490 try code.appendNTimes(0, abi_size);
490491 var bits: u16 = 0;
491492
492493 for (struct_type.field_types.get(ip), 0..) |field_ty, index| {
493494 const field_val = switch (aggregate.storage) {
494 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{
495 .bytes => |bytes| try pt.intern(.{ .int = .{
495496 .ty = field_ty,
496497 .storage = .{ .u64 = bytes.at(index, ip) },
497498 } }),
......@@ -502,18 +503,18 @@ pub fn generateSymbol(
502503 // pointer may point to a decl which must be marked used
503504 // but can also result in a relocation. Therefore we handle those separately.
504505 if (Type.fromInterned(field_ty).zigTypeTag(mod) == .Pointer) {
505 const field_size = math.cast(usize, Type.fromInterned(field_ty).abiSize(mod)) orelse
506 const field_size = math.cast(usize, Type.fromInterned(field_ty).abiSize(pt)) orelse
506507 return error.Overflow;
507508 var tmp_list = try std.ArrayList(u8).initCapacity(code.allocator, field_size);
508509 defer tmp_list.deinit();
509 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(field_val), &tmp_list, debug_output, reloc_info)) {
510 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(field_val), &tmp_list, debug_output, reloc_info)) {
510511 .ok => @memcpy(code.items[current_pos..][0..tmp_list.items.len], tmp_list.items),
511512 .fail => |em| return Result{ .fail = em },
512513 }
513514 } else {
514 Value.fromInterned(field_val).writeToPackedMemory(Type.fromInterned(field_ty), mod, code.items[current_pos..], bits) catch unreachable;
515 Value.fromInterned(field_val).writeToPackedMemory(Type.fromInterned(field_ty), pt, code.items[current_pos..], bits) catch unreachable;
515516 }
516 bits += @intCast(Type.fromInterned(field_ty).bitSize(mod));
517 bits += @intCast(Type.fromInterned(field_ty).bitSize(pt));
517518 }
518519 },
519520 .auto, .@"extern" => {
......@@ -524,10 +525,10 @@ pub fn generateSymbol(
524525 var it = struct_type.iterateRuntimeOrder(ip);
525526 while (it.next()) |field_index| {
526527 const field_ty = field_types[field_index];
527 if (!Type.fromInterned(field_ty).hasRuntimeBits(mod)) continue;
528 if (!Type.fromInterned(field_ty).hasRuntimeBits(pt)) continue;
528529
529530 const field_val = switch (ip.indexToKey(val.toIntern()).aggregate.storage) {
530 .bytes => |bytes| try ip.get(mod.gpa, .{ .int = .{
531 .bytes => |bytes| try pt.intern(.{ .int = .{
531532 .ty = field_ty,
532533 .storage = .{ .u64 = bytes.at(field_index, ip) },
533534 } }),
......@@ -541,7 +542,7 @@ pub fn generateSymbol(
541542 ) orelse return error.Overflow;
542543 if (padding > 0) try code.appendNTimes(0, padding);
543544
544 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(field_val), code, debug_output, reloc_info)) {
545 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(field_val), code, debug_output, reloc_info)) {
545546 .ok => {},
546547 .fail => |em| return Result{ .fail = em },
547548 }
......@@ -562,15 +563,15 @@ pub fn generateSymbol(
562563 else => unreachable,
563564 },
564565 .un => |un| {
565 const layout = ty.unionGetLayout(mod);
566 const layout = ty.unionGetLayout(pt);
566567
567568 if (layout.payload_size == 0) {
568 return generateSymbol(bin_file, src_loc, Value.fromInterned(un.tag), code, debug_output, reloc_info);
569 return generateSymbol(bin_file, pt, src_loc, Value.fromInterned(un.tag), code, debug_output, reloc_info);
569570 }
570571
571572 // Check if we should store the tag first.
572573 if (layout.tag_size > 0 and layout.tag_align.compare(.gte, layout.payload_align)) {
573 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(un.tag), code, debug_output, reloc_info)) {
574 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(un.tag), code, debug_output, reloc_info)) {
574575 .ok => {},
575576 .fail => |em| return Result{ .fail = em },
576577 }
......@@ -580,28 +581,28 @@ pub fn generateSymbol(
580581 if (un.tag != .none) {
581582 const field_index = ty.unionTagFieldIndex(Value.fromInterned(un.tag), mod).?;
582583 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
583 if (!field_ty.hasRuntimeBits(mod)) {
584 if (!field_ty.hasRuntimeBits(pt)) {
584585 try code.appendNTimes(0xaa, math.cast(usize, layout.payload_size) orelse return error.Overflow);
585586 } else {
586 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(un.val), code, debug_output, reloc_info)) {
587 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(un.val), code, debug_output, reloc_info)) {
587588 .ok => {},
588589 .fail => |em| return Result{ .fail = em },
589590 }
590591
591 const padding = math.cast(usize, layout.payload_size - field_ty.abiSize(mod)) orelse return error.Overflow;
592 const padding = math.cast(usize, layout.payload_size - field_ty.abiSize(pt)) orelse return error.Overflow;
592593 if (padding > 0) {
593594 try code.appendNTimes(0, padding);
594595 }
595596 }
596597 } else {
597 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(un.val), code, debug_output, reloc_info)) {
598 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(un.val), code, debug_output, reloc_info)) {
598599 .ok => {},
599600 .fail => |em| return Result{ .fail = em },
600601 }
601602 }
602603
603604 if (layout.tag_size > 0 and layout.tag_align.compare(.lt, layout.payload_align)) {
604 switch (try generateSymbol(bin_file, src_loc, Value.fromInterned(un.tag), code, debug_output, reloc_info)) {
605 switch (try generateSymbol(bin_file, pt, src_loc, Value.fromInterned(un.tag), code, debug_output, reloc_info)) {
605606 .ok => {},
606607 .fail => |em| return Result{ .fail = em },
607608 }
......@@ -618,22 +619,24 @@ pub fn generateSymbol(
618619
619620fn lowerPtr(
620621 bin_file: *link.File,
621 src_loc: Module.LazySrcLoc,
622 pt: Zcu.PerThread,
623 src_loc: Zcu.LazySrcLoc,
622624 ptr_val: InternPool.Index,
623625 code: *std.ArrayList(u8),
624626 debug_output: DebugInfoOutput,
625627 reloc_info: RelocInfo,
626628 prev_offset: u64,
627629) CodeGenError!Result {
628 const zcu = bin_file.comp.module.?;
630 const zcu = pt.zcu;
629631 const ptr = zcu.intern_pool.indexToKey(ptr_val).ptr;
630632 const offset: u64 = prev_offset + ptr.byte_offset;
631633 return switch (ptr.base_addr) {
632 .decl => |decl| try lowerDeclRef(bin_file, src_loc, decl, code, debug_output, reloc_info, offset),
633 .anon_decl => |ad| try lowerAnonDeclRef(bin_file, src_loc, ad, code, debug_output, reloc_info, offset),
634 .int => try generateSymbol(bin_file, src_loc, try zcu.intValue(Type.usize, offset), code, debug_output, reloc_info),
634 .decl => |decl| try lowerDeclRef(bin_file, pt, src_loc, decl, code, debug_output, reloc_info, offset),
635 .anon_decl => |ad| try lowerAnonDeclRef(bin_file, pt, src_loc, ad, code, debug_output, reloc_info, offset),
636 .int => try generateSymbol(bin_file, pt, src_loc, try pt.intValue(Type.usize, offset), code, debug_output, reloc_info),
635637 .eu_payload => |eu_ptr| try lowerPtr(
636638 bin_file,
639 pt,
637640 src_loc,
638641 eu_ptr,
639642 code,
......@@ -641,11 +644,12 @@ fn lowerPtr(
641644 reloc_info,
642645 offset + errUnionPayloadOffset(
643646 Value.fromInterned(eu_ptr).typeOf(zcu).childType(zcu).errorUnionPayload(zcu),
644 zcu,
647 pt,
645648 ),
646649 ),
647650 .opt_payload => |opt_ptr| try lowerPtr(
648651 bin_file,
652 pt,
649653 src_loc,
650654 opt_ptr,
651655 code,
......@@ -666,12 +670,12 @@ fn lowerPtr(
666670 };
667671 },
668672 .Struct, .Union => switch (base_ty.containerLayout(zcu)) {
669 .auto => base_ty.structFieldOffset(@intCast(field.index), zcu),
673 .auto => base_ty.structFieldOffset(@intCast(field.index), pt),
670674 .@"extern", .@"packed" => unreachable,
671675 },
672676 else => unreachable,
673677 };
674 return lowerPtr(bin_file, src_loc, field.base, code, debug_output, reloc_info, offset + field_off);
678 return lowerPtr(bin_file, pt, src_loc, field.base, code, debug_output, reloc_info, offset + field_off);
675679 },
676680 .arr_elem, .comptime_field, .comptime_alloc => unreachable,
677681 };
......@@ -683,7 +687,8 @@ const RelocInfo = struct {
683687
684688fn lowerAnonDeclRef(
685689 lf: *link.File,
686 src_loc: Module.LazySrcLoc,
690 pt: Zcu.PerThread,
691 src_loc: Zcu.LazySrcLoc,
687692 anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl,
688693 code: *std.ArrayList(u8),
689694 debug_output: DebugInfoOutput,
......@@ -691,22 +696,21 @@ fn lowerAnonDeclRef(
691696 offset: u64,
692697) CodeGenError!Result {
693698 _ = debug_output;
694 const zcu = lf.comp.module.?;
695 const ip = &zcu.intern_pool;
699 const ip = &pt.zcu.intern_pool;
696700 const target = lf.comp.root_mod.resolved_target.result;
697701
698702 const ptr_width_bytes = @divExact(target.ptrBitWidth(), 8);
699703 const decl_val = anon_decl.val;
700704 const decl_ty = Type.fromInterned(ip.typeOf(decl_val));
701 log.debug("lowerAnonDecl: ty = {}", .{decl_ty.fmt(zcu)});
702 const is_fn_body = decl_ty.zigTypeTag(zcu) == .Fn;
703 if (!is_fn_body and !decl_ty.hasRuntimeBits(zcu)) {
705 log.debug("lowerAnonDecl: ty = {}", .{decl_ty.fmt(pt)});
706 const is_fn_body = decl_ty.zigTypeTag(pt.zcu) == .Fn;
707 if (!is_fn_body and !decl_ty.hasRuntimeBits(pt)) {
704708 try code.appendNTimes(0xaa, ptr_width_bytes);
705709 return Result.ok;
706710 }
707711
708712 const decl_align = ip.indexToKey(anon_decl.orig_ty).ptr_type.flags.alignment;
709 const res = try lf.lowerAnonDecl(decl_val, decl_align, src_loc);
713 const res = try lf.lowerAnonDecl(pt, decl_val, decl_align, src_loc);
710714 switch (res) {
711715 .ok => {},
712716 .fail => |em| return .{ .fail = em },
......@@ -730,7 +734,8 @@ fn lowerAnonDeclRef(
730734
731735fn lowerDeclRef(
732736 lf: *link.File,
733 src_loc: Module.LazySrcLoc,
737 pt: Zcu.PerThread,
738 src_loc: Zcu.LazySrcLoc,
734739 decl_index: InternPool.DeclIndex,
735740 code: *std.ArrayList(u8),
736741 debug_output: DebugInfoOutput,
......@@ -739,19 +744,19 @@ fn lowerDeclRef(
739744) CodeGenError!Result {
740745 _ = src_loc;
741746 _ = debug_output;
742 const zcu = lf.comp.module.?;
747 const zcu = pt.zcu;
743748 const decl = zcu.declPtr(decl_index);
744749 const namespace = zcu.namespacePtr(decl.src_namespace);
745750 const target = namespace.fileScope(zcu).mod.resolved_target.result;
746751
747752 const ptr_width = target.ptrBitWidth();
748753 const is_fn_body = decl.typeOf(zcu).zigTypeTag(zcu) == .Fn;
749 if (!is_fn_body and !decl.typeOf(zcu).hasRuntimeBits(zcu)) {
754 if (!is_fn_body and !decl.typeOf(zcu).hasRuntimeBits(pt)) {
750755 try code.appendNTimes(0xaa, @divExact(ptr_width, 8));
751756 return Result.ok;
752757 }
753758
754 const vaddr = try lf.getDeclVAddr(decl_index, .{
759 const vaddr = try lf.getDeclVAddr(pt, decl_index, .{
755760 .parent_atom_index = reloc_info.parent_atom_index,
756761 .offset = code.items.len,
757762 .addend = @intCast(offset),
......@@ -814,7 +819,7 @@ pub const GenResult = union(enum) {
814819
815820 fn fail(
816821 gpa: Allocator,
817 src_loc: Module.LazySrcLoc,
822 src_loc: Zcu.LazySrcLoc,
818823 comptime format: []const u8,
819824 args: anytype,
820825 ) Allocator.Error!GenResult {
......@@ -825,14 +830,15 @@ pub const GenResult = union(enum) {
825830
826831fn genDeclRef(
827832 lf: *link.File,
828 src_loc: Module.LazySrcLoc,
833 pt: Zcu.PerThread,
834 src_loc: Zcu.LazySrcLoc,
829835 val: Value,
830836 ptr_decl_index: InternPool.DeclIndex,
831837) CodeGenError!GenResult {
832 const zcu = lf.comp.module.?;
838 const zcu = pt.zcu;
833839 const ip = &zcu.intern_pool;
834840 const ty = val.typeOf(zcu);
835 log.debug("genDeclRef: val = {}", .{val.fmtValue(zcu, null)});
841 log.debug("genDeclRef: val = {}", .{val.fmtValue(pt, null)});
836842
837843 const ptr_decl = zcu.declPtr(ptr_decl_index);
838844 const namespace = zcu.namespacePtr(ptr_decl.src_namespace);
......@@ -848,7 +854,7 @@ fn genDeclRef(
848854 };
849855 const decl = zcu.declPtr(decl_index);
850856
851 if (!decl.typeOf(zcu).isFnOrHasRuntimeBitsIgnoreComptime(zcu)) {
857 if (!decl.typeOf(zcu).isFnOrHasRuntimeBitsIgnoreComptime(pt)) {
852858 const imm: u64 = switch (ptr_bytes) {
853859 1 => 0xaa,
854860 2 => 0xaaaa,
......@@ -865,12 +871,12 @@ fn genDeclRef(
865871 // TODO this feels clunky. Perhaps we should check for it in `genTypedValue`?
866872 if (ty.castPtrToFn(zcu)) |fn_ty| {
867873 if (zcu.typeToFunc(fn_ty).?.is_generic) {
868 return GenResult.mcv(.{ .immediate = fn_ty.abiAlignment(zcu).toByteUnits().? });
874 return GenResult.mcv(.{ .immediate = fn_ty.abiAlignment(pt).toByteUnits().? });
869875 }
870876 } else if (ty.zigTypeTag(zcu) == .Pointer) {
871877 const elem_ty = ty.elemType2(zcu);
872 if (!elem_ty.hasRuntimeBits(zcu)) {
873 return GenResult.mcv(.{ .immediate = elem_ty.abiAlignment(zcu).toByteUnits().? });
878 if (!elem_ty.hasRuntimeBits(pt)) {
879 return GenResult.mcv(.{ .immediate = elem_ty.abiAlignment(pt).toByteUnits().? });
874880 }
875881 }
876882
......@@ -931,15 +937,15 @@ fn genDeclRef(
931937
932938fn genUnnamedConst(
933939 lf: *link.File,
934 src_loc: Module.LazySrcLoc,
940 pt: Zcu.PerThread,
941 src_loc: Zcu.LazySrcLoc,
935942 val: Value,
936943 owner_decl_index: InternPool.DeclIndex,
937944) CodeGenError!GenResult {
938 const zcu = lf.comp.module.?;
939945 const gpa = lf.comp.gpa;
940 log.debug("genUnnamedConst: val = {}", .{val.fmtValue(zcu, null)});
946 log.debug("genUnnamedConst: val = {}", .{val.fmtValue(pt, null)});
941947
942 const local_sym_index = lf.lowerUnnamedConst(val, owner_decl_index) catch |err| {
948 const local_sym_index = lf.lowerUnnamedConst(pt, val, owner_decl_index) catch |err| {
943949 return GenResult.fail(gpa, src_loc, "lowering unnamed constant failed: {s}", .{@errorName(err)});
944950 };
945951 switch (lf.tag) {
......@@ -970,15 +976,16 @@ fn genUnnamedConst(
970976
971977pub fn genTypedValue(
972978 lf: *link.File,
973 src_loc: Module.LazySrcLoc,
979 pt: Zcu.PerThread,
980 src_loc: Zcu.LazySrcLoc,
974981 val: Value,
975982 owner_decl_index: InternPool.DeclIndex,
976983) CodeGenError!GenResult {
977 const zcu = lf.comp.module.?;
984 const zcu = pt.zcu;
978985 const ip = &zcu.intern_pool;
979986 const ty = val.typeOf(zcu);
980987
981 log.debug("genTypedValue: val = {}", .{val.fmtValue(zcu, null)});
988 log.debug("genTypedValue: val = {}", .{val.fmtValue(pt, null)});
982989
983990 if (val.isUndef(zcu))
984991 return GenResult.mcv(.undef);
......@@ -990,7 +997,7 @@ pub fn genTypedValue(
990997
991998 if (!ty.isSlice(zcu)) switch (ip.indexToKey(val.toIntern())) {
992999 .ptr => |ptr| if (ptr.byte_offset == 0) switch (ptr.base_addr) {
993 .decl => |decl| return genDeclRef(lf, src_loc, val, decl),
1000 .decl => |decl| return genDeclRef(lf, pt, src_loc, val, decl),
9941001 else => {},
9951002 },
9961003 else => {},
......@@ -1007,7 +1014,7 @@ pub fn genTypedValue(
10071014 .none => {},
10081015 else => switch (ip.indexToKey(val.toIntern())) {
10091016 .int => {
1010 return GenResult.mcv(.{ .immediate = val.toUnsignedInt(zcu) });
1017 return GenResult.mcv(.{ .immediate = val.toUnsignedInt(pt) });
10111018 },
10121019 else => {},
10131020 },
......@@ -1017,8 +1024,8 @@ pub fn genTypedValue(
10171024 const info = ty.intInfo(zcu);
10181025 if (info.bits <= ptr_bits) {
10191026 const unsigned: u64 = switch (info.signedness) {
1020 .signed => @bitCast(val.toSignedInt(zcu)),
1021 .unsigned => val.toUnsignedInt(zcu),
1027 .signed => @bitCast(val.toSignedInt(pt)),
1028 .unsigned => val.toUnsignedInt(pt),
10221029 };
10231030 return GenResult.mcv(.{ .immediate = unsigned });
10241031 }
......@@ -1030,11 +1037,12 @@ pub fn genTypedValue(
10301037 if (ty.isPtrLikeOptional(zcu)) {
10311038 return genTypedValue(
10321039 lf,
1040 pt,
10331041 src_loc,
10341042 val.optionalValue(zcu) orelse return GenResult.mcv(.{ .immediate = 0 }),
10351043 owner_decl_index,
10361044 );
1037 } else if (ty.abiSize(zcu) == 1) {
1045 } else if (ty.abiSize(pt) == 1) {
10381046 return GenResult.mcv(.{ .immediate = @intFromBool(!val.isNull(zcu)) });
10391047 }
10401048 },
......@@ -1042,6 +1050,7 @@ pub fn genTypedValue(
10421050 const enum_tag = ip.indexToKey(val.toIntern()).enum_tag;
10431051 return genTypedValue(
10441052 lf,
1053 pt,
10451054 src_loc,
10461055 Value.fromInterned(enum_tag.int),
10471056 owner_decl_index,
......@@ -1055,14 +1064,15 @@ pub fn genTypedValue(
10551064 .ErrorUnion => {
10561065 const err_type = ty.errorUnionSet(zcu);
10571066 const payload_type = ty.errorUnionPayload(zcu);
1058 if (!payload_type.hasRuntimeBitsIgnoreComptime(zcu)) {
1067 if (!payload_type.hasRuntimeBitsIgnoreComptime(pt)) {
10591068 // We use the error type directly as the type.
1060 const err_int_ty = try zcu.errorIntType();
1069 const err_int_ty = try pt.errorIntType();
10611070 switch (ip.indexToKey(val.toIntern()).error_union.val) {
10621071 .err_name => |err_name| return genTypedValue(
10631072 lf,
1073 pt,
10641074 src_loc,
1065 Value.fromInterned(try zcu.intern(.{ .err = .{
1075 Value.fromInterned(try pt.intern(.{ .err = .{
10661076 .ty = err_type.toIntern(),
10671077 .name = err_name,
10681078 } })),
......@@ -1070,8 +1080,9 @@ pub fn genTypedValue(
10701080 ),
10711081 .payload => return genTypedValue(
10721082 lf,
1083 pt,
10731084 src_loc,
1074 try zcu.intValue(err_int_ty, 0),
1085 try pt.intValue(err_int_ty, 0),
10751086 owner_decl_index,
10761087 ),
10771088 }
......@@ -1090,26 +1101,26 @@ pub fn genTypedValue(
10901101 else => {},
10911102 }
10921103
1093 return genUnnamedConst(lf, src_loc, val, owner_decl_index);
1104 return genUnnamedConst(lf, pt, src_loc, val, owner_decl_index);
10941105}
10951106
1096pub fn errUnionPayloadOffset(payload_ty: Type, mod: *Module) u64 {
1097 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) return 0;
1098 const payload_align = payload_ty.abiAlignment(mod);
1099 const error_align = Type.anyerror.abiAlignment(mod);
1100 if (payload_align.compare(.gte, error_align) or !payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
1107pub fn errUnionPayloadOffset(payload_ty: Type, pt: Zcu.PerThread) u64 {
1108 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) return 0;
1109 const payload_align = payload_ty.abiAlignment(pt);
1110 const error_align = Type.anyerror.abiAlignment(pt);
1111 if (payload_align.compare(.gte, error_align) or !payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
11011112 return 0;
11021113 } else {
1103 return payload_align.forward(Type.anyerror.abiSize(mod));
1114 return payload_align.forward(Type.anyerror.abiSize(pt));
11041115 }
11051116}
11061117
1107pub fn errUnionErrorOffset(payload_ty: Type, mod: *Module) u64 {
1108 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) return 0;
1109 const payload_align = payload_ty.abiAlignment(mod);
1110 const error_align = Type.anyerror.abiAlignment(mod);
1111 if (payload_align.compare(.gte, error_align) and payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
1112 return error_align.forward(payload_ty.abiSize(mod));
1118pub fn errUnionErrorOffset(payload_ty: Type, pt: Zcu.PerThread) u64 {
1119 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) return 0;
1120 const payload_align = payload_ty.abiAlignment(pt);
1121 const error_align = Type.anyerror.abiAlignment(pt);
1122 if (payload_align.compare(.gte, error_align) and payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
1123 return error_align.forward(payload_ty.abiSize(pt));
11131124 } else {
11141125 return 0;
11151126 }
src/codegen/c.zig+408-337
......@@ -333,15 +333,15 @@ pub const Function = struct {
333333 const gop = try f.value_map.getOrPut(ref);
334334 if (gop.found_existing) return gop.value_ptr.*;
335335
336 const zcu = f.object.dg.zcu;
337 const val = (try f.air.value(ref, zcu)).?;
336 const pt = f.object.dg.pt;
337 const val = (try f.air.value(ref, pt)).?;
338338 const ty = f.typeOf(ref);
339339
340 const result: CValue = if (lowersToArray(ty, zcu)) result: {
340 const result: CValue = if (lowersToArray(ty, pt)) result: {
341341 const writer = f.object.codeHeaderWriter();
342342 const decl_c_value = try f.allocLocalValue(.{
343343 .ctype = try f.ctypeFromType(ty, .complete),
344 .alignas = CType.AlignAs.fromAbiAlignment(ty.abiAlignment(zcu)),
344 .alignas = CType.AlignAs.fromAbiAlignment(ty.abiAlignment(pt)),
345345 });
346346 const gpa = f.object.dg.gpa;
347347 try f.allocs.put(gpa, decl_c_value.new_local, false);
......@@ -358,7 +358,7 @@ pub const Function = struct {
358358 }
359359
360360 fn wantSafety(f: *Function) bool {
361 return switch (f.object.dg.zcu.optimizeMode()) {
361 return switch (f.object.dg.pt.zcu.optimizeMode()) {
362362 .Debug, .ReleaseSafe => true,
363363 .ReleaseFast, .ReleaseSmall => false,
364364 };
......@@ -379,7 +379,7 @@ pub const Function = struct {
379379 fn allocLocal(f: *Function, inst: ?Air.Inst.Index, ty: Type) !CValue {
380380 return f.allocAlignedLocal(inst, .{
381381 .ctype = try f.ctypeFromType(ty, .complete),
382 .alignas = CType.AlignAs.fromAbiAlignment(ty.abiAlignment(f.object.dg.zcu)),
382 .alignas = CType.AlignAs.fromAbiAlignment(ty.abiAlignment(f.object.dg.pt)),
383383 });
384384 }
385385
......@@ -500,7 +500,8 @@ pub const Function = struct {
500500
501501 fn getLazyFnName(f: *Function, key: LazyFnKey, data: LazyFnValue.Data) ![]const u8 {
502502 const gpa = f.object.dg.gpa;
503 const zcu = f.object.dg.zcu;
503 const pt = f.object.dg.pt;
504 const zcu = pt.zcu;
504505 const ctype_pool = &f.object.dg.ctype_pool;
505506
506507 const gop = try f.lazy_fns.getOrPut(gpa, key);
......@@ -539,13 +540,11 @@ pub const Function = struct {
539540 }
540541
541542 fn typeOf(f: *Function, inst: Air.Inst.Ref) Type {
542 const zcu = f.object.dg.zcu;
543 return f.air.typeOf(inst, &zcu.intern_pool);
543 return f.air.typeOf(inst, &f.object.dg.pt.zcu.intern_pool);
544544 }
545545
546546 fn typeOfIndex(f: *Function, inst: Air.Inst.Index) Type {
547 const zcu = f.object.dg.zcu;
548 return f.air.typeOfIndex(inst, &zcu.intern_pool);
547 return f.air.typeOfIndex(inst, &f.object.dg.pt.zcu.intern_pool);
549548 }
550549
551550 fn copyCValue(f: *Function, ctype: CType, dst: CValue, src: CValue) !void {
......@@ -608,7 +607,7 @@ pub const Object = struct {
608607/// This data is available both when outputting .c code and when outputting an .h file.
609608pub const DeclGen = struct {
610609 gpa: mem.Allocator,
611 zcu: *Zcu,
610 pt: Zcu.PerThread,
612611 mod: *Module,
613612 pass: Pass,
614613 is_naked_fn: bool,
......@@ -634,7 +633,7 @@ pub const DeclGen = struct {
634633
635634 fn fail(dg: *DeclGen, comptime format: []const u8, args: anytype) error{ AnalysisFail, OutOfMemory } {
636635 @setCold(true);
637 const zcu = dg.zcu;
636 const zcu = dg.pt.zcu;
638637 const decl_index = dg.pass.decl;
639638 const decl = zcu.declPtr(decl_index);
640639 const src_loc = decl.navSrcLoc(zcu);
......@@ -648,7 +647,8 @@ pub const DeclGen = struct {
648647 anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl,
649648 location: ValueRenderLocation,
650649 ) error{ OutOfMemory, AnalysisFail }!void {
651 const zcu = dg.zcu;
650 const pt = dg.pt;
651 const zcu = pt.zcu;
652652 const ip = &zcu.intern_pool;
653653 const ctype_pool = &dg.ctype_pool;
654654 const decl_val = Value.fromInterned(anon_decl.val);
......@@ -656,7 +656,7 @@ pub const DeclGen = struct {
656656
657657 // Render an undefined pointer if we have a pointer to a zero-bit or comptime type.
658658 const ptr_ty = Type.fromInterned(anon_decl.orig_ty);
659 if (ptr_ty.isPtrAtRuntime(zcu) and !decl_ty.isFnOrHasRuntimeBits(zcu)) {
659 if (ptr_ty.isPtrAtRuntime(zcu) and !decl_ty.isFnOrHasRuntimeBits(pt)) {
660660 return dg.writeCValue(writer, .{ .undef = ptr_ty });
661661 }
662662
......@@ -696,7 +696,7 @@ pub const DeclGen = struct {
696696 // alignment. If there is already an entry, keep the greater alignment.
697697 const explicit_alignment = ptr_type.flags.alignment;
698698 if (explicit_alignment != .none) {
699 const abi_alignment = Type.fromInterned(ptr_type.child).abiAlignment(zcu);
699 const abi_alignment = Type.fromInterned(ptr_type.child).abiAlignment(pt);
700700 if (explicit_alignment.order(abi_alignment).compare(.gt)) {
701701 const aligned_gop = try dg.aligned_anon_decls.getOrPut(dg.gpa, anon_decl.val);
702702 aligned_gop.value_ptr.* = if (aligned_gop.found_existing)
......@@ -713,15 +713,16 @@ pub const DeclGen = struct {
713713 decl_index: InternPool.DeclIndex,
714714 location: ValueRenderLocation,
715715 ) error{ OutOfMemory, AnalysisFail }!void {
716 const zcu = dg.zcu;
716 const pt = dg.pt;
717 const zcu = pt.zcu;
717718 const ctype_pool = &dg.ctype_pool;
718719 const decl = zcu.declPtr(decl_index);
719720 assert(decl.has_tv);
720721
721722 // Render an undefined pointer if we have a pointer to a zero-bit or comptime type.
722723 const decl_ty = decl.typeOf(zcu);
723 const ptr_ty = try decl.declPtrType(zcu);
724 if (!decl_ty.isFnOrHasRuntimeBits(zcu)) {
724 const ptr_ty = try decl.declPtrType(pt);
725 if (!decl_ty.isFnOrHasRuntimeBits(pt)) {
725726 return dg.writeCValue(writer, .{ .undef = ptr_ty });
726727 }
727728
......@@ -756,12 +757,13 @@ pub const DeclGen = struct {
756757 derivation: Value.PointerDeriveStep,
757758 location: ValueRenderLocation,
758759 ) error{ OutOfMemory, AnalysisFail }!void {
759 const zcu = dg.zcu;
760 const pt = dg.pt;
761 const zcu = pt.zcu;
760762 switch (derivation) {
761763 .comptime_alloc_ptr, .comptime_field_ptr => unreachable,
762764 .int => |int| {
763765 const ptr_ctype = try dg.ctypeFromType(int.ptr_ty, .complete);
764 const addr_val = try zcu.intValue(Type.usize, int.addr);
766 const addr_val = try pt.intValue(Type.usize, int.addr);
765767 try writer.writeByte('(');
766768 try dg.renderCType(writer, ptr_ctype);
767769 try writer.print("){x}", .{try dg.fmtIntLiteral(addr_val, .Other)});
......@@ -777,12 +779,12 @@ pub const DeclGen = struct {
777779 },
778780
779781 .field_ptr => |field| {
780 const parent_ptr_ty = try field.parent.ptrType(zcu);
782 const parent_ptr_ty = try field.parent.ptrType(pt);
781783
782784 // Ensure complete type definition is available before accessing fields.
783785 _ = try dg.ctypeFromType(parent_ptr_ty.childType(zcu), .complete);
784786
785 switch (fieldLocation(parent_ptr_ty, field.result_ptr_ty, field.field_idx, zcu)) {
787 switch (fieldLocation(parent_ptr_ty, field.result_ptr_ty, field.field_idx, pt)) {
786788 .begin => {
787789 const ptr_ctype = try dg.ctypeFromType(field.result_ptr_ty, .complete);
788790 try writer.writeByte('(');
......@@ -801,7 +803,7 @@ pub const DeclGen = struct {
801803 try writer.writeByte('(');
802804 try dg.renderCType(writer, ptr_ctype);
803805 try writer.writeByte(')');
804 const offset_val = try zcu.intValue(Type.usize, byte_offset);
806 const offset_val = try pt.intValue(Type.usize, byte_offset);
805807 try writer.writeAll("((char *)");
806808 try dg.renderPointer(writer, field.parent.*, location);
807809 try writer.print(" + {})", .{try dg.fmtIntLiteral(offset_val, .Other)});
......@@ -809,7 +811,7 @@ pub const DeclGen = struct {
809811 }
810812 },
811813
812 .elem_ptr => |elem| if (!(try elem.parent.ptrType(zcu)).childType(zcu).hasRuntimeBits(zcu)) {
814 .elem_ptr => |elem| if (!(try elem.parent.ptrType(pt)).childType(zcu).hasRuntimeBits(pt)) {
813815 // Element type is zero-bit, so lowers to `void`. The index is irrelevant; just cast the pointer.
814816 const ptr_ctype = try dg.ctypeFromType(elem.result_ptr_ty, .complete);
815817 try writer.writeByte('(');
......@@ -817,11 +819,11 @@ pub const DeclGen = struct {
817819 try writer.writeByte(')');
818820 try dg.renderPointer(writer, elem.parent.*, location);
819821 } else {
820 const index_val = try zcu.intValue(Type.usize, elem.elem_idx);
822 const index_val = try pt.intValue(Type.usize, elem.elem_idx);
821823 // We want to do pointer arithmetic on a pointer to the element type.
822824 // We might have a pointer-to-array. In this case, we must cast first.
823825 const result_ctype = try dg.ctypeFromType(elem.result_ptr_ty, .complete);
824 const parent_ctype = try dg.ctypeFromType(try elem.parent.ptrType(zcu), .complete);
826 const parent_ctype = try dg.ctypeFromType(try elem.parent.ptrType(pt), .complete);
825827 if (result_ctype.eql(parent_ctype)) {
826828 // The pointer already has an appropriate type - just do the arithmetic.
827829 try writer.writeByte('(');
......@@ -846,7 +848,7 @@ pub const DeclGen = struct {
846848 if (oac.byte_offset == 0) {
847849 try dg.renderPointer(writer, oac.parent.*, location);
848850 } else {
849 const offset_val = try zcu.intValue(Type.usize, oac.byte_offset);
851 const offset_val = try pt.intValue(Type.usize, oac.byte_offset);
850852 try writer.writeAll("((char *)");
851853 try dg.renderPointer(writer, oac.parent.*, location);
852854 try writer.print(" + {})", .{try dg.fmtIntLiteral(offset_val, .Other)});
......@@ -856,8 +858,7 @@ pub const DeclGen = struct {
856858 }
857859
858860 fn renderErrorName(dg: *DeclGen, writer: anytype, err_name: InternPool.NullTerminatedString) !void {
859 const zcu = dg.zcu;
860 const ip = &zcu.intern_pool;
861 const ip = &dg.pt.zcu.intern_pool;
861862 try writer.print("zig_error_{}", .{fmtIdent(err_name.toSlice(ip))});
862863 }
863864
......@@ -867,7 +868,8 @@ pub const DeclGen = struct {
867868 val: Value,
868869 location: ValueRenderLocation,
869870 ) error{ OutOfMemory, AnalysisFail }!void {
870 const zcu = dg.zcu;
871 const pt = dg.pt;
872 const zcu = pt.zcu;
871873 const ip = &zcu.intern_pool;
872874 const target = &dg.mod.resolved_target.result;
873875 const ctype_pool = &dg.ctype_pool;
......@@ -927,7 +929,7 @@ pub const DeclGen = struct {
927929 try writer.writeAll("((");
928930 try dg.renderCType(writer, ctype);
929931 try writer.print("){x})", .{try dg.fmtIntLiteral(
930 try zcu.intValue(Type.usize, val.toUnsignedInt(zcu)),
932 try pt.intValue(Type.usize, val.toUnsignedInt(pt)),
931933 .Other,
932934 )});
933935 },
......@@ -974,10 +976,10 @@ pub const DeclGen = struct {
974976 .enum_tag => |enum_tag| try dg.renderValue(writer, Value.fromInterned(enum_tag.int), location),
975977 .float => {
976978 const bits = ty.floatBits(target.*);
977 const f128_val = val.toFloat(f128, zcu);
979 const f128_val = val.toFloat(f128, pt);
978980
979981 // All unsigned ints matching float types are pre-allocated.
980 const repr_ty = zcu.intType(.unsigned, bits) catch unreachable;
982 const repr_ty = pt.intType(.unsigned, bits) catch unreachable;
981983
982984 assert(bits <= 128);
983985 var repr_val_limbs: [BigInt.calcTwosCompLimbCount(128)]BigIntLimb = undefined;
......@@ -988,10 +990,10 @@ pub const DeclGen = struct {
988990 };
989991
990992 switch (bits) {
991 16 => repr_val_big.set(@as(u16, @bitCast(val.toFloat(f16, zcu)))),
992 32 => repr_val_big.set(@as(u32, @bitCast(val.toFloat(f32, zcu)))),
993 64 => repr_val_big.set(@as(u64, @bitCast(val.toFloat(f64, zcu)))),
994 80 => repr_val_big.set(@as(u80, @bitCast(val.toFloat(f80, zcu)))),
993 16 => repr_val_big.set(@as(u16, @bitCast(val.toFloat(f16, pt)))),
994 32 => repr_val_big.set(@as(u32, @bitCast(val.toFloat(f32, pt)))),
995 64 => repr_val_big.set(@as(u64, @bitCast(val.toFloat(f64, pt)))),
996 80 => repr_val_big.set(@as(u80, @bitCast(val.toFloat(f80, pt)))),
995997 128 => repr_val_big.set(@as(u128, @bitCast(f128_val))),
996998 else => unreachable,
997999 }
......@@ -1002,10 +1004,10 @@ pub const DeclGen = struct {
10021004 try dg.renderTypeForBuiltinFnName(writer, ty);
10031005 try writer.writeByte('(');
10041006 switch (bits) {
1005 16 => try writer.print("{x}", .{val.toFloat(f16, zcu)}),
1006 32 => try writer.print("{x}", .{val.toFloat(f32, zcu)}),
1007 64 => try writer.print("{x}", .{val.toFloat(f64, zcu)}),
1008 80 => try writer.print("{x}", .{val.toFloat(f80, zcu)}),
1007 16 => try writer.print("{x}", .{val.toFloat(f16, pt)}),
1008 32 => try writer.print("{x}", .{val.toFloat(f32, pt)}),
1009 64 => try writer.print("{x}", .{val.toFloat(f64, pt)}),
1010 80 => try writer.print("{x}", .{val.toFloat(f80, pt)}),
10091011 128 => try writer.print("{x}", .{f128_val}),
10101012 else => unreachable,
10111013 }
......@@ -1045,10 +1047,10 @@ pub const DeclGen = struct {
10451047 if (std.math.isNan(f128_val)) switch (bits) {
10461048 // We only actually need to pass the significand, but it will get
10471049 // properly masked anyway, so just pass the whole value.
1048 16 => try writer.print("\"0x{x}\"", .{@as(u16, @bitCast(val.toFloat(f16, zcu)))}),
1049 32 => try writer.print("\"0x{x}\"", .{@as(u32, @bitCast(val.toFloat(f32, zcu)))}),
1050 64 => try writer.print("\"0x{x}\"", .{@as(u64, @bitCast(val.toFloat(f64, zcu)))}),
1051 80 => try writer.print("\"0x{x}\"", .{@as(u80, @bitCast(val.toFloat(f80, zcu)))}),
1050 16 => try writer.print("\"0x{x}\"", .{@as(u16, @bitCast(val.toFloat(f16, pt)))}),
1051 32 => try writer.print("\"0x{x}\"", .{@as(u32, @bitCast(val.toFloat(f32, pt)))}),
1052 64 => try writer.print("\"0x{x}\"", .{@as(u64, @bitCast(val.toFloat(f64, pt)))}),
1053 80 => try writer.print("\"0x{x}\"", .{@as(u80, @bitCast(val.toFloat(f80, pt)))}),
10521054 128 => try writer.print("\"0x{x}\"", .{@as(u128, @bitCast(f128_val))}),
10531055 else => unreachable,
10541056 };
......@@ -1056,7 +1058,7 @@ pub const DeclGen = struct {
10561058 empty = false;
10571059 }
10581060 try writer.print("{x}", .{try dg.fmtIntLiteral(
1059 try zcu.intValue_big(repr_ty, repr_val_big.toConst()),
1061 try pt.intValue_big(repr_ty, repr_val_big.toConst()),
10601062 location,
10611063 )});
10621064 if (!empty) try writer.writeByte(')');
......@@ -1084,7 +1086,7 @@ pub const DeclGen = struct {
10841086 .ptr => {
10851087 var arena = std.heap.ArenaAllocator.init(zcu.gpa);
10861088 defer arena.deinit();
1087 const derivation = try val.pointerDerivation(arena.allocator(), zcu);
1089 const derivation = try val.pointerDerivation(arena.allocator(), pt);
10881090 try dg.renderPointer(writer, derivation, location);
10891091 },
10901092 .opt => |opt| switch (ctype.info(ctype_pool)) {
......@@ -1167,15 +1169,15 @@ pub const DeclGen = struct {
11671169 try literal.start();
11681170 var index: usize = 0;
11691171 while (index < ai.len) : (index += 1) {
1170 const elem_val = try val.elemValue(zcu, index);
1172 const elem_val = try val.elemValue(pt, index);
11711173 const elem_val_u8: u8 = if (elem_val.isUndef(zcu))
11721174 undefPattern(u8)
11731175 else
1174 @intCast(elem_val.toUnsignedInt(zcu));
1176 @intCast(elem_val.toUnsignedInt(pt));
11751177 try literal.writeChar(elem_val_u8);
11761178 }
11771179 if (ai.sentinel) |s| {
1178 const s_u8: u8 = @intCast(s.toUnsignedInt(zcu));
1180 const s_u8: u8 = @intCast(s.toUnsignedInt(pt));
11791181 if (s_u8 != 0) try literal.writeChar(s_u8);
11801182 }
11811183 try literal.end();
......@@ -1184,7 +1186,7 @@ pub const DeclGen = struct {
11841186 var index: usize = 0;
11851187 while (index < ai.len) : (index += 1) {
11861188 if (index != 0) try writer.writeByte(',');
1187 const elem_val = try val.elemValue(zcu, index);
1189 const elem_val = try val.elemValue(pt, index);
11881190 try dg.renderValue(writer, elem_val, initializer_type);
11891191 }
11901192 if (ai.sentinel) |s| {
......@@ -1207,13 +1209,13 @@ pub const DeclGen = struct {
12071209 const comptime_val = tuple.values.get(ip)[field_index];
12081210 if (comptime_val != .none) continue;
12091211 const field_ty = Type.fromInterned(tuple.types.get(ip)[field_index]);
1210 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
1212 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
12111213
12121214 if (!empty) try writer.writeByte(',');
12131215
12141216 const field_val = Value.fromInterned(
12151217 switch (ip.indexToKey(val.toIntern()).aggregate.storage) {
1216 .bytes => |bytes| try ip.get(zcu.gpa, .{ .int = .{
1218 .bytes => |bytes| try pt.intern(.{ .int = .{
12171219 .ty = field_ty.toIntern(),
12181220 .storage = .{ .u64 = bytes.at(field_index, ip) },
12191221 } }),
......@@ -1242,12 +1244,12 @@ pub const DeclGen = struct {
12421244 var need_comma = false;
12431245 while (field_it.next()) |field_index| {
12441246 const field_ty = Type.fromInterned(loaded_struct.field_types.get(ip)[field_index]);
1245 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
1247 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
12461248
12471249 if (need_comma) try writer.writeByte(',');
12481250 need_comma = true;
12491251 const field_val = switch (ip.indexToKey(val.toIntern()).aggregate.storage) {
1250 .bytes => |bytes| try ip.get(zcu.gpa, .{ .int = .{
1252 .bytes => |bytes| try pt.intern(.{ .int = .{
12511253 .ty = field_ty.toIntern(),
12521254 .storage = .{ .u64 = bytes.at(field_index, ip) },
12531255 } }),
......@@ -1262,14 +1264,14 @@ pub const DeclGen = struct {
12621264 const int_info = ty.intInfo(zcu);
12631265
12641266 const bits = Type.smallestUnsignedBits(int_info.bits - 1);
1265 const bit_offset_ty = try zcu.intType(.unsigned, bits);
1267 const bit_offset_ty = try pt.intType(.unsigned, bits);
12661268
12671269 var bit_offset: u64 = 0;
12681270 var eff_num_fields: usize = 0;
12691271
12701272 for (0..loaded_struct.field_types.len) |field_index| {
12711273 const field_ty = Type.fromInterned(loaded_struct.field_types.get(ip)[field_index]);
1272 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
1274 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
12731275 eff_num_fields += 1;
12741276 }
12751277
......@@ -1277,7 +1279,7 @@ pub const DeclGen = struct {
12771279 try writer.writeByte('(');
12781280 try dg.renderUndefValue(writer, ty, location);
12791281 try writer.writeByte(')');
1280 } else if (ty.bitSize(zcu) > 64) {
1282 } else if (ty.bitSize(pt) > 64) {
12811283 // zig_or_u128(zig_or_u128(zig_shl_u128(a, a_off), zig_shl_u128(b, b_off)), zig_shl_u128(c, c_off))
12821284 var num_or = eff_num_fields - 1;
12831285 while (num_or > 0) : (num_or -= 1) {
......@@ -1290,10 +1292,10 @@ pub const DeclGen = struct {
12901292 var needs_closing_paren = false;
12911293 for (0..loaded_struct.field_types.len) |field_index| {
12921294 const field_ty = Type.fromInterned(loaded_struct.field_types.get(ip)[field_index]);
1293 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
1295 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
12941296
12951297 const field_val = switch (ip.indexToKey(val.toIntern()).aggregate.storage) {
1296 .bytes => |bytes| try ip.get(zcu.gpa, .{ .int = .{
1298 .bytes => |bytes| try pt.intern(.{ .int = .{
12971299 .ty = field_ty.toIntern(),
12981300 .storage = .{ .u64 = bytes.at(field_index, ip) },
12991301 } }),
......@@ -1307,7 +1309,7 @@ pub const DeclGen = struct {
13071309 try writer.writeByte('(');
13081310 try dg.renderIntCast(writer, ty, cast_context, field_ty, .FunctionArgument);
13091311 try writer.writeAll(", ");
1310 try dg.renderValue(writer, try zcu.intValue(bit_offset_ty, bit_offset), .FunctionArgument);
1312 try dg.renderValue(writer, try pt.intValue(bit_offset_ty, bit_offset), .FunctionArgument);
13111313 try writer.writeByte(')');
13121314 } else {
13131315 try dg.renderIntCast(writer, ty, cast_context, field_ty, .FunctionArgument);
......@@ -1316,7 +1318,7 @@ pub const DeclGen = struct {
13161318 if (needs_closing_paren) try writer.writeByte(')');
13171319 if (eff_index != eff_num_fields - 1) try writer.writeAll(", ");
13181320
1319 bit_offset += field_ty.bitSize(zcu);
1321 bit_offset += field_ty.bitSize(pt);
13201322 needs_closing_paren = true;
13211323 eff_index += 1;
13221324 }
......@@ -1326,7 +1328,7 @@ pub const DeclGen = struct {
13261328 var empty = true;
13271329 for (0..loaded_struct.field_types.len) |field_index| {
13281330 const field_ty = Type.fromInterned(loaded_struct.field_types.get(ip)[field_index]);
1329 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
1331 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
13301332
13311333 if (!empty) try writer.writeAll(" | ");
13321334 try writer.writeByte('(');
......@@ -1334,7 +1336,7 @@ pub const DeclGen = struct {
13341336 try writer.writeByte(')');
13351337
13361338 const field_val = switch (ip.indexToKey(val.toIntern()).aggregate.storage) {
1337 .bytes => |bytes| try ip.get(zcu.gpa, .{ .int = .{
1339 .bytes => |bytes| try pt.intern(.{ .int = .{
13381340 .ty = field_ty.toIntern(),
13391341 .storage = .{ .u64 = bytes.at(field_index, ip) },
13401342 } }),
......@@ -1345,12 +1347,12 @@ pub const DeclGen = struct {
13451347 if (bit_offset != 0) {
13461348 try dg.renderValue(writer, Value.fromInterned(field_val), .Other);
13471349 try writer.writeAll(" << ");
1348 try dg.renderValue(writer, try zcu.intValue(bit_offset_ty, bit_offset), .FunctionArgument);
1350 try dg.renderValue(writer, try pt.intValue(bit_offset_ty, bit_offset), .FunctionArgument);
13491351 } else {
13501352 try dg.renderValue(writer, Value.fromInterned(field_val), .Other);
13511353 }
13521354
1353 bit_offset += field_ty.bitSize(zcu);
1355 bit_offset += field_ty.bitSize(pt);
13541356 empty = false;
13551357 }
13561358 try writer.writeByte(')');
......@@ -1363,7 +1365,7 @@ pub const DeclGen = struct {
13631365 .un => |un| {
13641366 const loaded_union = ip.loadUnionType(ty.toIntern());
13651367 if (un.tag == .none) {
1366 const backing_ty = try ty.unionBackingType(zcu);
1368 const backing_ty = try ty.unionBackingType(pt);
13671369 switch (loaded_union.getLayout(ip)) {
13681370 .@"packed" => {
13691371 if (!location.isInitializer()) {
......@@ -1378,7 +1380,7 @@ pub const DeclGen = struct {
13781380 return dg.fail("TODO: C backend: implement extern union backing type rendering in static initializers", .{});
13791381 }
13801382
1381 const ptr_ty = try zcu.singleConstPtrType(ty);
1383 const ptr_ty = try pt.singleConstPtrType(ty);
13821384 try writer.writeAll("*((");
13831385 try dg.renderType(writer, ptr_ty);
13841386 try writer.writeAll(")(");
......@@ -1400,7 +1402,7 @@ pub const DeclGen = struct {
14001402 const field_ty = Type.fromInterned(loaded_union.field_types.get(ip)[field_index]);
14011403 const field_name = loaded_union.loadTagType(ip).names.get(ip)[field_index];
14021404 if (loaded_union.getLayout(ip) == .@"packed") {
1403 if (field_ty.hasRuntimeBits(zcu)) {
1405 if (field_ty.hasRuntimeBits(pt)) {
14041406 if (field_ty.isPtrAtRuntime(zcu)) {
14051407 try writer.writeByte('(');
14061408 try dg.renderCType(writer, ctype);
......@@ -1431,7 +1433,7 @@ pub const DeclGen = struct {
14311433 ),
14321434 .payload => {
14331435 try writer.writeByte('{');
1434 if (field_ty.hasRuntimeBits(zcu)) {
1436 if (field_ty.hasRuntimeBits(pt)) {
14351437 try writer.print(" .{ } = ", .{fmtIdent(field_name.toSlice(ip))});
14361438 try dg.renderValue(
14371439 writer,
......@@ -1443,7 +1445,7 @@ pub const DeclGen = struct {
14431445 const inner_field_ty = Type.fromInterned(
14441446 loaded_union.field_types.get(ip)[inner_field_index],
14451447 );
1446 if (!inner_field_ty.hasRuntimeBits(zcu)) continue;
1448 if (!inner_field_ty.hasRuntimeBits(pt)) continue;
14471449 try dg.renderUndefValue(writer, inner_field_ty, initializer_type);
14481450 break;
14491451 }
......@@ -1464,7 +1466,8 @@ pub const DeclGen = struct {
14641466 ty: Type,
14651467 location: ValueRenderLocation,
14661468 ) error{ OutOfMemory, AnalysisFail }!void {
1467 const zcu = dg.zcu;
1469 const pt = dg.pt;
1470 const zcu = pt.zcu;
14681471 const ip = &zcu.intern_pool;
14691472 const target = &dg.mod.resolved_target.result;
14701473 const ctype_pool = &dg.ctype_pool;
......@@ -1490,7 +1493,7 @@ pub const DeclGen = struct {
14901493 => {
14911494 const bits = ty.floatBits(target.*);
14921495 // All unsigned ints matching float types are pre-allocated.
1493 const repr_ty = zcu.intType(.unsigned, bits) catch unreachable;
1496 const repr_ty = dg.pt.intType(.unsigned, bits) catch unreachable;
14941497
14951498 try writer.writeAll("zig_make_");
14961499 try dg.renderTypeForBuiltinFnName(writer, ty);
......@@ -1515,14 +1518,14 @@ pub const DeclGen = struct {
15151518 .error_set_type,
15161519 .inferred_error_set_type,
15171520 => return writer.print("{x}", .{
1518 try dg.fmtIntLiteral(try zcu.undefValue(ty), location),
1521 try dg.fmtIntLiteral(try pt.undefValue(ty), location),
15191522 }),
15201523 .ptr_type => |ptr_type| switch (ptr_type.flags.size) {
15211524 .One, .Many, .C => {
15221525 try writer.writeAll("((");
15231526 try dg.renderCType(writer, ctype);
15241527 return writer.print("){x})", .{
1525 try dg.fmtIntLiteral(try zcu.undefValue(Type.usize), .Other),
1528 try dg.fmtIntLiteral(try pt.undefValue(Type.usize), .Other),
15261529 });
15271530 },
15281531 .Slice => {
......@@ -1536,7 +1539,7 @@ pub const DeclGen = struct {
15361539 const ptr_ty = ty.slicePtrFieldType(zcu);
15371540 try dg.renderType(writer, ptr_ty);
15381541 return writer.print("){x}, {0x}}}", .{
1539 try dg.fmtIntLiteral(try zcu.undefValue(Type.usize), .Other),
1542 try dg.fmtIntLiteral(try dg.pt.undefValue(Type.usize), .Other),
15401543 });
15411544 },
15421545 },
......@@ -1591,7 +1594,7 @@ pub const DeclGen = struct {
15911594 var need_comma = false;
15921595 while (field_it.next()) |field_index| {
15931596 const field_ty = Type.fromInterned(loaded_struct.field_types.get(ip)[field_index]);
1594 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
1597 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
15951598
15961599 if (need_comma) try writer.writeByte(',');
15971600 need_comma = true;
......@@ -1600,7 +1603,7 @@ pub const DeclGen = struct {
16001603 return writer.writeByte('}');
16011604 },
16021605 .@"packed" => return writer.print("{x}", .{
1603 try dg.fmtIntLiteral(try zcu.undefValue(ty), .Other),
1606 try dg.fmtIntLiteral(try pt.undefValue(ty), .Other),
16041607 }),
16051608 }
16061609 },
......@@ -1616,7 +1619,7 @@ pub const DeclGen = struct {
16161619 for (0..anon_struct_info.types.len) |field_index| {
16171620 if (anon_struct_info.values.get(ip)[field_index] != .none) continue;
16181621 const field_ty = Type.fromInterned(anon_struct_info.types.get(ip)[field_index]);
1619 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
1622 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
16201623
16211624 if (need_comma) try writer.writeByte(',');
16221625 need_comma = true;
......@@ -1654,7 +1657,7 @@ pub const DeclGen = struct {
16541657 const inner_field_ty = Type.fromInterned(
16551658 loaded_union.field_types.get(ip)[inner_field_index],
16561659 );
1657 if (!inner_field_ty.hasRuntimeBits(zcu)) continue;
1660 if (!inner_field_ty.hasRuntimeBits(pt)) continue;
16581661 try dg.renderUndefValue(
16591662 writer,
16601663 inner_field_ty,
......@@ -1670,7 +1673,7 @@ pub const DeclGen = struct {
16701673 if (has_tag) try writer.writeByte('}');
16711674 },
16721675 .@"packed" => return writer.print("{x}", .{
1673 try dg.fmtIntLiteral(try zcu.undefValue(ty), .Other),
1676 try dg.fmtIntLiteral(try pt.undefValue(ty), .Other),
16741677 }),
16751678 }
16761679 },
......@@ -1775,7 +1778,7 @@ pub const DeclGen = struct {
17751778 },
17761779 },
17771780 ) !void {
1778 const zcu = dg.zcu;
1781 const zcu = dg.pt.zcu;
17791782 const ip = &zcu.intern_pool;
17801783
17811784 const fn_ty = fn_val.typeOf(zcu);
......@@ -1856,7 +1859,7 @@ pub const DeclGen = struct {
18561859
18571860 fn ctypeFromType(dg: *DeclGen, ty: Type, kind: CType.Kind) !CType {
18581861 defer std.debug.assert(dg.scratch.items.len == 0);
1859 return dg.ctype_pool.fromType(dg.gpa, &dg.scratch, ty, dg.zcu, dg.mod, kind);
1862 return dg.ctype_pool.fromType(dg.gpa, &dg.scratch, ty, dg.pt, dg.mod, kind);
18601863 }
18611864
18621865 fn byteSize(dg: *DeclGen, ctype: CType) u64 {
......@@ -1879,8 +1882,8 @@ pub const DeclGen = struct {
18791882 }
18801883
18811884 fn renderCType(dg: *DeclGen, w: anytype, ctype: CType) error{OutOfMemory}!void {
1882 _ = try renderTypePrefix(dg.pass, &dg.ctype_pool, dg.zcu, w, ctype, .suffix, .{});
1883 try renderTypeSuffix(dg.pass, &dg.ctype_pool, dg.zcu, w, ctype, .suffix, .{});
1885 _ = try renderTypePrefix(dg.pass, &dg.ctype_pool, dg.pt.zcu, w, ctype, .suffix, .{});
1886 try renderTypeSuffix(dg.pass, &dg.ctype_pool, dg.pt.zcu, w, ctype, .suffix, .{});
18841887 }
18851888
18861889 const IntCastContext = union(enum) {
......@@ -1904,18 +1907,18 @@ pub const DeclGen = struct {
19041907 }
19051908 };
19061909 fn intCastIsNoop(dg: *DeclGen, dest_ty: Type, src_ty: Type) bool {
1907 const zcu = dg.zcu;
1908 const dest_bits = dest_ty.bitSize(zcu);
1909 const dest_int_info = dest_ty.intInfo(zcu);
1910 const pt = dg.pt;
1911 const dest_bits = dest_ty.bitSize(pt);
1912 const dest_int_info = dest_ty.intInfo(pt.zcu);
19101913
1911 const src_is_ptr = src_ty.isPtrAtRuntime(zcu);
1914 const src_is_ptr = src_ty.isPtrAtRuntime(pt.zcu);
19121915 const src_eff_ty: Type = if (src_is_ptr) switch (dest_int_info.signedness) {
19131916 .unsigned => Type.usize,
19141917 .signed => Type.isize,
19151918 } else src_ty;
19161919
1917 const src_bits = src_eff_ty.bitSize(zcu);
1918 const src_int_info = if (src_eff_ty.isAbiInt(zcu)) src_eff_ty.intInfo(zcu) else null;
1920 const src_bits = src_eff_ty.bitSize(pt);
1921 const src_int_info = if (src_eff_ty.isAbiInt(pt.zcu)) src_eff_ty.intInfo(pt.zcu) else null;
19191922 if (dest_bits <= 64 and src_bits <= 64) {
19201923 const needs_cast = src_int_info == null or
19211924 (toCIntBits(dest_int_info.bits) != toCIntBits(src_int_info.?.bits) or
......@@ -1944,8 +1947,9 @@ pub const DeclGen = struct {
19441947 src_ty: Type,
19451948 location: ValueRenderLocation,
19461949 ) !void {
1947 const zcu = dg.zcu;
1948 const dest_bits = dest_ty.bitSize(zcu);
1950 const pt = dg.pt;
1951 const zcu = pt.zcu;
1952 const dest_bits = dest_ty.bitSize(pt);
19491953 const dest_int_info = dest_ty.intInfo(zcu);
19501954
19511955 const src_is_ptr = src_ty.isPtrAtRuntime(zcu);
......@@ -1954,7 +1958,7 @@ pub const DeclGen = struct {
19541958 .signed => Type.isize,
19551959 } else src_ty;
19561960
1957 const src_bits = src_eff_ty.bitSize(zcu);
1961 const src_bits = src_eff_ty.bitSize(pt);
19581962 const src_int_info = if (src_eff_ty.isAbiInt(zcu)) src_eff_ty.intInfo(zcu) else null;
19591963 if (dest_bits <= 64 and src_bits <= 64) {
19601964 const needs_cast = src_int_info == null or
......@@ -2035,7 +2039,7 @@ pub const DeclGen = struct {
20352039 qualifiers,
20362040 CType.AlignAs.fromAlignment(.{
20372041 .@"align" = alignment,
2038 .abi = ty.abiAlignment(dg.zcu),
2042 .abi = ty.abiAlignment(dg.pt),
20392043 }),
20402044 );
20412045 }
......@@ -2048,6 +2052,7 @@ pub const DeclGen = struct {
20482052 qualifiers: CQualifiers,
20492053 alignas: CType.AlignAs,
20502054 ) error{ OutOfMemory, AnalysisFail }!void {
2055 const zcu = dg.pt.zcu;
20512056 switch (alignas.abiOrder()) {
20522057 .lt => try w.print("zig_under_align({}) ", .{alignas.toByteUnits()}),
20532058 .eq => {},
......@@ -2055,10 +2060,10 @@ pub const DeclGen = struct {
20552060 }
20562061
20572062 try w.print("{}", .{
2058 try renderTypePrefix(dg.pass, &dg.ctype_pool, dg.zcu, w, ctype, .suffix, qualifiers),
2063 try renderTypePrefix(dg.pass, &dg.ctype_pool, zcu, w, ctype, .suffix, qualifiers),
20592064 });
20602065 try dg.writeName(w, name);
2061 try renderTypeSuffix(dg.pass, &dg.ctype_pool, dg.zcu, w, ctype, .suffix, .{});
2066 try renderTypeSuffix(dg.pass, &dg.ctype_pool, zcu, w, ctype, .suffix, .{});
20622067 }
20632068
20642069 fn writeName(dg: *DeclGen, w: anytype, c_value: CValue) !void {
......@@ -2162,7 +2167,7 @@ pub const DeclGen = struct {
21622167 decl_index: InternPool.DeclIndex,
21632168 variable: InternPool.Key.Variable,
21642169 ) !void {
2165 const zcu = dg.zcu;
2170 const zcu = dg.pt.zcu;
21662171 const decl = zcu.declPtr(decl_index);
21672172 const fwd = dg.fwdDeclWriter();
21682173 try fwd.writeAll(if (variable.is_extern) "zig_extern " else "static ");
......@@ -2180,7 +2185,7 @@ pub const DeclGen = struct {
21802185 }
21812186
21822187 fn renderDeclName(dg: *DeclGen, writer: anytype, decl_index: InternPool.DeclIndex) !void {
2183 const zcu = dg.zcu;
2188 const zcu = dg.pt.zcu;
21842189 const ip = &zcu.intern_pool;
21852190 const decl = zcu.declPtr(decl_index);
21862191
......@@ -2236,15 +2241,15 @@ pub const DeclGen = struct {
22362241 .bits => {},
22372242 }
22382243
2239 const zcu = dg.zcu;
2240 const int_info = if (ty.isAbiInt(zcu)) ty.intInfo(zcu) else std.builtin.Type.Int{
2244 const pt = dg.pt;
2245 const int_info = if (ty.isAbiInt(pt.zcu)) ty.intInfo(pt.zcu) else std.builtin.Type.Int{
22412246 .signedness = .unsigned,
2242 .bits = @as(u16, @intCast(ty.bitSize(zcu))),
2247 .bits = @as(u16, @intCast(ty.bitSize(pt))),
22432248 };
22442249
22452250 if (is_big) try writer.print(", {}", .{int_info.signedness == .signed});
22462251 try writer.print(", {}", .{try dg.fmtIntLiteral(
2247 try zcu.intValue(if (is_big) Type.u16 else Type.u8, int_info.bits),
2252 try pt.intValue(if (is_big) Type.u16 else Type.u8, int_info.bits),
22482253 .FunctionArgument,
22492254 )});
22502255 }
......@@ -2254,7 +2259,7 @@ pub const DeclGen = struct {
22542259 val: Value,
22552260 loc: ValueRenderLocation,
22562261 ) !std.fmt.Formatter(formatIntLiteral) {
2257 const zcu = dg.zcu;
2262 const zcu = dg.pt.zcu;
22582263 const kind = loc.toCTypeKind();
22592264 const ty = val.typeOf(zcu);
22602265 return std.fmt.Formatter(formatIntLiteral){ .data = .{
......@@ -2616,7 +2621,8 @@ pub fn genGlobalAsm(zcu: *Zcu, writer: anytype) !void {
26162621}
26172622
26182623pub fn genErrDecls(o: *Object) !void {
2619 const zcu = o.dg.zcu;
2624 const pt = o.dg.pt;
2625 const zcu = pt.zcu;
26202626 const ip = &zcu.intern_pool;
26212627 const writer = o.writer();
26222628
......@@ -2628,7 +2634,7 @@ pub fn genErrDecls(o: *Object) !void {
26282634 for (zcu.global_error_set.keys()[1..], 1..) |name_nts, value| {
26292635 const name = name_nts.toSlice(ip);
26302636 max_name_len = @max(name.len, max_name_len);
2631 const err_val = try zcu.intern(.{ .err = .{
2637 const err_val = try pt.intern(.{ .err = .{
26322638 .ty = .anyerror_type,
26332639 .name = name_nts,
26342640 } });
......@@ -2649,12 +2655,12 @@ pub fn genErrDecls(o: *Object) !void {
26492655 @memcpy(name_buf[name_prefix.len..][0..name_slice.len], name_slice);
26502656 const identifier = name_buf[0 .. name_prefix.len + name_slice.len];
26512657
2652 const name_ty = try zcu.arrayType(.{
2658 const name_ty = try pt.arrayType(.{
26532659 .len = name_slice.len,
26542660 .child = .u8_type,
26552661 .sentinel = .zero_u8,
26562662 });
2657 const name_val = try zcu.intern(.{ .aggregate = .{
2663 const name_val = try pt.intern(.{ .aggregate = .{
26582664 .ty = name_ty.toIntern(),
26592665 .storage = .{ .bytes = name.toString() },
26602666 } });
......@@ -2673,7 +2679,7 @@ pub fn genErrDecls(o: *Object) !void {
26732679 try writer.writeAll(";\n");
26742680 }
26752681
2676 const name_array_ty = try zcu.arrayType(.{
2682 const name_array_ty = try pt.arrayType(.{
26772683 .len = zcu.global_error_set.count(),
26782684 .child = .slice_const_u8_sentinel_0_type,
26792685 });
......@@ -2693,14 +2699,15 @@ pub fn genErrDecls(o: *Object) !void {
26932699 if (value != 0) try writer.writeByte(',');
26942700 try writer.print("{{" ++ name_prefix ++ "{}, {}}}", .{
26952701 fmtIdent(name),
2696 try o.dg.fmtIntLiteral(try zcu.intValue(Type.usize, name.len), .StaticInitializer),
2702 try o.dg.fmtIntLiteral(try pt.intValue(Type.usize, name.len), .StaticInitializer),
26972703 });
26982704 }
26992705 try writer.writeAll("};\n");
27002706}
27012707
27022708pub fn genLazyFn(o: *Object, lazy_ctype_pool: *const CType.Pool, lazy_fn: LazyFnMap.Entry) !void {
2703 const zcu = o.dg.zcu;
2709 const pt = o.dg.pt;
2710 const zcu = pt.zcu;
27042711 const ip = &zcu.intern_pool;
27052712 const ctype_pool = &o.dg.ctype_pool;
27062713 const w = o.writer();
......@@ -2721,20 +2728,20 @@ pub fn genLazyFn(o: *Object, lazy_ctype_pool: *const CType.Pool, lazy_fn: LazyFn
27212728 for (0..tag_names.len) |tag_index| {
27222729 const tag_name = tag_names.get(ip)[tag_index];
27232730 const tag_name_len = tag_name.length(ip);
2724 const tag_val = try zcu.enumValueFieldIndex(enum_ty, @intCast(tag_index));
2731 const tag_val = try pt.enumValueFieldIndex(enum_ty, @intCast(tag_index));
27252732
2726 const name_ty = try zcu.arrayType(.{
2733 const name_ty = try pt.arrayType(.{
27272734 .len = tag_name_len,
27282735 .child = .u8_type,
27292736 .sentinel = .zero_u8,
27302737 });
2731 const name_val = try zcu.intern(.{ .aggregate = .{
2738 const name_val = try pt.intern(.{ .aggregate = .{
27322739 .ty = name_ty.toIntern(),
27332740 .storage = .{ .bytes = tag_name.toString() },
27342741 } });
27352742
27362743 try w.print(" case {}: {{\n static ", .{
2737 try o.dg.fmtIntLiteral(try tag_val.intFromEnum(enum_ty, zcu), .Other),
2744 try o.dg.fmtIntLiteral(try tag_val.intFromEnum(enum_ty, pt), .Other),
27382745 });
27392746 try o.dg.renderTypeAndName(w, name_ty, .{ .identifier = "name" }, Const, .none, .complete);
27402747 try w.writeAll(" = ");
......@@ -2743,7 +2750,7 @@ pub fn genLazyFn(o: *Object, lazy_ctype_pool: *const CType.Pool, lazy_fn: LazyFn
27432750 try o.dg.renderType(w, name_slice_ty);
27442751 try w.print("){{{}, {}}};\n", .{
27452752 fmtIdent("name"),
2746 try o.dg.fmtIntLiteral(try zcu.intValue(Type.usize, tag_name_len), .Other),
2753 try o.dg.fmtIntLiteral(try pt.intValue(Type.usize, tag_name_len), .Other),
27472754 });
27482755
27492756 try w.writeAll(" }\n");
......@@ -2788,7 +2795,7 @@ pub fn genFunc(f: *Function) !void {
27882795 defer tracy.end();
27892796
27902797 const o = &f.object;
2791 const zcu = o.dg.zcu;
2798 const zcu = o.dg.pt.zcu;
27922799 const gpa = o.dg.gpa;
27932800 const decl_index = o.dg.pass.decl;
27942801 const decl = zcu.declPtr(decl_index);
......@@ -2879,12 +2886,13 @@ pub fn genDecl(o: *Object) !void {
28792886 const tracy = trace(@src());
28802887 defer tracy.end();
28812888
2882 const zcu = o.dg.zcu;
2889 const pt = o.dg.pt;
2890 const zcu = pt.zcu;
28832891 const decl_index = o.dg.pass.decl;
28842892 const decl = zcu.declPtr(decl_index);
28852893 const decl_ty = decl.typeOf(zcu);
28862894
2887 if (!decl_ty.isFnOrHasRuntimeBitsIgnoreComptime(zcu)) return;
2895 if (!decl_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt)) return;
28882896 if (decl.val.getExternFunc(zcu)) |_| {
28892897 const fwd = o.dg.fwdDeclWriter();
28902898 try fwd.writeAll("zig_extern ");
......@@ -2928,7 +2936,7 @@ pub fn genDeclValue(
29282936 alignment: Alignment,
29292937 @"linksection": InternPool.OptionalNullTerminatedString,
29302938) !void {
2931 const zcu = o.dg.zcu;
2939 const zcu = o.dg.pt.zcu;
29322940 const ty = val.typeOf(zcu);
29332941
29342942 const fwd = o.dg.fwdDeclWriter();
......@@ -2946,7 +2954,7 @@ pub fn genDeclValue(
29462954}
29472955
29482956pub fn genExports(dg: *DeclGen, exported: Zcu.Exported, export_indices: []const u32) !void {
2949 const zcu = dg.zcu;
2957 const zcu = dg.pt.zcu;
29502958 const ip = &zcu.intern_pool;
29512959 const fwd = dg.fwdDeclWriter();
29522960
......@@ -3088,7 +3096,7 @@ fn genBodyResolveState(f: *Function, inst: Air.Inst.Index, leading_deaths: []con
30883096}
30893097
30903098fn genBodyInner(f: *Function, body: []const Air.Inst.Index) error{ AnalysisFail, OutOfMemory }!void {
3091 const zcu = f.object.dg.zcu;
3099 const zcu = f.object.dg.pt.zcu;
30923100 const ip = &zcu.intern_pool;
30933101 const air_tags = f.air.instructions.items(.tag);
30943102 const air_datas = f.air.instructions.items(.data);
......@@ -3388,10 +3396,10 @@ fn airSliceField(f: *Function, inst: Air.Inst.Index, is_ptr: bool, field_name: [
33883396}
33893397
33903398fn airPtrElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
3391 const zcu = f.object.dg.zcu;
3399 const pt = f.object.dg.pt;
33923400 const inst_ty = f.typeOfIndex(inst);
33933401 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
3394 if (!inst_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
3402 if (!inst_ty.hasRuntimeBitsIgnoreComptime(pt)) {
33953403 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
33963404 return .none;
33973405 }
......@@ -3414,13 +3422,14 @@ fn airPtrElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
34143422}
34153423
34163424fn airPtrElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {
3417 const zcu = f.object.dg.zcu;
3425 const pt = f.object.dg.pt;
3426 const zcu = pt.zcu;
34183427 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
34193428 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;
34203429
34213430 const inst_ty = f.typeOfIndex(inst);
34223431 const ptr_ty = f.typeOf(bin_op.lhs);
3423 const elem_has_bits = ptr_ty.elemType2(zcu).hasRuntimeBitsIgnoreComptime(zcu);
3432 const elem_has_bits = ptr_ty.elemType2(zcu).hasRuntimeBitsIgnoreComptime(pt);
34243433
34253434 const ptr = try f.resolveInst(bin_op.lhs);
34263435 const index = try f.resolveInst(bin_op.rhs);
......@@ -3449,10 +3458,10 @@ fn airPtrElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {
34493458}
34503459
34513460fn airSliceElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
3452 const zcu = f.object.dg.zcu;
3461 const pt = f.object.dg.pt;
34533462 const inst_ty = f.typeOfIndex(inst);
34543463 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
3455 if (!inst_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
3464 if (!inst_ty.hasRuntimeBitsIgnoreComptime(pt)) {
34563465 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
34573466 return .none;
34583467 }
......@@ -3475,14 +3484,15 @@ fn airSliceElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
34753484}
34763485
34773486fn airSliceElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {
3478 const zcu = f.object.dg.zcu;
3487 const pt = f.object.dg.pt;
3488 const zcu = pt.zcu;
34793489 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
34803490 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;
34813491
34823492 const inst_ty = f.typeOfIndex(inst);
34833493 const slice_ty = f.typeOf(bin_op.lhs);
34843494 const elem_ty = slice_ty.elemType2(zcu);
3485 const elem_has_bits = elem_ty.hasRuntimeBitsIgnoreComptime(zcu);
3495 const elem_has_bits = elem_ty.hasRuntimeBitsIgnoreComptime(pt);
34863496
34873497 const slice = try f.resolveInst(bin_op.lhs);
34883498 const index = try f.resolveInst(bin_op.rhs);
......@@ -3505,10 +3515,10 @@ fn airSliceElemPtr(f: *Function, inst: Air.Inst.Index) !CValue {
35053515}
35063516
35073517fn airArrayElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
3508 const zcu = f.object.dg.zcu;
3518 const pt = f.object.dg.pt;
35093519 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
35103520 const inst_ty = f.typeOfIndex(inst);
3511 if (!inst_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
3521 if (!inst_ty.hasRuntimeBitsIgnoreComptime(pt)) {
35123522 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
35133523 return .none;
35143524 }
......@@ -3531,40 +3541,40 @@ fn airArrayElemVal(f: *Function, inst: Air.Inst.Index) !CValue {
35313541}
35323542
35333543fn airAlloc(f: *Function, inst: Air.Inst.Index) !CValue {
3534 const zcu = f.object.dg.zcu;
3544 const pt = f.object.dg.pt;
3545 const zcu = pt.zcu;
35353546 const inst_ty = f.typeOfIndex(inst);
35363547 const elem_ty = inst_ty.childType(zcu);
3537 if (!elem_ty.isFnOrHasRuntimeBitsIgnoreComptime(zcu)) return .{ .undef = inst_ty };
3548 if (!elem_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt)) return .{ .undef = inst_ty };
35383549
35393550 const local = try f.allocLocalValue(.{
35403551 .ctype = try f.ctypeFromType(elem_ty, .complete),
35413552 .alignas = CType.AlignAs.fromAlignment(.{
35423553 .@"align" = inst_ty.ptrInfo(zcu).flags.alignment,
3543 .abi = elem_ty.abiAlignment(zcu),
3554 .abi = elem_ty.abiAlignment(pt),
35443555 }),
35453556 });
35463557 log.debug("%{d}: allocated unfreeable t{d}", .{ inst, local.new_local });
3547 const gpa = f.object.dg.zcu.gpa;
3548 try f.allocs.put(gpa, local.new_local, true);
3558 try f.allocs.put(zcu.gpa, local.new_local, true);
35493559 return .{ .local_ref = local.new_local };
35503560}
35513561
35523562fn airRetPtr(f: *Function, inst: Air.Inst.Index) !CValue {
3553 const zcu = f.object.dg.zcu;
3563 const pt = f.object.dg.pt;
3564 const zcu = pt.zcu;
35543565 const inst_ty = f.typeOfIndex(inst);
35553566 const elem_ty = inst_ty.childType(zcu);
3556 if (!elem_ty.isFnOrHasRuntimeBitsIgnoreComptime(zcu)) return .{ .undef = inst_ty };
3567 if (!elem_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt)) return .{ .undef = inst_ty };
35573568
35583569 const local = try f.allocLocalValue(.{
35593570 .ctype = try f.ctypeFromType(elem_ty, .complete),
35603571 .alignas = CType.AlignAs.fromAlignment(.{
35613572 .@"align" = inst_ty.ptrInfo(zcu).flags.alignment,
3562 .abi = elem_ty.abiAlignment(zcu),
3573 .abi = elem_ty.abiAlignment(pt),
35633574 }),
35643575 });
35653576 log.debug("%{d}: allocated unfreeable t{d}", .{ inst, local.new_local });
3566 const gpa = f.object.dg.zcu.gpa;
3567 try f.allocs.put(gpa, local.new_local, true);
3577 try f.allocs.put(zcu.gpa, local.new_local, true);
35683578 return .{ .local_ref = local.new_local };
35693579}
35703580
......@@ -3593,7 +3603,8 @@ fn airArg(f: *Function, inst: Air.Inst.Index) !CValue {
35933603}
35943604
35953605fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
3596 const zcu = f.object.dg.zcu;
3606 const pt = f.object.dg.pt;
3607 const zcu = pt.zcu;
35973608 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
35983609
35993610 const ptr_ty = f.typeOf(ty_op.operand);
......@@ -3601,7 +3612,7 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
36013612 const ptr_info = ptr_scalar_ty.ptrInfo(zcu);
36023613 const src_ty = Type.fromInterned(ptr_info.child);
36033614
3604 if (!src_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
3615 if (!src_ty.hasRuntimeBitsIgnoreComptime(pt)) {
36053616 try reap(f, inst, &.{ty_op.operand});
36063617 return .none;
36073618 }
......@@ -3611,10 +3622,10 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
36113622 try reap(f, inst, &.{ty_op.operand});
36123623
36133624 const is_aligned = if (ptr_info.flags.alignment != .none)
3614 ptr_info.flags.alignment.order(src_ty.abiAlignment(zcu)).compare(.gte)
3625 ptr_info.flags.alignment.order(src_ty.abiAlignment(pt)).compare(.gte)
36153626 else
36163627 true;
3617 const is_array = lowersToArray(src_ty, zcu);
3628 const is_array = lowersToArray(src_ty, pt);
36183629 const need_memcpy = !is_aligned or is_array;
36193630
36203631 const writer = f.object.writer();
......@@ -3634,12 +3645,12 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
36343645 try writer.writeAll("))");
36353646 } else if (ptr_info.packed_offset.host_size > 0 and ptr_info.flags.vector_index == .none) {
36363647 const host_bits: u16 = ptr_info.packed_offset.host_size * 8;
3637 const host_ty = try zcu.intType(.unsigned, host_bits);
3648 const host_ty = try pt.intType(.unsigned, host_bits);
36383649
3639 const bit_offset_ty = try zcu.intType(.unsigned, Type.smallestUnsignedBits(host_bits - 1));
3640 const bit_offset_val = try zcu.intValue(bit_offset_ty, ptr_info.packed_offset.bit_offset);
3650 const bit_offset_ty = try pt.intType(.unsigned, Type.smallestUnsignedBits(host_bits - 1));
3651 const bit_offset_val = try pt.intValue(bit_offset_ty, ptr_info.packed_offset.bit_offset);
36413652
3642 const field_ty = try zcu.intType(.unsigned, @as(u16, @intCast(src_ty.bitSize(zcu))));
3653 const field_ty = try pt.intType(.unsigned, @as(u16, @intCast(src_ty.bitSize(pt))));
36433654
36443655 try f.writeCValue(writer, local, .Other);
36453656 try v.elem(f, writer);
......@@ -3650,9 +3661,9 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
36503661 try writer.writeAll("((");
36513662 try f.renderType(writer, field_ty);
36523663 try writer.writeByte(')');
3653 const cant_cast = host_ty.isInt(zcu) and host_ty.bitSize(zcu) > 64;
3664 const cant_cast = host_ty.isInt(zcu) and host_ty.bitSize(pt) > 64;
36543665 if (cant_cast) {
3655 if (field_ty.bitSize(zcu) > 64) return f.fail("TODO: C backend: implement casting between types > 64 bits", .{});
3666 if (field_ty.bitSize(pt) > 64) return f.fail("TODO: C backend: implement casting between types > 64 bits", .{});
36563667 try writer.writeAll("zig_lo_");
36573668 try f.object.dg.renderTypeForBuiltinFnName(writer, host_ty);
36583669 try writer.writeByte('(');
......@@ -3680,7 +3691,8 @@ fn airLoad(f: *Function, inst: Air.Inst.Index) !CValue {
36803691}
36813692
36823693fn airRet(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValue {
3683 const zcu = f.object.dg.zcu;
3694 const pt = f.object.dg.pt;
3695 const zcu = pt.zcu;
36843696 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
36853697 const writer = f.object.writer();
36863698 const op_inst = un_op.toIndex();
......@@ -3695,11 +3707,11 @@ fn airRet(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValue {
36953707 const operand = try f.resolveInst(un_op);
36963708 try reap(f, inst, &.{un_op});
36973709 var deref = is_ptr;
3698 const is_array = lowersToArray(ret_ty, zcu);
3710 const is_array = lowersToArray(ret_ty, pt);
36993711 const ret_val = if (is_array) ret_val: {
37003712 const array_local = try f.allocAlignedLocal(inst, .{
37013713 .ctype = ret_ctype,
3702 .alignas = CType.AlignAs.fromAbiAlignment(ret_ty.abiAlignment(f.object.dg.zcu)),
3714 .alignas = CType.AlignAs.fromAbiAlignment(ret_ty.abiAlignment(pt)),
37033715 });
37043716 try writer.writeAll("memcpy(");
37053717 try f.writeCValueMember(writer, array_local, .{ .identifier = "array" });
......@@ -3733,7 +3745,8 @@ fn airRet(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValue {
37333745}
37343746
37353747fn airIntCast(f: *Function, inst: Air.Inst.Index) !CValue {
3736 const zcu = f.object.dg.zcu;
3748 const pt = f.object.dg.pt;
3749 const zcu = pt.zcu;
37373750 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
37383751
37393752 const operand = try f.resolveInst(ty_op.operand);
......@@ -3760,7 +3773,8 @@ fn airIntCast(f: *Function, inst: Air.Inst.Index) !CValue {
37603773}
37613774
37623775fn airTrunc(f: *Function, inst: Air.Inst.Index) !CValue {
3763 const zcu = f.object.dg.zcu;
3776 const pt = f.object.dg.pt;
3777 const zcu = pt.zcu;
37643778 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
37653779
37663780 const operand = try f.resolveInst(ty_op.operand);
......@@ -3809,13 +3823,13 @@ fn airTrunc(f: *Function, inst: Air.Inst.Index) !CValue {
38093823 try f.writeCValue(writer, operand, .FunctionArgument);
38103824 try v.elem(f, writer);
38113825 try writer.print(", {x})", .{
3812 try f.fmtIntLiteral(try inst_scalar_ty.maxIntScalar(zcu, scalar_ty)),
3826 try f.fmtIntLiteral(try inst_scalar_ty.maxIntScalar(pt, scalar_ty)),
38133827 });
38143828 },
38153829 .signed => {
38163830 const c_bits = toCIntBits(scalar_int_info.bits) orelse
38173831 return f.fail("TODO: C backend: implement integer types larger than 128 bits", .{});
3818 const shift_val = try zcu.intValue(Type.u8, c_bits - dest_bits);
3832 const shift_val = try pt.intValue(Type.u8, c_bits - dest_bits);
38193833
38203834 try writer.writeAll("zig_shr_");
38213835 try f.object.dg.renderTypeForBuiltinFnName(writer, scalar_ty);
......@@ -3860,7 +3874,8 @@ fn airIntFromBool(f: *Function, inst: Air.Inst.Index) !CValue {
38603874}
38613875
38623876fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
3863 const zcu = f.object.dg.zcu;
3877 const pt = f.object.dg.pt;
3878 const zcu = pt.zcu;
38643879 // *a = b;
38653880 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
38663881
......@@ -3871,7 +3886,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
38713886 const ptr_val = try f.resolveInst(bin_op.lhs);
38723887 const src_ty = f.typeOf(bin_op.rhs);
38733888
3874 const val_is_undef = if (try f.air.value(bin_op.rhs, zcu)) |v| v.isUndefDeep(zcu) else false;
3889 const val_is_undef = if (try f.air.value(bin_op.rhs, pt)) |v| v.isUndefDeep(zcu) else false;
38753890
38763891 if (val_is_undef) {
38773892 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
......@@ -3887,10 +3902,10 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
38873902 }
38883903
38893904 const is_aligned = if (ptr_info.flags.alignment != .none)
3890 ptr_info.flags.alignment.order(src_ty.abiAlignment(zcu)).compare(.gte)
3905 ptr_info.flags.alignment.order(src_ty.abiAlignment(pt)).compare(.gte)
38913906 else
38923907 true;
3893 const is_array = lowersToArray(Type.fromInterned(ptr_info.child), zcu);
3908 const is_array = lowersToArray(Type.fromInterned(ptr_info.child), pt);
38943909 const need_memcpy = !is_aligned or is_array;
38953910
38963911 const src_val = try f.resolveInst(bin_op.rhs);
......@@ -3901,7 +3916,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
39013916 if (need_memcpy) {
39023917 // For this memcpy to safely work we need the rhs to have the same
39033918 // underlying type as the lhs (i.e. they must both be arrays of the same underlying type).
3904 assert(src_ty.eql(Type.fromInterned(ptr_info.child), f.object.dg.zcu));
3919 assert(src_ty.eql(Type.fromInterned(ptr_info.child), zcu));
39053920
39063921 // If the source is a constant, writeCValue will emit a brace initialization
39073922 // so work around this by initializing into new local.
......@@ -3932,12 +3947,12 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
39323947 try v.end(f, inst, writer);
39333948 } else if (ptr_info.packed_offset.host_size > 0 and ptr_info.flags.vector_index == .none) {
39343949 const host_bits = ptr_info.packed_offset.host_size * 8;
3935 const host_ty = try zcu.intType(.unsigned, host_bits);
3950 const host_ty = try pt.intType(.unsigned, host_bits);
39363951
3937 const bit_offset_ty = try zcu.intType(.unsigned, Type.smallestUnsignedBits(host_bits - 1));
3938 const bit_offset_val = try zcu.intValue(bit_offset_ty, ptr_info.packed_offset.bit_offset);
3952 const bit_offset_ty = try pt.intType(.unsigned, Type.smallestUnsignedBits(host_bits - 1));
3953 const bit_offset_val = try pt.intValue(bit_offset_ty, ptr_info.packed_offset.bit_offset);
39393954
3940 const src_bits = src_ty.bitSize(zcu);
3955 const src_bits = src_ty.bitSize(pt);
39413956
39423957 const ExpectedContents = [BigInt.Managed.default_capacity]BigIntLimb;
39433958 var stack align(@alignOf(ExpectedContents)) =
......@@ -3950,7 +3965,7 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
39503965 try mask.shiftLeft(&mask, ptr_info.packed_offset.bit_offset);
39513966 try mask.bitNotWrap(&mask, .unsigned, host_bits);
39523967
3953 const mask_val = try zcu.intValue_big(host_ty, mask.toConst());
3968 const mask_val = try pt.intValue_big(host_ty, mask.toConst());
39543969
39553970 const v = try Vectorize.start(f, inst, writer, ptr_ty);
39563971 const a = try Assignment.start(f, writer, src_scalar_ctype);
......@@ -3967,9 +3982,9 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
39673982 try writer.print(", {x}), zig_shl_", .{try f.fmtIntLiteral(mask_val)});
39683983 try f.object.dg.renderTypeForBuiltinFnName(writer, host_ty);
39693984 try writer.writeByte('(');
3970 const cant_cast = host_ty.isInt(zcu) and host_ty.bitSize(zcu) > 64;
3985 const cant_cast = host_ty.isInt(zcu) and host_ty.bitSize(pt) > 64;
39713986 if (cant_cast) {
3972 if (src_ty.bitSize(zcu) > 64) return f.fail("TODO: C backend: implement casting between types > 64 bits", .{});
3987 if (src_ty.bitSize(pt) > 64) return f.fail("TODO: C backend: implement casting between types > 64 bits", .{});
39733988 try writer.writeAll("zig_make_");
39743989 try f.object.dg.renderTypeForBuiltinFnName(writer, host_ty);
39753990 try writer.writeAll("(0, ");
......@@ -4013,7 +4028,8 @@ fn airStore(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
40134028}
40144029
40154030fn airOverflow(f: *Function, inst: Air.Inst.Index, operation: []const u8, info: BuiltinInfo) !CValue {
4016 const zcu = f.object.dg.zcu;
4031 const pt = f.object.dg.pt;
4032 const zcu = pt.zcu;
40174033 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
40184034 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;
40194035
......@@ -4051,7 +4067,8 @@ fn airOverflow(f: *Function, inst: Air.Inst.Index, operation: []const u8, info:
40514067}
40524068
40534069fn airNot(f: *Function, inst: Air.Inst.Index) !CValue {
4054 const zcu = f.object.dg.zcu;
4070 const pt = f.object.dg.pt;
4071 const zcu = pt.zcu;
40554072 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
40564073 const operand_ty = f.typeOf(ty_op.operand);
40574074 const scalar_ty = operand_ty.scalarType(zcu);
......@@ -4084,11 +4101,12 @@ fn airBinOp(
40844101 operation: []const u8,
40854102 info: BuiltinInfo,
40864103) !CValue {
4087 const zcu = f.object.dg.zcu;
4104 const pt = f.object.dg.pt;
4105 const zcu = pt.zcu;
40884106 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
40894107 const operand_ty = f.typeOf(bin_op.lhs);
40904108 const scalar_ty = operand_ty.scalarType(zcu);
4091 if ((scalar_ty.isInt(zcu) and scalar_ty.bitSize(zcu) > 64) or scalar_ty.isRuntimeFloat())
4109 if ((scalar_ty.isInt(zcu) and scalar_ty.bitSize(pt) > 64) or scalar_ty.isRuntimeFloat())
40924110 return try airBinBuiltinCall(f, inst, operation, info);
40934111
40944112 const lhs = try f.resolveInst(bin_op.lhs);
......@@ -4122,11 +4140,12 @@ fn airCmpOp(
41224140 data: anytype,
41234141 operator: std.math.CompareOperator,
41244142) !CValue {
4125 const zcu = f.object.dg.zcu;
4143 const pt = f.object.dg.pt;
4144 const zcu = pt.zcu;
41264145 const lhs_ty = f.typeOf(data.lhs);
41274146 const scalar_ty = lhs_ty.scalarType(zcu);
41284147
4129 const scalar_bits = scalar_ty.bitSize(zcu);
4148 const scalar_bits = scalar_ty.bitSize(pt);
41304149 if (scalar_ty.isInt(zcu) and scalar_bits > 64)
41314150 return airCmpBuiltinCall(
41324151 f,
......@@ -4170,12 +4189,13 @@ fn airEquality(
41704189 inst: Air.Inst.Index,
41714190 operator: std.math.CompareOperator,
41724191) !CValue {
4173 const zcu = f.object.dg.zcu;
4192 const pt = f.object.dg.pt;
4193 const zcu = pt.zcu;
41744194 const ctype_pool = &f.object.dg.ctype_pool;
41754195 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
41764196
41774197 const operand_ty = f.typeOf(bin_op.lhs);
4178 const operand_bits = operand_ty.bitSize(zcu);
4198 const operand_bits = operand_ty.bitSize(pt);
41794199 if (operand_ty.isAbiInt(zcu) and operand_bits > 64)
41804200 return airCmpBuiltinCall(
41814201 f,
......@@ -4256,7 +4276,8 @@ fn airCmpLtErrorsLen(f: *Function, inst: Air.Inst.Index) !CValue {
42564276}
42574277
42584278fn airPtrAddSub(f: *Function, inst: Air.Inst.Index, operator: u8) !CValue {
4259 const zcu = f.object.dg.zcu;
4279 const pt = f.object.dg.pt;
4280 const zcu = pt.zcu;
42604281 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
42614282 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;
42624283
......@@ -4267,7 +4288,7 @@ fn airPtrAddSub(f: *Function, inst: Air.Inst.Index, operator: u8) !CValue {
42674288 const inst_ty = f.typeOfIndex(inst);
42684289 const inst_scalar_ty = inst_ty.scalarType(zcu);
42694290 const elem_ty = inst_scalar_ty.elemType2(zcu);
4270 if (!elem_ty.hasRuntimeBitsIgnoreComptime(zcu)) return f.moveCValue(inst, inst_ty, lhs);
4291 if (!elem_ty.hasRuntimeBitsIgnoreComptime(pt)) return f.moveCValue(inst, inst_ty, lhs);
42714292 const inst_scalar_ctype = try f.ctypeFromType(inst_scalar_ty, .complete);
42724293
42734294 const local = try f.allocLocal(inst, inst_ty);
......@@ -4299,13 +4320,14 @@ fn airPtrAddSub(f: *Function, inst: Air.Inst.Index, operator: u8) !CValue {
42994320}
43004321
43014322fn airMinMax(f: *Function, inst: Air.Inst.Index, operator: u8, operation: []const u8) !CValue {
4302 const zcu = f.object.dg.zcu;
4323 const pt = f.object.dg.pt;
4324 const zcu = pt.zcu;
43034325 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
43044326
43054327 const inst_ty = f.typeOfIndex(inst);
43064328 const inst_scalar_ty = inst_ty.scalarType(zcu);
43074329
4308 if ((inst_scalar_ty.isInt(zcu) and inst_scalar_ty.bitSize(zcu) > 64) or inst_scalar_ty.isRuntimeFloat())
4330 if ((inst_scalar_ty.isInt(zcu) and inst_scalar_ty.bitSize(pt) > 64) or inst_scalar_ty.isRuntimeFloat())
43094331 return try airBinBuiltinCall(f, inst, operation, .none);
43104332
43114333 const lhs = try f.resolveInst(bin_op.lhs);
......@@ -4339,7 +4361,8 @@ fn airMinMax(f: *Function, inst: Air.Inst.Index, operator: u8, operation: []cons
43394361}
43404362
43414363fn airSlice(f: *Function, inst: Air.Inst.Index) !CValue {
4342 const zcu = f.object.dg.zcu;
4364 const pt = f.object.dg.pt;
4365 const zcu = pt.zcu;
43434366 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
43444367 const bin_op = f.air.extraData(Air.Bin, ty_pl.payload).data;
43454368
......@@ -4374,7 +4397,8 @@ fn airCall(
43744397 inst: Air.Inst.Index,
43754398 modifier: std.builtin.CallModifier,
43764399) !CValue {
4377 const zcu = f.object.dg.zcu;
4400 const pt = f.object.dg.pt;
4401 const zcu = pt.zcu;
43784402 // Not even allowed to call panic in a naked function.
43794403 if (f.object.dg.is_naked_fn) return .none;
43804404
......@@ -4398,7 +4422,7 @@ fn airCall(
43984422 if (!arg_ctype.eql(try f.ctypeFromType(arg_ty, .complete))) {
43994423 const array_local = try f.allocAlignedLocal(inst, .{
44004424 .ctype = arg_ctype,
4401 .alignas = CType.AlignAs.fromAbiAlignment(arg_ty.abiAlignment(zcu)),
4425 .alignas = CType.AlignAs.fromAbiAlignment(arg_ty.abiAlignment(pt)),
44024426 });
44034427 try writer.writeAll("memcpy(");
44044428 try f.writeCValueMember(writer, array_local, .{ .identifier = "array" });
......@@ -4445,7 +4469,7 @@ fn airCall(
44454469 } else {
44464470 const local = try f.allocAlignedLocal(inst, .{
44474471 .ctype = ret_ctype,
4448 .alignas = CType.AlignAs.fromAbiAlignment(ret_ty.abiAlignment(zcu)),
4472 .alignas = CType.AlignAs.fromAbiAlignment(ret_ty.abiAlignment(pt)),
44494473 });
44504474 try f.writeCValue(writer, local, .Other);
44514475 try writer.writeAll(" = ");
......@@ -4456,7 +4480,7 @@ fn airCall(
44564480 callee: {
44574481 known: {
44584482 const fn_decl = fn_decl: {
4459 const callee_val = (try f.air.value(pl_op.operand, zcu)) orelse break :known;
4483 const callee_val = (try f.air.value(pl_op.operand, pt)) orelse break :known;
44604484 break :fn_decl switch (zcu.intern_pool.indexToKey(callee_val.toIntern())) {
44614485 .extern_func => |extern_func| extern_func.decl,
44624486 .func => |func| func.owner_decl,
......@@ -4499,7 +4523,7 @@ fn airCall(
44994523 try writer.writeAll(");\n");
45004524
45014525 const result = result: {
4502 if (result_local == .none or !lowersToArray(ret_ty, zcu))
4526 if (result_local == .none or !lowersToArray(ret_ty, pt))
45034527 break :result result_local;
45044528
45054529 const array_local = try f.allocLocal(inst, ret_ty);
......@@ -4533,7 +4557,8 @@ fn airDbgStmt(f: *Function, inst: Air.Inst.Index) !CValue {
45334557}
45344558
45354559fn airDbgInlineBlock(f: *Function, inst: Air.Inst.Index) !CValue {
4536 const zcu = f.object.dg.zcu;
4560 const pt = f.object.dg.pt;
4561 const zcu = pt.zcu;
45374562 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
45384563 const extra = f.air.extraData(Air.DbgInlineBlock, ty_pl.payload);
45394564 const owner_decl = zcu.funcOwnerDeclPtr(extra.data.func);
......@@ -4545,10 +4570,11 @@ fn airDbgInlineBlock(f: *Function, inst: Air.Inst.Index) !CValue {
45454570}
45464571
45474572fn airDbgVar(f: *Function, inst: Air.Inst.Index) !CValue {
4548 const zcu = f.object.dg.zcu;
4573 const pt = f.object.dg.pt;
4574 const zcu = pt.zcu;
45494575 const pl_op = f.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
45504576 const name = f.air.nullTerminatedString(pl_op.payload);
4551 const operand_is_undef = if (try f.air.value(pl_op.operand, zcu)) |v| v.isUndefDeep(zcu) else false;
4577 const operand_is_undef = if (try f.air.value(pl_op.operand, pt)) |v| v.isUndefDeep(zcu) else false;
45524578 if (!operand_is_undef) _ = try f.resolveInst(pl_op.operand);
45534579
45544580 try reap(f, inst, &.{pl_op.operand});
......@@ -4564,7 +4590,8 @@ fn airBlock(f: *Function, inst: Air.Inst.Index) !CValue {
45644590}
45654591
45664592fn lowerBlock(f: *Function, inst: Air.Inst.Index, body: []const Air.Inst.Index) !CValue {
4567 const zcu = f.object.dg.zcu;
4593 const pt = f.object.dg.pt;
4594 const zcu = pt.zcu;
45684595 const liveness_block = f.liveness.getBlock(inst);
45694596
45704597 const block_id: usize = f.next_block_index;
......@@ -4572,7 +4599,7 @@ fn lowerBlock(f: *Function, inst: Air.Inst.Index, body: []const Air.Inst.Index)
45724599 const writer = f.object.writer();
45734600
45744601 const inst_ty = f.typeOfIndex(inst);
4575 const result = if (inst_ty.hasRuntimeBitsIgnoreComptime(zcu) and !f.liveness.isUnused(inst))
4602 const result = if (inst_ty.hasRuntimeBitsIgnoreComptime(pt) and !f.liveness.isUnused(inst))
45764603 try f.allocLocal(inst, inst_ty)
45774604 else
45784605 .none;
......@@ -4611,7 +4638,8 @@ fn airTry(f: *Function, inst: Air.Inst.Index) !CValue {
46114638}
46124639
46134640fn airTryPtr(f: *Function, inst: Air.Inst.Index) !CValue {
4614 const zcu = f.object.dg.zcu;
4641 const pt = f.object.dg.pt;
4642 const zcu = pt.zcu;
46154643 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
46164644 const extra = f.air.extraData(Air.TryPtr, ty_pl.payload);
46174645 const body: []const Air.Inst.Index = @ptrCast(f.air.extra[extra.end..][0..extra.data.body_len]);
......@@ -4627,13 +4655,14 @@ fn lowerTry(
46274655 err_union_ty: Type,
46284656 is_ptr: bool,
46294657) !CValue {
4630 const zcu = f.object.dg.zcu;
4658 const pt = f.object.dg.pt;
4659 const zcu = pt.zcu;
46314660 const err_union = try f.resolveInst(operand);
46324661 const inst_ty = f.typeOfIndex(inst);
46334662 const liveness_condbr = f.liveness.getCondBr(inst);
46344663 const writer = f.object.writer();
46354664 const payload_ty = err_union_ty.errorUnionPayload(zcu);
4636 const payload_has_bits = payload_ty.hasRuntimeBitsIgnoreComptime(zcu);
4665 const payload_has_bits = payload_ty.hasRuntimeBitsIgnoreComptime(pt);
46374666
46384667 if (!err_union_ty.errorUnionSet(zcu).errorSetIsEmpty(zcu)) {
46394668 try writer.writeAll("if (");
......@@ -4725,7 +4754,8 @@ fn airBitcast(f: *Function, inst: Air.Inst.Index) !CValue {
47254754}
47264755
47274756fn bitcast(f: *Function, dest_ty: Type, operand: CValue, operand_ty: Type) !CValue {
4728 const zcu = f.object.dg.zcu;
4757 const pt = f.object.dg.pt;
4758 const zcu = pt.zcu;
47294759 const target = &f.object.dg.mod.resolved_target.result;
47304760 const ctype_pool = &f.object.dg.ctype_pool;
47314761 const writer = f.object.writer();
......@@ -4771,7 +4801,7 @@ fn bitcast(f: *Function, dest_ty: Type, operand: CValue, operand_ty: Type) !CVal
47714801 try writer.writeAll(", sizeof(");
47724802 try f.renderType(
47734803 writer,
4774 if (dest_ty.abiSize(zcu) <= operand_ty.abiSize(zcu)) dest_ty else operand_ty,
4804 if (dest_ty.abiSize(pt) <= operand_ty.abiSize(pt)) dest_ty else operand_ty,
47754805 );
47764806 try writer.writeAll("));\n");
47774807
......@@ -4805,7 +4835,7 @@ fn bitcast(f: *Function, dest_ty: Type, operand: CValue, operand_ty: Type) !CVal
48054835 try writer.writeByte('(');
48064836 }
48074837 try writer.writeAll("zig_wrap_");
4808 const info_ty = try zcu.intType(dest_info.signedness, bits);
4838 const info_ty = try pt.intType(dest_info.signedness, bits);
48094839 if (wrap_ctype) |ctype|
48104840 try f.object.dg.renderCTypeForBuiltinFnName(writer, ctype)
48114841 else
......@@ -4935,7 +4965,8 @@ fn airCondBr(f: *Function, inst: Air.Inst.Index) !CValue {
49354965}
49364966
49374967fn airSwitchBr(f: *Function, inst: Air.Inst.Index) !CValue {
4938 const zcu = f.object.dg.zcu;
4968 const pt = f.object.dg.pt;
4969 const zcu = pt.zcu;
49394970 const pl_op = f.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
49404971 const condition = try f.resolveInst(pl_op.operand);
49414972 try reap(f, inst, &.{pl_op.operand});
......@@ -4979,16 +5010,16 @@ fn airSwitchBr(f: *Function, inst: Air.Inst.Index) !CValue {
49795010 for (items) |item| {
49805011 try f.object.indent_writer.insertNewline();
49815012 try writer.writeAll("case ");
4982 const item_value = try f.air.value(item, zcu);
4983 if (item_value.?.getUnsignedInt(zcu)) |item_int| try writer.print("{}\n", .{
4984 try f.fmtIntLiteral(try zcu.intValue(lowered_condition_ty, item_int)),
5013 const item_value = try f.air.value(item, pt);
5014 if (item_value.?.getUnsignedInt(pt)) |item_int| try writer.print("{}\n", .{
5015 try f.fmtIntLiteral(try pt.intValue(lowered_condition_ty, item_int)),
49855016 }) else {
49865017 if (condition_ty.isPtrAtRuntime(zcu)) {
49875018 try writer.writeByte('(');
49885019 try f.renderType(writer, Type.usize);
49895020 try writer.writeByte(')');
49905021 }
4991 try f.object.dg.renderValue(writer, (try f.air.value(item, zcu)).?, .Other);
5022 try f.object.dg.renderValue(writer, (try f.air.value(item, pt)).?, .Other);
49925023 }
49935024 try writer.writeByte(':');
49945025 }
......@@ -5026,13 +5057,14 @@ fn airSwitchBr(f: *Function, inst: Air.Inst.Index) !CValue {
50265057}
50275058
50285059fn asmInputNeedsLocal(f: *Function, constraint: []const u8, value: CValue) bool {
5029 const target = &f.object.dg.mod.resolved_target.result;
5060 const dg = f.object.dg;
5061 const target = &dg.mod.resolved_target.result;
50305062 return switch (constraint[0]) {
50315063 '{' => true,
50325064 'i', 'r' => false,
50335065 'I' => !target.cpu.arch.isArmOrThumb(),
50345066 else => switch (value) {
5035 .constant => |val| switch (f.object.dg.zcu.intern_pool.indexToKey(val.toIntern())) {
5067 .constant => |val| switch (dg.pt.zcu.intern_pool.indexToKey(val.toIntern())) {
50365068 .ptr => |ptr| if (ptr.byte_offset == 0) switch (ptr.base_addr) {
50375069 .decl => false,
50385070 else => true,
......@@ -5045,7 +5077,8 @@ fn asmInputNeedsLocal(f: *Function, constraint: []const u8, value: CValue) bool
50455077}
50465078
50475079fn airAsm(f: *Function, inst: Air.Inst.Index) !CValue {
5048 const zcu = f.object.dg.zcu;
5080 const pt = f.object.dg.pt;
5081 const zcu = pt.zcu;
50495082 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
50505083 const extra = f.air.extraData(Air.Asm, ty_pl.payload);
50515084 const is_volatile = @as(u1, @truncate(extra.data.flags >> 31)) != 0;
......@@ -5060,10 +5093,10 @@ fn airAsm(f: *Function, inst: Air.Inst.Index) !CValue {
50605093 const result = result: {
50615094 const writer = f.object.writer();
50625095 const inst_ty = f.typeOfIndex(inst);
5063 const inst_local = if (inst_ty.hasRuntimeBitsIgnoreComptime(zcu)) local: {
5096 const inst_local = if (inst_ty.hasRuntimeBitsIgnoreComptime(pt)) local: {
50645097 const inst_local = try f.allocLocalValue(.{
50655098 .ctype = try f.ctypeFromType(inst_ty, .complete),
5066 .alignas = CType.AlignAs.fromAbiAlignment(inst_ty.abiAlignment(zcu)),
5099 .alignas = CType.AlignAs.fromAbiAlignment(inst_ty.abiAlignment(pt)),
50675100 });
50685101 if (f.wantSafety()) {
50695102 try f.writeCValue(writer, inst_local, .Other);
......@@ -5096,7 +5129,7 @@ fn airAsm(f: *Function, inst: Air.Inst.Index) !CValue {
50965129 try writer.writeAll("register ");
50975130 const output_local = try f.allocLocalValue(.{
50985131 .ctype = try f.ctypeFromType(output_ty, .complete),
5099 .alignas = CType.AlignAs.fromAbiAlignment(output_ty.abiAlignment(zcu)),
5132 .alignas = CType.AlignAs.fromAbiAlignment(output_ty.abiAlignment(pt)),
51005133 });
51015134 try f.allocs.put(gpa, output_local.new_local, false);
51025135 try f.object.dg.renderTypeAndName(writer, output_ty, output_local, .{}, .none, .complete);
......@@ -5131,7 +5164,7 @@ fn airAsm(f: *Function, inst: Air.Inst.Index) !CValue {
51315164 if (is_reg) try writer.writeAll("register ");
51325165 const input_local = try f.allocLocalValue(.{
51335166 .ctype = try f.ctypeFromType(input_ty, .complete),
5134 .alignas = CType.AlignAs.fromAbiAlignment(input_ty.abiAlignment(zcu)),
5167 .alignas = CType.AlignAs.fromAbiAlignment(input_ty.abiAlignment(pt)),
51355168 });
51365169 try f.allocs.put(gpa, input_local.new_local, false);
51375170 try f.object.dg.renderTypeAndName(writer, input_ty, input_local, Const, .none, .complete);
......@@ -5314,7 +5347,8 @@ fn airIsNull(
53145347 operator: std.math.CompareOperator,
53155348 is_ptr: bool,
53165349) !CValue {
5317 const zcu = f.object.dg.zcu;
5350 const pt = f.object.dg.pt;
5351 const zcu = pt.zcu;
53185352 const ctype_pool = &f.object.dg.ctype_pool;
53195353 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
53205354
......@@ -5369,7 +5403,8 @@ fn airIsNull(
53695403}
53705404
53715405fn airOptionalPayload(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValue {
5372 const zcu = f.object.dg.zcu;
5406 const pt = f.object.dg.pt;
5407 const zcu = pt.zcu;
53735408 const ctype_pool = &f.object.dg.ctype_pool;
53745409 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
53755410
......@@ -5404,7 +5439,8 @@ fn airOptionalPayload(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValue
54045439}
54055440
54065441fn airOptionalPayloadPtrSet(f: *Function, inst: Air.Inst.Index) !CValue {
5407 const zcu = f.object.dg.zcu;
5442 const pt = f.object.dg.pt;
5443 const zcu = pt.zcu;
54085444 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
54095445 const writer = f.object.writer();
54105446 const operand = try f.resolveInst(ty_op.operand);
......@@ -5458,21 +5494,22 @@ fn fieldLocation(
54585494 container_ptr_ty: Type,
54595495 field_ptr_ty: Type,
54605496 field_index: u32,
5461 zcu: *Zcu,
5497 pt: Zcu.PerThread,
54625498) union(enum) {
54635499 begin: void,
54645500 field: CValue,
54655501 byte_offset: u64,
54665502} {
5503 const zcu = pt.zcu;
54675504 const ip = &zcu.intern_pool;
54685505 const container_ty = Type.fromInterned(ip.indexToKey(container_ptr_ty.toIntern()).ptr_type.child);
54695506 switch (ip.indexToKey(container_ty.toIntern())) {
54705507 .struct_type => {
54715508 const loaded_struct = ip.loadStructType(container_ty.toIntern());
54725509 return switch (loaded_struct.layout) {
5473 .auto, .@"extern" => if (!container_ty.hasRuntimeBitsIgnoreComptime(zcu))
5510 .auto, .@"extern" => if (!container_ty.hasRuntimeBitsIgnoreComptime(pt))
54745511 .begin
5475 else if (!field_ptr_ty.childType(zcu).hasRuntimeBitsIgnoreComptime(zcu))
5512 else if (!field_ptr_ty.childType(zcu).hasRuntimeBitsIgnoreComptime(pt))
54765513 .{ .byte_offset = loaded_struct.offsets.get(ip)[field_index] }
54775514 else
54785515 .{ .field = if (loaded_struct.fieldName(ip, field_index).unwrap()) |field_name|
......@@ -5480,16 +5517,16 @@ fn fieldLocation(
54805517 else
54815518 .{ .field = field_index } },
54825519 .@"packed" => if (field_ptr_ty.ptrInfo(zcu).packed_offset.host_size == 0)
5483 .{ .byte_offset = @divExact(zcu.structPackedFieldBitOffset(loaded_struct, field_index) +
5520 .{ .byte_offset = @divExact(pt.structPackedFieldBitOffset(loaded_struct, field_index) +
54845521 container_ptr_ty.ptrInfo(zcu).packed_offset.bit_offset, 8) }
54855522 else
54865523 .begin,
54875524 };
54885525 },
5489 .anon_struct_type => |anon_struct_info| return if (!container_ty.hasRuntimeBitsIgnoreComptime(zcu))
5526 .anon_struct_type => |anon_struct_info| return if (!container_ty.hasRuntimeBitsIgnoreComptime(pt))
54905527 .begin
5491 else if (!field_ptr_ty.childType(zcu).hasRuntimeBitsIgnoreComptime(zcu))
5492 .{ .byte_offset = container_ty.structFieldOffset(field_index, zcu) }
5528 else if (!field_ptr_ty.childType(zcu).hasRuntimeBitsIgnoreComptime(pt))
5529 .{ .byte_offset = container_ty.structFieldOffset(field_index, pt) }
54935530 else
54945531 .{ .field = if (anon_struct_info.fieldName(ip, field_index).unwrap()) |field_name|
54955532 .{ .identifier = field_name.toSlice(ip) }
......@@ -5500,8 +5537,8 @@ fn fieldLocation(
55005537 switch (loaded_union.getLayout(ip)) {
55015538 .auto, .@"extern" => {
55025539 const field_ty = Type.fromInterned(loaded_union.field_types.get(ip)[field_index]);
5503 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu))
5504 return if (loaded_union.hasTag(ip) and !container_ty.unionHasAllZeroBitFieldTypes(zcu))
5540 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt))
5541 return if (loaded_union.hasTag(ip) and !container_ty.unionHasAllZeroBitFieldTypes(pt))
55055542 .{ .field = .{ .identifier = "payload" } }
55065543 else
55075544 .begin;
......@@ -5546,7 +5583,8 @@ fn airStructFieldPtrIndex(f: *Function, inst: Air.Inst.Index, index: u8) !CValue
55465583}
55475584
55485585fn airFieldParentPtr(f: *Function, inst: Air.Inst.Index) !CValue {
5549 const zcu = f.object.dg.zcu;
5586 const pt = f.object.dg.pt;
5587 const zcu = pt.zcu;
55505588 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
55515589 const extra = f.air.extraData(Air.FieldParentPtr, ty_pl.payload).data;
55525590
......@@ -5564,10 +5602,10 @@ fn airFieldParentPtr(f: *Function, inst: Air.Inst.Index) !CValue {
55645602 try f.renderType(writer, container_ptr_ty);
55655603 try writer.writeByte(')');
55665604
5567 switch (fieldLocation(container_ptr_ty, field_ptr_ty, extra.field_index, zcu)) {
5605 switch (fieldLocation(container_ptr_ty, field_ptr_ty, extra.field_index, pt)) {
55685606 .begin => try f.writeCValue(writer, field_ptr_val, .Initializer),
55695607 .field => |field| {
5570 const u8_ptr_ty = try zcu.adjustPtrTypeChild(field_ptr_ty, Type.u8);
5608 const u8_ptr_ty = try pt.adjustPtrTypeChild(field_ptr_ty, Type.u8);
55715609
55725610 try writer.writeAll("((");
55735611 try f.renderType(writer, u8_ptr_ty);
......@@ -5580,14 +5618,14 @@ fn airFieldParentPtr(f: *Function, inst: Air.Inst.Index) !CValue {
55805618 try writer.writeAll("))");
55815619 },
55825620 .byte_offset => |byte_offset| {
5583 const u8_ptr_ty = try zcu.adjustPtrTypeChild(field_ptr_ty, Type.u8);
5621 const u8_ptr_ty = try pt.adjustPtrTypeChild(field_ptr_ty, Type.u8);
55845622
55855623 try writer.writeAll("((");
55865624 try f.renderType(writer, u8_ptr_ty);
55875625 try writer.writeByte(')');
55885626 try f.writeCValue(writer, field_ptr_val, .Other);
55895627 try writer.print(" - {})", .{
5590 try f.fmtIntLiteral(try zcu.intValue(Type.usize, byte_offset)),
5628 try f.fmtIntLiteral(try pt.intValue(Type.usize, byte_offset)),
55915629 });
55925630 },
55935631 }
......@@ -5603,7 +5641,8 @@ fn fieldPtr(
56035641 container_ptr_val: CValue,
56045642 field_index: u32,
56055643) !CValue {
5606 const zcu = f.object.dg.zcu;
5644 const pt = f.object.dg.pt;
5645 const zcu = pt.zcu;
56075646 const container_ty = container_ptr_ty.childType(zcu);
56085647 const field_ptr_ty = f.typeOfIndex(inst);
56095648
......@@ -5617,21 +5656,21 @@ fn fieldPtr(
56175656 try f.renderType(writer, field_ptr_ty);
56185657 try writer.writeByte(')');
56195658
5620 switch (fieldLocation(container_ptr_ty, field_ptr_ty, field_index, zcu)) {
5659 switch (fieldLocation(container_ptr_ty, field_ptr_ty, field_index, pt)) {
56215660 .begin => try f.writeCValue(writer, container_ptr_val, .Initializer),
56225661 .field => |field| {
56235662 try writer.writeByte('&');
56245663 try f.writeCValueDerefMember(writer, container_ptr_val, field);
56255664 },
56265665 .byte_offset => |byte_offset| {
5627 const u8_ptr_ty = try zcu.adjustPtrTypeChild(field_ptr_ty, Type.u8);
5666 const u8_ptr_ty = try pt.adjustPtrTypeChild(field_ptr_ty, Type.u8);
56285667
56295668 try writer.writeAll("((");
56305669 try f.renderType(writer, u8_ptr_ty);
56315670 try writer.writeByte(')');
56325671 try f.writeCValue(writer, container_ptr_val, .Other);
56335672 try writer.print(" + {})", .{
5634 try f.fmtIntLiteral(try zcu.intValue(Type.usize, byte_offset)),
5673 try f.fmtIntLiteral(try pt.intValue(Type.usize, byte_offset)),
56355674 });
56365675 },
56375676 }
......@@ -5641,13 +5680,14 @@ fn fieldPtr(
56415680}
56425681
56435682fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
5644 const zcu = f.object.dg.zcu;
5683 const pt = f.object.dg.pt;
5684 const zcu = pt.zcu;
56455685 const ip = &zcu.intern_pool;
56465686 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
56475687 const extra = f.air.extraData(Air.StructField, ty_pl.payload).data;
56485688
56495689 const inst_ty = f.typeOfIndex(inst);
5650 if (!inst_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
5690 if (!inst_ty.hasRuntimeBitsIgnoreComptime(pt)) {
56515691 try reap(f, inst, &.{extra.struct_operand});
56525692 return .none;
56535693 }
......@@ -5671,15 +5711,15 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
56715711 .@"packed" => {
56725712 const int_info = struct_ty.intInfo(zcu);
56735713
5674 const bit_offset_ty = try zcu.intType(.unsigned, Type.smallestUnsignedBits(int_info.bits - 1));
5714 const bit_offset_ty = try pt.intType(.unsigned, Type.smallestUnsignedBits(int_info.bits - 1));
56755715
5676 const bit_offset = zcu.structPackedFieldBitOffset(loaded_struct, extra.field_index);
5716 const bit_offset = pt.structPackedFieldBitOffset(loaded_struct, extra.field_index);
56775717
56785718 const field_int_signedness = if (inst_ty.isAbiInt(zcu))
56795719 inst_ty.intInfo(zcu).signedness
56805720 else
56815721 .unsigned;
5682 const field_int_ty = try zcu.intType(field_int_signedness, @as(u16, @intCast(inst_ty.bitSize(zcu))));
5722 const field_int_ty = try pt.intType(field_int_signedness, @as(u16, @intCast(inst_ty.bitSize(pt))));
56835723
56845724 const temp_local = try f.allocLocal(inst, field_int_ty);
56855725 try f.writeCValue(writer, temp_local, .Other);
......@@ -5690,7 +5730,7 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
56905730 try writer.writeByte(')');
56915731 const cant_cast = int_info.bits > 64;
56925732 if (cant_cast) {
5693 if (field_int_ty.bitSize(zcu) > 64) return f.fail("TODO: C backend: implement casting between types > 64 bits", .{});
5733 if (field_int_ty.bitSize(pt) > 64) return f.fail("TODO: C backend: implement casting between types > 64 bits", .{});
56945734 try writer.writeAll("zig_lo_");
56955735 try f.object.dg.renderTypeForBuiltinFnName(writer, struct_ty);
56965736 try writer.writeByte('(');
......@@ -5702,12 +5742,12 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
57025742 }
57035743 try f.writeCValue(writer, struct_byval, .Other);
57045744 if (bit_offset > 0) try writer.print(", {})", .{
5705 try f.fmtIntLiteral(try zcu.intValue(bit_offset_ty, bit_offset)),
5745 try f.fmtIntLiteral(try pt.intValue(bit_offset_ty, bit_offset)),
57065746 });
57075747 if (cant_cast) try writer.writeByte(')');
57085748 try f.object.dg.renderBuiltinInfo(writer, field_int_ty, .bits);
57095749 try writer.writeAll(");\n");
5710 if (inst_ty.eql(field_int_ty, f.object.dg.zcu)) return temp_local;
5750 if (inst_ty.eql(field_int_ty, zcu)) return temp_local;
57115751
57125752 const local = try f.allocLocal(inst, inst_ty);
57135753 if (local.new_local != temp_local.new_local) {
......@@ -5783,7 +5823,8 @@ fn airStructFieldVal(f: *Function, inst: Air.Inst.Index) !CValue {
57835823/// *(E!T) -> E
57845824/// Note that the result is never a pointer.
57855825fn airUnwrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
5786 const zcu = f.object.dg.zcu;
5826 const pt = f.object.dg.pt;
5827 const zcu = pt.zcu;
57875828 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
57885829
57895830 const inst_ty = f.typeOfIndex(inst);
......@@ -5797,7 +5838,7 @@ fn airUnwrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
57975838 const payload_ty = error_union_ty.errorUnionPayload(zcu);
57985839 const local = try f.allocLocal(inst, inst_ty);
57995840
5800 if (!payload_ty.hasRuntimeBits(zcu) and operand == .local and operand.local == local.new_local) {
5841 if (!payload_ty.hasRuntimeBits(pt) and operand == .local and operand.local == local.new_local) {
58015842 // The store will be 'x = x'; elide it.
58025843 return local;
58035844 }
......@@ -5806,11 +5847,11 @@ fn airUnwrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
58065847 try f.writeCValue(writer, local, .Other);
58075848 try writer.writeAll(" = ");
58085849
5809 if (!payload_ty.hasRuntimeBits(zcu))
5850 if (!payload_ty.hasRuntimeBits(pt))
58105851 try f.writeCValue(writer, operand, .Other)
58115852 else if (error_ty.errorSetIsEmpty(zcu))
58125853 try writer.print("{}", .{
5813 try f.fmtIntLiteral(try zcu.intValue(try zcu.errorIntType(), 0)),
5854 try f.fmtIntLiteral(try pt.intValue(try pt.errorIntType(), 0)),
58145855 })
58155856 else if (operand_is_ptr)
58165857 try f.writeCValueDerefMember(writer, operand, .{ .identifier = "error" })
......@@ -5821,7 +5862,8 @@ fn airUnwrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
58215862}
58225863
58235864fn airUnwrapErrUnionPay(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValue {
5824 const zcu = f.object.dg.zcu;
5865 const pt = f.object.dg.pt;
5866 const zcu = pt.zcu;
58255867 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
58265868
58275869 const inst_ty = f.typeOfIndex(inst);
......@@ -5831,7 +5873,7 @@ fn airUnwrapErrUnionPay(f: *Function, inst: Air.Inst.Index, is_ptr: bool) !CValu
58315873 const error_union_ty = if (is_ptr) operand_ty.childType(zcu) else operand_ty;
58325874
58335875 const writer = f.object.writer();
5834 if (!error_union_ty.errorUnionPayload(zcu).hasRuntimeBits(zcu)) {
5876 if (!error_union_ty.errorUnionPayload(zcu).hasRuntimeBits(pt)) {
58355877 if (!is_ptr) return .none;
58365878
58375879 const local = try f.allocLocal(inst, inst_ty);
......@@ -5896,12 +5938,13 @@ fn airWrapOptional(f: *Function, inst: Air.Inst.Index) !CValue {
58965938}
58975939
58985940fn airWrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
5899 const zcu = f.object.dg.zcu;
5941 const pt = f.object.dg.pt;
5942 const zcu = pt.zcu;
59005943 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59015944
59025945 const inst_ty = f.typeOfIndex(inst);
59035946 const payload_ty = inst_ty.errorUnionPayload(zcu);
5904 const repr_is_err = !payload_ty.hasRuntimeBitsIgnoreComptime(zcu);
5947 const repr_is_err = !payload_ty.hasRuntimeBitsIgnoreComptime(pt);
59055948 const err_ty = inst_ty.errorUnionSet(zcu);
59065949 const err = try f.resolveInst(ty_op.operand);
59075950 try reap(f, inst, &.{ty_op.operand});
......@@ -5935,7 +5978,8 @@ fn airWrapErrUnionErr(f: *Function, inst: Air.Inst.Index) !CValue {
59355978}
59365979
59375980fn airErrUnionPayloadPtrSet(f: *Function, inst: Air.Inst.Index) !CValue {
5938 const zcu = f.object.dg.zcu;
5981 const pt = f.object.dg.pt;
5982 const zcu = pt.zcu;
59395983 const writer = f.object.writer();
59405984 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59415985 const inst_ty = f.typeOfIndex(inst);
......@@ -5944,12 +5988,12 @@ fn airErrUnionPayloadPtrSet(f: *Function, inst: Air.Inst.Index) !CValue {
59445988 const error_union_ty = operand_ty.childType(zcu);
59455989
59465990 const payload_ty = error_union_ty.errorUnionPayload(zcu);
5947 const err_int_ty = try zcu.errorIntType();
5948 const no_err = try zcu.intValue(err_int_ty, 0);
5991 const err_int_ty = try pt.errorIntType();
5992 const no_err = try pt.intValue(err_int_ty, 0);
59495993 try reap(f, inst, &.{ty_op.operand});
59505994
59515995 // First, set the non-error value.
5952 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
5996 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
59535997 const a = try Assignment.start(f, writer, try f.ctypeFromType(operand_ty, .complete));
59545998 try f.writeCValueDeref(writer, operand);
59555999 try a.assign(f, writer);
......@@ -5994,13 +6038,14 @@ fn airSaveErrReturnTraceIndex(f: *Function, inst: Air.Inst.Index) !CValue {
59946038}
59956039
59966040fn airWrapErrUnionPay(f: *Function, inst: Air.Inst.Index) !CValue {
5997 const zcu = f.object.dg.zcu;
6041 const pt = f.object.dg.pt;
6042 const zcu = pt.zcu;
59986043 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59996044
60006045 const inst_ty = f.typeOfIndex(inst);
60016046 const payload_ty = inst_ty.errorUnionPayload(zcu);
60026047 const payload = try f.resolveInst(ty_op.operand);
6003 const repr_is_err = !payload_ty.hasRuntimeBitsIgnoreComptime(zcu);
6048 const repr_is_err = !payload_ty.hasRuntimeBitsIgnoreComptime(pt);
60046049 const err_ty = inst_ty.errorUnionSet(zcu);
60056050 try reap(f, inst, &.{ty_op.operand});
60066051
......@@ -6020,14 +6065,15 @@ fn airWrapErrUnionPay(f: *Function, inst: Air.Inst.Index) !CValue {
60206065 else
60216066 try f.writeCValueMember(writer, local, .{ .identifier = "error" });
60226067 try a.assign(f, writer);
6023 try f.object.dg.renderValue(writer, try zcu.intValue(try zcu.errorIntType(), 0), .Other);
6068 try f.object.dg.renderValue(writer, try pt.intValue(try pt.errorIntType(), 0), .Other);
60246069 try a.end(f, writer);
60256070 }
60266071 return local;
60276072}
60286073
60296074fn airIsErr(f: *Function, inst: Air.Inst.Index, is_ptr: bool, operator: []const u8) !CValue {
6030 const zcu = f.object.dg.zcu;
6075 const pt = f.object.dg.pt;
6076 const zcu = pt.zcu;
60316077 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
60326078
60336079 const writer = f.object.writer();
......@@ -6042,9 +6088,9 @@ fn airIsErr(f: *Function, inst: Air.Inst.Index, is_ptr: bool, operator: []const
60426088 const a = try Assignment.start(f, writer, CType.bool);
60436089 try f.writeCValue(writer, local, .Other);
60446090 try a.assign(f, writer);
6045 const err_int_ty = try zcu.errorIntType();
6091 const err_int_ty = try pt.errorIntType();
60466092 if (!error_ty.errorSetIsEmpty(zcu))
6047 if (payload_ty.hasRuntimeBits(zcu))
6093 if (payload_ty.hasRuntimeBits(pt))
60486094 if (is_ptr)
60496095 try f.writeCValueDerefMember(writer, operand, .{ .identifier = "error" })
60506096 else
......@@ -6052,17 +6098,18 @@ fn airIsErr(f: *Function, inst: Air.Inst.Index, is_ptr: bool, operator: []const
60526098 else
60536099 try f.writeCValue(writer, operand, .Other)
60546100 else
6055 try f.object.dg.renderValue(writer, try zcu.intValue(err_int_ty, 0), .Other);
6101 try f.object.dg.renderValue(writer, try pt.intValue(err_int_ty, 0), .Other);
60566102 try writer.writeByte(' ');
60576103 try writer.writeAll(operator);
60586104 try writer.writeByte(' ');
6059 try f.object.dg.renderValue(writer, try zcu.intValue(err_int_ty, 0), .Other);
6105 try f.object.dg.renderValue(writer, try pt.intValue(err_int_ty, 0), .Other);
60606106 try a.end(f, writer);
60616107 return local;
60626108}
60636109
60646110fn airArrayToSlice(f: *Function, inst: Air.Inst.Index) !CValue {
6065 const zcu = f.object.dg.zcu;
6111 const pt = f.object.dg.pt;
6112 const zcu = pt.zcu;
60666113 const ctype_pool = &f.object.dg.ctype_pool;
60676114 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
60686115
......@@ -6096,7 +6143,7 @@ fn airArrayToSlice(f: *Function, inst: Air.Inst.Index) !CValue {
60966143 if (operand_child_ctype.info(ctype_pool) == .array) {
60976144 try writer.writeByte('&');
60986145 try f.writeCValueDeref(writer, operand);
6099 try writer.print("[{}]", .{try f.fmtIntLiteral(try zcu.intValue(Type.usize, 0))});
6146 try writer.print("[{}]", .{try f.fmtIntLiteral(try pt.intValue(Type.usize, 0))});
61006147 } else try f.writeCValue(writer, operand, .Initializer);
61016148 }
61026149 try a.end(f, writer);
......@@ -6106,7 +6153,7 @@ fn airArrayToSlice(f: *Function, inst: Air.Inst.Index) !CValue {
61066153 try f.writeCValueMember(writer, local, .{ .identifier = "len" });
61076154 try a.assign(f, writer);
61086155 try writer.print("{}", .{
6109 try f.fmtIntLiteral(try zcu.intValue(Type.usize, array_ty.arrayLen(zcu))),
6156 try f.fmtIntLiteral(try pt.intValue(Type.usize, array_ty.arrayLen(zcu))),
61106157 });
61116158 try a.end(f, writer);
61126159 }
......@@ -6115,7 +6162,8 @@ fn airArrayToSlice(f: *Function, inst: Air.Inst.Index) !CValue {
61156162}
61166163
61176164fn airFloatCast(f: *Function, inst: Air.Inst.Index) !CValue {
6118 const zcu = f.object.dg.zcu;
6165 const pt = f.object.dg.pt;
6166 const zcu = pt.zcu;
61196167 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
61206168
61216169 const inst_ty = f.typeOfIndex(inst);
......@@ -6165,7 +6213,8 @@ fn airFloatCast(f: *Function, inst: Air.Inst.Index) !CValue {
61656213}
61666214
61676215fn airIntFromPtr(f: *Function, inst: Air.Inst.Index) !CValue {
6168 const zcu = f.object.dg.zcu;
6216 const pt = f.object.dg.pt;
6217 const zcu = pt.zcu;
61696218 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
61706219
61716220 const operand = try f.resolveInst(un_op);
......@@ -6194,7 +6243,8 @@ fn airUnBuiltinCall(
61946243 operation: []const u8,
61956244 info: BuiltinInfo,
61966245) !CValue {
6197 const zcu = f.object.dg.zcu;
6246 const pt = f.object.dg.pt;
6247 const zcu = pt.zcu;
61986248
61996249 const operand = try f.resolveInst(operand_ref);
62006250 try reap(f, inst, &.{operand_ref});
......@@ -6237,7 +6287,8 @@ fn airBinBuiltinCall(
62376287 operation: []const u8,
62386288 info: BuiltinInfo,
62396289) !CValue {
6240 const zcu = f.object.dg.zcu;
6290 const pt = f.object.dg.pt;
6291 const zcu = pt.zcu;
62416292 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
62426293
62436294 const operand_ty = f.typeOf(bin_op.lhs);
......@@ -6292,7 +6343,8 @@ fn airCmpBuiltinCall(
62926343 operation: enum { cmp, operator },
62936344 info: BuiltinInfo,
62946345) !CValue {
6295 const zcu = f.object.dg.zcu;
6346 const pt = f.object.dg.pt;
6347 const zcu = pt.zcu;
62966348 const lhs = try f.resolveInst(data.lhs);
62976349 const rhs = try f.resolveInst(data.rhs);
62986350 try reap(f, inst, &.{ data.lhs, data.rhs });
......@@ -6333,7 +6385,7 @@ fn airCmpBuiltinCall(
63336385 try writer.writeByte(')');
63346386 if (!ref_ret) try writer.print("{s}{}", .{
63356387 compareOperatorC(operator),
6336 try f.fmtIntLiteral(try zcu.intValue(Type.i32, 0)),
6388 try f.fmtIntLiteral(try pt.intValue(Type.i32, 0)),
63376389 });
63386390 try writer.writeAll(";\n");
63396391 try v.end(f, inst, writer);
......@@ -6342,7 +6394,8 @@ fn airCmpBuiltinCall(
63426394}
63436395
63446396fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue {
6345 const zcu = f.object.dg.zcu;
6397 const pt = f.object.dg.pt;
6398 const zcu = pt.zcu;
63466399 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
63476400 const extra = f.air.extraData(Air.Cmpxchg, ty_pl.payload).data;
63486401 const inst_ty = f.typeOfIndex(inst);
......@@ -6358,7 +6411,7 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue
63586411 try reap(f, inst, &.{ extra.ptr, extra.expected_value, extra.new_value });
63596412
63606413 const repr_ty = if (ty.isRuntimeFloat())
6361 zcu.intType(.unsigned, @as(u16, @intCast(ty.abiSize(zcu) * 8))) catch unreachable
6414 pt.intType(.unsigned, @as(u16, @intCast(ty.abiSize(pt) * 8))) catch unreachable
63626415 else
63636416 ty;
63646417
......@@ -6448,7 +6501,8 @@ fn airCmpxchg(f: *Function, inst: Air.Inst.Index, flavor: [*:0]const u8) !CValue
64486501}
64496502
64506503fn airAtomicRmw(f: *Function, inst: Air.Inst.Index) !CValue {
6451 const zcu = f.object.dg.zcu;
6504 const pt = f.object.dg.pt;
6505 const zcu = pt.zcu;
64526506 const pl_op = f.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
64536507 const extra = f.air.extraData(Air.AtomicRmw, pl_op.payload).data;
64546508 const inst_ty = f.typeOfIndex(inst);
......@@ -6461,10 +6515,10 @@ fn airAtomicRmw(f: *Function, inst: Air.Inst.Index) !CValue {
64616515 const operand_mat = try Materialize.start(f, inst, ty, operand);
64626516 try reap(f, inst, &.{ pl_op.operand, extra.operand });
64636517
6464 const repr_bits = @as(u16, @intCast(ty.abiSize(zcu) * 8));
6518 const repr_bits = @as(u16, @intCast(ty.abiSize(pt) * 8));
64656519 const is_float = ty.isRuntimeFloat();
64666520 const is_128 = repr_bits == 128;
6467 const repr_ty = if (is_float) zcu.intType(.unsigned, repr_bits) catch unreachable else ty;
6521 const repr_ty = if (is_float) pt.intType(.unsigned, repr_bits) catch unreachable else ty;
64686522
64696523 const local = try f.allocLocal(inst, inst_ty);
64706524 try writer.print("zig_atomicrmw_{s}", .{toAtomicRmwSuffix(extra.op())});
......@@ -6503,7 +6557,8 @@ fn airAtomicRmw(f: *Function, inst: Air.Inst.Index) !CValue {
65036557}
65046558
65056559fn airAtomicLoad(f: *Function, inst: Air.Inst.Index) !CValue {
6506 const zcu = f.object.dg.zcu;
6560 const pt = f.object.dg.pt;
6561 const zcu = pt.zcu;
65076562 const atomic_load = f.air.instructions.items(.data)[@intFromEnum(inst)].atomic_load;
65086563 const ptr = try f.resolveInst(atomic_load.ptr);
65096564 try reap(f, inst, &.{atomic_load.ptr});
......@@ -6511,7 +6566,7 @@ fn airAtomicLoad(f: *Function, inst: Air.Inst.Index) !CValue {
65116566 const ty = ptr_ty.childType(zcu);
65126567
65136568 const repr_ty = if (ty.isRuntimeFloat())
6514 zcu.intType(.unsigned, @as(u16, @intCast(ty.abiSize(zcu) * 8))) catch unreachable
6569 pt.intType(.unsigned, @as(u16, @intCast(ty.abiSize(pt) * 8))) catch unreachable
65156570 else
65166571 ty;
65176572
......@@ -6539,7 +6594,8 @@ fn airAtomicLoad(f: *Function, inst: Air.Inst.Index) !CValue {
65396594}
65406595
65416596fn airAtomicStore(f: *Function, inst: Air.Inst.Index, order: [*:0]const u8) !CValue {
6542 const zcu = f.object.dg.zcu;
6597 const pt = f.object.dg.pt;
6598 const zcu = pt.zcu;
65436599 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
65446600 const ptr_ty = f.typeOf(bin_op.lhs);
65456601 const ty = ptr_ty.childType(zcu);
......@@ -6551,7 +6607,7 @@ fn airAtomicStore(f: *Function, inst: Air.Inst.Index, order: [*:0]const u8) !CVa
65516607 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
65526608
65536609 const repr_ty = if (ty.isRuntimeFloat())
6554 zcu.intType(.unsigned, @as(u16, @intCast(ty.abiSize(zcu) * 8))) catch unreachable
6610 pt.intType(.unsigned, @as(u16, @intCast(ty.abiSize(pt) * 8))) catch unreachable
65556611 else
65566612 ty;
65576613
......@@ -6574,7 +6630,8 @@ fn airAtomicStore(f: *Function, inst: Air.Inst.Index, order: [*:0]const u8) !CVa
65746630}
65756631
65766632fn writeSliceOrPtr(f: *Function, writer: anytype, ptr: CValue, ptr_ty: Type) !void {
6577 const zcu = f.object.dg.zcu;
6633 const pt = f.object.dg.pt;
6634 const zcu = pt.zcu;
65786635 if (ptr_ty.isSlice(zcu)) {
65796636 try f.writeCValueMember(writer, ptr, .{ .identifier = "ptr" });
65806637 } else {
......@@ -6583,14 +6640,15 @@ fn writeSliceOrPtr(f: *Function, writer: anytype, ptr: CValue, ptr_ty: Type) !vo
65836640}
65846641
65856642fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
6586 const zcu = f.object.dg.zcu;
6643 const pt = f.object.dg.pt;
6644 const zcu = pt.zcu;
65876645 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
65886646 const dest_ty = f.typeOf(bin_op.lhs);
65896647 const dest_slice = try f.resolveInst(bin_op.lhs);
65906648 const value = try f.resolveInst(bin_op.rhs);
65916649 const elem_ty = f.typeOf(bin_op.rhs);
6592 const elem_abi_size = elem_ty.abiSize(zcu);
6593 const val_is_undef = if (try f.air.value(bin_op.rhs, zcu)) |val| val.isUndefDeep(zcu) else false;
6650 const elem_abi_size = elem_ty.abiSize(pt);
6651 const val_is_undef = if (try f.air.value(bin_op.rhs, pt)) |val| val.isUndefDeep(zcu) else false;
65946652 const writer = f.object.writer();
65956653
65966654 if (val_is_undef) {
......@@ -6628,7 +6686,7 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
66286686 // For the assignment in this loop, the array pointer needs to get
66296687 // casted to a regular pointer, otherwise an error like this occurs:
66306688 // error: array type 'uint32_t[20]' (aka 'unsigned int[20]') is not assignable
6631 const elem_ptr_ty = try zcu.ptrType(.{
6689 const elem_ptr_ty = try pt.ptrType(.{
66326690 .child = elem_ty.toIntern(),
66336691 .flags = .{
66346692 .size = .C,
......@@ -6640,7 +6698,7 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
66406698 try writer.writeAll("for (");
66416699 try f.writeCValue(writer, index, .Other);
66426700 try writer.writeAll(" = ");
6643 try f.object.dg.renderValue(writer, try zcu.intValue(Type.usize, 0), .Initializer);
6701 try f.object.dg.renderValue(writer, try pt.intValue(Type.usize, 0), .Initializer);
66446702 try writer.writeAll("; ");
66456703 try f.writeCValue(writer, index, .Other);
66466704 try writer.writeAll(" != ");
......@@ -6705,7 +6763,8 @@ fn airMemset(f: *Function, inst: Air.Inst.Index, safety: bool) !CValue {
67056763}
67066764
67076765fn airMemcpy(f: *Function, inst: Air.Inst.Index) !CValue {
6708 const zcu = f.object.dg.zcu;
6766 const pt = f.object.dg.pt;
6767 const zcu = pt.zcu;
67096768 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
67106769 const dest_ptr = try f.resolveInst(bin_op.lhs);
67116770 const src_ptr = try f.resolveInst(bin_op.rhs);
......@@ -6733,10 +6792,11 @@ fn airMemcpy(f: *Function, inst: Air.Inst.Index) !CValue {
67336792}
67346793
67356794fn writeArrayLen(f: *Function, writer: ArrayListWriter, dest_ptr: CValue, dest_ty: Type) !void {
6736 const zcu = f.object.dg.zcu;
6795 const pt = f.object.dg.pt;
6796 const zcu = pt.zcu;
67376797 switch (dest_ty.ptrSize(zcu)) {
67386798 .One => try writer.print("{}", .{
6739 try f.fmtIntLiteral(try zcu.intValue(Type.usize, dest_ty.childType(zcu).arrayLen(zcu))),
6799 try f.fmtIntLiteral(try pt.intValue(Type.usize, dest_ty.childType(zcu).arrayLen(zcu))),
67406800 }),
67416801 .Many, .C => unreachable,
67426802 .Slice => try f.writeCValueMember(writer, dest_ptr, .{ .identifier = "len" }),
......@@ -6744,14 +6804,15 @@ fn writeArrayLen(f: *Function, writer: ArrayListWriter, dest_ptr: CValue, dest_t
67446804}
67456805
67466806fn airSetUnionTag(f: *Function, inst: Air.Inst.Index) !CValue {
6747 const zcu = f.object.dg.zcu;
6807 const pt = f.object.dg.pt;
6808 const zcu = pt.zcu;
67486809 const bin_op = f.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
67496810 const union_ptr = try f.resolveInst(bin_op.lhs);
67506811 const new_tag = try f.resolveInst(bin_op.rhs);
67516812 try reap(f, inst, &.{ bin_op.lhs, bin_op.rhs });
67526813
67536814 const union_ty = f.typeOf(bin_op.lhs).childType(zcu);
6754 const layout = union_ty.unionGetLayout(zcu);
6815 const layout = union_ty.unionGetLayout(pt);
67556816 if (layout.tag_size == 0) return .none;
67566817 const tag_ty = union_ty.unionTagTypeSafety(zcu).?;
67576818
......@@ -6765,14 +6826,14 @@ fn airSetUnionTag(f: *Function, inst: Air.Inst.Index) !CValue {
67656826}
67666827
67676828fn airGetUnionTag(f: *Function, inst: Air.Inst.Index) !CValue {
6768 const zcu = f.object.dg.zcu;
6829 const pt = f.object.dg.pt;
67696830 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
67706831
67716832 const operand = try f.resolveInst(ty_op.operand);
67726833 try reap(f, inst, &.{ty_op.operand});
67736834
67746835 const union_ty = f.typeOf(ty_op.operand);
6775 const layout = union_ty.unionGetLayout(zcu);
6836 const layout = union_ty.unionGetLayout(pt);
67766837 if (layout.tag_size == 0) return .none;
67776838
67786839 const inst_ty = f.typeOfIndex(inst);
......@@ -6787,7 +6848,8 @@ fn airGetUnionTag(f: *Function, inst: Air.Inst.Index) !CValue {
67876848}
67886849
67896850fn airTagName(f: *Function, inst: Air.Inst.Index) !CValue {
6790 const zcu = f.object.dg.zcu;
6851 const pt = f.object.dg.pt;
6852 const zcu = pt.zcu;
67916853 const un_op = f.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
67926854
67936855 const inst_ty = f.typeOfIndex(inst);
......@@ -6824,7 +6886,8 @@ fn airErrorName(f: *Function, inst: Air.Inst.Index) !CValue {
68246886}
68256887
68266888fn airSplat(f: *Function, inst: Air.Inst.Index) !CValue {
6827 const zcu = f.object.dg.zcu;
6889 const pt = f.object.dg.pt;
6890 const zcu = pt.zcu;
68286891 const ty_op = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
68296892
68306893 const operand = try f.resolveInst(ty_op.operand);
......@@ -6879,7 +6942,7 @@ fn airSelect(f: *Function, inst: Air.Inst.Index) !CValue {
68796942}
68806943
68816944fn airShuffle(f: *Function, inst: Air.Inst.Index) !CValue {
6882 const zcu = f.object.dg.zcu;
6945 const pt = f.object.dg.pt;
68836946 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
68846947 const extra = f.air.extraData(Air.Shuffle, ty_pl.payload).data;
68856948
......@@ -6895,11 +6958,11 @@ fn airShuffle(f: *Function, inst: Air.Inst.Index) !CValue {
68956958 for (0..extra.mask_len) |index| {
68966959 try f.writeCValue(writer, local, .Other);
68976960 try writer.writeByte('[');
6898 try f.object.dg.renderValue(writer, try zcu.intValue(Type.usize, index), .Other);
6961 try f.object.dg.renderValue(writer, try pt.intValue(Type.usize, index), .Other);
68996962 try writer.writeAll("] = ");
69006963
6901 const mask_elem = (try mask.elemValue(zcu, index)).toSignedInt(zcu);
6902 const src_val = try zcu.intValue(Type.usize, @as(u64, @intCast(mask_elem ^ mask_elem >> 63)));
6964 const mask_elem = (try mask.elemValue(pt, index)).toSignedInt(pt);
6965 const src_val = try pt.intValue(Type.usize, @as(u64, @intCast(mask_elem ^ mask_elem >> 63)));
69036966
69046967 try f.writeCValue(writer, if (mask_elem >= 0) lhs else rhs, .Other);
69056968 try writer.writeByte('[');
......@@ -6911,7 +6974,8 @@ fn airShuffle(f: *Function, inst: Air.Inst.Index) !CValue {
69116974}
69126975
69136976fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {
6914 const zcu = f.object.dg.zcu;
6977 const pt = f.object.dg.pt;
6978 const zcu = pt.zcu;
69156979 const reduce = f.air.instructions.items(.data)[@intFromEnum(inst)].reduce;
69166980
69176981 const scalar_ty = f.typeOfIndex(inst);
......@@ -6920,7 +6984,7 @@ fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {
69206984 const operand_ty = f.typeOf(reduce.operand);
69216985 const writer = f.object.writer();
69226986
6923 const use_operator = scalar_ty.bitSize(zcu) <= 64;
6987 const use_operator = scalar_ty.bitSize(pt) <= 64;
69246988 const op: union(enum) {
69256989 const Func = struct { operation: []const u8, info: BuiltinInfo = .none };
69266990 builtin: Func,
......@@ -6971,37 +7035,37 @@ fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {
69717035 try f.object.dg.renderValue(writer, switch (reduce.operation) {
69727036 .Or, .Xor => switch (scalar_ty.zigTypeTag(zcu)) {
69737037 .Bool => Value.false,
6974 .Int => try zcu.intValue(scalar_ty, 0),
7038 .Int => try pt.intValue(scalar_ty, 0),
69757039 else => unreachable,
69767040 },
69777041 .And => switch (scalar_ty.zigTypeTag(zcu)) {
69787042 .Bool => Value.true,
69797043 .Int => switch (scalar_ty.intInfo(zcu).signedness) {
6980 .unsigned => try scalar_ty.maxIntScalar(zcu, scalar_ty),
6981 .signed => try zcu.intValue(scalar_ty, -1),
7044 .unsigned => try scalar_ty.maxIntScalar(pt, scalar_ty),
7045 .signed => try pt.intValue(scalar_ty, -1),
69827046 },
69837047 else => unreachable,
69847048 },
69857049 .Add => switch (scalar_ty.zigTypeTag(zcu)) {
6986 .Int => try zcu.intValue(scalar_ty, 0),
6987 .Float => try zcu.floatValue(scalar_ty, 0.0),
7050 .Int => try pt.intValue(scalar_ty, 0),
7051 .Float => try pt.floatValue(scalar_ty, 0.0),
69887052 else => unreachable,
69897053 },
69907054 .Mul => switch (scalar_ty.zigTypeTag(zcu)) {
6991 .Int => try zcu.intValue(scalar_ty, 1),
6992 .Float => try zcu.floatValue(scalar_ty, 1.0),
7055 .Int => try pt.intValue(scalar_ty, 1),
7056 .Float => try pt.floatValue(scalar_ty, 1.0),
69937057 else => unreachable,
69947058 },
69957059 .Min => switch (scalar_ty.zigTypeTag(zcu)) {
69967060 .Bool => Value.true,
6997 .Int => try scalar_ty.maxIntScalar(zcu, scalar_ty),
6998 .Float => try zcu.floatValue(scalar_ty, std.math.nan(f128)),
7061 .Int => try scalar_ty.maxIntScalar(pt, scalar_ty),
7062 .Float => try pt.floatValue(scalar_ty, std.math.nan(f128)),
69997063 else => unreachable,
70007064 },
70017065 .Max => switch (scalar_ty.zigTypeTag(zcu)) {
70027066 .Bool => Value.false,
7003 .Int => try scalar_ty.minIntScalar(zcu, scalar_ty),
7004 .Float => try zcu.floatValue(scalar_ty, std.math.nan(f128)),
7067 .Int => try scalar_ty.minIntScalar(pt, scalar_ty),
7068 .Float => try pt.floatValue(scalar_ty, std.math.nan(f128)),
70057069 else => unreachable,
70067070 },
70077071 }, .Initializer);
......@@ -7046,7 +7110,8 @@ fn airReduce(f: *Function, inst: Air.Inst.Index) !CValue {
70467110}
70477111
70487112fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
7049 const zcu = f.object.dg.zcu;
7113 const pt = f.object.dg.pt;
7114 const zcu = pt.zcu;
70507115 const ip = &zcu.intern_pool;
70517116 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
70527117 const inst_ty = f.typeOfIndex(inst);
......@@ -7096,7 +7161,7 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
70967161 var field_it = loaded_struct.iterateRuntimeOrder(ip);
70977162 while (field_it.next()) |field_index| {
70987163 const field_ty = Type.fromInterned(loaded_struct.field_types.get(ip)[field_index]);
7099 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
7164 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
71007165
71017166 const a = try Assignment.start(f, writer, try f.ctypeFromType(field_ty, .complete));
71027167 try f.writeCValueMember(writer, local, if (loaded_struct.fieldName(ip, field_index).unwrap()) |field_name|
......@@ -7113,7 +7178,7 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
71137178 try writer.writeAll(" = ");
71147179 const int_info = inst_ty.intInfo(zcu);
71157180
7116 const bit_offset_ty = try zcu.intType(.unsigned, Type.smallestUnsignedBits(int_info.bits - 1));
7181 const bit_offset_ty = try pt.intType(.unsigned, Type.smallestUnsignedBits(int_info.bits - 1));
71177182
71187183 var bit_offset: u64 = 0;
71197184
......@@ -7121,7 +7186,7 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
71217186 for (0..elements.len) |field_index| {
71227187 if (inst_ty.structFieldIsComptime(field_index, zcu)) continue;
71237188 const field_ty = inst_ty.structFieldType(field_index, zcu);
7124 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
7189 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
71257190
71267191 if (!empty) {
71277192 try writer.writeAll("zig_or_");
......@@ -7134,7 +7199,7 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
71347199 for (resolved_elements, 0..) |element, field_index| {
71357200 if (inst_ty.structFieldIsComptime(field_index, zcu)) continue;
71367201 const field_ty = inst_ty.structFieldType(field_index, zcu);
7137 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
7202 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
71387203
71397204 if (!empty) try writer.writeAll(", ");
71407205 // TODO: Skip this entire shift if val is 0?
......@@ -7160,13 +7225,13 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
71607225 }
71617226
71627227 try writer.print(", {}", .{
7163 try f.fmtIntLiteral(try zcu.intValue(bit_offset_ty, bit_offset)),
7228 try f.fmtIntLiteral(try pt.intValue(bit_offset_ty, bit_offset)),
71647229 });
71657230 try f.object.dg.renderBuiltinInfo(writer, inst_ty, .bits);
71667231 try writer.writeByte(')');
71677232 if (!empty) try writer.writeByte(')');
71687233
7169 bit_offset += field_ty.bitSize(zcu);
7234 bit_offset += field_ty.bitSize(pt);
71707235 empty = false;
71717236 }
71727237 try writer.writeAll(";\n");
......@@ -7176,7 +7241,7 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
71767241 .anon_struct_type => |anon_struct_info| for (0..anon_struct_info.types.len) |field_index| {
71777242 if (anon_struct_info.values.get(ip)[field_index] != .none) continue;
71787243 const field_ty = Type.fromInterned(anon_struct_info.types.get(ip)[field_index]);
7179 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
7244 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
71807245
71817246 const a = try Assignment.start(f, writer, try f.ctypeFromType(field_ty, .complete));
71827247 try f.writeCValueMember(writer, local, if (anon_struct_info.fieldName(ip, field_index).unwrap()) |field_name|
......@@ -7194,7 +7259,8 @@ fn airAggregateInit(f: *Function, inst: Air.Inst.Index) !CValue {
71947259}
71957260
71967261fn airUnionInit(f: *Function, inst: Air.Inst.Index) !CValue {
7197 const zcu = f.object.dg.zcu;
7262 const pt = f.object.dg.pt;
7263 const zcu = pt.zcu;
71987264 const ip = &zcu.intern_pool;
71997265 const ty_pl = f.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
72007266 const extra = f.air.extraData(Air.UnionInit, ty_pl.payload).data;
......@@ -7211,15 +7277,15 @@ fn airUnionInit(f: *Function, inst: Air.Inst.Index) !CValue {
72117277 if (loaded_union.getLayout(ip) == .@"packed") return f.moveCValue(inst, union_ty, payload);
72127278
72137279 const field: CValue = if (union_ty.unionTagTypeSafety(zcu)) |tag_ty| field: {
7214 const layout = union_ty.unionGetLayout(zcu);
7280 const layout = union_ty.unionGetLayout(pt);
72157281 if (layout.tag_size != 0) {
72167282 const field_index = tag_ty.enumFieldIndex(field_name, zcu).?;
7217 const tag_val = try zcu.enumValueFieldIndex(tag_ty, field_index);
7283 const tag_val = try pt.enumValueFieldIndex(tag_ty, field_index);
72187284
72197285 const a = try Assignment.start(f, writer, try f.ctypeFromType(tag_ty, .complete));
72207286 try f.writeCValueMember(writer, local, .{ .identifier = "tag" });
72217287 try a.assign(f, writer);
7222 try writer.print("{}", .{try f.fmtIntLiteral(try tag_val.intFromEnum(tag_ty, zcu))});
7288 try writer.print("{}", .{try f.fmtIntLiteral(try tag_val.intFromEnum(tag_ty, pt))});
72237289 try a.end(f, writer);
72247290 }
72257291 break :field .{ .payload_identifier = field_name.toSlice(ip) };
......@@ -7234,7 +7300,8 @@ fn airUnionInit(f: *Function, inst: Air.Inst.Index) !CValue {
72347300}
72357301
72367302fn airPrefetch(f: *Function, inst: Air.Inst.Index) !CValue {
7237 const zcu = f.object.dg.zcu;
7303 const pt = f.object.dg.pt;
7304 const zcu = pt.zcu;
72387305 const prefetch = f.air.instructions.items(.data)[@intFromEnum(inst)].prefetch;
72397306
72407307 const ptr_ty = f.typeOf(prefetch.ptr);
......@@ -7291,7 +7358,8 @@ fn airWasmMemoryGrow(f: *Function, inst: Air.Inst.Index) !CValue {
72917358}
72927359
72937360fn airMulAdd(f: *Function, inst: Air.Inst.Index) !CValue {
7294 const zcu = f.object.dg.zcu;
7361 const pt = f.object.dg.pt;
7362 const zcu = pt.zcu;
72957363 const pl_op = f.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
72967364 const bin_op = f.air.extraData(Air.Bin, pl_op.payload).data;
72977365
......@@ -7326,7 +7394,8 @@ fn airMulAdd(f: *Function, inst: Air.Inst.Index) !CValue {
73267394}
73277395
73287396fn airCVaStart(f: *Function, inst: Air.Inst.Index) !CValue {
7329 const zcu = f.object.dg.zcu;
7397 const pt = f.object.dg.pt;
7398 const zcu = pt.zcu;
73307399 const inst_ty = f.typeOfIndex(inst);
73317400 const decl_index = f.object.dg.pass.decl;
73327401 const decl = zcu.declPtr(decl_index);
......@@ -7699,7 +7768,8 @@ fn formatIntLiteral(
76997768 options: std.fmt.FormatOptions,
77007769 writer: anytype,
77017770) @TypeOf(writer).Error!void {
7702 const zcu = data.dg.zcu;
7771 const pt = data.dg.pt;
7772 const zcu = pt.zcu;
77037773 const target = &data.dg.mod.resolved_target.result;
77047774 const ctype_pool = &data.dg.ctype_pool;
77057775
......@@ -7732,7 +7802,7 @@ fn formatIntLiteral(
77327802 };
77337803 undef_int.truncate(undef_int.toConst(), data.int_info.signedness, data.int_info.bits);
77347804 break :blk undef_int.toConst();
7735 } else data.val.toBigInt(&int_buf, zcu);
7805 } else data.val.toBigInt(&int_buf, pt);
77367806 assert(int.fitsInTwosComp(data.int_info.signedness, data.int_info.bits));
77377807
77387808 const c_bits: usize = @intCast(data.ctype.byteSize(ctype_pool, data.dg.mod) * 8);
......@@ -7866,7 +7936,7 @@ fn formatIntLiteral(
78667936 .int_info = c_limb_int_info,
78677937 .kind = data.kind,
78687938 .ctype = c_limb_ctype,
7869 .val = try zcu.intValue_big(Type.comptime_int, c_limb_mut.toConst()),
7939 .val = try pt.intValue_big(Type.comptime_int, c_limb_mut.toConst()),
78707940 }, fmt, options, writer);
78717941 }
78727942 }
......@@ -7940,17 +8010,18 @@ const Vectorize = struct {
79408010 index: CValue = .none,
79418011
79428012 pub fn start(f: *Function, inst: Air.Inst.Index, writer: anytype, ty: Type) !Vectorize {
7943 const zcu = f.object.dg.zcu;
8013 const pt = f.object.dg.pt;
8014 const zcu = pt.zcu;
79448015 return if (ty.zigTypeTag(zcu) == .Vector) index: {
79458016 const local = try f.allocLocal(inst, Type.usize);
79468017
79478018 try writer.writeAll("for (");
79488019 try f.writeCValue(writer, local, .Other);
7949 try writer.print(" = {d}; ", .{try f.fmtIntLiteral(try zcu.intValue(Type.usize, 0))});
8020 try writer.print(" = {d}; ", .{try f.fmtIntLiteral(try pt.intValue(Type.usize, 0))});
79508021 try f.writeCValue(writer, local, .Other);
7951 try writer.print(" < {d}; ", .{try f.fmtIntLiteral(try zcu.intValue(Type.usize, ty.vectorLen(zcu)))});
8022 try writer.print(" < {d}; ", .{try f.fmtIntLiteral(try pt.intValue(Type.usize, ty.vectorLen(zcu)))});
79528023 try f.writeCValue(writer, local, .Other);
7953 try writer.print(" += {d}) {{\n", .{try f.fmtIntLiteral(try zcu.intValue(Type.usize, 1))});
8024 try writer.print(" += {d}) {{\n", .{try f.fmtIntLiteral(try pt.intValue(Type.usize, 1))});
79548025 f.object.indent_writer.pushIndent();
79558026
79568027 break :index .{ .index = local };
......@@ -7974,10 +8045,10 @@ const Vectorize = struct {
79748045 }
79758046};
79768047
7977fn lowersToArray(ty: Type, zcu: *Zcu) bool {
7978 return switch (ty.zigTypeTag(zcu)) {
8048fn lowersToArray(ty: Type, pt: Zcu.PerThread) bool {
8049 return switch (ty.zigTypeTag(pt.zcu)) {
79798050 .Array, .Vector => return true,
7980 else => return ty.isAbiInt(zcu) and toCIntBits(@as(u32, @intCast(ty.bitSize(zcu)))) == null,
8051 else => return ty.isAbiInt(pt.zcu) and toCIntBits(@as(u32, @intCast(ty.bitSize(pt)))) == null,
79818052 };
79828053}
79838054
src/codegen/c/Type.zig+33-33
......@@ -1339,11 +1339,11 @@ pub const Pool = struct {
13391339 allocator: std.mem.Allocator,
13401340 scratch: *std.ArrayListUnmanaged(u32),
13411341 ty: Type,
1342 zcu: *Zcu,
1342 pt: Zcu.PerThread,
13431343 mod: *Module,
13441344 kind: Kind,
13451345 ) !CType {
1346 const ip = &zcu.intern_pool;
1346 const ip = &pt.zcu.intern_pool;
13471347 switch (ty.toIntern()) {
13481348 .u0_type,
13491349 .i0_type,
......@@ -1400,7 +1400,7 @@ pub const Pool = struct {
14001400 allocator,
14011401 scratch,
14021402 Type.fromInterned(ip.loadEnumType(ip_index).tag_ty),
1403 zcu,
1403 pt,
14041404 mod,
14051405 kind,
14061406 ),
......@@ -1409,7 +1409,7 @@ pub const Pool = struct {
14091409 .adhoc_inferred_error_set_type,
14101410 => return pool.fromIntInfo(allocator, .{
14111411 .signedness = .unsigned,
1412 .bits = zcu.errorSetBits(),
1412 .bits = pt.zcu.errorSetBits(),
14131413 }, mod, kind),
14141414 .manyptr_u8_type,
14151415 => return pool.getPointer(allocator, .{
......@@ -1492,13 +1492,13 @@ pub const Pool = struct {
14921492 allocator,
14931493 scratch,
14941494 Type.fromInterned(ptr_info.child),
1495 zcu,
1495 pt,
14961496 mod,
14971497 .forward,
14981498 ),
14991499 .alignas = AlignAs.fromAlignment(.{
15001500 .@"align" = ptr_info.flags.alignment,
1501 .abi = Type.fromInterned(ptr_info.child).abiAlignment(zcu),
1501 .abi = Type.fromInterned(ptr_info.child).abiAlignment(pt),
15021502 }),
15031503 };
15041504 break :elem_ctype if (elem.alignas.abiOrder().compare(.gte))
......@@ -1535,7 +1535,7 @@ pub const Pool = struct {
15351535 allocator,
15361536 scratch,
15371537 Type.fromInterned(ip.slicePtrType(ip_index)),
1538 zcu,
1538 pt,
15391539 mod,
15401540 kind,
15411541 ),
......@@ -1560,7 +1560,7 @@ pub const Pool = struct {
15601560 allocator,
15611561 scratch,
15621562 elem_type,
1563 zcu,
1563 pt,
15641564 mod,
15651565 kind.noParameter(),
15661566 );
......@@ -1574,7 +1574,7 @@ pub const Pool = struct {
15741574 .{
15751575 .name = .{ .index = .array },
15761576 .ctype = array_ctype,
1577 .alignas = AlignAs.fromAbiAlignment(elem_type.abiAlignment(zcu)),
1577 .alignas = AlignAs.fromAbiAlignment(elem_type.abiAlignment(pt)),
15781578 },
15791579 };
15801580 return pool.fromFields(allocator, .@"struct", &fields, kind);
......@@ -1586,7 +1586,7 @@ pub const Pool = struct {
15861586 allocator,
15871587 scratch,
15881588 elem_type,
1589 zcu,
1589 pt,
15901590 mod,
15911591 kind.noParameter(),
15921592 );
......@@ -1600,7 +1600,7 @@ pub const Pool = struct {
16001600 .{
16011601 .name = .{ .index = .array },
16021602 .ctype = vector_ctype,
1603 .alignas = AlignAs.fromAbiAlignment(elem_type.abiAlignment(zcu)),
1603 .alignas = AlignAs.fromAbiAlignment(elem_type.abiAlignment(pt)),
16041604 },
16051605 };
16061606 return pool.fromFields(allocator, .@"struct", &fields, kind);
......@@ -1611,7 +1611,7 @@ pub const Pool = struct {
16111611 allocator,
16121612 scratch,
16131613 Type.fromInterned(payload_type),
1614 zcu,
1614 pt,
16151615 mod,
16161616 kind.noParameter(),
16171617 );
......@@ -1635,7 +1635,7 @@ pub const Pool = struct {
16351635 .name = .{ .index = .payload },
16361636 .ctype = payload_ctype,
16371637 .alignas = AlignAs.fromAbiAlignment(
1638 Type.fromInterned(payload_type).abiAlignment(zcu),
1638 Type.fromInterned(payload_type).abiAlignment(pt),
16391639 ),
16401640 },
16411641 };
......@@ -1643,7 +1643,7 @@ pub const Pool = struct {
16431643 },
16441644 .anyframe_type => unreachable,
16451645 .error_union_type => |error_union_info| {
1646 const error_set_bits = zcu.errorSetBits();
1646 const error_set_bits = pt.zcu.errorSetBits();
16471647 const error_set_ctype = try pool.fromIntInfo(allocator, .{
16481648 .signedness = .unsigned,
16491649 .bits = error_set_bits,
......@@ -1654,7 +1654,7 @@ pub const Pool = struct {
16541654 allocator,
16551655 scratch,
16561656 payload_type,
1657 zcu,
1657 pt,
16581658 mod,
16591659 kind.noParameter(),
16601660 );
......@@ -1671,7 +1671,7 @@ pub const Pool = struct {
16711671 .{
16721672 .name = .{ .index = .payload },
16731673 .ctype = payload_ctype,
1674 .alignas = AlignAs.fromAbiAlignment(payload_type.abiAlignment(zcu)),
1674 .alignas = AlignAs.fromAbiAlignment(payload_type.abiAlignment(pt)),
16751675 },
16761676 };
16771677 return pool.fromFields(allocator, .@"struct", &fields, kind);
......@@ -1685,7 +1685,7 @@ pub const Pool = struct {
16851685 .tag = .@"struct",
16861686 .name = .{ .owner_decl = loaded_struct.decl.unwrap().? },
16871687 });
1688 if (kind.isForward()) return if (ty.hasRuntimeBitsIgnoreComptime(zcu))
1688 if (kind.isForward()) return if (ty.hasRuntimeBitsIgnoreComptime(pt))
16891689 fwd_decl
16901690 else
16911691 CType.void;
......@@ -1706,7 +1706,7 @@ pub const Pool = struct {
17061706 allocator,
17071707 scratch,
17081708 field_type,
1709 zcu,
1709 pt,
17101710 mod,
17111711 kind.noParameter(),
17121712 );
......@@ -1718,7 +1718,7 @@ pub const Pool = struct {
17181718 String.fromUnnamed(@intCast(field_index));
17191719 const field_alignas = AlignAs.fromAlignment(.{
17201720 .@"align" = loaded_struct.fieldAlign(ip, field_index),
1721 .abi = field_type.abiAlignment(zcu),
1721 .abi = field_type.abiAlignment(pt),
17221722 });
17231723 pool.addHashedExtraAssumeCapacityTo(scratch, &hasher, Field, .{
17241724 .name = field_name.index,
......@@ -1745,7 +1745,7 @@ pub const Pool = struct {
17451745 allocator,
17461746 scratch,
17471747 Type.fromInterned(loaded_struct.backingIntType(ip).*),
1748 zcu,
1748 pt,
17491749 mod,
17501750 kind,
17511751 ),
......@@ -1766,7 +1766,7 @@ pub const Pool = struct {
17661766 allocator,
17671767 scratch,
17681768 field_type,
1769 zcu,
1769 pt,
17701770 mod,
17711771 kind.noParameter(),
17721772 );
......@@ -1780,7 +1780,7 @@ pub const Pool = struct {
17801780 .name = field_name.index,
17811781 .ctype = field_ctype.index,
17821782 .flags = .{ .alignas = AlignAs.fromAbiAlignment(
1783 field_type.abiAlignment(zcu),
1783 field_type.abiAlignment(pt),
17841784 ) },
17851785 });
17861786 }
......@@ -1806,7 +1806,7 @@ pub const Pool = struct {
18061806 extra_index,
18071807 );
18081808 }
1809 const fwd_decl = try pool.fromType(allocator, scratch, ty, zcu, mod, .forward);
1809 const fwd_decl = try pool.fromType(allocator, scratch, ty, pt, mod, .forward);
18101810 try pool.ensureUnusedCapacity(allocator, 1);
18111811 const extra_index = try pool.addHashedExtra(allocator, &hasher, Aggregate, .{
18121812 .fwd_decl = fwd_decl.index,
......@@ -1824,7 +1824,7 @@ pub const Pool = struct {
18241824 .tag = if (has_tag) .@"struct" else .@"union",
18251825 .name = .{ .owner_decl = loaded_union.decl },
18261826 });
1827 if (kind.isForward()) return if (ty.hasRuntimeBitsIgnoreComptime(zcu))
1827 if (kind.isForward()) return if (ty.hasRuntimeBitsIgnoreComptime(pt))
18281828 fwd_decl
18291829 else
18301830 CType.void;
......@@ -1847,7 +1847,7 @@ pub const Pool = struct {
18471847 allocator,
18481848 scratch,
18491849 field_type,
1850 zcu,
1850 pt,
18511851 mod,
18521852 kind.noParameter(),
18531853 );
......@@ -1858,7 +1858,7 @@ pub const Pool = struct {
18581858 );
18591859 const field_alignas = AlignAs.fromAlignment(.{
18601860 .@"align" = loaded_union.fieldAlign(ip, field_index),
1861 .abi = field_type.abiAlignment(zcu),
1861 .abi = field_type.abiAlignment(pt),
18621862 });
18631863 pool.addHashedExtraAssumeCapacityTo(scratch, &hasher, Field, .{
18641864 .name = field_name.index,
......@@ -1895,7 +1895,7 @@ pub const Pool = struct {
18951895 allocator,
18961896 scratch,
18971897 tag_type,
1898 zcu,
1898 pt,
18991899 mod,
19001900 kind.noParameter(),
19011901 );
......@@ -1903,7 +1903,7 @@ pub const Pool = struct {
19031903 struct_fields[struct_fields_len] = .{
19041904 .name = .{ .index = .tag },
19051905 .ctype = tag_ctype,
1906 .alignas = AlignAs.fromAbiAlignment(tag_type.abiAlignment(zcu)),
1906 .alignas = AlignAs.fromAbiAlignment(tag_type.abiAlignment(pt)),
19071907 };
19081908 struct_fields_len += 1;
19091909 }
......@@ -1951,7 +1951,7 @@ pub const Pool = struct {
19511951 },
19521952 .@"packed" => return pool.fromIntInfo(allocator, .{
19531953 .signedness = .unsigned,
1954 .bits = @intCast(ty.bitSize(zcu)),
1954 .bits = @intCast(ty.bitSize(pt)),
19551955 }, mod, kind),
19561956 }
19571957 },
......@@ -1960,7 +1960,7 @@ pub const Pool = struct {
19601960 allocator,
19611961 scratch,
19621962 Type.fromInterned(ip.loadEnumType(ip_index).tag_ty),
1963 zcu,
1963 pt,
19641964 mod,
19651965 kind,
19661966 ),
......@@ -1975,7 +1975,7 @@ pub const Pool = struct {
19751975 allocator,
19761976 scratch,
19771977 return_type,
1978 zcu,
1978 pt,
19791979 mod,
19801980 kind.asParameter(),
19811981 ) else CType.void;
......@@ -1987,7 +1987,7 @@ pub const Pool = struct {
19871987 allocator,
19881988 scratch,
19891989 param_type,
1990 zcu,
1990 pt,
19911991 mod,
19921992 kind.asParameter(),
19931993 );
......@@ -2011,7 +2011,7 @@ pub const Pool = struct {
20112011 .inferred_error_set_type,
20122012 => return pool.fromIntInfo(allocator, .{
20132013 .signedness = .unsigned,
2014 .bits = zcu.errorSetBits(),
2014 .bits = pt.zcu.errorSetBits(),
20152015 }, mod, kind),
20162016
20172017 .undef,
src/codegen/llvm.zig+765-692
......@@ -15,8 +15,6 @@ const link = @import("../link.zig");
1515const Compilation = @import("../Compilation.zig");
1616const build_options = @import("build_options");
1717const Zcu = @import("../Zcu.zig");
18/// Deprecated.
19const Module = Zcu;
2018const InternPool = @import("../InternPool.zig");
2119const Package = @import("../Package.zig");
2220const Air = @import("../Air.zig");
......@@ -810,7 +808,7 @@ pub const Object = struct {
810808 gpa: Allocator,
811809 builder: Builder,
812810
813 module: *Module,
811 pt: Zcu.PerThread,
814812
815813 debug_compile_unit: Builder.Metadata,
816814
......@@ -820,7 +818,7 @@ pub const Object = struct {
820818 debug_enums: std.ArrayListUnmanaged(Builder.Metadata),
821819 debug_globals: std.ArrayListUnmanaged(Builder.Metadata),
822820
823 debug_file_map: std.AutoHashMapUnmanaged(*const Module.File, Builder.Metadata),
821 debug_file_map: std.AutoHashMapUnmanaged(*const Zcu.File, Builder.Metadata),
824822 debug_type_map: std.AutoHashMapUnmanaged(Type, Builder.Metadata),
825823
826824 debug_unresolved_namespace_scopes: std.AutoArrayHashMapUnmanaged(InternPool.NamespaceIndex, Builder.Metadata),
......@@ -992,7 +990,10 @@ pub const Object = struct {
992990 obj.* = .{
993991 .gpa = gpa,
994992 .builder = builder,
995 .module = comp.module.?,
993 .pt = .{
994 .zcu = comp.module.?,
995 .tid = .main,
996 },
996997 .debug_compile_unit = debug_compile_unit,
997998 .debug_enums_fwd_ref = debug_enums_fwd_ref,
998999 .debug_globals_fwd_ref = debug_globals_fwd_ref,
......@@ -1033,7 +1034,8 @@ pub const Object = struct {
10331034 // If o.error_name_table is null, then it was not referenced by any instructions.
10341035 if (o.error_name_table == .none) return;
10351036
1036 const mod = o.module;
1037 const pt = o.pt;
1038 const mod = pt.zcu;
10371039
10381040 const error_name_list = mod.global_error_set.keys();
10391041 const llvm_errors = try mod.gpa.alloc(Builder.Constant, error_name_list.len);
......@@ -1072,7 +1074,7 @@ pub const Object = struct {
10721074 table_variable_index.setMutability(.constant, &o.builder);
10731075 table_variable_index.setUnnamedAddr(.unnamed_addr, &o.builder);
10741076 table_variable_index.setAlignment(
1075 slice_ty.abiAlignment(mod).toLlvm(),
1077 slice_ty.abiAlignment(pt).toLlvm(),
10761078 &o.builder,
10771079 );
10781080
......@@ -1083,8 +1085,7 @@ pub const Object = struct {
10831085 // If there is no such function in the module, it means the source code does not need it.
10841086 const name = o.builder.strtabStringIfExists(lt_errors_fn_name) orelse return;
10851087 const llvm_fn = o.builder.getGlobal(name) orelse return;
1086 const mod = o.module;
1087 const errors_len = mod.global_error_set.count();
1088 const errors_len = o.pt.zcu.global_error_set.count();
10881089
10891090 var wip = try Builder.WipFunction.init(&o.builder, .{
10901091 .function = llvm_fn.ptrConst(&o.builder).kind.function,
......@@ -1106,10 +1107,8 @@ pub const Object = struct {
11061107 }
11071108
11081109 fn genModuleLevelAssembly(object: *Object) !void {
1109 const mod = object.module;
1110
11111110 const writer = object.builder.setModuleAsm();
1112 for (mod.global_assembly.values()) |assembly| {
1111 for (object.pt.zcu.global_assembly.values()) |assembly| {
11131112 try writer.print("{s}\n", .{assembly});
11141113 }
11151114 try object.builder.finishModuleAsm();
......@@ -1131,6 +1130,9 @@ pub const Object = struct {
11311130 };
11321131
11331132 pub fn emit(self: *Object, options: EmitOptions) !void {
1133 const zcu = self.pt.zcu;
1134 const comp = zcu.comp;
1135
11341136 {
11351137 try self.genErrorNameTable();
11361138 try self.genCmpLtErrorsLenFunction();
......@@ -1143,8 +1145,8 @@ pub const Object = struct {
11431145 const namespace_index = self.debug_unresolved_namespace_scopes.keys()[i];
11441146 const fwd_ref = self.debug_unresolved_namespace_scopes.values()[i];
11451147
1146 const namespace = self.module.namespacePtr(namespace_index);
1147 const debug_type = try self.lowerDebugType(namespace.getType(self.module));
1148 const namespace = zcu.namespacePtr(namespace_index);
1149 const debug_type = try self.lowerDebugType(namespace.getType(zcu));
11481150
11491151 self.builder.debugForwardReferenceSetType(fwd_ref, debug_type);
11501152 }
......@@ -1206,12 +1208,12 @@ pub const Object = struct {
12061208 try file.writeAll(ptr[0..(bitcode.len * 4)]);
12071209 }
12081210
1209 if (!build_options.have_llvm or !self.module.comp.config.use_lib_llvm) {
1211 if (!build_options.have_llvm or !comp.config.use_lib_llvm) {
12101212 log.err("emitting without libllvm not implemented", .{});
12111213 return error.FailedToEmit;
12121214 }
12131215
1214 initializeLLVMTarget(self.module.comp.root_mod.resolved_target.result.cpu.arch);
1216 initializeLLVMTarget(comp.root_mod.resolved_target.result.cpu.arch);
12151217
12161218 const context: *llvm.Context = llvm.Context.create();
12171219 errdefer context.dispose();
......@@ -1247,8 +1249,8 @@ pub const Object = struct {
12471249 @panic("Invalid LLVM triple");
12481250 }
12491251
1250 const optimize_mode = self.module.comp.root_mod.optimize_mode;
1251 const pic = self.module.comp.root_mod.pic;
1252 const optimize_mode = comp.root_mod.optimize_mode;
1253 const pic = comp.root_mod.pic;
12521254
12531255 const opt_level: llvm.CodeGenOptLevel = if (optimize_mode == .Debug)
12541256 .None
......@@ -1257,12 +1259,12 @@ pub const Object = struct {
12571259
12581260 const reloc_mode: llvm.RelocMode = if (pic)
12591261 .PIC
1260 else if (self.module.comp.config.link_mode == .dynamic)
1262 else if (comp.config.link_mode == .dynamic)
12611263 llvm.RelocMode.DynamicNoPIC
12621264 else
12631265 .Static;
12641266
1265 const code_model: llvm.CodeModel = switch (self.module.comp.root_mod.code_model) {
1267 const code_model: llvm.CodeModel = switch (comp.root_mod.code_model) {
12661268 .default => .Default,
12671269 .tiny => .Tiny,
12681270 .small => .Small,
......@@ -1277,24 +1279,24 @@ pub const Object = struct {
12771279 var target_machine = llvm.TargetMachine.create(
12781280 target,
12791281 target_triple_sentinel,
1280 if (self.module.comp.root_mod.resolved_target.result.cpu.model.llvm_name) |s| s.ptr else null,
1281 self.module.comp.root_mod.resolved_target.llvm_cpu_features.?,
1282 if (comp.root_mod.resolved_target.result.cpu.model.llvm_name) |s| s.ptr else null,
1283 comp.root_mod.resolved_target.llvm_cpu_features.?,
12821284 opt_level,
12831285 reloc_mode,
12841286 code_model,
1285 self.module.comp.function_sections,
1286 self.module.comp.data_sections,
1287 comp.function_sections,
1288 comp.data_sections,
12871289 float_abi,
1288 if (target_util.llvmMachineAbi(self.module.comp.root_mod.resolved_target.result)) |s| s.ptr else null,
1290 if (target_util.llvmMachineAbi(comp.root_mod.resolved_target.result)) |s| s.ptr else null,
12891291 );
12901292 errdefer target_machine.dispose();
12911293
12921294 if (pic) module.setModulePICLevel();
1293 if (self.module.comp.config.pie) module.setModulePIELevel();
1295 if (comp.config.pie) module.setModulePIELevel();
12941296 if (code_model != .Default) module.setModuleCodeModel(code_model);
12951297
1296 if (self.module.comp.llvm_opt_bisect_limit >= 0) {
1297 context.setOptBisectLimit(self.module.comp.llvm_opt_bisect_limit);
1298 if (comp.llvm_opt_bisect_limit >= 0) {
1299 context.setOptBisectLimit(comp.llvm_opt_bisect_limit);
12981300 }
12991301
13001302 // Unfortunately, LLVM shits the bed when we ask for both binary and assembly.
......@@ -1352,11 +1354,13 @@ pub const Object = struct {
13521354
13531355 pub fn updateFunc(
13541356 o: *Object,
1355 zcu: *Module,
1357 pt: Zcu.PerThread,
13561358 func_index: InternPool.Index,
13571359 air: Air,
13581360 liveness: Liveness,
13591361 ) !void {
1362 assert(std.meta.eql(pt, o.pt));
1363 const zcu = pt.zcu;
13601364 const comp = zcu.comp;
13611365 const func = zcu.funcInfo(func_index);
13621366 const decl_index = func.owner_decl;
......@@ -1437,7 +1441,7 @@ pub const Object = struct {
14371441 var llvm_arg_i: u32 = 0;
14381442
14391443 // This gets the LLVM values from the function and stores them in `dg.args`.
1440 const sret = firstParamSRet(fn_info, zcu, target);
1444 const sret = firstParamSRet(fn_info, pt, target);
14411445 const ret_ptr: Builder.Value = if (sret) param: {
14421446 const param = wip.arg(llvm_arg_i);
14431447 llvm_arg_i += 1;
......@@ -1478,8 +1482,8 @@ pub const Object = struct {
14781482 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[param_index]);
14791483 const param = wip.arg(llvm_arg_i);
14801484
1481 if (isByRef(param_ty, zcu)) {
1482 const alignment = param_ty.abiAlignment(zcu).toLlvm();
1485 if (isByRef(param_ty, pt)) {
1486 const alignment = param_ty.abiAlignment(pt).toLlvm();
14831487 const param_llvm_ty = param.typeOfWip(&wip);
14841488 const arg_ptr = try buildAllocaInner(&wip, param_llvm_ty, alignment, target);
14851489 _ = try wip.store(.normal, param, arg_ptr, alignment);
......@@ -1495,12 +1499,12 @@ pub const Object = struct {
14951499 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[it.zig_index - 1]);
14961500 const param_llvm_ty = try o.lowerType(param_ty);
14971501 const param = wip.arg(llvm_arg_i);
1498 const alignment = param_ty.abiAlignment(zcu).toLlvm();
1502 const alignment = param_ty.abiAlignment(pt).toLlvm();
14991503
15001504 try o.addByRefParamAttrs(&attributes, llvm_arg_i, alignment, it.byval_attr, param_llvm_ty);
15011505 llvm_arg_i += 1;
15021506
1503 if (isByRef(param_ty, zcu)) {
1507 if (isByRef(param_ty, pt)) {
15041508 args.appendAssumeCapacity(param);
15051509 } else {
15061510 args.appendAssumeCapacity(try wip.load(.normal, param_llvm_ty, param, alignment, ""));
......@@ -1510,12 +1514,12 @@ pub const Object = struct {
15101514 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[it.zig_index - 1]);
15111515 const param_llvm_ty = try o.lowerType(param_ty);
15121516 const param = wip.arg(llvm_arg_i);
1513 const alignment = param_ty.abiAlignment(zcu).toLlvm();
1517 const alignment = param_ty.abiAlignment(pt).toLlvm();
15141518
15151519 try attributes.addParamAttr(llvm_arg_i, .noundef, &o.builder);
15161520 llvm_arg_i += 1;
15171521
1518 if (isByRef(param_ty, zcu)) {
1522 if (isByRef(param_ty, pt)) {
15191523 args.appendAssumeCapacity(param);
15201524 } else {
15211525 args.appendAssumeCapacity(try wip.load(.normal, param_llvm_ty, param, alignment, ""));
......@@ -1528,11 +1532,11 @@ pub const Object = struct {
15281532 llvm_arg_i += 1;
15291533
15301534 const param_llvm_ty = try o.lowerType(param_ty);
1531 const alignment = param_ty.abiAlignment(zcu).toLlvm();
1535 const alignment = param_ty.abiAlignment(pt).toLlvm();
15321536 const arg_ptr = try buildAllocaInner(&wip, param_llvm_ty, alignment, target);
15331537 _ = try wip.store(.normal, param, arg_ptr, alignment);
15341538
1535 args.appendAssumeCapacity(if (isByRef(param_ty, zcu))
1539 args.appendAssumeCapacity(if (isByRef(param_ty, pt))
15361540 arg_ptr
15371541 else
15381542 try wip.load(.normal, param_llvm_ty, arg_ptr, alignment, ""));
......@@ -1556,7 +1560,7 @@ pub const Object = struct {
15561560 const elem_align = (if (ptr_info.flags.alignment != .none)
15571561 @as(InternPool.Alignment, ptr_info.flags.alignment)
15581562 else
1559 Type.fromInterned(ptr_info.child).abiAlignment(zcu).max(.@"1")).toLlvm();
1563 Type.fromInterned(ptr_info.child).abiAlignment(pt).max(.@"1")).toLlvm();
15601564 try attributes.addParamAttr(llvm_arg_i, .{ .@"align" = elem_align }, &o.builder);
15611565 const ptr_param = wip.arg(llvm_arg_i);
15621566 llvm_arg_i += 1;
......@@ -1573,7 +1577,7 @@ pub const Object = struct {
15731577 const field_types = it.types_buffer[0..it.types_len];
15741578 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[it.zig_index - 1]);
15751579 const param_llvm_ty = try o.lowerType(param_ty);
1576 const param_alignment = param_ty.abiAlignment(zcu).toLlvm();
1580 const param_alignment = param_ty.abiAlignment(pt).toLlvm();
15771581 const arg_ptr = try buildAllocaInner(&wip, param_llvm_ty, param_alignment, target);
15781582 const llvm_ty = try o.builder.structType(.normal, field_types);
15791583 for (0..field_types.len) |field_i| {
......@@ -1585,7 +1589,7 @@ pub const Object = struct {
15851589 _ = try wip.store(.normal, param, field_ptr, alignment);
15861590 }
15871591
1588 const is_by_ref = isByRef(param_ty, zcu);
1592 const is_by_ref = isByRef(param_ty, pt);
15891593 args.appendAssumeCapacity(if (is_by_ref)
15901594 arg_ptr
15911595 else
......@@ -1603,11 +1607,11 @@ pub const Object = struct {
16031607 const param = wip.arg(llvm_arg_i);
16041608 llvm_arg_i += 1;
16051609
1606 const alignment = param_ty.abiAlignment(zcu).toLlvm();
1610 const alignment = param_ty.abiAlignment(pt).toLlvm();
16071611 const arg_ptr = try buildAllocaInner(&wip, param_llvm_ty, alignment, target);
16081612 _ = try wip.store(.normal, param, arg_ptr, alignment);
16091613
1610 args.appendAssumeCapacity(if (isByRef(param_ty, zcu))
1614 args.appendAssumeCapacity(if (isByRef(param_ty, pt))
16111615 arg_ptr
16121616 else
16131617 try wip.load(.normal, param_llvm_ty, arg_ptr, alignment, ""));
......@@ -1618,11 +1622,11 @@ pub const Object = struct {
16181622 const param = wip.arg(llvm_arg_i);
16191623 llvm_arg_i += 1;
16201624
1621 const alignment = param_ty.abiAlignment(zcu).toLlvm();
1625 const alignment = param_ty.abiAlignment(pt).toLlvm();
16221626 const arg_ptr = try buildAllocaInner(&wip, param_llvm_ty, alignment, target);
16231627 _ = try wip.store(.normal, param, arg_ptr, alignment);
16241628
1625 args.appendAssumeCapacity(if (isByRef(param_ty, zcu))
1629 args.appendAssumeCapacity(if (isByRef(param_ty, pt))
16261630 arg_ptr
16271631 else
16281632 try wip.load(.normal, param_llvm_ty, arg_ptr, alignment, ""));
......@@ -1700,8 +1704,9 @@ pub const Object = struct {
17001704 try fg.wip.finish();
17011705 }
17021706
1703 pub fn updateDecl(self: *Object, module: *Module, decl_index: InternPool.DeclIndex) !void {
1704 const decl = module.declPtr(decl_index);
1707 pub fn updateDecl(self: *Object, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !void {
1708 assert(std.meta.eql(pt, self.pt));
1709 const decl = pt.zcu.declPtr(decl_index);
17051710 var dg: DeclGen = .{
17061711 .object = self,
17071712 .decl = decl,
......@@ -1711,7 +1716,7 @@ pub const Object = struct {
17111716 dg.genDecl() catch |err| switch (err) {
17121717 error.CodegenFail => {
17131718 decl.analysis = .codegen_failure;
1714 try module.failed_analysis.put(module.gpa, InternPool.AnalUnit.wrap(.{ .decl = decl_index }), dg.err_msg.?);
1719 try pt.zcu.failed_analysis.put(pt.zcu.gpa, InternPool.AnalUnit.wrap(.{ .decl = decl_index }), dg.err_msg.?);
17151720 dg.err_msg = null;
17161721 return;
17171722 },
......@@ -1721,10 +1726,12 @@ pub const Object = struct {
17211726
17221727 pub fn updateExports(
17231728 self: *Object,
1724 zcu: *Zcu,
1725 exported: Module.Exported,
1729 pt: Zcu.PerThread,
1730 exported: Zcu.Exported,
17261731 export_indices: []const u32,
17271732 ) link.File.UpdateExportsError!void {
1733 assert(std.meta.eql(pt, self.pt));
1734 const zcu = pt.zcu;
17281735 const decl_index = switch (exported) {
17291736 .decl_index => |i| i,
17301737 .value => |val| return updateExportedValue(self, zcu, val, export_indices),
......@@ -1737,7 +1744,7 @@ pub const Object = struct {
17371744 if (export_indices.len != 0) {
17381745 return updateExportedGlobal(self, zcu, global_index, export_indices);
17391746 } else {
1740 const fqn = try self.builder.strtabString((try decl.fullyQualifiedName(zcu)).toSlice(ip));
1747 const fqn = try self.builder.strtabString((try decl.fullyQualifiedName(pt)).toSlice(ip));
17411748 try global_index.rename(fqn, &self.builder);
17421749 global_index.setLinkage(.internal, &self.builder);
17431750 if (comp.config.dll_export_fns)
......@@ -1748,7 +1755,7 @@ pub const Object = struct {
17481755
17491756 fn updateExportedValue(
17501757 o: *Object,
1751 mod: *Module,
1758 mod: *Zcu,
17521759 exported_value: InternPool.Index,
17531760 export_indices: []const u32,
17541761 ) link.File.UpdateExportsError!void {
......@@ -1783,7 +1790,7 @@ pub const Object = struct {
17831790
17841791 fn updateExportedGlobal(
17851792 o: *Object,
1786 mod: *Module,
1793 mod: *Zcu,
17871794 global_index: Builder.Global.Index,
17881795 export_indices: []const u32,
17891796 ) link.File.UpdateExportsError!void {
......@@ -1879,7 +1886,7 @@ pub const Object = struct {
18791886 global.delete(&self.builder);
18801887 }
18811888
1882 fn getDebugFile(o: *Object, file: *const Module.File) Allocator.Error!Builder.Metadata {
1889 fn getDebugFile(o: *Object, file: *const Zcu.File) Allocator.Error!Builder.Metadata {
18831890 const gpa = o.gpa;
18841891 const gop = try o.debug_file_map.getOrPut(gpa, file);
18851892 errdefer assert(o.debug_file_map.remove(file));
......@@ -1909,7 +1916,8 @@ pub const Object = struct {
19091916
19101917 const gpa = o.gpa;
19111918 const target = o.target;
1912 const zcu = o.module;
1919 const pt = o.pt;
1920 const zcu = pt.zcu;
19131921 const ip = &zcu.intern_pool;
19141922
19151923 if (o.debug_type_map.get(ty)) |debug_type| return debug_type;
......@@ -1931,7 +1939,7 @@ pub const Object = struct {
19311939 const name = try o.allocTypeName(ty);
19321940 defer gpa.free(name);
19331941 const builder_name = try o.builder.metadataString(name);
1934 const debug_bits = ty.abiSize(zcu) * 8; // lldb cannot handle non-byte sized types
1942 const debug_bits = ty.abiSize(pt) * 8; // lldb cannot handle non-byte sized types
19351943 const debug_int_type = switch (info.signedness) {
19361944 .signed => try o.builder.debugSignedType(builder_name, debug_bits),
19371945 .unsigned => try o.builder.debugUnsignedType(builder_name, debug_bits),
......@@ -1941,9 +1949,9 @@ pub const Object = struct {
19411949 },
19421950 .Enum => {
19431951 const owner_decl_index = ty.getOwnerDecl(zcu);
1944 const owner_decl = o.module.declPtr(owner_decl_index);
1952 const owner_decl = zcu.declPtr(owner_decl_index);
19451953
1946 if (!ty.hasRuntimeBitsIgnoreComptime(zcu)) {
1954 if (!ty.hasRuntimeBitsIgnoreComptime(pt)) {
19471955 const debug_enum_type = try o.makeEmptyNamespaceDebugType(owner_decl_index);
19481956 try o.debug_type_map.put(gpa, ty, debug_enum_type);
19491957 return debug_enum_type;
......@@ -1961,7 +1969,7 @@ pub const Object = struct {
19611969 for (enum_type.names.get(ip), 0..) |field_name_ip, i| {
19621970 var bigint_space: Value.BigIntSpace = undefined;
19631971 const bigint = if (enum_type.values.len != 0)
1964 Value.fromInterned(enum_type.values.get(ip)[i]).toBigInt(&bigint_space, zcu)
1972 Value.fromInterned(enum_type.values.get(ip)[i]).toBigInt(&bigint_space, pt)
19651973 else
19661974 std.math.big.int.Mutable.init(&bigint_space.limbs, i).toConst();
19671975
......@@ -1986,8 +1994,8 @@ pub const Object = struct {
19861994 scope,
19871995 owner_decl.typeSrcLine(zcu) + 1, // Line
19881996 try o.lowerDebugType(int_ty),
1989 ty.abiSize(zcu) * 8,
1990 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
1997 ty.abiSize(pt) * 8,
1998 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
19911999 try o.builder.debugTuple(enumerators),
19922000 );
19932001
......@@ -2027,10 +2035,10 @@ pub const Object = struct {
20272035 ptr_info.flags.is_const or
20282036 ptr_info.flags.is_volatile or
20292037 ptr_info.flags.size == .Many or ptr_info.flags.size == .C or
2030 !Type.fromInterned(ptr_info.child).hasRuntimeBitsIgnoreComptime(zcu))
2038 !Type.fromInterned(ptr_info.child).hasRuntimeBitsIgnoreComptime(pt))
20312039 {
2032 const bland_ptr_ty = try zcu.ptrType(.{
2033 .child = if (!Type.fromInterned(ptr_info.child).hasRuntimeBitsIgnoreComptime(zcu))
2040 const bland_ptr_ty = try pt.ptrType(.{
2041 .child = if (!Type.fromInterned(ptr_info.child).hasRuntimeBitsIgnoreComptime(pt))
20342042 .anyopaque_type
20352043 else
20362044 ptr_info.child,
......@@ -2060,10 +2068,10 @@ pub const Object = struct {
20602068 defer gpa.free(name);
20612069 const line = 0;
20622070
2063 const ptr_size = ptr_ty.abiSize(zcu);
2064 const ptr_align = ptr_ty.abiAlignment(zcu);
2065 const len_size = len_ty.abiSize(zcu);
2066 const len_align = len_ty.abiAlignment(zcu);
2071 const ptr_size = ptr_ty.abiSize(pt);
2072 const ptr_align = ptr_ty.abiAlignment(pt);
2073 const len_size = len_ty.abiSize(pt);
2074 const len_align = len_ty.abiAlignment(pt);
20672075
20682076 const len_offset = len_align.forward(ptr_size);
20692077
......@@ -2095,8 +2103,8 @@ pub const Object = struct {
20952103 o.debug_compile_unit, // Scope
20962104 line,
20972105 .none, // Underlying type
2098 ty.abiSize(zcu) * 8,
2099 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2106 ty.abiSize(pt) * 8,
2107 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
21002108 try o.builder.debugTuple(&.{
21012109 debug_ptr_type,
21022110 debug_len_type,
......@@ -2124,7 +2132,7 @@ pub const Object = struct {
21242132 0, // Line
21252133 debug_elem_ty,
21262134 target.ptrBitWidth(),
2127 (ty.ptrAlignment(zcu).toByteUnits() orelse 0) * 8,
2135 (ty.ptrAlignment(pt).toByteUnits() orelse 0) * 8,
21282136 0, // Offset
21292137 );
21302138
......@@ -2149,7 +2157,7 @@ pub const Object = struct {
21492157 const name = try o.allocTypeName(ty);
21502158 defer gpa.free(name);
21512159 const owner_decl_index = ty.getOwnerDecl(zcu);
2152 const owner_decl = o.module.declPtr(owner_decl_index);
2160 const owner_decl = zcu.declPtr(owner_decl_index);
21532161 const file_scope = zcu.namespacePtr(owner_decl.src_namespace).fileScope(zcu);
21542162 const debug_opaque_type = try o.builder.debugStructType(
21552163 try o.builder.metadataString(name),
......@@ -2171,8 +2179,8 @@ pub const Object = struct {
21712179 .none, // Scope
21722180 0, // Line
21732181 try o.lowerDebugType(ty.childType(zcu)),
2174 ty.abiSize(zcu) * 8,
2175 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2182 ty.abiSize(pt) * 8,
2183 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
21762184 try o.builder.debugTuple(&.{
21772185 try o.builder.debugSubrange(
21782186 try o.builder.debugConstant(try o.builder.intConst(.i64, 0)),
......@@ -2214,8 +2222,8 @@ pub const Object = struct {
22142222 .none, // Scope
22152223 0, // Line
22162224 debug_elem_type,
2217 ty.abiSize(zcu) * 8,
2218 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2225 ty.abiSize(pt) * 8,
2226 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
22192227 try o.builder.debugTuple(&.{
22202228 try o.builder.debugSubrange(
22212229 try o.builder.debugConstant(try o.builder.intConst(.i64, 0)),
......@@ -2231,7 +2239,7 @@ pub const Object = struct {
22312239 const name = try o.allocTypeName(ty);
22322240 defer gpa.free(name);
22332241 const child_ty = ty.optionalChild(zcu);
2234 if (!child_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
2242 if (!child_ty.hasRuntimeBitsIgnoreComptime(pt)) {
22352243 const debug_bool_type = try o.builder.debugBoolType(
22362244 try o.builder.metadataString(name),
22372245 8,
......@@ -2258,10 +2266,10 @@ pub const Object = struct {
22582266 }
22592267
22602268 const non_null_ty = Type.u8;
2261 const payload_size = child_ty.abiSize(zcu);
2262 const payload_align = child_ty.abiAlignment(zcu);
2263 const non_null_size = non_null_ty.abiSize(zcu);
2264 const non_null_align = non_null_ty.abiAlignment(zcu);
2269 const payload_size = child_ty.abiSize(pt);
2270 const payload_align = child_ty.abiAlignment(pt);
2271 const non_null_size = non_null_ty.abiSize(pt);
2272 const non_null_align = non_null_ty.abiAlignment(pt);
22652273 const non_null_offset = non_null_align.forward(payload_size);
22662274
22672275 const debug_data_type = try o.builder.debugMemberType(
......@@ -2292,8 +2300,8 @@ pub const Object = struct {
22922300 o.debug_compile_unit, // Scope
22932301 0, // Line
22942302 .none, // Underlying type
2295 ty.abiSize(zcu) * 8,
2296 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2303 ty.abiSize(pt) * 8,
2304 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
22972305 try o.builder.debugTuple(&.{
22982306 debug_data_type,
22992307 debug_some_type,
......@@ -2310,7 +2318,7 @@ pub const Object = struct {
23102318 },
23112319 .ErrorUnion => {
23122320 const payload_ty = ty.errorUnionPayload(zcu);
2313 if (!payload_ty.hasRuntimeBitsIgnoreComptime(zcu)) {
2321 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
23142322 // TODO: Maybe remove?
23152323 const debug_error_union_type = try o.lowerDebugType(Type.anyerror);
23162324 try o.debug_type_map.put(gpa, ty, debug_error_union_type);
......@@ -2320,10 +2328,10 @@ pub const Object = struct {
23202328 const name = try o.allocTypeName(ty);
23212329 defer gpa.free(name);
23222330
2323 const error_size = Type.anyerror.abiSize(zcu);
2324 const error_align = Type.anyerror.abiAlignment(zcu);
2325 const payload_size = payload_ty.abiSize(zcu);
2326 const payload_align = payload_ty.abiAlignment(zcu);
2331 const error_size = Type.anyerror.abiSize(pt);
2332 const error_align = Type.anyerror.abiAlignment(pt);
2333 const payload_size = payload_ty.abiSize(pt);
2334 const payload_align = payload_ty.abiAlignment(pt);
23272335
23282336 var error_index: u32 = undefined;
23292337 var payload_index: u32 = undefined;
......@@ -2371,8 +2379,8 @@ pub const Object = struct {
23712379 o.debug_compile_unit, // Sope
23722380 0, // Line
23732381 .none, // Underlying type
2374 ty.abiSize(zcu) * 8,
2375 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2382 ty.abiSize(pt) * 8,
2383 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
23762384 try o.builder.debugTuple(&fields),
23772385 );
23782386
......@@ -2399,8 +2407,8 @@ pub const Object = struct {
23992407 const info = Type.fromInterned(backing_int_ty).intInfo(zcu);
24002408 const builder_name = try o.builder.metadataString(name);
24012409 const debug_int_type = switch (info.signedness) {
2402 .signed => try o.builder.debugSignedType(builder_name, ty.abiSize(zcu) * 8),
2403 .unsigned => try o.builder.debugUnsignedType(builder_name, ty.abiSize(zcu) * 8),
2410 .signed => try o.builder.debugSignedType(builder_name, ty.abiSize(pt) * 8),
2411 .unsigned => try o.builder.debugUnsignedType(builder_name, ty.abiSize(pt) * 8),
24042412 };
24052413 try o.debug_type_map.put(gpa, ty, debug_int_type);
24062414 return debug_int_type;
......@@ -2420,10 +2428,10 @@ pub const Object = struct {
24202428 const debug_fwd_ref = try o.builder.debugForwardReference();
24212429
24222430 for (tuple.types.get(ip), tuple.values.get(ip), 0..) |field_ty, field_val, i| {
2423 if (field_val != .none or !Type.fromInterned(field_ty).hasRuntimeBits(zcu)) continue;
2431 if (field_val != .none or !Type.fromInterned(field_ty).hasRuntimeBits(pt)) continue;
24242432
2425 const field_size = Type.fromInterned(field_ty).abiSize(zcu);
2426 const field_align = Type.fromInterned(field_ty).abiAlignment(zcu);
2433 const field_size = Type.fromInterned(field_ty).abiSize(pt);
2434 const field_align = Type.fromInterned(field_ty).abiAlignment(pt);
24272435 const field_offset = field_align.forward(offset);
24282436 offset = field_offset + field_size;
24292437
......@@ -2451,8 +2459,8 @@ pub const Object = struct {
24512459 o.debug_compile_unit, // Scope
24522460 0, // Line
24532461 .none, // Underlying type
2454 ty.abiSize(zcu) * 8,
2455 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2462 ty.abiSize(pt) * 8,
2463 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
24562464 try o.builder.debugTuple(fields.items),
24572465 );
24582466
......@@ -2479,7 +2487,7 @@ pub const Object = struct {
24792487 else => {},
24802488 }
24812489
2482 if (!ty.hasRuntimeBitsIgnoreComptime(zcu)) {
2490 if (!ty.hasRuntimeBitsIgnoreComptime(pt)) {
24832491 const owner_decl_index = ty.getOwnerDecl(zcu);
24842492 const debug_struct_type = try o.makeEmptyNamespaceDebugType(owner_decl_index);
24852493 try o.debug_type_map.put(gpa, ty, debug_struct_type);
......@@ -2502,17 +2510,17 @@ pub const Object = struct {
25022510 var it = struct_type.iterateRuntimeOrder(ip);
25032511 while (it.next()) |field_index| {
25042512 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
2505 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
2506 const field_size = field_ty.abiSize(zcu);
2507 const field_align = zcu.structFieldAlignment(
2513 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
2514 const field_size = field_ty.abiSize(pt);
2515 const field_align = pt.structFieldAlignment(
25082516 struct_type.fieldAlign(ip, field_index),
25092517 field_ty,
25102518 struct_type.layout,
25112519 );
2512 const field_offset = ty.structFieldOffset(field_index, zcu);
2520 const field_offset = ty.structFieldOffset(field_index, pt);
25132521
25142522 const field_name = struct_type.fieldName(ip, field_index).unwrap() orelse
2515 try ip.getOrPutStringFmt(gpa, "{d}", .{field_index}, .no_embedded_nulls);
2523 try ip.getOrPutStringFmt(gpa, pt.tid, "{d}", .{field_index}, .no_embedded_nulls);
25162524
25172525 fields.appendAssumeCapacity(try o.builder.debugMemberType(
25182526 try o.builder.metadataString(field_name.toSlice(ip)),
......@@ -2532,8 +2540,8 @@ pub const Object = struct {
25322540 o.debug_compile_unit, // Scope
25332541 0, // Line
25342542 .none, // Underlying type
2535 ty.abiSize(zcu) * 8,
2536 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2543 ty.abiSize(pt) * 8,
2544 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
25372545 try o.builder.debugTuple(fields.items),
25382546 );
25392547
......@@ -2553,7 +2561,7 @@ pub const Object = struct {
25532561
25542562 const union_type = ip.loadUnionType(ty.toIntern());
25552563 if (!union_type.haveFieldTypes(ip) or
2556 !ty.hasRuntimeBitsIgnoreComptime(zcu) or
2564 !ty.hasRuntimeBitsIgnoreComptime(pt) or
25572565 !union_type.haveLayout(ip))
25582566 {
25592567 const debug_union_type = try o.makeEmptyNamespaceDebugType(owner_decl_index);
......@@ -2561,7 +2569,7 @@ pub const Object = struct {
25612569 return debug_union_type;
25622570 }
25632571
2564 const layout = zcu.getUnionLayout(union_type);
2572 const layout = pt.getUnionLayout(union_type);
25652573
25662574 const debug_fwd_ref = try o.builder.debugForwardReference();
25672575
......@@ -2575,8 +2583,8 @@ pub const Object = struct {
25752583 o.debug_compile_unit, // Scope
25762584 0, // Line
25772585 .none, // Underlying type
2578 ty.abiSize(zcu) * 8,
2579 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2586 ty.abiSize(pt) * 8,
2587 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
25802588 try o.builder.debugTuple(
25812589 &.{try o.lowerDebugType(Type.fromInterned(union_type.enum_tag_ty))},
25822590 ),
......@@ -2603,12 +2611,12 @@ pub const Object = struct {
26032611
26042612 for (0..tag_type.names.len) |field_index| {
26052613 const field_ty = union_type.field_types.get(ip)[field_index];
2606 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(zcu)) continue;
2614 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(pt)) continue;
26072615
2608 const field_size = Type.fromInterned(field_ty).abiSize(zcu);
2616 const field_size = Type.fromInterned(field_ty).abiSize(pt);
26092617 const field_align: InternPool.Alignment = switch (union_type.flagsPtr(ip).layout) {
26102618 .@"packed" => .none,
2611 .auto, .@"extern" => zcu.unionFieldNormalAlignment(union_type, @intCast(field_index)),
2619 .auto, .@"extern" => pt.unionFieldNormalAlignment(union_type, @intCast(field_index)),
26122620 };
26132621
26142622 const field_name = tag_type.names.get(ip)[field_index];
......@@ -2637,8 +2645,8 @@ pub const Object = struct {
26372645 o.debug_compile_unit, // Scope
26382646 0, // Line
26392647 .none, // Underlying type
2640 ty.abiSize(zcu) * 8,
2641 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2648 ty.abiSize(pt) * 8,
2649 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
26422650 try o.builder.debugTuple(fields.items),
26432651 );
26442652
......@@ -2696,8 +2704,8 @@ pub const Object = struct {
26962704 o.debug_compile_unit, // Scope
26972705 0, // Line
26982706 .none, // Underlying type
2699 ty.abiSize(zcu) * 8,
2700 (ty.abiAlignment(zcu).toByteUnits() orelse 0) * 8,
2707 ty.abiSize(pt) * 8,
2708 (ty.abiAlignment(pt).toByteUnits() orelse 0) * 8,
27012709 try o.builder.debugTuple(&full_fields),
27022710 );
27032711
......@@ -2718,13 +2726,13 @@ pub const Object = struct {
27182726 try debug_param_types.ensureUnusedCapacity(3 + fn_info.param_types.len);
27192727
27202728 // Return type goes first.
2721 if (Type.fromInterned(fn_info.return_type).hasRuntimeBitsIgnoreComptime(zcu)) {
2722 const sret = firstParamSRet(fn_info, zcu, target);
2729 if (Type.fromInterned(fn_info.return_type).hasRuntimeBitsIgnoreComptime(pt)) {
2730 const sret = firstParamSRet(fn_info, pt, target);
27232731 const ret_ty = if (sret) Type.void else Type.fromInterned(fn_info.return_type);
27242732 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(ret_ty));
27252733
27262734 if (sret) {
2727 const ptr_ty = try zcu.singleMutPtrType(Type.fromInterned(fn_info.return_type));
2735 const ptr_ty = try pt.singleMutPtrType(Type.fromInterned(fn_info.return_type));
27282736 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(ptr_ty));
27292737 }
27302738 } else {
......@@ -2732,18 +2740,18 @@ pub const Object = struct {
27322740 }
27332741
27342742 if (Type.fromInterned(fn_info.return_type).isError(zcu) and
2735 o.module.comp.config.any_error_tracing)
2743 zcu.comp.config.any_error_tracing)
27362744 {
2737 const ptr_ty = try zcu.singleMutPtrType(try o.getStackTraceType());
2745 const ptr_ty = try pt.singleMutPtrType(try o.getStackTraceType());
27382746 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(ptr_ty));
27392747 }
27402748
27412749 for (0..fn_info.param_types.len) |i| {
27422750 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[i]);
2743 if (!param_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
2751 if (!param_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
27442752
2745 if (isByRef(param_ty, zcu)) {
2746 const ptr_ty = try zcu.singleMutPtrType(param_ty);
2753 if (isByRef(param_ty, pt)) {
2754 const ptr_ty = try pt.singleMutPtrType(param_ty);
27472755 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(ptr_ty));
27482756 } else {
27492757 debug_param_types.appendAssumeCapacity(try o.lowerDebugType(param_ty));
......@@ -2770,7 +2778,7 @@ pub const Object = struct {
27702778 }
27712779
27722780 fn namespaceToDebugScope(o: *Object, namespace_index: InternPool.NamespaceIndex) !Builder.Metadata {
2773 const zcu = o.module;
2781 const zcu = o.pt.zcu;
27742782 const namespace = zcu.namespacePtr(namespace_index);
27752783 const file_scope = namespace.fileScope(zcu);
27762784 if (namespace.parent == .none) return try o.getDebugFile(file_scope);
......@@ -2783,7 +2791,7 @@ pub const Object = struct {
27832791 }
27842792
27852793 fn makeEmptyNamespaceDebugType(o: *Object, decl_index: InternPool.DeclIndex) !Builder.Metadata {
2786 const zcu = o.module;
2794 const zcu = o.pt.zcu;
27872795 const decl = zcu.declPtr(decl_index);
27882796 const file_scope = zcu.namespacePtr(decl.src_namespace).fileScope(zcu);
27892797 return o.builder.debugStructType(
......@@ -2799,21 +2807,22 @@ pub const Object = struct {
27992807 }
28002808
28012809 fn getStackTraceType(o: *Object) Allocator.Error!Type {
2802 const zcu = o.module;
2810 const pt = o.pt;
2811 const zcu = pt.zcu;
28032812
28042813 const std_mod = zcu.std_mod;
28052814 const std_file_imported = zcu.importPkg(std_mod) catch unreachable;
28062815
2807 const builtin_str = try zcu.intern_pool.getOrPutString(zcu.gpa, "builtin", .no_embedded_nulls);
2816 const builtin_str = try zcu.intern_pool.getOrPutString(zcu.gpa, pt.tid, "builtin", .no_embedded_nulls);
28082817 const std_file_root_decl = zcu.fileRootDecl(std_file_imported.file_index);
28092818 const std_namespace = zcu.namespacePtr(zcu.declPtr(std_file_root_decl.unwrap().?).src_namespace);
2810 const builtin_decl = std_namespace.decls.getKeyAdapted(builtin_str, Module.DeclAdapter{ .zcu = zcu }).?;
2819 const builtin_decl = std_namespace.decls.getKeyAdapted(builtin_str, Zcu.DeclAdapter{ .zcu = zcu }).?;
28112820
2812 const stack_trace_str = try zcu.intern_pool.getOrPutString(zcu.gpa, "StackTrace", .no_embedded_nulls);
2821 const stack_trace_str = try zcu.intern_pool.getOrPutString(zcu.gpa, pt.tid, "StackTrace", .no_embedded_nulls);
28132822 // buffer is only used for int_type, `builtin` is a struct.
28142823 const builtin_ty = zcu.declPtr(builtin_decl).val.toType();
28152824 const builtin_namespace = zcu.namespacePtrUnwrap(builtin_ty.getNamespaceIndex(zcu)).?;
2816 const stack_trace_decl_index = builtin_namespace.decls.getKeyAdapted(stack_trace_str, Module.DeclAdapter{ .zcu = zcu }).?;
2825 const stack_trace_decl_index = builtin_namespace.decls.getKeyAdapted(stack_trace_str, Zcu.DeclAdapter{ .zcu = zcu }).?;
28172826 const stack_trace_decl = zcu.declPtr(stack_trace_decl_index);
28182827
28192828 // Sema should have ensured that StackTrace was analyzed.
......@@ -2824,7 +2833,7 @@ pub const Object = struct {
28242833 fn allocTypeName(o: *Object, ty: Type) Allocator.Error![:0]const u8 {
28252834 var buffer = std.ArrayList(u8).init(o.gpa);
28262835 errdefer buffer.deinit();
2827 try ty.print(buffer.writer(), o.module);
2836 try ty.print(buffer.writer(), o.pt);
28282837 return buffer.toOwnedSliceSentinel(0);
28292838 }
28302839
......@@ -2835,7 +2844,8 @@ pub const Object = struct {
28352844 o: *Object,
28362845 decl_index: InternPool.DeclIndex,
28372846 ) Allocator.Error!Builder.Function.Index {
2838 const zcu = o.module;
2847 const pt = o.pt;
2848 const zcu = pt.zcu;
28392849 const ip = &zcu.intern_pool;
28402850 const gpa = o.gpa;
28412851 const decl = zcu.declPtr(decl_index);
......@@ -2848,7 +2858,7 @@ pub const Object = struct {
28482858 assert(decl.has_tv);
28492859 const fn_info = zcu.typeToFunc(zig_fn_type).?;
28502860 const target = owner_mod.resolved_target.result;
2851 const sret = firstParamSRet(fn_info, zcu, target);
2861 const sret = firstParamSRet(fn_info, pt, target);
28522862
28532863 const is_extern = decl.isExtern(zcu);
28542864 const function_index = try o.builder.addFunction(
......@@ -2856,7 +2866,7 @@ pub const Object = struct {
28562866 try o.builder.strtabString((if (is_extern)
28572867 decl.name
28582868 else
2859 try decl.fullyQualifiedName(zcu)).toSlice(ip)),
2869 try decl.fullyQualifiedName(pt)).toSlice(ip)),
28602870 toLlvmAddressSpace(decl.@"addrspace", target),
28612871 );
28622872 gop.value_ptr.* = function_index.ptrConst(&o.builder).global;
......@@ -2929,14 +2939,14 @@ pub const Object = struct {
29292939 .byval => {
29302940 const param_index = it.zig_index - 1;
29312941 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[param_index]);
2932 if (!isByRef(param_ty, zcu)) {
2942 if (!isByRef(param_ty, pt)) {
29332943 try o.addByValParamAttrs(&attributes, param_ty, param_index, fn_info, it.llvm_index - 1);
29342944 }
29352945 },
29362946 .byref => {
29372947 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[it.zig_index - 1]);
29382948 const param_llvm_ty = try o.lowerType(param_ty);
2939 const alignment = param_ty.abiAlignment(zcu);
2949 const alignment = param_ty.abiAlignment(pt);
29402950 try o.addByRefParamAttrs(&attributes, it.llvm_index - 1, alignment.toLlvm(), it.byval_attr, param_llvm_ty);
29412951 },
29422952 .byref_mut => try attributes.addParamAttr(it.llvm_index - 1, .noundef, &o.builder),
......@@ -2964,7 +2974,7 @@ pub const Object = struct {
29642974 attributes: *Builder.FunctionAttributes.Wip,
29652975 owner_mod: *Package.Module,
29662976 ) Allocator.Error!void {
2967 const comp = o.module.comp;
2977 const comp = o.pt.zcu.comp;
29682978
29692979 if (!owner_mod.red_zone) {
29702980 try attributes.addFnAttr(.noredzone, &o.builder);
......@@ -3039,7 +3049,7 @@ pub const Object = struct {
30393049 }
30403050 errdefer assert(o.anon_decl_map.remove(decl_val));
30413051
3042 const mod = o.module;
3052 const mod = o.pt.zcu;
30433053 const decl_ty = mod.intern_pool.typeOf(decl_val);
30443054
30453055 const variable_index = try o.builder.addVariable(
......@@ -3065,7 +3075,8 @@ pub const Object = struct {
30653075 if (gop.found_existing) return gop.value_ptr.ptr(&o.builder).kind.variable;
30663076 errdefer assert(o.decl_map.remove(decl_index));
30673077
3068 const zcu = o.module;
3078 const pt = o.pt;
3079 const zcu = pt.zcu;
30693080 const decl = zcu.declPtr(decl_index);
30703081 const is_extern = decl.isExtern(zcu);
30713082
......@@ -3073,7 +3084,7 @@ pub const Object = struct {
30733084 try o.builder.strtabString((if (is_extern)
30743085 decl.name
30753086 else
3076 try decl.fullyQualifiedName(zcu)).toSlice(&zcu.intern_pool)),
3087 try decl.fullyQualifiedName(pt)).toSlice(&zcu.intern_pool)),
30773088 try o.lowerType(decl.typeOf(zcu)),
30783089 toLlvmGlobalAddressSpace(decl.@"addrspace", zcu.getTarget()),
30793090 );
......@@ -3100,11 +3111,12 @@ pub const Object = struct {
31003111 }
31013112
31023113 fn errorIntType(o: *Object) Allocator.Error!Builder.Type {
3103 return o.builder.intType(o.module.errorSetBits());
3114 return o.builder.intType(o.pt.zcu.errorSetBits());
31043115 }
31053116
31063117 fn lowerType(o: *Object, t: Type) Allocator.Error!Builder.Type {
3107 const mod = o.module;
3118 const pt = o.pt;
3119 const mod = pt.zcu;
31083120 const target = mod.getTarget();
31093121 const ip = &mod.intern_pool;
31103122 return switch (t.toIntern()) {
......@@ -3230,7 +3242,7 @@ pub const Object = struct {
32303242 ),
32313243 .opt_type => |child_ty| {
32323244 // Must stay in sync with `opt_payload` logic in `lowerPtr`.
3233 if (!Type.fromInterned(child_ty).hasRuntimeBitsIgnoreComptime(mod)) return .i8;
3245 if (!Type.fromInterned(child_ty).hasRuntimeBitsIgnoreComptime(pt)) return .i8;
32343246
32353247 const payload_ty = try o.lowerType(Type.fromInterned(child_ty));
32363248 if (t.optionalReprIsPayload(mod)) return payload_ty;
......@@ -3238,8 +3250,8 @@ pub const Object = struct {
32383250 comptime assert(optional_layout_version == 3);
32393251 var fields: [3]Builder.Type = .{ payload_ty, .i8, undefined };
32403252 var fields_len: usize = 2;
3241 const offset = Type.fromInterned(child_ty).abiSize(mod) + 1;
3242 const abi_size = t.abiSize(mod);
3253 const offset = Type.fromInterned(child_ty).abiSize(pt) + 1;
3254 const abi_size = t.abiSize(pt);
32433255 const padding_len = abi_size - offset;
32443256 if (padding_len > 0) {
32453257 fields[2] = try o.builder.arrayType(padding_len, .i8);
......@@ -3252,16 +3264,16 @@ pub const Object = struct {
32523264 // Must stay in sync with `codegen.errUnionPayloadOffset`.
32533265 // See logic in `lowerPtr`.
32543266 const error_type = try o.errorIntType();
3255 if (!Type.fromInterned(error_union_type.payload_type).hasRuntimeBitsIgnoreComptime(mod))
3267 if (!Type.fromInterned(error_union_type.payload_type).hasRuntimeBitsIgnoreComptime(pt))
32563268 return error_type;
32573269 const payload_type = try o.lowerType(Type.fromInterned(error_union_type.payload_type));
3258 const err_int_ty = try mod.errorIntType();
3270 const err_int_ty = try o.pt.errorIntType();
32593271
3260 const payload_align = Type.fromInterned(error_union_type.payload_type).abiAlignment(mod);
3261 const error_align = err_int_ty.abiAlignment(mod);
3272 const payload_align = Type.fromInterned(error_union_type.payload_type).abiAlignment(pt);
3273 const error_align = err_int_ty.abiAlignment(pt);
32623274
3263 const payload_size = Type.fromInterned(error_union_type.payload_type).abiSize(mod);
3264 const error_size = err_int_ty.abiSize(mod);
3275 const payload_size = Type.fromInterned(error_union_type.payload_type).abiSize(pt);
3276 const error_size = err_int_ty.abiSize(pt);
32653277
32663278 var fields: [3]Builder.Type = undefined;
32673279 var fields_len: usize = 2;
......@@ -3300,7 +3312,7 @@ pub const Object = struct {
33003312 return int_ty;
33013313 }
33023314
3303 const fqn = try mod.declPtr(struct_type.decl.unwrap().?).fullyQualifiedName(mod);
3315 const fqn = try mod.declPtr(struct_type.decl.unwrap().?).fullyQualifiedName(pt);
33043316
33053317 var llvm_field_types = std.ArrayListUnmanaged(Builder.Type){};
33063318 defer llvm_field_types.deinit(o.gpa);
......@@ -3317,12 +3329,12 @@ pub const Object = struct {
33173329 var it = struct_type.iterateRuntimeOrder(ip);
33183330 while (it.next()) |field_index| {
33193331 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
3320 const field_align = mod.structFieldAlignment(
3332 const field_align = pt.structFieldAlignment(
33213333 struct_type.fieldAlign(ip, field_index),
33223334 field_ty,
33233335 struct_type.layout,
33243336 );
3325 const field_ty_align = field_ty.abiAlignment(mod);
3337 const field_ty_align = field_ty.abiAlignment(pt);
33263338 if (field_align.compare(.lt, field_ty_align)) struct_kind = .@"packed";
33273339 big_align = big_align.max(field_align);
33283340 const prev_offset = offset;
......@@ -3334,7 +3346,7 @@ pub const Object = struct {
33343346 try o.builder.arrayType(padding_len, .i8),
33353347 );
33363348
3337 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) {
3349 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) {
33383350 // This is a zero-bit field. If there are runtime bits after this field,
33393351 // map to the next LLVM field (which we know exists): otherwise, don't
33403352 // map the field, indicating it's at the end of the struct.
......@@ -3353,7 +3365,7 @@ pub const Object = struct {
33533365 }, @intCast(llvm_field_types.items.len));
33543366 try llvm_field_types.append(o.gpa, try o.lowerType(field_ty));
33553367
3356 offset += field_ty.abiSize(mod);
3368 offset += field_ty.abiSize(pt);
33573369 }
33583370 {
33593371 const prev_offset = offset;
......@@ -3386,7 +3398,7 @@ pub const Object = struct {
33863398 var offset: u64 = 0;
33873399 var big_align: InternPool.Alignment = .none;
33883400
3389 const struct_size = t.abiSize(mod);
3401 const struct_size = t.abiSize(pt);
33903402
33913403 for (
33923404 anon_struct_type.types.get(ip),
......@@ -3395,7 +3407,7 @@ pub const Object = struct {
33953407 ) |field_ty, field_val, field_index| {
33963408 if (field_val != .none) continue;
33973409
3398 const field_align = Type.fromInterned(field_ty).abiAlignment(mod);
3410 const field_align = Type.fromInterned(field_ty).abiAlignment(pt);
33993411 big_align = big_align.max(field_align);
34003412 const prev_offset = offset;
34013413 offset = field_align.forward(offset);
......@@ -3405,7 +3417,7 @@ pub const Object = struct {
34053417 o.gpa,
34063418 try o.builder.arrayType(padding_len, .i8),
34073419 );
3408 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(mod)) {
3420 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(pt)) {
34093421 // This is a zero-bit field. If there are runtime bits after this field,
34103422 // map to the next LLVM field (which we know exists): otherwise, don't
34113423 // map the field, indicating it's at the end of the struct.
......@@ -3423,7 +3435,7 @@ pub const Object = struct {
34233435 }, @intCast(llvm_field_types.items.len));
34243436 try llvm_field_types.append(o.gpa, try o.lowerType(Type.fromInterned(field_ty)));
34253437
3426 offset += Type.fromInterned(field_ty).abiSize(mod);
3438 offset += Type.fromInterned(field_ty).abiSize(pt);
34273439 }
34283440 {
34293441 const prev_offset = offset;
......@@ -3440,10 +3452,10 @@ pub const Object = struct {
34403452 if (o.type_map.get(t.toIntern())) |value| return value;
34413453
34423454 const union_obj = ip.loadUnionType(t.toIntern());
3443 const layout = mod.getUnionLayout(union_obj);
3455 const layout = pt.getUnionLayout(union_obj);
34443456
34453457 if (union_obj.flagsPtr(ip).layout == .@"packed") {
3446 const int_ty = try o.builder.intType(@intCast(t.bitSize(mod)));
3458 const int_ty = try o.builder.intType(@intCast(t.bitSize(pt)));
34473459 try o.type_map.put(o.gpa, t.toIntern(), int_ty);
34483460 return int_ty;
34493461 }
......@@ -3454,7 +3466,7 @@ pub const Object = struct {
34543466 return enum_tag_ty;
34553467 }
34563468
3457 const fqn = try mod.declPtr(union_obj.decl).fullyQualifiedName(mod);
3469 const fqn = try mod.declPtr(union_obj.decl).fullyQualifiedName(pt);
34583470
34593471 const aligned_field_ty = Type.fromInterned(union_obj.field_types.get(ip)[layout.most_aligned_field]);
34603472 const aligned_field_llvm_ty = try o.lowerType(aligned_field_ty);
......@@ -3515,7 +3527,7 @@ pub const Object = struct {
35153527 const gop = try o.type_map.getOrPut(o.gpa, t.toIntern());
35163528 if (!gop.found_existing) {
35173529 const decl = mod.declPtr(ip.loadOpaqueType(t.toIntern()).decl);
3518 const fqn = try decl.fullyQualifiedName(mod);
3530 const fqn = try decl.fullyQualifiedName(pt);
35193531 gop.value_ptr.* = try o.builder.opaqueType(try o.builder.string(fqn.toSlice(ip)));
35203532 }
35213533 return gop.value_ptr.*;
......@@ -3552,18 +3564,20 @@ pub const Object = struct {
35523564 /// being a zero bit type, but it should still be lowered as an i8 in such case.
35533565 /// There are other similar cases handled here as well.
35543566 fn lowerPtrElemTy(o: *Object, elem_ty: Type) Allocator.Error!Builder.Type {
3555 const mod = o.module;
3567 const pt = o.pt;
3568 const mod = pt.zcu;
35563569 const lower_elem_ty = switch (elem_ty.zigTypeTag(mod)) {
35573570 .Opaque => true,
35583571 .Fn => !mod.typeToFunc(elem_ty).?.is_generic,
3559 .Array => elem_ty.childType(mod).hasRuntimeBitsIgnoreComptime(mod),
3560 else => elem_ty.hasRuntimeBitsIgnoreComptime(mod),
3572 .Array => elem_ty.childType(mod).hasRuntimeBitsIgnoreComptime(pt),
3573 else => elem_ty.hasRuntimeBitsIgnoreComptime(pt),
35613574 };
35623575 return if (lower_elem_ty) try o.lowerType(elem_ty) else .i8;
35633576 }
35643577
35653578 fn lowerTypeFn(o: *Object, fn_info: InternPool.Key.FuncType) Allocator.Error!Builder.Type {
3566 const mod = o.module;
3579 const pt = o.pt;
3580 const mod = pt.zcu;
35673581 const ip = &mod.intern_pool;
35683582 const target = mod.getTarget();
35693583 const ret_ty = try lowerFnRetTy(o, fn_info);
......@@ -3571,14 +3585,14 @@ pub const Object = struct {
35713585 var llvm_params = std.ArrayListUnmanaged(Builder.Type){};
35723586 defer llvm_params.deinit(o.gpa);
35733587
3574 if (firstParamSRet(fn_info, mod, target)) {
3588 if (firstParamSRet(fn_info, pt, target)) {
35753589 try llvm_params.append(o.gpa, .ptr);
35763590 }
35773591
35783592 if (Type.fromInterned(fn_info.return_type).isError(mod) and
35793593 mod.comp.config.any_error_tracing)
35803594 {
3581 const ptr_ty = try mod.singleMutPtrType(try o.getStackTraceType());
3595 const ptr_ty = try pt.singleMutPtrType(try o.getStackTraceType());
35823596 try llvm_params.append(o.gpa, try o.lowerType(ptr_ty));
35833597 }
35843598
......@@ -3595,7 +3609,7 @@ pub const Object = struct {
35953609 .abi_sized_int => {
35963610 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[it.zig_index - 1]);
35973611 try llvm_params.append(o.gpa, try o.builder.intType(
3598 @intCast(param_ty.abiSize(mod) * 8),
3612 @intCast(param_ty.abiSize(pt) * 8),
35993613 ));
36003614 },
36013615 .slice => {
......@@ -3633,7 +3647,8 @@ pub const Object = struct {
36333647 }
36343648
36353649 fn lowerValueToInt(o: *Object, llvm_int_ty: Builder.Type, arg_val: InternPool.Index) Error!Builder.Constant {
3636 const mod = o.module;
3650 const pt = o.pt;
3651 const mod = pt.zcu;
36373652 const ip = &mod.intern_pool;
36383653 const target = mod.getTarget();
36393654
......@@ -3666,15 +3681,15 @@ pub const Object = struct {
36663681 var running_int = try o.builder.intConst(llvm_int_ty, 0);
36673682 var running_bits: u16 = 0;
36683683 for (struct_type.field_types.get(ip), 0..) |field_ty, field_index| {
3669 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(mod)) continue;
3684 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(pt)) continue;
36703685
36713686 const shift_rhs = try o.builder.intConst(llvm_int_ty, running_bits);
3672 const field_val = try o.lowerValueToInt(llvm_int_ty, (try val.fieldValue(mod, field_index)).toIntern());
3687 const field_val = try o.lowerValueToInt(llvm_int_ty, (try val.fieldValue(pt, field_index)).toIntern());
36733688 const shifted = try o.builder.binConst(.shl, field_val, shift_rhs);
36743689
36753690 running_int = try o.builder.binConst(.xor, running_int, shifted);
36763691
3677 const ty_bit_size: u16 = @intCast(Type.fromInterned(field_ty).bitSize(mod));
3692 const ty_bit_size: u16 = @intCast(Type.fromInterned(field_ty).bitSize(pt));
36783693 running_bits += ty_bit_size;
36793694 }
36803695 return running_int;
......@@ -3683,7 +3698,7 @@ pub const Object = struct {
36833698 else => unreachable,
36843699 },
36853700 .un => |un| {
3686 const layout = ty.unionGetLayout(mod);
3701 const layout = ty.unionGetLayout(pt);
36873702 if (layout.payload_size == 0) return o.lowerValue(un.tag);
36883703
36893704 const union_obj = mod.typeToUnion(ty).?;
......@@ -3701,7 +3716,7 @@ pub const Object = struct {
37013716 }
37023717 const field_index = mod.unionTagFieldIndex(union_obj, Value.fromInterned(un.tag)).?;
37033718 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
3704 if (!field_ty.hasRuntimeBits(mod)) return o.builder.intConst(llvm_int_ty, 0);
3719 if (!field_ty.hasRuntimeBits(pt)) return o.builder.intConst(llvm_int_ty, 0);
37053720 return o.lowerValueToInt(llvm_int_ty, un.val);
37063721 },
37073722 .simple_value => |simple_value| switch (simple_value) {
......@@ -3715,7 +3730,7 @@ pub const Object = struct {
37153730 .opt => {}, // pointer like optional expected
37163731 else => unreachable,
37173732 }
3718 const bits = ty.bitSize(mod);
3733 const bits = ty.bitSize(pt);
37193734 const bytes: usize = @intCast(std.mem.alignForward(u64, bits, 8) / 8);
37203735
37213736 var stack = std.heap.stackFallback(32, o.gpa);
......@@ -3729,12 +3744,7 @@ pub const Object = struct {
37293744 defer allocator.free(limbs);
37303745 @memset(limbs, 0);
37313746
3732 val.writeToPackedMemory(
3733 ty,
3734 mod,
3735 std.mem.sliceAsBytes(limbs)[0..bytes],
3736 0,
3737 ) catch unreachable;
3747 val.writeToPackedMemory(ty, pt, std.mem.sliceAsBytes(limbs)[0..bytes], 0) catch unreachable;
37383748
37393749 if (builtin.target.cpu.arch.endian() == .little) {
37403750 if (target.cpu.arch.endian() == .big)
......@@ -3752,7 +3762,8 @@ pub const Object = struct {
37523762 }
37533763
37543764 fn lowerValue(o: *Object, arg_val: InternPool.Index) Error!Builder.Constant {
3755 const mod = o.module;
3765 const pt = o.pt;
3766 const mod = pt.zcu;
37563767 const ip = &mod.intern_pool;
37573768 const target = mod.getTarget();
37583769
......@@ -3811,7 +3822,7 @@ pub const Object = struct {
38113822 },
38123823 .int => {
38133824 var bigint_space: Value.BigIntSpace = undefined;
3814 const bigint = val.toBigInt(&bigint_space, mod);
3825 const bigint = val.toBigInt(&bigint_space, pt);
38153826 return lowerBigInt(o, ty, bigint);
38163827 },
38173828 .err => |err| {
......@@ -3821,24 +3832,24 @@ pub const Object = struct {
38213832 },
38223833 .error_union => |error_union| {
38233834 const err_val = switch (error_union.val) {
3824 .err_name => |err_name| try mod.intern(.{ .err = .{
3835 .err_name => |err_name| try pt.intern(.{ .err = .{
38253836 .ty = ty.errorUnionSet(mod).toIntern(),
38263837 .name = err_name,
38273838 } }),
3828 .payload => (try mod.intValue(try mod.errorIntType(), 0)).toIntern(),
3839 .payload => (try pt.intValue(try pt.errorIntType(), 0)).toIntern(),
38293840 };
3830 const err_int_ty = try mod.errorIntType();
3841 const err_int_ty = try pt.errorIntType();
38313842 const payload_type = ty.errorUnionPayload(mod);
3832 if (!payload_type.hasRuntimeBitsIgnoreComptime(mod)) {
3843 if (!payload_type.hasRuntimeBitsIgnoreComptime(pt)) {
38333844 // We use the error type directly as the type.
38343845 return o.lowerValue(err_val);
38353846 }
38363847
3837 const payload_align = payload_type.abiAlignment(mod);
3838 const error_align = err_int_ty.abiAlignment(mod);
3848 const payload_align = payload_type.abiAlignment(pt);
3849 const error_align = err_int_ty.abiAlignment(pt);
38393850 const llvm_error_value = try o.lowerValue(err_val);
38403851 const llvm_payload_value = try o.lowerValue(switch (error_union.val) {
3841 .err_name => try mod.intern(.{ .undef = payload_type.toIntern() }),
3852 .err_name => try pt.intern(.{ .undef = payload_type.toIntern() }),
38423853 .payload => |payload| payload,
38433854 });
38443855
......@@ -3869,16 +3880,16 @@ pub const Object = struct {
38693880 .enum_tag => |enum_tag| o.lowerValue(enum_tag.int),
38703881 .float => switch (ty.floatBits(target)) {
38713882 16 => if (backendSupportsF16(target))
3872 try o.builder.halfConst(val.toFloat(f16, mod))
3883 try o.builder.halfConst(val.toFloat(f16, pt))
38733884 else
3874 try o.builder.intConst(.i16, @as(i16, @bitCast(val.toFloat(f16, mod)))),
3875 32 => try o.builder.floatConst(val.toFloat(f32, mod)),
3876 64 => try o.builder.doubleConst(val.toFloat(f64, mod)),
3885 try o.builder.intConst(.i16, @as(i16, @bitCast(val.toFloat(f16, pt)))),
3886 32 => try o.builder.floatConst(val.toFloat(f32, pt)),
3887 64 => try o.builder.doubleConst(val.toFloat(f64, pt)),
38773888 80 => if (backendSupportsF80(target))
3878 try o.builder.x86_fp80Const(val.toFloat(f80, mod))
3889 try o.builder.x86_fp80Const(val.toFloat(f80, pt))
38793890 else
3880 try o.builder.intConst(.i80, @as(i80, @bitCast(val.toFloat(f80, mod)))),
3881 128 => try o.builder.fp128Const(val.toFloat(f128, mod)),
3891 try o.builder.intConst(.i80, @as(i80, @bitCast(val.toFloat(f80, pt)))),
3892 128 => try o.builder.fp128Const(val.toFloat(f128, pt)),
38823893 else => unreachable,
38833894 },
38843895 .ptr => try o.lowerPtr(arg_val, 0),
......@@ -3891,7 +3902,7 @@ pub const Object = struct {
38913902 const payload_ty = ty.optionalChild(mod);
38923903
38933904 const non_null_bit = try o.builder.intConst(.i8, @intFromBool(opt.val != .none));
3894 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
3905 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
38953906 return non_null_bit;
38963907 }
38973908 const llvm_ty = try o.lowerType(ty);
......@@ -3909,7 +3920,7 @@ pub const Object = struct {
39093920 var fields: [3]Builder.Type = undefined;
39103921 var vals: [3]Builder.Constant = undefined;
39113922 vals[0] = try o.lowerValue(switch (opt.val) {
3912 .none => try mod.intern(.{ .undef = payload_ty.toIntern() }),
3923 .none => try pt.intern(.{ .undef = payload_ty.toIntern() }),
39133924 else => |payload| payload,
39143925 });
39153926 vals[1] = non_null_bit;
......@@ -4058,9 +4069,9 @@ pub const Object = struct {
40584069 0..,
40594070 ) |field_ty, field_val, field_index| {
40604071 if (field_val != .none) continue;
4061 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(mod)) continue;
4072 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(pt)) continue;
40624073
4063 const field_align = Type.fromInterned(field_ty).abiAlignment(mod);
4074 const field_align = Type.fromInterned(field_ty).abiAlignment(pt);
40644075 big_align = big_align.max(field_align);
40654076 const prev_offset = offset;
40664077 offset = field_align.forward(offset);
......@@ -4076,13 +4087,13 @@ pub const Object = struct {
40764087 }
40774088
40784089 vals[llvm_index] =
4079 try o.lowerValue((try val.fieldValue(mod, field_index)).toIntern());
4090 try o.lowerValue((try val.fieldValue(pt, field_index)).toIntern());
40804091 fields[llvm_index] = vals[llvm_index].typeOf(&o.builder);
40814092 if (fields[llvm_index] != struct_ty.structFields(&o.builder)[llvm_index])
40824093 need_unnamed = true;
40834094 llvm_index += 1;
40844095
4085 offset += Type.fromInterned(field_ty).abiSize(mod);
4096 offset += Type.fromInterned(field_ty).abiSize(pt);
40864097 }
40874098 {
40884099 const prev_offset = offset;
......@@ -4109,7 +4120,7 @@ pub const Object = struct {
41094120 if (struct_type.layout == .@"packed") {
41104121 comptime assert(Type.packed_struct_layout_version == 2);
41114122
4112 const bits = ty.bitSize(mod);
4123 const bits = ty.bitSize(pt);
41134124 const llvm_int_ty = try o.builder.intType(@intCast(bits));
41144125
41154126 return o.lowerValueToInt(llvm_int_ty, arg_val);
......@@ -4138,7 +4149,7 @@ pub const Object = struct {
41384149 var field_it = struct_type.iterateRuntimeOrder(ip);
41394150 while (field_it.next()) |field_index| {
41404151 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
4141 const field_align = mod.structFieldAlignment(
4152 const field_align = pt.structFieldAlignment(
41424153 struct_type.fieldAlign(ip, field_index),
41434154 field_ty,
41444155 struct_type.layout,
......@@ -4158,20 +4169,20 @@ pub const Object = struct {
41584169 llvm_index += 1;
41594170 }
41604171
4161 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4172 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) {
41624173 // This is a zero-bit field - we only needed it for the alignment.
41634174 continue;
41644175 }
41654176
41664177 vals[llvm_index] = try o.lowerValue(
4167 (try val.fieldValue(mod, field_index)).toIntern(),
4178 (try val.fieldValue(pt, field_index)).toIntern(),
41684179 );
41694180 fields[llvm_index] = vals[llvm_index].typeOf(&o.builder);
41704181 if (fields[llvm_index] != struct_ty.structFields(&o.builder)[llvm_index])
41714182 need_unnamed = true;
41724183 llvm_index += 1;
41734184
4174 offset += field_ty.abiSize(mod);
4185 offset += field_ty.abiSize(pt);
41754186 }
41764187 {
41774188 const prev_offset = offset;
......@@ -4195,7 +4206,7 @@ pub const Object = struct {
41954206 },
41964207 .un => |un| {
41974208 const union_ty = try o.lowerType(ty);
4198 const layout = ty.unionGetLayout(mod);
4209 const layout = ty.unionGetLayout(pt);
41994210 if (layout.payload_size == 0) return o.lowerValue(un.tag);
42004211
42014212 const union_obj = mod.typeToUnion(ty).?;
......@@ -4206,8 +4217,8 @@ pub const Object = struct {
42064217 const field_index = mod.unionTagFieldIndex(union_obj, Value.fromInterned(un.tag)).?;
42074218 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[field_index]);
42084219 if (container_layout == .@"packed") {
4209 if (!field_ty.hasRuntimeBits(mod)) return o.builder.intConst(union_ty, 0);
4210 const bits = ty.bitSize(mod);
4220 if (!field_ty.hasRuntimeBits(pt)) return o.builder.intConst(union_ty, 0);
4221 const bits = ty.bitSize(pt);
42114222 const llvm_int_ty = try o.builder.intType(@intCast(bits));
42124223
42134224 return o.lowerValueToInt(llvm_int_ty, arg_val);
......@@ -4219,7 +4230,7 @@ pub const Object = struct {
42194230 // must pointer cast to the expected type before accessing the union.
42204231 need_unnamed = layout.most_aligned_field != field_index;
42214232
4222 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4233 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) {
42234234 const padding_len = layout.payload_size;
42244235 break :p try o.builder.undefConst(try o.builder.arrayType(padding_len, .i8));
42254236 }
......@@ -4228,7 +4239,7 @@ pub const Object = struct {
42284239 if (payload_ty != union_ty.structFields(&o.builder)[
42294240 @intFromBool(layout.tag_align.compare(.gte, layout.payload_align))
42304241 ]) need_unnamed = true;
4231 const field_size = field_ty.abiSize(mod);
4242 const field_size = field_ty.abiSize(pt);
42324243 if (field_size == layout.payload_size) break :p payload;
42334244 const padding_len = layout.payload_size - field_size;
42344245 const padding_ty = try o.builder.arrayType(padding_len, .i8);
......@@ -4239,7 +4250,7 @@ pub const Object = struct {
42394250 } else p: {
42404251 assert(layout.tag_size == 0);
42414252 if (container_layout == .@"packed") {
4242 const bits = ty.bitSize(mod);
4253 const bits = ty.bitSize(pt);
42434254 const llvm_int_ty = try o.builder.intType(@intCast(bits));
42444255
42454256 return o.lowerValueToInt(llvm_int_ty, arg_val);
......@@ -4286,7 +4297,7 @@ pub const Object = struct {
42864297 ty: Type,
42874298 bigint: std.math.big.int.Const,
42884299 ) Allocator.Error!Builder.Constant {
4289 const mod = o.module;
4300 const mod = o.pt.zcu;
42904301 return o.builder.bigIntConst(try o.builder.intType(ty.intInfo(mod).bits), bigint);
42914302 }
42924303
......@@ -4295,7 +4306,8 @@ pub const Object = struct {
42954306 ptr_val: InternPool.Index,
42964307 prev_offset: u64,
42974308 ) Error!Builder.Constant {
4298 const zcu = o.module;
4309 const pt = o.pt;
4310 const zcu = pt.zcu;
42994311 const ptr = zcu.intern_pool.indexToKey(ptr_val).ptr;
43004312 const offset: u64 = prev_offset + ptr.byte_offset;
43014313 return switch (ptr.base_addr) {
......@@ -4320,7 +4332,7 @@ pub const Object = struct {
43204332 eu_ptr,
43214333 offset + @import("../codegen.zig").errUnionPayloadOffset(
43224334 Value.fromInterned(eu_ptr).typeOf(zcu).childType(zcu),
4323 zcu,
4335 pt,
43244336 ),
43254337 ),
43264338 .opt_payload => |opt_ptr| try o.lowerPtr(opt_ptr, offset),
......@@ -4336,7 +4348,7 @@ pub const Object = struct {
43364348 };
43374349 },
43384350 .Struct, .Union => switch (agg_ty.containerLayout(zcu)) {
4339 .auto => agg_ty.structFieldOffset(@intCast(field.index), zcu),
4351 .auto => agg_ty.structFieldOffset(@intCast(field.index), pt),
43404352 .@"extern", .@"packed" => unreachable,
43414353 },
43424354 else => unreachable,
......@@ -4353,7 +4365,8 @@ pub const Object = struct {
43534365 o: *Object,
43544366 anon_decl: InternPool.Key.Ptr.BaseAddr.AnonDecl,
43554367 ) Error!Builder.Constant {
4356 const mod = o.module;
4368 const pt = o.pt;
4369 const mod = pt.zcu;
43574370 const ip = &mod.intern_pool;
43584371 const decl_val = anon_decl.val;
43594372 const decl_ty = Type.fromInterned(ip.typeOf(decl_val));
......@@ -4370,14 +4383,14 @@ pub const Object = struct {
43704383 const ptr_ty = Type.fromInterned(anon_decl.orig_ty);
43714384
43724385 const is_fn_body = decl_ty.zigTypeTag(mod) == .Fn;
4373 if ((!is_fn_body and !decl_ty.hasRuntimeBits(mod)) or
4386 if ((!is_fn_body and !decl_ty.hasRuntimeBits(pt)) or
43744387 (is_fn_body and mod.typeToFunc(decl_ty).?.is_generic)) return o.lowerPtrToVoid(ptr_ty);
43754388
43764389 if (is_fn_body)
43774390 @panic("TODO");
43784391
43794392 const llvm_addr_space = toLlvmAddressSpace(ptr_ty.ptrAddressSpace(mod), target);
4380 const alignment = ptr_ty.ptrAlignment(mod);
4393 const alignment = ptr_ty.ptrAlignment(pt);
43814394 const llvm_global = (try o.resolveGlobalAnonDecl(decl_val, llvm_addr_space, alignment)).ptrConst(&o.builder).global;
43824395
43834396 const llvm_val = try o.builder.convConst(
......@@ -4389,7 +4402,8 @@ pub const Object = struct {
43894402 }
43904403
43914404 fn lowerDeclRefValue(o: *Object, decl_index: InternPool.DeclIndex) Allocator.Error!Builder.Constant {
4392 const mod = o.module;
4405 const pt = o.pt;
4406 const mod = pt.zcu;
43934407
43944408 // In the case of something like:
43954409 // fn foo() void {}
......@@ -4408,10 +4422,10 @@ pub const Object = struct {
44084422 }
44094423
44104424 const decl_ty = decl.typeOf(mod);
4411 const ptr_ty = try decl.declPtrType(mod);
4425 const ptr_ty = try decl.declPtrType(pt);
44124426
44134427 const is_fn_body = decl_ty.zigTypeTag(mod) == .Fn;
4414 if ((!is_fn_body and !decl_ty.hasRuntimeBits(mod)) or
4428 if ((!is_fn_body and !decl_ty.hasRuntimeBits(pt)) or
44154429 (is_fn_body and mod.typeToFunc(decl_ty).?.is_generic))
44164430 {
44174431 return o.lowerPtrToVoid(ptr_ty);
......@@ -4431,7 +4445,7 @@ pub const Object = struct {
44314445 }
44324446
44334447 fn lowerPtrToVoid(o: *Object, ptr_ty: Type) Allocator.Error!Builder.Constant {
4434 const mod = o.module;
4448 const mod = o.pt.zcu;
44354449 // Even though we are pointing at something which has zero bits (e.g. `void`),
44364450 // Pointers are defined to have bits. So we must return something here.
44374451 // The value cannot be undefined, because we use the `nonnull` annotation
......@@ -4459,20 +4473,21 @@ pub const Object = struct {
44594473 /// RMW exchange of floating-point values is bitcasted to same-sized integer
44604474 /// types to work around a LLVM deficiency when targeting ARM/AArch64.
44614475 fn getAtomicAbiType(o: *Object, ty: Type, is_rmw_xchg: bool) Allocator.Error!Builder.Type {
4462 const mod = o.module;
4476 const pt = o.pt;
4477 const mod = pt.zcu;
44634478 const int_ty = switch (ty.zigTypeTag(mod)) {
44644479 .Int => ty,
44654480 .Enum => ty.intTagType(mod),
44664481 .Float => {
44674482 if (!is_rmw_xchg) return .none;
4468 return o.builder.intType(@intCast(ty.abiSize(mod) * 8));
4483 return o.builder.intType(@intCast(ty.abiSize(pt) * 8));
44694484 },
44704485 .Bool => return .i8,
44714486 else => return .none,
44724487 };
44734488 const bit_count = int_ty.intInfo(mod).bits;
44744489 if (!std.math.isPowerOfTwo(bit_count) or (bit_count % 8) != 0) {
4475 return o.builder.intType(@intCast(int_ty.abiSize(mod) * 8));
4490 return o.builder.intType(@intCast(int_ty.abiSize(pt) * 8));
44764491 } else {
44774492 return .none;
44784493 }
......@@ -4486,7 +4501,8 @@ pub const Object = struct {
44864501 fn_info: InternPool.Key.FuncType,
44874502 llvm_arg_i: u32,
44884503 ) Allocator.Error!void {
4489 const mod = o.module;
4504 const pt = o.pt;
4505 const mod = pt.zcu;
44904506 if (param_ty.isPtrAtRuntime(mod)) {
44914507 const ptr_info = param_ty.ptrInfo(mod);
44924508 if (math.cast(u5, param_index)) |i| {
......@@ -4507,7 +4523,7 @@ pub const Object = struct {
45074523 const elem_align = if (ptr_info.flags.alignment != .none)
45084524 ptr_info.flags.alignment
45094525 else
4510 Type.fromInterned(ptr_info.child).abiAlignment(mod).max(.@"1");
4526 Type.fromInterned(ptr_info.child).abiAlignment(pt).max(.@"1");
45114527 try attributes.addParamAttr(llvm_arg_i, .{ .@"align" = elem_align.toLlvm() }, &o.builder);
45124528 } else if (ccAbiPromoteInt(fn_info.cc, mod, param_ty)) |s| switch (s) {
45134529 .signed => try attributes.addParamAttr(llvm_arg_i, .signext, &o.builder),
......@@ -4540,7 +4556,7 @@ pub const Object = struct {
45404556 const name = try o.builder.strtabString(lt_errors_fn_name);
45414557 if (o.builder.getGlobal(name)) |llvm_fn| return llvm_fn.ptrConst(&o.builder).kind.function;
45424558
4543 const zcu = o.module;
4559 const zcu = o.pt.zcu;
45444560 const target = zcu.root_mod.resolved_target.result;
45454561 const function_index = try o.builder.addFunction(
45464562 try o.builder.fnType(.i1, &.{try o.errorIntType()}, .normal),
......@@ -4559,7 +4575,8 @@ pub const Object = struct {
45594575 }
45604576
45614577 fn getEnumTagNameFunction(o: *Object, enum_ty: Type) !Builder.Function.Index {
4562 const zcu = o.module;
4578 const pt = o.pt;
4579 const zcu = pt.zcu;
45634580 const ip = &zcu.intern_pool;
45644581 const enum_type = ip.loadEnumType(enum_ty.toIntern());
45654582
......@@ -4570,7 +4587,7 @@ pub const Object = struct {
45704587
45714588 const usize_ty = try o.lowerType(Type.usize);
45724589 const ret_ty = try o.lowerType(Type.slice_const_u8_sentinel_0);
4573 const fqn = try zcu.declPtr(enum_type.decl).fullyQualifiedName(zcu);
4590 const fqn = try zcu.declPtr(enum_type.decl).fullyQualifiedName(pt);
45744591 const target = zcu.root_mod.resolved_target.result;
45754592 const function_index = try o.builder.addFunction(
45764593 try o.builder.fnType(ret_ty, &.{try o.lowerType(Type.fromInterned(enum_type.tag_ty))}, .normal),
......@@ -4618,7 +4635,7 @@ pub const Object = struct {
46184635
46194636 const return_block = try wip.block(1, "Name");
46204637 const this_tag_int_value = try o.lowerValue(
4621 (try zcu.enumValueFieldIndex(enum_ty, @intCast(field_index))).toIntern(),
4638 (try pt.enumValueFieldIndex(enum_ty, @intCast(field_index))).toIntern(),
46224639 );
46234640 try wip_switch.addCase(this_tag_int_value, return_block, &wip);
46244641
......@@ -4636,13 +4653,13 @@ pub const Object = struct {
46364653
46374654pub const DeclGen = struct {
46384655 object: *Object,
4639 decl: *Module.Decl,
4656 decl: *Zcu.Decl,
46404657 decl_index: InternPool.DeclIndex,
4641 err_msg: ?*Module.ErrorMsg,
4658 err_msg: ?*Zcu.ErrorMsg,
46424659
46434660 fn ownerModule(dg: DeclGen) *Package.Module {
46444661 const o = dg.object;
4645 const zcu = o.module;
4662 const zcu = o.pt.zcu;
46464663 const namespace = zcu.namespacePtr(dg.decl.src_namespace);
46474664 const file_scope = namespace.fileScope(zcu);
46484665 return file_scope.mod;
......@@ -4653,15 +4670,15 @@ pub const DeclGen = struct {
46534670 assert(dg.err_msg == null);
46544671 const o = dg.object;
46554672 const gpa = o.gpa;
4656 const mod = o.module;
4657 const src_loc = dg.decl.navSrcLoc(mod);
4658 dg.err_msg = try Module.ErrorMsg.create(gpa, src_loc, "TODO (LLVM): " ++ format, args);
4673 const src_loc = dg.decl.navSrcLoc(o.pt.zcu);
4674 dg.err_msg = try Zcu.ErrorMsg.create(gpa, src_loc, "TODO (LLVM): " ++ format, args);
46594675 return error.CodegenFail;
46604676 }
46614677
46624678 fn genDecl(dg: *DeclGen) !void {
46634679 const o = dg.object;
4664 const zcu = o.module;
4680 const pt = o.pt;
4681 const zcu = pt.zcu;
46654682 const ip = &zcu.intern_pool;
46664683 const decl = dg.decl;
46674684 const decl_index = dg.decl_index;
......@@ -4672,7 +4689,7 @@ pub const DeclGen = struct {
46724689 } else {
46734690 const variable_index = try o.resolveGlobalDecl(decl_index);
46744691 variable_index.setAlignment(
4675 decl.getAlignment(zcu).toLlvm(),
4692 decl.getAlignment(pt).toLlvm(),
46764693 &o.builder,
46774694 );
46784695 if (decl.@"linksection".toSlice(ip)) |section|
......@@ -4833,23 +4850,21 @@ pub const FuncGen = struct {
48334850 const gop = try self.func_inst_table.getOrPut(gpa, inst);
48344851 if (gop.found_existing) return gop.value_ptr.*;
48354852
4836 const o = self.dg.object;
4837 const mod = o.module;
4838 const llvm_val = try self.resolveValue((try self.air.value(inst, mod)).?);
4853 const llvm_val = try self.resolveValue((try self.air.value(inst, self.dg.object.pt)).?);
48394854 gop.value_ptr.* = llvm_val.toValue();
48404855 return llvm_val.toValue();
48414856 }
48424857
48434858 fn resolveValue(self: *FuncGen, val: Value) Error!Builder.Constant {
48444859 const o = self.dg.object;
4845 const mod = o.module;
4846 const ty = val.typeOf(mod);
4860 const pt = o.pt;
4861 const ty = val.typeOf(pt.zcu);
48474862 const llvm_val = try o.lowerValue(val.toIntern());
4848 if (!isByRef(ty, mod)) return llvm_val;
4863 if (!isByRef(ty, pt)) return llvm_val;
48494864
48504865 // We have an LLVM value but we need to create a global constant and
48514866 // set the value as its initializer, and then return a pointer to the global.
4852 const target = mod.getTarget();
4867 const target = pt.zcu.getTarget();
48534868 const variable_index = try o.builder.addVariable(
48544869 .empty,
48554870 llvm_val.typeOf(&o.builder),
......@@ -4859,7 +4874,7 @@ pub const FuncGen = struct {
48594874 variable_index.setLinkage(.private, &o.builder);
48604875 variable_index.setMutability(.constant, &o.builder);
48614876 variable_index.setUnnamedAddr(.unnamed_addr, &o.builder);
4862 variable_index.setAlignment(ty.abiAlignment(mod).toLlvm(), &o.builder);
4877 variable_index.setAlignment(ty.abiAlignment(pt).toLlvm(), &o.builder);
48634878 return o.builder.convConst(
48644879 variable_index.toConst(&o.builder),
48654880 try o.builder.ptrType(toLlvmAddressSpace(.generic, target)),
......@@ -4868,10 +4883,10 @@ pub const FuncGen = struct {
48684883
48694884 fn resolveNullOptUsize(self: *FuncGen) Error!Builder.Constant {
48704885 const o = self.dg.object;
4871 const mod = o.module;
4886 const pt = o.pt;
48724887 if (o.null_opt_usize == .no_init) {
4873 o.null_opt_usize = try self.resolveValue(Value.fromInterned(try mod.intern(.{ .opt = .{
4874 .ty = try mod.intern(.{ .opt_type = .usize_type }),
4888 o.null_opt_usize = try self.resolveValue(Value.fromInterned(try pt.intern(.{ .opt = .{
4889 .ty = try pt.intern(.{ .opt_type = .usize_type }),
48754890 .val = .none,
48764891 } })));
48774892 }
......@@ -4880,7 +4895,7 @@ pub const FuncGen = struct {
48804895
48814896 fn genBody(self: *FuncGen, body: []const Air.Inst.Index) Error!void {
48824897 const o = self.dg.object;
4883 const mod = o.module;
4898 const mod = o.pt.zcu;
48844899 const ip = &mod.intern_pool;
48854900 const air_tags = self.air.instructions.items(.tag);
48864901 for (body, 0..) |inst, i| {
......@@ -5145,7 +5160,8 @@ pub const FuncGen = struct {
51455160
51465161 if (maybe_inline_func) |inline_func| {
51475162 const o = self.dg.object;
5148 const zcu = o.module;
5163 const pt = o.pt;
5164 const zcu = pt.zcu;
51495165
51505166 const func = zcu.funcInfo(inline_func);
51515167 const decl_index = func.owner_decl;
......@@ -5159,9 +5175,9 @@ pub const FuncGen = struct {
51595175 const line_number = decl.navSrcLine(zcu) + 1;
51605176 self.inlined = self.wip.debug_location;
51615177
5162 const fqn = try decl.fullyQualifiedName(zcu);
5178 const fqn = try decl.fullyQualifiedName(pt);
51635179
5164 const fn_ty = try zcu.funcType(.{
5180 const fn_ty = try pt.funcType(.{
51655181 .param_types = &.{},
51665182 .return_type = .void_type,
51675183 });
......@@ -5228,7 +5244,8 @@ pub const FuncGen = struct {
52285244 const extra = self.air.extraData(Air.Call, pl_op.payload);
52295245 const args: []const Air.Inst.Ref = @ptrCast(self.air.extra[extra.end..][0..extra.data.args_len]);
52305246 const o = self.dg.object;
5231 const mod = o.module;
5247 const pt = o.pt;
5248 const mod = pt.zcu;
52325249 const ip = &mod.intern_pool;
52335250 const callee_ty = self.typeOf(pl_op.operand);
52345251 const zig_fn_ty = switch (callee_ty.zigTypeTag(mod)) {
......@@ -5240,7 +5257,7 @@ pub const FuncGen = struct {
52405257 const return_type = Type.fromInterned(fn_info.return_type);
52415258 const llvm_fn = try self.resolveInst(pl_op.operand);
52425259 const target = mod.getTarget();
5243 const sret = firstParamSRet(fn_info, mod, target);
5260 const sret = firstParamSRet(fn_info, pt, target);
52445261
52455262 var llvm_args = std.ArrayList(Builder.Value).init(self.gpa);
52465263 defer llvm_args.deinit();
......@@ -5258,14 +5275,13 @@ pub const FuncGen = struct {
52585275 const llvm_ret_ty = try o.lowerType(return_type);
52595276 try attributes.addParamAttr(0, .{ .sret = llvm_ret_ty }, &o.builder);
52605277
5261 const alignment = return_type.abiAlignment(mod).toLlvm();
5278 const alignment = return_type.abiAlignment(pt).toLlvm();
52625279 const ret_ptr = try self.buildAllocaWorkaround(return_type, alignment);
52635280 try llvm_args.append(ret_ptr);
52645281 break :blk ret_ptr;
52655282 };
52665283
5267 const err_return_tracing = return_type.isError(mod) and
5268 o.module.comp.config.any_error_tracing;
5284 const err_return_tracing = return_type.isError(mod) and mod.comp.config.any_error_tracing;
52695285 if (err_return_tracing) {
52705286 assert(self.err_ret_trace != .none);
52715287 try llvm_args.append(self.err_ret_trace);
......@@ -5279,8 +5295,8 @@ pub const FuncGen = struct {
52795295 const param_ty = self.typeOf(arg);
52805296 const llvm_arg = try self.resolveInst(arg);
52815297 const llvm_param_ty = try o.lowerType(param_ty);
5282 if (isByRef(param_ty, mod)) {
5283 const alignment = param_ty.abiAlignment(mod).toLlvm();
5298 if (isByRef(param_ty, pt)) {
5299 const alignment = param_ty.abiAlignment(pt).toLlvm();
52845300 const loaded = try self.wip.load(.normal, llvm_param_ty, llvm_arg, alignment, "");
52855301 try llvm_args.append(loaded);
52865302 } else {
......@@ -5291,10 +5307,10 @@ pub const FuncGen = struct {
52915307 const arg = args[it.zig_index - 1];
52925308 const param_ty = self.typeOf(arg);
52935309 const llvm_arg = try self.resolveInst(arg);
5294 if (isByRef(param_ty, mod)) {
5310 if (isByRef(param_ty, pt)) {
52955311 try llvm_args.append(llvm_arg);
52965312 } else {
5297 const alignment = param_ty.abiAlignment(mod).toLlvm();
5313 const alignment = param_ty.abiAlignment(pt).toLlvm();
52985314 const param_llvm_ty = llvm_arg.typeOfWip(&self.wip);
52995315 const arg_ptr = try self.buildAlloca(param_llvm_ty, alignment);
53005316 _ = try self.wip.store(.normal, llvm_arg, arg_ptr, alignment);
......@@ -5306,10 +5322,10 @@ pub const FuncGen = struct {
53065322 const param_ty = self.typeOf(arg);
53075323 const llvm_arg = try self.resolveInst(arg);
53085324
5309 const alignment = param_ty.abiAlignment(mod).toLlvm();
5325 const alignment = param_ty.abiAlignment(pt).toLlvm();
53105326 const param_llvm_ty = try o.lowerType(param_ty);
53115327 const arg_ptr = try self.buildAllocaWorkaround(param_ty, alignment);
5312 if (isByRef(param_ty, mod)) {
5328 if (isByRef(param_ty, pt)) {
53135329 const loaded = try self.wip.load(.normal, param_llvm_ty, llvm_arg, alignment, "");
53145330 _ = try self.wip.store(.normal, loaded, arg_ptr, alignment);
53155331 } else {
......@@ -5321,16 +5337,16 @@ pub const FuncGen = struct {
53215337 const arg = args[it.zig_index - 1];
53225338 const param_ty = self.typeOf(arg);
53235339 const llvm_arg = try self.resolveInst(arg);
5324 const int_llvm_ty = try o.builder.intType(@intCast(param_ty.abiSize(mod) * 8));
5340 const int_llvm_ty = try o.builder.intType(@intCast(param_ty.abiSize(pt) * 8));
53255341
5326 if (isByRef(param_ty, mod)) {
5327 const alignment = param_ty.abiAlignment(mod).toLlvm();
5342 if (isByRef(param_ty, pt)) {
5343 const alignment = param_ty.abiAlignment(pt).toLlvm();
53285344 const loaded = try self.wip.load(.normal, int_llvm_ty, llvm_arg, alignment, "");
53295345 try llvm_args.append(loaded);
53305346 } else {
53315347 // LLVM does not allow bitcasting structs so we must allocate
53325348 // a local, store as one type, and then load as another type.
5333 const alignment = param_ty.abiAlignment(mod).toLlvm();
5349 const alignment = param_ty.abiAlignment(pt).toLlvm();
53345350 const int_ptr = try self.buildAllocaWorkaround(param_ty, alignment);
53355351 _ = try self.wip.store(.normal, llvm_arg, int_ptr, alignment);
53365352 const loaded = try self.wip.load(.normal, int_llvm_ty, int_ptr, alignment, "");
......@@ -5349,9 +5365,9 @@ pub const FuncGen = struct {
53495365 const param_ty = self.typeOf(arg);
53505366 const llvm_types = it.types_buffer[0..it.types_len];
53515367 const llvm_arg = try self.resolveInst(arg);
5352 const is_by_ref = isByRef(param_ty, mod);
5368 const is_by_ref = isByRef(param_ty, pt);
53535369 const arg_ptr = if (is_by_ref) llvm_arg else ptr: {
5354 const alignment = param_ty.abiAlignment(mod).toLlvm();
5370 const alignment = param_ty.abiAlignment(pt).toLlvm();
53555371 const ptr = try self.buildAlloca(llvm_arg.typeOfWip(&self.wip), alignment);
53565372 _ = try self.wip.store(.normal, llvm_arg, ptr, alignment);
53575373 break :ptr ptr;
......@@ -5377,8 +5393,8 @@ pub const FuncGen = struct {
53775393 const arg = args[it.zig_index - 1];
53785394 const arg_ty = self.typeOf(arg);
53795395 var llvm_arg = try self.resolveInst(arg);
5380 const alignment = arg_ty.abiAlignment(mod).toLlvm();
5381 if (!isByRef(arg_ty, mod)) {
5396 const alignment = arg_ty.abiAlignment(pt).toLlvm();
5397 if (!isByRef(arg_ty, pt)) {
53825398 const ptr = try self.buildAlloca(llvm_arg.typeOfWip(&self.wip), alignment);
53835399 _ = try self.wip.store(.normal, llvm_arg, ptr, alignment);
53845400 llvm_arg = ptr;
......@@ -5395,8 +5411,8 @@ pub const FuncGen = struct {
53955411 const arg = args[it.zig_index - 1];
53965412 const arg_ty = self.typeOf(arg);
53975413 var llvm_arg = try self.resolveInst(arg);
5398 const alignment = arg_ty.abiAlignment(mod).toLlvm();
5399 if (!isByRef(arg_ty, mod)) {
5414 const alignment = arg_ty.abiAlignment(pt).toLlvm();
5415 if (!isByRef(arg_ty, pt)) {
54005416 const ptr = try self.buildAlloca(llvm_arg.typeOfWip(&self.wip), alignment);
54015417 _ = try self.wip.store(.normal, llvm_arg, ptr, alignment);
54025418 llvm_arg = ptr;
......@@ -5418,7 +5434,7 @@ pub const FuncGen = struct {
54185434 .byval => {
54195435 const param_index = it.zig_index - 1;
54205436 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[param_index]);
5421 if (!isByRef(param_ty, mod)) {
5437 if (!isByRef(param_ty, pt)) {
54225438 try o.addByValParamAttrs(&attributes, param_ty, param_index, fn_info, it.llvm_index - 1);
54235439 }
54245440 },
......@@ -5426,7 +5442,7 @@ pub const FuncGen = struct {
54265442 const param_index = it.zig_index - 1;
54275443 const param_ty = Type.fromInterned(fn_info.param_types.get(ip)[param_index]);
54285444 const param_llvm_ty = try o.lowerType(param_ty);
5429 const alignment = param_ty.abiAlignment(mod).toLlvm();
5445 const alignment = param_ty.abiAlignment(pt).toLlvm();
54305446 try o.addByRefParamAttrs(&attributes, it.llvm_index - 1, alignment, it.byval_attr, param_llvm_ty);
54315447 },
54325448 .byref_mut => try attributes.addParamAttr(it.llvm_index - 1, .noundef, &o.builder),
......@@ -5460,7 +5476,7 @@ pub const FuncGen = struct {
54605476 const elem_align = (if (ptr_info.flags.alignment != .none)
54615477 @as(InternPool.Alignment, ptr_info.flags.alignment)
54625478 else
5463 Type.fromInterned(ptr_info.child).abiAlignment(mod).max(.@"1")).toLlvm();
5479 Type.fromInterned(ptr_info.child).abiAlignment(pt).max(.@"1")).toLlvm();
54645480 try attributes.addParamAttr(llvm_arg_i, .{ .@"align" = elem_align }, &o.builder);
54655481 },
54665482 };
......@@ -5485,17 +5501,17 @@ pub const FuncGen = struct {
54855501 return .none;
54865502 }
54875503
5488 if (self.liveness.isUnused(inst) or !return_type.hasRuntimeBitsIgnoreComptime(mod)) {
5504 if (self.liveness.isUnused(inst) or !return_type.hasRuntimeBitsIgnoreComptime(pt)) {
54895505 return .none;
54905506 }
54915507
54925508 const llvm_ret_ty = try o.lowerType(return_type);
54935509 if (ret_ptr) |rp| {
5494 if (isByRef(return_type, mod)) {
5510 if (isByRef(return_type, pt)) {
54955511 return rp;
54965512 } else {
54975513 // our by-ref status disagrees with sret so we must load.
5498 const return_alignment = return_type.abiAlignment(mod).toLlvm();
5514 const return_alignment = return_type.abiAlignment(pt).toLlvm();
54995515 return self.wip.load(.normal, llvm_ret_ty, rp, return_alignment, "");
55005516 }
55015517 }
......@@ -5506,19 +5522,19 @@ pub const FuncGen = struct {
55065522 // In this case the function return type is honoring the calling convention by having
55075523 // a different LLVM type than the usual one. We solve this here at the callsite
55085524 // by using our canonical type, then loading it if necessary.
5509 const alignment = return_type.abiAlignment(mod).toLlvm();
5525 const alignment = return_type.abiAlignment(pt).toLlvm();
55105526 const rp = try self.buildAlloca(abi_ret_ty, alignment);
55115527 _ = try self.wip.store(.normal, call, rp, alignment);
5512 return if (isByRef(return_type, mod))
5528 return if (isByRef(return_type, pt))
55135529 rp
55145530 else
55155531 try self.wip.load(.normal, llvm_ret_ty, rp, alignment, "");
55165532 }
55175533
5518 if (isByRef(return_type, mod)) {
5534 if (isByRef(return_type, pt)) {
55195535 // our by-ref status disagrees with sret so we must allocate, store,
55205536 // and return the allocation pointer.
5521 const alignment = return_type.abiAlignment(mod).toLlvm();
5537 const alignment = return_type.abiAlignment(pt).toLlvm();
55225538 const rp = try self.buildAlloca(llvm_ret_ty, alignment);
55235539 _ = try self.wip.store(.normal, call, rp, alignment);
55245540 return rp;
......@@ -5527,9 +5543,9 @@ pub const FuncGen = struct {
55275543 }
55285544 }
55295545
5530 fn buildSimplePanic(fg: *FuncGen, panic_id: Module.PanicId) !void {
5546 fn buildSimplePanic(fg: *FuncGen, panic_id: Zcu.PanicId) !void {
55315547 const o = fg.dg.object;
5532 const mod = o.module;
5548 const mod = o.pt.zcu;
55335549 const msg_decl_index = mod.panic_messages[@intFromEnum(panic_id)].unwrap().?;
55345550 const msg_decl = mod.declPtr(msg_decl_index);
55355551 const msg_len = msg_decl.typeOf(mod).childType(mod).arrayLen(mod);
......@@ -5567,15 +5583,16 @@ pub const FuncGen = struct {
55675583
55685584 fn airRet(self: *FuncGen, inst: Air.Inst.Index, safety: bool) !Builder.Value {
55695585 const o = self.dg.object;
5570 const mod = o.module;
5586 const pt = o.pt;
5587 const mod = pt.zcu;
55715588 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
55725589 const ret_ty = self.typeOf(un_op);
55735590
55745591 if (self.ret_ptr != .none) {
5575 const ptr_ty = try mod.singleMutPtrType(ret_ty);
5592 const ptr_ty = try pt.singleMutPtrType(ret_ty);
55765593
55775594 const operand = try self.resolveInst(un_op);
5578 const val_is_undef = if (try self.air.value(un_op, mod)) |val| val.isUndefDeep(mod) else false;
5595 const val_is_undef = if (try self.air.value(un_op, pt)) |val| val.isUndefDeep(mod) else false;
55795596 if (val_is_undef and safety) undef: {
55805597 const ptr_info = ptr_ty.ptrInfo(mod);
55815598 const needs_bitmask = (ptr_info.packed_offset.host_size != 0);
......@@ -5585,10 +5602,10 @@ pub const FuncGen = struct {
55855602 // https://github.com/ziglang/zig/issues/15337
55865603 break :undef;
55875604 }
5588 const len = try o.builder.intValue(try o.lowerType(Type.usize), ret_ty.abiSize(mod));
5605 const len = try o.builder.intValue(try o.lowerType(Type.usize), ret_ty.abiSize(pt));
55895606 _ = try self.wip.callMemSet(
55905607 self.ret_ptr,
5591 ptr_ty.ptrAlignment(mod).toLlvm(),
5608 ptr_ty.ptrAlignment(pt).toLlvm(),
55925609 try o.builder.intValue(.i8, 0xaa),
55935610 len,
55945611 if (ptr_ty.isVolatilePtr(mod)) .@"volatile" else .normal,
......@@ -5615,7 +5632,7 @@ pub const FuncGen = struct {
56155632 return .none;
56165633 }
56175634 const fn_info = mod.typeToFunc(self.dg.decl.typeOf(mod)).?;
5618 if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
5635 if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
56195636 if (Type.fromInterned(fn_info.return_type).isError(mod)) {
56205637 // Functions with an empty error set are emitted with an error code
56215638 // return type and return zero so they can be function pointers coerced
......@@ -5629,13 +5646,13 @@ pub const FuncGen = struct {
56295646
56305647 const abi_ret_ty = try lowerFnRetTy(o, fn_info);
56315648 const operand = try self.resolveInst(un_op);
5632 const val_is_undef = if (try self.air.value(un_op, mod)) |val| val.isUndefDeep(mod) else false;
5633 const alignment = ret_ty.abiAlignment(mod).toLlvm();
5649 const val_is_undef = if (try self.air.value(un_op, pt)) |val| val.isUndefDeep(mod) else false;
5650 const alignment = ret_ty.abiAlignment(pt).toLlvm();
56345651
56355652 if (val_is_undef and safety) {
56365653 const llvm_ret_ty = operand.typeOfWip(&self.wip);
56375654 const rp = try self.buildAlloca(llvm_ret_ty, alignment);
5638 const len = try o.builder.intValue(try o.lowerType(Type.usize), ret_ty.abiSize(mod));
5655 const len = try o.builder.intValue(try o.lowerType(Type.usize), ret_ty.abiSize(pt));
56395656 _ = try self.wip.callMemSet(
56405657 rp,
56415658 alignment,
......@@ -5651,7 +5668,7 @@ pub const FuncGen = struct {
56515668 return .none;
56525669 }
56535670
5654 if (isByRef(ret_ty, mod)) {
5671 if (isByRef(ret_ty, pt)) {
56555672 // operand is a pointer however self.ret_ptr is null so that means
56565673 // we need to return a value.
56575674 _ = try self.wip.ret(try self.wip.load(.normal, abi_ret_ty, operand, alignment, ""));
......@@ -5672,12 +5689,13 @@ pub const FuncGen = struct {
56725689
56735690 fn airRetLoad(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
56745691 const o = self.dg.object;
5675 const mod = o.module;
5692 const pt = o.pt;
5693 const mod = pt.zcu;
56765694 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
56775695 const ptr_ty = self.typeOf(un_op);
56785696 const ret_ty = ptr_ty.childType(mod);
56795697 const fn_info = mod.typeToFunc(self.dg.decl.typeOf(mod)).?;
5680 if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
5698 if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
56815699 if (Type.fromInterned(fn_info.return_type).isError(mod)) {
56825700 // Functions with an empty error set are emitted with an error code
56835701 // return type and return zero so they can be function pointers coerced
......@@ -5694,7 +5712,7 @@ pub const FuncGen = struct {
56945712 }
56955713 const ptr = try self.resolveInst(un_op);
56965714 const abi_ret_ty = try lowerFnRetTy(o, fn_info);
5697 const alignment = ret_ty.abiAlignment(mod).toLlvm();
5715 const alignment = ret_ty.abiAlignment(pt).toLlvm();
56985716 _ = try self.wip.ret(try self.wip.load(.normal, abi_ret_ty, ptr, alignment, ""));
56995717 return .none;
57005718 }
......@@ -5711,17 +5729,17 @@ pub const FuncGen = struct {
57115729
57125730 fn airCVaCopy(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
57135731 const o = self.dg.object;
5732 const pt = o.pt;
57145733 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
57155734 const src_list = try self.resolveInst(ty_op.operand);
57165735 const va_list_ty = ty_op.ty.toType();
57175736 const llvm_va_list_ty = try o.lowerType(va_list_ty);
5718 const mod = o.module;
57195737
5720 const result_alignment = va_list_ty.abiAlignment(mod).toLlvm();
5738 const result_alignment = va_list_ty.abiAlignment(pt).toLlvm();
57215739 const dest_list = try self.buildAllocaWorkaround(va_list_ty, result_alignment);
57225740
57235741 _ = try self.wip.callIntrinsic(.normal, .none, .va_copy, &.{}, &.{ dest_list, src_list }, "");
5724 return if (isByRef(va_list_ty, mod))
5742 return if (isByRef(va_list_ty, pt))
57255743 dest_list
57265744 else
57275745 try self.wip.load(.normal, llvm_va_list_ty, dest_list, result_alignment, "");
......@@ -5737,15 +5755,15 @@ pub const FuncGen = struct {
57375755
57385756 fn airCVaStart(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
57395757 const o = self.dg.object;
5740 const mod = o.module;
5758 const pt = o.pt;
57415759 const va_list_ty = self.typeOfIndex(inst);
57425760 const llvm_va_list_ty = try o.lowerType(va_list_ty);
57435761
5744 const result_alignment = va_list_ty.abiAlignment(mod).toLlvm();
5762 const result_alignment = va_list_ty.abiAlignment(pt).toLlvm();
57455763 const dest_list = try self.buildAllocaWorkaround(va_list_ty, result_alignment);
57465764
57475765 _ = try self.wip.callIntrinsic(.normal, .none, .va_start, &.{}, &.{dest_list}, "");
5748 return if (isByRef(va_list_ty, mod))
5766 return if (isByRef(va_list_ty, pt))
57495767 dest_list
57505768 else
57515769 try self.wip.load(.normal, llvm_va_list_ty, dest_list, result_alignment, "");
......@@ -5802,21 +5820,22 @@ pub const FuncGen = struct {
58025820 rhs: Builder.Value,
58035821 ) Allocator.Error!Builder.Value {
58045822 const o = self.dg.object;
5805 const mod = o.module;
5823 const pt = o.pt;
5824 const mod = pt.zcu;
58065825 const scalar_ty = operand_ty.scalarType(mod);
58075826 const int_ty = switch (scalar_ty.zigTypeTag(mod)) {
58085827 .Enum => scalar_ty.intTagType(mod),
58095828 .Int, .Bool, .Pointer, .ErrorSet => scalar_ty,
58105829 .Optional => blk: {
58115830 const payload_ty = operand_ty.optionalChild(mod);
5812 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod) or
5831 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt) or
58135832 operand_ty.optionalReprIsPayload(mod))
58145833 {
58155834 break :blk operand_ty;
58165835 }
58175836 // We need to emit instructions to check for equality/inequality
58185837 // of optionals that are not pointers.
5819 const is_by_ref = isByRef(scalar_ty, mod);
5838 const is_by_ref = isByRef(scalar_ty, pt);
58205839 const opt_llvm_ty = try o.lowerType(scalar_ty);
58215840 const lhs_non_null = try self.optCmpNull(.ne, opt_llvm_ty, lhs, is_by_ref);
58225841 const rhs_non_null = try self.optCmpNull(.ne, opt_llvm_ty, rhs, is_by_ref);
......@@ -5908,7 +5927,8 @@ pub const FuncGen = struct {
59085927 body: []const Air.Inst.Index,
59095928 ) !Builder.Value {
59105929 const o = self.dg.object;
5911 const mod = o.module;
5930 const pt = o.pt;
5931 const mod = pt.zcu;
59125932 const inst_ty = self.typeOfIndex(inst);
59135933
59145934 if (inst_ty.isNoReturn(mod)) {
......@@ -5916,7 +5936,7 @@ pub const FuncGen = struct {
59165936 return .none;
59175937 }
59185938
5919 const have_block_result = inst_ty.isFnOrHasRuntimeBitsIgnoreComptime(mod);
5939 const have_block_result = inst_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt);
59205940
59215941 var breaks: BreakList = if (have_block_result) .{ .list = .{} } else .{ .len = 0 };
59225942 defer if (have_block_result) breaks.list.deinit(self.gpa);
......@@ -5940,7 +5960,7 @@ pub const FuncGen = struct {
59405960 // a pointer to it. LLVM IR allows the call instruction to use function bodies instead
59415961 // of function pointers, however the phi makes it a runtime value and therefore
59425962 // the LLVM type has to be wrapped in a pointer.
5943 if (inst_ty.zigTypeTag(mod) == .Fn or isByRef(inst_ty, mod)) {
5963 if (inst_ty.zigTypeTag(mod) == .Fn or isByRef(inst_ty, pt)) {
59445964 break :ty .ptr;
59455965 }
59465966 break :ty raw_llvm_ty;
......@@ -5958,13 +5978,13 @@ pub const FuncGen = struct {
59585978
59595979 fn airBr(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
59605980 const o = self.dg.object;
5981 const pt = o.pt;
59615982 const branch = self.air.instructions.items(.data)[@intFromEnum(inst)].br;
59625983 const block = self.blocks.get(branch.block_inst).?;
59635984
59645985 // Add the values to the lists only if the break provides a value.
59655986 const operand_ty = self.typeOf(branch.operand);
5966 const mod = o.module;
5967 if (operand_ty.isFnOrHasRuntimeBitsIgnoreComptime(mod)) {
5987 if (operand_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt)) {
59685988 const val = try self.resolveInst(branch.operand);
59695989
59705990 // For the phi node, we need the basic blocks and the values of the
......@@ -5998,7 +6018,7 @@ pub const FuncGen = struct {
59986018
59996019 fn airTry(self: *FuncGen, body_tail: []const Air.Inst.Index) !Builder.Value {
60006020 const o = self.dg.object;
6001 const mod = o.module;
6021 const pt = o.pt;
60026022 const inst = body_tail[0];
60036023 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
60046024 const err_union = try self.resolveInst(pl_op.operand);
......@@ -6006,14 +6026,14 @@ pub const FuncGen = struct {
60066026 const body: []const Air.Inst.Index = @ptrCast(self.air.extra[extra.end..][0..extra.data.body_len]);
60076027 const err_union_ty = self.typeOf(pl_op.operand);
60086028 const payload_ty = self.typeOfIndex(inst);
6009 const can_elide_load = if (isByRef(payload_ty, mod)) self.canElideLoad(body_tail) else false;
6029 const can_elide_load = if (isByRef(payload_ty, pt)) self.canElideLoad(body_tail) else false;
60106030 const is_unused = self.liveness.isUnused(inst);
60116031 return lowerTry(self, err_union, body, err_union_ty, false, can_elide_load, is_unused);
60126032 }
60136033
60146034 fn airTryPtr(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
60156035 const o = self.dg.object;
6016 const mod = o.module;
6036 const mod = o.pt.zcu;
60176037 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
60186038 const extra = self.air.extraData(Air.TryPtr, ty_pl.payload);
60196039 const err_union_ptr = try self.resolveInst(extra.data.ptr);
......@@ -6033,9 +6053,10 @@ pub const FuncGen = struct {
60336053 is_unused: bool,
60346054 ) !Builder.Value {
60356055 const o = fg.dg.object;
6036 const mod = o.module;
6056 const pt = o.pt;
6057 const mod = pt.zcu;
60376058 const payload_ty = err_union_ty.errorUnionPayload(mod);
6038 const payload_has_bits = payload_ty.hasRuntimeBitsIgnoreComptime(mod);
6059 const payload_has_bits = payload_ty.hasRuntimeBitsIgnoreComptime(pt);
60396060 const err_union_llvm_ty = try o.lowerType(err_union_ty);
60406061 const error_type = try o.errorIntType();
60416062
......@@ -6048,8 +6069,8 @@ pub const FuncGen = struct {
60486069 else
60496070 err_union;
60506071 }
6051 const err_field_index = try errUnionErrorOffset(payload_ty, mod);
6052 if (operand_is_ptr or isByRef(err_union_ty, mod)) {
6072 const err_field_index = try errUnionErrorOffset(payload_ty, pt);
6073 if (operand_is_ptr or isByRef(err_union_ty, pt)) {
60536074 const err_field_ptr =
60546075 try fg.wip.gepStruct(err_union_llvm_ty, err_union, err_field_index, "");
60556076 // TODO add alignment to this load
......@@ -6077,13 +6098,13 @@ pub const FuncGen = struct {
60776098 }
60786099 if (is_unused) return .none;
60796100 if (!payload_has_bits) return if (operand_is_ptr) err_union else .none;
6080 const offset = try errUnionPayloadOffset(payload_ty, mod);
6101 const offset = try errUnionPayloadOffset(payload_ty, pt);
60816102 if (operand_is_ptr) {
60826103 return fg.wip.gepStruct(err_union_llvm_ty, err_union, offset, "");
6083 } else if (isByRef(err_union_ty, mod)) {
6104 } else if (isByRef(err_union_ty, pt)) {
60846105 const payload_ptr = try fg.wip.gepStruct(err_union_llvm_ty, err_union, offset, "");
6085 const payload_alignment = payload_ty.abiAlignment(mod).toLlvm();
6086 if (isByRef(payload_ty, mod)) {
6106 const payload_alignment = payload_ty.abiAlignment(pt).toLlvm();
6107 if (isByRef(payload_ty, pt)) {
60876108 if (can_elide_load)
60886109 return payload_ptr;
60896110
......@@ -6161,7 +6182,7 @@ pub const FuncGen = struct {
61616182
61626183 fn airLoop(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
61636184 const o = self.dg.object;
6164 const mod = o.module;
6185 const mod = o.pt.zcu;
61656186 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
61666187 const loop = self.air.extraData(Air.Block, ty_pl.payload);
61676188 const body: []const Air.Inst.Index = @ptrCast(self.air.extra[loop.end..][0..loop.data.body_len]);
......@@ -6185,7 +6206,8 @@ pub const FuncGen = struct {
61856206
61866207 fn airArrayToSlice(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
61876208 const o = self.dg.object;
6188 const mod = o.module;
6209 const pt = o.pt;
6210 const mod = pt.zcu;
61896211 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
61906212 const operand_ty = self.typeOf(ty_op.operand);
61916213 const array_ty = operand_ty.childType(mod);
......@@ -6193,7 +6215,7 @@ pub const FuncGen = struct {
61936215 const len = try o.builder.intValue(llvm_usize, array_ty.arrayLen(mod));
61946216 const slice_llvm_ty = try o.lowerType(self.typeOfIndex(inst));
61956217 const operand = try self.resolveInst(ty_op.operand);
6196 if (!array_ty.hasRuntimeBitsIgnoreComptime(mod))
6218 if (!array_ty.hasRuntimeBitsIgnoreComptime(pt))
61976219 return self.wip.buildAggregate(slice_llvm_ty, &.{ operand, len }, "");
61986220 const ptr = try self.wip.gep(.inbounds, try o.lowerType(array_ty), operand, &.{
61996221 try o.builder.intValue(llvm_usize, 0), try o.builder.intValue(llvm_usize, 0),
......@@ -6203,7 +6225,8 @@ pub const FuncGen = struct {
62036225
62046226 fn airFloatFromInt(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
62056227 const o = self.dg.object;
6206 const mod = o.module;
6228 const pt = o.pt;
6229 const mod = pt.zcu;
62076230 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
62086231
62096232 const workaround_operand = try self.resolveInst(ty_op.operand);
......@@ -6213,7 +6236,7 @@ pub const FuncGen = struct {
62136236
62146237 const operand = o: {
62156238 // Work around LLVM bug. See https://github.com/ziglang/zig/issues/17381.
6216 const bit_size = operand_scalar_ty.bitSize(mod);
6239 const bit_size = operand_scalar_ty.bitSize(pt);
62176240 for ([_]u8{ 8, 16, 32, 64, 128 }) |b| {
62186241 if (bit_size < b) {
62196242 break :o try self.wip.cast(
......@@ -6241,7 +6264,7 @@ pub const FuncGen = struct {
62416264 "",
62426265 );
62436266
6244 const rt_int_bits = compilerRtIntBits(@intCast(operand_scalar_ty.bitSize(mod)));
6267 const rt_int_bits = compilerRtIntBits(@intCast(operand_scalar_ty.bitSize(pt)));
62456268 const rt_int_ty = try o.builder.intType(rt_int_bits);
62466269 var extended = try self.wip.conv(
62476270 if (is_signed_int) .signed else .unsigned,
......@@ -6287,7 +6310,8 @@ pub const FuncGen = struct {
62876310 _ = fast;
62886311
62896312 const o = self.dg.object;
6290 const mod = o.module;
6313 const pt = o.pt;
6314 const mod = pt.zcu;
62916315 const target = mod.getTarget();
62926316 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
62936317
......@@ -6309,7 +6333,7 @@ pub const FuncGen = struct {
63096333 );
63106334 }
63116335
6312 const rt_int_bits = compilerRtIntBits(@intCast(dest_scalar_ty.bitSize(mod)));
6336 const rt_int_bits = compilerRtIntBits(@intCast(dest_scalar_ty.bitSize(pt)));
63136337 const ret_ty = try o.builder.intType(rt_int_bits);
63146338 const libc_ret_ty = if (rt_int_bits == 128 and (target.os.tag == .windows and target.cpu.arch == .x86_64)) b: {
63156339 // On Windows x86-64, "ti" functions must use Vector(2, u64) instead of the standard
......@@ -6348,19 +6372,20 @@ pub const FuncGen = struct {
63486372
63496373 fn sliceOrArrayPtr(fg: *FuncGen, ptr: Builder.Value, ty: Type) Allocator.Error!Builder.Value {
63506374 const o = fg.dg.object;
6351 const mod = o.module;
6375 const mod = o.pt.zcu;
63526376 return if (ty.isSlice(mod)) fg.wip.extractValue(ptr, &.{0}, "") else ptr;
63536377 }
63546378
63556379 fn sliceOrArrayLenInBytes(fg: *FuncGen, ptr: Builder.Value, ty: Type) Allocator.Error!Builder.Value {
63566380 const o = fg.dg.object;
6357 const mod = o.module;
6381 const pt = o.pt;
6382 const mod = pt.zcu;
63586383 const llvm_usize = try o.lowerType(Type.usize);
63596384 switch (ty.ptrSize(mod)) {
63606385 .Slice => {
63616386 const len = try fg.wip.extractValue(ptr, &.{1}, "");
63626387 const elem_ty = ty.childType(mod);
6363 const abi_size = elem_ty.abiSize(mod);
6388 const abi_size = elem_ty.abiSize(pt);
63646389 if (abi_size == 1) return len;
63656390 const abi_size_llvm_val = try o.builder.intValue(llvm_usize, abi_size);
63666391 return fg.wip.bin(.@"mul nuw", len, abi_size_llvm_val, "");
......@@ -6368,7 +6393,7 @@ pub const FuncGen = struct {
63686393 .One => {
63696394 const array_ty = ty.childType(mod);
63706395 const elem_ty = array_ty.childType(mod);
6371 const abi_size = elem_ty.abiSize(mod);
6396 const abi_size = elem_ty.abiSize(pt);
63726397 return o.builder.intValue(llvm_usize, array_ty.arrayLen(mod) * abi_size);
63736398 },
63746399 .Many, .C => unreachable,
......@@ -6383,7 +6408,7 @@ pub const FuncGen = struct {
63836408
63846409 fn airPtrSliceFieldPtr(self: *FuncGen, inst: Air.Inst.Index, index: c_uint) !Builder.Value {
63856410 const o = self.dg.object;
6386 const mod = o.module;
6411 const mod = o.pt.zcu;
63876412 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
63886413 const slice_ptr = try self.resolveInst(ty_op.operand);
63896414 const slice_ptr_ty = self.typeOf(ty_op.operand);
......@@ -6394,7 +6419,8 @@ pub const FuncGen = struct {
63946419
63956420 fn airSliceElemVal(self: *FuncGen, body_tail: []const Air.Inst.Index) !Builder.Value {
63966421 const o = self.dg.object;
6397 const mod = o.module;
6422 const pt = o.pt;
6423 const mod = pt.zcu;
63986424 const inst = body_tail[0];
63996425 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
64006426 const slice_ty = self.typeOf(bin_op.lhs);
......@@ -6404,11 +6430,11 @@ pub const FuncGen = struct {
64046430 const llvm_elem_ty = try o.lowerPtrElemTy(elem_ty);
64056431 const base_ptr = try self.wip.extractValue(slice, &.{0}, "");
64066432 const ptr = try self.wip.gep(.inbounds, llvm_elem_ty, base_ptr, &.{index}, "");
6407 if (isByRef(elem_ty, mod)) {
6433 if (isByRef(elem_ty, pt)) {
64086434 if (self.canElideLoad(body_tail))
64096435 return ptr;
64106436
6411 const elem_alignment = elem_ty.abiAlignment(mod).toLlvm();
6437 const elem_alignment = elem_ty.abiAlignment(pt).toLlvm();
64126438 return self.loadByRef(ptr, elem_ty, elem_alignment, .normal);
64136439 }
64146440
......@@ -6417,7 +6443,7 @@ pub const FuncGen = struct {
64176443
64186444 fn airSliceElemPtr(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
64196445 const o = self.dg.object;
6420 const mod = o.module;
6446 const mod = o.pt.zcu;
64216447 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
64226448 const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data;
64236449 const slice_ty = self.typeOf(bin_op.lhs);
......@@ -6431,7 +6457,8 @@ pub const FuncGen = struct {
64316457
64326458 fn airArrayElemVal(self: *FuncGen, body_tail: []const Air.Inst.Index) !Builder.Value {
64336459 const o = self.dg.object;
6434 const mod = o.module;
6460 const pt = o.pt;
6461 const mod = pt.zcu;
64356462 const inst = body_tail[0];
64366463
64376464 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
......@@ -6440,15 +6467,15 @@ pub const FuncGen = struct {
64406467 const rhs = try self.resolveInst(bin_op.rhs);
64416468 const array_llvm_ty = try o.lowerType(array_ty);
64426469 const elem_ty = array_ty.childType(mod);
6443 if (isByRef(array_ty, mod)) {
6470 if (isByRef(array_ty, pt)) {
64446471 const indices: [2]Builder.Value = .{
64456472 try o.builder.intValue(try o.lowerType(Type.usize), 0), rhs,
64466473 };
6447 if (isByRef(elem_ty, mod)) {
6474 if (isByRef(elem_ty, pt)) {
64486475 const elem_ptr =
64496476 try self.wip.gep(.inbounds, array_llvm_ty, array_llvm_val, &indices, "");
64506477 if (canElideLoad(self, body_tail)) return elem_ptr;
6451 const elem_alignment = elem_ty.abiAlignment(mod).toLlvm();
6478 const elem_alignment = elem_ty.abiAlignment(pt).toLlvm();
64526479 return self.loadByRef(elem_ptr, elem_ty, elem_alignment, .normal);
64536480 } else {
64546481 const elem_ptr =
......@@ -6463,7 +6490,8 @@ pub const FuncGen = struct {
64636490
64646491 fn airPtrElemVal(self: *FuncGen, body_tail: []const Air.Inst.Index) !Builder.Value {
64656492 const o = self.dg.object;
6466 const mod = o.module;
6493 const pt = o.pt;
6494 const mod = pt.zcu;
64676495 const inst = body_tail[0];
64686496 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
64696497 const ptr_ty = self.typeOf(bin_op.lhs);
......@@ -6477,9 +6505,9 @@ pub const FuncGen = struct {
64776505 &.{ try o.builder.intValue(try o.lowerType(Type.usize), 0), rhs }
64786506 else
64796507 &.{rhs}, "");
6480 if (isByRef(elem_ty, mod)) {
6508 if (isByRef(elem_ty, pt)) {
64816509 if (self.canElideLoad(body_tail)) return ptr;
6482 const elem_alignment = elem_ty.abiAlignment(mod).toLlvm();
6510 const elem_alignment = elem_ty.abiAlignment(pt).toLlvm();
64836511 return self.loadByRef(ptr, elem_ty, elem_alignment, .normal);
64846512 }
64856513
......@@ -6488,12 +6516,13 @@ pub const FuncGen = struct {
64886516
64896517 fn airPtrElemPtr(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
64906518 const o = self.dg.object;
6491 const mod = o.module;
6519 const pt = o.pt;
6520 const mod = pt.zcu;
64926521 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
64936522 const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data;
64946523 const ptr_ty = self.typeOf(bin_op.lhs);
64956524 const elem_ty = ptr_ty.childType(mod);
6496 if (!elem_ty.hasRuntimeBitsIgnoreComptime(mod)) return self.resolveInst(bin_op.lhs);
6525 if (!elem_ty.hasRuntimeBitsIgnoreComptime(pt)) return self.resolveInst(bin_op.lhs);
64976526
64986527 const base_ptr = try self.resolveInst(bin_op.lhs);
64996528 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -6530,7 +6559,8 @@ pub const FuncGen = struct {
65306559
65316560 fn airStructFieldVal(self: *FuncGen, body_tail: []const Air.Inst.Index) !Builder.Value {
65326561 const o = self.dg.object;
6533 const mod = o.module;
6562 const pt = o.pt;
6563 const mod = pt.zcu;
65346564 const inst = body_tail[0];
65356565 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
65366566 const struct_field = self.air.extraData(Air.StructField, ty_pl.payload).data;
......@@ -6538,27 +6568,27 @@ pub const FuncGen = struct {
65386568 const struct_llvm_val = try self.resolveInst(struct_field.struct_operand);
65396569 const field_index = struct_field.field_index;
65406570 const field_ty = struct_ty.structFieldType(field_index, mod);
6541 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) return .none;
6571 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) return .none;
65426572
6543 if (!isByRef(struct_ty, mod)) {
6544 assert(!isByRef(field_ty, mod));
6573 if (!isByRef(struct_ty, pt)) {
6574 assert(!isByRef(field_ty, pt));
65456575 switch (struct_ty.zigTypeTag(mod)) {
65466576 .Struct => switch (struct_ty.containerLayout(mod)) {
65476577 .@"packed" => {
65486578 const struct_type = mod.typeToStruct(struct_ty).?;
6549 const bit_offset = mod.structPackedFieldBitOffset(struct_type, field_index);
6579 const bit_offset = pt.structPackedFieldBitOffset(struct_type, field_index);
65506580 const containing_int = struct_llvm_val;
65516581 const shift_amt =
65526582 try o.builder.intValue(containing_int.typeOfWip(&self.wip), bit_offset);
65536583 const shifted_value = try self.wip.bin(.lshr, containing_int, shift_amt, "");
65546584 const elem_llvm_ty = try o.lowerType(field_ty);
65556585 if (field_ty.zigTypeTag(mod) == .Float or field_ty.zigTypeTag(mod) == .Vector) {
6556 const same_size_int = try o.builder.intType(@intCast(field_ty.bitSize(mod)));
6586 const same_size_int = try o.builder.intType(@intCast(field_ty.bitSize(pt)));
65576587 const truncated_int =
65586588 try self.wip.cast(.trunc, shifted_value, same_size_int, "");
65596589 return self.wip.cast(.bitcast, truncated_int, elem_llvm_ty, "");
65606590 } else if (field_ty.isPtrAtRuntime(mod)) {
6561 const same_size_int = try o.builder.intType(@intCast(field_ty.bitSize(mod)));
6591 const same_size_int = try o.builder.intType(@intCast(field_ty.bitSize(pt)));
65626592 const truncated_int =
65636593 try self.wip.cast(.trunc, shifted_value, same_size_int, "");
65646594 return self.wip.cast(.inttoptr, truncated_int, elem_llvm_ty, "");
......@@ -6575,12 +6605,12 @@ pub const FuncGen = struct {
65756605 const containing_int = struct_llvm_val;
65766606 const elem_llvm_ty = try o.lowerType(field_ty);
65776607 if (field_ty.zigTypeTag(mod) == .Float or field_ty.zigTypeTag(mod) == .Vector) {
6578 const same_size_int = try o.builder.intType(@intCast(field_ty.bitSize(mod)));
6608 const same_size_int = try o.builder.intType(@intCast(field_ty.bitSize(pt)));
65796609 const truncated_int =
65806610 try self.wip.cast(.trunc, containing_int, same_size_int, "");
65816611 return self.wip.cast(.bitcast, truncated_int, elem_llvm_ty, "");
65826612 } else if (field_ty.isPtrAtRuntime(mod)) {
6583 const same_size_int = try o.builder.intType(@intCast(field_ty.bitSize(mod)));
6613 const same_size_int = try o.builder.intType(@intCast(field_ty.bitSize(pt)));
65846614 const truncated_int =
65856615 try self.wip.cast(.trunc, containing_int, same_size_int, "");
65866616 return self.wip.cast(.inttoptr, truncated_int, elem_llvm_ty, "");
......@@ -6599,12 +6629,12 @@ pub const FuncGen = struct {
65996629 const llvm_field_index = o.llvmFieldIndex(struct_ty, field_index).?;
66006630 const field_ptr =
66016631 try self.wip.gepStruct(struct_llvm_ty, struct_llvm_val, llvm_field_index, "");
6602 const alignment = struct_ty.structFieldAlign(field_index, mod);
6603 const field_ptr_ty = try mod.ptrType(.{
6632 const alignment = struct_ty.structFieldAlign(field_index, pt);
6633 const field_ptr_ty = try pt.ptrType(.{
66046634 .child = field_ty.toIntern(),
66056635 .flags = .{ .alignment = alignment },
66066636 });
6607 if (isByRef(field_ty, mod)) {
6637 if (isByRef(field_ty, pt)) {
66086638 if (canElideLoad(self, body_tail))
66096639 return field_ptr;
66106640
......@@ -6617,12 +6647,12 @@ pub const FuncGen = struct {
66176647 },
66186648 .Union => {
66196649 const union_llvm_ty = try o.lowerType(struct_ty);
6620 const layout = struct_ty.unionGetLayout(mod);
6650 const layout = struct_ty.unionGetLayout(pt);
66216651 const payload_index = @intFromBool(layout.tag_align.compare(.gte, layout.payload_align));
66226652 const field_ptr =
66236653 try self.wip.gepStruct(union_llvm_ty, struct_llvm_val, payload_index, "");
66246654 const payload_alignment = layout.payload_align.toLlvm();
6625 if (isByRef(field_ty, mod)) {
6655 if (isByRef(field_ty, pt)) {
66266656 if (canElideLoad(self, body_tail)) return field_ptr;
66276657 return self.loadByRef(field_ptr, field_ty, payload_alignment, .normal);
66286658 } else {
......@@ -6635,14 +6665,15 @@ pub const FuncGen = struct {
66356665
66366666 fn airFieldParentPtr(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
66376667 const o = self.dg.object;
6638 const mod = o.module;
6668 const pt = o.pt;
6669 const mod = pt.zcu;
66396670 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
66406671 const extra = self.air.extraData(Air.FieldParentPtr, ty_pl.payload).data;
66416672
66426673 const field_ptr = try self.resolveInst(extra.field_ptr);
66436674
66446675 const parent_ty = ty_pl.ty.toType().childType(mod);
6645 const field_offset = parent_ty.structFieldOffset(extra.field_index, mod);
6676 const field_offset = parent_ty.structFieldOffset(extra.field_index, pt);
66466677 if (field_offset == 0) return field_ptr;
66476678
66486679 const res_ty = try o.lowerType(ty_pl.ty.toType());
......@@ -6696,7 +6727,7 @@ pub const FuncGen = struct {
66966727
66976728 fn airDbgVarPtr(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
66986729 const o = self.dg.object;
6699 const mod = o.module;
6730 const mod = o.pt.zcu;
67006731 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
67016732 const operand = try self.resolveInst(pl_op.operand);
67026733 const name = self.air.nullTerminatedString(pl_op.payload);
......@@ -6743,9 +6774,9 @@ pub const FuncGen = struct {
67436774 try o.lowerDebugType(operand_ty),
67446775 );
67456776
6746 const zcu = o.module;
6777 const pt = o.pt;
67476778 const owner_mod = self.dg.ownerModule();
6748 if (isByRef(operand_ty, zcu)) {
6779 if (isByRef(operand_ty, pt)) {
67496780 _ = try self.wip.callIntrinsic(
67506781 .normal,
67516782 .none,
......@@ -6759,7 +6790,7 @@ pub const FuncGen = struct {
67596790 "",
67606791 );
67616792 } else if (owner_mod.optimize_mode == .Debug) {
6762 const alignment = operand_ty.abiAlignment(zcu).toLlvm();
6793 const alignment = operand_ty.abiAlignment(pt).toLlvm();
67636794 const alloca = try self.buildAlloca(operand.typeOfWip(&self.wip), alignment);
67646795 _ = try self.wip.store(.normal, operand, alloca, alignment);
67656796 _ = try self.wip.callIntrinsic(
......@@ -6830,7 +6861,8 @@ pub const FuncGen = struct {
68306861 // This stores whether we need to add an elementtype attribute and
68316862 // if so, the element type itself.
68326863 const llvm_param_attrs = try arena.alloc(Builder.Type, max_param_count);
6833 const mod = o.module;
6864 const pt = o.pt;
6865 const mod = pt.zcu;
68346866 const target = mod.getTarget();
68356867
68366868 var llvm_ret_i: usize = 0;
......@@ -6930,13 +6962,13 @@ pub const FuncGen = struct {
69306962
69316963 const arg_llvm_value = try self.resolveInst(input);
69326964 const arg_ty = self.typeOf(input);
6933 const is_by_ref = isByRef(arg_ty, mod);
6965 const is_by_ref = isByRef(arg_ty, pt);
69346966 if (is_by_ref) {
69356967 if (constraintAllowsMemory(constraint)) {
69366968 llvm_param_values[llvm_param_i] = arg_llvm_value;
69376969 llvm_param_types[llvm_param_i] = arg_llvm_value.typeOfWip(&self.wip);
69386970 } else {
6939 const alignment = arg_ty.abiAlignment(mod).toLlvm();
6971 const alignment = arg_ty.abiAlignment(pt).toLlvm();
69406972 const arg_llvm_ty = try o.lowerType(arg_ty);
69416973 const load_inst =
69426974 try self.wip.load(.normal, arg_llvm_ty, arg_llvm_value, alignment, "");
......@@ -6948,7 +6980,7 @@ pub const FuncGen = struct {
69486980 llvm_param_values[llvm_param_i] = arg_llvm_value;
69496981 llvm_param_types[llvm_param_i] = arg_llvm_value.typeOfWip(&self.wip);
69506982 } else {
6951 const alignment = arg_ty.abiAlignment(mod).toLlvm();
6983 const alignment = arg_ty.abiAlignment(pt).toLlvm();
69526984 const arg_ptr = try self.buildAlloca(arg_llvm_value.typeOfWip(&self.wip), alignment);
69536985 _ = try self.wip.store(.normal, arg_llvm_value, arg_ptr, alignment);
69546986 llvm_param_values[llvm_param_i] = arg_ptr;
......@@ -7000,7 +7032,7 @@ pub const FuncGen = struct {
70007032 llvm_param_values[llvm_param_i] = llvm_rw_val;
70017033 llvm_param_types[llvm_param_i] = llvm_rw_val.typeOfWip(&self.wip);
70027034 } else {
7003 const alignment = rw_ty.abiAlignment(mod).toLlvm();
7035 const alignment = rw_ty.abiAlignment(pt).toLlvm();
70047036 const loaded = try self.wip.load(.normal, llvm_elem_ty, llvm_rw_val, alignment, "");
70057037 llvm_param_values[llvm_param_i] = loaded;
70067038 llvm_param_types[llvm_param_i] = llvm_elem_ty;
......@@ -7161,7 +7193,7 @@ pub const FuncGen = struct {
71617193 const output_ptr = try self.resolveInst(output);
71627194 const output_ptr_ty = self.typeOf(output);
71637195
7164 const alignment = output_ptr_ty.ptrAlignment(mod).toLlvm();
7196 const alignment = output_ptr_ty.ptrAlignment(pt).toLlvm();
71657197 _ = try self.wip.store(.normal, output_value, output_ptr, alignment);
71667198 } else {
71677199 ret_val = output_value;
......@@ -7179,7 +7211,8 @@ pub const FuncGen = struct {
71797211 cond: Builder.IntegerCondition,
71807212 ) !Builder.Value {
71817213 const o = self.dg.object;
7182 const mod = o.module;
7214 const pt = o.pt;
7215 const mod = pt.zcu;
71837216 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
71847217 const operand = try self.resolveInst(un_op);
71857218 const operand_ty = self.typeOf(un_op);
......@@ -7204,7 +7237,7 @@ pub const FuncGen = struct {
72047237
72057238 comptime assert(optional_layout_version == 3);
72067239
7207 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
7240 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
72087241 const loaded = if (operand_is_ptr)
72097242 try self.wip.load(.normal, optional_llvm_ty, operand, .default, "")
72107243 else
......@@ -7212,7 +7245,7 @@ pub const FuncGen = struct {
72127245 return self.wip.icmp(cond, loaded, try o.builder.intValue(.i8, 0), "");
72137246 }
72147247
7215 const is_by_ref = operand_is_ptr or isByRef(optional_ty, mod);
7248 const is_by_ref = operand_is_ptr or isByRef(optional_ty, pt);
72167249 return self.optCmpNull(cond, optional_llvm_ty, operand, is_by_ref);
72177250 }
72187251
......@@ -7223,7 +7256,8 @@ pub const FuncGen = struct {
72237256 operand_is_ptr: bool,
72247257 ) !Builder.Value {
72257258 const o = self.dg.object;
7226 const mod = o.module;
7259 const pt = o.pt;
7260 const mod = pt.zcu;
72277261 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
72287262 const operand = try self.resolveInst(un_op);
72297263 const operand_ty = self.typeOf(un_op);
......@@ -7241,7 +7275,7 @@ pub const FuncGen = struct {
72417275 return val.toValue();
72427276 }
72437277
7244 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
7278 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
72457279 const loaded = if (operand_is_ptr)
72467280 try self.wip.load(.normal, try o.lowerType(err_union_ty), operand, .default, "")
72477281 else
......@@ -7249,9 +7283,9 @@ pub const FuncGen = struct {
72497283 return self.wip.icmp(cond, loaded, zero, "");
72507284 }
72517285
7252 const err_field_index = try errUnionErrorOffset(payload_ty, mod);
7286 const err_field_index = try errUnionErrorOffset(payload_ty, pt);
72537287
7254 const loaded = if (operand_is_ptr or isByRef(err_union_ty, mod)) loaded: {
7288 const loaded = if (operand_is_ptr or isByRef(err_union_ty, pt)) loaded: {
72557289 const err_union_llvm_ty = try o.lowerType(err_union_ty);
72567290 const err_field_ptr =
72577291 try self.wip.gepStruct(err_union_llvm_ty, operand, err_field_index, "");
......@@ -7262,12 +7296,13 @@ pub const FuncGen = struct {
72627296
72637297 fn airOptionalPayloadPtr(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
72647298 const o = self.dg.object;
7265 const mod = o.module;
7299 const pt = o.pt;
7300 const mod = pt.zcu;
72667301 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
72677302 const operand = try self.resolveInst(ty_op.operand);
72687303 const optional_ty = self.typeOf(ty_op.operand).childType(mod);
72697304 const payload_ty = optional_ty.optionalChild(mod);
7270 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
7305 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
72717306 // We have a pointer to a zero-bit value and we need to return
72727307 // a pointer to a zero-bit value.
72737308 return operand;
......@@ -7283,13 +7318,14 @@ pub const FuncGen = struct {
72837318 comptime assert(optional_layout_version == 3);
72847319
72857320 const o = self.dg.object;
7286 const mod = o.module;
7321 const pt = o.pt;
7322 const mod = pt.zcu;
72877323 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
72887324 const operand = try self.resolveInst(ty_op.operand);
72897325 const optional_ty = self.typeOf(ty_op.operand).childType(mod);
72907326 const payload_ty = optional_ty.optionalChild(mod);
72917327 const non_null_bit = try o.builder.intValue(.i8, 1);
7292 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
7328 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
72937329 // We have a pointer to a i8. We need to set it to 1 and then return the same pointer.
72947330 _ = try self.wip.store(.normal, non_null_bit, operand, .default);
72957331 return operand;
......@@ -7314,13 +7350,14 @@ pub const FuncGen = struct {
73147350
73157351 fn airOptionalPayload(self: *FuncGen, body_tail: []const Air.Inst.Index) !Builder.Value {
73167352 const o = self.dg.object;
7317 const mod = o.module;
7353 const pt = o.pt;
7354 const mod = pt.zcu;
73187355 const inst = body_tail[0];
73197356 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
73207357 const operand = try self.resolveInst(ty_op.operand);
73217358 const optional_ty = self.typeOf(ty_op.operand);
73227359 const payload_ty = self.typeOfIndex(inst);
7323 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) return .none;
7360 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) return .none;
73247361
73257362 if (optional_ty.optionalReprIsPayload(mod)) {
73267363 // Payload value is the same as the optional value.
......@@ -7328,7 +7365,7 @@ pub const FuncGen = struct {
73287365 }
73297366
73307367 const opt_llvm_ty = try o.lowerType(optional_ty);
7331 const can_elide_load = if (isByRef(payload_ty, mod)) self.canElideLoad(body_tail) else false;
7368 const can_elide_load = if (isByRef(payload_ty, pt)) self.canElideLoad(body_tail) else false;
73327369 return self.optPayloadHandle(opt_llvm_ty, operand, optional_ty, can_elide_load);
73337370 }
73347371
......@@ -7338,7 +7375,8 @@ pub const FuncGen = struct {
73387375 operand_is_ptr: bool,
73397376 ) !Builder.Value {
73407377 const o = self.dg.object;
7341 const mod = o.module;
7378 const pt = o.pt;
7379 const mod = pt.zcu;
73427380 const inst = body_tail[0];
73437381 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
73447382 const operand = try self.resolveInst(ty_op.operand);
......@@ -7347,17 +7385,17 @@ pub const FuncGen = struct {
73477385 const result_ty = self.typeOfIndex(inst);
73487386 const payload_ty = if (operand_is_ptr) result_ty.childType(mod) else result_ty;
73497387
7350 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
7388 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
73517389 return if (operand_is_ptr) operand else .none;
73527390 }
7353 const offset = try errUnionPayloadOffset(payload_ty, mod);
7391 const offset = try errUnionPayloadOffset(payload_ty, pt);
73547392 const err_union_llvm_ty = try o.lowerType(err_union_ty);
73557393 if (operand_is_ptr) {
73567394 return self.wip.gepStruct(err_union_llvm_ty, operand, offset, "");
7357 } else if (isByRef(err_union_ty, mod)) {
7358 const payload_alignment = payload_ty.abiAlignment(mod).toLlvm();
7395 } else if (isByRef(err_union_ty, pt)) {
7396 const payload_alignment = payload_ty.abiAlignment(pt).toLlvm();
73597397 const payload_ptr = try self.wip.gepStruct(err_union_llvm_ty, operand, offset, "");
7360 if (isByRef(payload_ty, mod)) {
7398 if (isByRef(payload_ty, pt)) {
73617399 if (self.canElideLoad(body_tail)) return payload_ptr;
73627400 return self.loadByRef(payload_ptr, payload_ty, payload_alignment, .normal);
73637401 }
......@@ -7373,7 +7411,8 @@ pub const FuncGen = struct {
73737411 operand_is_ptr: bool,
73747412 ) !Builder.Value {
73757413 const o = self.dg.object;
7376 const mod = o.module;
7414 const pt = o.pt;
7415 const mod = pt.zcu;
73777416 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
73787417 const operand = try self.resolveInst(ty_op.operand);
73797418 const operand_ty = self.typeOf(ty_op.operand);
......@@ -7388,14 +7427,14 @@ pub const FuncGen = struct {
73887427 }
73897428
73907429 const payload_ty = err_union_ty.errorUnionPayload(mod);
7391 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
7430 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
73927431 if (!operand_is_ptr) return operand;
73937432 return self.wip.load(.normal, error_type, operand, .default, "");
73947433 }
73957434
7396 const offset = try errUnionErrorOffset(payload_ty, mod);
7435 const offset = try errUnionErrorOffset(payload_ty, pt);
73977436
7398 if (operand_is_ptr or isByRef(err_union_ty, mod)) {
7437 if (operand_is_ptr or isByRef(err_union_ty, pt)) {
73997438 const err_union_llvm_ty = try o.lowerType(err_union_ty);
74007439 const err_field_ptr = try self.wip.gepStruct(err_union_llvm_ty, operand, offset, "");
74017440 return self.wip.load(.normal, error_type, err_field_ptr, .default, "");
......@@ -7406,22 +7445,23 @@ pub const FuncGen = struct {
74067445
74077446 fn airErrUnionPayloadPtrSet(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
74087447 const o = self.dg.object;
7409 const mod = o.module;
7448 const pt = o.pt;
7449 const mod = pt.zcu;
74107450 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
74117451 const operand = try self.resolveInst(ty_op.operand);
74127452 const err_union_ty = self.typeOf(ty_op.operand).childType(mod);
74137453
74147454 const payload_ty = err_union_ty.errorUnionPayload(mod);
74157455 const non_error_val = try o.builder.intValue(try o.errorIntType(), 0);
7416 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
7456 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
74177457 _ = try self.wip.store(.normal, non_error_val, operand, .default);
74187458 return operand;
74197459 }
74207460 const err_union_llvm_ty = try o.lowerType(err_union_ty);
74217461 {
7422 const err_int_ty = try mod.errorIntType();
7423 const error_alignment = err_int_ty.abiAlignment(mod).toLlvm();
7424 const error_offset = try errUnionErrorOffset(payload_ty, mod);
7462 const err_int_ty = try pt.errorIntType();
7463 const error_alignment = err_int_ty.abiAlignment(pt).toLlvm();
7464 const error_offset = try errUnionErrorOffset(payload_ty, pt);
74257465 // First set the non-error value.
74267466 const non_null_ptr = try self.wip.gepStruct(err_union_llvm_ty, operand, error_offset, "");
74277467 _ = try self.wip.store(.normal, non_error_val, non_null_ptr, error_alignment);
......@@ -7429,7 +7469,7 @@ pub const FuncGen = struct {
74297469 // Then return the payload pointer (only if it is used).
74307470 if (self.liveness.isUnused(inst)) return .none;
74317471
7432 const payload_offset = try errUnionPayloadOffset(payload_ty, mod);
7472 const payload_offset = try errUnionPayloadOffset(payload_ty, pt);
74337473 return self.wip.gepStruct(err_union_llvm_ty, operand, payload_offset, "");
74347474 }
74357475
......@@ -7446,19 +7486,21 @@ pub const FuncGen = struct {
74467486
74477487 fn airSaveErrReturnTraceIndex(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
74487488 const o = self.dg.object;
7489 const pt = o.pt;
7490 const mod = pt.zcu;
7491
74497492 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
74507493 const struct_ty = ty_pl.ty.toType();
74517494 const field_index = ty_pl.payload;
74527495
7453 const mod = o.module;
74547496 const struct_llvm_ty = try o.lowerType(struct_ty);
74557497 const llvm_field_index = o.llvmFieldIndex(struct_ty, field_index).?;
74567498 assert(self.err_ret_trace != .none);
74577499 const field_ptr =
74587500 try self.wip.gepStruct(struct_llvm_ty, self.err_ret_trace, llvm_field_index, "");
7459 const field_alignment = struct_ty.structFieldAlign(field_index, mod);
7501 const field_alignment = struct_ty.structFieldAlign(field_index, pt);
74607502 const field_ty = struct_ty.structFieldType(field_index, mod);
7461 const field_ptr_ty = try mod.ptrType(.{
7503 const field_ptr_ty = try pt.ptrType(.{
74627504 .child = field_ty.toIntern(),
74637505 .flags = .{ .alignment = field_alignment },
74647506 });
......@@ -7490,29 +7532,30 @@ pub const FuncGen = struct {
74907532
74917533 fn airWrapOptional(self: *FuncGen, body_tail: []const Air.Inst.Index) !Builder.Value {
74927534 const o = self.dg.object;
7493 const mod = o.module;
7535 const pt = o.pt;
7536 const mod = pt.zcu;
74947537 const inst = body_tail[0];
74957538 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
74967539 const payload_ty = self.typeOf(ty_op.operand);
74977540 const non_null_bit = try o.builder.intValue(.i8, 1);
74987541 comptime assert(optional_layout_version == 3);
7499 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) return non_null_bit;
7542 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) return non_null_bit;
75007543 const operand = try self.resolveInst(ty_op.operand);
75017544 const optional_ty = self.typeOfIndex(inst);
75027545 if (optional_ty.optionalReprIsPayload(mod)) return operand;
75037546 const llvm_optional_ty = try o.lowerType(optional_ty);
7504 if (isByRef(optional_ty, mod)) {
7547 if (isByRef(optional_ty, pt)) {
75057548 const directReturn = self.isNextRet(body_tail);
75067549 const optional_ptr = if (directReturn)
75077550 self.ret_ptr
75087551 else brk: {
7509 const alignment = optional_ty.abiAlignment(mod).toLlvm();
7552 const alignment = optional_ty.abiAlignment(pt).toLlvm();
75107553 const optional_ptr = try self.buildAllocaWorkaround(optional_ty, alignment);
75117554 break :brk optional_ptr;
75127555 };
75137556
75147557 const payload_ptr = try self.wip.gepStruct(llvm_optional_ty, optional_ptr, 0, "");
7515 const payload_ptr_ty = try mod.singleMutPtrType(payload_ty);
7558 const payload_ptr_ty = try pt.singleMutPtrType(payload_ty);
75167559 try self.store(payload_ptr, payload_ptr_ty, operand, .none);
75177560 const non_null_ptr = try self.wip.gepStruct(llvm_optional_ty, optional_ptr, 1, "");
75187561 _ = try self.wip.store(.normal, non_null_bit, non_null_ptr, .default);
......@@ -7523,36 +7566,36 @@ pub const FuncGen = struct {
75237566
75247567 fn airWrapErrUnionPayload(self: *FuncGen, body_tail: []const Air.Inst.Index) !Builder.Value {
75257568 const o = self.dg.object;
7526 const mod = o.module;
7569 const pt = o.pt;
75277570 const inst = body_tail[0];
75287571 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
75297572 const err_un_ty = self.typeOfIndex(inst);
75307573 const operand = try self.resolveInst(ty_op.operand);
75317574 const payload_ty = self.typeOf(ty_op.operand);
7532 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
7575 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
75337576 return operand;
75347577 }
75357578 const ok_err_code = try o.builder.intValue(try o.errorIntType(), 0);
75367579 const err_un_llvm_ty = try o.lowerType(err_un_ty);
75377580
7538 const payload_offset = try errUnionPayloadOffset(payload_ty, mod);
7539 const error_offset = try errUnionErrorOffset(payload_ty, mod);
7540 if (isByRef(err_un_ty, mod)) {
7581 const payload_offset = try errUnionPayloadOffset(payload_ty, pt);
7582 const error_offset = try errUnionErrorOffset(payload_ty, pt);
7583 if (isByRef(err_un_ty, pt)) {
75417584 const directReturn = self.isNextRet(body_tail);
75427585 const result_ptr = if (directReturn)
75437586 self.ret_ptr
75447587 else brk: {
7545 const alignment = err_un_ty.abiAlignment(mod).toLlvm();
7588 const alignment = err_un_ty.abiAlignment(pt).toLlvm();
75467589 const result_ptr = try self.buildAllocaWorkaround(err_un_ty, alignment);
75477590 break :brk result_ptr;
75487591 };
75497592
75507593 const err_ptr = try self.wip.gepStruct(err_un_llvm_ty, result_ptr, error_offset, "");
7551 const err_int_ty = try mod.errorIntType();
7552 const error_alignment = err_int_ty.abiAlignment(mod).toLlvm();
7594 const err_int_ty = try pt.errorIntType();
7595 const error_alignment = err_int_ty.abiAlignment(pt).toLlvm();
75537596 _ = try self.wip.store(.normal, ok_err_code, err_ptr, error_alignment);
75547597 const payload_ptr = try self.wip.gepStruct(err_un_llvm_ty, result_ptr, payload_offset, "");
7555 const payload_ptr_ty = try mod.singleMutPtrType(payload_ty);
7598 const payload_ptr_ty = try pt.singleMutPtrType(payload_ty);
75567599 try self.store(payload_ptr, payload_ptr_ty, operand, .none);
75577600 return result_ptr;
75587601 }
......@@ -7564,33 +7607,34 @@ pub const FuncGen = struct {
75647607
75657608 fn airWrapErrUnionErr(self: *FuncGen, body_tail: []const Air.Inst.Index) !Builder.Value {
75667609 const o = self.dg.object;
7567 const mod = o.module;
7610 const pt = o.pt;
7611 const mod = pt.zcu;
75687612 const inst = body_tail[0];
75697613 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
75707614 const err_un_ty = self.typeOfIndex(inst);
75717615 const payload_ty = err_un_ty.errorUnionPayload(mod);
75727616 const operand = try self.resolveInst(ty_op.operand);
7573 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) return operand;
7617 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) return operand;
75747618 const err_un_llvm_ty = try o.lowerType(err_un_ty);
75757619
7576 const payload_offset = try errUnionPayloadOffset(payload_ty, mod);
7577 const error_offset = try errUnionErrorOffset(payload_ty, mod);
7578 if (isByRef(err_un_ty, mod)) {
7620 const payload_offset = try errUnionPayloadOffset(payload_ty, pt);
7621 const error_offset = try errUnionErrorOffset(payload_ty, pt);
7622 if (isByRef(err_un_ty, pt)) {
75797623 const directReturn = self.isNextRet(body_tail);
75807624 const result_ptr = if (directReturn)
75817625 self.ret_ptr
75827626 else brk: {
7583 const alignment = err_un_ty.abiAlignment(mod).toLlvm();
7627 const alignment = err_un_ty.abiAlignment(pt).toLlvm();
75847628 const result_ptr = try self.buildAllocaWorkaround(err_un_ty, alignment);
75857629 break :brk result_ptr;
75867630 };
75877631
75887632 const err_ptr = try self.wip.gepStruct(err_un_llvm_ty, result_ptr, error_offset, "");
7589 const err_int_ty = try mod.errorIntType();
7590 const error_alignment = err_int_ty.abiAlignment(mod).toLlvm();
7633 const err_int_ty = try pt.errorIntType();
7634 const error_alignment = err_int_ty.abiAlignment(pt).toLlvm();
75917635 _ = try self.wip.store(.normal, operand, err_ptr, error_alignment);
75927636 const payload_ptr = try self.wip.gepStruct(err_un_llvm_ty, result_ptr, payload_offset, "");
7593 const payload_ptr_ty = try mod.singleMutPtrType(payload_ty);
7637 const payload_ptr_ty = try pt.singleMutPtrType(payload_ty);
75947638 // TODO store undef to payload_ptr
75957639 _ = payload_ptr;
75967640 _ = payload_ptr_ty;
......@@ -7624,7 +7668,8 @@ pub const FuncGen = struct {
76247668
76257669 fn airVectorStoreElem(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
76267670 const o = self.dg.object;
7627 const mod = o.module;
7671 const pt = o.pt;
7672 const mod = pt.zcu;
76287673 const data = self.air.instructions.items(.data)[@intFromEnum(inst)].vector_store_elem;
76297674 const extra = self.air.extraData(Air.Bin, data.payload).data;
76307675
......@@ -7636,7 +7681,7 @@ pub const FuncGen = struct {
76367681 const access_kind: Builder.MemoryAccessKind =
76377682 if (vector_ptr_ty.isVolatilePtr(mod)) .@"volatile" else .normal;
76387683 const elem_llvm_ty = try o.lowerType(vector_ptr_ty.childType(mod));
7639 const alignment = vector_ptr_ty.ptrAlignment(mod).toLlvm();
7684 const alignment = vector_ptr_ty.ptrAlignment(pt).toLlvm();
76407685 const loaded = try self.wip.load(access_kind, elem_llvm_ty, vector_ptr, alignment, "");
76417686
76427687 const new_vector = try self.wip.insertElement(loaded, operand, index, "");
......@@ -7646,7 +7691,7 @@ pub const FuncGen = struct {
76467691
76477692 fn airMin(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
76487693 const o = self.dg.object;
7649 const mod = o.module;
7694 const mod = o.pt.zcu;
76507695 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
76517696 const lhs = try self.resolveInst(bin_op.lhs);
76527697 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7666,7 +7711,7 @@ pub const FuncGen = struct {
76667711
76677712 fn airMax(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
76687713 const o = self.dg.object;
7669 const mod = o.module;
7714 const mod = o.pt.zcu;
76707715 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
76717716 const lhs = try self.resolveInst(bin_op.lhs);
76727717 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7696,7 +7741,7 @@ pub const FuncGen = struct {
76967741
76977742 fn airAdd(self: *FuncGen, inst: Air.Inst.Index, fast: Builder.FastMathKind) !Builder.Value {
76987743 const o = self.dg.object;
7699 const mod = o.module;
7744 const mod = o.pt.zcu;
77007745 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
77017746 const lhs = try self.resolveInst(bin_op.lhs);
77027747 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7714,7 +7759,7 @@ pub const FuncGen = struct {
77147759 unsigned_intrinsic: Builder.Intrinsic,
77157760 ) !Builder.Value {
77167761 const o = fg.dg.object;
7717 const mod = o.module;
7762 const mod = o.pt.zcu;
77187763
77197764 const bin_op = fg.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
77207765 const lhs = try fg.resolveInst(bin_op.lhs);
......@@ -7762,7 +7807,7 @@ pub const FuncGen = struct {
77627807
77637808 fn airAddSat(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
77647809 const o = self.dg.object;
7765 const mod = o.module;
7810 const mod = o.pt.zcu;
77667811 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
77677812 const lhs = try self.resolveInst(bin_op.lhs);
77687813 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7782,7 +7827,7 @@ pub const FuncGen = struct {
77827827
77837828 fn airSub(self: *FuncGen, inst: Air.Inst.Index, fast: Builder.FastMathKind) !Builder.Value {
77847829 const o = self.dg.object;
7785 const mod = o.module;
7830 const mod = o.pt.zcu;
77867831 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
77877832 const lhs = try self.resolveInst(bin_op.lhs);
77887833 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7803,7 +7848,7 @@ pub const FuncGen = struct {
78037848
78047849 fn airSubSat(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
78057850 const o = self.dg.object;
7806 const mod = o.module;
7851 const mod = o.pt.zcu;
78077852 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
78087853 const lhs = try self.resolveInst(bin_op.lhs);
78097854 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7823,7 +7868,7 @@ pub const FuncGen = struct {
78237868
78247869 fn airMul(self: *FuncGen, inst: Air.Inst.Index, fast: Builder.FastMathKind) !Builder.Value {
78257870 const o = self.dg.object;
7826 const mod = o.module;
7871 const mod = o.pt.zcu;
78277872 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
78287873 const lhs = try self.resolveInst(bin_op.lhs);
78297874 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7844,7 +7889,7 @@ pub const FuncGen = struct {
78447889
78457890 fn airMulSat(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
78467891 const o = self.dg.object;
7847 const mod = o.module;
7892 const mod = o.pt.zcu;
78487893 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
78497894 const lhs = try self.resolveInst(bin_op.lhs);
78507895 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7873,7 +7918,7 @@ pub const FuncGen = struct {
78737918
78747919 fn airDivTrunc(self: *FuncGen, inst: Air.Inst.Index, fast: Builder.FastMathKind) !Builder.Value {
78757920 const o = self.dg.object;
7876 const mod = o.module;
7921 const mod = o.pt.zcu;
78777922 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
78787923 const lhs = try self.resolveInst(bin_op.lhs);
78797924 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7889,7 +7934,7 @@ pub const FuncGen = struct {
78897934
78907935 fn airDivFloor(self: *FuncGen, inst: Air.Inst.Index, fast: Builder.FastMathKind) !Builder.Value {
78917936 const o = self.dg.object;
7892 const mod = o.module;
7937 const mod = o.pt.zcu;
78937938 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
78947939 const lhs = try self.resolveInst(bin_op.lhs);
78957940 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7921,7 +7966,7 @@ pub const FuncGen = struct {
79217966
79227967 fn airDivExact(self: *FuncGen, inst: Air.Inst.Index, fast: Builder.FastMathKind) !Builder.Value {
79237968 const o = self.dg.object;
7924 const mod = o.module;
7969 const mod = o.pt.zcu;
79257970 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
79267971 const lhs = try self.resolveInst(bin_op.lhs);
79277972 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7939,7 +7984,7 @@ pub const FuncGen = struct {
79397984
79407985 fn airRem(self: *FuncGen, inst: Air.Inst.Index, fast: Builder.FastMathKind) !Builder.Value {
79417986 const o = self.dg.object;
7942 const mod = o.module;
7987 const mod = o.pt.zcu;
79437988 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
79447989 const lhs = try self.resolveInst(bin_op.lhs);
79457990 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7956,7 +8001,7 @@ pub const FuncGen = struct {
79568001
79578002 fn airMod(self: *FuncGen, inst: Air.Inst.Index, fast: Builder.FastMathKind) !Builder.Value {
79588003 const o = self.dg.object;
7959 const mod = o.module;
8004 const mod = o.pt.zcu;
79608005 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
79618006 const lhs = try self.resolveInst(bin_op.lhs);
79628007 const rhs = try self.resolveInst(bin_op.rhs);
......@@ -7992,7 +8037,7 @@ pub const FuncGen = struct {
79928037
79938038 fn airPtrAdd(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
79948039 const o = self.dg.object;
7995 const mod = o.module;
8040 const mod = o.pt.zcu;
79968041 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
79978042 const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data;
79988043 const ptr = try self.resolveInst(bin_op.lhs);
......@@ -8014,7 +8059,7 @@ pub const FuncGen = struct {
80148059
80158060 fn airPtrSub(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
80168061 const o = self.dg.object;
8017 const mod = o.module;
8062 const mod = o.pt.zcu;
80188063 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
80198064 const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data;
80208065 const ptr = try self.resolveInst(bin_op.lhs);
......@@ -8042,7 +8087,8 @@ pub const FuncGen = struct {
80428087 unsigned_intrinsic: Builder.Intrinsic,
80438088 ) !Builder.Value {
80448089 const o = self.dg.object;
8045 const mod = o.module;
8090 const pt = o.pt;
8091 const mod = pt.zcu;
80468092 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
80478093 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
80488094
......@@ -8065,8 +8111,8 @@ pub const FuncGen = struct {
80658111 const result_index = o.llvmFieldIndex(inst_ty, 0).?;
80668112 const overflow_index = o.llvmFieldIndex(inst_ty, 1).?;
80678113
8068 if (isByRef(inst_ty, mod)) {
8069 const result_alignment = inst_ty.abiAlignment(mod).toLlvm();
8114 if (isByRef(inst_ty, pt)) {
8115 const result_alignment = inst_ty.abiAlignment(pt).toLlvm();
80708116 const alloca_inst = try self.buildAllocaWorkaround(inst_ty, result_alignment);
80718117 {
80728118 const field_ptr = try self.wip.gepStruct(llvm_inst_ty, alloca_inst, result_index, "");
......@@ -8135,7 +8181,7 @@ pub const FuncGen = struct {
81358181 return o.builder.addFunction(
81368182 try o.builder.fnType(return_type, param_types, .normal),
81378183 fn_name,
8138 toLlvmAddressSpace(.generic, o.module.getTarget()),
8184 toLlvmAddressSpace(.generic, o.pt.zcu.getTarget()),
81398185 );
81408186 }
81418187
......@@ -8149,8 +8195,8 @@ pub const FuncGen = struct {
81498195 params: [2]Builder.Value,
81508196 ) !Builder.Value {
81518197 const o = self.dg.object;
8152 const mod = o.module;
8153 const target = o.module.getTarget();
8198 const mod = o.pt.zcu;
8199 const target = mod.getTarget();
81548200 const scalar_ty = ty.scalarType(mod);
81558201 const scalar_llvm_ty = try o.lowerType(scalar_ty);
81568202
......@@ -8255,7 +8301,7 @@ pub const FuncGen = struct {
82558301 params: [params_len]Builder.Value,
82568302 ) !Builder.Value {
82578303 const o = self.dg.object;
8258 const mod = o.module;
8304 const mod = o.pt.zcu;
82598305 const target = mod.getTarget();
82608306 const scalar_ty = ty.scalarType(mod);
82618307 const llvm_ty = try o.lowerType(ty);
......@@ -8396,7 +8442,8 @@ pub const FuncGen = struct {
83968442
83978443 fn airShlWithOverflow(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
83988444 const o = self.dg.object;
8399 const mod = o.module;
8445 const pt = o.pt;
8446 const mod = pt.zcu;
84008447 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
84018448 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
84028449
......@@ -8422,8 +8469,8 @@ pub const FuncGen = struct {
84228469 const result_index = o.llvmFieldIndex(dest_ty, 0).?;
84238470 const overflow_index = o.llvmFieldIndex(dest_ty, 1).?;
84248471
8425 if (isByRef(dest_ty, mod)) {
8426 const result_alignment = dest_ty.abiAlignment(mod).toLlvm();
8472 if (isByRef(dest_ty, pt)) {
8473 const result_alignment = dest_ty.abiAlignment(pt).toLlvm();
84278474 const alloca_inst = try self.buildAllocaWorkaround(dest_ty, result_alignment);
84288475 {
84298476 const field_ptr = try self.wip.gepStruct(llvm_dest_ty, alloca_inst, result_index, "");
......@@ -8466,7 +8513,7 @@ pub const FuncGen = struct {
84668513
84678514 fn airShlExact(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
84688515 const o = self.dg.object;
8469 const mod = o.module;
8516 const mod = o.pt.zcu;
84708517 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
84718518
84728519 const lhs = try self.resolveInst(bin_op.lhs);
......@@ -8497,7 +8544,8 @@ pub const FuncGen = struct {
84978544
84988545 fn airShlSat(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
84998546 const o = self.dg.object;
8500 const mod = o.module;
8547 const pt = o.pt;
8548 const mod = pt.zcu;
85018549 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
85028550
85038551 const lhs = try self.resolveInst(bin_op.lhs);
......@@ -8505,7 +8553,7 @@ pub const FuncGen = struct {
85058553
85068554 const lhs_ty = self.typeOf(bin_op.lhs);
85078555 const lhs_scalar_ty = lhs_ty.scalarType(mod);
8508 const lhs_bits = lhs_scalar_ty.bitSize(mod);
8556 const lhs_bits = lhs_scalar_ty.bitSize(pt);
85098557
85108558 const casted_rhs = try self.wip.conv(.unsigned, rhs, try o.lowerType(lhs_ty), "");
85118559
......@@ -8539,7 +8587,7 @@ pub const FuncGen = struct {
85398587
85408588 fn airShr(self: *FuncGen, inst: Air.Inst.Index, is_exact: bool) !Builder.Value {
85418589 const o = self.dg.object;
8542 const mod = o.module;
8590 const mod = o.pt.zcu;
85438591 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
85448592
85458593 const lhs = try self.resolveInst(bin_op.lhs);
......@@ -8558,7 +8606,7 @@ pub const FuncGen = struct {
85588606
85598607 fn airAbs(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
85608608 const o = self.dg.object;
8561 const mod = o.module;
8609 const mod = o.pt.zcu;
85628610 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
85638611 const operand = try self.resolveInst(ty_op.operand);
85648612 const operand_ty = self.typeOf(ty_op.operand);
......@@ -8580,7 +8628,7 @@ pub const FuncGen = struct {
85808628
85818629 fn airIntCast(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
85828630 const o = self.dg.object;
8583 const mod = o.module;
8631 const mod = o.pt.zcu;
85848632 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
85858633 const dest_ty = self.typeOfIndex(inst);
85868634 const dest_llvm_ty = try o.lowerType(dest_ty);
......@@ -8604,7 +8652,7 @@ pub const FuncGen = struct {
86048652
86058653 fn airFptrunc(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
86068654 const o = self.dg.object;
8607 const mod = o.module;
8655 const mod = o.pt.zcu;
86088656 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
86098657 const operand = try self.resolveInst(ty_op.operand);
86108658 const operand_ty = self.typeOf(ty_op.operand);
......@@ -8638,7 +8686,7 @@ pub const FuncGen = struct {
86388686
86398687 fn airFpext(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
86408688 const o = self.dg.object;
8641 const mod = o.module;
8689 const mod = o.pt.zcu;
86428690 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
86438691 const operand = try self.resolveInst(ty_op.operand);
86448692 const operand_ty = self.typeOf(ty_op.operand);
......@@ -8696,9 +8744,10 @@ pub const FuncGen = struct {
86968744
86978745 fn bitCast(self: *FuncGen, operand: Builder.Value, operand_ty: Type, inst_ty: Type) !Builder.Value {
86988746 const o = self.dg.object;
8699 const mod = o.module;
8700 const operand_is_ref = isByRef(operand_ty, mod);
8701 const result_is_ref = isByRef(inst_ty, mod);
8747 const pt = o.pt;
8748 const mod = pt.zcu;
8749 const operand_is_ref = isByRef(operand_ty, pt);
8750 const result_is_ref = isByRef(inst_ty, pt);
87028751 const llvm_dest_ty = try o.lowerType(inst_ty);
87038752
87048753 if (operand_is_ref and result_is_ref) {
......@@ -8721,9 +8770,9 @@ pub const FuncGen = struct {
87218770 if (!result_is_ref) {
87228771 return self.dg.todo("implement bitcast vector to non-ref array", .{});
87238772 }
8724 const alignment = inst_ty.abiAlignment(mod).toLlvm();
8773 const alignment = inst_ty.abiAlignment(pt).toLlvm();
87258774 const array_ptr = try self.buildAllocaWorkaround(inst_ty, alignment);
8726 const bitcast_ok = elem_ty.bitSize(mod) == elem_ty.abiSize(mod) * 8;
8775 const bitcast_ok = elem_ty.bitSize(pt) == elem_ty.abiSize(pt) * 8;
87278776 if (bitcast_ok) {
87288777 _ = try self.wip.store(.normal, operand, array_ptr, alignment);
87298778 } else {
......@@ -8748,11 +8797,11 @@ pub const FuncGen = struct {
87488797 const llvm_vector_ty = try o.lowerType(inst_ty);
87498798 if (!operand_is_ref) return self.dg.todo("implement bitcast non-ref array to vector", .{});
87508799
8751 const bitcast_ok = elem_ty.bitSize(mod) == elem_ty.abiSize(mod) * 8;
8800 const bitcast_ok = elem_ty.bitSize(pt) == elem_ty.abiSize(pt) * 8;
87528801 if (bitcast_ok) {
87538802 // The array is aligned to the element's alignment, while the vector might have a completely
87548803 // different alignment. This means we need to enforce the alignment of this load.
8755 const alignment = elem_ty.abiAlignment(mod).toLlvm();
8804 const alignment = elem_ty.abiAlignment(pt).toLlvm();
87568805 return self.wip.load(.normal, llvm_vector_ty, operand, alignment, "");
87578806 } else {
87588807 // If the ABI size of the element type is not evenly divisible by size in bits;
......@@ -8777,24 +8826,25 @@ pub const FuncGen = struct {
87778826 }
87788827
87798828 if (operand_is_ref) {
8780 const alignment = operand_ty.abiAlignment(mod).toLlvm();
8829 const alignment = operand_ty.abiAlignment(pt).toLlvm();
87818830 return self.wip.load(.normal, llvm_dest_ty, operand, alignment, "");
87828831 }
87838832
87848833 if (result_is_ref) {
8785 const alignment = operand_ty.abiAlignment(mod).max(inst_ty.abiAlignment(mod)).toLlvm();
8834 const alignment = operand_ty.abiAlignment(pt).max(inst_ty.abiAlignment(pt)).toLlvm();
87868835 const result_ptr = try self.buildAllocaWorkaround(inst_ty, alignment);
87878836 _ = try self.wip.store(.normal, operand, result_ptr, alignment);
87888837 return result_ptr;
87898838 }
87908839
87918840 if (llvm_dest_ty.isStruct(&o.builder) or
8792 ((operand_ty.zigTypeTag(mod) == .Vector or inst_ty.zigTypeTag(mod) == .Vector) and operand_ty.bitSize(mod) != inst_ty.bitSize(mod)))
8841 ((operand_ty.zigTypeTag(mod) == .Vector or inst_ty.zigTypeTag(mod) == .Vector) and
8842 operand_ty.bitSize(pt) != inst_ty.bitSize(pt)))
87938843 {
87948844 // Both our operand and our result are values, not pointers,
87958845 // but LLVM won't let us bitcast struct values or vectors with padding bits.
87968846 // Therefore, we store operand to alloca, then load for result.
8797 const alignment = operand_ty.abiAlignment(mod).max(inst_ty.abiAlignment(mod)).toLlvm();
8847 const alignment = operand_ty.abiAlignment(pt).max(inst_ty.abiAlignment(pt)).toLlvm();
87988848 const result_ptr = try self.buildAllocaWorkaround(inst_ty, alignment);
87998849 _ = try self.wip.store(.normal, operand, result_ptr, alignment);
88008850 return self.wip.load(.normal, llvm_dest_ty, result_ptr, alignment, "");
......@@ -8811,7 +8861,8 @@ pub const FuncGen = struct {
88118861
88128862 fn airArg(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
88138863 const o = self.dg.object;
8814 const mod = o.module;
8864 const pt = o.pt;
8865 const mod = pt.zcu;
88158866 const arg_val = self.args[self.arg_index];
88168867 self.arg_index += 1;
88178868
......@@ -8847,7 +8898,7 @@ pub const FuncGen = struct {
88478898 };
88488899
88498900 const owner_mod = self.dg.ownerModule();
8850 if (isByRef(inst_ty, mod)) {
8901 if (isByRef(inst_ty, pt)) {
88518902 _ = try self.wip.callIntrinsic(
88528903 .normal,
88538904 .none,
......@@ -8861,7 +8912,7 @@ pub const FuncGen = struct {
88618912 "",
88628913 );
88638914 } else if (owner_mod.optimize_mode == .Debug) {
8864 const alignment = inst_ty.abiAlignment(mod).toLlvm();
8915 const alignment = inst_ty.abiAlignment(pt).toLlvm();
88658916 const alloca = try self.buildAlloca(arg_val.typeOfWip(&self.wip), alignment);
88668917 _ = try self.wip.store(.normal, arg_val, alloca, alignment);
88678918 _ = try self.wip.callIntrinsic(
......@@ -8897,27 +8948,29 @@ pub const FuncGen = struct {
88978948
88988949 fn airAlloc(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
88998950 const o = self.dg.object;
8900 const mod = o.module;
8951 const pt = o.pt;
8952 const mod = pt.zcu;
89018953 const ptr_ty = self.typeOfIndex(inst);
89028954 const pointee_type = ptr_ty.childType(mod);
8903 if (!pointee_type.isFnOrHasRuntimeBitsIgnoreComptime(mod))
8955 if (!pointee_type.isFnOrHasRuntimeBitsIgnoreComptime(pt))
89048956 return (try o.lowerPtrToVoid(ptr_ty)).toValue();
89058957
89068958 //const pointee_llvm_ty = try o.lowerType(pointee_type);
8907 const alignment = ptr_ty.ptrAlignment(mod).toLlvm();
8959 const alignment = ptr_ty.ptrAlignment(pt).toLlvm();
89088960 return self.buildAllocaWorkaround(pointee_type, alignment);
89098961 }
89108962
89118963 fn airRetPtr(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
89128964 const o = self.dg.object;
8913 const mod = o.module;
8965 const pt = o.pt;
8966 const mod = pt.zcu;
89148967 const ptr_ty = self.typeOfIndex(inst);
89158968 const ret_ty = ptr_ty.childType(mod);
8916 if (!ret_ty.isFnOrHasRuntimeBitsIgnoreComptime(mod))
8969 if (!ret_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt))
89178970 return (try o.lowerPtrToVoid(ptr_ty)).toValue();
89188971 if (self.ret_ptr != .none) return self.ret_ptr;
89198972 //const ret_llvm_ty = try o.lowerType(ret_ty);
8920 const alignment = ptr_ty.ptrAlignment(mod).toLlvm();
8973 const alignment = ptr_ty.ptrAlignment(pt).toLlvm();
89218974 return self.buildAllocaWorkaround(ret_ty, alignment);
89228975 }
89238976
......@@ -8928,7 +8981,7 @@ pub const FuncGen = struct {
89288981 llvm_ty: Builder.Type,
89298982 alignment: Builder.Alignment,
89308983 ) Allocator.Error!Builder.Value {
8931 const target = self.dg.object.module.getTarget();
8984 const target = self.dg.object.pt.zcu.getTarget();
89328985 return buildAllocaInner(&self.wip, llvm_ty, alignment, target);
89338986 }
89348987
......@@ -8939,18 +8992,19 @@ pub const FuncGen = struct {
89398992 alignment: Builder.Alignment,
89408993 ) Allocator.Error!Builder.Value {
89418994 const o = self.dg.object;
8942 return self.buildAlloca(try o.builder.arrayType(ty.abiSize(o.module), .i8), alignment);
8995 return self.buildAlloca(try o.builder.arrayType(ty.abiSize(o.pt), .i8), alignment);
89438996 }
89448997
89458998 fn airStore(self: *FuncGen, inst: Air.Inst.Index, safety: bool) !Builder.Value {
89468999 const o = self.dg.object;
8947 const mod = o.module;
9000 const pt = o.pt;
9001 const mod = pt.zcu;
89489002 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
89499003 const dest_ptr = try self.resolveInst(bin_op.lhs);
89509004 const ptr_ty = self.typeOf(bin_op.lhs);
89519005 const operand_ty = ptr_ty.childType(mod);
89529006
8953 const val_is_undef = if (try self.air.value(bin_op.rhs, mod)) |val| val.isUndefDeep(mod) else false;
9007 const val_is_undef = if (try self.air.value(bin_op.rhs, pt)) |val| val.isUndefDeep(mod) else false;
89549008 if (val_is_undef) {
89559009 const ptr_info = ptr_ty.ptrInfo(mod);
89569010 const needs_bitmask = (ptr_info.packed_offset.host_size != 0);
......@@ -8964,10 +9018,10 @@ pub const FuncGen = struct {
89649018 // Even if safety is disabled, we still emit a memset to undefined since it conveys
89659019 // extra information to LLVM. However, safety makes the difference between using
89669020 // 0xaa or actual undefined for the fill byte.
8967 const len = try o.builder.intValue(try o.lowerType(Type.usize), operand_ty.abiSize(mod));
9021 const len = try o.builder.intValue(try o.lowerType(Type.usize), operand_ty.abiSize(pt));
89689022 _ = try self.wip.callMemSet(
89699023 dest_ptr,
8970 ptr_ty.ptrAlignment(mod).toLlvm(),
9024 ptr_ty.ptrAlignment(pt).toLlvm(),
89719025 if (safety) try o.builder.intValue(.i8, 0xaa) else try o.builder.undefValue(.i8),
89729026 len,
89739027 if (ptr_ty.isVolatilePtr(mod)) .@"volatile" else .normal,
......@@ -8992,7 +9046,7 @@ pub const FuncGen = struct {
89929046 /// The first instruction of `body_tail` is the one whose copy we want to elide.
89939047 fn canElideLoad(fg: *FuncGen, body_tail: []const Air.Inst.Index) bool {
89949048 const o = fg.dg.object;
8995 const mod = o.module;
9049 const mod = o.pt.zcu;
89969050 const ip = &mod.intern_pool;
89979051 for (body_tail[1..]) |body_inst| {
89989052 switch (fg.liveness.categorizeOperand(fg.air, body_inst, body_tail[0], ip)) {
......@@ -9008,7 +9062,8 @@ pub const FuncGen = struct {
90089062
90099063 fn airLoad(fg: *FuncGen, body_tail: []const Air.Inst.Index) !Builder.Value {
90109064 const o = fg.dg.object;
9011 const mod = o.module;
9065 const pt = o.pt;
9066 const mod = pt.zcu;
90129067 const inst = body_tail[0];
90139068 const ty_op = fg.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
90149069 const ptr_ty = fg.typeOf(ty_op.operand);
......@@ -9016,7 +9071,7 @@ pub const FuncGen = struct {
90169071 const ptr = try fg.resolveInst(ty_op.operand);
90179072
90189073 elide: {
9019 if (!isByRef(Type.fromInterned(ptr_info.child), mod)) break :elide;
9074 if (!isByRef(Type.fromInterned(ptr_info.child), pt)) break :elide;
90209075 if (!canElideLoad(fg, body_tail)) break :elide;
90219076 return ptr;
90229077 }
......@@ -9040,7 +9095,7 @@ pub const FuncGen = struct {
90409095 _ = inst;
90419096 const o = self.dg.object;
90429097 const llvm_usize = try o.lowerType(Type.usize);
9043 if (!target_util.supportsReturnAddress(o.module.getTarget())) {
9098 if (!target_util.supportsReturnAddress(o.pt.zcu.getTarget())) {
90449099 // https://github.com/ziglang/zig/issues/11946
90459100 return o.builder.intValue(llvm_usize, 0);
90469101 }
......@@ -9068,7 +9123,8 @@ pub const FuncGen = struct {
90689123 kind: Builder.Function.Instruction.CmpXchg.Kind,
90699124 ) !Builder.Value {
90709125 const o = self.dg.object;
9071 const mod = o.module;
9126 const pt = o.pt;
9127 const mod = pt.zcu;
90729128 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
90739129 const extra = self.air.extraData(Air.Cmpxchg, ty_pl.payload).data;
90749130 const ptr = try self.resolveInst(extra.ptr);
......@@ -9095,7 +9151,7 @@ pub const FuncGen = struct {
90959151 self.sync_scope,
90969152 toLlvmAtomicOrdering(extra.successOrder()),
90979153 toLlvmAtomicOrdering(extra.failureOrder()),
9098 ptr_ty.ptrAlignment(mod).toLlvm(),
9154 ptr_ty.ptrAlignment(pt).toLlvm(),
90999155 "",
91009156 );
91019157
......@@ -9118,7 +9174,8 @@ pub const FuncGen = struct {
91189174
91199175 fn airAtomicRmw(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
91209176 const o = self.dg.object;
9121 const mod = o.module;
9177 const pt = o.pt;
9178 const mod = pt.zcu;
91229179 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
91239180 const extra = self.air.extraData(Air.AtomicRmw, pl_op.payload).data;
91249181 const ptr = try self.resolveInst(pl_op.operand);
......@@ -9134,7 +9191,7 @@ pub const FuncGen = struct {
91349191
91359192 const access_kind: Builder.MemoryAccessKind =
91369193 if (ptr_ty.isVolatilePtr(mod)) .@"volatile" else .normal;
9137 const ptr_alignment = ptr_ty.ptrAlignment(mod).toLlvm();
9194 const ptr_alignment = ptr_ty.ptrAlignment(pt).toLlvm();
91389195
91399196 if (llvm_abi_ty != .none) {
91409197 // operand needs widening and truncating or bitcasting.
......@@ -9181,19 +9238,20 @@ pub const FuncGen = struct {
91819238
91829239 fn airAtomicLoad(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
91839240 const o = self.dg.object;
9184 const mod = o.module;
9241 const pt = o.pt;
9242 const mod = pt.zcu;
91859243 const atomic_load = self.air.instructions.items(.data)[@intFromEnum(inst)].atomic_load;
91869244 const ptr = try self.resolveInst(atomic_load.ptr);
91879245 const ptr_ty = self.typeOf(atomic_load.ptr);
91889246 const info = ptr_ty.ptrInfo(mod);
91899247 const elem_ty = Type.fromInterned(info.child);
9190 if (!elem_ty.hasRuntimeBitsIgnoreComptime(mod)) return .none;
9248 if (!elem_ty.hasRuntimeBitsIgnoreComptime(pt)) return .none;
91919249 const ordering = toLlvmAtomicOrdering(atomic_load.order);
91929250 const llvm_abi_ty = try o.getAtomicAbiType(elem_ty, false);
91939251 const ptr_alignment = (if (info.flags.alignment != .none)
91949252 @as(InternPool.Alignment, info.flags.alignment)
91959253 else
9196 Type.fromInterned(info.child).abiAlignment(mod)).toLlvm();
9254 Type.fromInterned(info.child).abiAlignment(pt)).toLlvm();
91979255 const access_kind: Builder.MemoryAccessKind =
91989256 if (info.flags.is_volatile) .@"volatile" else .normal;
91999257 const elem_llvm_ty = try o.lowerType(elem_ty);
......@@ -9228,11 +9286,12 @@ pub const FuncGen = struct {
92289286 ordering: Builder.AtomicOrdering,
92299287 ) !Builder.Value {
92309288 const o = self.dg.object;
9231 const mod = o.module;
9289 const pt = o.pt;
9290 const mod = pt.zcu;
92329291 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
92339292 const ptr_ty = self.typeOf(bin_op.lhs);
92349293 const operand_ty = ptr_ty.childType(mod);
9235 if (!operand_ty.isFnOrHasRuntimeBitsIgnoreComptime(mod)) return .none;
9294 if (!operand_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt)) return .none;
92369295 const ptr = try self.resolveInst(bin_op.lhs);
92379296 var element = try self.resolveInst(bin_op.rhs);
92389297 const llvm_abi_ty = try o.getAtomicAbiType(operand_ty, false);
......@@ -9252,12 +9311,13 @@ pub const FuncGen = struct {
92529311
92539312 fn airMemset(self: *FuncGen, inst: Air.Inst.Index, safety: bool) !Builder.Value {
92549313 const o = self.dg.object;
9255 const mod = o.module;
9314 const pt = o.pt;
9315 const mod = pt.zcu;
92569316 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
92579317 const dest_slice = try self.resolveInst(bin_op.lhs);
92589318 const ptr_ty = self.typeOf(bin_op.lhs);
92599319 const elem_ty = self.typeOf(bin_op.rhs);
9260 const dest_ptr_align = ptr_ty.ptrAlignment(mod).toLlvm();
9320 const dest_ptr_align = ptr_ty.ptrAlignment(pt).toLlvm();
92619321 const dest_ptr = try self.sliceOrArrayPtr(dest_slice, ptr_ty);
92629322 const access_kind: Builder.MemoryAccessKind =
92639323 if (ptr_ty.isVolatilePtr(mod)) .@"volatile" else .normal;
......@@ -9270,7 +9330,7 @@ pub const FuncGen = struct {
92709330 ptr_ty.isSlice(mod) and
92719331 std.Target.wasm.featureSetHas(o.target.cpu.features, .bulk_memory);
92729332
9273 if (try self.air.value(bin_op.rhs, mod)) |elem_val| {
9333 if (try self.air.value(bin_op.rhs, pt)) |elem_val| {
92749334 if (elem_val.isUndefDeep(mod)) {
92759335 // Even if safety is disabled, we still emit a memset to undefined since it conveys
92769336 // extra information to LLVM. However, safety makes the difference between using
......@@ -9296,7 +9356,7 @@ pub const FuncGen = struct {
92969356 // repeating byte pattern, for example, `@as(u64, 0)` has a
92979357 // repeating byte pattern of 0 bytes. In such case, the memset
92989358 // intrinsic can be used.
9299 if (try elem_val.hasRepeatedByteRepr(elem_ty, mod)) |byte_val| {
9359 if (try elem_val.hasRepeatedByteRepr(elem_ty, pt)) |byte_val| {
93009360 const fill_byte = try o.builder.intValue(.i8, byte_val);
93019361 const len = try self.sliceOrArrayLenInBytes(dest_slice, ptr_ty);
93029362 if (intrinsic_len0_traps) {
......@@ -9309,7 +9369,7 @@ pub const FuncGen = struct {
93099369 }
93109370
93119371 const value = try self.resolveInst(bin_op.rhs);
9312 const elem_abi_size = elem_ty.abiSize(mod);
9372 const elem_abi_size = elem_ty.abiSize(pt);
93139373
93149374 if (elem_abi_size == 1) {
93159375 // In this case we can take advantage of LLVM's intrinsic.
......@@ -9361,9 +9421,9 @@ pub const FuncGen = struct {
93619421 _ = try self.wip.brCond(end, body_block, end_block);
93629422
93639423 self.wip.cursor = .{ .block = body_block };
9364 const elem_abi_align = elem_ty.abiAlignment(mod);
9424 const elem_abi_align = elem_ty.abiAlignment(pt);
93659425 const it_ptr_align = InternPool.Alignment.fromLlvm(dest_ptr_align).min(elem_abi_align).toLlvm();
9366 if (isByRef(elem_ty, mod)) {
9426 if (isByRef(elem_ty, pt)) {
93679427 _ = try self.wip.callMemCpy(
93689428 it_ptr.toValue(),
93699429 it_ptr_align,
......@@ -9405,7 +9465,8 @@ pub const FuncGen = struct {
94059465
94069466 fn airMemcpy(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
94079467 const o = self.dg.object;
9408 const mod = o.module;
9468 const pt = o.pt;
9469 const mod = pt.zcu;
94099470 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
94109471 const dest_slice = try self.resolveInst(bin_op.lhs);
94119472 const dest_ptr_ty = self.typeOf(bin_op.lhs);
......@@ -9434,9 +9495,9 @@ pub const FuncGen = struct {
94349495 self.wip.cursor = .{ .block = memcpy_block };
94359496 _ = try self.wip.callMemCpy(
94369497 dest_ptr,
9437 dest_ptr_ty.ptrAlignment(mod).toLlvm(),
9498 dest_ptr_ty.ptrAlignment(pt).toLlvm(),
94389499 src_ptr,
9439 src_ptr_ty.ptrAlignment(mod).toLlvm(),
9500 src_ptr_ty.ptrAlignment(pt).toLlvm(),
94409501 len,
94419502 access_kind,
94429503 );
......@@ -9447,9 +9508,9 @@ pub const FuncGen = struct {
94479508
94489509 _ = try self.wip.callMemCpy(
94499510 dest_ptr,
9450 dest_ptr_ty.ptrAlignment(mod).toLlvm(),
9511 dest_ptr_ty.ptrAlignment(pt).toLlvm(),
94519512 src_ptr,
9452 src_ptr_ty.ptrAlignment(mod).toLlvm(),
9513 src_ptr_ty.ptrAlignment(pt).toLlvm(),
94539514 len,
94549515 access_kind,
94559516 );
......@@ -9458,10 +9519,11 @@ pub const FuncGen = struct {
94589519
94599520 fn airSetUnionTag(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
94609521 const o = self.dg.object;
9461 const mod = o.module;
9522 const pt = o.pt;
9523 const mod = pt.zcu;
94629524 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
94639525 const un_ty = self.typeOf(bin_op.lhs).childType(mod);
9464 const layout = un_ty.unionGetLayout(mod);
9526 const layout = un_ty.unionGetLayout(pt);
94659527 if (layout.tag_size == 0) return .none;
94669528 const union_ptr = try self.resolveInst(bin_op.lhs);
94679529 const new_tag = try self.resolveInst(bin_op.rhs);
......@@ -9479,13 +9541,13 @@ pub const FuncGen = struct {
94799541
94809542 fn airGetUnionTag(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
94819543 const o = self.dg.object;
9482 const mod = o.module;
9544 const pt = o.pt;
94839545 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
94849546 const un_ty = self.typeOf(ty_op.operand);
9485 const layout = un_ty.unionGetLayout(mod);
9547 const layout = un_ty.unionGetLayout(pt);
94869548 if (layout.tag_size == 0) return .none;
94879549 const union_handle = try self.resolveInst(ty_op.operand);
9488 if (isByRef(un_ty, mod)) {
9550 if (isByRef(un_ty, pt)) {
94899551 const llvm_un_ty = try o.lowerType(un_ty);
94909552 if (layout.payload_size == 0)
94919553 return self.wip.load(.normal, llvm_un_ty, union_handle, .default, "");
......@@ -9554,7 +9616,7 @@ pub const FuncGen = struct {
95549616
95559617 fn airByteSwap(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
95569618 const o = self.dg.object;
9557 const mod = o.module;
9619 const mod = o.pt.zcu;
95589620 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
95599621 const operand_ty = self.typeOf(ty_op.operand);
95609622 var bits = operand_ty.intInfo(mod).bits;
......@@ -9588,7 +9650,7 @@ pub const FuncGen = struct {
95889650
95899651 fn airErrorSetHasValue(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
95909652 const o = self.dg.object;
9591 const mod = o.module;
9653 const mod = o.pt.zcu;
95929654 const ip = &mod.intern_pool;
95939655 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
95949656 const operand = try self.resolveInst(ty_op.operand);
......@@ -9638,7 +9700,8 @@ pub const FuncGen = struct {
96389700
96399701 fn getIsNamedEnumValueFunction(self: *FuncGen, enum_ty: Type) !Builder.Function.Index {
96409702 const o = self.dg.object;
9641 const zcu = o.module;
9703 const pt = o.pt;
9704 const zcu = pt.zcu;
96429705 const enum_type = zcu.intern_pool.loadEnumType(enum_ty.toIntern());
96439706
96449707 // TODO: detect when the type changes and re-emit this function.
......@@ -9646,7 +9709,7 @@ pub const FuncGen = struct {
96469709 if (gop.found_existing) return gop.value_ptr.*;
96479710 errdefer assert(o.named_enum_map.remove(enum_type.decl));
96489711
9649 const fqn = try zcu.declPtr(enum_type.decl).fullyQualifiedName(zcu);
9712 const fqn = try zcu.declPtr(enum_type.decl).fullyQualifiedName(pt);
96509713 const target = zcu.root_mod.resolved_target.result;
96519714 const function_index = try o.builder.addFunction(
96529715 try o.builder.fnType(.i1, &.{try o.lowerType(Type.fromInterned(enum_type.tag_ty))}, .normal),
......@@ -9678,7 +9741,7 @@ pub const FuncGen = struct {
96789741
96799742 for (0..enum_type.names.len) |field_index| {
96809743 const this_tag_int_value = try o.lowerValue(
9681 (try zcu.enumValueFieldIndex(enum_ty, @intCast(field_index))).toIntern(),
9744 (try pt.enumValueFieldIndex(enum_ty, @intCast(field_index))).toIntern(),
96829745 );
96839746 try wip_switch.addCase(this_tag_int_value, named_block, &wip);
96849747 }
......@@ -9745,7 +9808,8 @@ pub const FuncGen = struct {
97459808
97469809 fn airShuffle(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
97479810 const o = self.dg.object;
9748 const mod = o.module;
9811 const pt = o.pt;
9812 const mod = pt.zcu;
97499813 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
97509814 const extra = self.air.extraData(Air.Shuffle, ty_pl.payload).data;
97519815 const a = try self.resolveInst(extra.a);
......@@ -9763,11 +9827,11 @@ pub const FuncGen = struct {
97639827 defer self.gpa.free(values);
97649828
97659829 for (values, 0..) |*val, i| {
9766 const elem = try mask.elemValue(mod, i);
9830 const elem = try mask.elemValue(pt, i);
97679831 if (elem.isUndef(mod)) {
97689832 val.* = try o.builder.undefConst(.i32);
97699833 } else {
9770 const int = elem.toSignedInt(mod);
9834 const int = elem.toSignedInt(pt);
97719835 const unsigned: u32 = @intCast(if (int >= 0) int else ~int + a_len);
97729836 val.* = try o.builder.intConst(.i32, unsigned);
97739837 }
......@@ -9854,7 +9918,7 @@ pub const FuncGen = struct {
98549918
98559919 fn airReduce(self: *FuncGen, inst: Air.Inst.Index, fast: Builder.FastMathKind) !Builder.Value {
98569920 const o = self.dg.object;
9857 const mod = o.module;
9921 const mod = o.pt.zcu;
98589922 const target = mod.getTarget();
98599923
98609924 const reduce = self.air.instructions.items(.data)[@intFromEnum(inst)].reduce;
......@@ -9964,7 +10028,8 @@ pub const FuncGen = struct {
996410028
996510029 fn airAggregateInit(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
996610030 const o = self.dg.object;
9967 const mod = o.module;
10031 const pt = o.pt;
10032 const mod = pt.zcu;
996810033 const ip = &mod.intern_pool;
996910034 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
997010035 const result_ty = self.typeOfIndex(inst);
......@@ -9986,16 +10051,16 @@ pub const FuncGen = struct {
998610051 if (mod.typeToPackedStruct(result_ty)) |struct_type| {
998710052 const backing_int_ty = struct_type.backingIntType(ip).*;
998810053 assert(backing_int_ty != .none);
9989 const big_bits = Type.fromInterned(backing_int_ty).bitSize(mod);
10054 const big_bits = Type.fromInterned(backing_int_ty).bitSize(pt);
999010055 const int_ty = try o.builder.intType(@intCast(big_bits));
999110056 comptime assert(Type.packed_struct_layout_version == 2);
999210057 var running_int = try o.builder.intValue(int_ty, 0);
999310058 var running_bits: u16 = 0;
999410059 for (elements, struct_type.field_types.get(ip)) |elem, field_ty| {
9995 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(mod)) continue;
10060 if (!Type.fromInterned(field_ty).hasRuntimeBitsIgnoreComptime(pt)) continue;
999610061
999710062 const non_int_val = try self.resolveInst(elem);
9998 const ty_bit_size: u16 = @intCast(Type.fromInterned(field_ty).bitSize(mod));
10063 const ty_bit_size: u16 = @intCast(Type.fromInterned(field_ty).bitSize(pt));
999910064 const small_int_ty = try o.builder.intType(ty_bit_size);
1000010065 const small_int_val = if (Type.fromInterned(field_ty).isPtrAtRuntime(mod))
1000110066 try self.wip.cast(.ptrtoint, non_int_val, small_int_ty, "")
......@@ -10013,23 +10078,23 @@ pub const FuncGen = struct {
1001310078
1001410079 assert(result_ty.containerLayout(mod) != .@"packed");
1001510080
10016 if (isByRef(result_ty, mod)) {
10081 if (isByRef(result_ty, pt)) {
1001710082 // TODO in debug builds init to undef so that the padding will be 0xaa
1001810083 // even if we fully populate the fields.
10019 const alignment = result_ty.abiAlignment(mod).toLlvm();
10084 const alignment = result_ty.abiAlignment(pt).toLlvm();
1002010085 const alloca_inst = try self.buildAllocaWorkaround(result_ty, alignment);
1002110086
1002210087 for (elements, 0..) |elem, i| {
10023 if ((try result_ty.structFieldValueComptime(mod, i)) != null) continue;
10088 if ((try result_ty.structFieldValueComptime(pt, i)) != null) continue;
1002410089
1002510090 const llvm_elem = try self.resolveInst(elem);
1002610091 const llvm_i = o.llvmFieldIndex(result_ty, i).?;
1002710092 const field_ptr =
1002810093 try self.wip.gepStruct(llvm_result_ty, alloca_inst, llvm_i, "");
10029 const field_ptr_ty = try mod.ptrType(.{
10094 const field_ptr_ty = try pt.ptrType(.{
1003010095 .child = self.typeOf(elem).toIntern(),
1003110096 .flags = .{
10032 .alignment = result_ty.structFieldAlign(i, mod),
10097 .alignment = result_ty.structFieldAlign(i, pt),
1003310098 },
1003410099 });
1003510100 try self.store(field_ptr, field_ptr_ty, llvm_elem, .none);
......@@ -10039,7 +10104,7 @@ pub const FuncGen = struct {
1003910104 } else {
1004010105 var result = try o.builder.poisonValue(llvm_result_ty);
1004110106 for (elements, 0..) |elem, i| {
10042 if ((try result_ty.structFieldValueComptime(mod, i)) != null) continue;
10107 if ((try result_ty.structFieldValueComptime(pt, i)) != null) continue;
1004310108
1004410109 const llvm_elem = try self.resolveInst(elem);
1004510110 const llvm_i = o.llvmFieldIndex(result_ty, i).?;
......@@ -10049,15 +10114,15 @@ pub const FuncGen = struct {
1004910114 }
1005010115 },
1005110116 .Array => {
10052 assert(isByRef(result_ty, mod));
10117 assert(isByRef(result_ty, pt));
1005310118
1005410119 const llvm_usize = try o.lowerType(Type.usize);
1005510120 const usize_zero = try o.builder.intValue(llvm_usize, 0);
10056 const alignment = result_ty.abiAlignment(mod).toLlvm();
10121 const alignment = result_ty.abiAlignment(pt).toLlvm();
1005710122 const alloca_inst = try self.buildAllocaWorkaround(result_ty, alignment);
1005810123
1005910124 const array_info = result_ty.arrayInfo(mod);
10060 const elem_ptr_ty = try mod.ptrType(.{
10125 const elem_ptr_ty = try pt.ptrType(.{
1006110126 .child = array_info.elem_type.toIntern(),
1006210127 });
1006310128
......@@ -10084,21 +10149,22 @@ pub const FuncGen = struct {
1008410149
1008510150 fn airUnionInit(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
1008610151 const o = self.dg.object;
10087 const mod = o.module;
10152 const pt = o.pt;
10153 const mod = pt.zcu;
1008810154 const ip = &mod.intern_pool;
1008910155 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
1009010156 const extra = self.air.extraData(Air.UnionInit, ty_pl.payload).data;
1009110157 const union_ty = self.typeOfIndex(inst);
1009210158 const union_llvm_ty = try o.lowerType(union_ty);
10093 const layout = union_ty.unionGetLayout(mod);
10159 const layout = union_ty.unionGetLayout(pt);
1009410160 const union_obj = mod.typeToUnion(union_ty).?;
1009510161
1009610162 if (union_obj.getLayout(ip) == .@"packed") {
10097 const big_bits = union_ty.bitSize(mod);
10163 const big_bits = union_ty.bitSize(pt);
1009810164 const int_llvm_ty = try o.builder.intType(@intCast(big_bits));
1009910165 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[extra.field_index]);
1010010166 const non_int_val = try self.resolveInst(extra.init);
10101 const small_int_ty = try o.builder.intType(@intCast(field_ty.bitSize(mod)));
10167 const small_int_ty = try o.builder.intType(@intCast(field_ty.bitSize(pt)));
1010210168 const small_int_val = if (field_ty.isPtrAtRuntime(mod))
1010310169 try self.wip.cast(.ptrtoint, non_int_val, small_int_ty, "")
1010410170 else
......@@ -10110,19 +10176,19 @@ pub const FuncGen = struct {
1011010176 const tag_ty = union_ty.unionTagTypeHypothetical(mod);
1011110177 const union_field_name = union_obj.loadTagType(ip).names.get(ip)[extra.field_index];
1011210178 const enum_field_index = tag_ty.enumFieldIndex(union_field_name, mod).?;
10113 const tag_val = try mod.enumValueFieldIndex(tag_ty, enum_field_index);
10114 break :blk try tag_val.intFromEnum(tag_ty, mod);
10179 const tag_val = try pt.enumValueFieldIndex(tag_ty, enum_field_index);
10180 break :blk try tag_val.intFromEnum(tag_ty, pt);
1011510181 };
1011610182 if (layout.payload_size == 0) {
1011710183 if (layout.tag_size == 0) {
1011810184 return .none;
1011910185 }
10120 assert(!isByRef(union_ty, mod));
10186 assert(!isByRef(union_ty, pt));
1012110187 var big_int_space: Value.BigIntSpace = undefined;
10122 const tag_big_int = tag_int_val.toBigInt(&big_int_space, mod);
10188 const tag_big_int = tag_int_val.toBigInt(&big_int_space, pt);
1012310189 return try o.builder.bigIntValue(union_llvm_ty, tag_big_int);
1012410190 }
10125 assert(isByRef(union_ty, mod));
10191 assert(isByRef(union_ty, pt));
1012610192 // The llvm type of the alloca will be the named LLVM union type, and will not
1012710193 // necessarily match the format that we need, depending on which tag is active.
1012810194 // We must construct the correct unnamed struct type here, in order to then set
......@@ -10132,14 +10198,14 @@ pub const FuncGen = struct {
1013210198 const llvm_payload = try self.resolveInst(extra.init);
1013310199 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[extra.field_index]);
1013410200 const field_llvm_ty = try o.lowerType(field_ty);
10135 const field_size = field_ty.abiSize(mod);
10136 const field_align = mod.unionFieldNormalAlignment(union_obj, extra.field_index);
10201 const field_size = field_ty.abiSize(pt);
10202 const field_align = pt.unionFieldNormalAlignment(union_obj, extra.field_index);
1013710203 const llvm_usize = try o.lowerType(Type.usize);
1013810204 const usize_zero = try o.builder.intValue(llvm_usize, 0);
1013910205
1014010206 const llvm_union_ty = t: {
1014110207 const payload_ty = p: {
10142 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) {
10208 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) {
1014310209 const padding_len = layout.payload_size;
1014410210 break :p try o.builder.arrayType(padding_len, .i8);
1014510211 }
......@@ -10169,7 +10235,7 @@ pub const FuncGen = struct {
1016910235
1017010236 // Now we follow the layout as expressed above with GEP instructions to set the
1017110237 // tag and the payload.
10172 const field_ptr_ty = try mod.ptrType(.{
10238 const field_ptr_ty = try pt.ptrType(.{
1017310239 .child = field_ty.toIntern(),
1017410240 .flags = .{ .alignment = field_align },
1017510241 });
......@@ -10195,9 +10261,9 @@ pub const FuncGen = struct {
1019510261 const field_ptr = try self.wip.gep(.inbounds, llvm_union_ty, result_ptr, &indices, "");
1019610262 const tag_ty = try o.lowerType(Type.fromInterned(union_obj.enum_tag_ty));
1019710263 var big_int_space: Value.BigIntSpace = undefined;
10198 const tag_big_int = tag_int_val.toBigInt(&big_int_space, mod);
10264 const tag_big_int = tag_int_val.toBigInt(&big_int_space, pt);
1019910265 const llvm_tag = try o.builder.bigIntValue(tag_ty, tag_big_int);
10200 const tag_alignment = Type.fromInterned(union_obj.enum_tag_ty).abiAlignment(mod).toLlvm();
10266 const tag_alignment = Type.fromInterned(union_obj.enum_tag_ty).abiAlignment(pt).toLlvm();
1020110267 _ = try self.wip.store(.normal, llvm_tag, field_ptr, tag_alignment);
1020210268 }
1020310269
......@@ -10223,7 +10289,7 @@ pub const FuncGen = struct {
1022310289 // by the target.
1022410290 // To work around this, don't emit llvm.prefetch in this case.
1022510291 // See https://bugs.llvm.org/show_bug.cgi?id=21037
10226 const mod = o.module;
10292 const mod = o.pt.zcu;
1022710293 const target = mod.getTarget();
1022810294 switch (prefetch.cache) {
1022910295 .instruction => switch (target.cpu.arch) {
......@@ -10279,7 +10345,7 @@ pub const FuncGen = struct {
1027910345
1028010346 fn airWorkItemId(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
1028110347 const o = self.dg.object;
10282 const target = o.module.getTarget();
10348 const target = o.pt.zcu.getTarget();
1028310349 assert(target.cpu.arch == .amdgcn); // TODO is to port this function to other GPU architectures
1028410350
1028510351 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
......@@ -10289,7 +10355,7 @@ pub const FuncGen = struct {
1028910355
1029010356 fn airWorkGroupSize(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
1029110357 const o = self.dg.object;
10292 const target = o.module.getTarget();
10358 const target = o.pt.zcu.getTarget();
1029310359 assert(target.cpu.arch == .amdgcn); // TODO is to port this function to other GPU architectures
1029410360
1029510361 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
......@@ -10312,7 +10378,7 @@ pub const FuncGen = struct {
1031210378
1031310379 fn airWorkGroupId(self: *FuncGen, inst: Air.Inst.Index) !Builder.Value {
1031410380 const o = self.dg.object;
10315 const target = o.module.getTarget();
10381 const target = o.pt.zcu.getTarget();
1031610382 assert(target.cpu.arch == .amdgcn); // TODO is to port this function to other GPU architectures
1031710383
1031810384 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
......@@ -10322,7 +10388,7 @@ pub const FuncGen = struct {
1032210388
1032310389 fn getErrorNameTable(self: *FuncGen) Allocator.Error!Builder.Variable.Index {
1032410390 const o = self.dg.object;
10325 const mod = o.module;
10391 const pt = o.pt;
1032610392
1032710393 const table = o.error_name_table;
1032810394 if (table != .none) return table;
......@@ -10334,7 +10400,7 @@ pub const FuncGen = struct {
1033410400 variable_index.setMutability(.constant, &o.builder);
1033510401 variable_index.setUnnamedAddr(.unnamed_addr, &o.builder);
1033610402 variable_index.setAlignment(
10337 Type.slice_const_u8_sentinel_0.abiAlignment(mod).toLlvm(),
10403 Type.slice_const_u8_sentinel_0.abiAlignment(pt).toLlvm(),
1033810404 &o.builder,
1033910405 );
1034010406
......@@ -10372,15 +10438,16 @@ pub const FuncGen = struct {
1037210438 can_elide_load: bool,
1037310439 ) !Builder.Value {
1037410440 const o = fg.dg.object;
10375 const mod = o.module;
10441 const pt = o.pt;
10442 const mod = pt.zcu;
1037610443 const payload_ty = opt_ty.optionalChild(mod);
1037710444
10378 if (isByRef(opt_ty, mod)) {
10445 if (isByRef(opt_ty, pt)) {
1037910446 // We have a pointer and we need to return a pointer to the first field.
1038010447 const payload_ptr = try fg.wip.gepStruct(opt_llvm_ty, opt_handle, 0, "");
1038110448
10382 const payload_alignment = payload_ty.abiAlignment(mod).toLlvm();
10383 if (isByRef(payload_ty, mod)) {
10449 const payload_alignment = payload_ty.abiAlignment(pt).toLlvm();
10450 if (isByRef(payload_ty, pt)) {
1038410451 if (can_elide_load)
1038510452 return payload_ptr;
1038610453
......@@ -10389,7 +10456,7 @@ pub const FuncGen = struct {
1038910456 return fg.loadTruncate(.normal, payload_ty, payload_ptr, payload_alignment);
1039010457 }
1039110458
10392 assert(!isByRef(payload_ty, mod));
10459 assert(!isByRef(payload_ty, pt));
1039310460 return fg.wip.extractValue(opt_handle, &.{0}, "");
1039410461 }
1039510462
......@@ -10400,12 +10467,12 @@ pub const FuncGen = struct {
1040010467 non_null_bit: Builder.Value,
1040110468 ) !Builder.Value {
1040210469 const o = self.dg.object;
10470 const pt = o.pt;
1040310471 const optional_llvm_ty = try o.lowerType(optional_ty);
1040410472 const non_null_field = try self.wip.cast(.zext, non_null_bit, .i8, "");
10405 const mod = o.module;
1040610473
10407 if (isByRef(optional_ty, mod)) {
10408 const payload_alignment = optional_ty.abiAlignment(mod).toLlvm();
10474 if (isByRef(optional_ty, pt)) {
10475 const payload_alignment = optional_ty.abiAlignment(pt).toLlvm();
1040910476 const alloca_inst = try self.buildAllocaWorkaround(optional_ty, payload_alignment);
1041010477
1041110478 {
......@@ -10432,7 +10499,8 @@ pub const FuncGen = struct {
1043210499 field_index: u32,
1043310500 ) !Builder.Value {
1043410501 const o = self.dg.object;
10435 const mod = o.module;
10502 const pt = o.pt;
10503 const mod = pt.zcu;
1043610504 const struct_ty = struct_ptr_ty.childType(mod);
1043710505 switch (struct_ty.zigTypeTag(mod)) {
1043810506 .Struct => switch (struct_ty.containerLayout(mod)) {
......@@ -10452,7 +10520,7 @@ pub const FuncGen = struct {
1045210520
1045310521 // We have a pointer to a packed struct field that happens to be byte-aligned.
1045410522 // Offset our operand pointer by the correct number of bytes.
10455 const byte_offset = @divExact(mod.structPackedFieldBitOffset(struct_type, field_index) + struct_ptr_ty_info.packed_offset.bit_offset, 8);
10523 const byte_offset = @divExact(pt.structPackedFieldBitOffset(struct_type, field_index) + struct_ptr_ty_info.packed_offset.bit_offset, 8);
1045610524 if (byte_offset == 0) return struct_ptr;
1045710525 const usize_ty = try o.lowerType(Type.usize);
1045810526 const llvm_index = try o.builder.intValue(usize_ty, byte_offset);
......@@ -10470,14 +10538,14 @@ pub const FuncGen = struct {
1047010538 // the struct.
1047110539 const llvm_index = try o.builder.intValue(
1047210540 try o.lowerType(Type.usize),
10473 @intFromBool(struct_ty.hasRuntimeBitsIgnoreComptime(mod)),
10541 @intFromBool(struct_ty.hasRuntimeBitsIgnoreComptime(pt)),
1047410542 );
1047510543 return self.wip.gep(.inbounds, struct_llvm_ty, struct_ptr, &.{llvm_index}, "");
1047610544 }
1047710545 },
1047810546 },
1047910547 .Union => {
10480 const layout = struct_ty.unionGetLayout(mod);
10548 const layout = struct_ty.unionGetLayout(pt);
1048110549 if (layout.payload_size == 0 or struct_ty.containerLayout(mod) == .@"packed") return struct_ptr;
1048210550 const payload_index = @intFromBool(layout.tag_align.compare(.gte, layout.payload_align));
1048310551 const union_llvm_ty = try o.lowerType(struct_ty);
......@@ -10500,9 +10568,10 @@ pub const FuncGen = struct {
1050010568 // => so load the byte aligned value and trunc the unwanted bits.
1050110569
1050210570 const o = fg.dg.object;
10503 const mod = o.module;
10571 const pt = o.pt;
10572 const mod = pt.zcu;
1050410573 const payload_llvm_ty = try o.lowerType(payload_ty);
10505 const abi_size = payload_ty.abiSize(mod);
10574 const abi_size = payload_ty.abiSize(pt);
1050610575
1050710576 // llvm bug workarounds:
1050810577 const workaround_explicit_mask = o.target.cpu.arch == .powerpc and abi_size >= 4;
......@@ -10522,7 +10591,7 @@ pub const FuncGen = struct {
1052210591 const shifted = if (payload_llvm_ty != load_llvm_ty and o.target.cpu.arch.endian() == .big)
1052310592 try fg.wip.bin(.lshr, loaded, try o.builder.intValue(
1052410593 load_llvm_ty,
10525 (payload_ty.abiSize(mod) - (std.math.divCeil(u64, payload_ty.bitSize(mod), 8) catch unreachable)) * 8,
10594 (payload_ty.abiSize(pt) - (std.math.divCeil(u64, payload_ty.bitSize(pt), 8) catch unreachable)) * 8,
1052610595 ), "")
1052710596 else
1052810597 loaded;
......@@ -10546,11 +10615,11 @@ pub const FuncGen = struct {
1054610615 access_kind: Builder.MemoryAccessKind,
1054710616 ) !Builder.Value {
1054810617 const o = fg.dg.object;
10549 const mod = o.module;
10618 const pt = o.pt;
1055010619 //const pointee_llvm_ty = try o.lowerType(pointee_type);
10551 const result_align = InternPool.Alignment.fromLlvm(ptr_alignment).max(pointee_type.abiAlignment(mod)).toLlvm();
10620 const result_align = InternPool.Alignment.fromLlvm(ptr_alignment).max(pointee_type.abiAlignment(pt)).toLlvm();
1055210621 const result_ptr = try fg.buildAllocaWorkaround(pointee_type, result_align);
10553 const size_bytes = pointee_type.abiSize(mod);
10622 const size_bytes = pointee_type.abiSize(pt);
1055410623 _ = try fg.wip.callMemCpy(
1055510624 result_ptr,
1055610625 result_align,
......@@ -10567,15 +10636,16 @@ pub const FuncGen = struct {
1056710636 /// For isByRef=false types, it creates a load instruction and returns it.
1056810637 fn load(self: *FuncGen, ptr: Builder.Value, ptr_ty: Type) !Builder.Value {
1056910638 const o = self.dg.object;
10570 const mod = o.module;
10639 const pt = o.pt;
10640 const mod = pt.zcu;
1057110641 const info = ptr_ty.ptrInfo(mod);
1057210642 const elem_ty = Type.fromInterned(info.child);
10573 if (!elem_ty.hasRuntimeBitsIgnoreComptime(mod)) return .none;
10643 if (!elem_ty.hasRuntimeBitsIgnoreComptime(pt)) return .none;
1057410644
1057510645 const ptr_alignment = (if (info.flags.alignment != .none)
1057610646 @as(InternPool.Alignment, info.flags.alignment)
1057710647 else
10578 elem_ty.abiAlignment(mod)).toLlvm();
10648 elem_ty.abiAlignment(pt)).toLlvm();
1057910649
1058010650 const access_kind: Builder.MemoryAccessKind =
1058110651 if (info.flags.is_volatile) .@"volatile" else .normal;
......@@ -10591,7 +10661,7 @@ pub const FuncGen = struct {
1059110661 }
1059210662
1059310663 if (info.packed_offset.host_size == 0) {
10594 if (isByRef(elem_ty, mod)) {
10664 if (isByRef(elem_ty, pt)) {
1059510665 return self.loadByRef(ptr, elem_ty, ptr_alignment, access_kind);
1059610666 }
1059710667 return self.loadTruncate(access_kind, elem_ty, ptr, ptr_alignment);
......@@ -10601,13 +10671,13 @@ pub const FuncGen = struct {
1060110671 const containing_int =
1060210672 try self.wip.load(access_kind, containing_int_ty, ptr, ptr_alignment, "");
1060310673
10604 const elem_bits = ptr_ty.childType(mod).bitSize(mod);
10674 const elem_bits = ptr_ty.childType(mod).bitSize(pt);
1060510675 const shift_amt = try o.builder.intValue(containing_int_ty, info.packed_offset.bit_offset);
1060610676 const shifted_value = try self.wip.bin(.lshr, containing_int, shift_amt, "");
1060710677 const elem_llvm_ty = try o.lowerType(elem_ty);
1060810678
10609 if (isByRef(elem_ty, mod)) {
10610 const result_align = elem_ty.abiAlignment(mod).toLlvm();
10679 if (isByRef(elem_ty, pt)) {
10680 const result_align = elem_ty.abiAlignment(pt).toLlvm();
1061110681 const result_ptr = try self.buildAllocaWorkaround(elem_ty, result_align);
1061210682
1061310683 const same_size_int = try o.builder.intType(@intCast(elem_bits));
......@@ -10639,13 +10709,14 @@ pub const FuncGen = struct {
1063910709 ordering: Builder.AtomicOrdering,
1064010710 ) !void {
1064110711 const o = self.dg.object;
10642 const mod = o.module;
10712 const pt = o.pt;
10713 const mod = pt.zcu;
1064310714 const info = ptr_ty.ptrInfo(mod);
1064410715 const elem_ty = Type.fromInterned(info.child);
10645 if (!elem_ty.isFnOrHasRuntimeBitsIgnoreComptime(mod)) {
10716 if (!elem_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt)) {
1064610717 return;
1064710718 }
10648 const ptr_alignment = ptr_ty.ptrAlignment(mod).toLlvm();
10719 const ptr_alignment = ptr_ty.ptrAlignment(pt).toLlvm();
1064910720 const access_kind: Builder.MemoryAccessKind =
1065010721 if (info.flags.is_volatile) .@"volatile" else .normal;
1065110722
......@@ -10669,7 +10740,7 @@ pub const FuncGen = struct {
1066910740 assert(ordering == .none);
1067010741 const containing_int =
1067110742 try self.wip.load(access_kind, containing_int_ty, ptr, ptr_alignment, "");
10672 const elem_bits = ptr_ty.childType(mod).bitSize(mod);
10743 const elem_bits = ptr_ty.childType(mod).bitSize(pt);
1067310744 const shift_amt = try o.builder.intConst(containing_int_ty, info.packed_offset.bit_offset);
1067410745 // Convert to equally-sized integer type in order to perform the bit
1067510746 // operations on the value to store
......@@ -10704,7 +10775,7 @@ pub const FuncGen = struct {
1070410775 _ = try self.wip.store(access_kind, ored_value, ptr, ptr_alignment);
1070510776 return;
1070610777 }
10707 if (!isByRef(elem_ty, mod)) {
10778 if (!isByRef(elem_ty, pt)) {
1070810779 _ = try self.wip.storeAtomic(
1070910780 access_kind,
1071010781 elem,
......@@ -10720,8 +10791,8 @@ pub const FuncGen = struct {
1072010791 ptr,
1072110792 ptr_alignment,
1072210793 elem,
10723 elem_ty.abiAlignment(mod).toLlvm(),
10724 try o.builder.intValue(try o.lowerType(Type.usize), elem_ty.abiSize(mod)),
10794 elem_ty.abiAlignment(pt).toLlvm(),
10795 try o.builder.intValue(try o.lowerType(Type.usize), elem_ty.abiSize(pt)),
1072510796 access_kind,
1072610797 );
1072710798 }
......@@ -10747,12 +10818,13 @@ pub const FuncGen = struct {
1074710818 a5: Builder.Value,
1074810819 ) Allocator.Error!Builder.Value {
1074910820 const o = fg.dg.object;
10750 const mod = o.module;
10821 const pt = o.pt;
10822 const mod = pt.zcu;
1075110823 const target = mod.getTarget();
1075210824 if (!target_util.hasValgrindSupport(target)) return default_value;
1075310825
1075410826 const llvm_usize = try o.lowerType(Type.usize);
10755 const usize_alignment = Type.usize.abiAlignment(mod).toLlvm();
10827 const usize_alignment = Type.usize.abiAlignment(pt).toLlvm();
1075610828
1075710829 const array_llvm_ty = try o.builder.arrayType(6, llvm_usize);
1075810830 const array_ptr = if (fg.valgrind_client_request_array == .none) a: {
......@@ -10813,13 +10885,13 @@ pub const FuncGen = struct {
1081310885
1081410886 fn typeOf(fg: *FuncGen, inst: Air.Inst.Ref) Type {
1081510887 const o = fg.dg.object;
10816 const mod = o.module;
10888 const mod = o.pt.zcu;
1081710889 return fg.air.typeOf(inst, &mod.intern_pool);
1081810890 }
1081910891
1082010892 fn typeOfIndex(fg: *FuncGen, inst: Air.Inst.Index) Type {
1082110893 const o = fg.dg.object;
10822 const mod = o.module;
10894 const mod = o.pt.zcu;
1082310895 return fg.air.typeOfIndex(inst, &mod.intern_pool);
1082410896 }
1082510897};
......@@ -10990,12 +11062,12 @@ fn toLlvmGlobalAddressSpace(wanted_address_space: std.builtin.AddressSpace, targ
1099011062 };
1099111063}
1099211064
10993fn returnTypeByRef(zcu: *Zcu, target: std.Target, ty: Type) bool {
10994 if (isByRef(ty, zcu)) {
11065fn returnTypeByRef(pt: Zcu.PerThread, target: std.Target, ty: Type) bool {
11066 if (isByRef(ty, pt)) {
1099511067 return true;
1099611068 } else if (target.cpu.arch.isX86() and
1099711069 !std.Target.x86.featureSetHas(target.cpu.features, .evex512) and
10998 ty.totalVectorBits(zcu) >= 512)
11070 ty.totalVectorBits(pt) >= 512)
1099911071 {
1100011072 // As of LLVM 18, passing a vector byval with fastcc that is 512 bits or more returns
1100111073 // "512-bit vector arguments require 'evex512' for AVX512"
......@@ -11005,38 +11077,38 @@ fn returnTypeByRef(zcu: *Zcu, target: std.Target, ty: Type) bool {
1100511077 }
1100611078}
1100711079
11008fn firstParamSRet(fn_info: InternPool.Key.FuncType, zcu: *Zcu, target: std.Target) bool {
11080fn firstParamSRet(fn_info: InternPool.Key.FuncType, pt: Zcu.PerThread, target: std.Target) bool {
1100911081 const return_type = Type.fromInterned(fn_info.return_type);
11010 if (!return_type.hasRuntimeBitsIgnoreComptime(zcu)) return false;
11082 if (!return_type.hasRuntimeBitsIgnoreComptime(pt)) return false;
1101111083
1101211084 return switch (fn_info.cc) {
11013 .Unspecified, .Inline => returnTypeByRef(zcu, target, return_type),
11085 .Unspecified, .Inline => returnTypeByRef(pt, target, return_type),
1101411086 .C => switch (target.cpu.arch) {
1101511087 .mips, .mipsel => false,
11016 .x86 => isByRef(return_type, zcu),
11088 .x86 => isByRef(return_type, pt),
1101711089 .x86_64 => switch (target.os.tag) {
11018 .windows => x86_64_abi.classifyWindows(return_type, zcu) == .memory,
11019 else => firstParamSRetSystemV(return_type, zcu, target),
11090 .windows => x86_64_abi.classifyWindows(return_type, pt) == .memory,
11091 else => firstParamSRetSystemV(return_type, pt, target),
1102011092 },
11021 .wasm32 => wasm_c_abi.classifyType(return_type, zcu)[0] == .indirect,
11022 .aarch64, .aarch64_be => aarch64_c_abi.classifyType(return_type, zcu) == .memory,
11023 .arm, .armeb => switch (arm_c_abi.classifyType(return_type, zcu, .ret)) {
11093 .wasm32 => wasm_c_abi.classifyType(return_type, pt)[0] == .indirect,
11094 .aarch64, .aarch64_be => aarch64_c_abi.classifyType(return_type, pt) == .memory,
11095 .arm, .armeb => switch (arm_c_abi.classifyType(return_type, pt, .ret)) {
1102411096 .memory, .i64_array => true,
1102511097 .i32_array => |size| size != 1,
1102611098 .byval => false,
1102711099 },
11028 .riscv32, .riscv64 => riscv_c_abi.classifyType(return_type, zcu) == .memory,
11100 .riscv32, .riscv64 => riscv_c_abi.classifyType(return_type, pt) == .memory,
1102911101 else => false, // TODO investigate C ABI for other architectures
1103011102 },
11031 .SysV => firstParamSRetSystemV(return_type, zcu, target),
11032 .Win64 => x86_64_abi.classifyWindows(return_type, zcu) == .memory,
11033 .Stdcall => !isScalar(zcu, return_type),
11103 .SysV => firstParamSRetSystemV(return_type, pt, target),
11104 .Win64 => x86_64_abi.classifyWindows(return_type, pt) == .memory,
11105 .Stdcall => !isScalar(pt.zcu, return_type),
1103411106 else => false,
1103511107 };
1103611108}
1103711109
11038fn firstParamSRetSystemV(ty: Type, zcu: *Zcu, target: std.Target) bool {
11039 const class = x86_64_abi.classifySystemV(ty, zcu, target, .ret);
11110fn firstParamSRetSystemV(ty: Type, pt: Zcu.PerThread, target: std.Target) bool {
11111 const class = x86_64_abi.classifySystemV(ty, pt, target, .ret);
1104011112 if (class[0] == .memory) return true;
1104111113 if (class[0] == .x87 and class[2] != .none) return true;
1104211114 return false;
......@@ -11046,9 +11118,10 @@ fn firstParamSRetSystemV(ty: Type, zcu: *Zcu, target: std.Target) bool {
1104611118/// completely differently in the function prototype to honor the C ABI, and then
1104711119/// be effectively bitcasted to the actual return type.
1104811120fn lowerFnRetTy(o: *Object, fn_info: InternPool.Key.FuncType) Allocator.Error!Builder.Type {
11049 const mod = o.module;
11121 const pt = o.pt;
11122 const mod = pt.zcu;
1105011123 const return_type = Type.fromInterned(fn_info.return_type);
11051 if (!return_type.hasRuntimeBitsIgnoreComptime(mod)) {
11124 if (!return_type.hasRuntimeBitsIgnoreComptime(pt)) {
1105211125 // If the return type is an error set or an error union, then we make this
1105311126 // anyerror return type instead, so that it can be coerced into a function
1105411127 // pointer type which has anyerror as the return type.
......@@ -11058,12 +11131,12 @@ fn lowerFnRetTy(o: *Object, fn_info: InternPool.Key.FuncType) Allocator.Error!Bu
1105811131 switch (fn_info.cc) {
1105911132 .Unspecified,
1106011133 .Inline,
11061 => return if (returnTypeByRef(mod, target, return_type)) .void else o.lowerType(return_type),
11134 => return if (returnTypeByRef(pt, target, return_type)) .void else o.lowerType(return_type),
1106211135
1106311136 .C => {
1106411137 switch (target.cpu.arch) {
1106511138 .mips, .mipsel => return o.lowerType(return_type),
11066 .x86 => return if (isByRef(return_type, mod)) .void else o.lowerType(return_type),
11139 .x86 => return if (isByRef(return_type, pt)) .void else o.lowerType(return_type),
1106711140 .x86_64 => switch (target.os.tag) {
1106811141 .windows => return lowerWin64FnRetTy(o, fn_info),
1106911142 else => return lowerSystemVFnRetTy(o, fn_info),
......@@ -11072,36 +11145,36 @@ fn lowerFnRetTy(o: *Object, fn_info: InternPool.Key.FuncType) Allocator.Error!Bu
1107211145 if (isScalar(mod, return_type)) {
1107311146 return o.lowerType(return_type);
1107411147 }
11075 const classes = wasm_c_abi.classifyType(return_type, mod);
11148 const classes = wasm_c_abi.classifyType(return_type, pt);
1107611149 if (classes[0] == .indirect or classes[0] == .none) {
1107711150 return .void;
1107811151 }
1107911152
1108011153 assert(classes[0] == .direct and classes[1] == .none);
11081 const scalar_type = wasm_c_abi.scalarType(return_type, mod);
11082 return o.builder.intType(@intCast(scalar_type.abiSize(mod) * 8));
11154 const scalar_type = wasm_c_abi.scalarType(return_type, pt);
11155 return o.builder.intType(@intCast(scalar_type.abiSize(pt) * 8));
1108311156 },
1108411157 .aarch64, .aarch64_be => {
11085 switch (aarch64_c_abi.classifyType(return_type, mod)) {
11158 switch (aarch64_c_abi.classifyType(return_type, pt)) {
1108611159 .memory => return .void,
1108711160 .float_array => return o.lowerType(return_type),
1108811161 .byval => return o.lowerType(return_type),
11089 .integer => return o.builder.intType(@intCast(return_type.bitSize(mod))),
11162 .integer => return o.builder.intType(@intCast(return_type.bitSize(pt))),
1109011163 .double_integer => return o.builder.arrayType(2, .i64),
1109111164 }
1109211165 },
1109311166 .arm, .armeb => {
11094 switch (arm_c_abi.classifyType(return_type, mod, .ret)) {
11167 switch (arm_c_abi.classifyType(return_type, pt, .ret)) {
1109511168 .memory, .i64_array => return .void,
1109611169 .i32_array => |len| return if (len == 1) .i32 else .void,
1109711170 .byval => return o.lowerType(return_type),
1109811171 }
1109911172 },
1110011173 .riscv32, .riscv64 => {
11101 switch (riscv_c_abi.classifyType(return_type, mod)) {
11174 switch (riscv_c_abi.classifyType(return_type, pt)) {
1110211175 .memory => return .void,
1110311176 .integer => {
11104 return o.builder.intType(@intCast(return_type.bitSize(mod)));
11177 return o.builder.intType(@intCast(return_type.bitSize(pt)));
1110511178 },
1110611179 .double_integer => {
1110711180 return o.builder.structType(.normal, &.{ .i64, .i64 });
......@@ -11112,7 +11185,7 @@ fn lowerFnRetTy(o: *Object, fn_info: InternPool.Key.FuncType) Allocator.Error!Bu
1111211185 var types: [8]Builder.Type = undefined;
1111311186 for (0..return_type.structFieldCount(mod)) |field_index| {
1111411187 const field_ty = return_type.structFieldType(field_index, mod);
11115 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
11188 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
1111611189 types[types_len] = try o.lowerType(field_ty);
1111711190 types_len += 1;
1111811191 }
......@@ -11132,14 +11205,14 @@ fn lowerFnRetTy(o: *Object, fn_info: InternPool.Key.FuncType) Allocator.Error!Bu
1113211205}
1113311206
1113411207fn lowerWin64FnRetTy(o: *Object, fn_info: InternPool.Key.FuncType) Allocator.Error!Builder.Type {
11135 const mod = o.module;
11208 const pt = o.pt;
1113611209 const return_type = Type.fromInterned(fn_info.return_type);
11137 switch (x86_64_abi.classifyWindows(return_type, mod)) {
11210 switch (x86_64_abi.classifyWindows(return_type, pt)) {
1113811211 .integer => {
11139 if (isScalar(mod, return_type)) {
11212 if (isScalar(pt.zcu, return_type)) {
1114011213 return o.lowerType(return_type);
1114111214 } else {
11142 return o.builder.intType(@intCast(return_type.abiSize(mod) * 8));
11215 return o.builder.intType(@intCast(return_type.abiSize(pt) * 8));
1114311216 }
1114411217 },
1114511218 .win_i128 => return o.builder.vectorType(.normal, 2, .i64),
......@@ -11150,14 +11223,15 @@ fn lowerWin64FnRetTy(o: *Object, fn_info: InternPool.Key.FuncType) Allocator.Err
1115011223}
1115111224
1115211225fn lowerSystemVFnRetTy(o: *Object, fn_info: InternPool.Key.FuncType) Allocator.Error!Builder.Type {
11153 const mod = o.module;
11226 const pt = o.pt;
11227 const mod = pt.zcu;
1115411228 const ip = &mod.intern_pool;
1115511229 const return_type = Type.fromInterned(fn_info.return_type);
1115611230 if (isScalar(mod, return_type)) {
1115711231 return o.lowerType(return_type);
1115811232 }
1115911233 const target = mod.getTarget();
11160 const classes = x86_64_abi.classifySystemV(return_type, mod, target, .ret);
11234 const classes = x86_64_abi.classifySystemV(return_type, pt, target, .ret);
1116111235 if (classes[0] == .memory) return .void;
1116211236 var types_index: u32 = 0;
1116311237 var types_buffer: [8]Builder.Type = undefined;
......@@ -11249,8 +11323,7 @@ const ParamTypeIterator = struct {
1124911323
1125011324 pub fn next(it: *ParamTypeIterator) Allocator.Error!?Lowering {
1125111325 if (it.zig_index >= it.fn_info.param_types.len) return null;
11252 const zcu = it.object.module;
11253 const ip = &zcu.intern_pool;
11326 const ip = &it.object.pt.zcu.intern_pool;
1125411327 const ty = it.fn_info.param_types.get(ip)[it.zig_index];
1125511328 it.byval_attr = false;
1125611329 return nextInner(it, Type.fromInterned(ty));
......@@ -11258,8 +11331,7 @@ const ParamTypeIterator = struct {
1125811331
1125911332 /// `airCall` uses this instead of `next` so that it can take into account variadic functions.
1126011333 pub fn nextCall(it: *ParamTypeIterator, fg: *FuncGen, args: []const Air.Inst.Ref) Allocator.Error!?Lowering {
11261 const zcu = it.object.module;
11262 const ip = &zcu.intern_pool;
11334 const ip = &it.object.pt.zcu.intern_pool;
1126311335 if (it.zig_index >= it.fn_info.param_types.len) {
1126411336 if (it.zig_index >= args.len) {
1126511337 return null;
......@@ -11272,10 +11344,11 @@ const ParamTypeIterator = struct {
1127211344 }
1127311345
1127411346 fn nextInner(it: *ParamTypeIterator, ty: Type) Allocator.Error!?Lowering {
11275 const zcu = it.object.module;
11347 const pt = it.object.pt;
11348 const zcu = pt.zcu;
1127611349 const target = zcu.getTarget();
1127711350
11278 if (!ty.hasRuntimeBitsIgnoreComptime(zcu)) {
11351 if (!ty.hasRuntimeBitsIgnoreComptime(pt)) {
1127911352 it.zig_index += 1;
1128011353 return .no_bits;
1128111354 }
......@@ -11288,11 +11361,11 @@ const ParamTypeIterator = struct {
1128811361 {
1128911362 it.llvm_index += 1;
1129011363 return .slice;
11291 } else if (isByRef(ty, zcu)) {
11364 } else if (isByRef(ty, pt)) {
1129211365 return .byref;
1129311366 } else if (target.cpu.arch.isX86() and
1129411367 !std.Target.x86.featureSetHas(target.cpu.features, .evex512) and
11295 ty.totalVectorBits(zcu) >= 512)
11368 ty.totalVectorBits(pt) >= 512)
1129611369 {
1129711370 // As of LLVM 18, passing a vector byval with fastcc that is 512 bits or more returns
1129811371 // "512-bit vector arguments require 'evex512' for AVX512"
......@@ -11320,7 +11393,7 @@ const ParamTypeIterator = struct {
1132011393 if (isScalar(zcu, ty)) {
1132111394 return .byval;
1132211395 }
11323 const classes = wasm_c_abi.classifyType(ty, zcu);
11396 const classes = wasm_c_abi.classifyType(ty, pt);
1132411397 if (classes[0] == .indirect) {
1132511398 return .byref;
1132611399 }
......@@ -11329,7 +11402,7 @@ const ParamTypeIterator = struct {
1132911402 .aarch64, .aarch64_be => {
1133011403 it.zig_index += 1;
1133111404 it.llvm_index += 1;
11332 switch (aarch64_c_abi.classifyType(ty, zcu)) {
11405 switch (aarch64_c_abi.classifyType(ty, pt)) {
1133311406 .memory => return .byref_mut,
1133411407 .float_array => |len| return Lowering{ .float_array = len },
1133511408 .byval => return .byval,
......@@ -11344,7 +11417,7 @@ const ParamTypeIterator = struct {
1134411417 .arm, .armeb => {
1134511418 it.zig_index += 1;
1134611419 it.llvm_index += 1;
11347 switch (arm_c_abi.classifyType(ty, zcu, .arg)) {
11420 switch (arm_c_abi.classifyType(ty, pt, .arg)) {
1134811421 .memory => {
1134911422 it.byval_attr = true;
1135011423 return .byref;
......@@ -11359,7 +11432,7 @@ const ParamTypeIterator = struct {
1135911432 it.llvm_index += 1;
1136011433 if (ty.toIntern() == .f16_type and
1136111434 !std.Target.riscv.featureSetHas(target.cpu.features, .d)) return .as_u16;
11362 switch (riscv_c_abi.classifyType(ty, zcu)) {
11435 switch (riscv_c_abi.classifyType(ty, pt)) {
1136311436 .memory => return .byref_mut,
1136411437 .byval => return .byval,
1136511438 .integer => return .abi_sized_int,
......@@ -11368,7 +11441,7 @@ const ParamTypeIterator = struct {
1136811441 it.types_len = 0;
1136911442 for (0..ty.structFieldCount(zcu)) |field_index| {
1137011443 const field_ty = ty.structFieldType(field_index, zcu);
11371 if (!field_ty.hasRuntimeBitsIgnoreComptime(zcu)) continue;
11444 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
1137211445 it.types_buffer[it.types_len] = try it.object.lowerType(field_ty);
1137311446 it.types_len += 1;
1137411447 }
......@@ -11406,10 +11479,10 @@ const ParamTypeIterator = struct {
1140611479 }
1140711480
1140811481 fn nextWin64(it: *ParamTypeIterator, ty: Type) ?Lowering {
11409 const zcu = it.object.module;
11410 switch (x86_64_abi.classifyWindows(ty, zcu)) {
11482 const pt = it.object.pt;
11483 switch (x86_64_abi.classifyWindows(ty, pt)) {
1141111484 .integer => {
11412 if (isScalar(zcu, ty)) {
11485 if (isScalar(pt.zcu, ty)) {
1141311486 it.zig_index += 1;
1141411487 it.llvm_index += 1;
1141511488 return .byval;
......@@ -11439,17 +11512,17 @@ const ParamTypeIterator = struct {
1143911512 }
1144011513
1144111514 fn nextSystemV(it: *ParamTypeIterator, ty: Type) Allocator.Error!?Lowering {
11442 const zcu = it.object.module;
11443 const ip = &zcu.intern_pool;
11444 const target = zcu.getTarget();
11445 const classes = x86_64_abi.classifySystemV(ty, zcu, target, .arg);
11515 const pt = it.object.pt;
11516 const ip = &pt.zcu.intern_pool;
11517 const target = pt.zcu.getTarget();
11518 const classes = x86_64_abi.classifySystemV(ty, pt, target, .arg);
1144611519 if (classes[0] == .memory) {
1144711520 it.zig_index += 1;
1144811521 it.llvm_index += 1;
1144911522 it.byval_attr = true;
1145011523 return .byref;
1145111524 }
11452 if (isScalar(zcu, ty)) {
11525 if (isScalar(pt.zcu, ty)) {
1145311526 it.zig_index += 1;
1145411527 it.llvm_index += 1;
1145511528 return .byval;
......@@ -11550,7 +11623,7 @@ fn iterateParamTypes(object: *Object, fn_info: InternPool.Key.FuncType) ParamTyp
1155011623
1155111624fn ccAbiPromoteInt(
1155211625 cc: std.builtin.CallingConvention,
11553 mod: *Module,
11626 mod: *Zcu,
1155411627 ty: Type,
1155511628) ?std.builtin.Signedness {
1155611629 const target = mod.getTarget();
......@@ -11598,13 +11671,13 @@ fn ccAbiPromoteInt(
1159811671
1159911672/// This is the one source of truth for whether a type is passed around as an LLVM pointer,
1160011673/// or as an LLVM value.
11601fn isByRef(ty: Type, mod: *Module) bool {
11674fn isByRef(ty: Type, pt: Zcu.PerThread) bool {
1160211675 // For tuples and structs, if there are more than this many non-void
1160311676 // fields, then we make it byref, otherwise byval.
1160411677 const max_fields_byval = 0;
11605 const ip = &mod.intern_pool;
11678 const ip = &pt.zcu.intern_pool;
1160611679
11607 switch (ty.zigTypeTag(mod)) {
11680 switch (ty.zigTypeTag(pt.zcu)) {
1160811681 .Type,
1160911682 .ComptimeInt,
1161011683 .ComptimeFloat,
......@@ -11627,17 +11700,17 @@ fn isByRef(ty: Type, mod: *Module) bool {
1162711700 .AnyFrame,
1162811701 => return false,
1162911702
11630 .Array, .Frame => return ty.hasRuntimeBits(mod),
11703 .Array, .Frame => return ty.hasRuntimeBits(pt),
1163111704 .Struct => {
1163211705 const struct_type = switch (ip.indexToKey(ty.toIntern())) {
1163311706 .anon_struct_type => |tuple| {
1163411707 var count: usize = 0;
1163511708 for (tuple.types.get(ip), tuple.values.get(ip)) |field_ty, field_val| {
11636 if (field_val != .none or !Type.fromInterned(field_ty).hasRuntimeBits(mod)) continue;
11709 if (field_val != .none or !Type.fromInterned(field_ty).hasRuntimeBits(pt)) continue;
1163711710
1163811711 count += 1;
1163911712 if (count > max_fields_byval) return true;
11640 if (isByRef(Type.fromInterned(field_ty), mod)) return true;
11713 if (isByRef(Type.fromInterned(field_ty), pt)) return true;
1164111714 }
1164211715 return false;
1164311716 },
......@@ -11655,27 +11728,27 @@ fn isByRef(ty: Type, mod: *Module) bool {
1165511728 count += 1;
1165611729 if (count > max_fields_byval) return true;
1165711730 const field_ty = Type.fromInterned(field_types[field_index]);
11658 if (isByRef(field_ty, mod)) return true;
11731 if (isByRef(field_ty, pt)) return true;
1165911732 }
1166011733 return false;
1166111734 },
11662 .Union => switch (ty.containerLayout(mod)) {
11735 .Union => switch (ty.containerLayout(pt.zcu)) {
1166311736 .@"packed" => return false,
11664 else => return ty.hasRuntimeBits(mod),
11737 else => return ty.hasRuntimeBits(pt),
1166511738 },
1166611739 .ErrorUnion => {
11667 const payload_ty = ty.errorUnionPayload(mod);
11668 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
11740 const payload_ty = ty.errorUnionPayload(pt.zcu);
11741 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
1166911742 return false;
1167011743 }
1167111744 return true;
1167211745 },
1167311746 .Optional => {
11674 const payload_ty = ty.optionalChild(mod);
11675 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
11747 const payload_ty = ty.optionalChild(pt.zcu);
11748 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
1167611749 return false;
1167711750 }
11678 if (ty.optionalReprIsPayload(mod)) {
11751 if (ty.optionalReprIsPayload(pt.zcu)) {
1167911752 return false;
1168011753 }
1168111754 return true;
......@@ -11683,7 +11756,7 @@ fn isByRef(ty: Type, mod: *Module) bool {
1168311756 }
1168411757}
1168511758
11686fn isScalar(mod: *Module, ty: Type) bool {
11759fn isScalar(mod: *Zcu, ty: Type) bool {
1168711760 return switch (ty.zigTypeTag(mod)) {
1168811761 .Void,
1168911762 .Bool,
......@@ -11774,7 +11847,7 @@ const lt_errors_fn_name = "__zig_lt_errors_len";
1177411847/// Without this workaround, LLVM crashes with "unknown codeview register H1"
1177511848/// https://github.com/llvm/llvm-project/issues/56484
1177611849fn needDbgVarWorkaround(o: *Object) bool {
11777 const target = o.module.getTarget();
11850 const target = o.pt.zcu.getTarget();
1177811851 if (target.os.tag == .windows and target.cpu.arch == .aarch64) {
1177911852 return true;
1178011853 }
......@@ -11817,14 +11890,14 @@ fn buildAllocaInner(
1181711890 return wip.conv(.unneeded, alloca, .ptr, "");
1181811891}
1181911892
11820fn errUnionPayloadOffset(payload_ty: Type, mod: *Module) !u1 {
11821 const err_int_ty = try mod.errorIntType();
11822 return @intFromBool(err_int_ty.abiAlignment(mod).compare(.gt, payload_ty.abiAlignment(mod)));
11893fn errUnionPayloadOffset(payload_ty: Type, pt: Zcu.PerThread) !u1 {
11894 const err_int_ty = try pt.errorIntType();
11895 return @intFromBool(err_int_ty.abiAlignment(pt).compare(.gt, payload_ty.abiAlignment(pt)));
1182311896}
1182411897
11825fn errUnionErrorOffset(payload_ty: Type, mod: *Module) !u1 {
11826 const err_int_ty = try mod.errorIntType();
11827 return @intFromBool(err_int_ty.abiAlignment(mod).compare(.lte, payload_ty.abiAlignment(mod)));
11898fn errUnionErrorOffset(payload_ty: Type, pt: Zcu.PerThread) !u1 {
11899 const err_int_ty = try pt.errorIntType();
11900 return @intFromBool(err_int_ty.abiAlignment(pt).compare(.lte, payload_ty.abiAlignment(pt)));
1182811901}
1182911902
1183011903/// Returns true for asm constraint (e.g. "=*m", "=r") if it accepts a memory location
src/codegen/spirv.zig+240-212
......@@ -6,9 +6,7 @@ const assert = std.debug.assert;
66const Signedness = std.builtin.Signedness;
77
88const Zcu = @import("../Zcu.zig");
9/// Deprecated.
10const Module = Zcu;
11const Decl = Module.Decl;
9const Decl = Zcu.Decl;
1210const Type = @import("../Type.zig");
1311const Value = @import("../Value.zig");
1412const Air = @import("../Air.zig");
......@@ -188,12 +186,13 @@ pub const Object = struct {
188186
189187 fn genDecl(
190188 self: *Object,
191 zcu: *Zcu,
189 pt: Zcu.PerThread,
192190 decl_index: InternPool.DeclIndex,
193191 air: Air,
194192 liveness: Liveness,
195193 ) !void {
196 const gpa = self.gpa;
194 const zcu = pt.zcu;
195 const gpa = zcu.gpa;
197196 const decl = zcu.declPtr(decl_index);
198197 const namespace = zcu.namespacePtr(decl.src_namespace);
199198 const structured_cfg = namespace.fileScope(zcu).mod.structured_cfg;
......@@ -201,7 +200,7 @@ pub const Object = struct {
201200 var decl_gen = DeclGen{
202201 .gpa = gpa,
203202 .object = self,
204 .module = zcu,
203 .pt = pt,
205204 .spv = &self.spv,
206205 .decl_index = decl_index,
207206 .air = air,
......@@ -235,34 +234,34 @@ pub const Object = struct {
235234
236235 pub fn updateFunc(
237236 self: *Object,
238 mod: *Module,
237 pt: Zcu.PerThread,
239238 func_index: InternPool.Index,
240239 air: Air,
241240 liveness: Liveness,
242241 ) !void {
243 const decl_index = mod.funcInfo(func_index).owner_decl;
242 const decl_index = pt.zcu.funcInfo(func_index).owner_decl;
244243 // TODO: Separate types for generating decls and functions?
245 try self.genDecl(mod, decl_index, air, liveness);
244 try self.genDecl(pt, decl_index, air, liveness);
246245 }
247246
248247 pub fn updateDecl(
249248 self: *Object,
250 mod: *Module,
249 pt: Zcu.PerThread,
251250 decl_index: InternPool.DeclIndex,
252251 ) !void {
253 try self.genDecl(mod, decl_index, undefined, undefined);
252 try self.genDecl(pt, decl_index, undefined, undefined);
254253 }
255254
256255 /// Fetch or allocate a result id for decl index. This function also marks the decl as alive.
257256 /// Note: Function does not actually generate the decl, it just allocates an index.
258 pub fn resolveDecl(self: *Object, mod: *Module, decl_index: InternPool.DeclIndex) !SpvModule.Decl.Index {
259 const decl = mod.declPtr(decl_index);
257 pub fn resolveDecl(self: *Object, zcu: *Zcu, decl_index: InternPool.DeclIndex) !SpvModule.Decl.Index {
258 const decl = zcu.declPtr(decl_index);
260259 assert(decl.has_tv); // TODO: Do we need to handle a situation where this is false?
261260
262261 const entry = try self.decl_link.getOrPut(self.gpa, decl_index);
263262 if (!entry.found_existing) {
264263 // TODO: Extern fn?
265 const kind: SpvModule.Decl.Kind = if (decl.val.isFuncBody(mod))
264 const kind: SpvModule.Decl.Kind = if (decl.val.isFuncBody(zcu))
266265 .func
267266 else switch (decl.@"addrspace") {
268267 .generic => .invocation_global,
......@@ -285,7 +284,7 @@ const DeclGen = struct {
285284 object: *Object,
286285
287286 /// The Zig module that we are generating decls for.
288 module: *Module,
287 pt: Zcu.PerThread,
289288
290289 /// The SPIR-V module that instructions should be emitted into.
291290 /// This is the same as `self.object.spv`, repeated here for brevity.
......@@ -333,7 +332,7 @@ const DeclGen = struct {
333332
334333 /// If `gen` returned `Error.CodegenFail`, this contains an explanatory message.
335334 /// Memory is owned by `module.gpa`.
336 error_msg: ?*Module.ErrorMsg = null,
335 error_msg: ?*Zcu.ErrorMsg = null,
337336
338337 /// Possible errors the `genDecl` function may return.
339338 const Error = error{ CodegenFail, OutOfMemory };
......@@ -410,15 +409,15 @@ const DeclGen = struct {
410409
411410 /// Return the target which we are currently compiling for.
412411 pub fn getTarget(self: *DeclGen) std.Target {
413 return self.module.getTarget();
412 return self.pt.zcu.getTarget();
414413 }
415414
416415 pub fn fail(self: *DeclGen, comptime format: []const u8, args: anytype) Error {
417416 @setCold(true);
418 const mod = self.module;
419 const src_loc = self.module.declPtr(self.decl_index).navSrcLoc(mod);
417 const zcu = self.pt.zcu;
418 const src_loc = zcu.declPtr(self.decl_index).navSrcLoc(zcu);
420419 assert(self.error_msg == null);
421 self.error_msg = try Module.ErrorMsg.create(self.module.gpa, src_loc, format, args);
420 self.error_msg = try Zcu.ErrorMsg.create(zcu.gpa, src_loc, format, args);
422421 return error.CodegenFail;
423422 }
424423
......@@ -439,8 +438,9 @@ const DeclGen = struct {
439438
440439 /// Fetch the result-id for a previously generated instruction or constant.
441440 fn resolve(self: *DeclGen, inst: Air.Inst.Ref) !IdRef {
442 const mod = self.module;
443 if (try self.air.value(inst, mod)) |val| {
441 const pt = self.pt;
442 const mod = pt.zcu;
443 if (try self.air.value(inst, pt)) |val| {
444444 const ty = self.typeOf(inst);
445445 if (ty.zigTypeTag(mod) == .Fn) {
446446 const fn_decl_index = switch (mod.intern_pool.indexToKey(val.ip_index)) {
......@@ -462,7 +462,7 @@ const DeclGen = struct {
462462 fn resolveAnonDecl(self: *DeclGen, val: InternPool.Index) !IdRef {
463463 // TODO: This cannot be a function at this point, but it should probably be handled anyway.
464464
465 const mod = self.module;
465 const mod = self.pt.zcu;
466466 const ty = Type.fromInterned(mod.intern_pool.typeOf(val));
467467 const decl_ptr_ty_id = try self.ptrType(ty, .Generic);
468468
......@@ -642,7 +642,7 @@ const DeclGen = struct {
642642
643643 /// Checks whether the type can be directly translated to SPIR-V vectors
644644 fn isSpvVector(self: *DeclGen, ty: Type) bool {
645 const mod = self.module;
645 const mod = self.pt.zcu;
646646 const target = self.getTarget();
647647 if (ty.zigTypeTag(mod) != .Vector) return false;
648648
......@@ -668,7 +668,7 @@ const DeclGen = struct {
668668 }
669669
670670 fn arithmeticTypeInfo(self: *DeclGen, ty: Type) ArithmeticTypeInfo {
671 const mod = self.module;
671 const mod = self.pt.zcu;
672672 const target = self.getTarget();
673673 var scalar_ty = ty.scalarType(mod);
674674 if (scalar_ty.zigTypeTag(mod) == .Enum) {
......@@ -744,7 +744,7 @@ const DeclGen = struct {
744744 /// the value to an unsigned int first for Kernels.
745745 fn constInt(self: *DeclGen, ty: Type, value: anytype, repr: Repr) !IdRef {
746746 // TODO: Cache?
747 const mod = self.module;
747 const mod = self.pt.zcu;
748748 const scalar_ty = ty.scalarType(mod);
749749 const int_info = scalar_ty.intInfo(mod);
750750 // Use backing bits so that negatives are sign extended
......@@ -824,7 +824,7 @@ const DeclGen = struct {
824824 /// Construct a vector at runtime.
825825 /// ty must be an vector type.
826826 fn constructVector(self: *DeclGen, ty: Type, constituents: []const IdRef) !IdRef {
827 const mod = self.module;
827 const mod = self.pt.zcu;
828828 assert(ty.vectorLen(mod) == constituents.len);
829829
830830 // Note: older versions of the Khronos SPRIV-LLVM translator crash on this instruction
......@@ -848,7 +848,7 @@ const DeclGen = struct {
848848 /// Construct a vector at runtime with all lanes set to the same value.
849849 /// ty must be an vector type.
850850 fn constructVectorSplat(self: *DeclGen, ty: Type, constituent: IdRef) !IdRef {
851 const mod = self.module;
851 const mod = self.pt.zcu;
852852 const n = ty.vectorLen(mod);
853853
854854 const constituents = try self.gpa.alloc(IdRef, n);
......@@ -886,12 +886,13 @@ const DeclGen = struct {
886886 return id;
887887 }
888888
889 const mod = self.module;
889 const pt = self.pt;
890 const mod = pt.zcu;
890891 const target = self.getTarget();
891892 const result_ty_id = try self.resolveType(ty, repr);
892893 const ip = &mod.intern_pool;
893894
894 log.debug("lowering constant: ty = {}, val = {}", .{ ty.fmt(mod), val.fmtValue(mod, null) });
895 log.debug("lowering constant: ty = {}, val = {}", .{ ty.fmt(pt), val.fmtValue(pt, null) });
895896 if (val.isUndefDeep(mod)) {
896897 return self.spv.constUndef(result_ty_id);
897898 }
......@@ -940,16 +941,16 @@ const DeclGen = struct {
940941 },
941942 .int => {
942943 if (ty.isSignedInt(mod)) {
943 break :cache try self.constInt(ty, val.toSignedInt(mod), repr);
944 break :cache try self.constInt(ty, val.toSignedInt(pt), repr);
944945 } else {
945 break :cache try self.constInt(ty, val.toUnsignedInt(mod), repr);
946 break :cache try self.constInt(ty, val.toUnsignedInt(pt), repr);
946947 }
947948 },
948949 .float => {
949950 const lit: spec.LiteralContextDependentNumber = switch (ty.floatBits(target)) {
950 16 => .{ .uint32 = @as(u16, @bitCast(val.toFloat(f16, mod))) },
951 32 => .{ .float32 = val.toFloat(f32, mod) },
952 64 => .{ .float64 = val.toFloat(f64, mod) },
951 16 => .{ .uint32 = @as(u16, @bitCast(val.toFloat(f16, pt))) },
952 32 => .{ .float32 = val.toFloat(f32, pt) },
953 64 => .{ .float64 = val.toFloat(f64, pt) },
953954 80, 128 => unreachable, // TODO
954955 else => unreachable,
955956 };
......@@ -968,17 +969,17 @@ const DeclGen = struct {
968969 .error_union => |error_union| {
969970 // TODO: Error unions may be constructed with constant instructions if the payload type
970971 // allows it. For now, just generate it here regardless.
971 const err_int_ty = try mod.errorIntType();
972 const err_int_ty = try pt.errorIntType();
972973 const err_ty = switch (error_union.val) {
973974 .err_name => ty.errorUnionSet(mod),
974975 .payload => err_int_ty,
975976 };
976977 const err_val = switch (error_union.val) {
977 .err_name => |err_name| Value.fromInterned((try mod.intern(.{ .err = .{
978 .err_name => |err_name| Value.fromInterned(try pt.intern(.{ .err = .{
978979 .ty = ty.errorUnionSet(mod).toIntern(),
979980 .name = err_name,
980 } }))),
981 .payload => try mod.intValue(err_int_ty, 0),
981 } })),
982 .payload => try pt.intValue(err_int_ty, 0),
982983 };
983984 const payload_ty = ty.errorUnionPayload(mod);
984985 const eu_layout = self.errorUnionLayout(payload_ty);
......@@ -988,7 +989,7 @@ const DeclGen = struct {
988989 }
989990
990991 const payload_val = Value.fromInterned(switch (error_union.val) {
991 .err_name => try mod.intern(.{ .undef = payload_ty.toIntern() }),
992 .err_name => try pt.intern(.{ .undef = payload_ty.toIntern() }),
992993 .payload => |payload| payload,
993994 });
994995
......@@ -1007,7 +1008,7 @@ const DeclGen = struct {
10071008 return try self.constructStruct(ty, &types, &constituents);
10081009 },
10091010 .enum_tag => {
1010 const int_val = try val.intFromEnum(ty, mod);
1011 const int_val = try val.intFromEnum(ty, pt);
10111012 const int_ty = ty.intTagType(mod);
10121013 break :cache try self.constant(int_ty, int_val, repr);
10131014 },
......@@ -1026,7 +1027,7 @@ const DeclGen = struct {
10261027 const payload_ty = ty.optionalChild(mod);
10271028 const maybe_payload_val = val.optionalValue(mod);
10281029
1029 if (!payload_ty.hasRuntimeBits(mod)) {
1030 if (!payload_ty.hasRuntimeBits(pt)) {
10301031 break :cache try self.constBool(maybe_payload_val != null, .indirect);
10311032 } else if (ty.optionalReprIsPayload(mod)) {
10321033 // Optional representation is a nullable pointer or slice.
......@@ -1104,13 +1105,13 @@ const DeclGen = struct {
11041105 var it = struct_type.iterateRuntimeOrder(ip);
11051106 while (it.next()) |field_index| {
11061107 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
1107 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) {
1108 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) {
11081109 // This is a zero-bit field - we only needed it for the alignment.
11091110 continue;
11101111 }
11111112
11121113 // TODO: Padding?
1113 const field_val = try val.fieldValue(mod, field_index);
1114 const field_val = try val.fieldValue(pt, field_index);
11141115 const field_id = try self.constant(field_ty, field_val, .indirect);
11151116
11161117 try types.append(field_ty);
......@@ -1126,7 +1127,7 @@ const DeclGen = struct {
11261127 const active_field = ty.unionTagFieldIndex(Value.fromInterned(un.tag), mod).?;
11271128 const union_obj = mod.typeToUnion(ty).?;
11281129 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[active_field]);
1129 const payload = if (field_ty.hasRuntimeBitsIgnoreComptime(mod))
1130 const payload = if (field_ty.hasRuntimeBitsIgnoreComptime(pt))
11301131 try self.constant(field_ty, Value.fromInterned(un.val), .direct)
11311132 else
11321133 null;
......@@ -1144,10 +1145,10 @@ const DeclGen = struct {
11441145 fn constantPtr(self: *DeclGen, ptr_val: Value) Error!IdRef {
11451146 // TODO: Caching??
11461147
1147 const zcu = self.module;
1148 const pt = self.pt;
11481149
1149 if (ptr_val.isUndef(zcu)) {
1150 const result_ty = ptr_val.typeOf(zcu);
1150 if (ptr_val.isUndef(pt.zcu)) {
1151 const result_ty = ptr_val.typeOf(pt.zcu);
11511152 const result_ty_id = try self.resolveType(result_ty, .direct);
11521153 return self.spv.constUndef(result_ty_id);
11531154 }
......@@ -1155,12 +1156,13 @@ const DeclGen = struct {
11551156 var arena = std.heap.ArenaAllocator.init(self.gpa);
11561157 defer arena.deinit();
11571158
1158 const derivation = try ptr_val.pointerDerivation(arena.allocator(), zcu);
1159 const derivation = try ptr_val.pointerDerivation(arena.allocator(), pt);
11591160 return self.derivePtr(derivation);
11601161 }
11611162
11621163 fn derivePtr(self: *DeclGen, derivation: Value.PointerDeriveStep) Error!IdRef {
1163 const zcu = self.module;
1164 const pt = self.pt;
1165 const zcu = pt.zcu;
11641166 switch (derivation) {
11651167 .comptime_alloc_ptr, .comptime_field_ptr => unreachable,
11661168 .int => |int| {
......@@ -1172,12 +1174,12 @@ const DeclGen = struct {
11721174 try self.func.body.emit(self.spv.gpa, .OpConvertUToPtr, .{
11731175 .id_result_type = result_ty_id,
11741176 .id_result = result_ptr_id,
1175 .integer_value = try self.constant(Type.usize, try zcu.intValue(Type.usize, int.addr), .direct),
1177 .integer_value = try self.constant(Type.usize, try pt.intValue(Type.usize, int.addr), .direct),
11761178 });
11771179 return result_ptr_id;
11781180 },
11791181 .decl_ptr => |decl| {
1180 const result_ptr_ty = try zcu.declPtr(decl).declPtrType(zcu);
1182 const result_ptr_ty = try zcu.declPtr(decl).declPtrType(pt);
11811183 return self.constantDeclRef(result_ptr_ty, decl);
11821184 },
11831185 .anon_decl_ptr => |ad| {
......@@ -1188,18 +1190,18 @@ const DeclGen = struct {
11881190 .opt_payload_ptr => @panic("TODO"),
11891191 .field_ptr => |field| {
11901192 const parent_ptr_id = try self.derivePtr(field.parent.*);
1191 const parent_ptr_ty = try field.parent.ptrType(zcu);
1193 const parent_ptr_ty = try field.parent.ptrType(pt);
11921194 return self.structFieldPtr(field.result_ptr_ty, parent_ptr_ty, parent_ptr_id, field.field_idx);
11931195 },
11941196 .elem_ptr => |elem| {
11951197 const parent_ptr_id = try self.derivePtr(elem.parent.*);
1196 const parent_ptr_ty = try elem.parent.ptrType(zcu);
1198 const parent_ptr_ty = try elem.parent.ptrType(pt);
11971199 const index_id = try self.constInt(Type.usize, elem.elem_idx, .direct);
11981200 return self.ptrElemPtr(parent_ptr_ty, parent_ptr_id, index_id);
11991201 },
12001202 .offset_and_cast => |oac| {
12011203 const parent_ptr_id = try self.derivePtr(oac.parent.*);
1202 const parent_ptr_ty = try oac.parent.ptrType(zcu);
1204 const parent_ptr_ty = try oac.parent.ptrType(pt);
12031205 disallow: {
12041206 if (oac.byte_offset != 0) break :disallow;
12051207 // Allow changing the pointer type child only to restructure arrays.
......@@ -1218,8 +1220,8 @@ const DeclGen = struct {
12181220 return result_ptr_id;
12191221 }
12201222 return self.fail("Cannot perform pointer cast: '{}' to '{}'", .{
1221 parent_ptr_ty.fmt(zcu),
1222 oac.new_ptr_ty.fmt(zcu),
1223 parent_ptr_ty.fmt(pt),
1224 oac.new_ptr_ty.fmt(pt),
12231225 });
12241226 },
12251227 }
......@@ -1232,7 +1234,8 @@ const DeclGen = struct {
12321234 ) !IdRef {
12331235 // TODO: Merge this function with constantDeclRef.
12341236
1235 const mod = self.module;
1237 const pt = self.pt;
1238 const mod = pt.zcu;
12361239 const ip = &mod.intern_pool;
12371240 const ty_id = try self.resolveType(ty, .direct);
12381241 const decl_val = anon_decl.val;
......@@ -1247,7 +1250,7 @@ const DeclGen = struct {
12471250 }
12481251
12491252 // const is_fn_body = decl_ty.zigTypeTag(mod) == .Fn;
1250 if (!decl_ty.isFnOrHasRuntimeBitsIgnoreComptime(mod)) {
1253 if (!decl_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt)) {
12511254 // Pointer to nothing - return undefoined
12521255 return self.spv.constUndef(ty_id);
12531256 }
......@@ -1276,7 +1279,8 @@ const DeclGen = struct {
12761279 }
12771280
12781281 fn constantDeclRef(self: *DeclGen, ty: Type, decl_index: InternPool.DeclIndex) !IdRef {
1279 const mod = self.module;
1282 const pt = self.pt;
1283 const mod = pt.zcu;
12801284 const ty_id = try self.resolveType(ty, .direct);
12811285 const decl = mod.declPtr(decl_index);
12821286
......@@ -1290,7 +1294,7 @@ const DeclGen = struct {
12901294 else => {},
12911295 }
12921296
1293 if (!decl.typeOf(mod).isFnOrHasRuntimeBitsIgnoreComptime(mod)) {
1297 if (!decl.typeOf(mod).isFnOrHasRuntimeBitsIgnoreComptime(pt)) {
12941298 // Pointer to nothing - return undefined.
12951299 return self.spv.constUndef(ty_id);
12961300 }
......@@ -1331,7 +1335,7 @@ const DeclGen = struct {
13311335 fn resolveTypeName(self: *DeclGen, ty: Type) ![]const u8 {
13321336 var name = std.ArrayList(u8).init(self.gpa);
13331337 defer name.deinit();
1334 try ty.print(name.writer(), self.module);
1338 try ty.print(name.writer(), self.pt);
13351339 return try name.toOwnedSlice();
13361340 }
13371341
......@@ -1424,14 +1428,14 @@ const DeclGen = struct {
14241428 }
14251429
14261430 fn zigScalarOrVectorTypeLike(self: *DeclGen, new_ty: Type, base_ty: Type) !Type {
1427 const mod = self.module;
1428 const new_scalar_ty = new_ty.scalarType(mod);
1429 if (!base_ty.isVector(mod)) {
1431 const pt = self.pt;
1432 const new_scalar_ty = new_ty.scalarType(pt.zcu);
1433 if (!base_ty.isVector(pt.zcu)) {
14301434 return new_scalar_ty;
14311435 }
14321436
1433 return try mod.vectorType(.{
1434 .len = base_ty.vectorLen(mod),
1437 return try pt.vectorType(.{
1438 .len = base_ty.vectorLen(pt.zcu),
14351439 .child = new_scalar_ty.toIntern(),
14361440 });
14371441 }
......@@ -1455,7 +1459,7 @@ const DeclGen = struct {
14551459 /// }
14561460 /// If any of the fields' size is 0, it will be omitted.
14571461 fn resolveUnionType(self: *DeclGen, ty: Type) !IdRef {
1458 const mod = self.module;
1462 const mod = self.pt.zcu;
14591463 const ip = &mod.intern_pool;
14601464 const union_obj = mod.typeToUnion(ty).?;
14611465
......@@ -1506,12 +1510,12 @@ const DeclGen = struct {
15061510 }
15071511
15081512 fn resolveFnReturnType(self: *DeclGen, ret_ty: Type) !IdRef {
1509 const mod = self.module;
1510 if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
1513 const pt = self.pt;
1514 if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
15111515 // If the return type is an error set or an error union, then we make this
15121516 // anyerror return type instead, so that it can be coerced into a function
15131517 // pointer type which has anyerror as the return type.
1514 if (ret_ty.isError(mod)) {
1518 if (ret_ty.isError(pt.zcu)) {
15151519 return self.resolveType(Type.anyerror, .direct);
15161520 } else {
15171521 return self.resolveType(Type.void, .direct);
......@@ -1533,9 +1537,10 @@ const DeclGen = struct {
15331537 }
15341538
15351539 fn resolveTypeInner(self: *DeclGen, ty: Type, repr: Repr) Error!IdRef {
1536 const mod = self.module;
1540 const pt = self.pt;
1541 const mod = pt.zcu;
15371542 const ip = &mod.intern_pool;
1538 log.debug("resolveType: ty = {}", .{ty.fmt(mod)});
1543 log.debug("resolveType: ty = {}", .{ty.fmt(pt)});
15391544 const target = self.getTarget();
15401545
15411546 const section = &self.spv.sections.types_globals_constants;
......@@ -1607,7 +1612,7 @@ const DeclGen = struct {
16071612 return self.fail("array type of {} elements is too large", .{ty.arrayLenIncludingSentinel(mod)});
16081613 };
16091614
1610 if (!elem_ty.hasRuntimeBitsIgnoreComptime(mod)) {
1615 if (!elem_ty.hasRuntimeBitsIgnoreComptime(pt)) {
16111616 // The size of the array would be 0, but that is not allowed in SPIR-V.
16121617 // This path can be reached when the backend is asked to generate a pointer to
16131618 // an array of some zero-bit type. This should always be an indirect path.
......@@ -1655,7 +1660,7 @@ const DeclGen = struct {
16551660 var param_index: usize = 0;
16561661 for (fn_info.param_types.get(ip)) |param_ty_index| {
16571662 const param_ty = Type.fromInterned(param_ty_index);
1658 if (!param_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
1663 if (!param_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
16591664
16601665 param_ty_ids[param_index] = try self.resolveType(param_ty, .direct);
16611666 param_index += 1;
......@@ -1713,7 +1718,7 @@ const DeclGen = struct {
17131718
17141719 var member_index: usize = 0;
17151720 for (tuple.types.get(ip), tuple.values.get(ip)) |field_ty, field_val| {
1716 if (field_val != .none or !Type.fromInterned(field_ty).hasRuntimeBits(mod)) continue;
1721 if (field_val != .none or !Type.fromInterned(field_ty).hasRuntimeBits(pt)) continue;
17171722
17181723 member_types[member_index] = try self.resolveType(Type.fromInterned(field_ty), .indirect);
17191724 member_index += 1;
......@@ -1742,13 +1747,13 @@ const DeclGen = struct {
17421747 var it = struct_type.iterateRuntimeOrder(ip);
17431748 while (it.next()) |field_index| {
17441749 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
1745 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) {
1750 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) {
17461751 // This is a zero-bit field - we only needed it for the alignment.
17471752 continue;
17481753 }
17491754
17501755 const field_name = struct_type.fieldName(ip, field_index).unwrap() orelse
1751 try ip.getOrPutStringFmt(mod.gpa, "{d}", .{field_index}, .no_embedded_nulls);
1756 try ip.getOrPutStringFmt(mod.gpa, pt.tid, "{d}", .{field_index}, .no_embedded_nulls);
17521757 try member_types.append(try self.resolveType(field_ty, .indirect));
17531758 try member_names.append(field_name.toSlice(ip));
17541759 }
......@@ -1761,7 +1766,7 @@ const DeclGen = struct {
17611766 },
17621767 .Optional => {
17631768 const payload_ty = ty.optionalChild(mod);
1764 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
1769 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
17651770 // Just use a bool.
17661771 // Note: Always generate the bool with indirect format, to save on some sanity
17671772 // Perform the conversion to a direct bool when the field is extracted.
......@@ -1878,14 +1883,14 @@ const DeclGen = struct {
18781883 };
18791884
18801885 fn errorUnionLayout(self: *DeclGen, payload_ty: Type) ErrorUnionLayout {
1881 const mod = self.module;
1886 const pt = self.pt;
18821887
1883 const error_align = Type.anyerror.abiAlignment(mod);
1884 const payload_align = payload_ty.abiAlignment(mod);
1888 const error_align = Type.anyerror.abiAlignment(pt);
1889 const payload_align = payload_ty.abiAlignment(pt);
18851890
18861891 const error_first = error_align.compare(.gt, payload_align);
18871892 return .{
1888 .payload_has_bits = payload_ty.hasRuntimeBitsIgnoreComptime(mod),
1893 .payload_has_bits = payload_ty.hasRuntimeBitsIgnoreComptime(pt),
18891894 .error_first = error_first,
18901895 };
18911896 }
......@@ -1909,9 +1914,10 @@ const DeclGen = struct {
19091914 };
19101915
19111916 fn unionLayout(self: *DeclGen, ty: Type) UnionLayout {
1912 const mod = self.module;
1917 const pt = self.pt;
1918 const mod = pt.zcu;
19131919 const ip = &mod.intern_pool;
1914 const layout = ty.unionGetLayout(self.module);
1920 const layout = ty.unionGetLayout(pt);
19151921 const union_obj = mod.typeToUnion(ty).?;
19161922
19171923 var union_layout = UnionLayout{
......@@ -1932,7 +1938,7 @@ const DeclGen = struct {
19321938 const most_aligned_field = layout.most_aligned_field;
19331939 const most_aligned_field_ty = Type.fromInterned(union_obj.field_types.get(ip)[most_aligned_field]);
19341940 union_layout.payload_ty = most_aligned_field_ty;
1935 union_layout.payload_size = @intCast(most_aligned_field_ty.abiSize(mod));
1941 union_layout.payload_size = @intCast(most_aligned_field_ty.abiSize(pt));
19361942 } else {
19371943 union_layout.payload_size = 0;
19381944 }
......@@ -1999,7 +2005,7 @@ const DeclGen = struct {
19992005 }
20002006
20012007 fn materialize(self: Temporary, dg: *DeclGen) !IdResult {
2002 const mod = dg.module;
2008 const mod = dg.pt.zcu;
20032009 switch (self.value) {
20042010 .singleton => |id| return id,
20052011 .exploded_vector => |range| {
......@@ -2029,12 +2035,12 @@ const DeclGen = struct {
20292035 /// 'Explode' a temporary into separate elements. This turns a vector
20302036 /// into a bag of elements.
20312037 fn explode(self: Temporary, dg: *DeclGen) !IdRange {
2032 const mod = dg.module;
2038 const mod = dg.pt.zcu;
20332039
20342040 // If the value is a scalar, then this is a no-op.
20352041 if (!self.ty.isVector(mod)) {
20362042 return switch (self.value) {
2037 .singleton => |id| IdRange{ .base = @intFromEnum(id), .len = 1 },
2043 .singleton => |id| .{ .base = @intFromEnum(id), .len = 1 },
20382044 .exploded_vector => |range| range,
20392045 };
20402046 }
......@@ -2088,7 +2094,7 @@ const DeclGen = struct {
20882094 /// only checks the size, but the source-of-truth is implemented
20892095 /// by `isSpvVector()`.
20902096 fn fromType(ty: Type, dg: *DeclGen) Vectorization {
2091 const mod = dg.module;
2097 const mod = dg.pt.zcu;
20922098 if (!ty.isVector(mod)) {
20932099 return .scalar;
20942100 } else if (dg.isSpvVector(ty)) {
......@@ -2164,11 +2170,11 @@ const DeclGen = struct {
21642170 /// Turns `ty` into the result-type of an individual vector operation.
21652171 /// `ty` may be a scalar or vector, it doesn't matter.
21662172 fn operationType(self: Vectorization, dg: *DeclGen, ty: Type) !Type {
2167 const mod = dg.module;
2168 const scalar_ty = ty.scalarType(mod);
2173 const pt = dg.pt;
2174 const scalar_ty = ty.scalarType(pt.zcu);
21692175 return switch (self) {
21702176 .scalar, .unrolled => scalar_ty,
2171 .spv_vectorized => |n| try mod.vectorType(.{
2177 .spv_vectorized => |n| try pt.vectorType(.{
21722178 .len = n,
21732179 .child = scalar_ty.toIntern(),
21742180 }),
......@@ -2178,11 +2184,11 @@ const DeclGen = struct {
21782184 /// Turns `ty` into the result-type of the entire operation.
21792185 /// `ty` may be a scalar or vector, it doesn't matter.
21802186 fn resultType(self: Vectorization, dg: *DeclGen, ty: Type) !Type {
2181 const mod = dg.module;
2182 const scalar_ty = ty.scalarType(mod);
2187 const pt = dg.pt;
2188 const scalar_ty = ty.scalarType(pt.zcu);
21832189 return switch (self) {
21842190 .scalar => scalar_ty,
2185 .unrolled, .spv_vectorized => |n| try mod.vectorType(.{
2191 .unrolled, .spv_vectorized => |n| try pt.vectorType(.{
21862192 .len = n,
21872193 .child = scalar_ty.toIntern(),
21882194 }),
......@@ -2193,8 +2199,8 @@ const DeclGen = struct {
21932199 /// this setup, and returns a new type that holds the relevant information on how to access
21942200 /// elements of the input.
21952201 fn prepare(self: Vectorization, dg: *DeclGen, tmp: Temporary) !PreparedOperand {
2196 const mod = dg.module;
2197 const is_vector = tmp.ty.isVector(mod);
2202 const pt = dg.pt;
2203 const is_vector = tmp.ty.isVector(pt.zcu);
21982204 const is_spv_vector = dg.isSpvVector(tmp.ty);
21992205 const value: PreparedOperand.Value = switch (tmp.value) {
22002206 .singleton => |id| switch (self) {
......@@ -2209,7 +2215,7 @@ const DeclGen = struct {
22092215 }
22102216
22112217 // Broadcast scalar into vector.
2212 const vector_ty = try mod.vectorType(.{
2218 const vector_ty = try pt.vectorType(.{
22132219 .len = self.components(),
22142220 .child = tmp.ty.toIntern(),
22152221 });
......@@ -2340,7 +2346,7 @@ const DeclGen = struct {
23402346 /// This function builds an OpSConvert of OpUConvert depending on the
23412347 /// signedness of the types.
23422348 fn buildIntConvert(self: *DeclGen, dst_ty: Type, src: Temporary) !Temporary {
2343 const mod = self.module;
2349 const mod = self.pt.zcu;
23442350
23452351 const dst_ty_id = try self.resolveType(dst_ty.scalarType(mod), .direct);
23462352 const src_ty_id = try self.resolveType(src.ty.scalarType(mod), .direct);
......@@ -2419,7 +2425,7 @@ const DeclGen = struct {
24192425 }
24202426
24212427 fn buildSelect(self: *DeclGen, condition: Temporary, lhs: Temporary, rhs: Temporary) !Temporary {
2422 const mod = self.module;
2428 const mod = self.pt.zcu;
24232429
24242430 const v = self.vectorization(.{ condition, lhs, rhs });
24252431 const ops = v.operations();
......@@ -2764,7 +2770,8 @@ const DeclGen = struct {
27642770 lhs: Temporary,
27652771 rhs: Temporary,
27662772 ) !struct { Temporary, Temporary } {
2767 const mod = self.module;
2773 const pt = self.pt;
2774 const mod = pt.zcu;
27682775 const target = self.getTarget();
27692776 const ip = &mod.intern_pool;
27702777
......@@ -2814,7 +2821,7 @@ const DeclGen = struct {
28142821 // where T is maybe vectorized.
28152822 const types = [2]InternPool.Index{ arith_op_ty.toIntern(), arith_op_ty.toIntern() };
28162823 const values = [2]InternPool.Index{ .none, .none };
2817 const index = try ip.getAnonStructType(mod.gpa, .{
2824 const index = try ip.getAnonStructType(mod.gpa, pt.tid, .{
28182825 .types = &types,
28192826 .values = &values,
28202827 .names = &.{},
......@@ -2888,7 +2895,7 @@ const DeclGen = struct {
28882895 /// the name of an error in the text executor.
28892896 fn generateTestEntryPoint(self: *DeclGen, name: []const u8, spv_test_decl_index: SpvModule.Decl.Index) !void {
28902897 const anyerror_ty_id = try self.resolveType(Type.anyerror, .direct);
2891 const ptr_anyerror_ty = try self.module.ptrType(.{
2898 const ptr_anyerror_ty = try self.pt.ptrType(.{
28922899 .child = Type.anyerror.toIntern(),
28932900 .flags = .{ .address_space = .global },
28942901 });
......@@ -2940,7 +2947,8 @@ const DeclGen = struct {
29402947 }
29412948
29422949 fn genDecl(self: *DeclGen) !void {
2943 const mod = self.module;
2950 const pt = self.pt;
2951 const mod = pt.zcu;
29442952 const ip = &mod.intern_pool;
29452953 const decl = mod.declPtr(self.decl_index);
29462954 const spv_decl_index = try self.object.resolveDecl(mod, self.decl_index);
......@@ -2967,7 +2975,7 @@ const DeclGen = struct {
29672975 try self.args.ensureUnusedCapacity(self.gpa, fn_info.param_types.len);
29682976 for (fn_info.param_types.get(ip)) |param_ty_index| {
29692977 const param_ty = Type.fromInterned(param_ty_index);
2970 if (!param_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
2978 if (!param_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
29712979
29722980 const param_type_id = try self.resolveType(param_ty, .direct);
29732981 const arg_result_id = self.spv.allocId();
......@@ -3004,11 +3012,11 @@ const DeclGen = struct {
30043012 // Append the actual code into the functions section.
30053013 try self.spv.addFunction(spv_decl_index, self.func);
30063014
3007 const fqn = try decl.fullyQualifiedName(self.module);
3015 const fqn = try decl.fullyQualifiedName(self.pt);
30083016 try self.spv.debugName(result_id, fqn.toSlice(ip));
30093017
30103018 // Temporarily generate a test kernel declaration if this is a test function.
3011 if (self.module.test_functions.contains(self.decl_index)) {
3019 if (self.pt.zcu.test_functions.contains(self.decl_index)) {
30123020 try self.generateTestEntryPoint(fqn.toSlice(ip), spv_decl_index);
30133021 }
30143022 },
......@@ -3033,7 +3041,7 @@ const DeclGen = struct {
30333041 .storage_class = final_storage_class,
30343042 });
30353043
3036 const fqn = try decl.fullyQualifiedName(self.module);
3044 const fqn = try decl.fullyQualifiedName(self.pt);
30373045 try self.spv.debugName(result_id, fqn.toSlice(ip));
30383046 try self.spv.declareDeclDeps(spv_decl_index, &.{});
30393047 },
......@@ -3078,7 +3086,7 @@ const DeclGen = struct {
30783086 try self.func.body.emit(self.spv.gpa, .OpFunctionEnd, {});
30793087 try self.spv.addFunction(spv_decl_index, self.func);
30803088
3081 const fqn = try decl.fullyQualifiedName(self.module);
3089 const fqn = try decl.fullyQualifiedName(self.pt);
30823090 try self.spv.debugNameFmt(initializer_id, "initializer of {}", .{fqn.fmt(ip)});
30833091
30843092 try self.spv.sections.types_globals_constants.emit(self.spv.gpa, .OpExtInst, .{
......@@ -3119,7 +3127,7 @@ const DeclGen = struct {
31193127 /// Convert representation from indirect (in memory) to direct (in 'register')
31203128 /// This converts the argument type from resolveType(ty, .indirect) to resolveType(ty, .direct).
31213129 fn convertToDirect(self: *DeclGen, ty: Type, operand_id: IdRef) !IdRef {
3122 const mod = self.module;
3130 const mod = self.pt.zcu;
31233131 switch (ty.scalarType(mod).zigTypeTag(mod)) {
31243132 .Bool => {
31253133 const false_id = try self.constBool(false, .indirect);
......@@ -3145,7 +3153,7 @@ const DeclGen = struct {
31453153 /// Convert representation from direct (in 'register) to direct (in memory)
31463154 /// This converts the argument type from resolveType(ty, .direct) to resolveType(ty, .indirect).
31473155 fn convertToIndirect(self: *DeclGen, ty: Type, operand_id: IdRef) !IdRef {
3148 const mod = self.module;
3156 const mod = self.pt.zcu;
31493157 switch (ty.scalarType(mod).zigTypeTag(mod)) {
31503158 .Bool => {
31513159 const result = try self.intFromBool(Temporary.init(ty, operand_id));
......@@ -3222,7 +3230,7 @@ const DeclGen = struct {
32223230 }
32233231
32243232 fn genInst(self: *DeclGen, inst: Air.Inst.Index) !void {
3225 const mod = self.module;
3233 const mod = self.pt.zcu;
32263234 const ip = &mod.intern_pool;
32273235 if (self.liveness.isUnused(inst) and !self.air.mustLower(inst, ip))
32283236 return;
......@@ -3402,7 +3410,7 @@ const DeclGen = struct {
34023410 }
34033411
34043412 fn airShift(self: *DeclGen, inst: Air.Inst.Index, unsigned: BinaryOp, signed: BinaryOp) !?IdRef {
3405 const mod = self.module;
3413 const mod = self.pt.zcu;
34063414 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
34073415
34083416 const base = try self.temporary(bin_op.lhs);
......@@ -3480,7 +3488,7 @@ const DeclGen = struct {
34803488 /// All other values are returned unmodified (this makes strange integer
34813489 /// wrapping easier to use in generic operations).
34823490 fn normalize(self: *DeclGen, value: Temporary, info: ArithmeticTypeInfo) !Temporary {
3483 const mod = self.module;
3491 const mod = self.pt.zcu;
34843492 const ty = value.ty;
34853493 switch (info.class) {
34863494 .integer, .bool, .float => return value,
......@@ -3721,7 +3729,7 @@ const DeclGen = struct {
37213729
37223730 fn airMulOverflow(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
37233731 const target = self.getTarget();
3724 const mod = self.module;
3732 const pt = self.pt;
37253733
37263734 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
37273735 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
......@@ -3758,7 +3766,7 @@ const DeclGen = struct {
37583766 const result, const overflowed = switch (info.signedness) {
37593767 .unsigned => blk: {
37603768 if (maybe_op_ty_bits) |op_ty_bits| {
3761 const op_ty = try mod.intType(.unsigned, op_ty_bits);
3769 const op_ty = try pt.intType(.unsigned, op_ty_bits);
37623770 const casted_lhs = try self.buildIntConvert(op_ty, lhs);
37633771 const casted_rhs = try self.buildIntConvert(op_ty, rhs);
37643772
......@@ -3828,7 +3836,7 @@ const DeclGen = struct {
38283836 );
38293837
38303838 if (maybe_op_ty_bits) |op_ty_bits| {
3831 const op_ty = try mod.intType(.signed, op_ty_bits);
3839 const op_ty = try pt.intType(.signed, op_ty_bits);
38323840 // Assume normalized; sign bit is set. We want a sign extend.
38333841 const casted_lhs = try self.buildIntConvert(op_ty, lhs);
38343842 const casted_rhs = try self.buildIntConvert(op_ty, rhs);
......@@ -3900,7 +3908,7 @@ const DeclGen = struct {
39003908 }
39013909
39023910 fn airShlOverflow(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
3903 const mod = self.module;
3911 const mod = self.pt.zcu;
39043912
39053913 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
39063914 const extra = self.air.extraData(Air.Bin, ty_pl.payload).data;
......@@ -3958,7 +3966,7 @@ const DeclGen = struct {
39583966 fn airClzCtz(self: *DeclGen, inst: Air.Inst.Index, op: UnaryOp) !?IdRef {
39593967 if (self.liveness.isUnused(inst)) return null;
39603968
3961 const mod = self.module;
3969 const mod = self.pt.zcu;
39623970 const target = self.getTarget();
39633971 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
39643972 const operand = try self.temporary(ty_op.operand);
......@@ -4007,7 +4015,7 @@ const DeclGen = struct {
40074015 }
40084016
40094017 fn airReduce(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
4010 const mod = self.module;
4018 const mod = self.pt.zcu;
40114019 const reduce = self.air.instructions.items(.data)[@intFromEnum(inst)].reduce;
40124020 const operand = try self.resolve(reduce.operand);
40134021 const operand_ty = self.typeOf(reduce.operand);
......@@ -4082,7 +4090,8 @@ const DeclGen = struct {
40824090 }
40834091
40844092 fn airShuffle(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
4085 const mod = self.module;
4093 const pt = self.pt;
4094 const mod = pt.zcu;
40864095 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
40874096 const extra = self.air.extraData(Air.Shuffle, ty_pl.payload).data;
40884097 const a = try self.resolve(extra.a);
......@@ -4108,14 +4117,14 @@ const DeclGen = struct {
41084117 const a_len = a_ty.vectorLen(mod);
41094118
41104119 for (components, 0..) |*component, i| {
4111 const elem = try mask.elemValue(mod, i);
4120 const elem = try mask.elemValue(pt, i);
41124121 if (elem.isUndef(mod)) {
41134122 // This is explicitly valid for OpVectorShuffle, it indicates undefined.
41144123 component.* = 0xFFFF_FFFF;
41154124 continue;
41164125 }
41174126
4118 const index = elem.toSignedInt(mod);
4127 const index = elem.toSignedInt(pt);
41194128 if (index >= 0) {
41204129 component.* = @intCast(index);
41214130 } else {
......@@ -4140,13 +4149,13 @@ const DeclGen = struct {
41404149 defer self.gpa.free(components);
41414150
41424151 for (components, 0..) |*id, i| {
4143 const elem = try mask.elemValue(mod, i);
4152 const elem = try mask.elemValue(pt, i);
41444153 if (elem.isUndef(mod)) {
41454154 id.* = try self.spv.constUndef(scalar_ty_id);
41464155 continue;
41474156 }
41484157
4149 const index = elem.toSignedInt(mod);
4158 const index = elem.toSignedInt(pt);
41504159 if (index >= 0) {
41514160 id.* = try self.extractVectorComponent(scalar_ty, a, @intCast(index));
41524161 } else {
......@@ -4220,7 +4229,7 @@ const DeclGen = struct {
42204229 }
42214230
42224231 fn ptrAdd(self: *DeclGen, result_ty: Type, ptr_ty: Type, ptr_id: IdRef, offset_id: IdRef) !IdRef {
4223 const mod = self.module;
4232 const mod = self.pt.zcu;
42244233 const result_ty_id = try self.resolveType(result_ty, .direct);
42254234
42264235 switch (ptr_ty.ptrSize(mod)) {
......@@ -4276,7 +4285,8 @@ const DeclGen = struct {
42764285 lhs: Temporary,
42774286 rhs: Temporary,
42784287 ) !Temporary {
4279 const mod = self.module;
4288 const pt = self.pt;
4289 const mod = pt.zcu;
42804290 const scalar_ty = lhs.ty.scalarType(mod);
42814291 const is_vector = lhs.ty.isVector(mod);
42824292
......@@ -4324,7 +4334,7 @@ const DeclGen = struct {
43244334
43254335 const payload_ty = ty.optionalChild(mod);
43264336 if (ty.optionalReprIsPayload(mod)) {
4327 assert(payload_ty.hasRuntimeBitsIgnoreComptime(mod));
4337 assert(payload_ty.hasRuntimeBitsIgnoreComptime(pt));
43284338 assert(!payload_ty.isSlice(mod));
43294339
43304340 return try self.cmp(op, lhs.pun(payload_ty), rhs.pun(payload_ty));
......@@ -4333,12 +4343,12 @@ const DeclGen = struct {
43334343 const lhs_id = try lhs.materialize(self);
43344344 const rhs_id = try rhs.materialize(self);
43354345
4336 const lhs_valid_id = if (payload_ty.hasRuntimeBitsIgnoreComptime(mod))
4346 const lhs_valid_id = if (payload_ty.hasRuntimeBitsIgnoreComptime(pt))
43374347 try self.extractField(Type.bool, lhs_id, 1)
43384348 else
43394349 try self.convertToDirect(Type.bool, lhs_id);
43404350
4341 const rhs_valid_id = if (payload_ty.hasRuntimeBitsIgnoreComptime(mod))
4351 const rhs_valid_id = if (payload_ty.hasRuntimeBitsIgnoreComptime(pt))
43424352 try self.extractField(Type.bool, rhs_id, 1)
43434353 else
43444354 try self.convertToDirect(Type.bool, rhs_id);
......@@ -4346,7 +4356,7 @@ const DeclGen = struct {
43464356 const lhs_valid = Temporary.init(Type.bool, lhs_valid_id);
43474357 const rhs_valid = Temporary.init(Type.bool, rhs_valid_id);
43484358
4349 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4359 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
43504360 return try self.cmp(op, lhs_valid, rhs_valid);
43514361 }
43524362
......@@ -4466,7 +4476,7 @@ const DeclGen = struct {
44664476 src_ty: Type,
44674477 src_id: IdRef,
44684478 ) !IdRef {
4469 const mod = self.module;
4479 const mod = self.pt.zcu;
44704480 const src_ty_id = try self.resolveType(src_ty, .direct);
44714481 const dst_ty_id = try self.resolveType(dst_ty, .direct);
44724482
......@@ -4675,7 +4685,8 @@ const DeclGen = struct {
46754685 }
46764686
46774687 fn airArrayToSlice(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
4678 const mod = self.module;
4688 const pt = self.pt;
4689 const mod = pt.zcu;
46794690 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
46804691 const array_ptr_ty = self.typeOf(ty_op.operand);
46814692 const array_ty = array_ptr_ty.childType(mod);
......@@ -4687,7 +4698,7 @@ const DeclGen = struct {
46874698 const array_ptr_id = try self.resolve(ty_op.operand);
46884699 const len_id = try self.constInt(Type.usize, array_ty.arrayLen(mod), .direct);
46894700
4690 const elem_ptr_id = if (!array_ty.hasRuntimeBitsIgnoreComptime(mod))
4701 const elem_ptr_id = if (!array_ty.hasRuntimeBitsIgnoreComptime(pt))
46914702 // Note: The pointer is something like *opaque{}, so we need to bitcast it to the element type.
46924703 try self.bitCast(elem_ptr_ty, array_ptr_ty, array_ptr_id)
46934704 else
......@@ -4719,7 +4730,8 @@ const DeclGen = struct {
47194730 }
47204731
47214732 fn airAggregateInit(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
4722 const mod = self.module;
4733 const pt = self.pt;
4734 const mod = pt.zcu;
47234735 const ip = &mod.intern_pool;
47244736 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
47254737 const result_ty = self.typeOfIndex(inst);
......@@ -4742,8 +4754,8 @@ const DeclGen = struct {
47424754 switch (ip.indexToKey(result_ty.toIntern())) {
47434755 .anon_struct_type => |tuple| {
47444756 for (tuple.types.get(ip), elements, 0..) |field_ty, element, i| {
4745 if ((try result_ty.structFieldValueComptime(mod, i)) != null) continue;
4746 assert(Type.fromInterned(field_ty).hasRuntimeBits(mod));
4757 if ((try result_ty.structFieldValueComptime(pt, i)) != null) continue;
4758 assert(Type.fromInterned(field_ty).hasRuntimeBits(pt));
47474759
47484760 const id = try self.resolve(element);
47494761 types[index] = Type.fromInterned(field_ty);
......@@ -4756,9 +4768,9 @@ const DeclGen = struct {
47564768 var it = struct_type.iterateRuntimeOrder(ip);
47574769 for (elements, 0..) |element, i| {
47584770 const field_index = it.next().?;
4759 if ((try result_ty.structFieldValueComptime(mod, i)) != null) continue;
4771 if ((try result_ty.structFieldValueComptime(pt, i)) != null) continue;
47604772 const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[field_index]);
4761 assert(field_ty.hasRuntimeBitsIgnoreComptime(mod));
4773 assert(field_ty.hasRuntimeBitsIgnoreComptime(pt));
47624774
47634775 const id = try self.resolve(element);
47644776 types[index] = field_ty;
......@@ -4808,13 +4820,14 @@ const DeclGen = struct {
48084820 }
48094821
48104822 fn sliceOrArrayLen(self: *DeclGen, operand_id: IdRef, ty: Type) !IdRef {
4811 const mod = self.module;
4823 const pt = self.pt;
4824 const mod = pt.zcu;
48124825 switch (ty.ptrSize(mod)) {
48134826 .Slice => return self.extractField(Type.usize, operand_id, 1),
48144827 .One => {
48154828 const array_ty = ty.childType(mod);
48164829 const elem_ty = array_ty.childType(mod);
4817 const abi_size = elem_ty.abiSize(mod);
4830 const abi_size = elem_ty.abiSize(pt);
48184831 const size = array_ty.arrayLenIncludingSentinel(mod) * abi_size;
48194832 return try self.constInt(Type.usize, size, .direct);
48204833 },
......@@ -4823,7 +4836,7 @@ const DeclGen = struct {
48234836 }
48244837
48254838 fn sliceOrArrayPtr(self: *DeclGen, operand_id: IdRef, ty: Type) !IdRef {
4826 const mod = self.module;
4839 const mod = self.pt.zcu;
48274840 if (ty.isSlice(mod)) {
48284841 const ptr_ty = ty.slicePtrFieldType(mod);
48294842 return self.extractField(ptr_ty, operand_id, 0);
......@@ -4855,7 +4868,7 @@ const DeclGen = struct {
48554868 }
48564869
48574870 fn airSliceElemPtr(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
4858 const mod = self.module;
4871 const mod = self.pt.zcu;
48594872 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
48604873 const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data;
48614874 const slice_ty = self.typeOf(bin_op.lhs);
......@@ -4872,7 +4885,7 @@ const DeclGen = struct {
48724885 }
48734886
48744887 fn airSliceElemVal(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
4875 const mod = self.module;
4888 const mod = self.pt.zcu;
48764889 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
48774890 const slice_ty = self.typeOf(bin_op.lhs);
48784891 if (!slice_ty.isVolatilePtr(mod) and self.liveness.isUnused(inst)) return null;
......@@ -4889,7 +4902,7 @@ const DeclGen = struct {
48894902 }
48904903
48914904 fn ptrElemPtr(self: *DeclGen, ptr_ty: Type, ptr_id: IdRef, index_id: IdRef) !IdRef {
4892 const mod = self.module;
4905 const mod = self.pt.zcu;
48934906 // Construct new pointer type for the resulting pointer
48944907 const elem_ty = ptr_ty.elemType2(mod); // use elemType() so that we get T for *[N]T.
48954908 const elem_ptr_ty_id = try self.ptrType(elem_ty, self.spvStorageClass(ptr_ty.ptrAddressSpace(mod)));
......@@ -4904,14 +4917,15 @@ const DeclGen = struct {
49044917 }
49054918
49064919 fn airPtrElemPtr(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
4907 const mod = self.module;
4920 const pt = self.pt;
4921 const mod = pt.zcu;
49084922 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
49094923 const bin_op = self.air.extraData(Air.Bin, ty_pl.payload).data;
49104924 const src_ptr_ty = self.typeOf(bin_op.lhs);
49114925 const elem_ty = src_ptr_ty.childType(mod);
49124926 const ptr_id = try self.resolve(bin_op.lhs);
49134927
4914 if (!elem_ty.hasRuntimeBitsIgnoreComptime(mod)) {
4928 if (!elem_ty.hasRuntimeBitsIgnoreComptime(pt)) {
49154929 const dst_ptr_ty = self.typeOfIndex(inst);
49164930 return try self.bitCast(dst_ptr_ty, src_ptr_ty, ptr_id);
49174931 }
......@@ -4921,7 +4935,7 @@ const DeclGen = struct {
49214935 }
49224936
49234937 fn airArrayElemVal(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
4924 const mod = self.module;
4938 const mod = self.pt.zcu;
49254939 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
49264940 const array_ty = self.typeOf(bin_op.lhs);
49274941 const elem_ty = array_ty.childType(mod);
......@@ -4982,7 +4996,7 @@ const DeclGen = struct {
49824996 }
49834997
49844998 fn airPtrElemVal(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
4985 const mod = self.module;
4999 const mod = self.pt.zcu;
49865000 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
49875001 const ptr_ty = self.typeOf(bin_op.lhs);
49885002 const elem_ty = self.typeOfIndex(inst);
......@@ -4993,7 +5007,7 @@ const DeclGen = struct {
49935007 }
49945008
49955009 fn airVectorStoreElem(self: *DeclGen, inst: Air.Inst.Index) !void {
4996 const mod = self.module;
5010 const mod = self.pt.zcu;
49975011 const data = self.air.instructions.items(.data)[@intFromEnum(inst)].vector_store_elem;
49985012 const extra = self.air.extraData(Air.Bin, data.payload).data;
49995013
......@@ -5015,7 +5029,7 @@ const DeclGen = struct {
50155029 }
50165030
50175031 fn airSetUnionTag(self: *DeclGen, inst: Air.Inst.Index) !void {
5018 const mod = self.module;
5032 const mod = self.pt.zcu;
50195033 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
50205034 const un_ptr_ty = self.typeOf(bin_op.lhs);
50215035 const un_ty = un_ptr_ty.childType(mod);
......@@ -5041,7 +5055,7 @@ const DeclGen = struct {
50415055 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
50425056 const un_ty = self.typeOf(ty_op.operand);
50435057
5044 const mod = self.module;
5058 const mod = self.pt.zcu;
50455059 const layout = self.unionLayout(un_ty);
50465060 if (layout.tag_size == 0) return null;
50475061
......@@ -5064,7 +5078,8 @@ const DeclGen = struct {
50645078
50655079 // Note: The result here is not cached, because it generates runtime code.
50665080
5067 const mod = self.module;
5081 const pt = self.pt;
5082 const mod = pt.zcu;
50685083 const ip = &mod.intern_pool;
50695084 const union_ty = mod.typeToUnion(ty).?;
50705085 const tag_ty = Type.fromInterned(union_ty.enum_tag_ty);
......@@ -5076,9 +5091,9 @@ const DeclGen = struct {
50765091 const layout = self.unionLayout(ty);
50775092
50785093 const tag_int = if (layout.tag_size != 0) blk: {
5079 const tag_val = try mod.enumValueFieldIndex(tag_ty, active_field);
5080 const tag_int_val = try tag_val.intFromEnum(tag_ty, mod);
5081 break :blk tag_int_val.toUnsignedInt(mod);
5094 const tag_val = try pt.enumValueFieldIndex(tag_ty, active_field);
5095 const tag_int_val = try tag_val.intFromEnum(tag_ty, pt);
5096 break :blk tag_int_val.toUnsignedInt(pt);
50825097 } else 0;
50835098
50845099 if (!layout.has_payload) {
......@@ -5095,7 +5110,7 @@ const DeclGen = struct {
50955110 }
50965111
50975112 const payload_ty = Type.fromInterned(union_ty.field_types.get(ip)[active_field]);
5098 if (payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
5113 if (payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
50995114 const pl_ptr_ty_id = try self.ptrType(layout.payload_ty, .Function);
51005115 const pl_ptr_id = try self.accessChain(pl_ptr_ty_id, tmp_id, &.{layout.payload_index});
51015116 const active_pl_ptr_ty_id = try self.ptrType(payload_ty, .Function);
......@@ -5118,7 +5133,8 @@ const DeclGen = struct {
51185133 }
51195134
51205135 fn airUnionInit(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
5121 const mod = self.module;
5136 const pt = self.pt;
5137 const mod = pt.zcu;
51225138 const ip = &mod.intern_pool;
51235139 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
51245140 const extra = self.air.extraData(Air.UnionInit, ty_pl.payload).data;
......@@ -5126,7 +5142,7 @@ const DeclGen = struct {
51265142
51275143 const union_obj = mod.typeToUnion(ty).?;
51285144 const field_ty = Type.fromInterned(union_obj.field_types.get(ip)[extra.field_index]);
5129 const payload = if (field_ty.hasRuntimeBitsIgnoreComptime(mod))
5145 const payload = if (field_ty.hasRuntimeBitsIgnoreComptime(pt))
51305146 try self.resolve(extra.init)
51315147 else
51325148 null;
......@@ -5134,7 +5150,8 @@ const DeclGen = struct {
51345150 }
51355151
51365152 fn airStructFieldVal(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
5137 const mod = self.module;
5153 const pt = self.pt;
5154 const mod = pt.zcu;
51385155 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
51395156 const struct_field = self.air.extraData(Air.StructField, ty_pl.payload).data;
51405157
......@@ -5143,7 +5160,7 @@ const DeclGen = struct {
51435160 const field_index = struct_field.field_index;
51445161 const field_ty = object_ty.structFieldType(field_index, mod);
51455162
5146 if (!field_ty.hasRuntimeBitsIgnoreComptime(mod)) return null;
5163 if (!field_ty.hasRuntimeBitsIgnoreComptime(pt)) return null;
51475164
51485165 switch (object_ty.zigTypeTag(mod)) {
51495166 .Struct => switch (object_ty.containerLayout(mod)) {
......@@ -5178,7 +5195,8 @@ const DeclGen = struct {
51785195 }
51795196
51805197 fn airFieldParentPtr(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
5181 const mod = self.module;
5198 const pt = self.pt;
5199 const mod = pt.zcu;
51825200 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
51835201 const extra = self.air.extraData(Air.FieldParentPtr, ty_pl.payload).data;
51845202
......@@ -5187,7 +5205,7 @@ const DeclGen = struct {
51875205
51885206 const field_ptr = try self.resolve(extra.field_ptr);
51895207 const field_ptr_int = try self.intFromPtr(field_ptr);
5190 const field_offset = parent_ty.structFieldOffset(extra.field_index, mod);
5208 const field_offset = parent_ty.structFieldOffset(extra.field_index, pt);
51915209
51925210 const base_ptr_int = base_ptr_int: {
51935211 if (field_offset == 0) break :base_ptr_int field_ptr_int;
......@@ -5218,7 +5236,7 @@ const DeclGen = struct {
52185236 ) !IdRef {
52195237 const result_ty_id = try self.resolveType(result_ptr_ty, .direct);
52205238
5221 const zcu = self.module;
5239 const zcu = self.pt.zcu;
52225240 const object_ty = object_ptr_ty.childType(zcu);
52235241 switch (object_ty.zigTypeTag(zcu)) {
52245242 .Pointer => {
......@@ -5312,7 +5330,7 @@ const DeclGen = struct {
53125330 }
53135331
53145332 fn airAlloc(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
5315 const mod = self.module;
5333 const mod = self.pt.zcu;
53165334 const ptr_ty = self.typeOfIndex(inst);
53175335 assert(ptr_ty.ptrAddressSpace(mod) == .generic);
53185336 const child_ty = ptr_ty.childType(mod);
......@@ -5486,9 +5504,10 @@ const DeclGen = struct {
54865504 // of the block, then a label, and then generate the rest of the current
54875505 // ir.Block in a different SPIR-V block.
54885506
5489 const mod = self.module;
5507 const pt = self.pt;
5508 const mod = pt.zcu;
54905509 const ty = self.typeOfIndex(inst);
5491 const have_block_result = ty.isFnOrHasRuntimeBitsIgnoreComptime(mod);
5510 const have_block_result = ty.isFnOrHasRuntimeBitsIgnoreComptime(pt);
54925511
54935512 const cf = switch (self.control_flow) {
54945513 .structured => |*cf| cf,
......@@ -5618,13 +5637,13 @@ const DeclGen = struct {
56185637 }
56195638
56205639 fn airBr(self: *DeclGen, inst: Air.Inst.Index) !void {
5621 const mod = self.module;
5640 const pt = self.pt;
56225641 const br = self.air.instructions.items(.data)[@intFromEnum(inst)].br;
56235642 const operand_ty = self.typeOf(br.operand);
56245643
56255644 switch (self.control_flow) {
56265645 .structured => |*cf| {
5627 if (operand_ty.isFnOrHasRuntimeBitsIgnoreComptime(mod)) {
5646 if (operand_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt)) {
56285647 const operand_id = try self.resolve(br.operand);
56295648 const block_result_var_id = cf.block_results.get(br.block_inst).?;
56305649 try self.store(operand_ty, block_result_var_id, operand_id, .{});
......@@ -5635,7 +5654,7 @@ const DeclGen = struct {
56355654 },
56365655 .unstructured => |cf| {
56375656 const block = cf.blocks.get(br.block_inst).?;
5638 if (operand_ty.isFnOrHasRuntimeBitsIgnoreComptime(mod)) {
5657 if (operand_ty.isFnOrHasRuntimeBitsIgnoreComptime(pt)) {
56395658 const operand_id = try self.resolve(br.operand);
56405659 // current_block_label should not be undefined here, lest there
56415660 // is a br or br_void in the function's body.
......@@ -5762,7 +5781,7 @@ const DeclGen = struct {
57625781 }
57635782
57645783 fn airLoad(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
5765 const mod = self.module;
5784 const mod = self.pt.zcu;
57665785 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
57675786 const ptr_ty = self.typeOf(ty_op.operand);
57685787 const elem_ty = self.typeOfIndex(inst);
......@@ -5773,20 +5792,22 @@ const DeclGen = struct {
57735792 }
57745793
57755794 fn airStore(self: *DeclGen, inst: Air.Inst.Index) !void {
5795 const mod = self.pt.zcu;
57765796 const bin_op = self.air.instructions.items(.data)[@intFromEnum(inst)].bin_op;
57775797 const ptr_ty = self.typeOf(bin_op.lhs);
5778 const elem_ty = ptr_ty.childType(self.module);
5798 const elem_ty = ptr_ty.childType(mod);
57795799 const ptr = try self.resolve(bin_op.lhs);
57805800 const value = try self.resolve(bin_op.rhs);
57815801
5782 try self.store(elem_ty, ptr, value, .{ .is_volatile = ptr_ty.isVolatilePtr(self.module) });
5802 try self.store(elem_ty, ptr, value, .{ .is_volatile = ptr_ty.isVolatilePtr(mod) });
57835803 }
57845804
57855805 fn airRet(self: *DeclGen, inst: Air.Inst.Index) !void {
5806 const pt = self.pt;
5807 const mod = pt.zcu;
57865808 const operand = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
57875809 const ret_ty = self.typeOf(operand);
5788 const mod = self.module;
5789 if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
5810 if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
57905811 const decl = mod.declPtr(self.decl_index);
57915812 const fn_info = mod.typeToFunc(decl.typeOf(mod)).?;
57925813 if (Type.fromInterned(fn_info.return_type).isError(mod)) {
......@@ -5805,12 +5826,13 @@ const DeclGen = struct {
58055826 }
58065827
58075828 fn airRetLoad(self: *DeclGen, inst: Air.Inst.Index) !void {
5808 const mod = self.module;
5829 const pt = self.pt;
5830 const mod = pt.zcu;
58095831 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
58105832 const ptr_ty = self.typeOf(un_op);
58115833 const ret_ty = ptr_ty.childType(mod);
58125834
5813 if (!ret_ty.hasRuntimeBitsIgnoreComptime(mod)) {
5835 if (!ret_ty.hasRuntimeBitsIgnoreComptime(pt)) {
58145836 const decl = mod.declPtr(self.decl_index);
58155837 const fn_info = mod.typeToFunc(decl.typeOf(mod)).?;
58165838 if (Type.fromInterned(fn_info.return_type).isError(mod)) {
......@@ -5832,7 +5854,7 @@ const DeclGen = struct {
58325854 }
58335855
58345856 fn airTry(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
5835 const mod = self.module;
5857 const mod = self.pt.zcu;
58365858 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
58375859 const err_union_id = try self.resolve(pl_op.operand);
58385860 const extra = self.air.extraData(Air.Try, pl_op.payload);
......@@ -5902,7 +5924,7 @@ const DeclGen = struct {
59025924 }
59035925
59045926 fn airErrUnionErr(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
5905 const mod = self.module;
5927 const mod = self.pt.zcu;
59065928 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59075929 const operand_id = try self.resolve(ty_op.operand);
59085930 const err_union_ty = self.typeOf(ty_op.operand);
......@@ -5938,7 +5960,7 @@ const DeclGen = struct {
59385960 }
59395961
59405962 fn airWrapErrUnionErr(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
5941 const mod = self.module;
5963 const mod = self.pt.zcu;
59425964 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
59435965 const err_union_ty = self.typeOfIndex(inst);
59445966 const payload_ty = err_union_ty.errorUnionPayload(mod);
......@@ -5985,7 +6007,8 @@ const DeclGen = struct {
59856007 }
59866008
59876009 fn airIsNull(self: *DeclGen, inst: Air.Inst.Index, is_pointer: bool, pred: enum { is_null, is_non_null }) !?IdRef {
5988 const mod = self.module;
6010 const pt = self.pt;
6011 const mod = pt.zcu;
59896012 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
59906013 const operand_id = try self.resolve(un_op);
59916014 const operand_ty = self.typeOf(un_op);
......@@ -6026,7 +6049,7 @@ const DeclGen = struct {
60266049
60276050 const is_non_null_id = blk: {
60286051 if (is_pointer) {
6029 if (payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
6052 if (payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
60306053 const storage_class = self.spvStorageClass(operand_ty.ptrAddressSpace(mod));
60316054 const bool_ptr_ty_id = try self.ptrType(Type.bool, storage_class);
60326055 const tag_ptr_id = try self.accessChain(bool_ptr_ty_id, operand_id, &.{1});
......@@ -6036,7 +6059,7 @@ const DeclGen = struct {
60366059 break :blk try self.load(Type.bool, operand_id, .{});
60376060 }
60386061
6039 break :blk if (payload_ty.hasRuntimeBitsIgnoreComptime(mod))
6062 break :blk if (payload_ty.hasRuntimeBitsIgnoreComptime(pt))
60406063 try self.extractField(Type.bool, operand_id, 1)
60416064 else
60426065 // Optional representation is bool indicating whether the optional is set
......@@ -6061,7 +6084,7 @@ const DeclGen = struct {
60616084 }
60626085
60636086 fn airIsErr(self: *DeclGen, inst: Air.Inst.Index, pred: enum { is_err, is_non_err }) !?IdRef {
6064 const mod = self.module;
6087 const mod = self.pt.zcu;
60656088 const un_op = self.air.instructions.items(.data)[@intFromEnum(inst)].un_op;
60666089 const operand_id = try self.resolve(un_op);
60676090 const err_union_ty = self.typeOf(un_op);
......@@ -6094,13 +6117,14 @@ const DeclGen = struct {
60946117 }
60956118
60966119 fn airUnwrapOptional(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
6097 const mod = self.module;
6120 const pt = self.pt;
6121 const mod = pt.zcu;
60986122 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
60996123 const operand_id = try self.resolve(ty_op.operand);
61006124 const optional_ty = self.typeOf(ty_op.operand);
61016125 const payload_ty = self.typeOfIndex(inst);
61026126
6103 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) return null;
6127 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) return null;
61046128
61056129 if (optional_ty.optionalReprIsPayload(mod)) {
61066130 return operand_id;
......@@ -6110,7 +6134,8 @@ const DeclGen = struct {
61106134 }
61116135
61126136 fn airUnwrapOptionalPtr(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
6113 const mod = self.module;
6137 const pt = self.pt;
6138 const mod = pt.zcu;
61146139 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
61156140 const operand_id = try self.resolve(ty_op.operand);
61166141 const operand_ty = self.typeOf(ty_op.operand);
......@@ -6119,7 +6144,7 @@ const DeclGen = struct {
61196144 const result_ty = self.typeOfIndex(inst);
61206145 const result_ty_id = try self.resolveType(result_ty, .direct);
61216146
6122 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
6147 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
61236148 // There is no payload, but we still need to return a valid pointer.
61246149 // We can just return anything here, so just return a pointer to the operand.
61256150 return try self.bitCast(result_ty, operand_ty, operand_id);
......@@ -6134,11 +6159,12 @@ const DeclGen = struct {
61346159 }
61356160
61366161 fn airWrapOptional(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
6137 const mod = self.module;
6162 const pt = self.pt;
6163 const mod = pt.zcu;
61386164 const ty_op = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_op;
61396165 const payload_ty = self.typeOf(ty_op.operand);
61406166
6141 if (!payload_ty.hasRuntimeBitsIgnoreComptime(mod)) {
6167 if (!payload_ty.hasRuntimeBitsIgnoreComptime(pt)) {
61426168 return try self.constBool(true, .indirect);
61436169 }
61446170
......@@ -6156,7 +6182,8 @@ const DeclGen = struct {
61566182 }
61576183
61586184 fn airSwitchBr(self: *DeclGen, inst: Air.Inst.Index) !void {
6159 const mod = self.module;
6185 const pt = self.pt;
6186 const mod = pt.zcu;
61606187 const target = self.getTarget();
61616188 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
61626189 const cond_ty = self.typeOf(pl_op.operand);
......@@ -6240,15 +6267,15 @@ const DeclGen = struct {
62406267 const label = case_labels.at(case_i);
62416268
62426269 for (items) |item| {
6243 const value = (try self.air.value(item, mod)) orelse unreachable;
6270 const value = (try self.air.value(item, pt)) orelse unreachable;
62446271 const int_val: u64 = switch (cond_ty.zigTypeTag(mod)) {
6245 .Bool, .Int => if (cond_ty.isSignedInt(mod)) @bitCast(value.toSignedInt(mod)) else value.toUnsignedInt(mod),
6272 .Bool, .Int => if (cond_ty.isSignedInt(mod)) @bitCast(value.toSignedInt(pt)) else value.toUnsignedInt(pt),
62466273 .Enum => blk: {
62476274 // TODO: figure out of cond_ty is correct (something with enum literals)
6248 break :blk (try value.intFromEnum(cond_ty, mod)).toUnsignedInt(mod); // TODO: composite integer constants
6275 break :blk (try value.intFromEnum(cond_ty, pt)).toUnsignedInt(pt); // TODO: composite integer constants
62496276 },
62506277 .ErrorSet => value.getErrorInt(mod),
6251 .Pointer => value.toUnsignedInt(mod),
6278 .Pointer => value.toUnsignedInt(pt),
62526279 else => unreachable,
62536280 };
62546281 const int_lit: spec.LiteralContextDependentNumber = switch (cond_words) {
......@@ -6328,8 +6355,9 @@ const DeclGen = struct {
63286355 }
63296356
63306357 fn airDbgStmt(self: *DeclGen, inst: Air.Inst.Index) !void {
6358 const pt = self.pt;
6359 const mod = pt.zcu;
63316360 const dbg_stmt = self.air.instructions.items(.data)[@intFromEnum(inst)].dbg_stmt;
6332 const mod = self.module;
63336361 const decl = mod.declPtr(self.decl_index);
63346362 const path = decl.getFileScope(mod).sub_file_path;
63356363 try self.func.body.emit(self.spv.gpa, .OpLine, .{
......@@ -6340,7 +6368,7 @@ const DeclGen = struct {
63406368 }
63416369
63426370 fn airDbgInlineBlock(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
6343 const mod = self.module;
6371 const mod = self.pt.zcu;
63446372 const inst_datas = self.air.instructions.items(.data);
63456373 const extra = self.air.extraData(Air.DbgInlineBlock, inst_datas[@intFromEnum(inst)].ty_pl.payload);
63466374 const decl = mod.funcOwnerDeclPtr(extra.data.func);
......@@ -6358,7 +6386,7 @@ const DeclGen = struct {
63586386 }
63596387
63606388 fn airAssembly(self: *DeclGen, inst: Air.Inst.Index) !?IdRef {
6361 const mod = self.module;
6389 const mod = self.pt.zcu;
63626390 const ty_pl = self.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
63636391 const extra = self.air.extraData(Air.Asm, ty_pl.payload);
63646392
......@@ -6440,20 +6468,20 @@ const DeclGen = struct {
64406468 // TODO: Translate proper error locations.
64416469 assert(as.errors.items.len != 0);
64426470 assert(self.error_msg == null);
6443 const src_loc = self.module.declPtr(self.decl_index).navSrcLoc(mod);
6444 self.error_msg = try Module.ErrorMsg.create(self.module.gpa, src_loc, "failed to assemble SPIR-V inline assembly", .{});
6445 const notes = try self.module.gpa.alloc(Module.ErrorMsg, as.errors.items.len);
6471 const src_loc = mod.declPtr(self.decl_index).navSrcLoc(mod);
6472 self.error_msg = try Zcu.ErrorMsg.create(mod.gpa, src_loc, "failed to assemble SPIR-V inline assembly", .{});
6473 const notes = try mod.gpa.alloc(Zcu.ErrorMsg, as.errors.items.len);
64466474
64476475 // Sub-scope to prevent `return error.CodegenFail` from running the errdefers.
64486476 {
6449 errdefer self.module.gpa.free(notes);
6477 errdefer mod.gpa.free(notes);
64506478 var i: usize = 0;
64516479 errdefer for (notes[0..i]) |*note| {
6452 note.deinit(self.module.gpa);
6480 note.deinit(mod.gpa);
64536481 };
64546482
64556483 while (i < as.errors.items.len) : (i += 1) {
6456 notes[i] = try Module.ErrorMsg.init(self.module.gpa, src_loc, "{s}", .{as.errors.items[i].msg});
6484 notes[i] = try Zcu.ErrorMsg.init(mod.gpa, src_loc, "{s}", .{as.errors.items[i].msg});
64576485 }
64586486 }
64596487 self.error_msg.?.notes = notes;
......@@ -6489,7 +6517,8 @@ const DeclGen = struct {
64896517 fn airCall(self: *DeclGen, inst: Air.Inst.Index, modifier: std.builtin.CallModifier) !?IdRef {
64906518 _ = modifier;
64916519
6492 const mod = self.module;
6520 const pt = self.pt;
6521 const mod = pt.zcu;
64936522 const pl_op = self.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
64946523 const extra = self.air.extraData(Air.Call, pl_op.payload);
64956524 const args: []const Air.Inst.Ref = @ptrCast(self.air.extra[extra.end..][0..extra.data.args_len]);
......@@ -6515,7 +6544,7 @@ const DeclGen = struct {
65156544 // before starting to emit OpFunctionCall instructions. Hence the
65166545 // temporary params buffer.
65176546 const arg_ty = self.typeOf(arg);
6518 if (!arg_ty.hasRuntimeBitsIgnoreComptime(mod)) continue;
6547 if (!arg_ty.hasRuntimeBitsIgnoreComptime(pt)) continue;
65196548 const arg_id = try self.resolve(arg);
65206549
65216550 params[n_params] = arg_id;
......@@ -6533,7 +6562,7 @@ const DeclGen = struct {
65336562 try self.func.body.emit(self.spv.gpa, .OpUnreachable, {});
65346563 }
65356564
6536 if (self.liveness.isUnused(inst) or !Type.fromInterned(return_type).hasRuntimeBitsIgnoreComptime(mod)) {
6565 if (self.liveness.isUnused(inst) or !Type.fromInterned(return_type).hasRuntimeBitsIgnoreComptime(pt)) {
65376566 return null;
65386567 }
65396568
......@@ -6541,11 +6570,10 @@ const DeclGen = struct {
65416570 }
65426571
65436572 fn builtin3D(self: *DeclGen, result_ty: Type, builtin: spec.BuiltIn, dimension: u32, out_of_range_value: anytype) !IdRef {
6544 const mod = self.module;
65456573 if (dimension >= 3) {
65466574 return try self.constInt(result_ty, out_of_range_value, .direct);
65476575 }
6548 const vec_ty = try mod.vectorType(.{
6576 const vec_ty = try self.pt.vectorType(.{
65496577 .len = 3,
65506578 .child = result_ty.toIntern(),
65516579 });
......@@ -6591,12 +6619,12 @@ const DeclGen = struct {
65916619 }
65926620
65936621 fn typeOf(self: *DeclGen, inst: Air.Inst.Ref) Type {
6594 const mod = self.module;
6622 const mod = self.pt.zcu;
65956623 return self.air.typeOf(inst, &mod.intern_pool);
65966624 }
65976625
65986626 fn typeOfIndex(self: *DeclGen, inst: Air.Inst.Index) Type {
6599 const mod = self.module;
6627 const mod = self.pt.zcu;
66006628 return self.air.typeOfIndex(inst, &mod.intern_pool);
66016629 }
66026630};
src/crash_report.zig+3-3
......@@ -76,9 +76,9 @@ fn dumpStatusReport() !void {
7676
7777 const stderr = io.getStdErr().writer();
7878 const block: *Sema.Block = anal.block;
79 const mod = anal.sema.mod;
79 const zcu = anal.sema.pt.zcu;
8080
81 const file, const src_base_node = Zcu.LazySrcLoc.resolveBaseNode(block.src_base_inst, mod);
81 const file, const src_base_node = Zcu.LazySrcLoc.resolveBaseNode(block.src_base_inst, zcu);
8282
8383 try stderr.writeAll("Analyzing ");
8484 try writeFilePath(file, stderr);
......@@ -104,7 +104,7 @@ fn dumpStatusReport() !void {
104104 while (parent) |curr| {
105105 fba.reset();
106106 try stderr.writeAll(" in ");
107 const cur_block_file, const cur_block_src_base_node = Zcu.LazySrcLoc.resolveBaseNode(curr.block.src_base_inst, mod);
107 const cur_block_file, const cur_block_src_base_node = Zcu.LazySrcLoc.resolveBaseNode(curr.block.src_base_inst, zcu);
108108 try writeFilePath(cur_block_file, stderr);
109109 try stderr.writeAll("\n > ");
110110 print_zir.renderSingleInstruction(
src/link.zig+29-30
......@@ -15,8 +15,6 @@ const Compilation = @import("Compilation.zig");
1515const LibCInstallation = std.zig.LibCInstallation;
1616const Liveness = @import("Liveness.zig");
1717const Zcu = @import("Zcu.zig");
18/// Deprecated.
19const Module = Zcu;
2018const InternPool = @import("InternPool.zig");
2119const Type = @import("Type.zig");
2220const Value = @import("Value.zig");
......@@ -367,14 +365,14 @@ pub const File = struct {
367365 /// Called from within the CodeGen to lower a local variable instantion as an unnamed
368366 /// constant. Returns the symbol index of the lowered constant in the read-only section
369367 /// of the final binary.
370 pub fn lowerUnnamedConst(base: *File, val: Value, decl_index: InternPool.DeclIndex) UpdateDeclError!u32 {
368 pub fn lowerUnnamedConst(base: *File, pt: Zcu.PerThread, val: Value, decl_index: InternPool.DeclIndex) UpdateDeclError!u32 {
371369 if (build_options.only_c) @compileError("unreachable");
372370 switch (base.tag) {
373371 .spirv => unreachable,
374372 .c => unreachable,
375373 .nvptx => unreachable,
376374 inline else => |t| {
377 return @as(*t.Type(), @fieldParentPtr("base", base)).lowerUnnamedConst(val, decl_index);
375 return @as(*t.Type(), @fieldParentPtr("base", base)).lowerUnnamedConst(pt, val, decl_index);
378376 },
379377 }
380378 }
......@@ -399,13 +397,13 @@ pub const File = struct {
399397 }
400398
401399 /// May be called before or after updateExports for any given Decl.
402 pub fn updateDecl(base: *File, module: *Module, decl_index: InternPool.DeclIndex) UpdateDeclError!void {
403 const decl = module.declPtr(decl_index);
400 pub fn updateDecl(base: *File, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) UpdateDeclError!void {
401 const decl = pt.zcu.declPtr(decl_index);
404402 assert(decl.has_tv);
405403 switch (base.tag) {
406404 inline else => |tag| {
407405 if (tag != .c and build_options.only_c) unreachable;
408 return @as(*tag.Type(), @fieldParentPtr("base", base)).updateDecl(module, decl_index);
406 return @as(*tag.Type(), @fieldParentPtr("base", base)).updateDecl(pt, decl_index);
409407 },
410408 }
411409 }
......@@ -413,7 +411,7 @@ pub const File = struct {
413411 /// May be called before or after updateExports for any given Decl.
414412 pub fn updateFunc(
415413 base: *File,
416 module: *Module,
414 pt: Zcu.PerThread,
417415 func_index: InternPool.Index,
418416 air: Air,
419417 liveness: Liveness,
......@@ -421,19 +419,19 @@ pub const File = struct {
421419 switch (base.tag) {
422420 inline else => |tag| {
423421 if (tag != .c and build_options.only_c) unreachable;
424 return @as(*tag.Type(), @fieldParentPtr("base", base)).updateFunc(module, func_index, air, liveness);
422 return @as(*tag.Type(), @fieldParentPtr("base", base)).updateFunc(pt, func_index, air, liveness);
425423 },
426424 }
427425 }
428426
429 pub fn updateDeclLineNumber(base: *File, module: *Module, decl_index: InternPool.DeclIndex) UpdateDeclError!void {
430 const decl = module.declPtr(decl_index);
427 pub fn updateDeclLineNumber(base: *File, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) UpdateDeclError!void {
428 const decl = pt.zcu.declPtr(decl_index);
431429 assert(decl.has_tv);
432430 switch (base.tag) {
433431 .spirv, .nvptx => {},
434432 inline else => |tag| {
435433 if (tag != .c and build_options.only_c) unreachable;
436 return @as(*tag.Type(), @fieldParentPtr("base", base)).updateDeclLineNumber(module, decl_index);
434 return @as(*tag.Type(), @fieldParentPtr("base", base)).updateDeclLineNumber(pt, decl_index);
437435 },
438436 }
439437 }
......@@ -537,10 +535,10 @@ pub const File = struct {
537535 /// Commit pending changes and write headers. Takes into account final output mode
538536 /// and `use_lld`, not only `effectiveOutputMode`.
539537 /// `arena` has the lifetime of the call to `Compilation.update`.
540 pub fn flush(base: *File, arena: Allocator, prog_node: std.Progress.Node) FlushError!void {
538 pub fn flush(base: *File, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) FlushError!void {
541539 if (build_options.only_c) {
542540 assert(base.tag == .c);
543 return @as(*C, @fieldParentPtr("base", base)).flush(arena, prog_node);
541 return @as(*C, @fieldParentPtr("base", base)).flush(arena, tid, prog_node);
544542 }
545543 const comp = base.comp;
546544 if (comp.clang_preprocessor_mode == .yes or comp.clang_preprocessor_mode == .pch) {
......@@ -563,27 +561,27 @@ pub const File = struct {
563561 const output_mode = comp.config.output_mode;
564562 const link_mode = comp.config.link_mode;
565563 if (use_lld and output_mode == .Lib and link_mode == .static) {
566 return base.linkAsArchive(arena, prog_node);
564 return base.linkAsArchive(arena, tid, prog_node);
567565 }
568566 switch (base.tag) {
569567 inline else => |tag| {
570 return @as(*tag.Type(), @fieldParentPtr("base", base)).flush(arena, prog_node);
568 return @as(*tag.Type(), @fieldParentPtr("base", base)).flush(arena, tid, prog_node);
571569 },
572570 }
573571 }
574572
575573 /// Commit pending changes and write headers. Works based on `effectiveOutputMode`
576574 /// rather than final output mode.
577 pub fn flushModule(base: *File, arena: Allocator, prog_node: std.Progress.Node) FlushError!void {
575 pub fn flushModule(base: *File, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) FlushError!void {
578576 switch (base.tag) {
579577 inline else => |tag| {
580578 if (tag != .c and build_options.only_c) unreachable;
581 return @as(*tag.Type(), @fieldParentPtr("base", base)).flushModule(arena, prog_node);
579 return @as(*tag.Type(), @fieldParentPtr("base", base)).flushModule(arena, tid, prog_node);
582580 },
583581 }
584582 }
585583
586 /// Called when a Decl is deleted from the Module.
584 /// Called when a Decl is deleted from the Zcu.
587585 pub fn freeDecl(base: *File, decl_index: InternPool.DeclIndex) void {
588586 switch (base.tag) {
589587 inline else => |tag| {
......@@ -604,14 +602,14 @@ pub const File = struct {
604602 /// May be called before or after updateDecl for any given Decl.
605603 pub fn updateExports(
606604 base: *File,
607 module: *Module,
608 exported: Module.Exported,
605 pt: Zcu.PerThread,
606 exported: Zcu.Exported,
609607 export_indices: []const u32,
610608 ) UpdateExportsError!void {
611609 switch (base.tag) {
612610 inline else => |tag| {
613611 if (tag != .c and build_options.only_c) unreachable;
614 return @as(*tag.Type(), @fieldParentPtr("base", base)).updateExports(module, exported, export_indices);
612 return @as(*tag.Type(), @fieldParentPtr("base", base)).updateExports(pt, exported, export_indices);
615613 },
616614 }
617615 }
......@@ -628,14 +626,14 @@ pub const File = struct {
628626 /// `Decl`'s address was not yet resolved, or the containing atom gets moved in virtual memory.
629627 /// May be called before or after updateFunc/updateDecl therefore it is up to the linker to allocate
630628 /// the block/atom.
631 pub fn getDeclVAddr(base: *File, decl_index: InternPool.DeclIndex, reloc_info: RelocInfo) !u64 {
629 pub fn getDeclVAddr(base: *File, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex, reloc_info: RelocInfo) !u64 {
632630 if (build_options.only_c) @compileError("unreachable");
633631 switch (base.tag) {
634632 .c => unreachable,
635633 .spirv => unreachable,
636634 .nvptx => unreachable,
637635 inline else => |tag| {
638 return @as(*tag.Type(), @fieldParentPtr("base", base)).getDeclVAddr(decl_index, reloc_info);
636 return @as(*tag.Type(), @fieldParentPtr("base", base)).getDeclVAddr(pt, decl_index, reloc_info);
639637 },
640638 }
641639 }
......@@ -644,9 +642,10 @@ pub const File = struct {
644642
645643 pub fn lowerAnonDecl(
646644 base: *File,
645 pt: Zcu.PerThread,
647646 decl_val: InternPool.Index,
648647 decl_align: InternPool.Alignment,
649 src_loc: Module.LazySrcLoc,
648 src_loc: Zcu.LazySrcLoc,
650649 ) !LowerResult {
651650 if (build_options.only_c) @compileError("unreachable");
652651 switch (base.tag) {
......@@ -654,7 +653,7 @@ pub const File = struct {
654653 .spirv => unreachable,
655654 .nvptx => unreachable,
656655 inline else => |tag| {
657 return @as(*tag.Type(), @fieldParentPtr("base", base)).lowerAnonDecl(decl_val, decl_align, src_loc);
656 return @as(*tag.Type(), @fieldParentPtr("base", base)).lowerAnonDecl(pt, decl_val, decl_align, src_loc);
658657 },
659658 }
660659 }
......@@ -689,7 +688,7 @@ pub const File = struct {
689688 }
690689 }
691690
692 pub fn linkAsArchive(base: *File, arena: Allocator, prog_node: std.Progress.Node) FlushError!void {
691 pub fn linkAsArchive(base: *File, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) FlushError!void {
693692 const tracy = trace(@src());
694693 defer tracy.end();
695694
......@@ -704,7 +703,7 @@ pub const File = struct {
704703 // If there is no Zig code to compile, then we should skip flushing the output file
705704 // because it will not be part of the linker line anyway.
706705 const zcu_obj_path: ?[]const u8 = if (opt_zcu != null) blk: {
707 try base.flushModule(arena, prog_node);
706 try base.flushModule(arena, tid, prog_node);
708707
709708 const dirname = fs.path.dirname(full_out_path_z) orelse ".";
710709 break :blk try fs.path.join(arena, &.{ dirname, base.zcu_object_sub_path.? });
......@@ -896,14 +895,14 @@ pub const File = struct {
896895 kind: Kind,
897896 ty: Type,
898897
899 pub fn initDecl(kind: Kind, decl: ?InternPool.DeclIndex, mod: *Module) LazySymbol {
898 pub fn initDecl(kind: Kind, decl: ?InternPool.DeclIndex, mod: *Zcu) LazySymbol {
900899 return .{ .kind = kind, .ty = if (decl) |decl_index|
901900 mod.declPtr(decl_index).val.toType()
902901 else
903902 Type.anyerror };
904903 }
905904
906 pub fn getDecl(self: LazySymbol, mod: *Module) InternPool.OptionalDeclIndex {
905 pub fn getDecl(self: LazySymbol, mod: *Zcu) InternPool.OptionalDeclIndex {
907906 return InternPool.OptionalDeclIndex.init(self.ty.getOwnerDeclOrNull(mod));
908907 }
909908 };
src/link/C.zig+33-30
......@@ -186,13 +186,13 @@ pub fn freeDecl(self: *C, decl_index: InternPool.DeclIndex) void {
186186
187187pub fn updateFunc(
188188 self: *C,
189 zcu: *Zcu,
189 pt: Zcu.PerThread,
190190 func_index: InternPool.Index,
191191 air: Air,
192192 liveness: Liveness,
193193) !void {
194 const gpa = self.base.comp.gpa;
195
194 const zcu = pt.zcu;
195 const gpa = zcu.gpa;
196196 const func = zcu.funcInfo(func_index);
197197 const decl_index = func.owner_decl;
198198 const decl = zcu.declPtr(decl_index);
......@@ -218,7 +218,7 @@ pub fn updateFunc(
218218 .object = .{
219219 .dg = .{
220220 .gpa = gpa,
221 .zcu = zcu,
221 .pt = pt,
222222 .mod = file_scope.mod,
223223 .error_msg = null,
224224 .pass = .{ .decl = decl_index },
......@@ -263,7 +263,7 @@ pub fn updateFunc(
263263 gop.value_ptr.code = try self.addString(function.object.code.items);
264264}
265265
266fn updateAnonDecl(self: *C, zcu: *Zcu, i: usize) !void {
266fn updateAnonDecl(self: *C, pt: Zcu.PerThread, i: usize) !void {
267267 const gpa = self.base.comp.gpa;
268268 const anon_decl = self.anon_decls.keys()[i];
269269
......@@ -275,8 +275,8 @@ fn updateAnonDecl(self: *C, zcu: *Zcu, i: usize) !void {
275275 var object: codegen.Object = .{
276276 .dg = .{
277277 .gpa = gpa,
278 .zcu = zcu,
279 .mod = zcu.root_mod,
278 .pt = pt,
279 .mod = pt.zcu.root_mod,
280280 .error_msg = null,
281281 .pass = .{ .anon = anon_decl },
282282 .is_naked_fn = false,
......@@ -319,12 +319,13 @@ fn updateAnonDecl(self: *C, zcu: *Zcu, i: usize) !void {
319319 };
320320}
321321
322pub fn updateDecl(self: *C, zcu: *Zcu, decl_index: InternPool.DeclIndex) !void {
322pub fn updateDecl(self: *C, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !void {
323323 const tracy = trace(@src());
324324 defer tracy.end();
325325
326326 const gpa = self.base.comp.gpa;
327327
328 const zcu = pt.zcu;
328329 const decl = zcu.declPtr(decl_index);
329330 const gop = try self.decl_table.getOrPut(gpa, decl_index);
330331 errdefer _ = self.decl_table.pop();
......@@ -342,7 +343,7 @@ pub fn updateDecl(self: *C, zcu: *Zcu, decl_index: InternPool.DeclIndex) !void {
342343 var object: codegen.Object = .{
343344 .dg = .{
344345 .gpa = gpa,
345 .zcu = zcu,
346 .pt = pt,
346347 .mod = file_scope.mod,
347348 .error_msg = null,
348349 .pass = .{ .decl = decl_index },
......@@ -382,16 +383,16 @@ pub fn updateDecl(self: *C, zcu: *Zcu, decl_index: InternPool.DeclIndex) !void {
382383 gop.value_ptr.fwd_decl = try self.addString(object.dg.fwd_decl.items);
383384}
384385
385pub fn updateDeclLineNumber(self: *C, zcu: *Zcu, decl_index: InternPool.DeclIndex) !void {
386pub fn updateDeclLineNumber(self: *C, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !void {
386387 // The C backend does not have the ability to fix line numbers without re-generating
387388 // the entire Decl.
388389 _ = self;
389 _ = zcu;
390 _ = pt;
390391 _ = decl_index;
391392}
392393
393pub fn flush(self: *C, arena: Allocator, prog_node: std.Progress.Node) !void {
394 return self.flushModule(arena, prog_node);
394pub fn flush(self: *C, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) !void {
395 return self.flushModule(arena, tid, prog_node);
395396}
396397
397398fn abiDefines(self: *C, target: std.Target) !std.ArrayList(u8) {
......@@ -409,7 +410,7 @@ fn abiDefines(self: *C, target: std.Target) !std.ArrayList(u8) {
409410 return defines;
410411}
411412
412pub fn flushModule(self: *C, arena: Allocator, prog_node: std.Progress.Node) !void {
413pub fn flushModule(self: *C, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) !void {
413414 _ = arena; // Has the same lifetime as the call to Compilation.update.
414415
415416 const tracy = trace(@src());
......@@ -421,11 +422,12 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: std.Progress.Node) !vo
421422 const comp = self.base.comp;
422423 const gpa = comp.gpa;
423424 const zcu = self.base.comp.module.?;
425 const pt: Zcu.PerThread = .{ .zcu = zcu, .tid = tid };
424426
425427 {
426428 var i: usize = 0;
427429 while (i < self.anon_decls.count()) : (i += 1) {
428 try updateAnonDecl(self, zcu, i);
430 try updateAnonDecl(self, pt, i);
429431 }
430432 }
431433
......@@ -463,7 +465,7 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: std.Progress.Node) !vo
463465 self.lazy_fwd_decl_buf.clearRetainingCapacity();
464466 self.lazy_code_buf.clearRetainingCapacity();
465467 try f.lazy_ctype_pool.init(gpa);
466 try self.flushErrDecls(zcu, &f.lazy_ctype_pool);
468 try self.flushErrDecls(pt, &f.lazy_ctype_pool);
467469
468470 // Unlike other backends, the .c code we are emitting has order-dependent decls.
469471 // `CType`s, forward decls, and non-functions first.
......@@ -483,7 +485,7 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: std.Progress.Node) !vo
483485 }
484486
485487 for (self.anon_decls.keys(), self.anon_decls.values()) |value, *decl_block| try self.flushDeclBlock(
486 zcu,
488 pt,
487489 zcu.root_mod,
488490 &f,
489491 decl_block,
......@@ -497,7 +499,7 @@ pub fn flushModule(self: *C, arena: Allocator, prog_node: std.Progress.Node) !vo
497499 const extern_name = if (decl.isExtern(zcu)) decl.name.toOptional() else .none;
498500 const mod = zcu.namespacePtr(decl.src_namespace).fileScope(zcu).mod;
499501 try self.flushDeclBlock(
500 zcu,
502 pt,
501503 mod,
502504 &f,
503505 decl_block,
......@@ -670,7 +672,7 @@ fn flushCTypes(
670672 }
671673}
672674
673fn flushErrDecls(self: *C, zcu: *Zcu, ctype_pool: *codegen.CType.Pool) FlushDeclError!void {
675fn flushErrDecls(self: *C, pt: Zcu.PerThread, ctype_pool: *codegen.CType.Pool) FlushDeclError!void {
674676 const gpa = self.base.comp.gpa;
675677
676678 const fwd_decl = &self.lazy_fwd_decl_buf;
......@@ -679,8 +681,8 @@ fn flushErrDecls(self: *C, zcu: *Zcu, ctype_pool: *codegen.CType.Pool) FlushDecl
679681 var object = codegen.Object{
680682 .dg = .{
681683 .gpa = gpa,
682 .zcu = zcu,
683 .mod = zcu.root_mod,
684 .pt = pt,
685 .mod = pt.zcu.root_mod,
684686 .error_msg = null,
685687 .pass = .flush,
686688 .is_naked_fn = false,
......@@ -712,7 +714,7 @@ fn flushErrDecls(self: *C, zcu: *Zcu, ctype_pool: *codegen.CType.Pool) FlushDecl
712714
713715fn flushLazyFn(
714716 self: *C,
715 zcu: *Zcu,
717 pt: Zcu.PerThread,
716718 mod: *Module,
717719 ctype_pool: *codegen.CType.Pool,
718720 lazy_ctype_pool: *const codegen.CType.Pool,
......@@ -726,7 +728,7 @@ fn flushLazyFn(
726728 var object = codegen.Object{
727729 .dg = .{
728730 .gpa = gpa,
729 .zcu = zcu,
731 .pt = pt,
730732 .mod = mod,
731733 .error_msg = null,
732734 .pass = .flush,
......@@ -761,7 +763,7 @@ fn flushLazyFn(
761763
762764fn flushLazyFns(
763765 self: *C,
764 zcu: *Zcu,
766 pt: Zcu.PerThread,
765767 mod: *Module,
766768 f: *Flush,
767769 lazy_ctype_pool: *const codegen.CType.Pool,
......@@ -775,13 +777,13 @@ fn flushLazyFns(
775777 const gop = f.lazy_fns.getOrPutAssumeCapacity(entry.key_ptr.*);
776778 if (gop.found_existing) continue;
777779 gop.value_ptr.* = {};
778 try self.flushLazyFn(zcu, mod, &f.lazy_ctype_pool, lazy_ctype_pool, entry);
780 try self.flushLazyFn(pt, mod, &f.lazy_ctype_pool, lazy_ctype_pool, entry);
779781 }
780782}
781783
782784fn flushDeclBlock(
783785 self: *C,
784 zcu: *Zcu,
786 pt: Zcu.PerThread,
785787 mod: *Module,
786788 f: *Flush,
787789 decl_block: *const DeclBlock,
......@@ -790,7 +792,7 @@ fn flushDeclBlock(
790792 extern_name: InternPool.OptionalNullTerminatedString,
791793) FlushDeclError!void {
792794 const gpa = self.base.comp.gpa;
793 try self.flushLazyFns(zcu, mod, f, &decl_block.ctype_pool, decl_block.lazy_fns);
795 try self.flushLazyFns(pt, mod, f, &decl_block.ctype_pool, decl_block.lazy_fns);
794796 try f.all_buffers.ensureUnusedCapacity(gpa, 1);
795797 // avoid emitting extern decls that are already exported
796798 if (extern_name.unwrap()) |name| if (export_names.contains(name)) return;
......@@ -845,11 +847,12 @@ pub fn flushEmitH(zcu: *Zcu) !void {
845847
846848pub fn updateExports(
847849 self: *C,
848 zcu: *Zcu,
850 pt: Zcu.PerThread,
849851 exported: Zcu.Exported,
850852 export_indices: []const u32,
851853) !void {
852 const gpa = self.base.comp.gpa;
854 const zcu = pt.zcu;
855 const gpa = zcu.gpa;
853856 const mod, const pass: codegen.DeclGen.Pass, const decl_block, const exported_block = switch (exported) {
854857 .decl_index => |decl_index| .{
855858 zcu.namespacePtr(zcu.declPtr(decl_index).src_namespace).fileScope(zcu).mod,
......@@ -869,7 +872,7 @@ pub fn updateExports(
869872 fwd_decl.clearRetainingCapacity();
870873 var dg: codegen.DeclGen = .{
871874 .gpa = gpa,
872 .zcu = zcu,
875 .pt = pt,
873876 .mod = mod,
874877 .error_msg = null,
875878 .pass = pass,
src/link/Coff.zig+58-37
......@@ -1120,16 +1120,17 @@ fn freeAtom(self: *Coff, atom_index: Atom.Index) void {
11201120 self.getAtomPtr(atom_index).sym_index = 0;
11211121}
11221122
1123pub fn updateFunc(self: *Coff, mod: *Module, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
1123pub fn updateFunc(self: *Coff, pt: Zcu.PerThread, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
11241124 if (build_options.skip_non_native and builtin.object_format != .coff) {
11251125 @panic("Attempted to compile for object format that was disabled by build configuration");
11261126 }
11271127 if (self.llvm_object) |llvm_object| {
1128 return llvm_object.updateFunc(mod, func_index, air, liveness);
1128 return llvm_object.updateFunc(pt, func_index, air, liveness);
11291129 }
11301130 const tracy = trace(@src());
11311131 defer tracy.end();
11321132
1133 const mod = pt.zcu;
11331134 const func = mod.funcInfo(func_index);
11341135 const decl_index = func.owner_decl;
11351136 const decl = mod.declPtr(decl_index);
......@@ -1144,6 +1145,7 @@ pub fn updateFunc(self: *Coff, mod: *Module, func_index: InternPool.Index, air:
11441145
11451146 const res = try codegen.generateFunction(
11461147 &self.base,
1148 pt,
11471149 decl.navSrcLoc(mod),
11481150 func_index,
11491151 air,
......@@ -1160,26 +1162,26 @@ pub fn updateFunc(self: *Coff, mod: *Module, func_index: InternPool.Index, air:
11601162 },
11611163 };
11621164
1163 try self.updateDeclCode(decl_index, code, .FUNCTION);
1165 try self.updateDeclCode(pt, decl_index, code, .FUNCTION);
11641166
11651167 // Exports will be updated by `Zcu.processExports` after the update.
11661168}
11671169
1168pub fn lowerUnnamedConst(self: *Coff, val: Value, decl_index: InternPool.DeclIndex) !u32 {
1169 const gpa = self.base.comp.gpa;
1170 const mod = self.base.comp.module.?;
1170pub fn lowerUnnamedConst(self: *Coff, pt: Zcu.PerThread, val: Value, decl_index: InternPool.DeclIndex) !u32 {
1171 const mod = pt.zcu;
1172 const gpa = mod.gpa;
11711173 const decl = mod.declPtr(decl_index);
11721174 const gop = try self.unnamed_const_atoms.getOrPut(gpa, decl_index);
11731175 if (!gop.found_existing) {
11741176 gop.value_ptr.* = .{};
11751177 }
11761178 const unnamed_consts = gop.value_ptr;
1177 const decl_name = try decl.fullyQualifiedName(mod);
1179 const decl_name = try decl.fullyQualifiedName(pt);
11781180 const index = unnamed_consts.items.len;
11791181 const sym_name = try std.fmt.allocPrint(gpa, "__unnamed_{}_{d}", .{ decl_name.fmt(&mod.intern_pool), index });
11801182 defer gpa.free(sym_name);
11811183 const ty = val.typeOf(mod);
1182 const atom_index = switch (try self.lowerConst(sym_name, val, ty.abiAlignment(mod), self.rdata_section_index.?, decl.navSrcLoc(mod))) {
1184 const atom_index = switch (try self.lowerConst(pt, sym_name, val, ty.abiAlignment(pt), self.rdata_section_index.?, decl.navSrcLoc(mod))) {
11831185 .ok => |atom_index| atom_index,
11841186 .fail => |em| {
11851187 decl.analysis = .codegen_failure;
......@@ -1197,7 +1199,15 @@ const LowerConstResult = union(enum) {
11971199 fail: *Module.ErrorMsg,
11981200};
11991201
1200fn lowerConst(self: *Coff, name: []const u8, val: Value, required_alignment: InternPool.Alignment, sect_id: u16, src_loc: Module.LazySrcLoc) !LowerConstResult {
1202fn lowerConst(
1203 self: *Coff,
1204 pt: Zcu.PerThread,
1205 name: []const u8,
1206 val: Value,
1207 required_alignment: InternPool.Alignment,
1208 sect_id: u16,
1209 src_loc: Module.LazySrcLoc,
1210) !LowerConstResult {
12011211 const gpa = self.base.comp.gpa;
12021212
12031213 var code_buffer = std.ArrayList(u8).init(gpa);
......@@ -1208,7 +1218,7 @@ fn lowerConst(self: *Coff, name: []const u8, val: Value, required_alignment: Int
12081218 try self.setSymbolName(sym, name);
12091219 sym.section_number = @as(coff.SectionNumber, @enumFromInt(sect_id + 1));
12101220
1211 const res = try codegen.generateSymbol(&self.base, src_loc, val, &code_buffer, .none, .{
1221 const res = try codegen.generateSymbol(&self.base, pt, src_loc, val, &code_buffer, .none, .{
12121222 .parent_atom_index = self.getAtom(atom_index).getSymbolIndex().?,
12131223 });
12141224 const code = switch (res) {
......@@ -1235,13 +1245,14 @@ fn lowerConst(self: *Coff, name: []const u8, val: Value, required_alignment: Int
12351245
12361246pub fn updateDecl(
12371247 self: *Coff,
1238 mod: *Module,
1248 pt: Zcu.PerThread,
12391249 decl_index: InternPool.DeclIndex,
12401250) link.File.UpdateDeclError!void {
1251 const mod = pt.zcu;
12411252 if (build_options.skip_non_native and builtin.object_format != .coff) {
12421253 @panic("Attempted to compile for object format that was disabled by build configuration");
12431254 }
1244 if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(mod, decl_index);
1255 if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(pt, decl_index);
12451256 const tracy = trace(@src());
12461257 defer tracy.end();
12471258
......@@ -1270,7 +1281,7 @@ pub fn updateDecl(
12701281 defer code_buffer.deinit();
12711282
12721283 const decl_val = if (decl.val.getVariable(mod)) |variable| Value.fromInterned(variable.init) else decl.val;
1273 const res = try codegen.generateSymbol(&self.base, decl.navSrcLoc(mod), decl_val, &code_buffer, .none, .{
1284 const res = try codegen.generateSymbol(&self.base, pt, decl.navSrcLoc(mod), decl_val, &code_buffer, .none, .{
12741285 .parent_atom_index = atom.getSymbolIndex().?,
12751286 });
12761287 const code = switch (res) {
......@@ -1282,19 +1293,20 @@ pub fn updateDecl(
12821293 },
12831294 };
12841295
1285 try self.updateDeclCode(decl_index, code, .NULL);
1296 try self.updateDeclCode(pt, decl_index, code, .NULL);
12861297
12871298 // Exports will be updated by `Zcu.processExports` after the update.
12881299}
12891300
12901301fn updateLazySymbolAtom(
12911302 self: *Coff,
1303 pt: Zcu.PerThread,
12921304 sym: link.File.LazySymbol,
12931305 atom_index: Atom.Index,
12941306 section_index: u16,
12951307) !void {
1296 const gpa = self.base.comp.gpa;
1297 const mod = self.base.comp.module.?;
1308 const mod = pt.zcu;
1309 const gpa = mod.gpa;
12981310
12991311 var required_alignment: InternPool.Alignment = .none;
13001312 var code_buffer = std.ArrayList(u8).init(gpa);
......@@ -1302,7 +1314,7 @@ fn updateLazySymbolAtom(
13021314
13031315 const name = try std.fmt.allocPrint(gpa, "__lazy_{s}_{}", .{
13041316 @tagName(sym.kind),
1305 sym.ty.fmt(mod),
1317 sym.ty.fmt(pt),
13061318 });
13071319 defer gpa.free(name);
13081320
......@@ -1312,6 +1324,7 @@ fn updateLazySymbolAtom(
13121324 const src = sym.ty.srcLocOrNull(mod) orelse Module.LazySrcLoc.unneeded;
13131325 const res = try codegen.generateLazySymbol(
13141326 &self.base,
1327 pt,
13151328 src,
13161329 sym,
13171330 &required_alignment,
......@@ -1346,7 +1359,7 @@ fn updateLazySymbolAtom(
13461359 try self.writeAtom(atom_index, code);
13471360}
13481361
1349pub fn getOrCreateAtomForLazySymbol(self: *Coff, sym: link.File.LazySymbol) !Atom.Index {
1362pub fn getOrCreateAtomForLazySymbol(self: *Coff, pt: Zcu.PerThread, sym: link.File.LazySymbol) !Atom.Index {
13501363 const gpa = self.base.comp.gpa;
13511364 const mod = self.base.comp.module.?;
13521365 const gop = try self.lazy_syms.getOrPut(gpa, sym.getDecl(mod));
......@@ -1364,7 +1377,7 @@ pub fn getOrCreateAtomForLazySymbol(self: *Coff, sym: link.File.LazySymbol) !Ato
13641377 metadata.state.* = .pending_flush;
13651378 const atom = metadata.atom.*;
13661379 // anyerror needs to be deferred until flushModule
1367 if (sym.getDecl(mod) != .none) try self.updateLazySymbolAtom(sym, atom, switch (sym.kind) {
1380 if (sym.getDecl(mod) != .none) try self.updateLazySymbolAtom(pt, sym, atom, switch (sym.kind) {
13681381 .code => self.text_section_index.?,
13691382 .const_data => self.rdata_section_index.?,
13701383 });
......@@ -1410,14 +1423,14 @@ fn getDeclOutputSection(self: *Coff, decl_index: InternPool.DeclIndex) u16 {
14101423 return index;
14111424}
14121425
1413fn updateDeclCode(self: *Coff, decl_index: InternPool.DeclIndex, code: []u8, complex_type: coff.ComplexType) !void {
1414 const mod = self.base.comp.module.?;
1426fn updateDeclCode(self: *Coff, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex, code: []u8, complex_type: coff.ComplexType) !void {
1427 const mod = pt.zcu;
14151428 const decl = mod.declPtr(decl_index);
14161429
1417 const decl_name = try decl.fullyQualifiedName(mod);
1430 const decl_name = try decl.fullyQualifiedName(pt);
14181431
14191432 log.debug("updateDeclCode {}{*}", .{ decl_name.fmt(&mod.intern_pool), decl });
1420 const required_alignment: u32 = @intCast(decl.getAlignment(mod).toByteUnits() orelse 0);
1433 const required_alignment: u32 = @intCast(decl.getAlignment(pt).toByteUnits() orelse 0);
14211434
14221435 const decl_metadata = self.decls.get(decl_index).?;
14231436 const atom_index = decl_metadata.atom;
......@@ -1496,7 +1509,7 @@ pub fn freeDecl(self: *Coff, decl_index: InternPool.DeclIndex) void {
14961509
14971510pub fn updateExports(
14981511 self: *Coff,
1499 mod: *Module,
1512 pt: Zcu.PerThread,
15001513 exported: Module.Exported,
15011514 export_indices: []const u32,
15021515) link.File.UpdateExportsError!void {
......@@ -1504,6 +1517,7 @@ pub fn updateExports(
15041517 @panic("Attempted to compile for object format that was disabled by build configuration");
15051518 }
15061519
1520 const mod = pt.zcu;
15071521 const ip = &mod.intern_pool;
15081522 const comp = self.base.comp;
15091523 const target = comp.root_mod.resolved_target.result;
......@@ -1542,7 +1556,7 @@ pub fn updateExports(
15421556 }
15431557 }
15441558
1545 if (self.llvm_object) |llvm_object| return llvm_object.updateExports(mod, exported, export_indices);
1559 if (self.llvm_object) |llvm_object| return llvm_object.updateExports(pt, exported, export_indices);
15461560
15471561 const gpa = comp.gpa;
15481562
......@@ -1553,7 +1567,7 @@ pub fn updateExports(
15531567 },
15541568 .value => |value| self.anon_decls.getPtr(value) orelse blk: {
15551569 const first_exp = mod.all_exports.items[export_indices[0]];
1556 const res = try self.lowerAnonDecl(value, .none, first_exp.src);
1570 const res = try self.lowerAnonDecl(pt, value, .none, first_exp.src);
15571571 switch (res) {
15581572 .ok => {},
15591573 .fail => |em| {
......@@ -1696,19 +1710,19 @@ fn resolveGlobalSymbol(self: *Coff, current: SymbolWithLoc) !void {
16961710 gop.value_ptr.* = current;
16971711}
16981712
1699pub fn flush(self: *Coff, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
1713pub fn flush(self: *Coff, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
17001714 const comp = self.base.comp;
17011715 const use_lld = build_options.have_llvm and comp.config.use_lld;
17021716 if (use_lld) {
1703 return lld.linkWithLLD(self, arena, prog_node);
1717 return lld.linkWithLLD(self, arena, tid, prog_node);
17041718 }
17051719 switch (comp.config.output_mode) {
1706 .Exe, .Obj => return self.flushModule(arena, prog_node),
1720 .Exe, .Obj => return self.flushModule(arena, tid, prog_node),
17071721 .Lib => return error.TODOImplementWritingLibFiles,
17081722 }
17091723}
17101724
1711pub fn flushModule(self: *Coff, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
1725pub fn flushModule(self: *Coff, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
17121726 const tracy = trace(@src());
17131727 defer tracy.end();
17141728
......@@ -1723,13 +1737,17 @@ pub fn flushModule(self: *Coff, arena: Allocator, prog_node: std.Progress.Node)
17231737 const sub_prog_node = prog_node.start("COFF Flush", 0);
17241738 defer sub_prog_node.end();
17251739
1726 const module = comp.module orelse return error.LinkingWithoutZigSourceUnimplemented;
1740 const pt: Zcu.PerThread = .{
1741 .zcu = comp.module orelse return error.LinkingWithoutZigSourceUnimplemented,
1742 .tid = tid,
1743 };
17271744
17281745 if (self.lazy_syms.getPtr(.none)) |metadata| {
17291746 // Most lazy symbols can be updated on first use, but
17301747 // anyerror needs to wait for everything to be flushed.
17311748 if (metadata.text_state != .unused) self.updateLazySymbolAtom(
1732 link.File.LazySymbol.initDecl(.code, null, module),
1749 pt,
1750 link.File.LazySymbol.initDecl(.code, null, pt.zcu),
17331751 metadata.text_atom,
17341752 self.text_section_index.?,
17351753 ) catch |err| return switch (err) {
......@@ -1737,7 +1755,8 @@ pub fn flushModule(self: *Coff, arena: Allocator, prog_node: std.Progress.Node)
17371755 else => |e| e,
17381756 };
17391757 if (metadata.rdata_state != .unused) self.updateLazySymbolAtom(
1740 link.File.LazySymbol.initDecl(.const_data, null, module),
1758 pt,
1759 link.File.LazySymbol.initDecl(.const_data, null, pt.zcu),
17411760 metadata.rdata_atom,
17421761 self.rdata_section_index.?,
17431762 ) catch |err| return switch (err) {
......@@ -1836,7 +1855,7 @@ pub fn flushModule(self: *Coff, arena: Allocator, prog_node: std.Progress.Node)
18361855 assert(!self.imports_count_dirty);
18371856}
18381857
1839pub fn getDeclVAddr(self: *Coff, decl_index: InternPool.DeclIndex, reloc_info: link.File.RelocInfo) !u64 {
1858pub fn getDeclVAddr(self: *Coff, _: Zcu.PerThread, decl_index: InternPool.DeclIndex, reloc_info: link.File.RelocInfo) !u64 {
18401859 assert(self.llvm_object == null);
18411860
18421861 const this_atom_index = try self.getOrCreateAtomForDecl(decl_index);
......@@ -1858,6 +1877,7 @@ pub fn getDeclVAddr(self: *Coff, decl_index: InternPool.DeclIndex, reloc_info: l
18581877
18591878pub fn lowerAnonDecl(
18601879 self: *Coff,
1880 pt: Zcu.PerThread,
18611881 decl_val: InternPool.Index,
18621882 explicit_alignment: InternPool.Alignment,
18631883 src_loc: Module.LazySrcLoc,
......@@ -1866,7 +1886,7 @@ pub fn lowerAnonDecl(
18661886 const mod = self.base.comp.module.?;
18671887 const ty = Type.fromInterned(mod.intern_pool.typeOf(decl_val));
18681888 const decl_alignment = switch (explicit_alignment) {
1869 .none => ty.abiAlignment(mod),
1889 .none => ty.abiAlignment(pt),
18701890 else => explicit_alignment,
18711891 };
18721892 if (self.anon_decls.get(decl_val)) |metadata| {
......@@ -1881,6 +1901,7 @@ pub fn lowerAnonDecl(
18811901 @intFromEnum(decl_val),
18821902 }) catch unreachable;
18831903 const res = self.lowerConst(
1904 pt,
18841905 name,
18851906 val,
18861907 decl_alignment,
......@@ -1951,9 +1972,9 @@ pub fn getGlobalSymbol(self: *Coff, name: []const u8, lib_name_name: ?[]const u8
19511972 return global_index;
19521973}
19531974
1954pub fn updateDeclLineNumber(self: *Coff, module: *Module, decl_index: InternPool.DeclIndex) !void {
1975pub fn updateDeclLineNumber(self: *Coff, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !void {
19551976 _ = self;
1956 _ = module;
1977 _ = pt;
19571978 _ = decl_index;
19581979 log.debug("TODO implement updateDeclLineNumber", .{});
19591980}
src/link/Coff/lld.zig+3-2
......@@ -15,8 +15,9 @@ const Allocator = mem.Allocator;
1515
1616const Coff = @import("../Coff.zig");
1717const Compilation = @import("../../Compilation.zig");
18const Zcu = @import("../../Zcu.zig");
1819
19pub fn linkWithLLD(self: *Coff, arena: Allocator, prog_node: std.Progress.Node) !void {
20pub fn linkWithLLD(self: *Coff, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) !void {
2021 const tracy = trace(@src());
2122 defer tracy.end();
2223
......@@ -29,7 +30,7 @@ pub fn linkWithLLD(self: *Coff, arena: Allocator, prog_node: std.Progress.Node)
2930 // If there is no Zig code to compile, then we should skip flushing the output file because it
3031 // will not be part of the linker line anyway.
3132 const module_obj_path: ?[]const u8 = if (comp.module != null) blk: {
32 try self.flushModule(arena, prog_node);
33 try self.flushModule(arena, tid, prog_node);
3334
3435 if (fs.path.dirname(full_out_path)) |dirname| {
3536 break :blk try fs.path.join(arena, &.{ dirname, self.base.zcu_object_sub_path.? });
src/link/Dwarf.zig+112-110
......@@ -31,7 +31,7 @@ strtab: StringTable = .{},
3131/// They will end up in the DWARF debug_line header as two lists:
3232/// * []include_directory
3333/// * []file_names
34di_files: std.AutoArrayHashMapUnmanaged(*const Module.File, void) = .{},
34di_files: std.AutoArrayHashMapUnmanaged(*const Zcu.File, void) = .{},
3535
3636global_abbrev_relocs: std.ArrayListUnmanaged(AbbrevRelocation) = .{},
3737
......@@ -67,7 +67,7 @@ const DbgLineHeader = struct {
6767/// Decl's inner Atom is assigned an offset within the DWARF section.
6868pub const DeclState = struct {
6969 dwarf: *Dwarf,
70 mod: *Module,
70 pt: Zcu.PerThread,
7171 di_atom_decls: *const AtomTable,
7272 dbg_line_func: InternPool.Index,
7373 dbg_line: std.ArrayList(u8),
......@@ -113,7 +113,7 @@ pub const DeclState = struct {
113113 .type = ty,
114114 .offset = undefined,
115115 });
116 log.debug("%{d}: {}", .{ sym_index, ty.fmt(self.mod) });
116 log.debug("%{d}: {}", .{ sym_index, ty.fmt(self.pt) });
117117 try self.abbrev_resolver.putNoClobber(gpa, ty.toIntern(), sym_index);
118118 break :blk sym_index;
119119 };
......@@ -128,16 +128,17 @@ pub const DeclState = struct {
128128
129129 fn addDbgInfoType(
130130 self: *DeclState,
131 mod: *Module,
131 pt: Zcu.PerThread,
132132 atom_index: Atom.Index,
133133 ty: Type,
134134 ) error{OutOfMemory}!void {
135 const zcu = pt.zcu;
135136 const dbg_info_buffer = &self.dbg_info;
136 const target = mod.getTarget();
137 const target = zcu.getTarget();
137138 const target_endian = target.cpu.arch.endian();
138 const ip = &mod.intern_pool;
139 const ip = &zcu.intern_pool;
139140
140 switch (ty.zigTypeTag(mod)) {
141 switch (ty.zigTypeTag(zcu)) {
141142 .NoReturn => unreachable,
142143 .Void => {
143144 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.zero_bit_type));
......@@ -148,12 +149,12 @@ pub const DeclState = struct {
148149 // DW.AT.encoding, DW.FORM.data1
149150 dbg_info_buffer.appendAssumeCapacity(DW.ATE.boolean);
150151 // DW.AT.byte_size, DW.FORM.udata
151 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(mod));
152 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(pt));
152153 // DW.AT.name, DW.FORM.string
153 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(mod)});
154 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(pt)});
154155 },
155156 .Int => {
156 const info = ty.intInfo(mod);
157 const info = ty.intInfo(zcu);
157158 try dbg_info_buffer.ensureUnusedCapacity(12);
158159 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.base_type));
159160 // DW.AT.encoding, DW.FORM.data1
......@@ -162,30 +163,30 @@ pub const DeclState = struct {
162163 .unsigned => DW.ATE.unsigned,
163164 });
164165 // DW.AT.byte_size, DW.FORM.udata
165 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(mod));
166 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(pt));
166167 // DW.AT.name, DW.FORM.string
167 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(mod)});
168 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(pt)});
168169 },
169170 .Optional => {
170 if (ty.isPtrLikeOptional(mod)) {
171 if (ty.isPtrLikeOptional(zcu)) {
171172 try dbg_info_buffer.ensureUnusedCapacity(12);
172173 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.base_type));
173174 // DW.AT.encoding, DW.FORM.data1
174175 dbg_info_buffer.appendAssumeCapacity(DW.ATE.address);
175176 // DW.AT.byte_size, DW.FORM.udata
176 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(mod));
177 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(pt));
177178 // DW.AT.name, DW.FORM.string
178 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(mod)});
179 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(pt)});
179180 } else {
180181 // Non-pointer optionals are structs: struct { .maybe = *, .val = * }
181 const payload_ty = ty.optionalChild(mod);
182 const payload_ty = ty.optionalChild(zcu);
182183 // DW.AT.structure_type
183184 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.struct_type));
184185 // DW.AT.byte_size, DW.FORM.udata
185 const abi_size = ty.abiSize(mod);
186 const abi_size = ty.abiSize(pt);
186187 try leb128.writeUleb128(dbg_info_buffer.writer(), abi_size);
187188 // DW.AT.name, DW.FORM.string
188 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(mod)});
189 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(pt)});
189190 // DW.AT.member
190191 try dbg_info_buffer.ensureUnusedCapacity(21);
191192 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.struct_member));
......@@ -208,14 +209,14 @@ pub const DeclState = struct {
208209 dbg_info_buffer.appendNTimesAssumeCapacity(0, 4);
209210 try self.addTypeRelocGlobal(atom_index, payload_ty, @intCast(index));
210211 // DW.AT.data_member_location, DW.FORM.udata
211 const offset = abi_size - payload_ty.abiSize(mod);
212 const offset = abi_size - payload_ty.abiSize(pt);
212213 try leb128.writeUleb128(dbg_info_buffer.writer(), offset);
213214 // DW.AT.structure_type delimit children
214215 try dbg_info_buffer.append(0);
215216 }
216217 },
217218 .Pointer => {
218 if (ty.isSlice(mod)) {
219 if (ty.isSlice(zcu)) {
219220 // Slices are structs: struct { .ptr = *, .len = N }
220221 const ptr_bits = target.ptrBitWidth();
221222 const ptr_bytes: u8 = @intCast(@divExact(ptr_bits, 8));
......@@ -223,9 +224,9 @@ pub const DeclState = struct {
223224 try dbg_info_buffer.ensureUnusedCapacity(2);
224225 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.struct_type));
225226 // DW.AT.byte_size, DW.FORM.udata
226 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(mod));
227 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(pt));
227228 // DW.AT.name, DW.FORM.string
228 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(mod)});
229 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(pt)});
229230 // DW.AT.member
230231 try dbg_info_buffer.ensureUnusedCapacity(21);
231232 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.struct_member));
......@@ -235,7 +236,7 @@ pub const DeclState = struct {
235236 // DW.AT.type, DW.FORM.ref4
236237 var index = dbg_info_buffer.items.len;
237238 dbg_info_buffer.appendNTimesAssumeCapacity(0, 4);
238 const ptr_ty = ty.slicePtrFieldType(mod);
239 const ptr_ty = ty.slicePtrFieldType(zcu);
239240 try self.addTypeRelocGlobal(atom_index, ptr_ty, @intCast(index));
240241 // DW.AT.data_member_location, DW.FORM.udata
241242 dbg_info_buffer.appendAssumeCapacity(0);
......@@ -258,19 +259,19 @@ pub const DeclState = struct {
258259 // DW.AT.type, DW.FORM.ref4
259260 const index = dbg_info_buffer.items.len;
260261 dbg_info_buffer.appendNTimesAssumeCapacity(0, 4);
261 try self.addTypeRelocGlobal(atom_index, ty.childType(mod), @intCast(index));
262 try self.addTypeRelocGlobal(atom_index, ty.childType(zcu), @intCast(index));
262263 }
263264 },
264265 .Array => {
265266 // DW.AT.array_type
266267 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.array_type));
267268 // DW.AT.name, DW.FORM.string
268 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(mod)});
269 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(pt)});
269270 // DW.AT.type, DW.FORM.ref4
270271 var index = dbg_info_buffer.items.len;
271272 try dbg_info_buffer.ensureUnusedCapacity(9);
272273 dbg_info_buffer.appendNTimesAssumeCapacity(0, 4);
273 try self.addTypeRelocGlobal(atom_index, ty.childType(mod), @intCast(index));
274 try self.addTypeRelocGlobal(atom_index, ty.childType(zcu), @intCast(index));
274275 // DW.AT.subrange_type
275276 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.array_dim));
276277 // DW.AT.type, DW.FORM.ref4
......@@ -278,7 +279,7 @@ pub const DeclState = struct {
278279 dbg_info_buffer.appendNTimesAssumeCapacity(0, 4);
279280 try self.addTypeRelocGlobal(atom_index, Type.usize, @intCast(index));
280281 // DW.AT.count, DW.FORM.udata
281 const len = ty.arrayLenIncludingSentinel(mod);
282 const len = ty.arrayLenIncludingSentinel(pt.zcu);
282283 try leb128.writeUleb128(dbg_info_buffer.writer(), len);
283284 // DW.AT.array_type delimit children
284285 try dbg_info_buffer.append(0);
......@@ -287,13 +288,13 @@ pub const DeclState = struct {
287288 // DW.AT.structure_type
288289 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.struct_type));
289290 // DW.AT.byte_size, DW.FORM.udata
290 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(mod));
291 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(pt));
291292
292293 blk: {
293294 switch (ip.indexToKey(ty.ip_index)) {
294295 .anon_struct_type => |fields| {
295296 // DW.AT.name, DW.FORM.string
296 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(mod)});
297 try dbg_info_buffer.writer().print("{}\x00", .{ty.fmt(pt)});
297298
298299 for (fields.types.get(ip), 0..) |field_ty, field_index| {
299300 // DW.AT.member
......@@ -305,14 +306,14 @@ pub const DeclState = struct {
305306 try dbg_info_buffer.appendNTimes(0, 4);
306307 try self.addTypeRelocGlobal(atom_index, Type.fromInterned(field_ty), @intCast(index));
307308 // DW.AT.data_member_location, DW.FORM.udata
308 const field_off = ty.structFieldOffset(field_index, mod);
309 const field_off = ty.structFieldOffset(field_index, pt);
309310 try leb128.writeUleb128(dbg_info_buffer.writer(), field_off);
310311 }
311312 },
312313 .struct_type => {
313314 const struct_type = ip.loadStructType(ty.toIntern());
314315 // DW.AT.name, DW.FORM.string
315 try ty.print(dbg_info_buffer.writer(), mod);
316 try ty.print(dbg_info_buffer.writer(), pt);
316317 try dbg_info_buffer.append(0);
317318
318319 if (struct_type.layout == .@"packed") {
......@@ -322,7 +323,7 @@ pub const DeclState = struct {
322323
323324 if (struct_type.isTuple(ip)) {
324325 for (struct_type.field_types.get(ip), struct_type.offsets.get(ip), 0..) |field_ty, field_off, field_index| {
325 if (!Type.fromInterned(field_ty).hasRuntimeBits(mod)) continue;
326 if (!Type.fromInterned(field_ty).hasRuntimeBits(pt)) continue;
326327 // DW.AT.member
327328 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.struct_member));
328329 // DW.AT.name, DW.FORM.string
......@@ -340,7 +341,7 @@ pub const DeclState = struct {
340341 struct_type.field_types.get(ip),
341342 struct_type.offsets.get(ip),
342343 ) |field_name, field_ty, field_off| {
343 if (!Type.fromInterned(field_ty).hasRuntimeBits(mod)) continue;
344 if (!Type.fromInterned(field_ty).hasRuntimeBits(pt)) continue;
344345 const field_name_slice = field_name.toSlice(ip);
345346 // DW.AT.member
346347 try dbg_info_buffer.ensureUnusedCapacity(field_name_slice.len + 2);
......@@ -367,9 +368,9 @@ pub const DeclState = struct {
367368 // DW.AT.enumeration_type
368369 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.enum_type));
369370 // DW.AT.byte_size, DW.FORM.udata
370 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(mod));
371 try leb128.writeUleb128(dbg_info_buffer.writer(), ty.abiSize(pt));
371372 // DW.AT.name, DW.FORM.string
372 try ty.print(dbg_info_buffer.writer(), mod);
373 try ty.print(dbg_info_buffer.writer(), pt);
373374 try dbg_info_buffer.append(0);
374375
375376 const enum_type = ip.loadEnumType(ty.ip_index);
......@@ -386,8 +387,8 @@ pub const DeclState = struct {
386387 const value = enum_type.values.get(ip)[field_i];
387388 // TODO do not assume a 64bit enum value - could be bigger.
388389 // See https://github.com/ziglang/zig/issues/645
389 const field_int_val = try Value.fromInterned(value).intFromEnum(ty, mod);
390 break :value @bitCast(field_int_val.toSignedInt(mod));
390 const field_int_val = try Value.fromInterned(value).intFromEnum(ty, pt);
391 break :value @bitCast(field_int_val.toSignedInt(pt));
391392 };
392393 mem.writeInt(u64, dbg_info_buffer.addManyAsArrayAssumeCapacity(8), value, target_endian);
393394 }
......@@ -396,8 +397,8 @@ pub const DeclState = struct {
396397 try dbg_info_buffer.append(0);
397398 },
398399 .Union => {
399 const union_obj = mod.typeToUnion(ty).?;
400 const layout = mod.getUnionLayout(union_obj);
400 const union_obj = zcu.typeToUnion(ty).?;
401 const layout = pt.getUnionLayout(union_obj);
401402 const payload_offset = if (layout.tag_align.compare(.gte, layout.payload_align)) layout.tag_size else 0;
402403 const tag_offset = if (layout.tag_align.compare(.gte, layout.payload_align)) 0 else layout.payload_size;
403404 // TODO this is temporary to match current state of unions in Zig - we don't yet have
......@@ -410,7 +411,7 @@ pub const DeclState = struct {
410411 // DW.AT.byte_size, DW.FORM.udata
411412 try leb128.writeUleb128(dbg_info_buffer.writer(), layout.abi_size);
412413 // DW.AT.name, DW.FORM.string
413 try ty.print(dbg_info_buffer.writer(), mod);
414 try ty.print(dbg_info_buffer.writer(), pt);
414415 try dbg_info_buffer.append(0);
415416
416417 // DW.AT.member
......@@ -435,12 +436,12 @@ pub const DeclState = struct {
435436 if (is_tagged) {
436437 try dbg_info_buffer.writer().print("AnonUnion\x00", .{});
437438 } else {
438 try ty.print(dbg_info_buffer.writer(), mod);
439 try ty.print(dbg_info_buffer.writer(), pt);
439440 try dbg_info_buffer.append(0);
440441 }
441442
442443 for (union_obj.field_types.get(ip), union_obj.loadTagType(ip).names.get(ip)) |field_ty, field_name| {
443 if (!Type.fromInterned(field_ty).hasRuntimeBits(mod)) continue;
444 if (!Type.fromInterned(field_ty).hasRuntimeBits(pt)) continue;
444445 const field_name_slice = field_name.toSlice(ip);
445446 // DW.AT.member
446447 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.struct_member));
......@@ -474,25 +475,25 @@ pub const DeclState = struct {
474475 try dbg_info_buffer.append(0);
475476 }
476477 },
477 .ErrorSet => try addDbgInfoErrorSet(mod, ty, target, &self.dbg_info),
478 .ErrorSet => try addDbgInfoErrorSet(pt, ty, target, &self.dbg_info),
478479 .ErrorUnion => {
479 const error_ty = ty.errorUnionSet(mod);
480 const payload_ty = ty.errorUnionPayload(mod);
481 const payload_align = if (payload_ty.isNoReturn(mod)) .none else payload_ty.abiAlignment(mod);
482 const error_align = Type.anyerror.abiAlignment(mod);
483 const abi_size = ty.abiSize(mod);
484 const payload_off = if (error_align.compare(.gte, payload_align)) Type.anyerror.abiSize(mod) else 0;
485 const error_off = if (error_align.compare(.gte, payload_align)) 0 else payload_ty.abiSize(mod);
480 const error_ty = ty.errorUnionSet(zcu);
481 const payload_ty = ty.errorUnionPayload(zcu);
482 const payload_align = if (payload_ty.isNoReturn(zcu)) .none else payload_ty.abiAlignment(pt);
483 const error_align = Type.anyerror.abiAlignment(pt);
484 const abi_size = ty.abiSize(pt);
485 const payload_off = if (error_align.compare(.gte, payload_align)) Type.anyerror.abiSize(pt) else 0;
486 const error_off = if (error_align.compare(.gte, payload_align)) 0 else payload_ty.abiSize(pt);
486487
487488 // DW.AT.structure_type
488489 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.struct_type));
489490 // DW.AT.byte_size, DW.FORM.udata
490491 try leb128.writeUleb128(dbg_info_buffer.writer(), abi_size);
491492 // DW.AT.name, DW.FORM.string
492 try ty.print(dbg_info_buffer.writer(), mod);
493 try ty.print(dbg_info_buffer.writer(), pt);
493494 try dbg_info_buffer.append(0);
494495
495 if (!payload_ty.isNoReturn(mod)) {
496 if (!payload_ty.isNoReturn(zcu)) {
496497 // DW.AT.member
497498 try dbg_info_buffer.ensureUnusedCapacity(11);
498499 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.struct_member));
......@@ -526,7 +527,7 @@ pub const DeclState = struct {
526527 try dbg_info_buffer.append(0);
527528 },
528529 else => {
529 log.debug("TODO implement .debug_info for type '{}'", .{ty.fmt(self.mod)});
530 log.debug("TODO implement .debug_info for type '{}'", .{ty.fmt(pt)});
530531 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.zero_bit_type));
531532 },
532533 }
......@@ -555,6 +556,7 @@ pub const DeclState = struct {
555556 owner_decl: InternPool.DeclIndex,
556557 loc: DbgInfoLoc,
557558 ) error{OutOfMemory}!void {
559 const pt = self.pt;
558560 const dbg_info = &self.dbg_info;
559561 const atom_index = self.di_atom_decls.get(owner_decl).?;
560562 const name_with_null = name.ptr[0 .. name.len + 1];
......@@ -580,9 +582,9 @@ pub const DeclState = struct {
580582 }
581583 },
582584 .register_pair => |regs| {
583 const reg_bits = self.mod.getTarget().ptrBitWidth();
585 const reg_bits = pt.zcu.getTarget().ptrBitWidth();
584586 const reg_bytes: u8 = @intCast(@divExact(reg_bits, 8));
585 const abi_size = ty.abiSize(self.mod);
587 const abi_size = ty.abiSize(pt);
586588 try dbg_info.ensureUnusedCapacity(10);
587589 dbg_info.appendAssumeCapacity(@intFromEnum(AbbrevCode.parameter));
588590 // DW.AT.location, DW.FORM.exprloc
......@@ -675,10 +677,10 @@ pub const DeclState = struct {
675677 const name_with_null = name.ptr[0 .. name.len + 1];
676678 try dbg_info.append(@intFromEnum(AbbrevCode.variable));
677679 const gpa = self.dwarf.allocator;
678 const mod = self.mod;
679 const target = mod.getTarget();
680 const pt = self.pt;
681 const target = pt.zcu.getTarget();
680682 const endian = target.cpu.arch.endian();
681 const child_ty = if (is_ptr) ty.childType(mod) else ty;
683 const child_ty = if (is_ptr) ty.childType(pt.zcu) else ty;
682684
683685 switch (loc) {
684686 .register => |reg| {
......@@ -701,9 +703,9 @@ pub const DeclState = struct {
701703 },
702704
703705 .register_pair => |regs| {
704 const reg_bits = self.mod.getTarget().ptrBitWidth();
706 const reg_bits = pt.zcu.getTarget().ptrBitWidth();
705707 const reg_bytes: u8 = @intCast(@divExact(reg_bits, 8));
706 const abi_size = child_ty.abiSize(self.mod);
708 const abi_size = child_ty.abiSize(pt);
707709 try dbg_info.ensureUnusedCapacity(9);
708710 // DW.AT.location, DW.FORM.exprloc
709711 var expr_len = std.io.countingWriter(std.io.null_writer);
......@@ -829,9 +831,9 @@ pub const DeclState = struct {
829831 const fixup = dbg_info.items.len;
830832 dbg_info.appendSliceAssumeCapacity(&[2]u8{ // DW.AT.location, DW.FORM.exprloc
831833 1,
832 if (child_ty.isSignedInt(mod)) DW.OP.consts else DW.OP.constu,
834 if (child_ty.isSignedInt(pt.zcu)) DW.OP.consts else DW.OP.constu,
833835 });
834 if (child_ty.isSignedInt(mod)) {
836 if (child_ty.isSignedInt(pt.zcu)) {
835837 try leb128.writeIleb128(dbg_info.writer(), @as(i64, @bitCast(x)));
836838 } else {
837839 try leb128.writeUleb128(dbg_info.writer(), x);
......@@ -844,7 +846,7 @@ pub const DeclState = struct {
844846 // DW.AT.location, DW.FORM.exprloc
845847 // uleb128(exprloc_len)
846848 // DW.OP.implicit_value uleb128(len_of_bytes) bytes
847 const abi_size: u32 = @intCast(child_ty.abiSize(mod));
849 const abi_size: u32 = @intCast(child_ty.abiSize(self.pt));
848850 var implicit_value_len = std.ArrayList(u8).init(gpa);
849851 defer implicit_value_len.deinit();
850852 try leb128.writeUleb128(implicit_value_len.writer(), abi_size);
......@@ -934,22 +936,23 @@ pub const DeclState = struct {
934936 }
935937
936938 pub fn setInlineFunc(self: *DeclState, func: InternPool.Index) error{OutOfMemory}!void {
939 const zcu = self.pt.zcu;
937940 if (self.dbg_line_func == func) return;
938941
939942 try self.dbg_line.ensureUnusedCapacity((1 + 4) + (1 + 5));
940943
941 const old_func_info = self.mod.funcInfo(self.dbg_line_func);
942 const new_func_info = self.mod.funcInfo(func);
944 const old_func_info = zcu.funcInfo(self.dbg_line_func);
945 const new_func_info = zcu.funcInfo(func);
943946
944 const old_file = try self.dwarf.addDIFile(self.mod, old_func_info.owner_decl);
945 const new_file = try self.dwarf.addDIFile(self.mod, new_func_info.owner_decl);
947 const old_file = try self.dwarf.addDIFile(zcu, old_func_info.owner_decl);
948 const new_file = try self.dwarf.addDIFile(zcu, new_func_info.owner_decl);
946949 if (old_file != new_file) {
947950 self.dbg_line.appendAssumeCapacity(DW.LNS.set_file);
948951 leb128.writeUnsignedFixed(4, self.dbg_line.addManyAsArrayAssumeCapacity(4), new_file);
949952 }
950953
951 const old_src_line: i33 = self.mod.declPtr(old_func_info.owner_decl).navSrcLine(self.mod);
952 const new_src_line: i33 = self.mod.declPtr(new_func_info.owner_decl).navSrcLine(self.mod);
954 const old_src_line: i33 = zcu.declPtr(old_func_info.owner_decl).navSrcLine(zcu);
955 const new_src_line: i33 = zcu.declPtr(new_func_info.owner_decl).navSrcLine(zcu);
953956 if (new_src_line != old_src_line) {
954957 self.dbg_line.appendAssumeCapacity(DW.LNS.advance_line);
955958 leb128.writeSignedFixed(5, self.dbg_line.addManyAsArrayAssumeCapacity(5), new_src_line - old_src_line);
......@@ -1074,19 +1077,19 @@ pub fn deinit(self: *Dwarf) void {
10741077
10751078/// Initializes Decl's state and its matching output buffers.
10761079/// Call this before `commitDeclState`.
1077pub fn initDeclState(self: *Dwarf, mod: *Module, decl_index: InternPool.DeclIndex) !DeclState {
1080pub fn initDeclState(self: *Dwarf, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !DeclState {
10781081 const tracy = trace(@src());
10791082 defer tracy.end();
10801083
1081 const decl = mod.declPtr(decl_index);
1082 const decl_linkage_name = try decl.fullyQualifiedName(mod);
1084 const decl = pt.zcu.declPtr(decl_index);
1085 const decl_linkage_name = try decl.fullyQualifiedName(pt);
10831086
1084 log.debug("initDeclState {}{*}", .{ decl_linkage_name.fmt(&mod.intern_pool), decl });
1087 log.debug("initDeclState {}{*}", .{ decl_linkage_name.fmt(&pt.zcu.intern_pool), decl });
10851088
10861089 const gpa = self.allocator;
10871090 var decl_state: DeclState = .{
10881091 .dwarf = self,
1089 .mod = mod,
1092 .pt = pt,
10901093 .di_atom_decls = &self.di_atom_decls,
10911094 .dbg_line_func = undefined,
10921095 .dbg_line = std.ArrayList(u8).init(gpa),
......@@ -1105,7 +1108,7 @@ pub fn initDeclState(self: *Dwarf, mod: *Module, decl_index: InternPool.DeclInde
11051108
11061109 assert(decl.has_tv);
11071110
1108 switch (decl.typeOf(mod).zigTypeTag(mod)) {
1111 switch (decl.typeOf(pt.zcu).zigTypeTag(pt.zcu)) {
11091112 .Fn => {
11101113 _ = try self.getOrCreateAtomForDecl(.src_fn, decl_index);
11111114
......@@ -1114,13 +1117,13 @@ pub fn initDeclState(self: *Dwarf, mod: *Module, decl_index: InternPool.DeclInde
11141117 try dbg_line_buffer.ensureTotalCapacity((3 + ptr_width_bytes) + (1 + 4) + (1 + 4) + (1 + 5) + 1);
11151118
11161119 decl_state.dbg_line_func = decl.val.toIntern();
1117 const func = decl.val.getFunction(mod).?;
1120 const func = decl.val.getFunction(pt.zcu).?;
11181121 log.debug("decl.src_line={d}, func.lbrace_line={d}, func.rbrace_line={d}", .{
1119 decl.navSrcLine(mod),
1122 decl.navSrcLine(pt.zcu),
11201123 func.lbrace_line,
11211124 func.rbrace_line,
11221125 });
1123 const line: u28 = @intCast(decl.navSrcLine(mod) + func.lbrace_line);
1126 const line: u28 = @intCast(decl.navSrcLine(pt.zcu) + func.lbrace_line);
11241127
11251128 dbg_line_buffer.appendSliceAssumeCapacity(&.{
11261129 DW.LNS.extended_op,
......@@ -1142,7 +1145,7 @@ pub fn initDeclState(self: *Dwarf, mod: *Module, decl_index: InternPool.DeclInde
11421145 assert(self.getRelocDbgFileIndex() == dbg_line_buffer.items.len);
11431146 // Once we support more than one source file, this will have the ability to be more
11441147 // than one possible value.
1145 const file_index = try self.addDIFile(mod, decl_index);
1148 const file_index = try self.addDIFile(pt.zcu, decl_index);
11461149 leb128.writeUnsignedFixed(4, dbg_line_buffer.addManyAsArrayAssumeCapacity(4), file_index);
11471150
11481151 dbg_line_buffer.appendAssumeCapacity(DW.LNS.set_column);
......@@ -1153,13 +1156,13 @@ pub fn initDeclState(self: *Dwarf, mod: *Module, decl_index: InternPool.DeclInde
11531156 dbg_line_buffer.appendAssumeCapacity(DW.LNS.copy);
11541157
11551158 // .debug_info subprogram
1156 const decl_name_slice = decl.name.toSlice(&mod.intern_pool);
1157 const decl_linkage_name_slice = decl_linkage_name.toSlice(&mod.intern_pool);
1159 const decl_name_slice = decl.name.toSlice(&pt.zcu.intern_pool);
1160 const decl_linkage_name_slice = decl_linkage_name.toSlice(&pt.zcu.intern_pool);
11581161 try dbg_info_buffer.ensureUnusedCapacity(1 + ptr_width_bytes + 4 + 4 +
11591162 (decl_name_slice.len + 1) + (decl_linkage_name_slice.len + 1));
11601163
1161 const fn_ret_type = decl.typeOf(mod).fnReturnType(mod);
1162 const fn_ret_has_bits = fn_ret_type.hasRuntimeBits(mod);
1164 const fn_ret_type = decl.typeOf(pt.zcu).fnReturnType(pt.zcu);
1165 const fn_ret_has_bits = fn_ret_type.hasRuntimeBits(pt);
11631166 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(
11641167 @as(AbbrevCode, if (fn_ret_has_bits) .subprogram else .subprogram_retvoid),
11651168 ));
......@@ -1191,7 +1194,7 @@ pub fn initDeclState(self: *Dwarf, mod: *Module, decl_index: InternPool.DeclInde
11911194
11921195pub fn commitDeclState(
11931196 self: *Dwarf,
1194 zcu: *Module,
1197 pt: Zcu.PerThread,
11951198 decl_index: InternPool.DeclIndex,
11961199 sym_addr: u64,
11971200 sym_size: u64,
......@@ -1201,6 +1204,7 @@ pub fn commitDeclState(
12011204 defer tracy.end();
12021205
12031206 const gpa = self.allocator;
1207 const zcu = pt.zcu;
12041208 const decl = zcu.declPtr(decl_index);
12051209 const ip = &zcu.intern_pool;
12061210 const namespace = zcu.namespacePtr(decl.src_namespace);
......@@ -1432,7 +1436,7 @@ pub fn commitDeclState(
14321436 if (ip.isErrorSetType(ty.toIntern())) continue;
14331437
14341438 symbol.offset = @intCast(dbg_info_buffer.items.len);
1435 try decl_state.addDbgInfoType(zcu, di_atom_index, ty);
1439 try decl_state.addDbgInfoType(pt, di_atom_index, ty);
14361440 }
14371441 }
14381442
......@@ -1457,7 +1461,7 @@ pub fn commitDeclState(
14571461 reloc.offset,
14581462 value,
14591463 reloc_target,
1460 ty.fmt(zcu),
1464 ty.fmt(pt),
14611465 });
14621466 mem.writeInt(
14631467 u32,
......@@ -1691,7 +1695,7 @@ fn writeDeclDebugInfo(self: *Dwarf, atom_index: Atom.Index, dbg_info_buf: []cons
16911695 }
16921696}
16931697
1694pub fn updateDeclLineNumber(self: *Dwarf, mod: *Module, decl_index: InternPool.DeclIndex) !void {
1698pub fn updateDeclLineNumber(self: *Dwarf, zcu: *Zcu, decl_index: InternPool.DeclIndex) !void {
16951699 const tracy = trace(@src());
16961700 defer tracy.end();
16971701
......@@ -1699,14 +1703,14 @@ pub fn updateDeclLineNumber(self: *Dwarf, mod: *Module, decl_index: InternPool.D
16991703 const atom = self.getAtom(.src_fn, atom_index);
17001704 if (atom.len == 0) return;
17011705
1702 const decl = mod.declPtr(decl_index);
1703 const func = decl.val.getFunction(mod).?;
1706 const decl = zcu.declPtr(decl_index);
1707 const func = decl.val.getFunction(zcu).?;
17041708 log.debug("decl.src_line={d}, func.lbrace_line={d}, func.rbrace_line={d}", .{
1705 decl.navSrcLine(mod),
1709 decl.navSrcLine(zcu),
17061710 func.lbrace_line,
17071711 func.rbrace_line,
17081712 });
1709 const line: u28 = @intCast(decl.navSrcLine(mod) + func.lbrace_line);
1713 const line: u28 = @intCast(decl.navSrcLine(zcu) + func.lbrace_line);
17101714 var data: [4]u8 = undefined;
17111715 leb128.writeUnsignedFixed(4, &data, line);
17121716
......@@ -1969,7 +1973,7 @@ fn dbgInfoHeaderBytes(self: *Dwarf) usize {
19691973 return 120;
19701974}
19711975
1972pub fn writeDbgInfoHeader(self: *Dwarf, zcu: *Module, low_pc: u64, high_pc: u64) !void {
1976pub fn writeDbgInfoHeader(self: *Dwarf, zcu: *Zcu, low_pc: u64, high_pc: u64) !void {
19731977 // If this value is null it means there is an error in the module;
19741978 // leave debug_info_header_dirty=true.
19751979 const first_dbg_info_off = self.getDebugInfoOff() orelse return;
......@@ -2058,14 +2062,14 @@ pub fn writeDbgInfoHeader(self: *Dwarf, zcu: *Module, low_pc: u64, high_pc: u64)
20582062 }
20592063}
20602064
2061fn resolveCompilationDir(module: *Module, buffer: *[std.fs.max_path_bytes]u8) []const u8 {
2065fn resolveCompilationDir(zcu: *Zcu, buffer: *[std.fs.max_path_bytes]u8) []const u8 {
20622066 // We fully resolve all paths at this point to avoid lack of source line info in stack
20632067 // traces or lack of debugging information which, if relative paths were used, would
20642068 // be very location dependent.
20652069 // TODO: the only concern I have with this is WASI as either host or target, should
20662070 // we leave the paths as relative then?
2067 const root_dir_path = module.root_mod.root.root_dir.path orelse ".";
2068 const sub_path = module.root_mod.root.sub_path;
2071 const root_dir_path = zcu.root_mod.root.root_dir.path orelse ".";
2072 const sub_path = zcu.root_mod.root.sub_path;
20692073 const realpath = if (std.fs.path.isAbsolute(root_dir_path)) r: {
20702074 @memcpy(buffer[0..root_dir_path.len], root_dir_path);
20712075 break :r root_dir_path;
......@@ -2682,7 +2686,7 @@ fn padToIdeal(actual_size: anytype) @TypeOf(actual_size) {
26822686 return actual_size +| (actual_size / ideal_factor);
26832687}
26842688
2685pub fn flushModule(self: *Dwarf, module: *Module) !void {
2689pub fn flushModule(self: *Dwarf, pt: Zcu.PerThread) !void {
26862690 const comp = self.bin_file.comp;
26872691 const target = comp.root_mod.resolved_target.result;
26882692
......@@ -2694,9 +2698,9 @@ pub fn flushModule(self: *Dwarf, module: *Module) !void {
26942698
26952699 var dbg_info_buffer = std.ArrayList(u8).init(arena);
26962700 try addDbgInfoErrorSetNames(
2697 module,
2701 pt,
26982702 Type.anyerror,
2699 module.global_error_set.keys(),
2703 pt.zcu.global_error_set.keys(),
27002704 target,
27012705 &dbg_info_buffer,
27022706 );
......@@ -2759,9 +2763,9 @@ pub fn flushModule(self: *Dwarf, module: *Module) !void {
27592763 }
27602764}
27612765
2762fn addDIFile(self: *Dwarf, mod: *Module, decl_index: InternPool.DeclIndex) !u28 {
2763 const decl = mod.declPtr(decl_index);
2764 const file_scope = decl.getFileScope(mod);
2766fn addDIFile(self: *Dwarf, zcu: *Zcu, decl_index: InternPool.DeclIndex) !u28 {
2767 const decl = zcu.declPtr(decl_index);
2768 const file_scope = decl.getFileScope(zcu);
27652769 const gop = try self.di_files.getOrPut(self.allocator, file_scope);
27662770 if (!gop.found_existing) {
27672771 switch (self.bin_file.tag) {
......@@ -2827,16 +2831,16 @@ fn genIncludeDirsAndFileNames(self: *Dwarf, arena: Allocator) !struct {
28272831}
28282832
28292833fn addDbgInfoErrorSet(
2830 mod: *Module,
2834 pt: Zcu.PerThread,
28312835 ty: Type,
28322836 target: std.Target,
28332837 dbg_info_buffer: *std.ArrayList(u8),
28342838) !void {
2835 return addDbgInfoErrorSetNames(mod, ty, ty.errorSetNames(mod).get(&mod.intern_pool), target, dbg_info_buffer);
2839 return addDbgInfoErrorSetNames(pt, ty, ty.errorSetNames(pt.zcu).get(&pt.zcu.intern_pool), target, dbg_info_buffer);
28362840}
28372841
28382842fn addDbgInfoErrorSetNames(
2839 mod: *Module,
2843 pt: Zcu.PerThread,
28402844 /// Used for printing the type name only.
28412845 ty: Type,
28422846 error_names: []const InternPool.NullTerminatedString,
......@@ -2848,10 +2852,10 @@ fn addDbgInfoErrorSetNames(
28482852 // DW.AT.enumeration_type
28492853 try dbg_info_buffer.append(@intFromEnum(AbbrevCode.enum_type));
28502854 // DW.AT.byte_size, DW.FORM.udata
2851 const abi_size = Type.anyerror.abiSize(mod);
2855 const abi_size = Type.anyerror.abiSize(pt);
28522856 try leb128.writeUleb128(dbg_info_buffer.writer(), abi_size);
28532857 // DW.AT.name, DW.FORM.string
2854 try ty.print(dbg_info_buffer.writer(), mod);
2858 try ty.print(dbg_info_buffer.writer(), pt);
28552859 try dbg_info_buffer.append(0);
28562860
28572861 // DW.AT.enumerator
......@@ -2865,8 +2869,8 @@ fn addDbgInfoErrorSetNames(
28652869 mem.writeInt(u64, dbg_info_buffer.addManyAsArrayAssumeCapacity(8), 0, target_endian);
28662870
28672871 for (error_names) |error_name| {
2868 const int = try mod.getErrorValue(error_name);
2869 const error_name_slice = error_name.toSlice(&mod.intern_pool);
2872 const int = try pt.zcu.getErrorValue(error_name);
2873 const error_name_slice = error_name.toSlice(&pt.zcu.intern_pool);
28702874 // DW.AT.enumerator
28712875 try dbg_info_buffer.ensureUnusedCapacity(error_name_slice.len + 2 + @sizeOf(u64));
28722876 dbg_info_buffer.appendAssumeCapacity(@intFromEnum(AbbrevCode.enum_variant));
......@@ -2965,8 +2969,6 @@ const LinkBlock = File.LinkBlock;
29652969const LinkFn = File.LinkFn;
29662970const LinkerLoad = @import("../codegen.zig").LinkerLoad;
29672971const Zcu = @import("../Zcu.zig");
2968/// Deprecated.
2969const Module = Zcu;
29702972const InternPool = @import("../InternPool.zig");
29712973const StringTable = @import("StringTable.zig");
29722974const Type = @import("../Type.zig");
src/link/Elf.zig+23-22
......@@ -543,18 +543,19 @@ pub fn deinit(self: *Elf) void {
543543 self.comdat_group_sections.deinit(gpa);
544544}
545545
546pub fn getDeclVAddr(self: *Elf, decl_index: InternPool.DeclIndex, reloc_info: link.File.RelocInfo) !u64 {
546pub fn getDeclVAddr(self: *Elf, _: Zcu.PerThread, decl_index: InternPool.DeclIndex, reloc_info: link.File.RelocInfo) !u64 {
547547 assert(self.llvm_object == null);
548548 return self.zigObjectPtr().?.getDeclVAddr(self, decl_index, reloc_info);
549549}
550550
551551pub fn lowerAnonDecl(
552552 self: *Elf,
553 pt: Zcu.PerThread,
553554 decl_val: InternPool.Index,
554555 explicit_alignment: InternPool.Alignment,
555556 src_loc: Module.LazySrcLoc,
556557) !codegen.Result {
557 return self.zigObjectPtr().?.lowerAnonDecl(self, decl_val, explicit_alignment, src_loc);
558 return self.zigObjectPtr().?.lowerAnonDecl(self, pt, decl_val, explicit_alignment, src_loc);
558559}
559560
560561pub fn getAnonDeclVAddr(self: *Elf, decl_val: InternPool.Index, reloc_info: link.File.RelocInfo) !u64 {
......@@ -1064,15 +1065,15 @@ pub fn markDirty(self: *Elf, shdr_index: u32) void {
10641065 }
10651066}
10661067
1067pub fn flush(self: *Elf, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
1068pub fn flush(self: *Elf, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
10681069 const use_lld = build_options.have_llvm and self.base.comp.config.use_lld;
10691070 if (use_lld) {
1070 return self.linkWithLLD(arena, prog_node);
1071 return self.linkWithLLD(arena, tid, prog_node);
10711072 }
1072 try self.flushModule(arena, prog_node);
1073 try self.flushModule(arena, tid, prog_node);
10731074}
10741075
1075pub fn flushModule(self: *Elf, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
1076pub fn flushModule(self: *Elf, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
10761077 const tracy = trace(@src());
10771078 defer tracy.end();
10781079
......@@ -1103,7 +1104,7 @@ pub fn flushModule(self: *Elf, arena: Allocator, prog_node: std.Progress.Node) l
11031104 // --verbose-link
11041105 if (comp.verbose_link) try self.dumpArgv(comp);
11051106
1106 if (self.zigObjectPtr()) |zig_object| try zig_object.flushModule(self);
1107 if (self.zigObjectPtr()) |zig_object| try zig_object.flushModule(self, tid);
11071108 if (self.base.isStaticLib()) return relocatable.flushStaticLib(self, comp, module_obj_path);
11081109 if (self.base.isObject()) return relocatable.flushObject(self, comp, module_obj_path);
11091110
......@@ -2146,7 +2147,7 @@ fn scanRelocs(self: *Elf) !void {
21462147 }
21472148}
21482149
2149fn linkWithLLD(self: *Elf, arena: Allocator, prog_node: std.Progress.Node) !void {
2150fn linkWithLLD(self: *Elf, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) !void {
21502151 const tracy = trace(@src());
21512152 defer tracy.end();
21522153
......@@ -2159,7 +2160,7 @@ fn linkWithLLD(self: *Elf, arena: Allocator, prog_node: std.Progress.Node) !void
21592160 // If there is no Zig code to compile, then we should skip flushing the output file because it
21602161 // will not be part of the linker line anyway.
21612162 const module_obj_path: ?[]const u8 = if (comp.module != null) blk: {
2162 try self.flushModule(arena, prog_node);
2163 try self.flushModule(arena, tid, prog_node);
21632164
21642165 if (fs.path.dirname(full_out_path)) |dirname| {
21652166 break :blk try fs.path.join(arena, &.{ dirname, self.base.zcu_object_sub_path.? });
......@@ -2983,46 +2984,46 @@ pub fn freeDecl(self: *Elf, decl_index: InternPool.DeclIndex) void {
29832984 return self.zigObjectPtr().?.freeDecl(self, decl_index);
29842985}
29852986
2986pub fn updateFunc(self: *Elf, mod: *Module, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
2987pub fn updateFunc(self: *Elf, pt: Zcu.PerThread, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
29872988 if (build_options.skip_non_native and builtin.object_format != .elf) {
29882989 @panic("Attempted to compile for object format that was disabled by build configuration");
29892990 }
2990 if (self.llvm_object) |llvm_object| return llvm_object.updateFunc(mod, func_index, air, liveness);
2991 return self.zigObjectPtr().?.updateFunc(self, mod, func_index, air, liveness);
2991 if (self.llvm_object) |llvm_object| return llvm_object.updateFunc(pt, func_index, air, liveness);
2992 return self.zigObjectPtr().?.updateFunc(self, pt, func_index, air, liveness);
29922993}
29932994
29942995pub fn updateDecl(
29952996 self: *Elf,
2996 mod: *Module,
2997 pt: Zcu.PerThread,
29972998 decl_index: InternPool.DeclIndex,
29982999) link.File.UpdateDeclError!void {
29993000 if (build_options.skip_non_native and builtin.object_format != .elf) {
30003001 @panic("Attempted to compile for object format that was disabled by build configuration");
30013002 }
3002 if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(mod, decl_index);
3003 return self.zigObjectPtr().?.updateDecl(self, mod, decl_index);
3003 if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(pt, decl_index);
3004 return self.zigObjectPtr().?.updateDecl(self, pt, decl_index);
30043005}
30053006
3006pub fn lowerUnnamedConst(self: *Elf, val: Value, decl_index: InternPool.DeclIndex) !u32 {
3007 return self.zigObjectPtr().?.lowerUnnamedConst(self, val, decl_index);
3007pub fn lowerUnnamedConst(self: *Elf, pt: Zcu.PerThread, val: Value, decl_index: InternPool.DeclIndex) !u32 {
3008 return self.zigObjectPtr().?.lowerUnnamedConst(self, pt, val, decl_index);
30083009}
30093010
30103011pub fn updateExports(
30113012 self: *Elf,
3012 mod: *Module,
3013 pt: Zcu.PerThread,
30133014 exported: Module.Exported,
30143015 export_indices: []const u32,
30153016) link.File.UpdateExportsError!void {
30163017 if (build_options.skip_non_native and builtin.object_format != .elf) {
30173018 @panic("Attempted to compile for object format that was disabled by build configuration");
30183019 }
3019 if (self.llvm_object) |llvm_object| return llvm_object.updateExports(mod, exported, export_indices);
3020 return self.zigObjectPtr().?.updateExports(self, mod, exported, export_indices);
3020 if (self.llvm_object) |llvm_object| return llvm_object.updateExports(pt, exported, export_indices);
3021 return self.zigObjectPtr().?.updateExports(self, pt, exported, export_indices);
30213022}
30223023
3023pub fn updateDeclLineNumber(self: *Elf, mod: *Module, decl_index: InternPool.DeclIndex) !void {
3024pub fn updateDeclLineNumber(self: *Elf, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !void {
30243025 if (self.llvm_object) |_| return;
3025 return self.zigObjectPtr().?.updateDeclLineNumber(mod, decl_index);
3026 return self.zigObjectPtr().?.updateDeclLineNumber(pt, decl_index);
30263027}
30273028
30283029pub fn deleteExport(
src/link/Elf/ZigObject.zig+68-63
......@@ -158,16 +158,17 @@ pub fn deinit(self: *ZigObject, allocator: Allocator) void {
158158 }
159159}
160160
161pub fn flushModule(self: *ZigObject, elf_file: *Elf) !void {
161pub fn flushModule(self: *ZigObject, elf_file: *Elf, tid: Zcu.PerThread.Id) !void {
162162 // Handle any lazy symbols that were emitted by incremental compilation.
163163 if (self.lazy_syms.getPtr(.none)) |metadata| {
164 const zcu = elf_file.base.comp.module.?;
164 const pt: Zcu.PerThread = .{ .zcu = elf_file.base.comp.module.?, .tid = tid };
165165
166166 // Most lazy symbols can be updated on first use, but
167167 // anyerror needs to wait for everything to be flushed.
168168 if (metadata.text_state != .unused) self.updateLazySymbol(
169169 elf_file,
170 link.File.LazySymbol.initDecl(.code, null, zcu),
170 pt,
171 link.File.LazySymbol.initDecl(.code, null, pt.zcu),
171172 metadata.text_symbol_index,
172173 ) catch |err| return switch (err) {
173174 error.CodegenFail => error.FlushFailure,
......@@ -175,7 +176,8 @@ pub fn flushModule(self: *ZigObject, elf_file: *Elf) !void {
175176 };
176177 if (metadata.rodata_state != .unused) self.updateLazySymbol(
177178 elf_file,
178 link.File.LazySymbol.initDecl(.const_data, null, zcu),
179 pt,
180 link.File.LazySymbol.initDecl(.const_data, null, pt.zcu),
179181 metadata.rodata_symbol_index,
180182 ) catch |err| return switch (err) {
181183 error.CodegenFail => error.FlushFailure,
......@@ -188,8 +190,8 @@ pub fn flushModule(self: *ZigObject, elf_file: *Elf) !void {
188190 }
189191
190192 if (self.dwarf) |*dw| {
191 const zcu = elf_file.base.comp.module.?;
192 try dw.flushModule(zcu);
193 const pt: Zcu.PerThread = .{ .zcu = elf_file.base.comp.module.?, .tid = tid };
194 try dw.flushModule(pt);
193195
194196 // TODO I need to re-think how to handle ZigObject's debug sections AND debug sections
195197 // extracted from input object files correctly.
......@@ -202,7 +204,7 @@ pub fn flushModule(self: *ZigObject, elf_file: *Elf) !void {
202204 const text_shdr = elf_file.shdrs.items[elf_file.zig_text_section_index.?];
203205 const low_pc = text_shdr.sh_addr;
204206 const high_pc = text_shdr.sh_addr + text_shdr.sh_size;
205 try dw.writeDbgInfoHeader(zcu, low_pc, high_pc);
207 try dw.writeDbgInfoHeader(pt.zcu, low_pc, high_pc);
206208 self.debug_info_header_dirty = false;
207209 }
208210
......@@ -684,6 +686,7 @@ pub fn getAnonDeclVAddr(
684686pub fn lowerAnonDecl(
685687 self: *ZigObject,
686688 elf_file: *Elf,
689 pt: Zcu.PerThread,
687690 decl_val: InternPool.Index,
688691 explicit_alignment: InternPool.Alignment,
689692 src_loc: Module.LazySrcLoc,
......@@ -692,7 +695,7 @@ pub fn lowerAnonDecl(
692695 const mod = elf_file.base.comp.module.?;
693696 const ty = Type.fromInterned(mod.intern_pool.typeOf(decl_val));
694697 const decl_alignment = switch (explicit_alignment) {
695 .none => ty.abiAlignment(mod),
698 .none => ty.abiAlignment(pt),
696699 else => explicit_alignment,
697700 };
698701 if (self.anon_decls.get(decl_val)) |metadata| {
......@@ -708,6 +711,7 @@ pub fn lowerAnonDecl(
708711 }) catch unreachable;
709712 const res = self.lowerConst(
710713 elf_file,
714 pt,
711715 name,
712716 val,
713717 decl_alignment,
......@@ -733,10 +737,11 @@ pub fn lowerAnonDecl(
733737pub fn getOrCreateMetadataForLazySymbol(
734738 self: *ZigObject,
735739 elf_file: *Elf,
740 pt: Zcu.PerThread,
736741 lazy_sym: link.File.LazySymbol,
737742) !Symbol.Index {
738 const gpa = elf_file.base.comp.gpa;
739 const mod = elf_file.base.comp.module.?;
743 const mod = pt.zcu;
744 const gpa = mod.gpa;
740745 const gop = try self.lazy_syms.getOrPut(gpa, lazy_sym.getDecl(mod));
741746 errdefer _ = if (!gop.found_existing) self.lazy_syms.pop();
742747 if (!gop.found_existing) gop.value_ptr.* = .{};
......@@ -766,7 +771,7 @@ pub fn getOrCreateMetadataForLazySymbol(
766771 metadata.state.* = .pending_flush;
767772 const symbol_index = metadata.symbol_index.*;
768773 // anyerror needs to be deferred until flushModule
769 if (lazy_sym.getDecl(mod) != .none) try self.updateLazySymbol(elf_file, lazy_sym, symbol_index);
774 if (lazy_sym.getDecl(mod) != .none) try self.updateLazySymbol(elf_file, pt, lazy_sym, symbol_index);
770775 return symbol_index;
771776}
772777
......@@ -893,6 +898,7 @@ fn getDeclShdrIndex(
893898fn updateDeclCode(
894899 self: *ZigObject,
895900 elf_file: *Elf,
901 pt: Zcu.PerThread,
896902 decl_index: InternPool.DeclIndex,
897903 sym_index: Symbol.Index,
898904 shdr_index: u32,
......@@ -900,13 +906,13 @@ fn updateDeclCode(
900906 stt_bits: u8,
901907) !void {
902908 const gpa = elf_file.base.comp.gpa;
903 const mod = elf_file.base.comp.module.?;
909 const mod = pt.zcu;
904910 const decl = mod.declPtr(decl_index);
905 const decl_name = try decl.fullyQualifiedName(mod);
911 const decl_name = try decl.fullyQualifiedName(pt);
906912
907913 log.debug("updateDeclCode {}{*}", .{ decl_name.fmt(&mod.intern_pool), decl });
908914
909 const required_alignment = decl.getAlignment(mod).max(
915 const required_alignment = decl.getAlignment(pt).max(
910916 target_util.minFunctionAlignment(mod.getTarget()),
911917 );
912918
......@@ -994,19 +1000,20 @@ fn updateDeclCode(
9941000fn updateTlv(
9951001 self: *ZigObject,
9961002 elf_file: *Elf,
1003 pt: Zcu.PerThread,
9971004 decl_index: InternPool.DeclIndex,
9981005 sym_index: Symbol.Index,
9991006 shndx: u32,
10001007 code: []const u8,
10011008) !void {
1002 const gpa = elf_file.base.comp.gpa;
1003 const mod = elf_file.base.comp.module.?;
1009 const mod = pt.zcu;
1010 const gpa = mod.gpa;
10041011 const decl = mod.declPtr(decl_index);
1005 const decl_name = try decl.fullyQualifiedName(mod);
1012 const decl_name = try decl.fullyQualifiedName(pt);
10061013
10071014 log.debug("updateTlv {} ({*})", .{ decl_name.fmt(&mod.intern_pool), decl });
10081015
1009 const required_alignment = decl.getAlignment(mod);
1016 const required_alignment = decl.getAlignment(pt);
10101017
10111018 const sym = elf_file.symbol(sym_index);
10121019 const esym = &self.local_esyms.items(.elf_sym)[sym.esym_index];
......@@ -1048,7 +1055,7 @@ fn updateTlv(
10481055pub fn updateFunc(
10491056 self: *ZigObject,
10501057 elf_file: *Elf,
1051 mod: *Module,
1058 pt: Zcu.PerThread,
10521059 func_index: InternPool.Index,
10531060 air: Air,
10541061 liveness: Liveness,
......@@ -1056,6 +1063,7 @@ pub fn updateFunc(
10561063 const tracy = trace(@src());
10571064 defer tracy.end();
10581065
1066 const mod = pt.zcu;
10591067 const gpa = elf_file.base.comp.gpa;
10601068 const func = mod.funcInfo(func_index);
10611069 const decl_index = func.owner_decl;
......@@ -1068,29 +1076,19 @@ pub fn updateFunc(
10681076 var code_buffer = std.ArrayList(u8).init(gpa);
10691077 defer code_buffer.deinit();
10701078
1071 var decl_state: ?Dwarf.DeclState = if (self.dwarf) |*dw| try dw.initDeclState(mod, decl_index) else null;
1079 var decl_state: ?Dwarf.DeclState = if (self.dwarf) |*dw| try dw.initDeclState(pt, decl_index) else null;
10721080 defer if (decl_state) |*ds| ds.deinit();
10731081
1074 const res = if (decl_state) |*ds|
1075 try codegen.generateFunction(
1076 &elf_file.base,
1077 decl.navSrcLoc(mod),
1078 func_index,
1079 air,
1080 liveness,
1081 &code_buffer,
1082 .{ .dwarf = ds },
1083 )
1084 else
1085 try codegen.generateFunction(
1086 &elf_file.base,
1087 decl.navSrcLoc(mod),
1088 func_index,
1089 air,
1090 liveness,
1091 &code_buffer,
1092 .none,
1093 );
1082 const res = try codegen.generateFunction(
1083 &elf_file.base,
1084 pt,
1085 decl.navSrcLoc(mod),
1086 func_index,
1087 air,
1088 liveness,
1089 &code_buffer,
1090 if (decl_state) |*ds| .{ .dwarf = ds } else .none,
1091 );
10941092
10951093 const code = switch (res) {
10961094 .ok => code_buffer.items,
......@@ -1102,12 +1100,12 @@ pub fn updateFunc(
11021100 };
11031101
11041102 const shndx = try self.getDeclShdrIndex(elf_file, decl, code);
1105 try self.updateDeclCode(elf_file, decl_index, sym_index, shndx, code, elf.STT_FUNC);
1103 try self.updateDeclCode(elf_file, pt, decl_index, sym_index, shndx, code, elf.STT_FUNC);
11061104
11071105 if (decl_state) |*ds| {
11081106 const sym = elf_file.symbol(sym_index);
11091107 try self.dwarf.?.commitDeclState(
1110 mod,
1108 pt,
11111109 decl_index,
11121110 @intCast(sym.address(.{}, elf_file)),
11131111 sym.atom(elf_file).?.size,
......@@ -1121,12 +1119,13 @@ pub fn updateFunc(
11211119pub fn updateDecl(
11221120 self: *ZigObject,
11231121 elf_file: *Elf,
1124 mod: *Module,
1122 pt: Zcu.PerThread,
11251123 decl_index: InternPool.DeclIndex,
11261124) link.File.UpdateDeclError!void {
11271125 const tracy = trace(@src());
11281126 defer tracy.end();
11291127
1128 const mod = pt.zcu;
11301129 const decl = mod.declPtr(decl_index);
11311130
11321131 if (decl.val.getExternFunc(mod)) |_| {
......@@ -1150,19 +1149,19 @@ pub fn updateDecl(
11501149 var code_buffer = std.ArrayList(u8).init(gpa);
11511150 defer code_buffer.deinit();
11521151
1153 var decl_state: ?Dwarf.DeclState = if (self.dwarf) |*dw| try dw.initDeclState(mod, decl_index) else null;
1152 var decl_state: ?Dwarf.DeclState = if (self.dwarf) |*dw| try dw.initDeclState(pt, decl_index) else null;
11541153 defer if (decl_state) |*ds| ds.deinit();
11551154
11561155 // TODO implement .debug_info for global variables
11571156 const decl_val = if (decl.val.getVariable(mod)) |variable| Value.fromInterned(variable.init) else decl.val;
11581157 const res = if (decl_state) |*ds|
1159 try codegen.generateSymbol(&elf_file.base, decl.navSrcLoc(mod), decl_val, &code_buffer, .{
1158 try codegen.generateSymbol(&elf_file.base, pt, decl.navSrcLoc(mod), decl_val, &code_buffer, .{
11601159 .dwarf = ds,
11611160 }, .{
11621161 .parent_atom_index = sym_index,
11631162 })
11641163 else
1165 try codegen.generateSymbol(&elf_file.base, decl.navSrcLoc(mod), decl_val, &code_buffer, .none, .{
1164 try codegen.generateSymbol(&elf_file.base, pt, decl.navSrcLoc(mod), decl_val, &code_buffer, .none, .{
11661165 .parent_atom_index = sym_index,
11671166 });
11681167
......@@ -1177,14 +1176,14 @@ pub fn updateDecl(
11771176
11781177 const shndx = try self.getDeclShdrIndex(elf_file, decl, code);
11791178 if (elf_file.shdrs.items[shndx].sh_flags & elf.SHF_TLS != 0)
1180 try self.updateTlv(elf_file, decl_index, sym_index, shndx, code)
1179 try self.updateTlv(elf_file, pt, decl_index, sym_index, shndx, code)
11811180 else
1182 try self.updateDeclCode(elf_file, decl_index, sym_index, shndx, code, elf.STT_OBJECT);
1181 try self.updateDeclCode(elf_file, pt, decl_index, sym_index, shndx, code, elf.STT_OBJECT);
11831182
11841183 if (decl_state) |*ds| {
11851184 const sym = elf_file.symbol(sym_index);
11861185 try self.dwarf.?.commitDeclState(
1187 mod,
1186 pt,
11881187 decl_index,
11891188 @intCast(sym.address(.{}, elf_file)),
11901189 sym.atom(elf_file).?.size,
......@@ -1198,11 +1197,12 @@ pub fn updateDecl(
11981197fn updateLazySymbol(
11991198 self: *ZigObject,
12001199 elf_file: *Elf,
1200 pt: Zcu.PerThread,
12011201 sym: link.File.LazySymbol,
12021202 symbol_index: Symbol.Index,
12031203) !void {
1204 const gpa = elf_file.base.comp.gpa;
1205 const mod = elf_file.base.comp.module.?;
1204 const mod = pt.zcu;
1205 const gpa = mod.gpa;
12061206
12071207 var required_alignment: InternPool.Alignment = .none;
12081208 var code_buffer = std.ArrayList(u8).init(gpa);
......@@ -1211,7 +1211,7 @@ fn updateLazySymbol(
12111211 const name_str_index = blk: {
12121212 const name = try std.fmt.allocPrint(gpa, "__lazy_{s}_{}", .{
12131213 @tagName(sym.kind),
1214 sym.ty.fmt(mod),
1214 sym.ty.fmt(pt),
12151215 });
12161216 defer gpa.free(name);
12171217 break :blk try self.strtab.insert(gpa, name);
......@@ -1220,6 +1220,7 @@ fn updateLazySymbol(
12201220 const src = sym.ty.srcLocOrNull(mod) orelse Module.LazySrcLoc.unneeded;
12211221 const res = try codegen.generateLazySymbol(
12221222 &elf_file.base,
1223 pt,
12231224 src,
12241225 sym,
12251226 &required_alignment,
......@@ -1273,6 +1274,7 @@ fn updateLazySymbol(
12731274pub fn lowerUnnamedConst(
12741275 self: *ZigObject,
12751276 elf_file: *Elf,
1277 pt: Zcu.PerThread,
12761278 val: Value,
12771279 decl_index: InternPool.DeclIndex,
12781280) !u32 {
......@@ -1284,16 +1286,17 @@ pub fn lowerUnnamedConst(
12841286 }
12851287 const unnamed_consts = gop.value_ptr;
12861288 const decl = mod.declPtr(decl_index);
1287 const decl_name = try decl.fullyQualifiedName(mod);
1289 const decl_name = try decl.fullyQualifiedName(pt);
12881290 const index = unnamed_consts.items.len;
12891291 const name = try std.fmt.allocPrint(gpa, "__unnamed_{}_{d}", .{ decl_name.fmt(&mod.intern_pool), index });
12901292 defer gpa.free(name);
12911293 const ty = val.typeOf(mod);
12921294 const sym_index = switch (try self.lowerConst(
12931295 elf_file,
1296 pt,
12941297 name,
12951298 val,
1296 ty.abiAlignment(mod),
1299 ty.abiAlignment(pt),
12971300 elf_file.zig_data_rel_ro_section_index.?,
12981301 decl.navSrcLoc(mod),
12991302 )) {
......@@ -1318,20 +1321,21 @@ const LowerConstResult = union(enum) {
13181321fn lowerConst(
13191322 self: *ZigObject,
13201323 elf_file: *Elf,
1324 pt: Zcu.PerThread,
13211325 name: []const u8,
13221326 val: Value,
13231327 required_alignment: InternPool.Alignment,
13241328 output_section_index: u32,
13251329 src_loc: Module.LazySrcLoc,
13261330) !LowerConstResult {
1327 const gpa = elf_file.base.comp.gpa;
1331 const gpa = pt.zcu.gpa;
13281332
13291333 var code_buffer = std.ArrayList(u8).init(gpa);
13301334 defer code_buffer.deinit();
13311335
13321336 const sym_index = try self.addAtom(elf_file);
13331337
1334 const res = try codegen.generateSymbol(&elf_file.base, src_loc, val, &code_buffer, .{
1338 const res = try codegen.generateSymbol(&elf_file.base, pt, src_loc, val, &code_buffer, .{
13351339 .none = {},
13361340 }, .{
13371341 .parent_atom_index = sym_index,
......@@ -1373,13 +1377,14 @@ fn lowerConst(
13731377pub fn updateExports(
13741378 self: *ZigObject,
13751379 elf_file: *Elf,
1376 mod: *Module,
1380 pt: Zcu.PerThread,
13771381 exported: Module.Exported,
13781382 export_indices: []const u32,
13791383) link.File.UpdateExportsError!void {
13801384 const tracy = trace(@src());
13811385 defer tracy.end();
13821386
1387 const mod = pt.zcu;
13831388 const gpa = elf_file.base.comp.gpa;
13841389 const metadata = switch (exported) {
13851390 .decl_index => |decl_index| blk: {
......@@ -1388,7 +1393,7 @@ pub fn updateExports(
13881393 },
13891394 .value => |value| self.anon_decls.getPtr(value) orelse blk: {
13901395 const first_exp = mod.all_exports.items[export_indices[0]];
1391 const res = try self.lowerAnonDecl(elf_file, value, .none, first_exp.src);
1396 const res = try self.lowerAnonDecl(elf_file, pt, value, .none, first_exp.src);
13921397 switch (res) {
13931398 .ok => {},
13941399 .fail => |em| {
......@@ -1461,19 +1466,19 @@ pub fn updateExports(
14611466/// Must be called only after a successful call to `updateDecl`.
14621467pub fn updateDeclLineNumber(
14631468 self: *ZigObject,
1464 mod: *Module,
1469 pt: Zcu.PerThread,
14651470 decl_index: InternPool.DeclIndex,
14661471) !void {
14671472 const tracy = trace(@src());
14681473 defer tracy.end();
14691474
1470 const decl = mod.declPtr(decl_index);
1471 const decl_name = try decl.fullyQualifiedName(mod);
1475 const decl = pt.zcu.declPtr(decl_index);
1476 const decl_name = try decl.fullyQualifiedName(pt);
14721477
1473 log.debug("updateDeclLineNumber {}{*}", .{ decl_name.fmt(&mod.intern_pool), decl });
1478 log.debug("updateDeclLineNumber {}{*}", .{ decl_name.fmt(&pt.zcu.intern_pool), decl });
14741479
14751480 if (self.dwarf) |*dw| {
1476 try dw.updateDeclLineNumber(mod, decl_index);
1481 try dw.updateDeclLineNumber(pt.zcu, decl_index);
14771482 }
14781483}
14791484
src/link/MachO.zig+20-19
......@@ -360,11 +360,11 @@ pub fn deinit(self: *MachO) void {
360360 self.unwind_records.deinit(gpa);
361361}
362362
363pub fn flush(self: *MachO, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
364 try self.flushModule(arena, prog_node);
363pub fn flush(self: *MachO, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
364 try self.flushModule(arena, tid, prog_node);
365365}
366366
367pub fn flushModule(self: *MachO, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
367pub fn flushModule(self: *MachO, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
368368 const tracy = trace(@src());
369369 defer tracy.end();
370370
......@@ -391,7 +391,7 @@ pub fn flushModule(self: *MachO, arena: Allocator, prog_node: std.Progress.Node)
391391 // --verbose-link
392392 if (comp.verbose_link) try self.dumpArgv(comp);
393393
394 if (self.getZigObject()) |zo| try zo.flushModule(self);
394 if (self.getZigObject()) |zo| try zo.flushModule(self, tid);
395395 if (self.base.isStaticLib()) return relocatable.flushStaticLib(self, comp, module_obj_path);
396396 if (self.base.isObject()) return relocatable.flushObject(self, comp, module_obj_path);
397397
......@@ -3178,42 +3178,42 @@ pub fn writeCodeSignature(self: *MachO, code_sig: *CodeSignature) !void {
31783178 try self.base.file.?.pwriteAll(buffer.items, offset);
31793179}
31803180
3181pub fn updateFunc(self: *MachO, mod: *Module, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
3181pub fn updateFunc(self: *MachO, pt: Zcu.PerThread, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
31823182 if (build_options.skip_non_native and builtin.object_format != .macho) {
31833183 @panic("Attempted to compile for object format that was disabled by build configuration");
31843184 }
3185 if (self.llvm_object) |llvm_object| return llvm_object.updateFunc(mod, func_index, air, liveness);
3186 return self.getZigObject().?.updateFunc(self, mod, func_index, air, liveness);
3185 if (self.llvm_object) |llvm_object| return llvm_object.updateFunc(pt, func_index, air, liveness);
3186 return self.getZigObject().?.updateFunc(self, pt, func_index, air, liveness);
31873187}
31883188
3189pub fn lowerUnnamedConst(self: *MachO, val: Value, decl_index: InternPool.DeclIndex) !u32 {
3190 return self.getZigObject().?.lowerUnnamedConst(self, val, decl_index);
3189pub fn lowerUnnamedConst(self: *MachO, pt: Zcu.PerThread, val: Value, decl_index: InternPool.DeclIndex) !u32 {
3190 return self.getZigObject().?.lowerUnnamedConst(self, pt, val, decl_index);
31913191}
31923192
3193pub fn updateDecl(self: *MachO, mod: *Module, decl_index: InternPool.DeclIndex) !void {
3193pub fn updateDecl(self: *MachO, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !void {
31943194 if (build_options.skip_non_native and builtin.object_format != .macho) {
31953195 @panic("Attempted to compile for object format that was disabled by build configuration");
31963196 }
3197 if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(mod, decl_index);
3198 return self.getZigObject().?.updateDecl(self, mod, decl_index);
3197 if (self.llvm_object) |llvm_object| return llvm_object.updateDecl(pt, decl_index);
3198 return self.getZigObject().?.updateDecl(self, pt, decl_index);
31993199}
32003200
3201pub fn updateDeclLineNumber(self: *MachO, module: *Module, decl_index: InternPool.DeclIndex) !void {
3201pub fn updateDeclLineNumber(self: *MachO, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !void {
32023202 if (self.llvm_object) |_| return;
3203 return self.getZigObject().?.updateDeclLineNumber(module, decl_index);
3203 return self.getZigObject().?.updateDeclLineNumber(pt, decl_index);
32043204}
32053205
32063206pub fn updateExports(
32073207 self: *MachO,
3208 mod: *Module,
3208 pt: Zcu.PerThread,
32093209 exported: Module.Exported,
32103210 export_indices: []const u32,
32113211) link.File.UpdateExportsError!void {
32123212 if (build_options.skip_non_native and builtin.object_format != .macho) {
32133213 @panic("Attempted to compile for object format that was disabled by build configuration");
32143214 }
3215 if (self.llvm_object) |llvm_object| return llvm_object.updateExports(mod, exported, export_indices);
3216 return self.getZigObject().?.updateExports(self, mod, exported, export_indices);
3215 if (self.llvm_object) |llvm_object| return llvm_object.updateExports(pt, exported, export_indices);
3216 return self.getZigObject().?.updateExports(self, pt, exported, export_indices);
32173217}
32183218
32193219pub fn deleteExport(
......@@ -3230,18 +3230,19 @@ pub fn freeDecl(self: *MachO, decl_index: InternPool.DeclIndex) void {
32303230 return self.getZigObject().?.freeDecl(decl_index);
32313231}
32323232
3233pub fn getDeclVAddr(self: *MachO, decl_index: InternPool.DeclIndex, reloc_info: link.File.RelocInfo) !u64 {
3233pub fn getDeclVAddr(self: *MachO, _: Zcu.PerThread, decl_index: InternPool.DeclIndex, reloc_info: link.File.RelocInfo) !u64 {
32343234 assert(self.llvm_object == null);
32353235 return self.getZigObject().?.getDeclVAddr(self, decl_index, reloc_info);
32363236}
32373237
32383238pub fn lowerAnonDecl(
32393239 self: *MachO,
3240 pt: Zcu.PerThread,
32403241 decl_val: InternPool.Index,
32413242 explicit_alignment: InternPool.Alignment,
32423243 src_loc: Module.LazySrcLoc,
32433244) !codegen.Result {
3244 return self.getZigObject().?.lowerAnonDecl(self, decl_val, explicit_alignment, src_loc);
3245 return self.getZigObject().?.lowerAnonDecl(self, pt, decl_val, explicit_alignment, src_loc);
32453246}
32463247
32473248pub fn getAnonDeclVAddr(self: *MachO, decl_val: InternPool.Index, reloc_info: link.File.RelocInfo) !u64 {
src/link/MachO/ZigObject.zig+56-41
......@@ -425,16 +425,17 @@ pub fn getInputSection(self: ZigObject, atom: Atom, macho_file: *MachO) macho.se
425425 return sect;
426426}
427427
428pub fn flushModule(self: *ZigObject, macho_file: *MachO) !void {
428pub fn flushModule(self: *ZigObject, macho_file: *MachO, tid: Zcu.PerThread.Id) !void {
429429 // Handle any lazy symbols that were emitted by incremental compilation.
430430 if (self.lazy_syms.getPtr(.none)) |metadata| {
431 const zcu = macho_file.base.comp.module.?;
431 const pt: Zcu.PerThread = .{ .zcu = macho_file.base.comp.module.?, .tid = tid };
432432
433433 // Most lazy symbols can be updated on first use, but
434434 // anyerror needs to wait for everything to be flushed.
435435 if (metadata.text_state != .unused) self.updateLazySymbol(
436436 macho_file,
437 link.File.LazySymbol.initDecl(.code, null, zcu),
437 pt,
438 link.File.LazySymbol.initDecl(.code, null, pt.zcu),
438439 metadata.text_symbol_index,
439440 ) catch |err| return switch (err) {
440441 error.CodegenFail => error.FlushFailure,
......@@ -442,7 +443,8 @@ pub fn flushModule(self: *ZigObject, macho_file: *MachO) !void {
442443 };
443444 if (metadata.const_state != .unused) self.updateLazySymbol(
444445 macho_file,
445 link.File.LazySymbol.initDecl(.const_data, null, zcu),
446 pt,
447 link.File.LazySymbol.initDecl(.const_data, null, pt.zcu),
446448 metadata.const_symbol_index,
447449 ) catch |err| return switch (err) {
448450 error.CodegenFail => error.FlushFailure,
......@@ -455,8 +457,8 @@ pub fn flushModule(self: *ZigObject, macho_file: *MachO) !void {
455457 }
456458
457459 if (self.dwarf) |*dw| {
458 const zcu = macho_file.base.comp.module.?;
459 try dw.flushModule(zcu);
460 const pt: Zcu.PerThread = .{ .zcu = macho_file.base.comp.module.?, .tid = tid };
461 try dw.flushModule(pt);
460462
461463 if (self.debug_abbrev_dirty) {
462464 try dw.writeDbgAbbrev();
......@@ -469,7 +471,7 @@ pub fn flushModule(self: *ZigObject, macho_file: *MachO) !void {
469471 const text_section = macho_file.sections.items(.header)[macho_file.zig_text_sect_index.?];
470472 const low_pc = text_section.addr;
471473 const high_pc = text_section.addr + text_section.size;
472 try dw.writeDbgInfoHeader(zcu, low_pc, high_pc);
474 try dw.writeDbgInfoHeader(pt.zcu, low_pc, high_pc);
473475 self.debug_info_header_dirty = false;
474476 }
475477
......@@ -570,6 +572,7 @@ pub fn getAnonDeclVAddr(
570572pub fn lowerAnonDecl(
571573 self: *ZigObject,
572574 macho_file: *MachO,
575 pt: Zcu.PerThread,
573576 decl_val: InternPool.Index,
574577 explicit_alignment: Atom.Alignment,
575578 src_loc: Module.LazySrcLoc,
......@@ -578,7 +581,7 @@ pub fn lowerAnonDecl(
578581 const mod = macho_file.base.comp.module.?;
579582 const ty = Type.fromInterned(mod.intern_pool.typeOf(decl_val));
580583 const decl_alignment = switch (explicit_alignment) {
581 .none => ty.abiAlignment(mod),
584 .none => ty.abiAlignment(pt),
582585 else => explicit_alignment,
583586 };
584587 if (self.anon_decls.get(decl_val)) |metadata| {
......@@ -593,6 +596,7 @@ pub fn lowerAnonDecl(
593596 }) catch unreachable;
594597 const res = self.lowerConst(
595598 macho_file,
599 pt,
596600 name,
597601 Value.fromInterned(decl_val),
598602 decl_alignment,
......@@ -656,7 +660,7 @@ pub fn freeDecl(self: *ZigObject, macho_file: *MachO, decl_index: InternPool.Dec
656660pub fn updateFunc(
657661 self: *ZigObject,
658662 macho_file: *MachO,
659 mod: *Module,
663 pt: Zcu.PerThread,
660664 func_index: InternPool.Index,
661665 air: Air,
662666 liveness: Liveness,
......@@ -664,7 +668,8 @@ pub fn updateFunc(
664668 const tracy = trace(@src());
665669 defer tracy.end();
666670
667 const gpa = macho_file.base.comp.gpa;
671 const mod = pt.zcu;
672 const gpa = mod.gpa;
668673 const func = mod.funcInfo(func_index);
669674 const decl_index = func.owner_decl;
670675 const decl = mod.declPtr(decl_index);
......@@ -676,12 +681,13 @@ pub fn updateFunc(
676681 var code_buffer = std.ArrayList(u8).init(gpa);
677682 defer code_buffer.deinit();
678683
679 var decl_state: ?Dwarf.DeclState = if (self.dwarf) |*dw| try dw.initDeclState(mod, decl_index) else null;
684 var decl_state: ?Dwarf.DeclState = if (self.dwarf) |*dw| try dw.initDeclState(pt, decl_index) else null;
680685 defer if (decl_state) |*ds| ds.deinit();
681686
682687 const dio: codegen.DebugInfoOutput = if (decl_state) |*ds| .{ .dwarf = ds } else .none;
683688 const res = try codegen.generateFunction(
684689 &macho_file.base,
690 pt,
685691 decl.navSrcLoc(mod),
686692 func_index,
687693 air,
......@@ -700,12 +706,12 @@ pub fn updateFunc(
700706 };
701707
702708 const sect_index = try self.getDeclOutputSection(macho_file, decl, code);
703 try self.updateDeclCode(macho_file, decl_index, sym_index, sect_index, code);
709 try self.updateDeclCode(macho_file, pt, decl_index, sym_index, sect_index, code);
704710
705711 if (decl_state) |*ds| {
706712 const sym = macho_file.getSymbol(sym_index);
707713 try self.dwarf.?.commitDeclState(
708 mod,
714 pt,
709715 decl_index,
710716 sym.getAddress(.{}, macho_file),
711717 sym.getAtom(macho_file).?.size,
......@@ -719,12 +725,13 @@ pub fn updateFunc(
719725pub fn updateDecl(
720726 self: *ZigObject,
721727 macho_file: *MachO,
722 mod: *Module,
728 pt: Zcu.PerThread,
723729 decl_index: InternPool.DeclIndex,
724730) link.File.UpdateDeclError!void {
725731 const tracy = trace(@src());
726732 defer tracy.end();
727733
734 const mod = pt.zcu;
728735 const decl = mod.declPtr(decl_index);
729736
730737 if (decl.val.getExternFunc(mod)) |_| {
......@@ -749,12 +756,12 @@ pub fn updateDecl(
749756 var code_buffer = std.ArrayList(u8).init(gpa);
750757 defer code_buffer.deinit();
751758
752 var decl_state: ?Dwarf.DeclState = if (self.dwarf) |*dw| try dw.initDeclState(mod, decl_index) else null;
759 var decl_state: ?Dwarf.DeclState = if (self.dwarf) |*dw| try dw.initDeclState(pt, decl_index) else null;
753760 defer if (decl_state) |*ds| ds.deinit();
754761
755762 const decl_val = if (decl.val.getVariable(mod)) |variable| Value.fromInterned(variable.init) else decl.val;
756763 const dio: codegen.DebugInfoOutput = if (decl_state) |*ds| .{ .dwarf = ds } else .none;
757 const res = try codegen.generateSymbol(&macho_file.base, decl.navSrcLoc(mod), decl_val, &code_buffer, dio, .{
764 const res = try codegen.generateSymbol(&macho_file.base, pt, decl.navSrcLoc(mod), decl_val, &code_buffer, dio, .{
758765 .parent_atom_index = sym_index,
759766 });
760767
......@@ -772,15 +779,15 @@ pub fn updateDecl(
772779 else => false,
773780 };
774781 if (is_threadlocal) {
775 try self.updateTlv(macho_file, decl_index, sym_index, sect_index, code);
782 try self.updateTlv(macho_file, pt, decl_index, sym_index, sect_index, code);
776783 } else {
777 try self.updateDeclCode(macho_file, decl_index, sym_index, sect_index, code);
784 try self.updateDeclCode(macho_file, pt, decl_index, sym_index, sect_index, code);
778785 }
779786
780787 if (decl_state) |*ds| {
781788 const sym = macho_file.getSymbol(sym_index);
782789 try self.dwarf.?.commitDeclState(
783 mod,
790 pt,
784791 decl_index,
785792 sym.getAddress(.{}, macho_file),
786793 sym.getAtom(macho_file).?.size,
......@@ -794,19 +801,20 @@ pub fn updateDecl(
794801fn updateDeclCode(
795802 self: *ZigObject,
796803 macho_file: *MachO,
804 pt: Zcu.PerThread,
797805 decl_index: InternPool.DeclIndex,
798806 sym_index: Symbol.Index,
799807 sect_index: u8,
800808 code: []const u8,
801809) !void {
802810 const gpa = macho_file.base.comp.gpa;
803 const mod = macho_file.base.comp.module.?;
811 const mod = pt.zcu;
804812 const decl = mod.declPtr(decl_index);
805 const decl_name = try decl.fullyQualifiedName(mod);
813 const decl_name = try decl.fullyQualifiedName(pt);
806814
807815 log.debug("updateDeclCode {}{*}", .{ decl_name.fmt(&mod.intern_pool), decl });
808816
809 const required_alignment = decl.getAlignment(mod);
817 const required_alignment = decl.getAlignment(pt);
810818
811819 const sect = &macho_file.sections.items(.header)[sect_index];
812820 const sym = macho_file.getSymbol(sym_index);
......@@ -879,19 +887,19 @@ fn updateDeclCode(
879887fn updateTlv(
880888 self: *ZigObject,
881889 macho_file: *MachO,
890 pt: Zcu.PerThread,
882891 decl_index: InternPool.DeclIndex,
883892 sym_index: Symbol.Index,
884893 sect_index: u8,
885894 code: []const u8,
886895) !void {
887 const mod = macho_file.base.comp.module.?;
888 const decl = mod.declPtr(decl_index);
889 const decl_name = try decl.fullyQualifiedName(mod);
896 const decl = pt.zcu.declPtr(decl_index);
897 const decl_name = try decl.fullyQualifiedName(pt);
890898
891 log.debug("updateTlv {} ({*})", .{ decl_name.fmt(&mod.intern_pool), decl });
899 log.debug("updateTlv {} ({*})", .{ decl_name.fmt(&pt.zcu.intern_pool), decl });
892900
893 const decl_name_slice = decl_name.toSlice(&mod.intern_pool);
894 const required_alignment = decl.getAlignment(mod);
901 const decl_name_slice = decl_name.toSlice(&pt.zcu.intern_pool);
902 const required_alignment = decl.getAlignment(pt);
895903
896904 // 1. Lower TLV initializer
897905 const init_sym_index = try self.createTlvInitializer(
......@@ -1079,26 +1087,28 @@ fn getDeclOutputSection(
10791087pub fn lowerUnnamedConst(
10801088 self: *ZigObject,
10811089 macho_file: *MachO,
1090 pt: Zcu.PerThread,
10821091 val: Value,
10831092 decl_index: InternPool.DeclIndex,
10841093) !u32 {
1085 const gpa = macho_file.base.comp.gpa;
1086 const mod = macho_file.base.comp.module.?;
1094 const mod = pt.zcu;
1095 const gpa = mod.gpa;
10871096 const gop = try self.unnamed_consts.getOrPut(gpa, decl_index);
10881097 if (!gop.found_existing) {
10891098 gop.value_ptr.* = .{};
10901099 }
10911100 const unnamed_consts = gop.value_ptr;
10921101 const decl = mod.declPtr(decl_index);
1093 const decl_name = try decl.fullyQualifiedName(mod);
1102 const decl_name = try decl.fullyQualifiedName(pt);
10941103 const index = unnamed_consts.items.len;
10951104 const name = try std.fmt.allocPrint(gpa, "__unnamed_{}_{d}", .{ decl_name.fmt(&mod.intern_pool), index });
10961105 defer gpa.free(name);
10971106 const sym_index = switch (try self.lowerConst(
10981107 macho_file,
1108 pt,
10991109 name,
11001110 val,
1101 val.typeOf(mod).abiAlignment(mod),
1111 val.typeOf(mod).abiAlignment(pt),
11021112 macho_file.zig_const_sect_index.?,
11031113 decl.navSrcLoc(mod),
11041114 )) {
......@@ -1123,6 +1133,7 @@ const LowerConstResult = union(enum) {
11231133fn lowerConst(
11241134 self: *ZigObject,
11251135 macho_file: *MachO,
1136 pt: Zcu.PerThread,
11261137 name: []const u8,
11271138 val: Value,
11281139 required_alignment: Atom.Alignment,
......@@ -1136,7 +1147,7 @@ fn lowerConst(
11361147
11371148 const sym_index = try self.addAtom(macho_file);
11381149
1139 const res = try codegen.generateSymbol(&macho_file.base, src_loc, val, &code_buffer, .{
1150 const res = try codegen.generateSymbol(&macho_file.base, pt, src_loc, val, &code_buffer, .{
11401151 .none = {},
11411152 }, .{
11421153 .parent_atom_index = sym_index,
......@@ -1181,13 +1192,14 @@ fn lowerConst(
11811192pub fn updateExports(
11821193 self: *ZigObject,
11831194 macho_file: *MachO,
1184 mod: *Module,
1195 pt: Zcu.PerThread,
11851196 exported: Module.Exported,
11861197 export_indices: []const u32,
11871198) link.File.UpdateExportsError!void {
11881199 const tracy = trace(@src());
11891200 defer tracy.end();
11901201
1202 const mod = pt.zcu;
11911203 const gpa = macho_file.base.comp.gpa;
11921204 const metadata = switch (exported) {
11931205 .decl_index => |decl_index| blk: {
......@@ -1196,7 +1208,7 @@ pub fn updateExports(
11961208 },
11971209 .value => |value| self.anon_decls.getPtr(value) orelse blk: {
11981210 const first_exp = mod.all_exports.items[export_indices[0]];
1199 const res = try self.lowerAnonDecl(macho_file, value, .none, first_exp.src);
1211 const res = try self.lowerAnonDecl(macho_file, pt, value, .none, first_exp.src);
12001212 switch (res) {
12011213 .ok => {},
12021214 .fail => |em| {
......@@ -1272,6 +1284,7 @@ pub fn updateExports(
12721284fn updateLazySymbol(
12731285 self: *ZigObject,
12741286 macho_file: *MachO,
1287 pt: Zcu.PerThread,
12751288 lazy_sym: link.File.LazySymbol,
12761289 symbol_index: Symbol.Index,
12771290) !void {
......@@ -1285,7 +1298,7 @@ fn updateLazySymbol(
12851298 const name_str_index = blk: {
12861299 const name = try std.fmt.allocPrint(gpa, "__lazy_{s}_{}", .{
12871300 @tagName(lazy_sym.kind),
1288 lazy_sym.ty.fmt(mod),
1301 lazy_sym.ty.fmt(pt),
12891302 });
12901303 defer gpa.free(name);
12911304 break :blk try self.strtab.insert(gpa, name);
......@@ -1294,6 +1307,7 @@ fn updateLazySymbol(
12941307 const src = lazy_sym.ty.srcLocOrNull(mod) orelse Module.LazySrcLoc.unneeded;
12951308 const res = try codegen.generateLazySymbol(
12961309 &macho_file.base,
1310 pt,
12971311 src,
12981312 lazy_sym,
12991313 &required_alignment,
......@@ -1348,9 +1362,9 @@ fn updateLazySymbol(
13481362}
13491363
13501364/// Must be called only after a successful call to `updateDecl`.
1351pub fn updateDeclLineNumber(self: *ZigObject, mod: *Module, decl_index: InternPool.DeclIndex) !void {
1365pub fn updateDeclLineNumber(self: *ZigObject, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !void {
13521366 if (self.dwarf) |*dw| {
1353 try dw.updateDeclLineNumber(mod, decl_index);
1367 try dw.updateDeclLineNumber(pt.zcu, decl_index);
13541368 }
13551369}
13561370
......@@ -1431,10 +1445,11 @@ pub fn getOrCreateMetadataForDecl(
14311445pub fn getOrCreateMetadataForLazySymbol(
14321446 self: *ZigObject,
14331447 macho_file: *MachO,
1448 pt: Zcu.PerThread,
14341449 lazy_sym: link.File.LazySymbol,
14351450) !Symbol.Index {
1436 const gpa = macho_file.base.comp.gpa;
1437 const mod = macho_file.base.comp.module.?;
1451 const mod = pt.zcu;
1452 const gpa = mod.gpa;
14381453 const gop = try self.lazy_syms.getOrPut(gpa, lazy_sym.getDecl(mod));
14391454 errdefer _ = if (!gop.found_existing) self.lazy_syms.pop();
14401455 if (!gop.found_existing) gop.value_ptr.* = .{};
......@@ -1464,7 +1479,7 @@ pub fn getOrCreateMetadataForLazySymbol(
14641479 metadata.state.* = .pending_flush;
14651480 const symbol_index = metadata.symbol_index.*;
14661481 // anyerror needs to be deferred until flushModule
1467 if (lazy_sym.getDecl(mod) != .none) try self.updateLazySymbol(macho_file, lazy_sym, symbol_index);
1482 if (lazy_sym.getDecl(mod) != .none) try self.updateLazySymbol(macho_file, pt, lazy_sym, symbol_index);
14681483 return symbol_index;
14691484}
14701485
src/link/NvPtx.zig+11-12
......@@ -13,8 +13,6 @@ const assert = std.debug.assert;
1313const log = std.log.scoped(.link);
1414
1515const Zcu = @import("../Zcu.zig");
16/// Deprecated.
17const Module = Zcu;
1816const InternPool = @import("../InternPool.zig");
1917const Compilation = @import("../Compilation.zig");
2018const link = @import("../link.zig");
......@@ -84,35 +82,35 @@ pub fn deinit(self: *NvPtx) void {
8482 self.llvm_object.deinit();
8583}
8684
87pub fn updateFunc(self: *NvPtx, module: *Module, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
88 try self.llvm_object.updateFunc(module, func_index, air, liveness);
85pub fn updateFunc(self: *NvPtx, pt: Zcu.PerThread, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
86 try self.llvm_object.updateFunc(pt, func_index, air, liveness);
8987}
9088
91pub fn updateDecl(self: *NvPtx, module: *Module, decl_index: InternPool.DeclIndex) !void {
92 return self.llvm_object.updateDecl(module, decl_index);
89pub fn updateDecl(self: *NvPtx, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !void {
90 return self.llvm_object.updateDecl(pt, decl_index);
9391}
9492
9593pub fn updateExports(
9694 self: *NvPtx,
97 module: *Module,
98 exported: Module.Exported,
95 pt: Zcu.PerThread,
96 exported: Zcu.Exported,
9997 export_indices: []const u32,
10098) !void {
10199 if (build_options.skip_non_native and builtin.object_format != .nvptx)
102100 @panic("Attempted to compile for object format that was disabled by build configuration");
103101
104 return self.llvm_object.updateExports(module, exported, export_indices);
102 return self.llvm_object.updateExports(pt, exported, export_indices);
105103}
106104
107105pub fn freeDecl(self: *NvPtx, decl_index: InternPool.DeclIndex) void {
108106 return self.llvm_object.freeDecl(decl_index);
109107}
110108
111pub fn flush(self: *NvPtx, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
112 return self.flushModule(arena, prog_node);
109pub fn flush(self: *NvPtx, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
110 return self.flushModule(arena, tid, prog_node);
113111}
114112
115pub fn flushModule(self: *NvPtx, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
113pub fn flushModule(self: *NvPtx, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
116114 if (build_options.skip_non_native)
117115 @panic("Attempted to compile for architecture that was disabled by build configuration");
118116
......@@ -121,5 +119,6 @@ pub fn flushModule(self: *NvPtx, arena: Allocator, prog_node: std.Progress.Node)
121119 _ = arena;
122120 _ = self;
123121 _ = prog_node;
122 _ = tid;
124123 @panic("TODO: rewrite the NvPtx.flushModule function");
125124}
src/link/Plan9.zig+53-46
......@@ -4,8 +4,6 @@
44const Plan9 = @This();
55const link = @import("../link.zig");
66const Zcu = @import("../Zcu.zig");
7/// Deprecated.
8const Module = Zcu;
97const InternPool = @import("../InternPool.zig");
108const Compilation = @import("../Compilation.zig");
119const aout = @import("Plan9/aout.zig");
......@@ -56,7 +54,7 @@ path_arena: std.heap.ArenaAllocator,
5654/// of the function to know what file it came from.
5755/// If we group the decls by file, it makes it really easy to do this (put the symbol in the correct place)
5856fn_decl_table: std.AutoArrayHashMapUnmanaged(
59 *Module.File,
57 *Zcu.File,
6058 struct { sym_index: u32, functions: std.AutoArrayHashMapUnmanaged(InternPool.DeclIndex, FnDeclOutput) = .{} },
6159) = .{},
6260/// the code is modified when relocated, so that is why it is mutable
......@@ -411,12 +409,13 @@ fn addPathComponents(self: *Plan9, path: []const u8, a: *std.ArrayList(u8)) !voi
411409 }
412410}
413411
414pub fn updateFunc(self: *Plan9, mod: *Module, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
412pub fn updateFunc(self: *Plan9, pt: Zcu.PerThread, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
415413 if (build_options.skip_non_native and builtin.object_format != .plan9) {
416414 @panic("Attempted to compile for object format that was disabled by build configuration");
417415 }
418416
419 const gpa = self.base.comp.gpa;
417 const mod = pt.zcu;
418 const gpa = mod.gpa;
420419 const target = self.base.comp.root_mod.resolved_target.result;
421420 const func = mod.funcInfo(func_index);
422421 const decl_index = func.owner_decl;
......@@ -439,6 +438,7 @@ pub fn updateFunc(self: *Plan9, mod: *Module, func_index: InternPool.Index, air:
439438
440439 const res = try codegen.generateFunction(
441440 &self.base,
441 pt,
442442 decl.navSrcLoc(mod),
443443 func_index,
444444 air,
......@@ -468,13 +468,13 @@ pub fn updateFunc(self: *Plan9, mod: *Module, func_index: InternPool.Index, air:
468468 return self.updateFinish(decl_index);
469469}
470470
471pub fn lowerUnnamedConst(self: *Plan9, val: Value, decl_index: InternPool.DeclIndex) !u32 {
472 const gpa = self.base.comp.gpa;
471pub fn lowerUnnamedConst(self: *Plan9, pt: Zcu.PerThread, val: Value, decl_index: InternPool.DeclIndex) !u32 {
472 const mod = pt.zcu;
473 const gpa = mod.gpa;
473474 _ = try self.seeDecl(decl_index);
474475 var code_buffer = std.ArrayList(u8).init(gpa);
475476 defer code_buffer.deinit();
476477
477 const mod = self.base.comp.module.?;
478478 const decl = mod.declPtr(decl_index);
479479
480480 const gop = try self.unnamed_const_atoms.getOrPut(gpa, decl_index);
......@@ -483,7 +483,7 @@ pub fn lowerUnnamedConst(self: *Plan9, val: Value, decl_index: InternPool.DeclIn
483483 }
484484 const unnamed_consts = gop.value_ptr;
485485
486 const decl_name = try decl.fullyQualifiedName(mod);
486 const decl_name = try decl.fullyQualifiedName(pt);
487487
488488 const index = unnamed_consts.items.len;
489489 // name is freed when the unnamed const is freed
......@@ -505,7 +505,7 @@ pub fn lowerUnnamedConst(self: *Plan9, val: Value, decl_index: InternPool.DeclIn
505505 };
506506 self.syms.items[info.sym_index.?] = sym;
507507
508 const res = try codegen.generateSymbol(&self.base, decl.navSrcLoc(mod), val, &code_buffer, .{
508 const res = try codegen.generateSymbol(&self.base, pt, decl.navSrcLoc(mod), val, &code_buffer, .{
509509 .none = {},
510510 }, .{
511511 .parent_atom_index = new_atom_idx,
......@@ -530,8 +530,9 @@ pub fn lowerUnnamedConst(self: *Plan9, val: Value, decl_index: InternPool.DeclIn
530530 return new_atom_idx;
531531}
532532
533pub fn updateDecl(self: *Plan9, mod: *Module, decl_index: InternPool.DeclIndex) !void {
533pub fn updateDecl(self: *Plan9, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !void {
534534 const gpa = self.base.comp.gpa;
535 const mod = pt.zcu;
535536 const decl = mod.declPtr(decl_index);
536537
537538 if (decl.isExtern(mod)) {
......@@ -544,7 +545,7 @@ pub fn updateDecl(self: *Plan9, mod: *Module, decl_index: InternPool.DeclIndex)
544545 defer code_buffer.deinit();
545546 const decl_val = if (decl.val.getVariable(mod)) |variable| Value.fromInterned(variable.init) else decl.val;
546547 // TODO we need the symbol index for symbol in the table of locals for the containing atom
547 const res = try codegen.generateSymbol(&self.base, decl.navSrcLoc(mod), decl_val, &code_buffer, .{ .none = {} }, .{
548 const res = try codegen.generateSymbol(&self.base, pt, decl.navSrcLoc(mod), decl_val, &code_buffer, .{ .none = {} }, .{
548549 .parent_atom_index = @as(Atom.Index, @intCast(atom_idx)),
549550 });
550551 const code = switch (res) {
......@@ -610,7 +611,7 @@ fn allocateGotIndex(self: *Plan9) usize {
610611 }
611612}
612613
613pub fn flush(self: *Plan9, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
614pub fn flush(self: *Plan9, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
614615 const comp = self.base.comp;
615616 const use_lld = build_options.have_llvm and comp.config.use_lld;
616617 assert(!use_lld);
......@@ -621,7 +622,7 @@ pub fn flush(self: *Plan9, arena: Allocator, prog_node: std.Progress.Node) link.
621622 .Obj => return error.TODOImplementPlan9Objs,
622623 .Lib => return error.TODOImplementWritingLibFiles,
623624 }
624 return self.flushModule(arena, prog_node);
625 return self.flushModule(arena, tid, prog_node);
625626}
626627
627628pub fn changeLine(l: *std.ArrayList(u8), delta_line: i32) !void {
......@@ -669,20 +670,20 @@ fn atomCount(self: *Plan9) usize {
669670 return data_decl_count + fn_decl_count + unnamed_const_count + lazy_atom_count + extern_atom_count + anon_atom_count;
670671}
671672
672pub fn flushModule(self: *Plan9, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
673pub fn flushModule(self: *Plan9, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
673674 if (build_options.skip_non_native and builtin.object_format != .plan9) {
674675 @panic("Attempted to compile for object format that was disabled by build configuration");
675676 }
676677
678 const tracy = trace(@src());
679 defer tracy.end();
680
677681 _ = arena; // Has the same lifetime as the call to Compilation.update.
678682
679683 const comp = self.base.comp;
680684 const gpa = comp.gpa;
681685 const target = comp.root_mod.resolved_target.result;
682686
683 const tracy = trace(@src());
684 defer tracy.end();
685
686687 const sub_prog_node = prog_node.start("Flush Module", 0);
687688 defer sub_prog_node.end();
688689
......@@ -690,21 +691,26 @@ pub fn flushModule(self: *Plan9, arena: Allocator, prog_node: std.Progress.Node)
690691
691692 defer assert(self.hdr.entry != 0x0);
692693
693 const mod = self.base.comp.module orelse return error.LinkingWithoutZigSourceUnimplemented;
694 const pt: Zcu.PerThread = .{
695 .zcu = self.base.comp.module orelse return error.LinkingWithoutZigSourceUnimplemented,
696 .tid = tid,
697 };
694698
695699 // finish up the lazy syms
696700 if (self.lazy_syms.getPtr(.none)) |metadata| {
697701 // Most lazy symbols can be updated on first use, but
698702 // anyerror needs to wait for everything to be flushed.
699703 if (metadata.text_state != .unused) self.updateLazySymbolAtom(
700 File.LazySymbol.initDecl(.code, null, mod),
704 pt,
705 File.LazySymbol.initDecl(.code, null, pt.zcu),
701706 metadata.text_atom,
702707 ) catch |err| return switch (err) {
703708 error.CodegenFail => error.FlushFailure,
704709 else => |e| e,
705710 };
706711 if (metadata.rodata_state != .unused) self.updateLazySymbolAtom(
707 File.LazySymbol.initDecl(.const_data, null, mod),
712 pt,
713 File.LazySymbol.initDecl(.const_data, null, pt.zcu),
708714 metadata.rodata_atom,
709715 ) catch |err| return switch (err) {
710716 error.CodegenFail => error.FlushFailure,
......@@ -747,7 +753,7 @@ pub fn flushModule(self: *Plan9, arena: Allocator, prog_node: std.Progress.Node)
747753 var it = fentry.value_ptr.functions.iterator();
748754 while (it.next()) |entry| {
749755 const decl_index = entry.key_ptr.*;
750 const decl = mod.declPtr(decl_index);
756 const decl = pt.zcu.declPtr(decl_index);
751757 const atom = self.getAtomPtr(self.decls.get(decl_index).?.index);
752758 const out = entry.value_ptr.*;
753759 {
......@@ -767,7 +773,7 @@ pub fn flushModule(self: *Plan9, arena: Allocator, prog_node: std.Progress.Node)
767773 const off = self.getAddr(text_i, .t);
768774 text_i += out.code.len;
769775 atom.offset = off;
770 log.debug("write text decl {*} ({}), lines {d} to {d}.;__GOT+0x{x} vaddr: 0x{x}", .{ decl, decl.name.fmt(&mod.intern_pool), out.start_line + 1, out.end_line, atom.got_index.? * 8, off });
776 log.debug("write text decl {*} ({}), lines {d} to {d}.;__GOT+0x{x} vaddr: 0x{x}", .{ decl, decl.name.fmt(&pt.zcu.intern_pool), out.start_line + 1, out.end_line, atom.got_index.? * 8, off });
771777 if (!self.sixtyfour_bit) {
772778 mem.writeInt(u32, got_table[atom.got_index.? * 4 ..][0..4], @as(u32, @intCast(off)), target.cpu.arch.endian());
773779 } else {
......@@ -775,7 +781,7 @@ pub fn flushModule(self: *Plan9, arena: Allocator, prog_node: std.Progress.Node)
775781 }
776782 self.syms.items[atom.sym_index.?].value = off;
777783 if (self.decl_exports.get(decl_index)) |export_indices| {
778 try self.addDeclExports(mod, decl_index, export_indices);
784 try self.addDeclExports(pt.zcu, decl_index, export_indices);
779785 }
780786 }
781787 }
......@@ -841,7 +847,7 @@ pub fn flushModule(self: *Plan9, arena: Allocator, prog_node: std.Progress.Node)
841847 }
842848 self.syms.items[atom.sym_index.?].value = off;
843849 if (self.decl_exports.get(decl_index)) |export_indices| {
844 try self.addDeclExports(mod, decl_index, export_indices);
850 try self.addDeclExports(pt.zcu, decl_index, export_indices);
845851 }
846852 }
847853 // write the unnamed constants after the other data decls
......@@ -1009,7 +1015,7 @@ pub fn flushModule(self: *Plan9, arena: Allocator, prog_node: std.Progress.Node)
10091015}
10101016fn addDeclExports(
10111017 self: *Plan9,
1012 mod: *Module,
1018 mod: *Zcu,
10131019 decl_index: InternPool.DeclIndex,
10141020 export_indices: []const u32,
10151021) !void {
......@@ -1025,7 +1031,7 @@ fn addDeclExports(
10251031 if (!section_name.eqlSlice(".text", &mod.intern_pool) and
10261032 !section_name.eqlSlice(".data", &mod.intern_pool))
10271033 {
1028 try mod.failed_exports.put(mod.gpa, export_idx, try Module.ErrorMsg.create(
1034 try mod.failed_exports.put(mod.gpa, export_idx, try Zcu.ErrorMsg.create(
10291035 gpa,
10301036 mod.declPtr(decl_index).navSrcLoc(mod),
10311037 "plan9 does not support extra sections",
......@@ -1155,8 +1161,8 @@ pub fn seeDecl(self: *Plan9, decl_index: InternPool.DeclIndex) !Atom.Index {
11551161
11561162pub fn updateExports(
11571163 self: *Plan9,
1158 module: *Module,
1159 exported: Module.Exported,
1164 pt: Zcu.PerThread,
1165 exported: Zcu.Exported,
11601166 export_indices: []const u32,
11611167) !void {
11621168 const gpa = self.base.comp.gpa;
......@@ -1173,11 +1179,11 @@ pub fn updateExports(
11731179 },
11741180 }
11751181 // all proper work is done in flush
1176 _ = module;
1182 _ = pt;
11771183}
11781184
1179pub fn getOrCreateAtomForLazySymbol(self: *Plan9, sym: File.LazySymbol) !Atom.Index {
1180 const gpa = self.base.comp.gpa;
1185pub fn getOrCreateAtomForLazySymbol(self: *Plan9, pt: Zcu.PerThread, sym: File.LazySymbol) !Atom.Index {
1186 const gpa = pt.zcu.gpa;
11811187 const gop = try self.lazy_syms.getOrPut(gpa, sym.getDecl(self.base.comp.module.?));
11821188 errdefer _ = if (!gop.found_existing) self.lazy_syms.pop();
11831189
......@@ -1198,14 +1204,13 @@ pub fn getOrCreateAtomForLazySymbol(self: *Plan9, sym: File.LazySymbol) !Atom.In
11981204 _ = self.getAtomPtr(atom).getOrCreateOffsetTableEntry(self);
11991205 // anyerror needs to be deferred until flushModule
12001206 if (sym.getDecl(self.base.comp.module.?) != .none) {
1201 try self.updateLazySymbolAtom(sym, atom);
1207 try self.updateLazySymbolAtom(pt, sym, atom);
12021208 }
12031209 return atom;
12041210}
12051211
1206fn updateLazySymbolAtom(self: *Plan9, sym: File.LazySymbol, atom_index: Atom.Index) !void {
1207 const gpa = self.base.comp.gpa;
1208 const mod = self.base.comp.module.?;
1212fn updateLazySymbolAtom(self: *Plan9, pt: Zcu.PerThread, sym: File.LazySymbol, atom_index: Atom.Index) !void {
1213 const gpa = pt.zcu.gpa;
12091214
12101215 var required_alignment: InternPool.Alignment = .none;
12111216 var code_buffer = std.ArrayList(u8).init(gpa);
......@@ -1214,7 +1219,7 @@ fn updateLazySymbolAtom(self: *Plan9, sym: File.LazySymbol, atom_index: Atom.Ind
12141219 // create the symbol for the name
12151220 const name = try std.fmt.allocPrint(gpa, "__lazy_{s}_{}", .{
12161221 @tagName(sym.kind),
1217 sym.ty.fmt(mod),
1222 sym.ty.fmt(pt),
12181223 });
12191224
12201225 const symbol: aout.Sym = .{
......@@ -1225,9 +1230,10 @@ fn updateLazySymbolAtom(self: *Plan9, sym: File.LazySymbol, atom_index: Atom.Ind
12251230 self.syms.items[self.getAtomPtr(atom_index).sym_index.?] = symbol;
12261231
12271232 // generate the code
1228 const src = sym.ty.srcLocOrNull(mod) orelse Module.LazySrcLoc.unneeded;
1233 const src = sym.ty.srcLocOrNull(pt.zcu) orelse Zcu.LazySrcLoc.unneeded;
12291234 const res = try codegen.generateLazySymbol(
12301235 &self.base,
1236 pt,
12311237 src,
12321238 sym,
12331239 &required_alignment,
......@@ -1490,22 +1496,22 @@ pub fn writeSyms(self: *Plan9, buf: *std.ArrayList(u8)) !void {
14901496}
14911497
14921498/// Must be called only after a successful call to `updateDecl`.
1493pub fn updateDeclLineNumber(self: *Plan9, mod: *Module, decl_index: InternPool.DeclIndex) !void {
1499pub fn updateDeclLineNumber(self: *Plan9, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !void {
14941500 _ = self;
1495 _ = mod;
1501 _ = pt;
14961502 _ = decl_index;
14971503}
14981504
14991505pub fn getDeclVAddr(
15001506 self: *Plan9,
1507 pt: Zcu.PerThread,
15011508 decl_index: InternPool.DeclIndex,
15021509 reloc_info: link.File.RelocInfo,
15031510) !u64 {
1504 const mod = self.base.comp.module.?;
1505 const ip = &mod.intern_pool;
1506 const decl = mod.declPtr(decl_index);
1511 const ip = &pt.zcu.intern_pool;
1512 const decl = pt.zcu.declPtr(decl_index);
15071513 log.debug("getDeclVAddr for {}", .{decl.name.fmt(ip)});
1508 if (decl.isExtern(mod)) {
1514 if (decl.isExtern(pt.zcu)) {
15091515 if (decl.name.eqlSlice("etext", ip)) {
15101516 try self.addReloc(reloc_info.parent_atom_index, .{
15111517 .target = undefined,
......@@ -1544,9 +1550,10 @@ pub fn getDeclVAddr(
15441550
15451551pub fn lowerAnonDecl(
15461552 self: *Plan9,
1553 pt: Zcu.PerThread,
15471554 decl_val: InternPool.Index,
15481555 explicit_alignment: InternPool.Alignment,
1549 src_loc: Module.LazySrcLoc,
1556 src_loc: Zcu.LazySrcLoc,
15501557) !codegen.Result {
15511558 _ = explicit_alignment;
15521559 // This is basically the same as lowerUnnamedConst.
......@@ -1569,7 +1576,7 @@ pub fn lowerAnonDecl(
15691576 gop.value_ptr.* = index;
15701577 // we need to free name latex
15711578 var code_buffer = std.ArrayList(u8).init(gpa);
1572 const res = try codegen.generateSymbol(&self.base, src_loc, val, &code_buffer, .{ .none = {} }, .{ .parent_atom_index = index });
1579 const res = try codegen.generateSymbol(&self.base, pt, src_loc, val, &code_buffer, .{ .none = {} }, .{ .parent_atom_index = index });
15731580 const code = switch (res) {
15741581 .ok => code_buffer.items,
15751582 .fail => |em| return .{ .fail = em },
src/link/SpirV.zig+16-16
......@@ -28,8 +28,6 @@ const assert = std.debug.assert;
2828const log = std.log.scoped(.link);
2929
3030const Zcu = @import("../Zcu.zig");
31/// Deprecated.
32const Module = Zcu;
3331const InternPool = @import("../InternPool.zig");
3432const Compilation = @import("../Compilation.zig");
3533const link = @import("../link.zig");
......@@ -125,35 +123,36 @@ pub fn deinit(self: *SpirV) void {
125123 self.object.deinit();
126124}
127125
128pub fn updateFunc(self: *SpirV, module: *Module, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
126pub fn updateFunc(self: *SpirV, pt: Zcu.PerThread, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
129127 if (build_options.skip_non_native) {
130128 @panic("Attempted to compile for architecture that was disabled by build configuration");
131129 }
132130
133 const func = module.funcInfo(func_index);
134 const decl = module.declPtr(func.owner_decl);
135 log.debug("lowering function {}", .{decl.name.fmt(&module.intern_pool)});
131 const func = pt.zcu.funcInfo(func_index);
132 const decl = pt.zcu.declPtr(func.owner_decl);
133 log.debug("lowering function {}", .{decl.name.fmt(&pt.zcu.intern_pool)});
136134
137 try self.object.updateFunc(module, func_index, air, liveness);
135 try self.object.updateFunc(pt, func_index, air, liveness);
138136}
139137
140pub fn updateDecl(self: *SpirV, module: *Module, decl_index: InternPool.DeclIndex) !void {
138pub fn updateDecl(self: *SpirV, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !void {
141139 if (build_options.skip_non_native) {
142140 @panic("Attempted to compile for architecture that was disabled by build configuration");
143141 }
144142
145 const decl = module.declPtr(decl_index);
146 log.debug("lowering declaration {}", .{decl.name.fmt(&module.intern_pool)});
143 const decl = pt.zcu.declPtr(decl_index);
144 log.debug("lowering declaration {}", .{decl.name.fmt(&pt.zcu.intern_pool)});
147145
148 try self.object.updateDecl(module, decl_index);
146 try self.object.updateDecl(pt, decl_index);
149147}
150148
151149pub fn updateExports(
152150 self: *SpirV,
153 mod: *Module,
154 exported: Module.Exported,
151 pt: Zcu.PerThread,
152 exported: Zcu.Exported,
155153 export_indices: []const u32,
156154) !void {
155 const mod = pt.zcu;
157156 const decl_index = switch (exported) {
158157 .decl_index => |i| i,
159158 .value => |val| {
......@@ -196,11 +195,11 @@ pub fn freeDecl(self: *SpirV, decl_index: InternPool.DeclIndex) void {
196195 _ = decl_index;
197196}
198197
199pub fn flush(self: *SpirV, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
200 return self.flushModule(arena, prog_node);
198pub fn flush(self: *SpirV, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
199 return self.flushModule(arena, tid, prog_node);
201200}
202201
203pub fn flushModule(self: *SpirV, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
202pub fn flushModule(self: *SpirV, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
204203 if (build_options.skip_non_native) {
205204 @panic("Attempted to compile for architecture that was disabled by build configuration");
206205 }
......@@ -216,6 +215,7 @@ pub fn flushModule(self: *SpirV, arena: Allocator, prog_node: std.Progress.Node)
216215 const comp = self.base.comp;
217216 const gpa = comp.gpa;
218217 const target = comp.getTarget();
218 _ = tid;
219219
220220 try writeCapabilities(spv, target);
221221 try writeMemoryModel(spv, target);
src/link/Wasm.zig+30-30
......@@ -29,8 +29,6 @@ const InternPool = @import("../InternPool.zig");
2929const Liveness = @import("../Liveness.zig");
3030const LlvmObject = @import("../codegen/llvm.zig").Object;
3131const Zcu = @import("../Zcu.zig");
32/// Deprecated.
33const Module = Zcu;
3432const Object = @import("Wasm/Object.zig");
3533const Symbol = @import("Wasm/Symbol.zig");
3634const Type = @import("../Type.zig");
......@@ -1441,27 +1439,27 @@ pub fn deinit(wasm: *Wasm) void {
14411439 wasm.files.deinit(gpa);
14421440}
14431441
1444pub fn updateFunc(wasm: *Wasm, mod: *Module, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
1442pub fn updateFunc(wasm: *Wasm, pt: Zcu.PerThread, func_index: InternPool.Index, air: Air, liveness: Liveness) !void {
14451443 if (build_options.skip_non_native and builtin.object_format != .wasm) {
14461444 @panic("Attempted to compile for object format that was disabled by build configuration");
14471445 }
1448 if (wasm.llvm_object) |llvm_object| return llvm_object.updateFunc(mod, func_index, air, liveness);
1449 try wasm.zigObjectPtr().?.updateFunc(wasm, mod, func_index, air, liveness);
1446 if (wasm.llvm_object) |llvm_object| return llvm_object.updateFunc(pt, func_index, air, liveness);
1447 try wasm.zigObjectPtr().?.updateFunc(wasm, pt, func_index, air, liveness);
14501448}
14511449
14521450// Generate code for the Decl, storing it in memory to be later written to
14531451// the file on flush().
1454pub fn updateDecl(wasm: *Wasm, mod: *Module, decl_index: InternPool.DeclIndex) !void {
1452pub fn updateDecl(wasm: *Wasm, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !void {
14551453 if (build_options.skip_non_native and builtin.object_format != .wasm) {
14561454 @panic("Attempted to compile for object format that was disabled by build configuration");
14571455 }
1458 if (wasm.llvm_object) |llvm_object| return llvm_object.updateDecl(mod, decl_index);
1459 try wasm.zigObjectPtr().?.updateDecl(wasm, mod, decl_index);
1456 if (wasm.llvm_object) |llvm_object| return llvm_object.updateDecl(pt, decl_index);
1457 try wasm.zigObjectPtr().?.updateDecl(wasm, pt, decl_index);
14601458}
14611459
1462pub fn updateDeclLineNumber(wasm: *Wasm, mod: *Module, decl_index: InternPool.DeclIndex) !void {
1460pub fn updateDeclLineNumber(wasm: *Wasm, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !void {
14631461 if (wasm.llvm_object) |_| return;
1464 try wasm.zigObjectPtr().?.updateDeclLineNumber(mod, decl_index);
1462 try wasm.zigObjectPtr().?.updateDeclLineNumber(pt, decl_index);
14651463}
14661464
14671465/// From a given symbol location, returns its `wasm.GlobalType`.
......@@ -1506,8 +1504,8 @@ fn getFunctionSignature(wasm: *const Wasm, loc: SymbolLoc) std.wasm.Type {
15061504/// Lowers a constant typed value to a local symbol and atom.
15071505/// Returns the symbol index of the local
15081506/// The given `decl` is the parent decl whom owns the constant.
1509pub fn lowerUnnamedConst(wasm: *Wasm, val: Value, decl_index: InternPool.DeclIndex) !u32 {
1510 return wasm.zigObjectPtr().?.lowerUnnamedConst(wasm, val, decl_index);
1507pub fn lowerUnnamedConst(wasm: *Wasm, pt: Zcu.PerThread, val: Value, decl_index: InternPool.DeclIndex) !u32 {
1508 return wasm.zigObjectPtr().?.lowerUnnamedConst(wasm, pt, val, decl_index);
15111509}
15121510
15131511/// Returns the symbol index from a symbol of which its flag is set global,
......@@ -1523,19 +1521,21 @@ pub fn getGlobalSymbol(wasm: *Wasm, name: []const u8, lib_name: ?[]const u8) !Sy
15231521/// Returns the given pointer address
15241522pub fn getDeclVAddr(
15251523 wasm: *Wasm,
1524 pt: Zcu.PerThread,
15261525 decl_index: InternPool.DeclIndex,
15271526 reloc_info: link.File.RelocInfo,
15281527) !u64 {
1529 return wasm.zigObjectPtr().?.getDeclVAddr(wasm, decl_index, reloc_info);
1528 return wasm.zigObjectPtr().?.getDeclVAddr(wasm, pt, decl_index, reloc_info);
15301529}
15311530
15321531pub fn lowerAnonDecl(
15331532 wasm: *Wasm,
1533 pt: Zcu.PerThread,
15341534 decl_val: InternPool.Index,
15351535 explicit_alignment: Alignment,
1536 src_loc: Module.LazySrcLoc,
1536 src_loc: Zcu.LazySrcLoc,
15371537) !codegen.Result {
1538 return wasm.zigObjectPtr().?.lowerAnonDecl(wasm, decl_val, explicit_alignment, src_loc);
1538 return wasm.zigObjectPtr().?.lowerAnonDecl(wasm, pt, decl_val, explicit_alignment, src_loc);
15391539}
15401540
15411541pub fn getAnonDeclVAddr(wasm: *Wasm, decl_val: InternPool.Index, reloc_info: link.File.RelocInfo) !u64 {
......@@ -1553,15 +1553,15 @@ pub fn deleteExport(
15531553
15541554pub fn updateExports(
15551555 wasm: *Wasm,
1556 mod: *Module,
1557 exported: Module.Exported,
1556 pt: Zcu.PerThread,
1557 exported: Zcu.Exported,
15581558 export_indices: []const u32,
15591559) !void {
15601560 if (build_options.skip_non_native and builtin.object_format != .wasm) {
15611561 @panic("Attempted to compile for object format that was disabled by build configuration");
15621562 }
1563 if (wasm.llvm_object) |llvm_object| return llvm_object.updateExports(mod, exported, export_indices);
1564 return wasm.zigObjectPtr().?.updateExports(wasm, mod, exported, export_indices);
1563 if (wasm.llvm_object) |llvm_object| return llvm_object.updateExports(pt, exported, export_indices);
1564 return wasm.zigObjectPtr().?.updateExports(wasm, pt, exported, export_indices);
15651565}
15661566
15671567pub fn freeDecl(wasm: *Wasm, decl_index: InternPool.DeclIndex) void {
......@@ -2466,18 +2466,18 @@ fn appendDummySegment(wasm: *Wasm) !void {
24662466 });
24672467}
24682468
2469pub fn flush(wasm: *Wasm, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
2469pub fn flush(wasm: *Wasm, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
24702470 const comp = wasm.base.comp;
24712471 const use_lld = build_options.have_llvm and comp.config.use_lld;
24722472
24732473 if (use_lld) {
2474 return wasm.linkWithLLD(arena, prog_node);
2474 return wasm.linkWithLLD(arena, tid, prog_node);
24752475 }
2476 return wasm.flushModule(arena, prog_node);
2476 return wasm.flushModule(arena, tid, prog_node);
24772477}
24782478
24792479/// Uses the in-house linker to link one or multiple object -and archive files into a WebAssembly binary.
2480pub fn flushModule(wasm: *Wasm, arena: Allocator, prog_node: std.Progress.Node) link.File.FlushError!void {
2480pub fn flushModule(wasm: *Wasm, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) link.File.FlushError!void {
24812481 const tracy = trace(@src());
24822482 defer tracy.end();
24832483
......@@ -2513,7 +2513,7 @@ pub fn flushModule(wasm: *Wasm, arena: Allocator, prog_node: std.Progress.Node)
25132513 const wasi_exec_model = comp.config.wasi_exec_model;
25142514
25152515 if (wasm.zigObjectPtr()) |zig_object| {
2516 try zig_object.flushModule(wasm);
2516 try zig_object.flushModule(wasm, tid);
25172517 }
25182518
25192519 // When the target os is WASI, we allow linking with WASI-LIBC
......@@ -3324,7 +3324,7 @@ fn emitImport(wasm: *Wasm, writer: anytype, import: types.Import) !void {
33243324 }
33253325}
33263326
3327fn linkWithLLD(wasm: *Wasm, arena: Allocator, prog_node: std.Progress.Node) !void {
3327fn linkWithLLD(wasm: *Wasm, arena: Allocator, tid: Zcu.PerThread.Id, prog_node: std.Progress.Node) !void {
33283328 const tracy = trace(@src());
33293329 defer tracy.end();
33303330
......@@ -3342,7 +3342,7 @@ fn linkWithLLD(wasm: *Wasm, arena: Allocator, prog_node: std.Progress.Node) !voi
33423342 // If there is no Zig code to compile, then we should skip flushing the output file because it
33433343 // will not be part of the linker line anyway.
33443344 const module_obj_path: ?[]const u8 = if (comp.module != null) blk: {
3345 try wasm.flushModule(arena, prog_node);
3345 try wasm.flushModule(arena, tid, prog_node);
33463346
33473347 if (fs.path.dirname(full_out_path)) |dirname| {
33483348 break :blk try fs.path.join(arena, &.{ dirname, wasm.base.zcu_object_sub_path.? });
......@@ -4009,16 +4009,16 @@ pub fn storeDeclType(wasm: *Wasm, decl_index: InternPool.DeclIndex, func_type: s
40094009/// Returns the symbol index of the error name table.
40104010///
40114011/// When the symbol does not yet exist, it will create a new one instead.
4012pub fn getErrorTableSymbol(wasm_file: *Wasm) !u32 {
4013 const sym_index = try wasm_file.zigObjectPtr().?.getErrorTableSymbol(wasm_file);
4012pub fn getErrorTableSymbol(wasm_file: *Wasm, pt: Zcu.PerThread) !u32 {
4013 const sym_index = try wasm_file.zigObjectPtr().?.getErrorTableSymbol(wasm_file, pt);
40144014 return @intFromEnum(sym_index);
40154015}
40164016
40174017/// For a given `InternPool.DeclIndex` returns its corresponding `Atom.Index`.
40184018/// When the index was not found, a new `Atom` will be created, and its index will be returned.
40194019/// The newly created Atom is empty with default fields as specified by `Atom.empty`.
4020pub fn getOrCreateAtomForDecl(wasm_file: *Wasm, decl_index: InternPool.DeclIndex) !Atom.Index {
4021 return wasm_file.zigObjectPtr().?.getOrCreateAtomForDecl(wasm_file, decl_index);
4020pub fn getOrCreateAtomForDecl(wasm_file: *Wasm, pt: Zcu.PerThread, decl_index: InternPool.DeclIndex) !Atom.Index {
4021 return wasm_file.zigObjectPtr().?.getOrCreateAtomForDecl(wasm_file, pt, decl_index);
40224022}
40234023
40244024/// Verifies all resolved symbols and checks whether itself needs to be marked alive,
src/link/Wasm/ZigObject.zig+88-62
......@@ -241,9 +241,10 @@ pub fn allocateSymbol(zig_object: *ZigObject, gpa: std.mem.Allocator) !Symbol.In
241241pub fn updateDecl(
242242 zig_object: *ZigObject,
243243 wasm_file: *Wasm,
244 mod: *Module,
244 pt: Zcu.PerThread,
245245 decl_index: InternPool.DeclIndex,
246246) !void {
247 const mod = pt.zcu;
247248 const decl = mod.declPtr(decl_index);
248249 if (decl.val.getFunction(mod)) |_| {
249250 return;
......@@ -252,7 +253,7 @@ pub fn updateDecl(
252253 }
253254
254255 const gpa = wasm_file.base.comp.gpa;
255 const atom_index = try zig_object.getOrCreateAtomForDecl(wasm_file, decl_index);
256 const atom_index = try zig_object.getOrCreateAtomForDecl(wasm_file, pt, decl_index);
256257 const atom = wasm_file.getAtomPtr(atom_index);
257258 atom.clear();
258259
......@@ -269,6 +270,7 @@ pub fn updateDecl(
269270
270271 const res = try codegen.generateSymbol(
271272 &wasm_file.base,
273 pt,
272274 decl.navSrcLoc(mod),
273275 val,
274276 &code_writer,
......@@ -285,22 +287,22 @@ pub fn updateDecl(
285287 },
286288 };
287289
288 return zig_object.finishUpdateDecl(wasm_file, decl_index, code);
290 return zig_object.finishUpdateDecl(wasm_file, pt, decl_index, code);
289291}
290292
291293pub fn updateFunc(
292294 zig_object: *ZigObject,
293295 wasm_file: *Wasm,
294 mod: *Module,
296 pt: Zcu.PerThread,
295297 func_index: InternPool.Index,
296298 air: Air,
297299 liveness: Liveness,
298300) !void {
299301 const gpa = wasm_file.base.comp.gpa;
300 const func = mod.funcInfo(func_index);
302 const func = pt.zcu.funcInfo(func_index);
301303 const decl_index = func.owner_decl;
302 const decl = mod.declPtr(decl_index);
303 const atom_index = try zig_object.getOrCreateAtomForDecl(wasm_file, decl_index);
304 const decl = pt.zcu.declPtr(decl_index);
305 const atom_index = try zig_object.getOrCreateAtomForDecl(wasm_file, pt, decl_index);
304306 const atom = wasm_file.getAtomPtr(atom_index);
305307 atom.clear();
306308
......@@ -308,7 +310,8 @@ pub fn updateFunc(
308310 defer code_writer.deinit();
309311 const result = try codegen.generateFunction(
310312 &wasm_file.base,
311 decl.navSrcLoc(mod),
313 pt,
314 decl.navSrcLoc(pt.zcu),
312315 func_index,
313316 air,
314317 liveness,
......@@ -320,29 +323,31 @@ pub fn updateFunc(
320323 .ok => code_writer.items,
321324 .fail => |em| {
322325 decl.analysis = .codegen_failure;
323 try mod.failed_analysis.put(mod.gpa, AnalUnit.wrap(.{ .decl = decl_index }), em);
326 try pt.zcu.failed_analysis.put(gpa, AnalUnit.wrap(.{ .decl = decl_index }), em);
324327 return;
325328 },
326329 };
327330
328 return zig_object.finishUpdateDecl(wasm_file, decl_index, code);
331 return zig_object.finishUpdateDecl(wasm_file, pt, decl_index, code);
329332}
330333
331334fn finishUpdateDecl(
332335 zig_object: *ZigObject,
333336 wasm_file: *Wasm,
337 pt: Zcu.PerThread,
334338 decl_index: InternPool.DeclIndex,
335339 code: []const u8,
336340) !void {
337 const gpa = wasm_file.base.comp.gpa;
338 const zcu = wasm_file.base.comp.module.?;
341 const zcu = pt.zcu;
342 const ip = &zcu.intern_pool;
343 const gpa = zcu.gpa;
339344 const decl = zcu.declPtr(decl_index);
340345 const decl_info = zig_object.decls_map.get(decl_index).?;
341346 const atom_index = decl_info.atom;
342347 const atom = wasm_file.getAtomPtr(atom_index);
343348 const sym = zig_object.symbol(atom.sym_index);
344 const full_name = try decl.fullyQualifiedName(zcu);
345 sym.name = try zig_object.string_table.insert(gpa, full_name.toSlice(&zcu.intern_pool));
349 const full_name = try decl.fullyQualifiedName(pt);
350 sym.name = try zig_object.string_table.insert(gpa, full_name.toSlice(ip));
346351 try atom.code.appendSlice(gpa, code);
347352 atom.size = @intCast(code.len);
348353
......@@ -382,7 +387,7 @@ fn finishUpdateDecl(
382387 // Will be freed upon freeing of decl or after cleanup of Wasm binary.
383388 const full_segment_name = try std.mem.concat(gpa, u8, &.{
384389 segment_name,
385 full_name.toSlice(&zcu.intern_pool),
390 full_name.toSlice(ip),
386391 });
387392 errdefer gpa.free(full_segment_name);
388393 sym.tag = .data;
......@@ -390,7 +395,7 @@ fn finishUpdateDecl(
390395 },
391396 }
392397 if (code.len == 0) return;
393 atom.alignment = decl.getAlignment(zcu);
398 atom.alignment = decl.getAlignment(pt);
394399}
395400
396401/// Creates and initializes a new segment in the 'Data' section.
......@@ -419,17 +424,21 @@ fn createDataSegment(
419424/// For a given `InternPool.DeclIndex` returns its corresponding `Atom.Index`.
420425/// When the index was not found, a new `Atom` will be created, and its index will be returned.
421426/// The newly created Atom is empty with default fields as specified by `Atom.empty`.
422pub fn getOrCreateAtomForDecl(zig_object: *ZigObject, wasm_file: *Wasm, decl_index: InternPool.DeclIndex) !Atom.Index {
423 const gpa = wasm_file.base.comp.gpa;
427pub fn getOrCreateAtomForDecl(
428 zig_object: *ZigObject,
429 wasm_file: *Wasm,
430 pt: Zcu.PerThread,
431 decl_index: InternPool.DeclIndex,
432) !Atom.Index {
433 const gpa = pt.zcu.gpa;
424434 const gop = try zig_object.decls_map.getOrPut(gpa, decl_index);
425435 if (!gop.found_existing) {
426436 const sym_index = try zig_object.allocateSymbol(gpa);
427437 gop.value_ptr.* = .{ .atom = try wasm_file.createAtom(sym_index, zig_object.index) };
428 const mod = wasm_file.base.comp.module.?;
429 const decl = mod.declPtr(decl_index);
430 const full_name = try decl.fullyQualifiedName(mod);
438 const decl = pt.zcu.declPtr(decl_index);
439 const full_name = try decl.fullyQualifiedName(pt);
431440 const sym = zig_object.symbol(sym_index);
432 sym.name = try zig_object.string_table.insert(gpa, full_name.toSlice(&mod.intern_pool));
441 sym.name = try zig_object.string_table.insert(gpa, full_name.toSlice(&pt.zcu.intern_pool));
433442 }
434443 return gop.value_ptr.atom;
435444}
......@@ -437,9 +446,10 @@ pub fn getOrCreateAtomForDecl(zig_object: *ZigObject, wasm_file: *Wasm, decl_ind
437446pub fn lowerAnonDecl(
438447 zig_object: *ZigObject,
439448 wasm_file: *Wasm,
449 pt: Zcu.PerThread,
440450 decl_val: InternPool.Index,
441451 explicit_alignment: InternPool.Alignment,
442 src_loc: Module.LazySrcLoc,
452 src_loc: Zcu.LazySrcLoc,
443453) !codegen.Result {
444454 const gpa = wasm_file.base.comp.gpa;
445455 const gop = try zig_object.anon_decls.getOrPut(gpa, decl_val);
......@@ -449,7 +459,7 @@ pub fn lowerAnonDecl(
449459 @intFromEnum(decl_val),
450460 }) catch unreachable;
451461
452 switch (try zig_object.lowerConst(wasm_file, name, Value.fromInterned(decl_val), src_loc)) {
462 switch (try zig_object.lowerConst(wasm_file, pt, name, Value.fromInterned(decl_val), src_loc)) {
453463 .ok => |atom_index| zig_object.anon_decls.values()[gop.index] = atom_index,
454464 .fail => |em| return .{ .fail = em },
455465 }
......@@ -469,16 +479,22 @@ pub fn lowerAnonDecl(
469479/// Lowers a constant typed value to a local symbol and atom.
470480/// Returns the symbol index of the local
471481/// The given `decl` is the parent decl whom owns the constant.
472pub fn lowerUnnamedConst(zig_object: *ZigObject, wasm_file: *Wasm, val: Value, decl_index: InternPool.DeclIndex) !u32 {
473 const gpa = wasm_file.base.comp.gpa;
474 const mod = wasm_file.base.comp.module.?;
482pub fn lowerUnnamedConst(
483 zig_object: *ZigObject,
484 wasm_file: *Wasm,
485 pt: Zcu.PerThread,
486 val: Value,
487 decl_index: InternPool.DeclIndex,
488) !u32 {
489 const mod = pt.zcu;
490 const gpa = mod.gpa;
475491 std.debug.assert(val.typeOf(mod).zigTypeTag(mod) != .Fn); // cannot create local symbols for functions
476492 const decl = mod.declPtr(decl_index);
477493
478 const parent_atom_index = try zig_object.getOrCreateAtomForDecl(wasm_file, decl_index);
494 const parent_atom_index = try zig_object.getOrCreateAtomForDecl(wasm_file, pt, decl_index);
479495 const parent_atom = wasm_file.getAtom(parent_atom_index);
480496 const local_index = parent_atom.locals.items.len;
481 const fqn = try decl.fullyQualifiedName(mod);
497 const fqn = try decl.fullyQualifiedName(pt);
482498 const name = try std.fmt.allocPrintZ(gpa, "__unnamed_{}_{d}", .{
483499 fqn.fmt(&mod.intern_pool), local_index,
484500 });
......@@ -494,7 +510,7 @@ pub fn lowerUnnamedConst(zig_object: *ZigObject, wasm_file: *Wasm, val: Value, d
494510 else
495511 decl.navSrcLoc(mod);
496512
497 switch (try zig_object.lowerConst(wasm_file, name, val, decl_src)) {
513 switch (try zig_object.lowerConst(wasm_file, pt, name, val, decl_src)) {
498514 .ok => |atom_index| {
499515 try wasm_file.getAtomPtr(parent_atom_index).locals.append(gpa, atom_index);
500516 return @intFromEnum(wasm_file.getAtom(atom_index).sym_index);
......@@ -509,10 +525,17 @@ pub fn lowerUnnamedConst(zig_object: *ZigObject, wasm_file: *Wasm, val: Value, d
509525
510526const LowerConstResult = union(enum) {
511527 ok: Atom.Index,
512 fail: *Module.ErrorMsg,
528 fail: *Zcu.ErrorMsg,
513529};
514530
515fn lowerConst(zig_object: *ZigObject, wasm_file: *Wasm, name: []const u8, val: Value, src_loc: Module.LazySrcLoc) !LowerConstResult {
531fn lowerConst(
532 zig_object: *ZigObject,
533 wasm_file: *Wasm,
534 pt: Zcu.PerThread,
535 name: []const u8,
536 val: Value,
537 src_loc: Zcu.LazySrcLoc,
538) !LowerConstResult {
516539 const gpa = wasm_file.base.comp.gpa;
517540 const mod = wasm_file.base.comp.module.?;
518541
......@@ -526,7 +549,7 @@ fn lowerConst(zig_object: *ZigObject, wasm_file: *Wasm, name: []const u8, val: V
526549
527550 const code = code: {
528551 const atom = wasm_file.getAtomPtr(atom_index);
529 atom.alignment = ty.abiAlignment(mod);
552 atom.alignment = ty.abiAlignment(pt);
530553 const segment_name = try std.mem.concat(gpa, u8, &.{ ".rodata.", name });
531554 errdefer gpa.free(segment_name);
532555 zig_object.symbol(sym_index).* = .{
......@@ -536,13 +559,14 @@ fn lowerConst(zig_object: *ZigObject, wasm_file: *Wasm, name: []const u8, val: V
536559 .index = try zig_object.createDataSegment(
537560 gpa,
538561 segment_name,
539 ty.abiAlignment(mod),
562 ty.abiAlignment(pt),
540563 ),
541564 .virtual_address = undefined,
542565 };
543566
544567 const result = try codegen.generateSymbol(
545568 &wasm_file.base,
569 pt,
546570 src_loc,
547571 val,
548572 &value_bytes,
......@@ -568,7 +592,7 @@ fn lowerConst(zig_object: *ZigObject, wasm_file: *Wasm, name: []const u8, val: V
568592/// Returns the symbol index of the error name table.
569593///
570594/// When the symbol does not yet exist, it will create a new one instead.
571pub fn getErrorTableSymbol(zig_object: *ZigObject, wasm_file: *Wasm) !Symbol.Index {
595pub fn getErrorTableSymbol(zig_object: *ZigObject, wasm_file: *Wasm, pt: Zcu.PerThread) !Symbol.Index {
572596 if (zig_object.error_table_symbol != .null) {
573597 return zig_object.error_table_symbol;
574598 }
......@@ -581,8 +605,7 @@ pub fn getErrorTableSymbol(zig_object: *ZigObject, wasm_file: *Wasm) !Symbol.Ind
581605 const atom_index = try wasm_file.createAtom(sym_index, zig_object.index);
582606 const atom = wasm_file.getAtomPtr(atom_index);
583607 const slice_ty = Type.slice_const_u8_sentinel_0;
584 const mod = wasm_file.base.comp.module.?;
585 atom.alignment = slice_ty.abiAlignment(mod);
608 atom.alignment = slice_ty.abiAlignment(pt);
586609
587610 const sym_name = try zig_object.string_table.insert(gpa, "__zig_err_name_table");
588611 const segment_name = try gpa.dupe(u8, ".rodata.__zig_err_name_table");
......@@ -604,7 +627,7 @@ pub fn getErrorTableSymbol(zig_object: *ZigObject, wasm_file: *Wasm) !Symbol.Ind
604627///
605628/// This creates a table that consists of pointers and length to each error name.
606629/// The table is what is being pointed to within the runtime bodies that are generated.
607fn populateErrorNameTable(zig_object: *ZigObject, wasm_file: *Wasm) !void {
630fn populateErrorNameTable(zig_object: *ZigObject, wasm_file: *Wasm, tid: Zcu.PerThread.Id) !void {
608631 if (zig_object.error_table_symbol == .null) return;
609632 const gpa = wasm_file.base.comp.gpa;
610633 const atom_index = wasm_file.symbol_atom.get(.{ .file = zig_object.index, .index = zig_object.error_table_symbol }).?;
......@@ -631,11 +654,11 @@ fn populateErrorNameTable(zig_object: *ZigObject, wasm_file: *Wasm) !void {
631654
632655 // Addend for each relocation to the table
633656 var addend: u32 = 0;
634 const mod = wasm_file.base.comp.module.?;
635 for (mod.global_error_set.keys()) |error_name| {
657 const pt: Zcu.PerThread = .{ .zcu = wasm_file.base.comp.module.?, .tid = tid };
658 for (pt.zcu.global_error_set.keys()) |error_name| {
636659 const atom = wasm_file.getAtomPtr(atom_index);
637660
638 const error_name_slice = error_name.toSlice(&mod.intern_pool);
661 const error_name_slice = error_name.toSlice(&pt.zcu.intern_pool);
639662 const len: u32 = @intCast(error_name_slice.len + 1); // names are 0-terminated
640663
641664 const slice_ty = Type.slice_const_u8_sentinel_0;
......@@ -650,14 +673,14 @@ fn populateErrorNameTable(zig_object: *ZigObject, wasm_file: *Wasm) !void {
650673 .offset = offset,
651674 .addend = @intCast(addend),
652675 });
653 atom.size += @intCast(slice_ty.abiSize(mod));
676 atom.size += @intCast(slice_ty.abiSize(pt));
654677 addend += len;
655678
656679 // as we updated the error name table, we now store the actual name within the names atom
657680 try names_atom.code.ensureUnusedCapacity(gpa, len);
658681 names_atom.code.appendSliceAssumeCapacity(error_name_slice[0..len]);
659682
660 log.debug("Populated error name: '{}'", .{error_name.fmt(&mod.intern_pool)});
683 log.debug("Populated error name: '{}'", .{error_name.fmt(&pt.zcu.intern_pool)});
661684 }
662685 names_atom.size = addend;
663686 zig_object.error_names_atom = names_atom_index;
......@@ -756,22 +779,22 @@ pub fn getGlobalSymbol(zig_object: *ZigObject, gpa: std.mem.Allocator, name: []c
756779pub fn getDeclVAddr(
757780 zig_object: *ZigObject,
758781 wasm_file: *Wasm,
782 pt: Zcu.PerThread,
759783 decl_index: InternPool.DeclIndex,
760784 reloc_info: link.File.RelocInfo,
761785) !u64 {
762786 const target = wasm_file.base.comp.root_mod.resolved_target.result;
763 const gpa = wasm_file.base.comp.gpa;
764 const mod = wasm_file.base.comp.module.?;
765 const decl = mod.declPtr(decl_index);
787 const gpa = pt.zcu.gpa;
788 const decl = pt.zcu.declPtr(decl_index);
766789
767 const target_atom_index = try zig_object.getOrCreateAtomForDecl(wasm_file, decl_index);
790 const target_atom_index = try zig_object.getOrCreateAtomForDecl(wasm_file, pt, decl_index);
768791 const target_symbol_index = @intFromEnum(wasm_file.getAtom(target_atom_index).sym_index);
769792
770793 std.debug.assert(reloc_info.parent_atom_index != 0);
771794 const atom_index = wasm_file.symbol_atom.get(.{ .file = zig_object.index, .index = @enumFromInt(reloc_info.parent_atom_index) }).?;
772795 const atom = wasm_file.getAtomPtr(atom_index);
773796 const is_wasm32 = target.cpu.arch == .wasm32;
774 if (decl.typeOf(mod).zigTypeTag(mod) == .Fn) {
797 if (decl.typeOf(pt.zcu).zigTypeTag(pt.zcu) == .Fn) {
775798 std.debug.assert(reloc_info.addend == 0); // addend not allowed for function relocations
776799 try atom.relocs.append(gpa, .{
777800 .index = target_symbol_index,
......@@ -858,10 +881,11 @@ pub fn deleteExport(
858881pub fn updateExports(
859882 zig_object: *ZigObject,
860883 wasm_file: *Wasm,
861 mod: *Module,
862 exported: Module.Exported,
884 pt: Zcu.PerThread,
885 exported: Zcu.Exported,
863886 export_indices: []const u32,
864887) !void {
888 const mod = pt.zcu;
865889 const decl_index = switch (exported) {
866890 .decl_index => |i| i,
867891 .value => |val| {
......@@ -870,7 +894,7 @@ pub fn updateExports(
870894 },
871895 };
872896 const decl = mod.declPtr(decl_index);
873 const atom_index = try zig_object.getOrCreateAtomForDecl(wasm_file, decl_index);
897 const atom_index = try zig_object.getOrCreateAtomForDecl(wasm_file, pt, decl_index);
874898 const decl_info = zig_object.decls_map.getPtr(decl_index).?;
875899 const atom = wasm_file.getAtom(atom_index);
876900 const atom_sym = atom.symbolLoc().getSymbol(wasm_file).*;
......@@ -880,7 +904,7 @@ pub fn updateExports(
880904 for (export_indices) |export_idx| {
881905 const exp = mod.all_exports.items[export_idx];
882906 if (exp.opts.section.toSlice(&mod.intern_pool)) |section| {
883 try mod.failed_exports.putNoClobber(gpa, export_idx, try Module.ErrorMsg.create(
907 try mod.failed_exports.putNoClobber(gpa, export_idx, try Zcu.ErrorMsg.create(
884908 gpa,
885909 decl.navSrcLoc(mod),
886910 "Unimplemented: ExportOptions.section '{s}'",
......@@ -913,7 +937,7 @@ pub fn updateExports(
913937 },
914938 .strong => {}, // symbols are strong by default
915939 .link_once => {
916 try mod.failed_exports.putNoClobber(gpa, export_idx, try Module.ErrorMsg.create(
940 try mod.failed_exports.putNoClobber(gpa, export_idx, try Zcu.ErrorMsg.create(
917941 gpa,
918942 decl.navSrcLoc(mod),
919943 "Unimplemented: LinkOnce",
......@@ -1096,13 +1120,17 @@ pub fn createDebugSectionForIndex(zig_object: *ZigObject, wasm_file: *Wasm, inde
10961120 return atom_index;
10971121}
10981122
1099pub fn updateDeclLineNumber(zig_object: *ZigObject, mod: *Module, decl_index: InternPool.DeclIndex) !void {
1123pub fn updateDeclLineNumber(
1124 zig_object: *ZigObject,
1125 pt: Zcu.PerThread,
1126 decl_index: InternPool.DeclIndex,
1127) !void {
11001128 if (zig_object.dwarf) |*dw| {
1101 const decl = mod.declPtr(decl_index);
1102 const decl_name = try decl.fullyQualifiedName(mod);
1129 const decl = pt.zcu.declPtr(decl_index);
1130 const decl_name = try decl.fullyQualifiedName(pt);
11031131
1104 log.debug("updateDeclLineNumber {}{*}", .{ decl_name.fmt(&mod.intern_pool), decl });
1105 try dw.updateDeclLineNumber(mod, decl_index);
1132 log.debug("updateDeclLineNumber {}{*}", .{ decl_name.fmt(&pt.zcu.intern_pool), decl });
1133 try dw.updateDeclLineNumber(pt.zcu, decl_index);
11061134 }
11071135}
11081136
......@@ -1228,8 +1256,8 @@ fn appendFunction(zig_object: *ZigObject, gpa: std.mem.Allocator, func: std.wasm
12281256 return index;
12291257}
12301258
1231pub fn flushModule(zig_object: *ZigObject, wasm_file: *Wasm) !void {
1232 try zig_object.populateErrorNameTable(wasm_file);
1259pub fn flushModule(zig_object: *ZigObject, wasm_file: *Wasm, tid: Zcu.PerThread.Id) !void {
1260 try zig_object.populateErrorNameTable(wasm_file, tid);
12331261 try zig_object.setupErrorsLen(wasm_file);
12341262}
12351263
......@@ -1248,8 +1276,6 @@ const File = @import("file.zig").File;
12481276const InternPool = @import("../../InternPool.zig");
12491277const Liveness = @import("../../Liveness.zig");
12501278const Zcu = @import("../../Zcu.zig");
1251/// Deprecated.
1252const Module = Zcu;
12531279const StringTable = @import("../StringTable.zig");
12541280const Symbol = @import("Symbol.zig");
12551281const Type = @import("../../Type.zig");
src/main.zig+42-4
......@@ -172,7 +172,7 @@ pub fn main() anyerror!void {
172172 }
173173 // We would prefer to use raw libc allocator here, but cannot
174174 // use it if it won't support the alignment we need.
175 if (@alignOf(std.c.max_align_t) < @alignOf(i128)) {
175 if (@alignOf(std.c.max_align_t) < @max(@alignOf(i128), std.atomic.cache_line)) {
176176 break :gpa std.heap.c_allocator;
177177 }
178178 break :gpa std.heap.raw_c_allocator;
......@@ -403,6 +403,7 @@ const usage_build_generic =
403403 \\General Options:
404404 \\ -h, --help Print this help and exit
405405 \\ --color [auto|off|on] Enable or disable colored error messages
406 \\ -j<N> Limit concurrent jobs (default is to use all CPU cores)
406407 \\ -femit-bin[=path] (default) Output machine code
407408 \\ -fno-emit-bin Do not output machine code
408409 \\ -femit-asm[=path] Output .s (assembly code)
......@@ -1004,6 +1005,7 @@ fn buildOutputType(
10041005 .on
10051006 else
10061007 .auto;
1008 var n_jobs: ?u32 = null;
10071009
10081010 switch (arg_mode) {
10091011 .build, .translate_c, .zig_test, .run => {
......@@ -1141,6 +1143,17 @@ fn buildOutputType(
11411143 color = std.meta.stringToEnum(Color, next_arg) orelse {
11421144 fatal("expected [auto|on|off] after --color, found '{s}'", .{next_arg});
11431145 };
1146 } else if (mem.startsWith(u8, arg, "-j")) {
1147 const str = arg["-j".len..];
1148 const num = std.fmt.parseUnsigned(u32, str, 10) catch |err| {
1149 fatal("unable to parse jobs count '{s}': {s}", .{
1150 str, @errorName(err),
1151 });
1152 };
1153 if (num < 1) {
1154 fatal("number of jobs must be at least 1\n", .{});
1155 }
1156 n_jobs = num;
11441157 } else if (mem.eql(u8, arg, "--subsystem")) {
11451158 subsystem = try parseSubSystem(args_iter.nextOrFatal());
11461159 } else if (mem.eql(u8, arg, "-O")) {
......@@ -3092,7 +3105,11 @@ fn buildOutputType(
30923105 defer emit_implib_resolved.deinit();
30933106
30943107 var thread_pool: ThreadPool = undefined;
3095 try thread_pool.init(.{ .allocator = gpa });
3108 try thread_pool.init(.{
3109 .allocator = gpa,
3110 .n_jobs = @min(@max(n_jobs orelse std.Thread.getCpuCount() catch 1, 1), std.math.maxInt(u8)),
3111 .track_ids = true,
3112 });
30963113 defer thread_pool.deinit();
30973114
30983115 var cleanup_local_cache_dir: ?fs.Dir = null;
......@@ -4644,6 +4661,7 @@ const usage_build =
46444661 \\ all Print the build summary in its entirety
46454662 \\ failures (Default) Only print failed steps
46464663 \\ none Do not print the build summary
4664 \\ -j<N> Limit concurrent jobs (default is to use all CPU cores)
46474665 \\ --build-file [file] Override path to build.zig
46484666 \\ --cache-dir [path] Override path to local Zig cache directory
46494667 \\ --global-cache-dir [path] Override path to global Zig cache directory
......@@ -4718,6 +4736,7 @@ fn cmdBuild(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
47184736 try child_argv.append("-Z" ++ results_tmp_file_nonce);
47194737
47204738 var color: Color = .auto;
4739 var n_jobs: ?u32 = null;
47214740
47224741 {
47234742 var i: usize = 0;
......@@ -4811,6 +4830,17 @@ fn cmdBuild(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
48114830 };
48124831 try child_argv.appendSlice(&.{ arg, args[i] });
48134832 continue;
4833 } else if (mem.startsWith(u8, arg, "-j")) {
4834 const str = arg["-j".len..];
4835 const num = std.fmt.parseUnsigned(u32, str, 10) catch |err| {
4836 fatal("unable to parse jobs count '{s}': {s}", .{
4837 str, @errorName(err),
4838 });
4839 };
4840 if (num < 1) {
4841 fatal("number of jobs must be at least 1\n", .{});
4842 }
4843 n_jobs = num;
48144844 } else if (mem.eql(u8, arg, "--seed")) {
48154845 if (i + 1 >= args.len) fatal("expected argument after '{s}'", .{arg});
48164846 i += 1;
......@@ -4895,7 +4925,11 @@ fn cmdBuild(gpa: Allocator, arena: Allocator, args: []const []const u8) !void {
48954925 child_argv.items[argv_index_cache_dir] = local_cache_directory.path orelse cwd_path;
48964926
48974927 var thread_pool: ThreadPool = undefined;
4898 try thread_pool.init(.{ .allocator = gpa });
4928 try thread_pool.init(.{
4929 .allocator = gpa,
4930 .n_jobs = @min(@max(n_jobs orelse std.Thread.getCpuCount() catch 1, 1), std.math.maxInt(u8)),
4931 .track_ids = true,
4932 });
48994933 defer thread_pool.deinit();
49004934
49014935 // Dummy http client that is not actually used when only_core_functionality is enabled.
......@@ -5329,7 +5363,11 @@ fn jitCmd(
53295363 defer global_cache_directory.handle.close();
53305364
53315365 var thread_pool: ThreadPool = undefined;
5332 try thread_pool.init(.{ .allocator = gpa });
5366 try thread_pool.init(.{
5367 .allocator = gpa,
5368 .n_jobs = @min(@max(std.Thread.getCpuCount() catch 1, 1), std.math.maxInt(u8)),
5369 .track_ids = true,
5370 });
53335371 defer thread_pool.deinit();
53345372
53355373 var child_argv: std.ArrayListUnmanaged([]const u8) = .{};
src/mutable_value.zig+48-52
......@@ -54,46 +54,44 @@ pub const MutableValue = union(enum) {
5454 payload: *MutableValue,
5555 };
5656
57 pub fn intern(mv: MutableValue, zcu: *Zcu, arena: Allocator) Allocator.Error!Value {
58 const ip = &zcu.intern_pool;
59 const gpa = zcu.gpa;
57 pub fn intern(mv: MutableValue, pt: Zcu.PerThread, arena: Allocator) Allocator.Error!Value {
6058 return Value.fromInterned(switch (mv) {
6159 .interned => |ip_index| ip_index,
62 .eu_payload => |sv| try ip.get(gpa, .{ .error_union = .{
60 .eu_payload => |sv| try pt.intern(.{ .error_union = .{
6361 .ty = sv.ty,
64 .val = .{ .payload = (try sv.child.intern(zcu, arena)).toIntern() },
62 .val = .{ .payload = (try sv.child.intern(pt, arena)).toIntern() },
6563 } }),
66 .opt_payload => |sv| try ip.get(gpa, .{ .opt = .{
64 .opt_payload => |sv| try pt.intern(.{ .opt = .{
6765 .ty = sv.ty,
68 .val = (try sv.child.intern(zcu, arena)).toIntern(),
66 .val = (try sv.child.intern(pt, arena)).toIntern(),
6967 } }),
70 .repeated => |sv| try ip.get(gpa, .{ .aggregate = .{
68 .repeated => |sv| try pt.intern(.{ .aggregate = .{
7169 .ty = sv.ty,
72 .storage = .{ .repeated_elem = (try sv.child.intern(zcu, arena)).toIntern() },
70 .storage = .{ .repeated_elem = (try sv.child.intern(pt, arena)).toIntern() },
7371 } }),
74 .bytes => |b| try ip.get(gpa, .{ .aggregate = .{
72 .bytes => |b| try pt.intern(.{ .aggregate = .{
7573 .ty = b.ty,
76 .storage = .{ .bytes = try ip.getOrPutString(gpa, b.data, .maybe_embedded_nulls) },
74 .storage = .{ .bytes = try pt.zcu.intern_pool.getOrPutString(pt.zcu.gpa, pt.tid, b.data, .maybe_embedded_nulls) },
7775 } }),
7876 .aggregate => |a| {
7977 const elems = try arena.alloc(InternPool.Index, a.elems.len);
8078 for (a.elems, elems) |mut_elem, *interned_elem| {
81 interned_elem.* = (try mut_elem.intern(zcu, arena)).toIntern();
79 interned_elem.* = (try mut_elem.intern(pt, arena)).toIntern();
8280 }
83 return Value.fromInterned(try ip.get(gpa, .{ .aggregate = .{
81 return Value.fromInterned(try pt.intern(.{ .aggregate = .{
8482 .ty = a.ty,
8583 .storage = .{ .elems = elems },
8684 } }));
8785 },
88 .slice => |s| try ip.get(gpa, .{ .slice = .{
86 .slice => |s| try pt.intern(.{ .slice = .{
8987 .ty = s.ty,
90 .ptr = (try s.ptr.intern(zcu, arena)).toIntern(),
91 .len = (try s.len.intern(zcu, arena)).toIntern(),
88 .ptr = (try s.ptr.intern(pt, arena)).toIntern(),
89 .len = (try s.len.intern(pt, arena)).toIntern(),
9290 } }),
93 .un => |u| try ip.get(gpa, .{ .un = .{
91 .un => |u| try pt.intern(.{ .un = .{
9492 .ty = u.ty,
9593 .tag = u.tag,
96 .val = (try u.payload.intern(zcu, arena)).toIntern(),
94 .val = (try u.payload.intern(pt, arena)).toIntern(),
9795 } }),
9896 });
9997 }
......@@ -108,13 +106,13 @@ pub const MutableValue = union(enum) {
108106 /// If `!allow_repeated`, the `repeated` representation will not be used.
109107 pub fn unintern(
110108 mv: *MutableValue,
111 zcu: *Zcu,
109 pt: Zcu.PerThread,
112110 arena: Allocator,
113111 allow_bytes: bool,
114112 allow_repeated: bool,
115113 ) Allocator.Error!void {
114 const zcu = pt.zcu;
116115 const ip = &zcu.intern_pool;
117 const gpa = zcu.gpa;
118116 switch (mv.*) {
119117 .interned => |ip_index| switch (ip.indexToKey(ip_index)) {
120118 .opt => |opt| if (opt.val != .none) {
......@@ -170,7 +168,7 @@ pub const MutableValue = union(enum) {
170168 } else {
171169 const mut_elems = try arena.alloc(MutableValue, len);
172170 for (bytes.toSlice(len, ip), mut_elems) |b, *mut_elem| {
173 mut_elem.* = .{ .interned = try ip.get(gpa, .{ .int = .{
171 mut_elem.* = .{ .interned = try pt.intern(.{ .int = .{
174172 .ty = .u8_type,
175173 .storage = .{ .u64 = b },
176174 } }) };
......@@ -221,12 +219,12 @@ pub const MutableValue = union(enum) {
221219 switch (type_tag) {
222220 .Array, .Vector => {
223221 const elem_ty = ip.childType(ty_ip);
224 const undef_elem = try ip.get(gpa, .{ .undef = elem_ty });
222 const undef_elem = try pt.intern(.{ .undef = elem_ty });
225223 @memset(elems[0..@intCast(len_no_sent)], .{ .interned = undef_elem });
226224 },
227225 .Struct => for (elems[0..@intCast(len_no_sent)], 0..) |*mut_elem, i| {
228226 const field_ty = ty.structFieldType(i, zcu).toIntern();
229 mut_elem.* = .{ .interned = try ip.get(gpa, .{ .undef = field_ty }) };
227 mut_elem.* = .{ .interned = try pt.intern(.{ .undef = field_ty }) };
230228 },
231229 else => unreachable,
232230 }
......@@ -238,7 +236,7 @@ pub const MutableValue = union(enum) {
238236 } else {
239237 const repeated_val = try arena.create(MutableValue);
240238 repeated_val.* = .{
241 .interned = try ip.get(gpa, .{ .undef = ip.childType(ty_ip) }),
239 .interned = try pt.intern(.{ .undef = ip.childType(ty_ip) }),
242240 };
243241 mv.* = .{ .repeated = .{
244242 .ty = ty_ip,
......@@ -248,11 +246,8 @@ pub const MutableValue = union(enum) {
248246 },
249247 .Union => {
250248 const payload = try arena.create(MutableValue);
251 const backing_ty = try Type.fromInterned(ty_ip).unionBackingType(zcu);
252 payload.* = .{ .interned = try ip.get(
253 gpa,
254 .{ .undef = backing_ty.toIntern() },
255 ) };
249 const backing_ty = try Type.fromInterned(ty_ip).unionBackingType(pt);
250 payload.* = .{ .interned = try pt.intern(.{ .undef = backing_ty.toIntern() }) };
256251 mv.* = .{ .un = .{
257252 .ty = ty_ip,
258253 .tag = .none,
......@@ -264,8 +259,8 @@ pub const MutableValue = union(enum) {
264259 if (ptr_ty.flags.size != .Slice) return;
265260 const ptr = try arena.create(MutableValue);
266261 const len = try arena.create(MutableValue);
267 ptr.* = .{ .interned = try ip.get(gpa, .{ .undef = ip.slicePtrType(ty_ip) }) };
268 len.* = .{ .interned = try ip.get(gpa, .{ .undef = .usize_type }) };
262 ptr.* = .{ .interned = try pt.intern(.{ .undef = ip.slicePtrType(ty_ip) }) };
263 len.* = .{ .interned = try pt.intern(.{ .undef = .usize_type }) };
269264 mv.* = .{ .slice = .{
270265 .ty = ty_ip,
271266 .ptr = ptr,
......@@ -279,7 +274,7 @@ pub const MutableValue = union(enum) {
279274 .bytes => |bytes| if (!allow_bytes) {
280275 const elems = try arena.alloc(MutableValue, bytes.data.len);
281276 for (bytes.data, elems) |byte, *interned_byte| {
282 interned_byte.* = .{ .interned = try ip.get(gpa, .{ .int = .{
277 interned_byte.* = .{ .interned = try pt.intern(.{ .int = .{
283278 .ty = .u8_type,
284279 .storage = .{ .u64 = byte },
285280 } }) };
......@@ -298,22 +293,22 @@ pub const MutableValue = union(enum) {
298293 /// The returned pointer is valid until the representation of `mv` changes.
299294 pub fn elem(
300295 mv: *MutableValue,
301 zcu: *Zcu,
296 pt: Zcu.PerThread,
302297 arena: Allocator,
303298 field_idx: usize,
304299 ) Allocator.Error!*MutableValue {
300 const zcu = pt.zcu;
305301 const ip = &zcu.intern_pool;
306 const gpa = zcu.gpa;
307302 // Convert to the `aggregate` representation.
308303 switch (mv.*) {
309304 .eu_payload, .opt_payload, .un => unreachable,
310305 .interned => {
311 try mv.unintern(zcu, arena, false, false);
306 try mv.unintern(pt, arena, false, false);
312307 },
313308 .bytes => |bytes| {
314309 const elems = try arena.alloc(MutableValue, bytes.data.len);
315310 for (bytes.data, elems) |byte, *interned_byte| {
316 interned_byte.* = .{ .interned = try ip.get(gpa, .{ .int = .{
311 interned_byte.* = .{ .interned = try pt.intern(.{ .int = .{
317312 .ty = .u8_type,
318313 .storage = .{ .u64 = byte },
319314 } }) };
......@@ -351,14 +346,15 @@ pub const MutableValue = union(enum) {
351346 /// For slices, uses `Value.slice_ptr_index` and `Value.slice_len_index`.
352347 pub fn setElem(
353348 mv: *MutableValue,
354 zcu: *Zcu,
349 pt: Zcu.PerThread,
355350 arena: Allocator,
356351 field_idx: usize,
357352 field_val: MutableValue,
358353 ) Allocator.Error!void {
354 const zcu = pt.zcu;
359355 const ip = &zcu.intern_pool;
360356 const is_trivial_int = field_val.isTrivialInt(zcu);
361 try mv.unintern(zcu, arena, is_trivial_int, true);
357 try mv.unintern(pt, arena, is_trivial_int, true);
362358 switch (mv.*) {
363359 .interned,
364360 .eu_payload,
......@@ -373,7 +369,7 @@ pub const MutableValue = union(enum) {
373369 .bytes => |b| {
374370 assert(is_trivial_int);
375371 assert(field_val.typeOf(zcu).toIntern() == .u8_type);
376 b.data[field_idx] = @intCast(Value.fromInterned(field_val.interned).toUnsignedInt(zcu));
372 b.data[field_idx] = @intCast(Value.fromInterned(field_val.interned).toUnsignedInt(pt));
377373 },
378374 .repeated => |r| {
379375 if (field_val.eqlTrivial(r.child.*)) return;
......@@ -386,9 +382,9 @@ pub const MutableValue = union(enum) {
386382 {
387383 // We can use the `bytes` representation.
388384 const bytes = try arena.alloc(u8, @intCast(len_inc_sent));
389 const repeated_byte = Value.fromInterned(r.child.interned).toUnsignedInt(zcu);
385 const repeated_byte = Value.fromInterned(r.child.interned).toUnsignedInt(pt);
390386 @memset(bytes, @intCast(repeated_byte));
391 bytes[field_idx] = @intCast(Value.fromInterned(field_val.interned).toUnsignedInt(zcu));
387 bytes[field_idx] = @intCast(Value.fromInterned(field_val.interned).toUnsignedInt(pt));
392388 mv.* = .{ .bytes = .{
393389 .ty = r.ty,
394390 .data = bytes,
......@@ -435,7 +431,7 @@ pub const MutableValue = union(enum) {
435431 } else {
436432 const bytes = try arena.alloc(u8, a.elems.len);
437433 for (a.elems, bytes) |elem_val, *b| {
438 b.* = @intCast(Value.fromInterned(elem_val.interned).toUnsignedInt(zcu));
434 b.* = @intCast(Value.fromInterned(elem_val.interned).toUnsignedInt(pt));
439435 }
440436 mv.* = .{ .bytes = .{
441437 .ty = a.ty,
......@@ -451,7 +447,7 @@ pub const MutableValue = union(enum) {
451447 /// For slices, uses `Value.slice_ptr_index` and `Value.slice_len_index`.
452448 pub fn getElem(
453449 mv: MutableValue,
454 zcu: *Zcu,
450 pt: Zcu.PerThread,
455451 field_idx: usize,
456452 ) Allocator.Error!MutableValue {
457453 return switch (mv) {
......@@ -459,16 +455,16 @@ pub const MutableValue = union(enum) {
459455 .opt_payload,
460456 => unreachable,
461457 .interned => |ip_index| {
462 const ty = Type.fromInterned(zcu.intern_pool.typeOf(ip_index));
463 switch (ty.zigTypeTag(zcu)) {
464 .Array, .Vector => return .{ .interned = (try Value.fromInterned(ip_index).elemValue(zcu, field_idx)).toIntern() },
465 .Struct, .Union => return .{ .interned = (try Value.fromInterned(ip_index).fieldValue(zcu, field_idx)).toIntern() },
458 const ty = Type.fromInterned(pt.zcu.intern_pool.typeOf(ip_index));
459 switch (ty.zigTypeTag(pt.zcu)) {
460 .Array, .Vector => return .{ .interned = (try Value.fromInterned(ip_index).elemValue(pt, field_idx)).toIntern() },
461 .Struct, .Union => return .{ .interned = (try Value.fromInterned(ip_index).fieldValue(pt, field_idx)).toIntern() },
466462 .Pointer => {
467 assert(ty.isSlice(zcu));
463 assert(ty.isSlice(pt.zcu));
468464 return switch (field_idx) {
469 Value.slice_ptr_index => .{ .interned = Value.fromInterned(ip_index).slicePtr(zcu).toIntern() },
470 Value.slice_len_index => .{ .interned = switch (zcu.intern_pool.indexToKey(ip_index)) {
471 .undef => try zcu.intern(.{ .undef = .usize_type }),
465 Value.slice_ptr_index => .{ .interned = Value.fromInterned(ip_index).slicePtr(pt.zcu).toIntern() },
466 Value.slice_len_index => .{ .interned = switch (pt.zcu.intern_pool.indexToKey(ip_index)) {
467 .undef => try pt.intern(.{ .undef = .usize_type }),
472468 .slice => |s| s.len,
473469 else => unreachable,
474470 } },
......@@ -487,7 +483,7 @@ pub const MutableValue = union(enum) {
487483 Value.slice_len_index => s.len.*,
488484 else => unreachable,
489485 },
490 .bytes => |b| .{ .interned = try zcu.intern(.{ .int = .{
486 .bytes => |b| .{ .interned = try pt.intern(.{ .int = .{
491487 .ty = .u8_type,
492488 .storage = .{ .u64 = b.data[field_idx] },
493489 } }) },
src/print_air.zig+19-19
......@@ -9,7 +9,7 @@ const Air = @import("Air.zig");
99const Liveness = @import("Liveness.zig");
1010const InternPool = @import("InternPool.zig");
1111
12pub fn write(stream: anytype, module: *Zcu, air: Air, liveness: ?Liveness) void {
12pub fn write(stream: anytype, pt: Zcu.PerThread, air: Air, liveness: ?Liveness) void {
1313 const instruction_bytes = air.instructions.len *
1414 // Here we don't use @sizeOf(Air.Inst.Data) because it would include
1515 // the debug safety tag but we want to measure release size.
......@@ -42,8 +42,8 @@ pub fn write(stream: anytype, module: *Zcu, air: Air, liveness: ?Liveness) void
4242 // zig fmt: on
4343
4444 var writer: Writer = .{
45 .module = module,
46 .gpa = module.gpa,
45 .pt = pt,
46 .gpa = pt.zcu.gpa,
4747 .air = air,
4848 .liveness = liveness,
4949 .indent = 2,
......@@ -55,13 +55,13 @@ pub fn write(stream: anytype, module: *Zcu, air: Air, liveness: ?Liveness) void
5555pub fn writeInst(
5656 stream: anytype,
5757 inst: Air.Inst.Index,
58 module: *Zcu,
58 pt: Zcu.PerThread,
5959 air: Air,
6060 liveness: ?Liveness,
6161) void {
6262 var writer: Writer = .{
63 .module = module,
64 .gpa = module.gpa,
63 .pt = pt,
64 .gpa = pt.zcu.gpa,
6565 .air = air,
6666 .liveness = liveness,
6767 .indent = 2,
......@@ -70,16 +70,16 @@ pub fn writeInst(
7070 writer.writeInst(stream, inst) catch return;
7171}
7272
73pub fn dump(module: *Zcu, air: Air, liveness: ?Liveness) void {
74 write(std.io.getStdErr().writer(), module, air, liveness);
73pub fn dump(pt: Zcu.PerThread, air: Air, liveness: ?Liveness) void {
74 write(std.io.getStdErr().writer(), pt, air, liveness);
7575}
7676
77pub fn dumpInst(inst: Air.Inst.Index, module: *Zcu, air: Air, liveness: ?Liveness) void {
78 writeInst(std.io.getStdErr().writer(), inst, module, air, liveness);
77pub fn dumpInst(inst: Air.Inst.Index, pt: Zcu.PerThread, air: Air, liveness: ?Liveness) void {
78 writeInst(std.io.getStdErr().writer(), inst, pt, air, liveness);
7979}
8080
8181const Writer = struct {
82 module: *Zcu,
82 pt: Zcu.PerThread,
8383 gpa: Allocator,
8484 air: Air,
8585 liveness: ?Liveness,
......@@ -345,7 +345,7 @@ const Writer = struct {
345345 }
346346
347347 fn writeType(w: *Writer, s: anytype, ty: Type) !void {
348 return ty.print(s, w.module);
348 return ty.print(s, w.pt);
349349 }
350350
351351 fn writeTy(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
......@@ -424,7 +424,7 @@ const Writer = struct {
424424 }
425425
426426 fn writeAggregateInit(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
427 const mod = w.module;
427 const mod = w.pt.zcu;
428428 const ty_pl = w.air.instructions.items(.data)[@intFromEnum(inst)].ty_pl;
429429 const vector_ty = ty_pl.ty.toType();
430430 const len = @as(usize, @intCast(vector_ty.arrayLen(mod)));
......@@ -504,7 +504,7 @@ const Writer = struct {
504504 }
505505
506506 fn writeSelect(w: *Writer, s: anytype, inst: Air.Inst.Index) @TypeOf(s).Error!void {
507 const mod = w.module;
507 const mod = w.pt.zcu;
508508 const pl_op = w.air.instructions.items(.data)[@intFromEnum(inst)].pl_op;
509509 const extra = w.air.extraData(Air.Bin, pl_op.payload).data;
510510
......@@ -947,11 +947,11 @@ const Writer = struct {
947947 if (@intFromEnum(operand) < InternPool.static_len) {
948948 return s.print("@{}", .{operand});
949949 } else if (operand.toInterned()) |ip_index| {
950 const mod = w.module;
951 const ty = Type.fromInterned(mod.intern_pool.indexToKey(ip_index).typeOf());
950 const pt = w.pt;
951 const ty = Type.fromInterned(pt.zcu.intern_pool.indexToKey(ip_index).typeOf());
952952 try s.print("<{}, {}>", .{
953 ty.fmt(mod),
954 Value.fromInterned(ip_index).fmtValue(mod, null),
953 ty.fmt(pt),
954 Value.fromInterned(ip_index).fmtValue(pt, null),
955955 });
956956 } else {
957957 return w.writeInstIndex(s, operand.toIndex().?, dies);
......@@ -970,7 +970,7 @@ const Writer = struct {
970970 }
971971
972972 fn typeOfIndex(w: *Writer, inst: Air.Inst.Index) Type {
973 const mod = w.module;
973 const mod = w.pt.zcu;
974974 return w.air.typeOfIndex(inst, &mod.intern_pool);
975975 }
976976};
src/print_value.zig+53-52
......@@ -5,8 +5,6 @@ const std = @import("std");
55const Type = @import("Type.zig");
66const Value = @import("Value.zig");
77const Zcu = @import("Zcu.zig");
8/// Deprecated.
9const Module = Zcu;
108const Sema = @import("Sema.zig");
119const InternPool = @import("InternPool.zig");
1210const Allocator = std.mem.Allocator;
......@@ -17,7 +15,7 @@ const max_string_len = 256;
1715
1816pub const FormatContext = struct {
1917 val: Value,
20 mod: *Module,
18 pt: Zcu.PerThread,
2119 opt_sema: ?*Sema,
2220 depth: u8,
2321};
......@@ -30,7 +28,7 @@ pub fn format(
3028) !void {
3129 _ = options;
3230 comptime std.debug.assert(fmt.len == 0);
33 return print(ctx.val, writer, ctx.depth, ctx.mod, ctx.opt_sema) catch |err| switch (err) {
31 return print(ctx.val, writer, ctx.depth, ctx.pt, ctx.opt_sema) catch |err| switch (err) {
3432 error.OutOfMemory => @panic("OOM"), // We're not allowed to return this from a format function
3533 error.ComptimeBreak, error.ComptimeReturn => unreachable,
3634 error.AnalysisFail => unreachable, // TODO: re-evaluate when we use `opt_sema` more fully
......@@ -42,10 +40,11 @@ pub fn print(
4240 val: Value,
4341 writer: anytype,
4442 level: u8,
45 mod: *Module,
43 pt: Zcu.PerThread,
4644 /// If this `Sema` is provided, we will recurse through pointers where possible to provide friendly output.
4745 opt_sema: ?*Sema,
48) (@TypeOf(writer).Error || Module.CompileError)!void {
46) (@TypeOf(writer).Error || Zcu.CompileError)!void {
47 const mod = pt.zcu;
4948 const ip = &mod.intern_pool;
5049 switch (ip.indexToKey(val.toIntern())) {
5150 .int_type,
......@@ -64,7 +63,7 @@ pub fn print(
6463 .func_type,
6564 .error_set_type,
6665 .inferred_error_set_type,
67 => try Type.print(val.toType(), writer, mod),
66 => try Type.print(val.toType(), writer, pt),
6867 .undef => try writer.writeAll("undefined"),
6968 .simple_value => |simple_value| switch (simple_value) {
7069 .void => try writer.writeAll("{}"),
......@@ -82,13 +81,13 @@ pub fn print(
8281 .int => |int| switch (int.storage) {
8382 inline .u64, .i64, .big_int => |x| try writer.print("{}", .{x}),
8483 .lazy_align => |ty| if (opt_sema != null) {
85 const a = (try Type.fromInterned(ty).abiAlignmentAdvanced(mod, .sema)).scalar;
84 const a = (try Type.fromInterned(ty).abiAlignmentAdvanced(pt, .sema)).scalar;
8685 try writer.print("{}", .{a.toByteUnits() orelse 0});
87 } else try writer.print("@alignOf({})", .{Type.fromInterned(ty).fmt(mod)}),
86 } else try writer.print("@alignOf({})", .{Type.fromInterned(ty).fmt(pt)}),
8887 .lazy_size => |ty| if (opt_sema != null) {
89 const s = (try Type.fromInterned(ty).abiSizeAdvanced(mod, .sema)).scalar;
88 const s = (try Type.fromInterned(ty).abiSizeAdvanced(pt, .sema)).scalar;
9089 try writer.print("{}", .{s});
91 } else try writer.print("@sizeOf({})", .{Type.fromInterned(ty).fmt(mod)}),
90 } else try writer.print("@sizeOf({})", .{Type.fromInterned(ty).fmt(pt)}),
9291 },
9392 .err => |err| try writer.print("error.{}", .{
9493 err.name.fmt(ip),
......@@ -97,7 +96,7 @@ pub fn print(
9796 .err_name => |err_name| try writer.print("error.{}", .{
9897 err_name.fmt(ip),
9998 }),
100 .payload => |payload| try print(Value.fromInterned(payload), writer, level, mod, opt_sema),
99 .payload => |payload| try print(Value.fromInterned(payload), writer, level, pt, opt_sema),
101100 },
102101 .enum_literal => |enum_literal| try writer.print(".{}", .{
103102 enum_literal.fmt(ip),
......@@ -111,7 +110,7 @@ pub fn print(
111110 return writer.writeAll("@enumFromInt(...)");
112111 }
113112 try writer.writeAll("@enumFromInt(");
114 try print(Value.fromInterned(enum_tag.int), writer, level - 1, mod, opt_sema);
113 try print(Value.fromInterned(enum_tag.int), writer, level - 1, pt, opt_sema);
115114 try writer.writeAll(")");
116115 },
117116 .empty_enum_value => try writer.writeAll("(empty enum value)"),
......@@ -128,12 +127,12 @@ pub fn print(
128127 // TODO: eventually we want to load the slice as an array with `opt_sema`, but that's
129128 // currently not possible without e.g. triggering compile errors.
130129 }
131 try printPtr(Value.fromInterned(slice.ptr), writer, level, mod, opt_sema);
130 try printPtr(Value.fromInterned(slice.ptr), writer, level, pt, opt_sema);
132131 try writer.writeAll("[0..");
133132 if (level == 0) {
134133 try writer.writeAll("(...)");
135134 } else {
136 try print(Value.fromInterned(slice.len), writer, level - 1, mod, opt_sema);
135 try print(Value.fromInterned(slice.len), writer, level - 1, pt, opt_sema);
137136 }
138137 try writer.writeAll("]");
139138 },
......@@ -147,28 +146,28 @@ pub fn print(
147146 // TODO: eventually we want to load the pointer with `opt_sema`, but that's
148147 // currently not possible without e.g. triggering compile errors.
149148 }
150 try printPtr(val, writer, level, mod, opt_sema);
149 try printPtr(val, writer, level, pt, opt_sema);
151150 },
152151 .opt => |opt| switch (opt.val) {
153152 .none => try writer.writeAll("null"),
154 else => |payload| try print(Value.fromInterned(payload), writer, level, mod, opt_sema),
153 else => |payload| try print(Value.fromInterned(payload), writer, level, pt, opt_sema),
155154 },
156 .aggregate => |aggregate| try printAggregate(val, aggregate, false, writer, level, mod, opt_sema),
155 .aggregate => |aggregate| try printAggregate(val, aggregate, false, writer, level, pt, opt_sema),
157156 .un => |un| {
158157 if (level == 0) {
159158 try writer.writeAll(".{ ... }");
160159 return;
161160 }
162161 if (un.tag == .none) {
163 const backing_ty = try val.typeOf(mod).unionBackingType(mod);
164 try writer.print("@bitCast(@as({}, ", .{backing_ty.fmt(mod)});
165 try print(Value.fromInterned(un.val), writer, level - 1, mod, opt_sema);
162 const backing_ty = try val.typeOf(mod).unionBackingType(pt);
163 try writer.print("@bitCast(@as({}, ", .{backing_ty.fmt(pt)});
164 try print(Value.fromInterned(un.val), writer, level - 1, pt, opt_sema);
166165 try writer.writeAll("))");
167166 } else {
168167 try writer.writeAll(".{ ");
169 try print(Value.fromInterned(un.tag), writer, level - 1, mod, opt_sema);
168 try print(Value.fromInterned(un.tag), writer, level - 1, pt, opt_sema);
170169 try writer.writeAll(" = ");
171 try print(Value.fromInterned(un.val), writer, level - 1, mod, opt_sema);
170 try print(Value.fromInterned(un.val), writer, level - 1, pt, opt_sema);
172171 try writer.writeAll(" }");
173172 }
174173 },
......@@ -182,13 +181,14 @@ fn printAggregate(
182181 is_ref: bool,
183182 writer: anytype,
184183 level: u8,
185 zcu: *Zcu,
184 pt: Zcu.PerThread,
186185 opt_sema: ?*Sema,
187) (@TypeOf(writer).Error || Module.CompileError)!void {
186) (@TypeOf(writer).Error || Zcu.CompileError)!void {
188187 if (level == 0) {
189188 if (is_ref) try writer.writeByte('&');
190189 return writer.writeAll(".{ ... }");
191190 }
191 const zcu = pt.zcu;
192192 const ip = &zcu.intern_pool;
193193 const ty = Type.fromInterned(aggregate.ty);
194194 switch (ty.zigTypeTag(zcu)) {
......@@ -203,7 +203,7 @@ fn printAggregate(
203203 if (i != 0) try writer.writeAll(", ");
204204 const field_name = ty.structFieldName(@intCast(i), zcu).unwrap().?;
205205 try writer.print(".{i} = ", .{field_name.fmt(ip)});
206 try print(try val.fieldValue(zcu, i), writer, level - 1, zcu, opt_sema);
206 try print(try val.fieldValue(pt, i), writer, level - 1, pt, opt_sema);
207207 }
208208 try writer.writeAll(" }");
209209 return;
......@@ -230,7 +230,7 @@ fn printAggregate(
230230 if (ty.childType(zcu).toIntern() != .u8_type) break :one_byte_str;
231231 const elem_val = Value.fromInterned(aggregate.storage.values()[0]);
232232 if (elem_val.isUndef(zcu)) break :one_byte_str;
233 const byte = elem_val.toUnsignedInt(zcu);
233 const byte = elem_val.toUnsignedInt(pt);
234234 try writer.print("\"{}\"", .{std.zig.fmtEscapes(&.{@intCast(byte)})});
235235 if (!is_ref) try writer.writeAll(".*");
236236 return;
......@@ -253,7 +253,7 @@ fn printAggregate(
253253 const max_len = @min(len, max_aggregate_items);
254254 for (0..max_len) |i| {
255255 if (i != 0) try writer.writeAll(", ");
256 try print(try val.fieldValue(zcu, i), writer, level - 1, zcu, opt_sema);
256 try print(try val.fieldValue(pt, i), writer, level - 1, pt, opt_sema);
257257 }
258258 if (len > max_aggregate_items) {
259259 try writer.writeAll(", ...");
......@@ -261,8 +261,8 @@ fn printAggregate(
261261 return writer.writeAll(" }");
262262}
263263
264fn printPtr(ptr_val: Value, writer: anytype, level: u8, zcu: *Zcu, opt_sema: ?*Sema) (@TypeOf(writer).Error || Module.CompileError)!void {
265 const ptr = switch (zcu.intern_pool.indexToKey(ptr_val.toIntern())) {
264fn printPtr(ptr_val: Value, writer: anytype, level: u8, pt: Zcu.PerThread, opt_sema: ?*Sema) (@TypeOf(writer).Error || Zcu.CompileError)!void {
265 const ptr = switch (pt.zcu.intern_pool.indexToKey(ptr_val.toIntern())) {
266266 .undef => return writer.writeAll("undefined"),
267267 .ptr => |ptr| ptr,
268268 else => unreachable,
......@@ -270,32 +270,33 @@ fn printPtr(ptr_val: Value, writer: anytype, level: u8, zcu: *Zcu, opt_sema: ?*S
270270
271271 if (ptr.base_addr == .anon_decl) {
272272 // If the value is an aggregate, we can potentially print it more nicely.
273 switch (zcu.intern_pool.indexToKey(ptr.base_addr.anon_decl.val)) {
273 switch (pt.zcu.intern_pool.indexToKey(ptr.base_addr.anon_decl.val)) {
274274 .aggregate => |agg| return printAggregate(
275275 Value.fromInterned(ptr.base_addr.anon_decl.val),
276276 agg,
277277 true,
278278 writer,
279279 level,
280 zcu,
280 pt,
281281 opt_sema,
282282 ),
283283 else => {},
284284 }
285285 }
286286
287 var arena = std.heap.ArenaAllocator.init(zcu.gpa);
287 var arena = std.heap.ArenaAllocator.init(pt.zcu.gpa);
288288 defer arena.deinit();
289 const derivation = try ptr_val.pointerDerivationAdvanced(arena.allocator(), zcu, opt_sema);
290 try printPtrDerivation(derivation, writer, level, zcu, opt_sema);
289 const derivation = try ptr_val.pointerDerivationAdvanced(arena.allocator(), pt, opt_sema);
290 try printPtrDerivation(derivation, writer, level, pt, opt_sema);
291291}
292292
293293/// Print `derivation` as an lvalue, i.e. such that writing `&` before this gives the pointer value.
294fn printPtrDerivation(derivation: Value.PointerDeriveStep, writer: anytype, level: u8, zcu: *Zcu, opt_sema: ?*Sema) (@TypeOf(writer).Error || Module.CompileError)!void {
294fn printPtrDerivation(derivation: Value.PointerDeriveStep, writer: anytype, level: u8, pt: Zcu.PerThread, opt_sema: ?*Sema) (@TypeOf(writer).Error || Zcu.CompileError)!void {
295 const zcu = pt.zcu;
295296 const ip = &zcu.intern_pool;
296297 switch (derivation) {
297298 .int => |int| try writer.print("@as({}, @ptrFromInt({x})).*", .{
298 int.ptr_ty.fmt(zcu),
299 int.ptr_ty.fmt(pt),
299300 int.addr,
300301 }),
301302 .decl_ptr => |decl| {
......@@ -303,33 +304,33 @@ fn printPtrDerivation(derivation: Value.PointerDeriveStep, writer: anytype, leve
303304 },
304305 .anon_decl_ptr => |anon| {
305306 const ty = Value.fromInterned(anon.val).typeOf(zcu);
306 try writer.print("@as({}, ", .{ty.fmt(zcu)});
307 try print(Value.fromInterned(anon.val), writer, level - 1, zcu, opt_sema);
307 try writer.print("@as({}, ", .{ty.fmt(pt)});
308 try print(Value.fromInterned(anon.val), writer, level - 1, pt, opt_sema);
308309 try writer.writeByte(')');
309310 },
310311 .comptime_alloc_ptr => |info| {
311 try writer.print("@as({}, ", .{info.val.typeOf(zcu).fmt(zcu)});
312 try print(info.val, writer, level - 1, zcu, opt_sema);
312 try writer.print("@as({}, ", .{info.val.typeOf(zcu).fmt(pt)});
313 try print(info.val, writer, level - 1, pt, opt_sema);
313314 try writer.writeByte(')');
314315 },
315316 .comptime_field_ptr => |val| {
316317 const ty = val.typeOf(zcu);
317 try writer.print("@as({}, ", .{ty.fmt(zcu)});
318 try print(val, writer, level - 1, zcu, opt_sema);
318 try writer.print("@as({}, ", .{ty.fmt(pt)});
319 try print(val, writer, level - 1, pt, opt_sema);
319320 try writer.writeByte(')');
320321 },
321322 .eu_payload_ptr => |info| {
322323 try writer.writeByte('(');
323 try printPtrDerivation(info.parent.*, writer, level, zcu, opt_sema);
324 try printPtrDerivation(info.parent.*, writer, level, pt, opt_sema);
324325 try writer.writeAll(" catch unreachable)");
325326 },
326327 .opt_payload_ptr => |info| {
327 try printPtrDerivation(info.parent.*, writer, level, zcu, opt_sema);
328 try printPtrDerivation(info.parent.*, writer, level, pt, opt_sema);
328329 try writer.writeAll(".?");
329330 },
330331 .field_ptr => |field| {
331 try printPtrDerivation(field.parent.*, writer, level, zcu, opt_sema);
332 const agg_ty = (try field.parent.ptrType(zcu)).childType(zcu);
332 try printPtrDerivation(field.parent.*, writer, level, pt, opt_sema);
333 const agg_ty = (try field.parent.ptrType(pt)).childType(zcu);
333334 switch (agg_ty.zigTypeTag(zcu)) {
334335 .Struct => if (agg_ty.structFieldName(field.field_idx, zcu).unwrap()) |field_name| {
335336 try writer.print(".{i}", .{field_name.fmt(ip)});
......@@ -350,16 +351,16 @@ fn printPtrDerivation(derivation: Value.PointerDeriveStep, writer: anytype, leve
350351 }
351352 },
352353 .elem_ptr => |elem| {
353 try printPtrDerivation(elem.parent.*, writer, level, zcu, opt_sema);
354 try printPtrDerivation(elem.parent.*, writer, level, pt, opt_sema);
354355 try writer.print("[{d}]", .{elem.elem_idx});
355356 },
356357 .offset_and_cast => |oac| if (oac.byte_offset == 0) {
357 try writer.print("@as({}, @ptrCast(", .{oac.new_ptr_ty.fmt(zcu)});
358 try printPtrDerivation(oac.parent.*, writer, level, zcu, opt_sema);
358 try writer.print("@as({}, @ptrCast(", .{oac.new_ptr_ty.fmt(pt)});
359 try printPtrDerivation(oac.parent.*, writer, level, pt, opt_sema);
359360 try writer.writeAll("))");
360361 } else {
361 try writer.print("@as({}, @ptrFromInt(@intFromPtr(", .{oac.new_ptr_ty.fmt(zcu)});
362 try printPtrDerivation(oac.parent.*, writer, level, zcu, opt_sema);
362 try writer.print("@as({}, @ptrFromInt(@intFromPtr(", .{oac.new_ptr_ty.fmt(pt)});
363 try printPtrDerivation(oac.parent.*, writer, level, pt, opt_sema);
363364 try writer.print(") + {d}))", .{oac.byte_offset});
364365 },
365366 }
src/print_zir.zig+4-5
......@@ -7,13 +7,12 @@ const InternPool = @import("InternPool.zig");
77
88const Zir = std.zig.Zir;
99const Zcu = @import("Zcu.zig");
10const Module = Zcu;
1110const LazySrcLoc = Zcu.LazySrcLoc;
1211
1312/// Write human-readable, debug formatted ZIR code to a file.
1413pub fn renderAsTextToFile(
1514 gpa: Allocator,
16 scope_file: *Module.File,
15 scope_file: *Zcu.File,
1716 fs_file: std.fs.File,
1817) !void {
1918 var arena = std.heap.ArenaAllocator.init(gpa);
......@@ -64,7 +63,7 @@ pub fn renderInstructionContext(
6463 gpa: Allocator,
6564 block: []const Zir.Inst.Index,
6665 block_index: usize,
67 scope_file: *Module.File,
66 scope_file: *Zcu.File,
6867 parent_decl_node: Ast.Node.Index,
6968 indent: u32,
7069 stream: anytype,
......@@ -96,7 +95,7 @@ pub fn renderInstructionContext(
9695pub fn renderSingleInstruction(
9796 gpa: Allocator,
9897 inst: Zir.Inst.Index,
99 scope_file: *Module.File,
98 scope_file: *Zcu.File,
10099 parent_decl_node: Ast.Node.Index,
101100 indent: u32,
102101 stream: anytype,
......@@ -122,7 +121,7 @@ pub fn renderSingleInstruction(
122121const Writer = struct {
123122 gpa: Allocator,
124123 arena: Allocator,
125 file: *Module.File,
124 file: *Zcu.File,
126125 code: Zir,
127126 indent: u32,
128127 parent_decl_node: Ast.Node.Index,
src/register_manager.zig-2
......@@ -7,8 +7,6 @@ const Air = @import("Air.zig");
77const StaticBitSet = std.bit_set.StaticBitSet;
88const Type = @import("Type.zig");
99const Zcu = @import("Zcu.zig");
10/// Deprecated.
11const Module = Zcu;
1210const expect = std.testing.expect;
1311const expectEqual = std.testing.expectEqual;
1412const expectEqualSlices = std.testing.expectEqualSlices;
src/target.zig+36-14
......@@ -537,20 +537,42 @@ pub fn zigBackend(target: std.Target, use_llvm: bool) std.builtin.CompilerBacken
537537 };
538538}
539539
540pub fn backendSupportsFeature(
541 cpu_arch: std.Target.Cpu.Arch,
542 ofmt: std.Target.ObjectFormat,
543 use_llvm: bool,
544 feature: Feature,
545) bool {
540pub inline fn backendSupportsFeature(backend: std.builtin.CompilerBackend, comptime feature: Feature) bool {
546541 return switch (feature) {
547 .panic_fn => ofmt == .c or use_llvm or cpu_arch == .x86_64 or cpu_arch == .riscv64,
548 .panic_unwrap_error => ofmt == .c or use_llvm,
549 .safety_check_formatted => ofmt == .c or use_llvm,
550 .error_return_trace => use_llvm,
551 .is_named_enum_value => use_llvm,
552 .error_set_has_value => use_llvm or cpu_arch.isWasm(),
553 .field_reordering => ofmt == .c or use_llvm,
554 .safety_checked_instructions => use_llvm,
542 .panic_fn => switch (backend) {
543 .stage2_c, .stage2_llvm, .stage2_x86_64, .stage2_riscv64 => true,
544 else => false,
545 },
546 .panic_unwrap_error => switch (backend) {
547 .stage2_c, .stage2_llvm => true,
548 else => false,
549 },
550 .safety_check_formatted => switch (backend) {
551 .stage2_c, .stage2_llvm => true,
552 else => false,
553 },
554 .error_return_trace => switch (backend) {
555 .stage2_llvm => true,
556 else => false,
557 },
558 .is_named_enum_value => switch (backend) {
559 .stage2_llvm => true,
560 else => false,
561 },
562 .error_set_has_value => switch (backend) {
563 .stage2_llvm, .stage2_wasm => true,
564 else => false,
565 },
566 .field_reordering => switch (backend) {
567 .stage2_c, .stage2_llvm => true,
568 else => false,
569 },
570 .safety_checked_instructions => switch (backend) {
571 .stage2_llvm => true,
572 else => false,
573 },
574 .separate_thread => switch (backend) {
575 else => false,
576 },
555577 };
556578}