forked from ziglang/zig
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathc.zig
More file actions
8432 lines (7641 loc) · 325 KB
/
Copy pathc.zig
File metadata and controls
8432 lines (7641 loc) · 325 KB
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
const std = @import("std");
const builtin = @import("builtin");
const assert = std.debug.assert;
const mem = std.mem;
const log = std.log.scoped(.c);
const Allocator = mem.Allocator;
const Writer = std.Io.Writer;
const dev = @import("../dev.zig");
const link = @import("../link.zig");
const Zcu = @import("../Zcu.zig");
const Module = @import("../Package/Module.zig");
const Compilation = @import("../Compilation.zig");
const Value = @import("../Value.zig");
const Type = @import("../Type.zig");
const C = link.File.C;
const Decl = Zcu.Decl;
const trace = @import("../tracy.zig").trace;
const Air = @import("../Air.zig");
const InternPool = @import("../InternPool.zig");
const Alignment = InternPool.Alignment;
const BigIntLimb = std.math.big.Limb;
const BigInt = std.math.big.int;
pub fn legalizeFeatures(_: *const std.Target) ?*const Air.Legalize.Features {
return comptime switch (dev.env.supports(.legalize)) {
inline false, true => |supports_legalize| &.init(.{
// we don't currently ask zig1 to use safe optimization modes
.expand_intcast_safe = supports_legalize,
.expand_int_from_float_safe = supports_legalize,
.expand_int_from_float_optimized_safe = supports_legalize,
.expand_add_safe = supports_legalize,
.expand_sub_safe = supports_legalize,
.expand_mul_safe = supports_legalize,
.expand_packed_load = true,
.expand_packed_store = true,
.expand_packed_struct_field_val = true,
.expand_packed_aggregate_init = true,
}),
};
}
/// For most backends, MIR is basically a sequence of machine code instructions, perhaps with some
/// "pseudo instructions" thrown in. For the C backend, it is instead the generated C code for a
/// single function. We also need to track some information to get merged into the global `link.C`
/// state, including:
/// * The UAVs used, so declarations can be emitted in `flush`
/// * The types used, so declarations can be emitted in `flush`
/// * The lazy functions used, so definitions can be emitted in `flush`
pub const Mir = struct {
/// This map contains all the UAVs we saw generating this function.
/// `link.C` will merge them into its `uavs`/`aligned_uavs` fields.
/// Key is the value of the UAV; value is the UAV's alignment, or
/// `.none` for natural alignment. The specified alignment is never
/// less than the natural alignment.
uavs: std.AutoArrayHashMapUnmanaged(InternPool.Index, Alignment),
// These remaining fields are essentially just an owned version of `link.C.AvBlock`.
code_header: []u8,
code: []u8,
fwd_decl: []u8,
ctype_pool: CType.Pool,
lazy_fns: LazyFnMap,
pub fn deinit(mir: *Mir, gpa: Allocator) void {
mir.uavs.deinit(gpa);
gpa.free(mir.code_header);
gpa.free(mir.code);
gpa.free(mir.fwd_decl);
mir.ctype_pool.deinit(gpa);
mir.lazy_fns.deinit(gpa);
}
};
pub const Error = Writer.Error || std.mem.Allocator.Error || error{AnalysisFail};
pub const CType = @import("c/Type.zig");
pub const CValue = union(enum) {
none: void,
new_local: LocalIndex,
local: LocalIndex,
/// Address of a local.
local_ref: LocalIndex,
/// A constant instruction, to be rendered inline.
constant: Value,
/// Index into the parameters
arg: usize,
/// The array field of a parameter
arg_array: usize,
/// Index into a tuple's fields
field: usize,
/// By-value
nav: InternPool.Nav.Index,
nav_ref: InternPool.Nav.Index,
/// An undefined value (cannot be dereferenced)
undef: Type,
/// Rendered as an identifier (using fmtIdent)
identifier: []const u8,
/// Rendered as "payload." followed by as identifier (using fmtIdent)
payload_identifier: []const u8,
/// Rendered with fmtCTypePoolString
ctype_pool_string: CType.Pool.String,
fn eql(lhs: CValue, rhs: CValue) bool {
return switch (lhs) {
.none => rhs == .none,
.new_local, .local => |lhs_local| switch (rhs) {
.new_local, .local => |rhs_local| lhs_local == rhs_local,
else => false,
},
.local_ref => |lhs_local| switch (rhs) {
.local_ref => |rhs_local| lhs_local == rhs_local,
else => false,
},
.constant => |lhs_val| switch (rhs) {
.constant => |rhs_val| lhs_val.toIntern() == rhs_val.toIntern(),
else => false,
},
.arg => |lhs_arg_index| switch (rhs) {
.arg => |rhs_arg_index| lhs_arg_index == rhs_arg_index,
else => false,
},
.arg_array => |lhs_arg_index| switch (rhs) {
.arg_array => |rhs_arg_index| lhs_arg_index == rhs_arg_index,
else => false,
},
.field => |lhs_field_index| switch (rhs) {
.field => |rhs_field_index| lhs_field_index == rhs_field_index,
else => false,
},
.nav => |lhs_nav| switch (rhs) {
.nav => |rhs_nav| lhs_nav == rhs_nav,
else => false,
},
.nav_ref => |lhs_nav| switch (rhs) {
.nav_ref => |rhs_nav| lhs_nav == rhs_nav,
else => false,
},
.undef => |lhs_ty| switch (rhs) {
.undef => |rhs_ty| lhs_ty.toIntern() == rhs_ty.toIntern(),
else => false,
},
.identifier => |lhs_id| switch (rhs) {
.identifier => |rhs_id| std.mem.eql(u8, lhs_id, rhs_id),
else => false,
},
.payload_identifier => |lhs_id| switch (rhs) {
.payload_identifier => |rhs_id| std.mem.eql(u8, lhs_id, rhs_id),
else => false,
},
.ctype_pool_string => |lhs_str| switch (rhs) {
.ctype_pool_string => |rhs_str| lhs_str.index == rhs_str.index,
else => false,
},
};
}
};
const BlockData = struct {
block_id: u32,
result: CValue,
};
pub const CValueMap = std.AutoHashMap(Air.Inst.Ref, CValue);
pub const LazyFnKey = union(enum) {
tag_name: InternPool.Index,
never_tail: InternPool.Nav.Index,
never_inline: InternPool.Nav.Index,
};
pub const LazyFnValue = struct {
fn_name: CType.Pool.String,
};
pub const LazyFnMap = std.AutoArrayHashMapUnmanaged(LazyFnKey, LazyFnValue);
const Local = struct {
ctype: CType,
flags: packed struct(u32) {
alignas: CType.AlignAs,
_: u20 = undefined,
},
fn getType(local: Local) LocalType {
return .{ .ctype = local.ctype, .alignas = local.flags.alignas };
}
};
const LocalIndex = u16;
const LocalType = struct { ctype: CType, alignas: CType.AlignAs };
const LocalsList = std.AutoArrayHashMapUnmanaged(LocalIndex, void);
const LocalsMap = std.AutoArrayHashMapUnmanaged(LocalType, LocalsList);
const ValueRenderLocation = enum {
FunctionArgument,
Initializer,
StaticInitializer,
Other,
fn isInitializer(loc: ValueRenderLocation) bool {
return switch (loc) {
.Initializer, .StaticInitializer => true,
else => false,
};
}
fn toCTypeKind(loc: ValueRenderLocation) CType.Kind {
return switch (loc) {
.FunctionArgument => .parameter,
.Initializer, .Other => .complete,
.StaticInitializer => .global,
};
}
};
const BuiltinInfo = enum { none, bits };
const reserved_idents = std.StaticStringMap(void).initComptime(.{
// C language
.{ "alignas", {
@setEvalBranchQuota(4000);
} },
.{ "alignof", {} },
.{ "asm", {} },
.{ "atomic_bool", {} },
.{ "atomic_char", {} },
.{ "atomic_char16_t", {} },
.{ "atomic_char32_t", {} },
.{ "atomic_int", {} },
.{ "atomic_int_fast16_t", {} },
.{ "atomic_int_fast32_t", {} },
.{ "atomic_int_fast64_t", {} },
.{ "atomic_int_fast8_t", {} },
.{ "atomic_int_least16_t", {} },
.{ "atomic_int_least32_t", {} },
.{ "atomic_int_least64_t", {} },
.{ "atomic_int_least8_t", {} },
.{ "atomic_intmax_t", {} },
.{ "atomic_intptr_t", {} },
.{ "atomic_llong", {} },
.{ "atomic_long", {} },
.{ "atomic_ptrdiff_t", {} },
.{ "atomic_schar", {} },
.{ "atomic_short", {} },
.{ "atomic_size_t", {} },
.{ "atomic_uchar", {} },
.{ "atomic_uint", {} },
.{ "atomic_uint_fast16_t", {} },
.{ "atomic_uint_fast32_t", {} },
.{ "atomic_uint_fast64_t", {} },
.{ "atomic_uint_fast8_t", {} },
.{ "atomic_uint_least16_t", {} },
.{ "atomic_uint_least32_t", {} },
.{ "atomic_uint_least64_t", {} },
.{ "atomic_uint_least8_t", {} },
.{ "atomic_uintmax_t", {} },
.{ "atomic_uintptr_t", {} },
.{ "atomic_ullong", {} },
.{ "atomic_ulong", {} },
.{ "atomic_ushort", {} },
.{ "atomic_wchar_t", {} },
.{ "auto", {} },
.{ "break", {} },
.{ "case", {} },
.{ "char", {} },
.{ "complex", {} },
.{ "const", {} },
.{ "continue", {} },
.{ "default", {} },
.{ "do", {} },
.{ "double", {} },
.{ "else", {} },
.{ "enum", {} },
.{ "extern", {} },
.{ "float", {} },
.{ "for", {} },
.{ "fortran", {} },
.{ "goto", {} },
.{ "if", {} },
.{ "imaginary", {} },
.{ "inline", {} },
.{ "int", {} },
.{ "int16_t", {} },
.{ "int32_t", {} },
.{ "int64_t", {} },
.{ "int8_t", {} },
.{ "intptr_t", {} },
.{ "long", {} },
.{ "noreturn", {} },
.{ "register", {} },
.{ "restrict", {} },
.{ "return", {} },
.{ "short", {} },
.{ "signed", {} },
.{ "size_t", {} },
.{ "sizeof", {} },
.{ "ssize_t", {} },
.{ "static", {} },
.{ "static_assert", {} },
.{ "struct", {} },
.{ "switch", {} },
.{ "thread_local", {} },
.{ "typedef", {} },
.{ "typeof", {} },
.{ "uint16_t", {} },
.{ "uint32_t", {} },
.{ "uint64_t", {} },
.{ "uint8_t", {} },
.{ "uintptr_t", {} },
.{ "union", {} },
.{ "unsigned", {} },
.{ "void", {} },
.{ "volatile", {} },
.{ "while", {} },
// stdarg.h
.{ "va_start", {} },
.{ "va_arg", {} },
.{ "va_end", {} },
.{ "va_copy", {} },
// stdbool.h
.{ "bool", {} },
.{ "false", {} },
.{ "true", {} },
// stddef.h
.{ "offsetof", {} },
// windows.h
.{ "max", {} },
.{ "min", {} },
});
fn isReservedIdent(ident: []const u8) bool {
if (ident.len >= 2 and ident[0] == '_') { // C language
switch (ident[1]) {
'A'...'Z', '_' => return true,
else => return false,
}
} else if (mem.startsWith(u8, ident, "DUMMYSTRUCTNAME") or
mem.startsWith(u8, ident, "DUMMYUNIONNAME"))
{ // windows.h
return true;
} else return reserved_idents.has(ident);
}
fn formatIdentSolo(ident: []const u8, w: *Writer) Writer.Error!void {
return formatIdentOptions(ident, w, true);
}
fn formatIdentUnsolo(ident: []const u8, w: *Writer) Writer.Error!void {
return formatIdentOptions(ident, w, false);
}
fn formatIdentOptions(ident: []const u8, w: *Writer, solo: bool) Writer.Error!void {
if (solo and isReservedIdent(ident)) {
try w.writeAll("zig_e_");
}
for (ident, 0..) |c, i| {
switch (c) {
'a'...'z', 'A'...'Z', '_' => try w.writeByte(c),
'.' => try w.writeByte('_'),
'0'...'9' => if (i == 0) {
try w.print("_{x:2}", .{c});
} else {
try w.writeByte(c);
},
else => try w.print("_{x:2}", .{c}),
}
}
}
pub fn fmtIdentSolo(ident: []const u8) std.fmt.Alt([]const u8, formatIdentSolo) {
return .{ .data = ident };
}
pub fn fmtIdentUnsolo(ident: []const u8) std.fmt.Alt([]const u8, formatIdentUnsolo) {
return .{ .data = ident };
}
const CTypePoolStringFormatData = struct {
ctype_pool_string: CType.Pool.String,
ctype_pool: *const CType.Pool,
solo: bool,
};
fn formatCTypePoolString(data: CTypePoolStringFormatData, w: *Writer) Writer.Error!void {
if (data.ctype_pool_string.toSlice(data.ctype_pool)) |slice|
try formatIdentOptions(slice, w, data.solo)
else
try w.print("{f}", .{data.ctype_pool_string.fmt(data.ctype_pool)});
}
pub fn fmtCTypePoolString(
ctype_pool_string: CType.Pool.String,
ctype_pool: *const CType.Pool,
solo: bool,
) std.fmt.Alt(CTypePoolStringFormatData, formatCTypePoolString) {
return .{ .data = .{
.ctype_pool_string = ctype_pool_string,
.ctype_pool = ctype_pool,
.solo = solo,
} };
}
// Returns true if `formatIdent` would make any edits to ident.
// This must be kept in sync with `formatIdent`.
pub fn isMangledIdent(ident: []const u8, solo: bool) bool {
if (solo and isReservedIdent(ident)) return true;
for (ident, 0..) |c, i| {
switch (c) {
'a'...'z', 'A'...'Z', '_' => {},
'0'...'9' => if (i == 0) return true,
else => return true,
}
}
return false;
}
/// This data is available when outputting .c code for a `InternPool.Index`
/// that corresponds to `func`.
/// It is not available when generating .h file.
pub const Function = struct {
air: Air,
liveness: Air.Liveness,
value_map: CValueMap,
blocks: std.AutoHashMapUnmanaged(Air.Inst.Index, BlockData) = .empty,
next_arg_index: u32 = 0,
next_block_index: u32 = 0,
object: Object,
lazy_fns: LazyFnMap,
func_index: InternPool.Index,
/// All the locals, to be emitted at the top of the function.
locals: std.ArrayList(Local) = .empty,
/// Which locals are available for reuse, based on Type.
free_locals_map: LocalsMap = .{},
/// Locals which will not be freed by Liveness. This is used after a
/// Function body is lowered in order to make `free_locals_map` have
/// 100% of the locals within so that it can be used to render the block
/// of variable declarations at the top of a function, sorted descending
/// by type alignment.
/// The value is whether the alloc needs to be emitted in the header.
allocs: std.AutoArrayHashMapUnmanaged(LocalIndex, bool) = .empty,
/// Maps from `loop_switch_br` instructions to the allocated local used
/// for the switch cond. Dispatches should set this local to the new cond.
loop_switch_conds: std.AutoHashMapUnmanaged(Air.Inst.Index, LocalIndex) = .empty,
fn resolveInst(f: *Function, ref: Air.Inst.Ref) !CValue {
const gop = try f.value_map.getOrPut(ref);
if (gop.found_existing) return gop.value_ptr.*;
const pt = f.object.dg.pt;
const zcu = pt.zcu;
const val = (try f.air.value(ref, pt)).?;
const ty = f.typeOf(ref);
const result: CValue = if (lowersToArray(ty, zcu)) result: {
const ch = &f.object.code_header.writer;
const decl_c_value = try f.allocLocalValue(.{
.ctype = try f.ctypeFromType(ty, .complete),
.alignas = CType.AlignAs.fromAbiAlignment(ty.abiAlignment(zcu)),
});
const gpa = f.object.dg.gpa;
try f.allocs.put(gpa, decl_c_value.new_local, false);
try ch.writeAll("static ");
try f.object.dg.renderTypeAndName(ch, ty, decl_c_value, Const, .none, .complete);
try ch.writeAll(" = ");
try f.object.dg.renderValue(ch, val, .StaticInitializer);
try ch.writeAll(";\n ");
break :result .{ .local = decl_c_value.new_local };
} else .{ .constant = val };
gop.value_ptr.* = result;
return result;
}
fn wantSafety(f: *Function) bool {
return switch (f.object.dg.pt.zcu.optimizeMode()) {
.Debug, .ReleaseSafe => true,
.ReleaseFast, .ReleaseSmall => false,
};
}
/// Skips the reuse logic. This function should be used for any persistent allocation, i.e.
/// those which go into `allocs`. This function does not add the resulting local into `allocs`;
/// that responsibility lies with the caller.
fn allocLocalValue(f: *Function, local_type: LocalType) !CValue {
try f.locals.ensureUnusedCapacity(f.object.dg.gpa, 1);
defer f.locals.appendAssumeCapacity(.{
.ctype = local_type.ctype,
.flags = .{ .alignas = local_type.alignas },
});
return .{ .new_local = @intCast(f.locals.items.len) };
}
fn allocLocal(f: *Function, inst: ?Air.Inst.Index, ty: Type) !CValue {
return f.allocAlignedLocal(inst, .{
.ctype = try f.ctypeFromType(ty, .complete),
.alignas = CType.AlignAs.fromAbiAlignment(ty.abiAlignment(f.object.dg.pt.zcu)),
});
}
/// Only allocates the local; does not print anything. Will attempt to re-use locals, so should
/// not be used for persistent locals (i.e. those in `allocs`).
fn allocAlignedLocal(f: *Function, inst: ?Air.Inst.Index, local_type: LocalType) !CValue {
const result: CValue = result: {
if (f.free_locals_map.getPtr(local_type)) |locals_list| {
if (locals_list.pop()) |local_entry| {
break :result .{ .new_local = local_entry.key };
}
}
break :result try f.allocLocalValue(local_type);
};
if (inst) |i| {
log.debug("%{d}: allocating t{d}", .{ i, result.new_local });
} else {
log.debug("allocating t{d}", .{result.new_local});
}
return result;
}
fn writeCValue(f: *Function, w: *Writer, c_value: CValue, location: ValueRenderLocation) !void {
switch (c_value) {
.none => unreachable,
.new_local, .local => |i| try w.print("t{d}", .{i}),
.local_ref => |i| try w.print("&t{d}", .{i}),
.constant => |val| try f.object.dg.renderValue(w, val, location),
.arg => |i| try w.print("a{d}", .{i}),
.arg_array => |i| try f.writeCValueMember(w, .{ .arg = i }, .{ .identifier = "array" }),
.undef => |ty| try f.object.dg.renderUndefValue(w, ty, location),
else => try f.object.dg.writeCValue(w, c_value),
}
}
fn writeCValueDeref(f: *Function, w: *Writer, c_value: CValue) !void {
switch (c_value) {
.none => unreachable,
.new_local, .local, .constant => {
try w.writeAll("(*");
try f.writeCValue(w, c_value, .Other);
try w.writeByte(')');
},
.local_ref => |i| try w.print("t{d}", .{i}),
.arg => |i| try w.print("(*a{d})", .{i}),
.arg_array => |i| {
try w.writeAll("(*");
try f.writeCValueMember(w, .{ .arg = i }, .{ .identifier = "array" });
try w.writeByte(')');
},
else => try f.object.dg.writeCValueDeref(w, c_value),
}
}
fn writeCValueMember(
f: *Function,
w: *Writer,
c_value: CValue,
member: CValue,
) Error!void {
switch (c_value) {
.new_local, .local, .local_ref, .constant, .arg, .arg_array => {
try f.writeCValue(w, c_value, .Other);
try w.writeByte('.');
try f.writeCValue(w, member, .Other);
},
else => return f.object.dg.writeCValueMember(w, c_value, member),
}
}
fn writeCValueDerefMember(f: *Function, w: *Writer, c_value: CValue, member: CValue) !void {
switch (c_value) {
.new_local, .local, .arg, .arg_array => {
try f.writeCValue(w, c_value, .Other);
try w.writeAll("->");
},
.constant => {
try w.writeByte('(');
try f.writeCValue(w, c_value, .Other);
try w.writeAll(")->");
},
.local_ref => {
try f.writeCValueDeref(w, c_value);
try w.writeByte('.');
},
else => return f.object.dg.writeCValueDerefMember(w, c_value, member),
}
try f.writeCValue(w, member, .Other);
}
fn fail(f: *Function, comptime format: []const u8, args: anytype) Error {
return f.object.dg.fail(format, args);
}
fn ctypeFromType(f: *Function, ty: Type, kind: CType.Kind) !CType {
return f.object.dg.ctypeFromType(ty, kind);
}
fn byteSize(f: *Function, ctype: CType) u64 {
return f.object.dg.byteSize(ctype);
}
fn renderType(f: *Function, w: *Writer, ctype: Type) !void {
return f.object.dg.renderType(w, ctype);
}
fn renderCType(f: *Function, w: *Writer, ctype: CType) !void {
return f.object.dg.renderCType(w, ctype);
}
fn renderIntCast(f: *Function, w: *Writer, dest_ty: Type, src: CValue, v: Vectorize, src_ty: Type, location: ValueRenderLocation) !void {
return f.object.dg.renderIntCast(w, dest_ty, .{ .c_value = .{ .f = f, .value = src, .v = v } }, src_ty, location);
}
fn fmtIntLiteralDec(f: *Function, val: Value) !std.fmt.Alt(FormatIntLiteralContext, formatIntLiteral) {
return f.object.dg.fmtIntLiteralDec(val, .Other);
}
fn fmtIntLiteralHex(f: *Function, val: Value) !std.fmt.Alt(FormatIntLiteralContext, formatIntLiteral) {
return f.object.dg.fmtIntLiteralHex(val, .Other);
}
fn getLazyFnName(f: *Function, key: LazyFnKey) ![]const u8 {
const gpa = f.object.dg.gpa;
const pt = f.object.dg.pt;
const zcu = pt.zcu;
const ip = &zcu.intern_pool;
const ctype_pool = &f.object.dg.ctype_pool;
const gop = try f.lazy_fns.getOrPut(gpa, key);
if (!gop.found_existing) {
errdefer _ = f.lazy_fns.pop();
gop.value_ptr.* = .{
.fn_name = switch (key) {
.tag_name,
=> |enum_ty| try ctype_pool.fmt(gpa, "zig_{s}_{f}__{d}", .{
@tagName(key),
fmtIdentUnsolo(ip.loadEnumType(enum_ty).name.toSlice(ip)),
@intFromEnum(enum_ty),
}),
.never_tail,
.never_inline,
=> |owner_nav| try ctype_pool.fmt(gpa, "zig_{s}_{f}__{d}", .{
@tagName(key),
fmtIdentUnsolo(ip.getNav(owner_nav).name.toSlice(ip)),
@intFromEnum(owner_nav),
}),
},
};
}
return gop.value_ptr.fn_name.toSlice(ctype_pool).?;
}
pub fn deinit(f: *Function) void {
const gpa = f.object.dg.gpa;
f.allocs.deinit(gpa);
f.locals.deinit(gpa);
deinitFreeLocalsMap(gpa, &f.free_locals_map);
f.blocks.deinit(gpa);
f.value_map.deinit();
f.lazy_fns.deinit(gpa);
f.loop_switch_conds.deinit(gpa);
}
fn typeOf(f: *Function, inst: Air.Inst.Ref) Type {
return f.air.typeOf(inst, &f.object.dg.pt.zcu.intern_pool);
}
fn typeOfIndex(f: *Function, inst: Air.Inst.Index) Type {
return f.air.typeOfIndex(inst, &f.object.dg.pt.zcu.intern_pool);
}
fn copyCValue(f: *Function, ctype: CType, dst: CValue, src: CValue) !void {
switch (dst) {
.new_local, .local => |dst_local_index| switch (src) {
.new_local, .local => |src_local_index| if (dst_local_index == src_local_index) return,
else => {},
},
else => {},
}
const w = &f.object.code.writer;
const a = try Assignment.start(f, w, ctype);
try f.writeCValue(w, dst, .Other);
try a.assign(f, w);
try f.writeCValue(w, src, .Other);
try a.end(f, w);
}
fn moveCValue(f: *Function, inst: Air.Inst.Index, ty: Type, src: CValue) !CValue {
switch (src) {
// Move the freshly allocated local to be owned by this instruction,
// by returning it here instead of freeing it.
.new_local => return src,
else => {
try freeCValue(f, inst, src);
const dst = try f.allocLocal(inst, ty);
try f.copyCValue(try f.ctypeFromType(ty, .complete), dst, src);
return dst;
},
}
}
fn freeCValue(f: *Function, inst: ?Air.Inst.Index, val: CValue) !void {
switch (val) {
.new_local => |local_index| try freeLocal(f, inst, local_index, null),
else => {},
}
}
};
/// This data is available when outputting .c code for a `Zcu`.
/// It is not available when generating .h file.
pub const Object = struct {
dg: DeclGen,
code_header: Writer.Allocating,
code: Writer.Allocating,
indent_counter: usize,
const indent_width = 1;
const indent_char = ' ';
fn newline(o: *Object) !void {
const w = &o.code.writer;
try w.writeByte('\n');
try w.splatByteAll(indent_char, o.indent_counter);
}
fn indent(o: *Object) void {
o.indent_counter += indent_width;
}
fn outdent(o: *Object) !void {
o.indent_counter -= indent_width;
const written = o.code.written();
switch (written[written.len - 1]) {
indent_char => o.code.shrinkRetainingCapacity(written.len - indent_width),
'\n' => try o.code.writer.splatByteAll(indent_char, o.indent_counter),
else => {
std.debug.print("\"{f}\"\n", .{std.zig.fmtString(written[written.len -| 100..])});
unreachable;
},
}
}
};
/// This data is available both when outputting .c code and when outputting an .h file.
pub const DeclGen = struct {
gpa: Allocator,
pt: Zcu.PerThread,
mod: *Module,
pass: Pass,
is_naked_fn: bool,
expected_block: ?u32,
fwd_decl: Writer.Allocating,
error_msg: ?*Zcu.ErrorMsg,
ctype_pool: CType.Pool,
scratch: std.ArrayList(u32),
/// This map contains all the UAVs we saw generating this function.
/// `link.C` will merge them into its `uavs`/`aligned_uavs` fields.
/// Key is the value of the UAV; value is the UAV's alignment, or
/// `.none` for natural alignment. The specified alignment is never
/// less than the natural alignment.
uavs: std.AutoArrayHashMapUnmanaged(InternPool.Index, Alignment),
pub const Pass = union(enum) {
nav: InternPool.Nav.Index,
uav: InternPool.Index,
flush,
};
fn fail(dg: *DeclGen, comptime format: []const u8, args: anytype) Error {
@branchHint(.cold);
const zcu = dg.pt.zcu;
const src_loc = zcu.navSrcLoc(dg.pass.nav);
dg.error_msg = try Zcu.ErrorMsg.create(dg.gpa, src_loc, format, args);
return error.AnalysisFail;
}
fn renderUav(
dg: *DeclGen,
w: *Writer,
uav: InternPool.Key.Ptr.BaseAddr.Uav,
location: ValueRenderLocation,
) Error!void {
const pt = dg.pt;
const zcu = pt.zcu;
const ip = &zcu.intern_pool;
const ctype_pool = &dg.ctype_pool;
const uav_val = Value.fromInterned(uav.val);
const uav_ty = uav_val.typeOf(zcu);
// Render an undefined pointer if we have a pointer to a zero-bit or comptime type.
const ptr_ty: Type = .fromInterned(uav.orig_ty);
if (ptr_ty.isPtrAtRuntime(zcu) and !uav_ty.isFnOrHasRuntimeBits(zcu)) {
return dg.writeCValue(w, .{ .undef = ptr_ty });
}
// Chase function values in order to be able to reference the original function.
switch (ip.indexToKey(uav.val)) {
.variable => unreachable,
.func => |func| return dg.renderNav(w, func.owner_nav, location),
.@"extern" => |@"extern"| return dg.renderNav(w, @"extern".owner_nav, location),
else => {},
}
// We shouldn't cast C function pointers as this is UB (when you call
// them). The analysis until now should ensure that the C function
// pointers are compatible. If they are not, then there is a bug
// somewhere and we should let the C compiler tell us about it.
const ptr_ctype = try dg.ctypeFromType(ptr_ty, .complete);
const elem_ctype = ptr_ctype.info(ctype_pool).pointer.elem_ctype;
const uav_ctype = try dg.ctypeFromType(uav_ty, .complete);
const need_cast = !elem_ctype.eql(uav_ctype) and
(elem_ctype.info(ctype_pool) != .function or uav_ctype.info(ctype_pool) != .function);
if (need_cast) {
try w.writeAll("((");
try dg.renderCType(w, ptr_ctype);
try w.writeByte(')');
}
try w.writeByte('&');
try renderUavName(w, uav_val);
if (need_cast) try w.writeByte(')');
// Indicate that the anon decl should be rendered to the output so that
// our reference above is not undefined.
const ptr_type = ip.indexToKey(uav.orig_ty).ptr_type;
const gop = try dg.uavs.getOrPut(dg.gpa, uav.val);
if (!gop.found_existing) gop.value_ptr.* = .none;
// If there is an explicit alignment, greater than the current one, use it.
// Note that we intentionally start at `.none`, so `gop.value_ptr.*` is never
// underaligned, so we don't need to worry about the `.none` case here.
if (ptr_type.flags.alignment != .none) {
// Resolve the current alignment so we can choose the bigger one.
const cur_alignment: Alignment = if (gop.value_ptr.* == .none) abi: {
break :abi Type.fromInterned(ptr_type.child).abiAlignment(zcu);
} else gop.value_ptr.*;
gop.value_ptr.* = cur_alignment.maxStrict(ptr_type.flags.alignment);
}
}
fn renderNav(
dg: *DeclGen,
w: *Writer,
nav_index: InternPool.Nav.Index,
location: ValueRenderLocation,
) Error!void {
_ = location;
const pt = dg.pt;
const zcu = pt.zcu;
const ip = &zcu.intern_pool;
const ctype_pool = &dg.ctype_pool;
// Chase function values in order to be able to reference the original function.
const owner_nav = switch (ip.getNav(nav_index).status) {
.unresolved => unreachable,
.type_resolved => nav_index, // this can't be an extern or a function
.fully_resolved => |r| switch (ip.indexToKey(r.val)) {
.func => |f| f.owner_nav,
.@"extern" => |e| e.owner_nav,
else => nav_index,
},
};
// Render an undefined pointer if we have a pointer to a zero-bit or comptime type.
const nav_ty: Type = .fromInterned(ip.getNav(owner_nav).typeOf(ip));
const ptr_ty = try pt.navPtrType(owner_nav);
if (!nav_ty.isFnOrHasRuntimeBits(zcu)) {
return dg.writeCValue(w, .{ .undef = ptr_ty });
}
// We shouldn't cast C function pointers as this is UB (when you call
// them). The analysis until now should ensure that the C function
// pointers are compatible. If they are not, then there is a bug
// somewhere and we should let the C compiler tell us about it.
const ctype = try dg.ctypeFromType(ptr_ty, .complete);
const elem_ctype = ctype.info(ctype_pool).pointer.elem_ctype;
const nav_ctype = try dg.ctypeFromType(nav_ty, .complete);
const need_cast = !elem_ctype.eql(nav_ctype) and
(elem_ctype.info(ctype_pool) != .function or nav_ctype.info(ctype_pool) != .function);
if (need_cast) {
try w.writeAll("((");
try dg.renderCType(w, ctype);
try w.writeByte(')');
}
try w.writeByte('&');
try dg.renderNavName(w, owner_nav);
if (need_cast) try w.writeByte(')');
}
fn renderPointer(
dg: *DeclGen,
w: *Writer,
derivation: Value.PointerDeriveStep,
location: ValueRenderLocation,
) Error!void {
const pt = dg.pt;
const zcu = pt.zcu;
switch (derivation) {
.comptime_alloc_ptr, .comptime_field_ptr => unreachable,
.int => |int| {
const ptr_ctype = try dg.ctypeFromType(int.ptr_ty, .complete);
const addr_val = try pt.intValue(.usize, int.addr);
try w.writeByte('(');
try dg.renderCType(w, ptr_ctype);
try w.print("){f}", .{try dg.fmtIntLiteralHex(addr_val, .Other)});
},
.nav_ptr => |nav| try dg.renderNav(w, nav, location),
.uav_ptr => |uav| try dg.renderUav(w, uav, location),
inline .eu_payload_ptr, .opt_payload_ptr => |info| {
try w.writeAll("&(");
try dg.renderPointer(w, info.parent.*, location);
try w.writeAll(")->payload");
},
.field_ptr => |field| {
const parent_ptr_ty = try field.parent.ptrType(pt);
// Ensure complete type definition is available before accessing fields.
_ = try dg.ctypeFromType(parent_ptr_ty.childType(zcu), .complete);
switch (fieldLocation(parent_ptr_ty, field.result_ptr_ty, field.field_idx, zcu)) {
.begin => {
const ptr_ctype = try dg.ctypeFromType(field.result_ptr_ty, .complete);
try w.writeByte('(');
try dg.renderCType(w, ptr_ctype);
try w.writeByte(')');
try dg.renderPointer(w, field.parent.*, location);
},
.field => |name| {
try w.writeAll("&(");
try dg.renderPointer(w, field.parent.*, location);
try w.writeAll(")->");
try dg.writeCValue(w, name);
},
.byte_offset => |byte_offset| {
const ptr_ctype = try dg.ctypeFromType(field.result_ptr_ty, .complete);
try w.writeByte('(');
try dg.renderCType(w, ptr_ctype);
try w.writeByte(')');
const offset_val = try pt.intValue(.usize, byte_offset);
try w.writeAll("((char *)");
try dg.renderPointer(w, field.parent.*, location);
try w.print(" + {f})", .{try dg.fmtIntLiteralDec(offset_val, .Other)});
},
}
},
.elem_ptr => |elem| if (!(try elem.parent.ptrType(pt)).childType(zcu).hasRuntimeBits(zcu)) {
// Element type is zero-bit, so lowers to `void`. The index is irrelevant; just cast the pointer.
const ptr_ctype = try dg.ctypeFromType(elem.result_ptr_ty, .complete);
try w.writeByte('(');
try dg.renderCType(w, ptr_ctype);
try w.writeByte(')');
try dg.renderPointer(w, elem.parent.*, location);
} else {
const index_val = try pt.intValue(.usize, elem.elem_idx);
// We want to do pointer arithmetic on a pointer to the element type.
// We might have a pointer-to-array. In this case, we must cast first.
const result_ctype = try dg.ctypeFromType(elem.result_ptr_ty, .complete);
const parent_ctype = try dg.ctypeFromType(try elem.parent.ptrType(pt), .complete);
if (result_ctype.eql(parent_ctype)) {
// The pointer already has an appropriate type - just do the arithmetic.
try w.writeByte('(');
try dg.renderPointer(w, elem.parent.*, location);
try w.print(" + {f})", .{try dg.fmtIntLiteralDec(index_val, .Other)});
} else {
// We probably have an array pointer `T (*)[n]`. Cast to an element pointer,
// and *then* apply the index.
try w.writeAll("((");
try dg.renderCType(w, result_ctype);
try w.writeByte(')');
try dg.renderPointer(w, elem.parent.*, location);
try w.print(" + {f})", .{try dg.fmtIntLiteralDec(index_val, .Other)});
}
},
.offset_and_cast => |oac| {
const ptr_ctype = try dg.ctypeFromType(oac.new_ptr_ty, .complete);
try w.writeByte('(');
try dg.renderCType(w, ptr_ctype);
try w.writeByte(')');
if (oac.byte_offset == 0) {
try dg.renderPointer(w, oac.parent.*, location);
} else {
const offset_val = try pt.intValue(.usize, oac.byte_offset);
try w.writeAll("((char *)");
try dg.renderPointer(w, oac.parent.*, location);
try w.print(" + {f})", .{try dg.fmtIntLiteralDec(offset_val, .Other)});
}
},
}
}
fn renderErrorName(dg: *DeclGen, w: *Writer, err_name: InternPool.NullTerminatedString) !void {
try w.print("zig_error_{f}", .{fmtIdentUnsolo(err_name.toSlice(&dg.pt.zcu.intern_pool))});
}
fn renderValue(
dg: *DeclGen,
w: *Writer,