-
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Compilation.zig
6294 lines (5593 loc) · 243 KB
/
Compilation.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
const Compilation = @This();
const std = @import("std");
const builtin = @import("builtin");
const mem = std.mem;
const Allocator = std.mem.Allocator;
const assert = std.debug.assert;
const log = std.log.scoped(.compilation);
const Target = std.Target;
const ThreadPool = std.Thread.Pool;
const WaitGroup = std.Thread.WaitGroup;
const ErrorBundle = std.zig.ErrorBundle;
const Value = @import("Value.zig");
const Type = @import("type.zig").Type;
const target_util = @import("target.zig");
const Package = @import("Package.zig");
const link = @import("link.zig");
const tracy = @import("tracy.zig");
const trace = tracy.trace;
const build_options = @import("build_options");
const LibCInstallation = std.zig.LibCInstallation;
const glibc = @import("glibc.zig");
const musl = @import("musl.zig");
const mingw = @import("mingw.zig");
const libunwind = @import("libunwind.zig");
const libcxx = @import("libcxx.zig");
const wasi_libc = @import("wasi_libc.zig");
const fatal = @import("main.zig").fatal;
const clangMain = @import("main.zig").clangMain;
const Zcu = @import("Module.zig");
/// Deprecated; use `Zcu`.
const Module = Zcu;
const InternPool = @import("InternPool.zig");
const Cache = std.Build.Cache;
const c_codegen = @import("codegen/c.zig");
const libtsan = @import("libtsan.zig");
const Zir = std.zig.Zir;
const Builtin = @import("Builtin.zig");
const LlvmObject = @import("codegen/llvm.zig").Object;
pub const Config = @import("Compilation/Config.zig");
/// General-purpose allocator. Used for both temporary and long-term storage.
gpa: Allocator,
/// Arena-allocated memory, mostly used during initialization. However, it can
/// be used for other things requiring the same lifetime as the `Compilation`.
arena: Allocator,
/// Not every Compilation compiles .zig code! For example you could do `zig build-exe foo.o`.
/// TODO: rename to zcu: ?*Zcu
module: ?*Module,
/// Contains different state depending on whether the Compilation uses
/// incremental or whole cache mode.
cache_use: CacheUse,
/// All compilations have a root module because this is where some important
/// settings are stored, such as target and optimization mode. This module
/// might not have any .zig code associated with it, however.
root_mod: *Package.Module,
/// User-specified settings that have all the defaults resolved into concrete values.
config: Config,
/// The main output file.
/// In whole cache mode, this is null except for during the body of the update
/// function. In incremental cache mode, this is a long-lived object.
/// In both cases, this is `null` when `-fno-emit-bin` is used.
bin_file: ?*link.File,
/// The root path for the dynamic linker and system libraries (as well as frameworks on Darwin)
sysroot: ?[]const u8,
/// This is `null` when not building a Windows DLL, or when `-fno-emit-implib` is used.
implib_emit: ?Emit,
/// This is non-null when `-femit-docs` is provided.
docs_emit: ?Emit,
root_name: [:0]const u8,
include_compiler_rt: bool,
objects: []Compilation.LinkObject,
/// Needed only for passing -F args to clang.
framework_dirs: []const []const u8,
/// These are *always* dynamically linked. Static libraries will be
/// provided as positional arguments.
system_libs: std.StringArrayHashMapUnmanaged(SystemLib),
version: ?std.SemanticVersion,
libc_installation: ?*const LibCInstallation,
skip_linker_dependencies: bool,
no_builtin: bool,
function_sections: bool,
data_sections: bool,
link_eh_frame_hdr: bool,
native_system_include_paths: []const []const u8,
/// List of symbols forced as undefined in the symbol table
/// thus forcing their resolution by the linker.
/// Corresponds to `-u <symbol>` for ELF/MachO and `/include:<symbol>` for COFF/PE.
force_undefined_symbols: std.StringArrayHashMapUnmanaged(void),
c_object_table: std.AutoArrayHashMapUnmanaged(*CObject, void) = .{},
win32_resource_table: if (build_options.only_core_functionality) void else std.AutoArrayHashMapUnmanaged(*Win32Resource, void) =
if (build_options.only_core_functionality) {} else .{},
link_error_flags: link.File.ErrorFlags = .{},
link_errors: std.ArrayListUnmanaged(link.File.ErrorMsg) = .{},
lld_errors: std.ArrayListUnmanaged(LldError) = .{},
work_queue: std.fifo.LinearFifo(Job, .Dynamic),
/// These jobs are to invoke the Clang compiler to create an object file, which
/// gets linked with the Compilation.
c_object_work_queue: std.fifo.LinearFifo(*CObject, .Dynamic),
/// These jobs are to invoke the RC compiler to create a compiled resource file (.res), which
/// gets linked with the Compilation.
win32_resource_work_queue: if (build_options.only_core_functionality) void else std.fifo.LinearFifo(*Win32Resource, .Dynamic),
/// These jobs are to tokenize, parse, and astgen files, which may be outdated
/// since the last compilation, as well as scan for `@import` and queue up
/// additional jobs corresponding to those new files.
astgen_work_queue: std.fifo.LinearFifo(*Module.File, .Dynamic),
/// These jobs are to inspect the file system stat() and if the embedded file has changed
/// on disk, mark the corresponding Decl outdated and queue up an `analyze_decl`
/// task for it.
embed_file_work_queue: std.fifo.LinearFifo(*Module.EmbedFile, .Dynamic),
/// The ErrorMsg memory is owned by the `CObject`, using Compilation's general purpose allocator.
/// This data is accessed by multiple threads and is protected by `mutex`.
failed_c_objects: std.AutoArrayHashMapUnmanaged(*CObject, *CObject.Diag.Bundle) = .{},
/// The ErrorBundle memory is owned by the `Win32Resource`, using Compilation's general purpose allocator.
/// This data is accessed by multiple threads and is protected by `mutex`.
failed_win32_resources: if (build_options.only_core_functionality) void else std.AutoArrayHashMapUnmanaged(*Win32Resource, ErrorBundle) =
if (build_options.only_core_functionality) {} else .{},
/// Miscellaneous things that can fail.
misc_failures: std.AutoArrayHashMapUnmanaged(MiscTask, MiscError) = .{},
/// When this is `true` it means invoking clang as a sub-process is expected to inherit
/// stdin, stdout, stderr, and if it returns non success, to forward the exit code.
/// Otherwise we attempt to parse the error messages and expose them via the Compilation API.
/// This is `true` for `zig cc`, `zig c++`, and `zig translate-c`.
clang_passthrough_mode: bool,
clang_preprocessor_mode: ClangPreprocessorMode,
/// Whether to print clang argvs to stdout.
verbose_cc: bool,
verbose_air: bool,
verbose_intern_pool: bool,
verbose_generic_instances: bool,
verbose_llvm_ir: ?[]const u8,
verbose_llvm_bc: ?[]const u8,
verbose_cimport: bool,
verbose_llvm_cpu_features: bool,
verbose_link: bool,
disable_c_depfile: bool,
time_report: bool,
stack_report: bool,
debug_compiler_runtime_libs: bool,
debug_compile_errors: bool,
debug_incremental: bool,
job_queued_compiler_rt_lib: bool = false,
job_queued_compiler_rt_obj: bool = false,
job_queued_update_builtin_zig: bool,
alloc_failure_occurred: bool = false,
formatted_panics: bool = false,
last_update_was_cache_hit: bool = false,
c_source_files: []const CSourceFile,
rc_source_files: []const RcSourceFile,
global_cc_argv: []const []const u8,
cache_parent: *Cache,
/// Path to own executable for invoking `zig clang`.
self_exe_path: ?[]const u8,
zig_lib_directory: Directory,
local_cache_directory: Directory,
global_cache_directory: Directory,
libc_include_dir_list: []const []const u8,
libc_framework_dir_list: []const []const u8,
rc_includes: RcIncludes,
mingw_unicode_entry_point: bool,
thread_pool: *ThreadPool,
/// Populated when we build the libc++ static library. A Job to build this is placed in the queue
/// and resolved before calling linker.flush().
libcxx_static_lib: ?CRTFile = null,
/// Populated when we build the libc++abi static library. A Job to build this is placed in the queue
/// and resolved before calling linker.flush().
libcxxabi_static_lib: ?CRTFile = null,
/// Populated when we build the libunwind static library. A Job to build this is placed in the queue
/// and resolved before calling linker.flush().
libunwind_static_lib: ?CRTFile = null,
/// Populated when we build the TSAN static library. A Job to build this is placed in the queue
/// and resolved before calling linker.flush().
tsan_static_lib: ?CRTFile = null,
/// Populated when we build the libc static library. A Job to build this is placed in the queue
/// and resolved before calling linker.flush().
libc_static_lib: ?CRTFile = null,
/// Populated when we build the libcompiler_rt static library. A Job to build this is indicated
/// by setting `job_queued_compiler_rt_lib` and resolved before calling linker.flush().
compiler_rt_lib: ?CRTFile = null,
/// Populated when we build the compiler_rt_obj object. A Job to build this is indicated
/// by setting `job_queued_compiler_rt_obj` and resolved before calling linker.flush().
compiler_rt_obj: ?CRTFile = null,
glibc_so_files: ?glibc.BuiltSharedObjects = null,
wasi_emulated_libs: []const wasi_libc.CRTFile,
/// For example `Scrt1.o` and `libc_nonshared.a`. These are populated after building libc from source,
/// The set of needed CRT (C runtime) files differs depending on the target and compilation settings.
/// The key is the basename, and the value is the absolute path to the completed build artifact.
crt_files: std.StringHashMapUnmanaged(CRTFile) = .{},
/// How many lines of reference trace should be included per compile error.
/// Null means only show snippet on first error.
reference_trace: ?u32 = null,
libcxx_abi_version: libcxx.AbiVersion = libcxx.AbiVersion.default,
/// This mutex guards all `Compilation` mutable state.
mutex: std.Thread.Mutex = .{},
test_filters: []const []const u8,
test_name_prefix: ?[]const u8,
emit_asm: ?EmitLoc,
emit_llvm_ir: ?EmitLoc,
emit_llvm_bc: ?EmitLoc,
work_queue_wait_group: WaitGroup = .{},
astgen_wait_group: WaitGroup = .{},
llvm_opt_bisect_limit: c_int,
pub const Emit = struct {
/// Where the output will go.
directory: Directory,
/// Path to the output file, relative to `directory`.
sub_path: []const u8,
/// Returns the full path to `basename` if it were in the same directory as the
/// `Emit` sub_path.
pub fn basenamePath(emit: Emit, arena: Allocator, basename: []const u8) ![:0]const u8 {
const full_path = if (emit.directory.path) |p|
try std.fs.path.join(arena, &[_][]const u8{ p, emit.sub_path })
else
emit.sub_path;
if (std.fs.path.dirname(full_path)) |dirname| {
return try std.fs.path.joinZ(arena, &.{ dirname, basename });
} else {
return try arena.dupeZ(u8, basename);
}
}
};
pub const default_stack_protector_buffer_size = target_util.default_stack_protector_buffer_size;
pub const SemaError = Module.SemaError;
pub const CRTFile = struct {
lock: Cache.Lock,
full_object_path: []const u8,
pub fn deinit(self: *CRTFile, gpa: Allocator) void {
self.lock.release();
gpa.free(self.full_object_path);
self.* = undefined;
}
};
/// Supported languages for "zig clang -x <lang>".
/// Loosely based on llvm-project/clang/include/clang/Driver/Types.def
pub const LangToExt = std.ComptimeStringMap(FileExt, .{
.{ "c", .c },
.{ "c-header", .h },
.{ "c++", .cpp },
.{ "c++-header", .hpp },
.{ "objective-c", .m },
.{ "objective-c-header", .hm },
.{ "objective-c++", .mm },
.{ "objective-c++-header", .hmm },
.{ "assembler", .assembly },
.{ "assembler-with-cpp", .assembly_with_cpp },
.{ "cuda", .cu },
});
/// For passing to a C compiler.
pub const CSourceFile = struct {
/// Many C compiler flags are determined by settings contained in the owning Module.
owner: *Package.Module,
src_path: []const u8,
extra_flags: []const []const u8 = &.{},
/// Same as extra_flags except they are not added to the Cache hash.
cache_exempt_flags: []const []const u8 = &.{},
/// This field is non-null if and only if the language was explicitly set
/// with "-x lang".
ext: ?FileExt = null,
};
/// For passing to resinator.
pub const RcSourceFile = struct {
owner: *Package.Module,
src_path: []const u8,
extra_flags: []const []const u8 = &.{},
};
pub const RcIncludes = enum {
/// Use MSVC if available, fall back to MinGW.
any,
/// Use MSVC include paths (MSVC install + Windows SDK, must be present on the system).
msvc,
/// Use MinGW include paths (distributed with Zig).
gnu,
/// Do not use any autodetected include paths.
none,
};
const Job = union(enum) {
/// Write the constant value for a Decl to the output file.
codegen_decl: InternPool.DeclIndex,
/// Write the machine code for a function to the output file.
/// This will either be a non-generic `func_decl` or a `func_instance`.
codegen_func: InternPool.Index,
/// Render the .h file snippet for the Decl.
emit_h_decl: InternPool.DeclIndex,
/// The Decl needs to be analyzed and possibly export itself.
/// It may have already be analyzed, or it may have been determined
/// to be outdated; in this case perform semantic analysis again.
analyze_decl: InternPool.DeclIndex,
/// The source file containing the Decl has been updated, and so the
/// Decl may need its line number information updated in the debug info.
update_line_number: InternPool.DeclIndex,
/// The main source file for the module needs to be analyzed.
analyze_mod: *Package.Module,
/// one of the glibc static objects
glibc_crt_file: glibc.CRTFile,
/// all of the glibc shared objects
glibc_shared_objects,
/// one of the musl static objects
musl_crt_file: musl.CRTFile,
/// one of the mingw-w64 static objects
mingw_crt_file: mingw.CRTFile,
/// libunwind.a, usually needed when linking libc
libunwind: void,
libcxx: void,
libcxxabi: void,
libtsan: void,
/// needed when not linking libc and using LLVM for code generation because it generates
/// calls to, for example, memcpy and memset.
zig_libc: void,
/// one of WASI libc static objects
wasi_libc_crt_file: wasi_libc.CRTFile,
/// The value is the index into `system_libs`.
windows_import_lib: usize,
};
pub const CObject = struct {
/// Relative to cwd. Owned by arena.
src: CSourceFile,
status: union(enum) {
new,
success: struct {
/// The outputted result. Owned by gpa.
object_path: []u8,
/// This is a file system lock on the cache hash manifest representing this
/// object. It prevents other invocations of the Zig compiler from interfering
/// with this object until released.
lock: Cache.Lock,
},
/// There will be a corresponding ErrorMsg in Compilation.failed_c_objects.
failure,
/// A transient failure happened when trying to compile the C Object; it may
/// succeed if we try again. There may be a corresponding ErrorMsg in
/// Compilation.failed_c_objects. If there is not, the failure is out of memory.
failure_retryable,
},
pub const Diag = struct {
level: u32 = 0,
category: u32 = 0,
msg: []const u8 = &.{},
src_loc: SrcLoc = .{},
src_ranges: []const SrcRange = &.{},
sub_diags: []const Diag = &.{},
pub const SrcLoc = struct {
file: u32 = 0,
line: u32 = 0,
column: u32 = 0,
offset: u32 = 0,
};
pub const SrcRange = struct {
start: SrcLoc = .{},
end: SrcLoc = .{},
};
pub fn deinit(diag: *Diag, gpa: Allocator) void {
gpa.free(diag.msg);
gpa.free(diag.src_ranges);
for (diag.sub_diags) |sub_diag| {
var sub_diag_mut = sub_diag;
sub_diag_mut.deinit(gpa);
}
gpa.free(diag.sub_diags);
diag.* = undefined;
}
pub fn count(diag: Diag) u32 {
var total: u32 = 1;
for (diag.sub_diags) |sub_diag| total += sub_diag.count();
return total;
}
pub fn addToErrorBundle(diag: Diag, eb: *ErrorBundle.Wip, bundle: Bundle, note: *u32) !void {
const err_msg = try eb.addErrorMessage(try diag.toErrorMessage(eb, bundle, 0));
eb.extra.items[note.*] = @intFromEnum(err_msg);
note.* += 1;
for (diag.sub_diags) |sub_diag| try sub_diag.addToErrorBundle(eb, bundle, note);
}
pub fn toErrorMessage(
diag: Diag,
eb: *ErrorBundle.Wip,
bundle: Bundle,
notes_len: u32,
) !ErrorBundle.ErrorMessage {
var start = diag.src_loc.offset;
var end = diag.src_loc.offset;
for (diag.src_ranges) |src_range| {
if (src_range.start.file == diag.src_loc.file and
src_range.start.line == diag.src_loc.line)
{
start = @min(src_range.start.offset, start);
}
if (src_range.end.file == diag.src_loc.file and
src_range.end.line == diag.src_loc.line)
{
end = @max(src_range.end.offset, end);
}
}
const file_name = bundle.file_names.get(diag.src_loc.file) orelse "";
const source_line = source_line: {
if (diag.src_loc.offset == 0 or diag.src_loc.column == 0) break :source_line 0;
const file = std.fs.cwd().openFile(file_name, .{}) catch break :source_line 0;
defer file.close();
file.seekTo(diag.src_loc.offset + 1 - diag.src_loc.column) catch break :source_line 0;
var line = std.ArrayList(u8).init(eb.gpa);
defer line.deinit();
file.reader().readUntilDelimiterArrayList(&line, '\n', 1 << 10) catch break :source_line 0;
break :source_line try eb.addString(line.items);
};
return .{
.msg = try eb.addString(diag.msg),
.src_loc = try eb.addSourceLocation(.{
.src_path = try eb.addString(file_name),
.line = diag.src_loc.line -| 1,
.column = diag.src_loc.column -| 1,
.span_start = start,
.span_main = diag.src_loc.offset,
.span_end = end + 1,
.source_line = source_line,
}),
.notes_len = notes_len,
};
}
pub const Bundle = struct {
file_names: std.AutoArrayHashMapUnmanaged(u32, []const u8) = .{},
category_names: std.AutoArrayHashMapUnmanaged(u32, []const u8) = .{},
diags: []Diag = &.{},
pub fn destroy(bundle: *Bundle, gpa: Allocator) void {
for (bundle.file_names.values()) |file_name| gpa.free(file_name);
for (bundle.category_names.values()) |category_name| gpa.free(category_name);
for (bundle.diags) |*diag| diag.deinit(gpa);
gpa.free(bundle.diags);
gpa.destroy(bundle);
}
pub fn parse(gpa: Allocator, path: []const u8) !*Bundle {
const BitcodeReader = @import("codegen/llvm/BitcodeReader.zig");
const BlockId = enum(u32) {
Meta = 8,
Diag,
_,
};
const RecordId = enum(u32) {
Version = 1,
DiagInfo,
SrcRange,
DiagFlag,
CatName,
FileName,
FixIt,
_,
};
const WipDiag = struct {
level: u32 = 0,
category: u32 = 0,
msg: []const u8 = &.{},
src_loc: SrcLoc = .{},
src_ranges: std.ArrayListUnmanaged(SrcRange) = .{},
sub_diags: std.ArrayListUnmanaged(Diag) = .{},
fn deinit(wip_diag: *@This(), allocator: Allocator) void {
allocator.free(wip_diag.msg);
wip_diag.src_ranges.deinit(allocator);
for (wip_diag.sub_diags.items) |*sub_diag| sub_diag.deinit(allocator);
wip_diag.sub_diags.deinit(allocator);
wip_diag.* = undefined;
}
};
const file = try std.fs.cwd().openFile(path, .{});
defer file.close();
var br = std.io.bufferedReader(file.reader());
const reader = br.reader();
var bc = BitcodeReader.init(gpa, .{ .reader = reader.any() });
defer bc.deinit();
var file_names: std.AutoArrayHashMapUnmanaged(u32, []const u8) = .{};
errdefer {
for (file_names.values()) |file_name| gpa.free(file_name);
file_names.deinit(gpa);
}
var category_names: std.AutoArrayHashMapUnmanaged(u32, []const u8) = .{};
errdefer {
for (category_names.values()) |category_name| gpa.free(category_name);
category_names.deinit(gpa);
}
var stack: std.ArrayListUnmanaged(WipDiag) = .{};
defer {
for (stack.items) |*wip_diag| wip_diag.deinit(gpa);
stack.deinit(gpa);
}
try stack.append(gpa, .{});
try bc.checkMagic("DIAG");
while (try bc.next()) |item| switch (item) {
.start_block => |block| switch (@as(BlockId, @enumFromInt(block.id))) {
.Meta => if (stack.items.len > 0) try bc.skipBlock(block),
.Diag => try stack.append(gpa, .{}),
_ => try bc.skipBlock(block),
},
.record => |record| switch (@as(RecordId, @enumFromInt(record.id))) {
.Version => if (record.operands[0] != 2) return error.InvalidVersion,
.DiagInfo => {
const top = &stack.items[stack.items.len - 1];
top.level = @intCast(record.operands[0]);
top.src_loc = .{
.file = @intCast(record.operands[1]),
.line = @intCast(record.operands[2]),
.column = @intCast(record.operands[3]),
.offset = @intCast(record.operands[4]),
};
top.category = @intCast(record.operands[5]);
top.msg = try gpa.dupe(u8, record.blob);
},
.SrcRange => try stack.items[stack.items.len - 1].src_ranges.append(gpa, .{
.start = .{
.file = @intCast(record.operands[0]),
.line = @intCast(record.operands[1]),
.column = @intCast(record.operands[2]),
.offset = @intCast(record.operands[3]),
},
.end = .{
.file = @intCast(record.operands[4]),
.line = @intCast(record.operands[5]),
.column = @intCast(record.operands[6]),
.offset = @intCast(record.operands[7]),
},
}),
.DiagFlag => {},
.CatName => {
try category_names.ensureUnusedCapacity(gpa, 1);
category_names.putAssumeCapacity(
@intCast(record.operands[0]),
try gpa.dupe(u8, record.blob),
);
},
.FileName => {
try file_names.ensureUnusedCapacity(gpa, 1);
file_names.putAssumeCapacity(
@intCast(record.operands[0]),
try gpa.dupe(u8, record.blob),
);
},
.FixIt => {},
_ => {},
},
.end_block => |block| switch (@as(BlockId, @enumFromInt(block.id))) {
.Meta => {},
.Diag => {
var wip_diag = stack.pop();
errdefer wip_diag.deinit(gpa);
const src_ranges = try wip_diag.src_ranges.toOwnedSlice(gpa);
errdefer gpa.free(src_ranges);
const sub_diags = try wip_diag.sub_diags.toOwnedSlice(gpa);
errdefer {
for (sub_diags) |*sub_diag| sub_diag.deinit(gpa);
gpa.free(sub_diags);
}
try stack.items[stack.items.len - 1].sub_diags.append(gpa, .{
.level = wip_diag.level,
.category = wip_diag.category,
.msg = wip_diag.msg,
.src_loc = wip_diag.src_loc,
.src_ranges = src_ranges,
.sub_diags = sub_diags,
});
},
_ => {},
},
};
const bundle = try gpa.create(Bundle);
assert(stack.items.len == 1);
bundle.* = .{
.file_names = file_names,
.category_names = category_names,
.diags = try stack.items[0].sub_diags.toOwnedSlice(gpa),
};
return bundle;
}
pub fn addToErrorBundle(bundle: Bundle, eb: *ErrorBundle.Wip) !void {
for (bundle.diags) |diag| {
const notes_len = diag.count() - 1;
try eb.addRootErrorMessage(try diag.toErrorMessage(eb, bundle, notes_len));
if (notes_len > 0) {
var note = try eb.reserveNotes(notes_len);
for (diag.sub_diags) |sub_diag|
try sub_diag.addToErrorBundle(eb, bundle, ¬e);
}
}
}
};
};
/// Returns if there was failure.
pub fn clearStatus(self: *CObject, gpa: Allocator) bool {
switch (self.status) {
.new => return false,
.failure, .failure_retryable => {
self.status = .new;
return true;
},
.success => |*success| {
gpa.free(success.object_path);
success.lock.release();
self.status = .new;
return false;
},
}
}
pub fn destroy(self: *CObject, gpa: Allocator) void {
_ = self.clearStatus(gpa);
gpa.destroy(self);
}
};
pub const Win32Resource = struct {
/// Relative to cwd. Owned by arena.
src: union(enum) {
rc: RcSourceFile,
manifest: []const u8,
},
status: union(enum) {
new,
success: struct {
/// The outputted result. Owned by gpa.
res_path: []u8,
/// This is a file system lock on the cache hash manifest representing this
/// object. It prevents other invocations of the Zig compiler from interfering
/// with this object until released.
lock: Cache.Lock,
},
/// There will be a corresponding ErrorMsg in Compilation.failed_win32_resources.
failure,
/// A transient failure happened when trying to compile the resource file; it may
/// succeed if we try again. There may be a corresponding ErrorMsg in
/// Compilation.failed_win32_resources. If there is not, the failure is out of memory.
failure_retryable,
},
/// Returns true if there was failure.
pub fn clearStatus(self: *Win32Resource, gpa: Allocator) bool {
switch (self.status) {
.new => return false,
.failure, .failure_retryable => {
self.status = .new;
return true;
},
.success => |*success| {
gpa.free(success.res_path);
success.lock.release();
self.status = .new;
return false;
},
}
}
pub fn destroy(self: *Win32Resource, gpa: Allocator) void {
_ = self.clearStatus(gpa);
gpa.destroy(self);
}
};
pub const MiscTask = enum {
write_builtin_zig,
rename_results,
check_whole_cache,
glibc_crt_file,
glibc_shared_objects,
musl_crt_file,
mingw_crt_file,
windows_import_lib,
libunwind,
libcxx,
libcxxabi,
libtsan,
wasi_libc_crt_file,
compiler_rt,
zig_libc,
analyze_mod,
docs_copy,
docs_wasm,
@"musl crti.o",
@"musl crtn.o",
@"musl crt1.o",
@"musl rcrt1.o",
@"musl Scrt1.o",
@"musl libc.a",
@"musl libc.so",
@"wasi crt1-reactor.o",
@"wasi crt1-command.o",
@"wasi libc.a",
@"libwasi-emulated-process-clocks.a",
@"libwasi-emulated-getpid.a",
@"libwasi-emulated-mman.a",
@"libwasi-emulated-signal.a",
@"glibc crti.o",
@"glibc crtn.o",
@"glibc Scrt1.o",
@"glibc libc_nonshared.a",
@"glibc shared object",
@"mingw-w64 crt2.o",
@"mingw-w64 dllcrt2.o",
@"mingw-w64 mingw32.lib",
};
pub const MiscError = struct {
/// Allocated with gpa.
msg: []u8,
children: ?ErrorBundle = null,
pub fn deinit(misc_err: *MiscError, gpa: Allocator) void {
gpa.free(misc_err.msg);
if (misc_err.children) |*children| {
children.deinit(gpa);
}
misc_err.* = undefined;
}
};
pub const LldError = struct {
/// Allocated with gpa.
msg: []const u8,
context_lines: []const []const u8 = &.{},
pub fn deinit(self: *LldError, gpa: Allocator) void {
for (self.context_lines) |line| {
gpa.free(line);
}
gpa.free(self.context_lines);
gpa.free(self.msg);
}
};
pub const Directory = Cache.Directory;
pub const EmitLoc = struct {
/// If this is `null` it means the file will be output to the cache directory.
/// When provided, both the open file handle and the path name must outlive the `Compilation`.
directory: ?Compilation.Directory,
/// This may not have sub-directories in it.
basename: []const u8,
};
pub const cache_helpers = struct {
pub fn addModule(hh: *Cache.HashHelper, mod: *const Package.Module) void {
addResolvedTarget(hh, mod.resolved_target);
hh.add(mod.optimize_mode);
hh.add(mod.code_model);
hh.add(mod.single_threaded);
hh.add(mod.error_tracing);
hh.add(mod.valgrind);
hh.add(mod.pic);
hh.add(mod.strip);
hh.add(mod.omit_frame_pointer);
hh.add(mod.stack_check);
hh.add(mod.red_zone);
hh.add(mod.sanitize_c);
hh.add(mod.sanitize_thread);
hh.add(mod.unwind_tables);
hh.add(mod.structured_cfg);
hh.addListOfBytes(mod.cc_argv);
}
pub fn addResolvedTarget(
hh: *Cache.HashHelper,
resolved_target: Package.Module.ResolvedTarget,
) void {
const target = resolved_target.result;
hh.add(target.cpu.arch);
hh.addBytes(target.cpu.model.name);
hh.add(target.cpu.features.ints);
hh.add(target.os.tag);
hh.add(target.os.getVersionRange());
hh.add(target.abi);
hh.add(target.ofmt);
hh.add(resolved_target.is_native_os);
hh.add(resolved_target.is_native_abi);
}
pub fn addEmitLoc(hh: *Cache.HashHelper, emit_loc: EmitLoc) void {
hh.addBytes(emit_loc.basename);
}
pub fn addOptionalEmitLoc(hh: *Cache.HashHelper, optional_emit_loc: ?EmitLoc) void {
hh.add(optional_emit_loc != null);
addEmitLoc(hh, optional_emit_loc orelse return);
}
pub fn addOptionalDebugFormat(hh: *Cache.HashHelper, x: ?Config.DebugFormat) void {
hh.add(x != null);
addDebugFormat(hh, x orelse return);
}
pub fn addDebugFormat(hh: *Cache.HashHelper, x: Config.DebugFormat) void {
const tag: @typeInfo(Config.DebugFormat).Union.tag_type.? = x;
hh.add(tag);
switch (x) {
.strip, .code_view => {},
.dwarf => |f| hh.add(f),
}
}
pub fn hashCSource(self: *Cache.Manifest, c_source: CSourceFile) !void {
_ = try self.addFile(c_source.src_path, null);
// Hash the extra flags, with special care to call addFile for file parameters.
// TODO this logic can likely be improved by utilizing clang_options_data.zig.
const file_args = [_][]const u8{"-include"};
var arg_i: usize = 0;
while (arg_i < c_source.extra_flags.len) : (arg_i += 1) {
const arg = c_source.extra_flags[arg_i];
self.hash.addBytes(arg);
for (file_args) |file_arg| {
if (mem.eql(u8, file_arg, arg) and arg_i + 1 < c_source.extra_flags.len) {
arg_i += 1;
_ = try self.addFile(c_source.extra_flags[arg_i], null);
}
}
}
}
};
pub const ClangPreprocessorMode = enum {
no,
/// This means we are doing `zig cc -E -o <path>`.
yes,
/// This means we are doing `zig cc -E`.
stdout,
/// precompiled C header
pch,
};
pub const Framework = link.File.MachO.Framework;
pub const SystemLib = link.SystemLib;
pub const CacheMode = enum { incremental, whole };
const CacheUse = union(CacheMode) {
incremental: *Incremental,
whole: *Whole,
const Whole = struct {
/// This is a pointer to a local variable inside `update()`.
cache_manifest: ?*Cache.Manifest = null,
cache_manifest_mutex: std.Thread.Mutex = .{},
/// null means -fno-emit-bin.
/// This is mutable memory allocated into the Compilation-lifetime arena (`arena`)
/// of exactly the correct size for "o/[digest]/[basename]".
/// The basename is of the outputted binary file in case we don't know the directory yet.
bin_sub_path: ?[]u8,
/// Same as `bin_sub_path` but for implibs.
implib_sub_path: ?[]u8,
docs_sub_path: ?[]u8,
lf_open_opts: link.File.OpenOptions,
tmp_artifact_directory: ?Cache.Directory,
/// Prevents other processes from clobbering files in the output directory.
lock: ?Cache.Lock,
fn releaseLock(whole: *Whole) void {
if (whole.lock) |*lock| {
lock.release();
whole.lock = null;
}
}
fn moveLock(whole: *Whole) Cache.Lock {
const result = whole.lock.?;
whole.lock = null;
return result;
}
};
const Incremental = struct {
/// Where build artifacts and incremental compilation metadata serialization go.
artifact_directory: Compilation.Directory,
};
fn deinit(cu: CacheUse) void {
switch (cu) {
.incremental => |incremental| {
incremental.artifact_directory.handle.close();
},
.whole => |whole| {
whole.releaseLock();
},
}
}
};
pub const LinkObject = struct {
path: []const u8,
must_link: bool = false,
// When the library is passed via a positional argument, it will be
// added as a full path. If it's `-l<lib>`, then just the basename.
//
// Consistent with `withLOption` variable name in lld ELF driver.
loption: bool = false,
};
pub const CreateOptions = struct {
zig_lib_directory: Directory,
local_cache_directory: Directory,
global_cache_directory: Directory,
thread_pool: *ThreadPool,
self_exe_path: ?[]const u8 = null,
/// Options that have been resolved by calling `resolveDefaults`.
config: Compilation.Config,
root_mod: *Package.Module,
/// Normally, `main_mod` and `root_mod` are the same. The exception is `zig
/// test`, in which `root_mod` is the test runner, and `main_mod` is the
/// user's source file which has the tests.
main_mod: ?*Package.Module = null,
/// This is provided so that the API user has a chance to tweak the
/// per-module settings of the standard library.
/// When this is null, a default configuration of the std lib is created
/// based on the settings of root_mod.
std_mod: ?*Package.Module = null,
root_name: []const u8,
sysroot: ?[]const u8 = null,
/// `null` means to not emit a binary file.
emit_bin: ?EmitLoc,
/// `null` means to not emit a C header file.
emit_h: ?EmitLoc = null,
/// `null` means to not emit assembly.
emit_asm: ?EmitLoc = null,
/// `null` means to not emit LLVM IR.
emit_llvm_ir: ?EmitLoc = null,
/// `null` means to not emit LLVM module bitcode.
emit_llvm_bc: ?EmitLoc = null,
/// `null` means to not emit docs.
emit_docs: ?EmitLoc = null,
/// `null` means to not emit an import lib.
emit_implib: ?EmitLoc = null,
/// Normally when using LLD to link, Zig uses a file named "lld.id" in the
/// same directory as the output binary which contains the hash of the link
/// operation, allowing Zig to skip linking when the hash would be unchanged.
/// In the case that the output binary is being emitted into a directory which
/// is externally modified - essentially anything other than zig-cache - then
/// this flag would be set to disable this machinery to avoid false positives.