authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-07-28 21:57:13-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-07-29 02:29:37-07:00
log4beff80b2f30ad85f2127b1281053b8b25b0cc33
tree9937e9ee95d3060afa021449439caefd6476b5c2
parent2b8e7deeda5d4d0d74f42265a4ddf466f91c8fc2

stage2: codegen handles undefined values

* `optimize_mode` is passed to `link.File` and stored there * improve the debugging function `Module.dumpInst` * get rid of `Value.the_one_possible_value` in favor of a few more specific values for different types. This is less buggy, one less footgun. * `Type.onePossibleValue` now returns a `?Value` instead of `bool`. * codegen handles undefined values. `undef` is a new `MCValue` tag. It uses 0xaa values depending on optimization mode. However optimization mode does not yet support scope overrides. * link.zig: move the `Options` field from `File.Elf` and `File.C` to the base struct. - fix the Tag enum to adhere to style conventions * ZIR now supports emitting undefined values. * Fix the logic of comptime math to properly compare against zero using the `compareWithZero` function.

8 files changed, 248 insertions(+), 120 deletions(-)

src-self-hosted/Module.zig+43-19
......@@ -47,7 +47,6 @@ export_owners: std.AutoHashMapUnmanaged(*Decl, []*Export) = .{},
4747/// Maps fully qualified namespaced names to the Decl struct for them.
4848decl_table: std.HashMapUnmanaged(Scope.NameHash, *Decl, Scope.name_hash_hash, Scope.name_hash_eql, false) = .{},
4949
50optimize_mode: std.builtin.Mode,
5150link_error_flags: link.File.ErrorFlags = .{},
5251
5352work_queue: std.fifo.LinearFifo(WorkItem, .Dynamic),
......@@ -385,18 +384,6 @@ pub const Scope = struct {
385384 };
386385 }
387386
388 pub fn dumpInst(self: *Scope, inst: *Inst) void {
389 const zir_module = self.namespace();
390 const loc = std.zig.findLineColumn(zir_module.source.bytes, inst.src);
391 std.debug.warn("{}:{}:{}: {}: ty={}\n", .{
392 zir_module.sub_file_path,
393 loc.line + 1,
394 loc.column + 1,
395 @tagName(inst.tag),
396 inst.ty,
397 });
398 }
399
400387 /// Asserts the scope has a parent which is a ZIRModule or File and
401388 /// returns the sub_file_path field.
402389 pub fn subFilePath(base: *Scope) []const u8 {
......@@ -802,6 +789,7 @@ pub fn init(gpa: *Allocator, options: InitOptions) !Module {
802789 .output_mode = options.output_mode,
803790 .link_mode = options.link_mode orelse .Static,
804791 .object_format = options.object_format orelse options.target.getObjectFormat(),
792 .optimize_mode = options.optimize_mode,
805793 });
806794 errdefer bin_file.destroy();
807795
......@@ -838,7 +826,6 @@ pub fn init(gpa: *Allocator, options: InitOptions) !Module {
838826 .bin_file_dir = bin_file_dir,
839827 .bin_file_path = options.bin_file_path,
840828 .bin_file = bin_file,
841 .optimize_mode = options.optimize_mode,
842829 .work_queue = std.fifo.LinearFifo(WorkItem, .Dynamic).init(gpa),
843830 .keep_source_files_loaded = options.keep_source_files_loaded,
844831 };
......@@ -894,7 +881,11 @@ fn freeExportList(gpa: *Allocator, export_list: []*Export) void {
894881}
895882
896883pub fn target(self: Module) std.Target {
897 return self.bin_file.options().target;
884 return self.bin_file.options.target;
885}
886
887pub fn optimizeMode(self: Module) std.builtin.Mode {
888 return self.bin_file.options.optimize_mode;
898889}
899890
900891/// Detect changes to source files, perform semantic analysis, and update the output files.
......@@ -1991,14 +1982,14 @@ pub fn constType(self: *Module, scope: *Scope, src: usize, ty: Type) !*Inst {
19911982pub fn constVoid(self: *Module, scope: *Scope, src: usize) !*Inst {
19921983 return self.constInst(scope, src, .{
19931984 .ty = Type.initTag(.void),
1994 .val = Value.initTag(.the_one_possible_value),
1985 .val = Value.initTag(.void_value),
19951986 });
19961987}
19971988
19981989pub fn constNoReturn(self: *Module, scope: *Scope, src: usize) !*Inst {
19991990 return self.constInst(scope, src, .{
20001991 .ty = Type.initTag(.noreturn),
2001 .val = Value.initTag(.the_one_possible_value),
1992 .val = Value.initTag(.unreachable_value),
20021993 });
20031994}
20041995
......@@ -2162,7 +2153,8 @@ pub fn analyzeDeclRefByName(self: *Module, scope: *Scope, src: usize, decl_name:
21622153}
21632154
21642155pub fn wantSafety(self: *Module, scope: *Scope) bool {
2165 return switch (self.optimize_mode) {
2156 // TODO take into account scope's safety overrides
2157 return switch (self.optimizeMode()) {
21662158 .Debug => true,
21672159 .ReleaseSafe => true,
21682160 .ReleaseFast => false,
......@@ -2511,7 +2503,7 @@ pub fn storePtr(self: *Module, scope: *Scope, src: usize, ptr: *Inst, uncasted_v
25112503
25122504 const elem_ty = ptr.ty.elemType();
25132505 const value = try self.coerce(scope, elem_ty, uncasted_value);
2514 if (elem_ty.onePossibleValue())
2506 if (elem_ty.onePossibleValue() != null)
25152507 return self.constVoid(scope, src);
25162508
25172509 // TODO handle comptime pointer writes
......@@ -2803,3 +2795,35 @@ pub fn singleConstPtrType(self: *Module, scope: *Scope, src: usize, elem_ty: Typ
28032795 type_payload.* = .{ .pointee_type = elem_ty };
28042796 return Type.initPayload(&type_payload.base);
28052797}
2798
2799pub fn dumpInst(self: *Module, scope: *Scope, inst: *Inst) void {
2800 const zir_module = scope.namespace();
2801 const source = zir_module.getSource(self) catch @panic("dumpInst failed to get source");
2802 const loc = std.zig.findLineColumn(source, inst.src);
2803 if (inst.tag == .constant) {
2804 std.debug.warn("constant ty={} val={} src={}:{}:{}\n", .{
2805 inst.ty,
2806 inst.castTag(.constant).?.val,
2807 zir_module.subFilePath(),
2808 loc.line + 1,
2809 loc.column + 1,
2810 });
2811 } else if (inst.deaths == 0) {
2812 std.debug.warn("{} ty={} src={}:{}:{}\n", .{
2813 @tagName(inst.tag),
2814 inst.ty,
2815 zir_module.subFilePath(),
2816 loc.line + 1,
2817 loc.column + 1,
2818 });
2819 } else {
2820 std.debug.warn("{} ty={} deaths={b} src={}:{}:{}\n", .{
2821 @tagName(inst.tag),
2822 inst.ty,
2823 inst.deaths,
2824 zir_module.subFilePath(),
2825 loc.line + 1,
2826 loc.column + 1,
2827 });
2828 }
2829}
src-self-hosted/codegen.zig+51-7
......@@ -50,7 +50,7 @@ pub fn generateSymbol(
5050
5151 switch (typed_value.ty.zigTypeTag()) {
5252 .Fn => {
53 switch (bin_file.options.target.cpu.arch) {
53 switch (bin_file.base.options.target.cpu.arch) {
5454 //.arm => return Function(.arm).generateSymbol(bin_file, src, typed_value, code),
5555 //.armeb => return Function(.armeb).generateSymbol(bin_file, src, typed_value, code),
5656 //.aarch64 => return Function(.aarch64).generateSymbol(bin_file, src, typed_value, code),
......@@ -143,7 +143,7 @@ pub fn generateSymbol(
143143 // TODO handle the dependency of this symbol on the decl's vaddr.
144144 // If the decl changes vaddr, then this symbol needs to get regenerated.
145145 const vaddr = bin_file.local_symbols.items[decl.link.local_sym_index].st_value;
146 const endian = bin_file.options.target.cpu.arch.endian();
146 const endian = bin_file.base.options.target.cpu.arch.endian();
147147 switch (bin_file.ptr_width) {
148148 .p32 => {
149149 try code.resize(4);
......@@ -166,7 +166,7 @@ pub fn generateSymbol(
166166 };
167167 },
168168 .Int => {
169 const info = typed_value.ty.intInfo(bin_file.options.target);
169 const info = typed_value.ty.intInfo(bin_file.base.options.target);
170170 if (info.bits == 8 and !info.signed) {
171171 const x = typed_value.val.toUnsignedInt();
172172 try code.append(@intCast(u8, x));
......@@ -230,6 +230,8 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
230230 unreach,
231231 /// No more references to this value remain.
232232 dead,
233 /// The value is undefined.
234 undef,
233235 /// A pointer-sized integer that fits in a register.
234236 /// If the type is a pointer, this is the pointer address in virtual address space.
235237 immediate: u64,
......@@ -282,6 +284,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
282284 .compare_flags_signed,
283285 .ptr_stack_offset,
284286 .ptr_embedded_in_code,
287 .undef,
285288 => false,
286289
287290 .register,
......@@ -360,7 +363,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
360363
361364 var function = Self{
362365 .gpa = bin_file.allocator,
363 .target = &bin_file.options.target,
366 .target = &bin_file.base.options.target,
364367 .bin_file = bin_file,
365368 .mod_fn = module_fn,
366369 .code = code,
......@@ -656,6 +659,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
656659 };
657660 switch (ptr) {
658661 .none => unreachable,
662 .undef => unreachable,
659663 .unreach => unreachable,
660664 .dead => unreachable,
661665 .compare_flags_unsigned => unreachable,
......@@ -687,6 +691,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
687691 const elem_ty = inst.rhs.ty;
688692 switch (ptr) {
689693 .none => unreachable,
694 .undef => unreachable,
690695 .unreach => unreachable,
691696 .dead => unreachable,
692697 .compare_flags_unsigned => unreachable,
......@@ -798,6 +803,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
798803 fn genX8664BinMathCode(self: *Self, src: usize, dst_mcv: MCValue, src_mcv: MCValue, opx: u8, mr: u8) !void {
799804 switch (dst_mcv) {
800805 .none => unreachable,
806 .undef => unreachable,
801807 .dead, .unreach, .immediate => unreachable,
802808 .compare_flags_unsigned => unreachable,
803809 .compare_flags_signed => unreachable,
......@@ -806,6 +812,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
806812 .register => |dst_reg| {
807813 switch (src_mcv) {
808814 .none => unreachable,
815 .undef => try self.genSetReg(src, dst_reg, .undef),
809816 .dead, .unreach => unreachable,
810817 .ptr_stack_offset => unreachable,
811818 .ptr_embedded_in_code => unreachable,
......@@ -905,11 +912,12 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
905912 return self.fail(inst.base.src, "TODO implement calling with parameters in memory", .{});
906913 },
907914 .ptr_stack_offset => {
908 return self.fail(inst.base.src, "TODO implement calling with MCValue.ptr_stack_offset", .{});
915 return self.fail(inst.base.src, "TODO implement calling with MCValue.ptr_stack_offset arg", .{});
909916 },
910917 .ptr_embedded_in_code => {
911 return self.fail(inst.base.src, "TODO implement calling with MCValue.ptr_embedded_in_code", .{});
918 return self.fail(inst.base.src, "TODO implement calling with MCValue.ptr_embedded_in_code arg", .{});
912919 },
920 .undef => unreachable,
913921 .immediate => unreachable,
914922 .unreach => unreachable,
915923 .dead => unreachable,
......@@ -966,6 +974,8 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
966974 .stack_offset => |offset| return MCValue{ .ptr_stack_offset = offset },
967975 .embedded_in_code => |offset| return MCValue{ .ptr_embedded_in_code = offset },
968976 .memory => |vaddr| return MCValue{ .immediate = vaddr },
977
978 .undef => return self.fail(inst.base.src, "TODO implement ref on an undefined value", .{}),
969979 }
970980 }
971981
......@@ -1243,6 +1253,12 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
12431253 .ptr_stack_offset => unreachable,
12441254 .ptr_embedded_in_code => unreachable,
12451255 .unreach, .none => return, // Nothing to do.
1256 .undef => {
1257 if (!self.wantSafety())
1258 return; // The already existing value will do just fine.
1259 // TODO Upgrade this to a memset call when we have that available.
1260 return self.genSetStack(src, ty, stack_offset, .{ .immediate = 0xaaaaaaaa });
1261 },
12461262 .compare_flags_unsigned => |op| {
12471263 return self.fail(src, "TODO implement set stack variable with compare flags value (unsigned)", .{});
12481264 },
......@@ -1250,6 +1266,10 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
12501266 return self.fail(src, "TODO implement set stack variable with compare flags value (signed)", .{});
12511267 },
12521268 .immediate => |x_big| {
1269 if (ty.abiSize(self.target.*) != 4) {
1270 // TODO after fixing this, need to update the undef case above
1271 return self.fail(src, "TODO implement set non 4 abi size stack variable with immediate", .{});
1272 }
12531273 try self.code.ensureCapacity(self.code.items.len + 7);
12541274 if (x_big <= math.maxInt(u32)) {
12551275 const x = @intCast(u32, x_big);
......@@ -1311,6 +1331,18 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
13111331 .ptr_stack_offset => unreachable,
13121332 .ptr_embedded_in_code => unreachable,
13131333 .unreach, .none => return, // Nothing to do.
1334 .undef => {
1335 if (!self.wantSafety())
1336 return; // The already existing value will do just fine.
1337 // Write the debug undefined value.
1338 switch (reg.size()) {
1339 8 => return self.genSetReg(src, reg, .{ .immediate = 0xaa }),
1340 16 => return self.genSetReg(src, reg, .{ .immediate = 0xaaaa }),
1341 32 => return self.genSetReg(src, reg, .{ .immediate = 0xaaaaaaaa }),
1342 64 => return self.genSetReg(src, reg, .{ .immediate = 0xaaaaaaaaaaaaaaaa }),
1343 else => unreachable,
1344 }
1345 },
13141346 .compare_flags_unsigned => |op| {
13151347 try self.code.ensureCapacity(self.code.items.len + 3);
13161348 self.rex(.{ .b = reg.isExtended(), .w = reg.size() == 64 });
......@@ -1471,7 +1503,7 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
14711503 // is no way to possibly encode it. This means that RSP, RBP, R12, and R13 cannot be used with
14721504 // this instruction.
14731505 const id3 = @truncate(u3, reg.id());
1474 std.debug.assert(id3 != 4 and id3 != 5);
1506 assert(id3 != 4 and id3 != 5);
14751507
14761508 // Rather than duplicate the logic used for the move, we just use a self-call with a new MCValue.
14771509 try self.genSetReg(src, reg, MCValue{ .immediate = x });
......@@ -1580,6 +1612,8 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
15801612 }
15811613
15821614 fn genTypedValue(self: *Self, src: usize, typed_value: TypedValue) !MCValue {
1615 if (typed_value.val.isUndef())
1616 return MCValue.undef;
15831617 const ptr_bits = self.target.cpu.arch.ptrBitWidth();
15841618 const ptr_bytes: u64 = @divExact(ptr_bits, 8);
15851619 switch (typed_value.ty.zigTypeTag()) {
......@@ -1691,6 +1725,16 @@ fn Function(comptime arch: std.Target.Cpu.Arch) type {
16911725 return result;
16921726 }
16931727
1728 /// TODO support scope overrides. Also note this logic is duplicated with `Module.wantSafety`.
1729 fn wantSafety(self: *Self) bool {
1730 return switch (self.bin_file.base.options.optimize_mode) {
1731 .Debug => true,
1732 .ReleaseSafe => true,
1733 .ReleaseFast => false,
1734 .ReleaseSmall => false,
1735 };
1736 }
1737
16941738 fn fail(self: *Self, src: usize, comptime format: []const u8, args: anytype) error{ CodegenFail, OutOfMemory } {
16951739 @setCold(true);
16961740 assert(self.err_msg == null);
src-self-hosted/ir.zig+1-2
......@@ -165,8 +165,7 @@ pub const Inst = struct {
165165
166166 /// Returns `null` if runtime-known.
167167 pub fn value(base: *Inst) ?Value {
168 if (base.ty.onePossibleValue())
169 return Value.initTag(.the_one_possible_value);
168 if (base.ty.onePossibleValue()) |opv| return opv;
170169
171170 const inst = base.cast(Constant) orelse return null;
172171 return inst.val;
src-self-hosted/link.zig+63-57
......@@ -16,6 +16,7 @@ pub const Options = struct {
1616 output_mode: std.builtin.OutputMode,
1717 link_mode: std.builtin.LinkMode,
1818 object_format: std.builtin.ObjectFormat,
19 optimize_mode: std.builtin.Mode,
1920 /// Used for calculating how much space to reserve for symbols in case the binary file
2021 /// does not already have a symbol table.
2122 symbol_count_hint: u64 = 32,
......@@ -66,6 +67,7 @@ pub fn writeFilePath(
6667 .link_mode = module.link_mode,
6768 .object_format = module.object_format,
6869 .symbol_count_hint = module.decls.items.len,
70 .optimize_mode = module.optimize_mode,
6971 };
7072 const af = try dir.atomicFile(sub_path, .{ .mode = determineMode(options) });
7173 defer af.deinit();
......@@ -88,9 +90,12 @@ pub fn writeFilePath(
8890
8991fn openCFile(allocator: *Allocator, file: fs.File, options: Options) !File.C {
9092 return File.C{
93 .base = .{
94 .tag = .c,
95 .options = options,
96 },
9197 .allocator = allocator,
9298 .file = file,
93 .options = options,
9499 .main = std.ArrayList(u8).init(allocator),
95100 .header = std.ArrayList(u8).init(allocator),
96101 .constants = std.ArrayList(u8).init(allocator),
......@@ -114,6 +119,8 @@ pub fn openBinFile(allocator: *Allocator, file: fs.File, options: Options) !File
114119
115120pub const File = struct {
116121 tag: Tag,
122 options: Options,
123
117124 pub fn cast(base: *File, comptime T: type) ?*T {
118125 if (base.tag != T.base_tag)
119126 return null;
......@@ -123,47 +130,47 @@ pub const File = struct {
123130
124131 pub fn makeWritable(base: *File, dir: fs.Dir, sub_path: []const u8) !void {
125132 switch (base.tag) {
126 .Elf => return @fieldParentPtr(Elf, "base", base).makeWritable(dir, sub_path),
127 .C => {},
133 .elf => return @fieldParentPtr(Elf, "base", base).makeWritable(dir, sub_path),
134 .c => {},
128135 }
129136 }
130137
131138 pub fn makeExecutable(base: *File) !void {
132139 switch (base.tag) {
133 .Elf => return @fieldParentPtr(Elf, "base", base).makeExecutable(),
134 .C => unreachable,
140 .elf => return @fieldParentPtr(Elf, "base", base).makeExecutable(),
141 .c => unreachable,
135142 }
136143 }
137144
138145 pub fn updateDecl(base: *File, module: *Module, decl: *Module.Decl) !void {
139146 switch (base.tag) {
140 .Elf => return @fieldParentPtr(Elf, "base", base).updateDecl(module, decl),
141 .C => return @fieldParentPtr(C, "base", base).updateDecl(module, decl),
147 .elf => return @fieldParentPtr(Elf, "base", base).updateDecl(module, decl),
148 .c => return @fieldParentPtr(C, "base", base).updateDecl(module, decl),
142149 }
143150 }
144151
145152 pub fn allocateDeclIndexes(base: *File, decl: *Module.Decl) !void {
146153 switch (base.tag) {
147 .Elf => return @fieldParentPtr(Elf, "base", base).allocateDeclIndexes(decl),
148 .C => {},
154 .elf => return @fieldParentPtr(Elf, "base", base).allocateDeclIndexes(decl),
155 .c => {},
149156 }
150157 }
151158
152159 pub fn deinit(base: *File) void {
153160 switch (base.tag) {
154 .Elf => @fieldParentPtr(Elf, "base", base).deinit(),
155 .C => @fieldParentPtr(C, "base", base).deinit(),
161 .elf => @fieldParentPtr(Elf, "base", base).deinit(),
162 .c => @fieldParentPtr(C, "base", base).deinit(),
156163 }
157164 }
158165
159166 pub fn destroy(base: *File) void {
160167 switch (base.tag) {
161 .Elf => {
168 .elf => {
162169 const parent = @fieldParentPtr(Elf, "base", base);
163170 parent.deinit();
164171 parent.allocator.destroy(parent);
165172 },
166 .C => {
173 .c => {
167174 const parent = @fieldParentPtr(C, "base", base);
168175 parent.deinit();
169176 parent.allocator.destroy(parent);
......@@ -173,29 +180,22 @@ pub const File = struct {
173180
174181 pub fn flush(base: *File) !void {
175182 try switch (base.tag) {
176 .Elf => @fieldParentPtr(Elf, "base", base).flush(),
177 .C => @fieldParentPtr(C, "base", base).flush(),
183 .elf => @fieldParentPtr(Elf, "base", base).flush(),
184 .c => @fieldParentPtr(C, "base", base).flush(),
178185 };
179186 }
180187
181188 pub fn freeDecl(base: *File, decl: *Module.Decl) void {
182189 switch (base.tag) {
183 .Elf => @fieldParentPtr(Elf, "base", base).freeDecl(decl),
184 .C => unreachable,
190 .elf => @fieldParentPtr(Elf, "base", base).freeDecl(decl),
191 .c => unreachable,
185192 }
186193 }
187194
188195 pub fn errorFlags(base: *File) ErrorFlags {
189196 return switch (base.tag) {
190 .Elf => @fieldParentPtr(Elf, "base", base).error_flags,
191 .C => return .{ .no_entry_point_found = false },
192 };
193 }
194
195 pub fn options(base: *File) Options {
196 return switch (base.tag) {
197 .Elf => @fieldParentPtr(Elf, "base", base).options,
198 .C => @fieldParentPtr(C, "base", base).options,
197 .elf => @fieldParentPtr(Elf, "base", base).error_flags,
198 .c => return .{ .no_entry_point_found = false },
199199 };
200200 }
201201
......@@ -207,14 +207,14 @@ pub const File = struct {
207207 exports: []const *Module.Export,
208208 ) !void {
209209 switch (base.tag) {
210 .Elf => return @fieldParentPtr(Elf, "base", base).updateDeclExports(module, decl, exports),
211 .C => return {},
210 .elf => return @fieldParentPtr(Elf, "base", base).updateDeclExports(module, decl, exports),
211 .c => return {},
212212 }
213213 }
214214
215215 pub const Tag = enum {
216 Elf,
217 C,
216 elf,
217 c,
218218 };
219219
220220 pub const ErrorFlags = struct {
......@@ -222,15 +222,15 @@ pub const File = struct {
222222 };
223223
224224 pub const C = struct {
225 pub const base_tag: Tag = .C;
226 base: File = File{ .tag = base_tag },
225 pub const base_tag: Tag = .c;
226
227 base: File,
227228
228229 allocator: *Allocator,
229230 header: std.ArrayList(u8),
230231 constants: std.ArrayList(u8),
231232 main: std.ArrayList(u8),
232233 file: ?fs.File,
233 options: Options,
234234 called: std.StringHashMap(void),
235235 need_stddef: bool = false,
236236 need_stdint: bool = false,
......@@ -294,13 +294,13 @@ pub const File = struct {
294294 };
295295
296296 pub const Elf = struct {
297 pub const base_tag: Tag = .Elf;
298 base: File = File{ .tag = base_tag },
297 pub const base_tag: Tag = .elf;
298
299 base: File,
299300
300301 allocator: *Allocator,
301302 file: ?fs.File,
302303 owns_file_handle: bool,
303 options: Options,
304304 ptr_width: enum { p32, p64 },
305305
306306 /// Stored in native-endian format, depending on target endianness needs to be bswapped on read/write.
......@@ -460,13 +460,13 @@ pub const File = struct {
460460 self.file = try dir.createFile(sub_path, .{
461461 .truncate = false,
462462 .read = true,
463 .mode = determineMode(self.options),
463 .mode = determineMode(self.base.options),
464464 });
465465 }
466466
467467 /// Returns end pos of collision, if any.
468468 fn detectAllocCollision(self: *Elf, start: u64, size: u64) ?u64 {
469 const small_ptr = self.options.target.cpu.arch.ptrBitWidth() == 32;
469 const small_ptr = self.base.options.target.cpu.arch.ptrBitWidth() == 32;
470470 const ehdr_size: u64 = if (small_ptr) @sizeOf(elf.Elf32_Ehdr) else @sizeOf(elf.Elf64_Ehdr);
471471 if (start < ehdr_size)
472472 return ehdr_size;
......@@ -569,7 +569,7 @@ pub const File = struct {
569569 };
570570 if (self.phdr_load_re_index == null) {
571571 self.phdr_load_re_index = @intCast(u16, self.program_headers.items.len);
572 const file_size = self.options.program_code_size_hint;
572 const file_size = self.base.options.program_code_size_hint;
573573 const p_align = 0x1000;
574574 const off = self.findFreeSpace(file_size, p_align);
575575 std.log.debug(.link, "found PT_LOAD free space 0x{x} to 0x{x}\n", .{ off, off + file_size });
......@@ -588,7 +588,7 @@ pub const File = struct {
588588 }
589589 if (self.phdr_got_index == null) {
590590 self.phdr_got_index = @intCast(u16, self.program_headers.items.len);
591 const file_size = @as(u64, ptr_size) * self.options.symbol_count_hint;
591 const file_size = @as(u64, ptr_size) * self.base.options.symbol_count_hint;
592592 // We really only need ptr alignment but since we are using PROGBITS, linux requires
593593 // page align.
594594 const p_align = 0x1000;
......@@ -671,7 +671,7 @@ pub const File = struct {
671671 self.symtab_section_index = @intCast(u16, self.sections.items.len);
672672 const min_align: u16 = if (small_ptr) @alignOf(elf.Elf32_Sym) else @alignOf(elf.Elf64_Sym);
673673 const each_size: u64 = if (small_ptr) @sizeOf(elf.Elf32_Sym) else @sizeOf(elf.Elf64_Sym);
674 const file_size = self.options.symbol_count_hint * each_size;
674 const file_size = self.base.options.symbol_count_hint * each_size;
675675 const off = self.findFreeSpace(file_size, min_align);
676676 std.log.debug(.link, "found symtab free space 0x{x} to 0x{x}\n", .{ off, off + file_size });
677677
......@@ -726,7 +726,7 @@ pub const File = struct {
726726
727727 /// Commit pending changes and write headers.
728728 pub fn flush(self: *Elf) !void {
729 const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
729 const foreign_endian = self.base.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
730730
731731 // Unfortunately these have to be buffered and done at the end because ELF does not allow
732732 // mixing local and global symbols within a symbol table.
......@@ -845,7 +845,7 @@ pub const File = struct {
845845 }
846846 self.shdr_table_dirty = false;
847847 }
848 if (self.entry_addr == null and self.options.output_mode == .Exe) {
848 if (self.entry_addr == null and self.base.options.output_mode == .Exe) {
849849 std.log.debug(.link, "no_entry_point_found = true\n", .{});
850850 self.error_flags.no_entry_point_found = true;
851851 } else {
......@@ -875,7 +875,7 @@ pub const File = struct {
875875 };
876876 index += 1;
877877
878 const endian = self.options.target.cpu.arch.endian();
878 const endian = self.base.options.target.cpu.arch.endian();
879879 hdr_buf[index] = switch (endian) {
880880 .Little => elf.ELFDATA2LSB,
881881 .Big => elf.ELFDATA2MSB,
......@@ -893,10 +893,10 @@ pub const File = struct {
893893
894894 assert(index == 16);
895895
896 const elf_type = switch (self.options.output_mode) {
896 const elf_type = switch (self.base.options.output_mode) {
897897 .Exe => elf.ET.EXEC,
898898 .Obj => elf.ET.REL,
899 .Lib => switch (self.options.link_mode) {
899 .Lib => switch (self.base.options.link_mode) {
900900 .Static => elf.ET.REL,
901901 .Dynamic => elf.ET.DYN,
902902 },
......@@ -904,7 +904,7 @@ pub const File = struct {
904904 mem.writeInt(u16, hdr_buf[index..][0..2], @enumToInt(elf_type), endian);
905905 index += 2;
906906
907 const machine = self.options.target.cpu.arch.toElfMachine();
907 const machine = self.base.options.target.cpu.arch.toElfMachine();
908908 mem.writeInt(u16, hdr_buf[index..][0..2], @enumToInt(machine), endian);
909909 index += 2;
910910
......@@ -1216,7 +1216,7 @@ pub const File = struct {
12161216 },
12171217 };
12181218
1219 const required_alignment = typed_value.ty.abiAlignment(self.options.target);
1219 const required_alignment = typed_value.ty.abiAlignment(self.base.options.target);
12201220
12211221 const stt_bits: u8 = switch (typed_value.ty.zigTypeTag()) {
12221222 .Fn => elf.STT_FUNC,
......@@ -1361,9 +1361,9 @@ pub const File = struct {
13611361 }
13621362
13631363 fn writeProgHeader(self: *Elf, index: usize) !void {
1364 const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
1364 const foreign_endian = self.base.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
13651365 const offset = self.program_headers.items[index].p_offset;
1366 switch (self.options.target.cpu.arch.ptrBitWidth()) {
1366 switch (self.base.options.target.cpu.arch.ptrBitWidth()) {
13671367 32 => {
13681368 var phdr = [1]elf.Elf32_Phdr{progHeaderTo32(self.program_headers.items[index])};
13691369 if (foreign_endian) {
......@@ -1383,9 +1383,9 @@ pub const File = struct {
13831383 }
13841384
13851385 fn writeSectHeader(self: *Elf, index: usize) !void {
1386 const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
1386 const foreign_endian = self.base.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
13871387 const offset = self.sections.items[index].sh_offset;
1388 switch (self.options.target.cpu.arch.ptrBitWidth()) {
1388 switch (self.base.options.target.cpu.arch.ptrBitWidth()) {
13891389 32 => {
13901390 var shdr: [1]elf.Elf32_Shdr = undefined;
13911391 shdr[0] = sectHeaderTo32(self.sections.items[index]);
......@@ -1433,7 +1433,7 @@ pub const File = struct {
14331433
14341434 self.offset_table_count_dirty = false;
14351435 }
1436 const endian = self.options.target.cpu.arch.endian();
1436 const endian = self.base.options.target.cpu.arch.endian();
14371437 const off = shdr.sh_offset + @as(u64, entry_size) * index;
14381438 switch (self.ptr_width) {
14391439 .p32 => {
......@@ -1475,7 +1475,7 @@ pub const File = struct {
14751475 syms_sect.sh_size = needed_size; // anticipating adding the global symbols later
14761476 self.shdr_table_dirty = true; // TODO look into only writing one section
14771477 }
1478 const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
1478 const foreign_endian = self.base.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
14791479 switch (self.ptr_width) {
14801480 .p32 => {
14811481 var sym = [1]elf.Elf32_Sym{
......@@ -1511,7 +1511,7 @@ pub const File = struct {
15111511 .p32 => @sizeOf(elf.Elf32_Sym),
15121512 .p64 => @sizeOf(elf.Elf64_Sym),
15131513 };
1514 const foreign_endian = self.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
1514 const foreign_endian = self.base.options.target.cpu.arch.endian() != std.Target.current.cpu.arch.endian();
15151515 const global_syms_off = syms_sect.sh_offset + self.local_symbols.items.len * sym_size;
15161516 switch (self.ptr_width) {
15171517 .p32 => {
......@@ -1577,9 +1577,12 @@ pub fn createElfFile(allocator: *Allocator, file: fs.File, options: Options) !Fi
15771577 }
15781578
15791579 var self: File.Elf = .{
1580 .base = .{
1581 .tag = .elf,
1582 .options = options,
1583 },
15801584 .allocator = allocator,
15811585 .file = file,
1582 .options = options,
15831586 .ptr_width = switch (options.target.cpu.arch.ptrBitWidth()) {
15841587 32 => .p32,
15851588 64 => .p64,
......@@ -1637,10 +1640,13 @@ fn openBinFileInner(allocator: *Allocator, file: fs.File, options: Options) !Fil
16371640 .raw => return error.IncrFailed,
16381641 }
16391642 var self: File.Elf = .{
1643 .base = .{
1644 .tag = .elf,
1645 .options = options,
1646 },
16401647 .allocator = allocator,
16411648 .file = file,
16421649 .owns_file_handle = false,
1643 .options = options,
16441650 .ptr_width = switch (options.target.cpu.arch.ptrBitWidth()) {
16451651 32 => .p32,
16461652 64 => .p64,
src-self-hosted/type.zig+22-11
......@@ -1653,7 +1653,7 @@ pub const Type = extern union {
16531653 };
16541654 }
16551655
1656 pub fn onePossibleValue(self: Type) bool {
1656 pub fn onePossibleValue(self: Type) ?Value {
16571657 var ty = self;
16581658 while (true) switch (ty.tag()) {
16591659 .f16,
......@@ -1692,21 +1692,32 @@ pub const Type = extern union {
16921692 .single_const_pointer_to_comptime_int,
16931693 .array_u8_sentinel_0,
16941694 .const_slice_u8,
1695 => return false,
1696
16971695 .c_void,
1698 .void,
1699 .noreturn,
1700 .@"null",
1701 .@"undefined",
1702 => return true,
1696 => return null,
1697
1698 .void => return Value.initTag(.void_value),
1699 .noreturn => return Value.initTag(.unreachable_value),
1700 .@"null" => return Value.initTag(.null_value),
1701 .@"undefined" => return Value.initTag(.undef),
17031702
1704 .int_unsigned => return ty.cast(Payload.IntUnsigned).?.bits == 0,
1705 .int_signed => return ty.cast(Payload.IntSigned).?.bits == 0,
1703 .int_unsigned => {
1704 if (ty.cast(Payload.IntUnsigned).?.bits == 0) {
1705 return Value.initTag(.zero);
1706 } else {
1707 return null;
1708 }
1709 },
1710 .int_signed => {
1711 if (ty.cast(Payload.IntSigned).?.bits == 0) {
1712 return Value.initTag(.zero);
1713 } else {
1714 return null;
1715 }
1716 },
17061717 .array => {
17071718 const array = ty.cast(Payload.Array).?;
17081719 if (array.len == 0)
1709 return true;
1720 return Value.initTag(.empty_array);
17101721 ty = array.elem_type;
17111722 continue;
17121723 },
src-self-hosted/value.zig+50-22
......@@ -63,7 +63,9 @@ pub const Value = extern union {
6363
6464 undef,
6565 zero,
66 the_one_possible_value, // when the type only has one possible value
66 void_value,
67 unreachable_value,
68 empty_array,
6769 null_value,
6870 bool_true,
6971 bool_false, // See last_no_payload_tag below.
......@@ -164,7 +166,9 @@ pub const Value = extern union {
164166 .const_slice_u8_type,
165167 .undef,
166168 .zero,
167 .the_one_possible_value,
169 .void_value,
170 .unreachable_value,
171 .empty_array,
168172 .null_value,
169173 .bool_true,
170174 .bool_false,
......@@ -285,7 +289,8 @@ pub const Value = extern union {
285289 .null_value => return out_stream.writeAll("null"),
286290 .undef => return out_stream.writeAll("undefined"),
287291 .zero => return out_stream.writeAll("0"),
288 .the_one_possible_value => return out_stream.writeAll("(one possible value)"),
292 .void_value => return out_stream.writeAll("{}"),
293 .unreachable_value => return out_stream.writeAll("unreachable"),
289294 .bool_true => return out_stream.writeAll("true"),
290295 .bool_false => return out_stream.writeAll("false"),
291296 .ty => return val.cast(Payload.Ty).?.ty.format("", options, out_stream),
......@@ -312,6 +317,7 @@ pub const Value = extern union {
312317 try out_stream.print("&[{}] ", .{elem_ptr.index});
313318 val = elem_ptr.array_ptr;
314319 },
320 .empty_array => return out_stream.writeAll(".{}"),
315321 .bytes => return std.zig.renderStringLiteral(self.cast(Payload.Bytes).?.data, out_stream),
316322 .repeated => {
317323 try out_stream.writeAll("(repeated) ");
......@@ -388,7 +394,9 @@ pub const Value = extern union {
388394
389395 .undef,
390396 .zero,
391 .the_one_possible_value,
397 .void_value,
398 .unreachable_value,
399 .empty_array,
392400 .bool_true,
393401 .bool_false,
394402 .null_value,
......@@ -460,15 +468,18 @@ pub const Value = extern union {
460468 .decl_ref,
461469 .elem_ptr,
462470 .bytes,
463 .undef,
464471 .repeated,
465472 .float_16,
466473 .float_32,
467474 .float_64,
468475 .float_128,
476 .void_value,
477 .unreachable_value,
478 .empty_array,
469479 => unreachable,
470480
471 .the_one_possible_value, // An integer with one possible value is always zero.
481 .undef => unreachable,
482
472483 .zero,
473484 .bool_false,
474485 => return BigIntMutable.init(&space.limbs, 0).toConst(),
......@@ -532,16 +543,19 @@ pub const Value = extern union {
532543 .decl_ref,
533544 .elem_ptr,
534545 .bytes,
535 .undef,
536546 .repeated,
537547 .float_16,
538548 .float_32,
539549 .float_64,
540550 .float_128,
551 .void_value,
552 .unreachable_value,
553 .empty_array,
541554 => unreachable,
542555
556 .undef => unreachable,
557
543558 .zero,
544 .the_one_possible_value, // an integer with one possible value is always zero
545559 .bool_false,
546560 => return 0,
547561
......@@ -570,7 +584,7 @@ pub const Value = extern union {
570584 .float_64 => @floatCast(T, self.cast(Payload.Float_64).?.val),
571585 .float_128 => @floatCast(T, self.cast(Payload.Float_128).?.val),
572586
573 .zero, .the_one_possible_value => 0,
587 .zero => 0,
574588 .int_u64 => @intToFloat(T, self.cast(Payload.Int_u64).?.int),
575589 // .int_i64 => @intToFloat(f128, self.cast(Payload.Int_i64).?.int),
576590 .int_i64 => @panic("TODO lld: error: undefined symbol: __floatditf"),
......@@ -637,9 +651,11 @@ pub const Value = extern union {
637651 .float_32,
638652 .float_64,
639653 .float_128,
654 .void_value,
655 .unreachable_value,
656 .empty_array,
640657 => unreachable,
641658
642 .the_one_possible_value, // an integer with one possible value is always zero
643659 .zero,
644660 .bool_false,
645661 => return 0,
......@@ -714,11 +730,13 @@ pub const Value = extern union {
714730 .float_32,
715731 .float_64,
716732 .float_128,
733 .void_value,
734 .unreachable_value,
735 .empty_array,
717736 => unreachable,
718737
719738 .zero,
720739 .undef,
721 .the_one_possible_value, // an integer with one possible value is always zero
722740 .bool_false,
723741 => return true,
724742
......@@ -797,13 +815,13 @@ pub const Value = extern union {
797815 // return Value.initPayload(&res_payload.base).copy(allocator);
798816 },
799817 32 => {
800 var res_payload = Value.Payload.Float_32{.val = self.toFloat(f32)};
818 var res_payload = Value.Payload.Float_32{ .val = self.toFloat(f32) };
801819 if (!self.eql(Value.initPayload(&res_payload.base)))
802820 return error.Overflow;
803821 return Value.initPayload(&res_payload.base).copy(allocator);
804822 },
805823 64 => {
806 var res_payload = Value.Payload.Float_64{.val = self.toFloat(f64)};
824 var res_payload = Value.Payload.Float_64{ .val = self.toFloat(f64) };
807825 if (!self.eql(Value.initPayload(&res_payload.base)))
808826 return error.Overflow;
809827 return Value.initPayload(&res_payload.base).copy(allocator);
......@@ -875,7 +893,9 @@ pub const Value = extern union {
875893 .int_i64,
876894 .int_big_positive,
877895 .int_big_negative,
878 .the_one_possible_value,
896 .empty_array,
897 .void_value,
898 .unreachable_value,
879899 => unreachable,
880900
881901 .zero => false,
......@@ -939,10 +959,12 @@ pub const Value = extern union {
939959 .bytes,
940960 .repeated,
941961 .undef,
962 .void_value,
963 .unreachable_value,
964 .empty_array,
942965 => unreachable,
943966
944967 .zero,
945 .the_one_possible_value, // an integer with one possible value is always zero
946968 .bool_false,
947969 => .eq,
948970
......@@ -964,8 +986,8 @@ pub const Value = extern union {
964986 pub fn order(lhs: Value, rhs: Value) std.math.Order {
965987 const lhs_tag = lhs.tag();
966988 const rhs_tag = rhs.tag();
967 const lhs_is_zero = lhs_tag == .zero or lhs_tag == .the_one_possible_value;
968 const rhs_is_zero = rhs_tag == .zero or rhs_tag == .the_one_possible_value;
989 const lhs_is_zero = lhs_tag == .zero;
990 const rhs_is_zero = rhs_tag == .zero;
969991 if (lhs_is_zero) return rhs.orderAgainstZero().invert();
970992 if (rhs_is_zero) return lhs.orderAgainstZero();
971993
......@@ -1071,9 +1093,11 @@ pub const Value = extern union {
10711093 .float_32,
10721094 .float_64,
10731095 .float_128,
1096 .void_value,
1097 .unreachable_value,
1098 .empty_array,
10741099 => unreachable,
10751100
1076 .the_one_possible_value => Value.initTag(.the_one_possible_value),
10771101 .ref_val => self.cast(Payload.RefVal).?.val,
10781102 .decl_ref => self.cast(Payload.DeclRef).?.decl.value(),
10791103 .elem_ptr => {
......@@ -1130,7 +1154,6 @@ pub const Value = extern union {
11301154 .single_const_pointer_to_comptime_int_type,
11311155 .const_slice_u8_type,
11321156 .zero,
1133 .the_one_possible_value,
11341157 .bool_true,
11351158 .bool_false,
11361159 .null_value,
......@@ -1147,8 +1170,12 @@ pub const Value = extern union {
11471170 .float_32,
11481171 .float_64,
11491172 .float_128,
1173 .void_value,
1174 .unreachable_value,
11501175 => unreachable,
11511176
1177 .empty_array => unreachable, // out of bounds array index
1178
11521179 .bytes => {
11531180 const int_payload = try allocator.create(Payload.Int_u64);
11541181 int_payload.* = .{ .int = self.cast(Payload.Bytes).?.data[index] };
......@@ -1175,8 +1202,7 @@ pub const Value = extern union {
11751202 return self.tag() == .undef;
11761203 }
11771204
1178 /// Valid for all types. Asserts the value is not undefined.
1179 /// `.the_one_possible_value` is reported as not null.
1205 /// Valid for all types. Asserts the value is not undefined and not unreachable.
11801206 pub fn isNull(self: Value) bool {
11811207 return switch (self.tag()) {
11821208 .ty,
......@@ -1221,7 +1247,7 @@ pub const Value = extern union {
12211247 .single_const_pointer_to_comptime_int_type,
12221248 .const_slice_u8_type,
12231249 .zero,
1224 .the_one_possible_value,
1250 .empty_array,
12251251 .bool_true,
12261252 .bool_false,
12271253 .function,
......@@ -1238,9 +1264,11 @@ pub const Value = extern union {
12381264 .float_32,
12391265 .float_64,
12401266 .float_128,
1267 .void_value,
12411268 => false,
12421269
12431270 .undef => unreachable,
1271 .unreachable_value => unreachable,
12441272 .null_value => true,
12451273 };
12461274 }
src-self-hosted/zir.zig+16-1
......@@ -742,7 +742,7 @@ pub const Inst = struct {
742742 .@"false" => .{ .ty = Type.initTag(.bool), .val = Value.initTag(.bool_false) },
743743 .@"null" => .{ .ty = Type.initTag(.@"null"), .val = Value.initTag(.null_value) },
744744 .@"undefined" => .{ .ty = Type.initTag(.@"undefined"), .val = Value.initTag(.undef) },
745 .void_value => .{ .ty = Type.initTag(.void), .val = Value.initTag(.the_one_possible_value) },
745 .void_value => .{ .ty = Type.initTag(.void), .val = Value.initTag(.void_value) },
746746 };
747747 }
748748 };
......@@ -1598,6 +1598,21 @@ const EmitZIR = struct {
15981598 const decl = decl_ref.decl;
15991599 return try self.emitUnnamedDecl(try self.emitDeclRef(src, decl));
16001600 }
1601 if (typed_value.val.isUndef()) {
1602 const as_inst = try self.arena.allocator.create(Inst.BinOp);
1603 as_inst.* = .{
1604 .base = .{
1605 .tag = .as,
1606 .src = src,
1607 },
1608 .positionals = .{
1609 .lhs = (try self.emitType(src, typed_value.ty)).inst,
1610 .rhs = (try self.emitPrimitive(src, .@"undefined")).inst,
1611 },
1612 .kw_args = .{},
1613 };
1614 return self.emitUnnamedDecl(&as_inst.base);
1615 }
16011616 switch (typed_value.ty.zigTypeTag()) {
16021617 .Pointer => {
16031618 const ptr_elem_type = typed_value.ty.elemType();
src-self-hosted/zir_sema.zig+2-1
......@@ -882,7 +882,7 @@ fn analyzeInstArithmetic(mod: *Module, scope: *Scope, inst: *zir.Inst.BinOp) Inn
882882fn analyzeInstComptimeOp(mod: *Module, scope: *Scope, res_type: Type, inst: *zir.Inst.BinOp, lhs_val: Value, rhs_val: Value) InnerError!*Inst {
883883 // incase rhs is 0, simply return lhs without doing any calculations
884884 // TODO Once division is implemented we should throw an error when dividing by 0.
885 if (rhs_val.tag() == .zero or rhs_val.tag() == .the_one_possible_value) {
885 if (rhs_val.compareWithZero(.eq)) {
886886 return mod.constInst(scope, inst.base.src, .{
887887 .ty = res_type,
888888 .val = lhs_val,
......@@ -1083,6 +1083,7 @@ fn analyzeInstUnreachNoChk(mod: *Module, scope: *Scope, unreach: *zir.Inst.NoOp)
10831083
10841084fn analyzeInstUnreachable(mod: *Module, scope: *Scope, unreach: *zir.Inst.NoOp) InnerError!*Inst {
10851085 const b = try mod.requireRuntimeBlock(scope, unreach.base.src);
1086 // TODO Add compile error for @optimizeFor occurring too late in a scope.
10861087 if (mod.wantSafety(scope)) {
10871088 // TODO Once we have a panic function to call, call it here instead of this.
10881089 _ = try mod.addNoOp(b, unreach.base.src, Type.initTag(.void), .breakpoint);