-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy pathType.zig
4147 lines (3773 loc) · 154 KB
/
Type.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Both types and values are canonically represented by a single 32-bit integer
//! which is an index into an `InternPool` data structure.
//! This struct abstracts around this storage by providing methods only
//! applicable to types rather than values in general.
const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const Value = @import("Value.zig");
const assert = std.debug.assert;
const Target = std.Target;
const Zcu = @import("Zcu.zig");
const log = std.log.scoped(.Type);
const target_util = @import("target.zig");
const Sema = @import("Sema.zig");
const InternPool = @import("InternPool.zig");
const Alignment = InternPool.Alignment;
const Zir = std.zig.Zir;
const Type = @This();
const SemaError = Zcu.SemaError;
ip_index: InternPool.Index,
pub fn zigTypeTag(ty: Type, zcu: *const Zcu) std.builtin.TypeId {
return zcu.intern_pool.zigTypeTag(ty.toIntern());
}
pub fn baseZigTypeTag(self: Type, mod: *Zcu) std.builtin.TypeId {
return switch (self.zigTypeTag(mod)) {
.error_union => self.errorUnionPayload(mod).baseZigTypeTag(mod),
.optional => {
return self.optionalChild(mod).baseZigTypeTag(mod);
},
else => |t| t,
};
}
/// Asserts the type is resolved.
pub fn isSelfComparable(ty: Type, zcu: *const Zcu, is_equality_cmp: bool) bool {
return switch (ty.zigTypeTag(zcu)) {
.int,
.float,
.comptime_float,
.comptime_int,
=> true,
.vector => ty.elemType2(zcu).isSelfComparable(zcu, is_equality_cmp),
.bool,
.type,
.void,
.error_set,
.@"fn",
.@"opaque",
.@"anyframe",
.@"enum",
.enum_literal,
=> is_equality_cmp,
.noreturn,
.array,
.undefined,
.null,
.error_union,
.@"union",
.frame,
=> false,
.@"struct" => is_equality_cmp and ty.containerLayout(zcu) == .@"packed",
.pointer => !ty.isSlice(zcu) and (is_equality_cmp or ty.isCPtr(zcu)),
.optional => {
if (!is_equality_cmp) return false;
return ty.optionalChild(zcu).isSelfComparable(zcu, is_equality_cmp);
},
};
}
/// If it is a function pointer, returns the function type. Otherwise returns null.
pub fn castPtrToFn(ty: Type, zcu: *const Zcu) ?Type {
if (ty.zigTypeTag(zcu) != .pointer) return null;
const elem_ty = ty.childType(zcu);
if (elem_ty.zigTypeTag(zcu) != .@"fn") return null;
return elem_ty;
}
/// Asserts the type is a pointer.
pub fn ptrIsMutable(ty: Type, zcu: *const Zcu) bool {
return !zcu.intern_pool.indexToKey(ty.toIntern()).ptr_type.flags.is_const;
}
pub const ArrayInfo = struct {
elem_type: Type,
sentinel: ?Value = null,
len: u64,
};
pub fn arrayInfo(self: Type, zcu: *const Zcu) ArrayInfo {
return .{
.len = self.arrayLen(zcu),
.sentinel = self.sentinel(zcu),
.elem_type = self.childType(zcu),
};
}
pub fn ptrInfo(ty: Type, zcu: *const Zcu) InternPool.Key.PtrType {
return switch (zcu.intern_pool.indexToKey(ty.toIntern())) {
.ptr_type => |p| p,
.opt_type => |child| switch (zcu.intern_pool.indexToKey(child)) {
.ptr_type => |p| p,
else => unreachable,
},
else => unreachable,
};
}
pub fn eql(a: Type, b: Type, zcu: *const Zcu) bool {
_ = zcu; // TODO: remove this parameter
// The InternPool data structure hashes based on Key to make interned objects
// unique. An Index can be treated simply as u32 value for the
// purpose of Type/Value hashing and equality.
return a.toIntern() == b.toIntern();
}
pub fn format(ty: Type, comptime unused_fmt_string: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = ty;
_ = unused_fmt_string;
_ = options;
_ = writer;
@compileError("do not format types directly; use either ty.fmtDebug() or ty.fmt()");
}
pub const Formatter = std.fmt.Formatter(format2);
pub fn fmt(ty: Type, pt: Zcu.PerThread) Formatter {
return .{ .data = .{
.ty = ty,
.pt = pt,
} };
}
const FormatContext = struct {
ty: Type,
pt: Zcu.PerThread,
};
fn format2(
ctx: FormatContext,
comptime unused_format_string: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) !void {
comptime assert(unused_format_string.len == 0);
_ = options;
return print(ctx.ty, writer, ctx.pt);
}
pub fn fmtDebug(ty: Type) std.fmt.Formatter(dump) {
return .{ .data = ty };
}
/// This is a debug function. In order to print types in a meaningful way
/// we also need access to the module.
pub fn dump(
start_type: Type,
comptime unused_format_string: []const u8,
options: std.fmt.FormatOptions,
writer: anytype,
) @TypeOf(writer).Error!void {
_ = options;
comptime assert(unused_format_string.len == 0);
return writer.print("{any}", .{start_type.ip_index});
}
/// Prints a name suitable for `@typeName`.
/// TODO: take an `opt_sema` to pass to `fmtValue` when printing sentinels.
pub fn print(ty: Type, writer: anytype, pt: Zcu.PerThread) @TypeOf(writer).Error!void {
const zcu = pt.zcu;
const ip = &zcu.intern_pool;
switch (ip.indexToKey(ty.toIntern())) {
.int_type => |int_type| {
const sign_char: u8 = switch (int_type.signedness) {
.signed => 'i',
.unsigned => 'u',
};
return writer.print("{c}{d}", .{ sign_char, int_type.bits });
},
.ptr_type => {
const info = ty.ptrInfo(zcu);
if (info.sentinel != .none) switch (info.flags.size) {
.one, .c => unreachable,
.many => try writer.print("[*:{}]", .{Value.fromInterned(info.sentinel).fmtValue(pt)}),
.slice => try writer.print("[:{}]", .{Value.fromInterned(info.sentinel).fmtValue(pt)}),
} else switch (info.flags.size) {
.one => try writer.writeAll("*"),
.many => try writer.writeAll("[*]"),
.c => try writer.writeAll("[*c]"),
.slice => try writer.writeAll("[]"),
}
if (info.flags.is_allowzero and info.flags.size != .c) try writer.writeAll("allowzero ");
if (info.flags.alignment != .none or
info.packed_offset.host_size != 0 or
info.flags.vector_index != .none)
{
const alignment = if (info.flags.alignment != .none)
info.flags.alignment
else
Type.fromInterned(info.child).abiAlignment(pt.zcu);
try writer.print("align({d}", .{alignment.toByteUnits() orelse 0});
if (info.packed_offset.bit_offset != 0 or info.packed_offset.host_size != 0) {
try writer.print(":{d}:{d}", .{
info.packed_offset.bit_offset, info.packed_offset.host_size,
});
}
if (info.flags.vector_index == .runtime) {
try writer.writeAll(":?");
} else if (info.flags.vector_index != .none) {
try writer.print(":{d}", .{@intFromEnum(info.flags.vector_index)});
}
try writer.writeAll(") ");
}
if (info.flags.address_space != .generic) {
try writer.print("addrspace(.{s}) ", .{@tagName(info.flags.address_space)});
}
if (info.flags.is_const) try writer.writeAll("const ");
if (info.flags.is_volatile) try writer.writeAll("volatile ");
try print(Type.fromInterned(info.child), writer, pt);
return;
},
.array_type => |array_type| {
if (array_type.sentinel == .none) {
try writer.print("[{d}]", .{array_type.len});
try print(Type.fromInterned(array_type.child), writer, pt);
} else {
try writer.print("[{d}:{}]", .{
array_type.len,
Value.fromInterned(array_type.sentinel).fmtValue(pt),
});
try print(Type.fromInterned(array_type.child), writer, pt);
}
return;
},
.vector_type => |vector_type| {
try writer.print("@Vector({d}, ", .{vector_type.len});
try print(Type.fromInterned(vector_type.child), writer, pt);
try writer.writeAll(")");
return;
},
.opt_type => |child| {
try writer.writeByte('?');
return print(Type.fromInterned(child), writer, pt);
},
.error_union_type => |error_union_type| {
try print(Type.fromInterned(error_union_type.error_set_type), writer, pt);
try writer.writeByte('!');
if (error_union_type.payload_type == .generic_poison_type) {
try writer.writeAll("anytype");
} else {
try print(Type.fromInterned(error_union_type.payload_type), writer, pt);
}
return;
},
.inferred_error_set_type => |func_index| {
const func_nav = ip.getNav(zcu.funcInfo(func_index).owner_nav);
try writer.print("@typeInfo(@typeInfo(@TypeOf({})).@\"fn\".return_type.?).error_union.error_set", .{
func_nav.fqn.fmt(ip),
});
},
.error_set_type => |error_set_type| {
const names = error_set_type.names;
try writer.writeAll("error{");
for (names.get(ip), 0..) |name, i| {
if (i != 0) try writer.writeByte(',');
try writer.print("{}", .{name.fmt(ip)});
}
try writer.writeAll("}");
},
.simple_type => |s| switch (s) {
.f16,
.f32,
.f64,
.f80,
.f128,
.usize,
.isize,
.c_char,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.c_longdouble,
.anyopaque,
.bool,
.void,
.type,
.anyerror,
.comptime_int,
.comptime_float,
.noreturn,
.adhoc_inferred_error_set,
=> return writer.writeAll(@tagName(s)),
.null,
.undefined,
=> try writer.print("@TypeOf({s})", .{@tagName(s)}),
.enum_literal => try writer.writeAll("@Type(.enum_literal)"),
.generic_poison => unreachable,
},
.struct_type => {
const name = ip.loadStructType(ty.toIntern()).name;
try writer.print("{}", .{name.fmt(ip)});
},
.tuple_type => |tuple| {
if (tuple.types.len == 0) {
return writer.writeAll("@TypeOf(.{})");
}
try writer.writeAll("struct {");
for (tuple.types.get(ip), tuple.values.get(ip), 0..) |field_ty, val, i| {
try writer.writeAll(if (i == 0) " " else ", ");
if (val != .none) try writer.writeAll("comptime ");
try print(Type.fromInterned(field_ty), writer, pt);
if (val != .none) try writer.print(" = {}", .{Value.fromInterned(val).fmtValue(pt)});
}
try writer.writeAll(" }");
},
.union_type => {
const name = ip.loadUnionType(ty.toIntern()).name;
try writer.print("{}", .{name.fmt(ip)});
},
.opaque_type => {
const name = ip.loadOpaqueType(ty.toIntern()).name;
try writer.print("{}", .{name.fmt(ip)});
},
.enum_type => {
const name = ip.loadEnumType(ty.toIntern()).name;
try writer.print("{}", .{name.fmt(ip)});
},
.func_type => |fn_info| {
if (fn_info.is_noinline) {
try writer.writeAll("noinline ");
}
try writer.writeAll("fn (");
const param_types = fn_info.param_types.get(&zcu.intern_pool);
for (param_types, 0..) |param_ty, i| {
if (i != 0) try writer.writeAll(", ");
if (std.math.cast(u5, i)) |index| {
if (fn_info.paramIsComptime(index)) {
try writer.writeAll("comptime ");
}
if (fn_info.paramIsNoalias(index)) {
try writer.writeAll("noalias ");
}
}
if (param_ty == .generic_poison_type) {
try writer.writeAll("anytype");
} else {
try print(Type.fromInterned(param_ty), writer, pt);
}
}
if (fn_info.is_var_args) {
if (param_types.len != 0) {
try writer.writeAll(", ");
}
try writer.writeAll("...");
}
try writer.writeAll(") ");
if (fn_info.cc != .auto) print_cc: {
if (zcu.getTarget().cCallingConvention()) |ccc| {
if (fn_info.cc.eql(ccc)) {
try writer.writeAll("callconv(.c) ");
break :print_cc;
}
}
switch (fn_info.cc) {
.auto, .@"async", .naked, .@"inline" => try writer.print("callconv(.{}) ", .{std.zig.fmtId(@tagName(fn_info.cc))}),
else => try writer.print("callconv({any}) ", .{fn_info.cc}),
}
}
if (fn_info.return_type == .generic_poison_type) {
try writer.writeAll("anytype");
} else {
try print(Type.fromInterned(fn_info.return_type), writer, pt);
}
},
.anyframe_type => |child| {
if (child == .none) return writer.writeAll("anyframe");
try writer.writeAll("anyframe->");
return print(Type.fromInterned(child), writer, pt);
},
// values, not types
.undef,
.simple_value,
.variable,
.@"extern",
.func,
.int,
.err,
.error_union,
.enum_literal,
.enum_tag,
.empty_enum_value,
.float,
.ptr,
.slice,
.opt,
.aggregate,
.un,
// memoization, not types
.memoized_call,
=> unreachable,
}
}
pub fn fromInterned(i: InternPool.Index) Type {
assert(i != .none);
return .{ .ip_index = i };
}
pub fn toIntern(ty: Type) InternPool.Index {
assert(ty.ip_index != .none);
return ty.ip_index;
}
pub fn toValue(self: Type) Value {
return Value.fromInterned(self.toIntern());
}
const RuntimeBitsError = SemaError || error{NeedLazy};
pub fn hasRuntimeBits(ty: Type, zcu: *const Zcu) bool {
return hasRuntimeBitsInner(ty, false, .eager, zcu, {}) catch unreachable;
}
pub fn hasRuntimeBitsSema(ty: Type, pt: Zcu.PerThread) SemaError!bool {
return hasRuntimeBitsInner(ty, false, .sema, pt.zcu, pt.tid) catch |err| switch (err) {
error.NeedLazy => unreachable, // this would require a resolve strat of lazy
else => |e| return e,
};
}
pub fn hasRuntimeBitsIgnoreComptime(ty: Type, zcu: *const Zcu) bool {
return hasRuntimeBitsInner(ty, true, .eager, zcu, {}) catch unreachable;
}
pub fn hasRuntimeBitsIgnoreComptimeSema(ty: Type, pt: Zcu.PerThread) SemaError!bool {
return hasRuntimeBitsInner(ty, true, .sema, pt.zcu, pt.tid) catch |err| switch (err) {
error.NeedLazy => unreachable, // this would require a resolve strat of lazy
else => |e| return e,
};
}
/// true if and only if the type takes up space in memory at runtime.
/// There are two reasons a type will return false:
/// * the type is a comptime-only type. For example, the type `type` itself.
/// - note, however, that a struct can have mixed fields and only the non-comptime-only
/// fields will count towards the ABI size. For example, `struct {T: type, x: i32}`
/// hasRuntimeBits()=true and abiSize()=4
/// * the type has only one possible value, making its ABI size 0.
/// - an enum with an explicit tag type has the ABI size of the integer tag type,
/// making it one-possible-value only if the integer tag type has 0 bits.
/// When `ignore_comptime_only` is true, then types that are comptime-only
/// may return false positives.
pub fn hasRuntimeBitsInner(
ty: Type,
ignore_comptime_only: bool,
comptime strat: ResolveStratLazy,
zcu: strat.ZcuPtr(),
tid: strat.Tid(),
) RuntimeBitsError!bool {
const ip = &zcu.intern_pool;
return switch (ty.toIntern()) {
.empty_tuple_type => false,
else => switch (ip.indexToKey(ty.toIntern())) {
.int_type => |int_type| int_type.bits != 0,
.ptr_type => {
// Pointers to zero-bit types still have a runtime address; however, pointers
// to comptime-only types do not, with the exception of function pointers.
if (ignore_comptime_only) return true;
return switch (strat) {
.sema => {
const pt = strat.pt(zcu, tid);
return !try ty.comptimeOnlySema(pt);
},
.eager => !ty.comptimeOnly(zcu),
.lazy => error.NeedLazy,
};
},
.anyframe_type => true,
.array_type => |array_type| return array_type.lenIncludingSentinel() > 0 and
try Type.fromInterned(array_type.child).hasRuntimeBitsInner(ignore_comptime_only, strat, zcu, tid),
.vector_type => |vector_type| return vector_type.len > 0 and
try Type.fromInterned(vector_type.child).hasRuntimeBitsInner(ignore_comptime_only, strat, zcu, tid),
.opt_type => |child| {
const child_ty = Type.fromInterned(child);
if (child_ty.isNoReturn(zcu)) {
// Then the optional is comptime-known to be null.
return false;
}
if (ignore_comptime_only) return true;
return switch (strat) {
.sema => !try child_ty.comptimeOnlyInner(.sema, zcu, tid),
.eager => !child_ty.comptimeOnly(zcu),
.lazy => error.NeedLazy,
};
},
.error_union_type,
.error_set_type,
.inferred_error_set_type,
=> true,
// These are function *bodies*, not pointers.
// They return false here because they are comptime-only types.
// Special exceptions have to be made when emitting functions due to
// this returning false.
.func_type => false,
.simple_type => |t| switch (t) {
.f16,
.f32,
.f64,
.f80,
.f128,
.usize,
.isize,
.c_char,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.c_longdouble,
.bool,
.anyerror,
.adhoc_inferred_error_set,
.anyopaque,
=> true,
// These are false because they are comptime-only types.
.void,
.type,
.comptime_int,
.comptime_float,
.noreturn,
.null,
.undefined,
.enum_literal,
=> false,
.generic_poison => unreachable,
},
.struct_type => {
const struct_type = ip.loadStructType(ty.toIntern());
if (strat != .eager and struct_type.assumeRuntimeBitsIfFieldTypesWip(ip)) {
// In this case, we guess that hasRuntimeBits() for this type is true,
// and then later if our guess was incorrect, we emit a compile error.
return true;
}
switch (strat) {
.sema => try ty.resolveFields(strat.pt(zcu, tid)),
.eager => assert(struct_type.haveFieldTypes(ip)),
.lazy => if (!struct_type.haveFieldTypes(ip)) return error.NeedLazy,
}
for (0..struct_type.field_types.len) |i| {
if (struct_type.comptime_bits.getBit(ip, i)) continue;
const field_ty = Type.fromInterned(struct_type.field_types.get(ip)[i]);
if (try field_ty.hasRuntimeBitsInner(ignore_comptime_only, strat, zcu, tid))
return true;
} else {
return false;
}
},
.tuple_type => |tuple| {
for (tuple.types.get(ip), tuple.values.get(ip)) |field_ty, val| {
if (val != .none) continue; // comptime field
if (try Type.fromInterned(field_ty).hasRuntimeBitsInner(
ignore_comptime_only,
strat,
zcu,
tid,
)) return true;
}
return false;
},
.union_type => {
const union_type = ip.loadUnionType(ty.toIntern());
const union_flags = union_type.flagsUnordered(ip);
switch (union_flags.runtime_tag) {
.none => if (strat != .eager) {
// In this case, we guess that hasRuntimeBits() for this type is true,
// and then later if our guess was incorrect, we emit a compile error.
if (union_type.assumeRuntimeBitsIfFieldTypesWip(ip)) return true;
},
.safety, .tagged => {},
}
switch (strat) {
.sema => try ty.resolveFields(strat.pt(zcu, tid)),
.eager => assert(union_flags.status.haveFieldTypes()),
.lazy => if (!union_flags.status.haveFieldTypes())
return error.NeedLazy,
}
switch (union_flags.runtime_tag) {
.none => {},
.safety, .tagged => {
const tag_ty = union_type.tagTypeUnordered(ip);
assert(tag_ty != .none); // tag_ty should have been resolved above
if (try Type.fromInterned(tag_ty).hasRuntimeBitsInner(
ignore_comptime_only,
strat,
zcu,
tid,
)) {
return true;
}
},
}
for (0..union_type.field_types.len) |field_index| {
const field_ty = Type.fromInterned(union_type.field_types.get(ip)[field_index]);
if (try field_ty.hasRuntimeBitsInner(ignore_comptime_only, strat, zcu, tid))
return true;
} else {
return false;
}
},
.opaque_type => true,
.enum_type => Type.fromInterned(ip.loadEnumType(ty.toIntern()).tag_ty).hasRuntimeBitsInner(
ignore_comptime_only,
strat,
zcu,
tid,
),
// values, not types
.undef,
.simple_value,
.variable,
.@"extern",
.func,
.int,
.err,
.error_union,
.enum_literal,
.enum_tag,
.empty_enum_value,
.float,
.ptr,
.slice,
.opt,
.aggregate,
.un,
// memoization, not types
.memoized_call,
=> unreachable,
},
};
}
/// true if and only if the type has a well-defined memory layout
/// readFrom/writeToMemory are supported only for types with a well-
/// defined memory layout
pub fn hasWellDefinedLayout(ty: Type, zcu: *const Zcu) bool {
const ip = &zcu.intern_pool;
return switch (ip.indexToKey(ty.toIntern())) {
.int_type,
.vector_type,
=> true,
.error_union_type,
.error_set_type,
.inferred_error_set_type,
.tuple_type,
.opaque_type,
.anyframe_type,
// These are function bodies, not function pointers.
.func_type,
=> false,
.array_type => |array_type| Type.fromInterned(array_type.child).hasWellDefinedLayout(zcu),
.opt_type => ty.isPtrLikeOptional(zcu),
.ptr_type => |ptr_type| ptr_type.flags.size != .slice,
.simple_type => |t| switch (t) {
.f16,
.f32,
.f64,
.f80,
.f128,
.usize,
.isize,
.c_char,
.c_short,
.c_ushort,
.c_int,
.c_uint,
.c_long,
.c_ulong,
.c_longlong,
.c_ulonglong,
.c_longdouble,
.bool,
.void,
=> true,
.anyerror,
.adhoc_inferred_error_set,
.anyopaque,
.type,
.comptime_int,
.comptime_float,
.noreturn,
.null,
.undefined,
.enum_literal,
.generic_poison,
=> false,
},
.struct_type => ip.loadStructType(ty.toIntern()).layout != .auto,
.union_type => {
const union_type = ip.loadUnionType(ty.toIntern());
return switch (union_type.flagsUnordered(ip).runtime_tag) {
.none, .safety => union_type.flagsUnordered(ip).layout != .auto,
.tagged => false,
};
},
.enum_type => switch (ip.loadEnumType(ty.toIntern()).tag_mode) {
.auto => false,
.explicit, .nonexhaustive => true,
},
// values, not types
.undef,
.simple_value,
.variable,
.@"extern",
.func,
.int,
.err,
.error_union,
.enum_literal,
.enum_tag,
.empty_enum_value,
.float,
.ptr,
.slice,
.opt,
.aggregate,
.un,
// memoization, not types
.memoized_call,
=> unreachable,
};
}
pub fn fnHasRuntimeBits(ty: Type, zcu: *Zcu) bool {
return ty.fnHasRuntimeBitsInner(.normal, zcu, {}) catch unreachable;
}
pub fn fnHasRuntimeBitsSema(ty: Type, pt: Zcu.PerThread) SemaError!bool {
return try ty.fnHasRuntimeBitsInner(.sema, pt.zcu, pt.tid);
}
/// Determines whether a function type has runtime bits, i.e. whether a
/// function with this type can exist at runtime.
/// Asserts that `ty` is a function type.
pub fn fnHasRuntimeBitsInner(
ty: Type,
comptime strat: ResolveStrat,
zcu: strat.ZcuPtr(),
tid: strat.Tid(),
) SemaError!bool {
const fn_info = zcu.typeToFunc(ty).?;
if (fn_info.is_generic) return false;
if (fn_info.is_var_args) return true;
if (fn_info.cc == .@"inline") return false;
return !try Type.fromInterned(fn_info.return_type).comptimeOnlyInner(strat, zcu, tid);
}
pub fn isFnOrHasRuntimeBits(ty: Type, zcu: *Zcu) bool {
switch (ty.zigTypeTag(zcu)) {
.@"fn" => return ty.fnHasRuntimeBits(zcu),
else => return ty.hasRuntimeBits(zcu),
}
}
/// Same as `isFnOrHasRuntimeBits` but comptime-only types may return a false positive.
pub fn isFnOrHasRuntimeBitsIgnoreComptime(ty: Type, zcu: *Zcu) bool {
return switch (ty.zigTypeTag(zcu)) {
.@"fn" => true,
else => return ty.hasRuntimeBitsIgnoreComptime(zcu),
};
}
pub fn isNoReturn(ty: Type, zcu: *const Zcu) bool {
return zcu.intern_pool.isNoReturn(ty.toIntern());
}
/// Never returns `none`. Asserts that all necessary type resolution is already done.
pub fn ptrAlignment(ty: Type, zcu: *Zcu) Alignment {
return ptrAlignmentInner(ty, .normal, zcu, {}) catch unreachable;
}
pub fn ptrAlignmentSema(ty: Type, pt: Zcu.PerThread) SemaError!Alignment {
return try ty.ptrAlignmentInner(.sema, pt.zcu, pt.tid);
}
pub fn ptrAlignmentInner(
ty: Type,
comptime strat: ResolveStrat,
zcu: strat.ZcuPtr(),
tid: strat.Tid(),
) !Alignment {
return switch (zcu.intern_pool.indexToKey(ty.toIntern())) {
.ptr_type => |ptr_type| {
if (ptr_type.flags.alignment != .none) return ptr_type.flags.alignment;
const res = try Type.fromInterned(ptr_type.child).abiAlignmentInner(strat.toLazy(), zcu, tid);
return res.scalar;
},
.opt_type => |child| Type.fromInterned(child).ptrAlignmentInner(strat, zcu, tid),
else => unreachable,
};
}
pub fn ptrAddressSpace(ty: Type, zcu: *const Zcu) std.builtin.AddressSpace {
return switch (zcu.intern_pool.indexToKey(ty.toIntern())) {
.ptr_type => |ptr_type| ptr_type.flags.address_space,
.opt_type => |child| zcu.intern_pool.indexToKey(child).ptr_type.flags.address_space,
else => unreachable,
};
}
/// May capture a reference to `ty`.
/// Returned value has type `comptime_int`.
pub fn lazyAbiAlignment(ty: Type, pt: Zcu.PerThread) !Value {
switch (try ty.abiAlignmentInner(.lazy, pt.zcu, pt.tid)) {
.val => |val| return val,
.scalar => |x| return pt.intValue(Type.comptime_int, x.toByteUnits() orelse 0),
}
}
pub const AbiAlignmentInner = union(enum) {
scalar: Alignment,
val: Value,
};
pub const ResolveStratLazy = enum {
/// Return a `lazy_size` or `lazy_align` value if necessary.
/// This value can be resolved later using `Value.resolveLazy`.
lazy,
/// Return a scalar result, expecting all necessary type resolution to be completed.
/// Backends should typically use this, since they must not perform type resolution.
eager,
/// Return a scalar result, performing type resolution as necessary.
/// This should typically be used from semantic analysis.
sema,
pub fn Tid(strat: ResolveStratLazy) type {
return switch (strat) {
.lazy, .sema => Zcu.PerThread.Id,
.eager => void,
};
}
pub fn ZcuPtr(strat: ResolveStratLazy) type {
return switch (strat) {
.eager => *const Zcu,
.sema, .lazy => *Zcu,
};
}
pub fn pt(
comptime strat: ResolveStratLazy,
zcu: strat.ZcuPtr(),
tid: strat.Tid(),
) switch (strat) {
.lazy, .sema => Zcu.PerThread,
.eager => void,
} {
return switch (strat) {
.lazy, .sema => .{ .tid = tid, .zcu = zcu },
else => {},
};
}
};
/// The chosen strategy can be easily optimized away in release builds.
/// However, in debug builds, it helps to avoid accidentally resolving types in backends.
pub const ResolveStrat = enum {
/// Assert that all necessary resolution is completed.
/// Backends should typically use this, since they must not perform type resolution.
normal,
/// Perform type resolution as necessary using `Zcu`.
/// This should typically be used from semantic analysis.
sema,
pub fn Tid(strat: ResolveStrat) type {
return switch (strat) {
.sema => Zcu.PerThread.Id,
.normal => void,
};
}
pub fn ZcuPtr(strat: ResolveStrat) type {
return switch (strat) {
.normal => *const Zcu,
.sema => *Zcu,
};
}
pub fn pt(comptime strat: ResolveStrat, zcu: strat.ZcuPtr(), tid: strat.Tid()) switch (strat) {
.sema => Zcu.PerThread,
.normal => void,
} {
return switch (strat) {
.sema => .{ .tid = tid, .zcu = zcu },
.normal => {},
};
}
pub inline fn toLazy(strat: ResolveStrat) ResolveStratLazy {
return switch (strat) {
.normal => .eager,
.sema => .sema,
};
}
};
/// Never returns `none`. Asserts that all necessary type resolution is already done.
pub fn abiAlignment(ty: Type, zcu: *const Zcu) Alignment {
return (ty.abiAlignmentInner(.eager, zcu, {}) catch unreachable).scalar;
}
pub fn abiAlignmentSema(ty: Type, pt: Zcu.PerThread) SemaError!Alignment {
return (try ty.abiAlignmentInner(.sema, pt.zcu, pt.tid)).scalar;
}
/// If you pass `eager` you will get back `scalar` and assert the type is resolved.
/// In this case there will be no error, guaranteed.
/// If you pass `lazy` you may get back `scalar` or `val`.
/// If `val` is returned, a reference to `ty` has been captured.
/// If you pass `sema` you will get back `scalar` and resolve the type if
/// necessary, possibly returning a CompileError.
pub fn abiAlignmentInner(
ty: Type,
comptime strat: ResolveStratLazy,
zcu: strat.ZcuPtr(),
tid: strat.Tid(),
) SemaError!AbiAlignmentInner {
const pt = strat.pt(zcu, tid);
const target = zcu.getTarget();
const ip = &zcu.intern_pool;
switch (ty.toIntern()) {
.empty_tuple_type => return .{ .scalar = .@"1" },
else => switch (ip.indexToKey(ty.toIntern())) {
.int_type => |int_type| {
if (int_type.bits == 0) return .{ .scalar = .@"1" };
return .{ .scalar = .fromByteUnits(std.zig.target.intAlignment(target, int_type.bits)) };
},
.ptr_type, .anyframe_type => {
return .{ .scalar = ptrAbiAlignment(target) };
},
.array_type => |array_type| {
return Type.fromInterned(array_type.child).abiAlignmentInner(strat, zcu, tid);
},
.vector_type => |vector_type| {
if (vector_type.len == 0) return .{ .scalar = .@"1" };
switch (zcu.comp.getZigBackend()) {
else => {
// This is fine because the child type of a vector always has a bit-size known
// without needing any type resolution.
const elem_bits: u32 = @intCast(Type.fromInterned(vector_type.child).bitSize(zcu));
if (elem_bits == 0) return .{ .scalar = .@"1" };
const bytes = ((elem_bits * vector_type.len) + 7) / 8;
const alignment = std.math.ceilPowerOfTwoAssert(u32, bytes);
return .{ .scalar = Alignment.fromByteUnits(alignment) };
},
.stage2_c => {
return Type.fromInterned(vector_type.child).abiAlignmentInner(strat, zcu, tid);
},
.stage2_x86_64 => {
if (vector_type.child == .bool_type) {
if (vector_type.len > 256 and std.Target.x86.featureSetHas(target.cpu.features, .avx512f)) return .{ .scalar = .@"64" };
if (vector_type.len > 128 and std.Target.x86.featureSetHas(target.cpu.features, .avx2)) return .{ .scalar = .@"32" };
if (vector_type.len > 64) return .{ .scalar = .@"16" };
const bytes = std.math.divCeil(u32, vector_type.len, 8) catch unreachable;
const alignment = std.math.ceilPowerOfTwoAssert(u32, bytes);