Commit 6f9c7e33b9

Veikka Tuominen <git@vexu.eu>
2022-11-27 14:37:48
llvm: implement `union_init` for packed unions
Closes #13664
1 parent 34be578
Changed files (3)
src
codegen
test
behavior
src/codegen/llvm.zig
@@ -9228,6 +9228,21 @@ pub const FuncGen = struct {
         const target = self.dg.module.getTarget();
         const layout = union_ty.unionGetLayout(target);
         const union_obj = union_ty.cast(Type.Payload.Union).?.data;
+
+        if (union_obj.layout == .Packed) {
+            const big_bits = union_ty.bitSize(target);
+            const int_llvm_ty = self.dg.context.intType(@intCast(c_uint, big_bits));
+            const field = union_obj.fields.values()[extra.field_index];
+            const non_int_val = try self.resolveInst(extra.init);
+            const ty_bit_size = @intCast(u16, field.ty.bitSize(target));
+            const small_int_ty = self.dg.context.intType(ty_bit_size);
+            const small_int_val = if (field.ty.isPtrAtRuntime())
+                self.builder.buildPtrToInt(non_int_val, small_int_ty, "")
+            else
+                self.builder.buildBitCast(non_int_val, small_int_ty, "");
+            return self.builder.buildZExtOrBitCast(small_int_val, int_llvm_ty, "");
+        }
+
         const tag_int = blk: {
             const tag_ty = union_ty.unionTagTypeHypothetical();
             const union_field_name = union_obj.fields.keys()[extra.field_index];
test/behavior/bugs/13664.zig
@@ -0,0 +1,27 @@
+const std = @import("std");
+const builtin = @import("builtin");
+
+const Fields = packed struct {
+    timestamp: u50,
+    random_bits: u13,
+};
+const ID = packed union {
+    value: u63,
+    fields: Fields,
+};
+fn value() i64 {
+    return 1341;
+}
+test {
+    if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO
+    if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO
+    if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO
+    if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO
+
+    const timestamp: i64 = value();
+    const id = ID{ .fields = Fields{
+        .timestamp = @intCast(u50, timestamp),
+        .random_bits = 420,
+    } };
+    try std.testing.expect((ID{ .value = id.value }).fields.timestamp == timestamp);
+}
test/behavior.zig
@@ -116,6 +116,7 @@ test {
     _ = @import("behavior/bugs/13171.zig");
     _ = @import("behavior/bugs/13285.zig");
     _ = @import("behavior/bugs/13435.zig");
+    _ = @import("behavior/bugs/13664.zig");
     _ = @import("behavior/byteswap.zig");
     _ = @import("behavior/byval_arg_var.zig");
     _ = @import("behavior/call.zig");