-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy pathcodegen.cpp
10864 lines (9544 loc) · 475 KB
/
codegen.cpp
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
/*
* Copyright (c) 2015 Andrew Kelley
*
* This file is part of zig, which is MIT licensed.
* See http://opensource.org/licenses/MIT
*/
#include "analyze.hpp"
#include "ast_render.hpp"
#include "codegen.hpp"
#include "compiler.hpp"
#include "config.h"
#include "errmsg.hpp"
#include "error.hpp"
#include "hash_map.hpp"
#include "ir.hpp"
#include "os.hpp"
#include "target.hpp"
#include "util.hpp"
#include "zig_llvm.h"
#include "userland.h"
#include "dump_analysis.hpp"
#include <stdio.h>
#include <errno.h>
enum ResumeId {
ResumeIdManual,
ResumeIdReturn,
ResumeIdCall,
};
// TODO https://github.com/ziglang/zig/issues/2883
// Until then we have this same default as Clang.
// This avoids https://github.com/ziglang/zig/issues/3275
static const char *riscv_default_features = "+a,+c,+d,+f,+m,+relax";
static void init_darwin_native(CodeGen *g) {
char *osx_target = getenv("MACOSX_DEPLOYMENT_TARGET");
char *ios_target = getenv("IPHONEOS_DEPLOYMENT_TARGET");
// Allow conflicts among OSX and iOS, but choose the default platform.
if (osx_target && ios_target) {
if (g->zig_target->arch == ZigLLVM_arm ||
g->zig_target->arch == ZigLLVM_aarch64 ||
g->zig_target->arch == ZigLLVM_thumb)
{
osx_target = nullptr;
} else {
ios_target = nullptr;
}
}
if (osx_target) {
g->mmacosx_version_min = buf_create_from_str(osx_target);
} else if (ios_target) {
g->mios_version_min = buf_create_from_str(ios_target);
} else if (g->zig_target->os != OsIOS) {
g->mmacosx_version_min = buf_create_from_str("10.14");
}
}
static ZigPackage *new_package(const char *root_src_dir, const char *root_src_path, const char *pkg_path) {
ZigPackage *entry = allocate<ZigPackage>(1);
entry->package_table.init(4);
buf_init_from_str(&entry->root_src_dir, root_src_dir);
buf_init_from_str(&entry->root_src_path, root_src_path);
buf_init_from_str(&entry->pkg_path, pkg_path);
return entry;
}
ZigPackage *new_anonymous_package() {
return new_package("", "", "");
}
static const char *symbols_that_llvm_depends_on[] = {
"memcpy",
"memset",
"sqrt",
"powi",
"sin",
"cos",
"pow",
"exp",
"exp2",
"log",
"log10",
"log2",
"fma",
"fabs",
"minnum",
"maxnum",
"copysign",
"floor",
"ceil",
"trunc",
"rint",
"nearbyint",
"round",
// TODO probably all of compiler-rt needs to go here
};
void codegen_set_clang_argv(CodeGen *g, const char **args, size_t len) {
g->clang_argv = args;
g->clang_argv_len = len;
}
void codegen_set_llvm_argv(CodeGen *g, const char **args, size_t len) {
g->llvm_argv = args;
g->llvm_argv_len = len;
}
void codegen_set_test_filter(CodeGen *g, Buf *filter) {
g->test_filter = filter;
}
void codegen_set_test_name_prefix(CodeGen *g, Buf *prefix) {
g->test_name_prefix = prefix;
}
void codegen_set_lib_version(CodeGen *g, size_t major, size_t minor, size_t patch) {
g->version_major = major;
g->version_minor = minor;
g->version_patch = patch;
}
void codegen_set_emit_file_type(CodeGen *g, EmitFileType emit_file_type) {
g->emit_file_type = emit_file_type;
}
void codegen_set_each_lib_rpath(CodeGen *g, bool each_lib_rpath) {
g->each_lib_rpath = each_lib_rpath;
}
void codegen_set_errmsg_color(CodeGen *g, ErrColor err_color) {
g->err_color = err_color;
}
void codegen_set_strip(CodeGen *g, bool strip) {
g->strip_debug_symbols = strip;
if (!target_has_debug_info(g->zig_target)) {
g->strip_debug_symbols = true;
}
}
void codegen_set_out_name(CodeGen *g, Buf *out_name) {
g->root_out_name = out_name;
}
void codegen_add_lib_dir(CodeGen *g, const char *dir) {
g->lib_dirs.append(dir);
}
void codegen_add_rpath(CodeGen *g, const char *name) {
g->rpath_list.append(buf_create_from_str(name));
}
LinkLib *codegen_add_link_lib(CodeGen *g, Buf *name) {
return add_link_lib(g, name);
}
void codegen_add_forbidden_lib(CodeGen *codegen, Buf *lib) {
codegen->forbidden_libs.append(lib);
}
void codegen_add_framework(CodeGen *g, const char *framework) {
g->darwin_frameworks.append(buf_create_from_str(framework));
}
void codegen_set_mmacosx_version_min(CodeGen *g, Buf *mmacosx_version_min) {
g->mmacosx_version_min = mmacosx_version_min;
}
void codegen_set_mios_version_min(CodeGen *g, Buf *mios_version_min) {
g->mios_version_min = mios_version_min;
}
void codegen_set_rdynamic(CodeGen *g, bool rdynamic) {
g->linker_rdynamic = rdynamic;
}
void codegen_set_linker_script(CodeGen *g, const char *linker_script) {
g->linker_script = linker_script;
}
static void render_const_val(CodeGen *g, ZigValue *const_val, const char *name);
static void render_const_val_global(CodeGen *g, ZigValue *const_val, const char *name);
static LLVMValueRef gen_const_val(CodeGen *g, ZigValue *const_val, const char *name);
static void generate_error_name_table(CodeGen *g);
static bool value_is_all_undef(CodeGen *g, ZigValue *const_val);
static void gen_undef_init(CodeGen *g, uint32_t ptr_align_bytes, ZigType *value_type, LLVMValueRef ptr);
static LLVMValueRef build_alloca(CodeGen *g, ZigType *type_entry, const char *name, uint32_t alignment);
static LLVMValueRef gen_await_early_return(CodeGen *g, IrInstruction *source_instr,
LLVMValueRef target_frame_ptr, ZigType *result_type, ZigType *ptr_result_type,
LLVMValueRef result_loc, bool non_async);
static Error get_tmp_filename(CodeGen *g, Buf *out, Buf *suffix);
static void addLLVMAttr(LLVMValueRef val, LLVMAttributeIndex attr_index, const char *attr_name) {
unsigned kind_id = LLVMGetEnumAttributeKindForName(attr_name, strlen(attr_name));
assert(kind_id != 0);
LLVMAttributeRef llvm_attr = LLVMCreateEnumAttribute(LLVMGetGlobalContext(), kind_id, 0);
LLVMAddAttributeAtIndex(val, attr_index, llvm_attr);
}
static void addLLVMAttrStr(LLVMValueRef val, LLVMAttributeIndex attr_index,
const char *attr_name, const char *attr_val)
{
LLVMAttributeRef llvm_attr = LLVMCreateStringAttribute(LLVMGetGlobalContext(),
attr_name, (unsigned)strlen(attr_name), attr_val, (unsigned)strlen(attr_val));
LLVMAddAttributeAtIndex(val, attr_index, llvm_attr);
}
static void addLLVMAttrInt(LLVMValueRef val, LLVMAttributeIndex attr_index,
const char *attr_name, uint64_t attr_val)
{
unsigned kind_id = LLVMGetEnumAttributeKindForName(attr_name, strlen(attr_name));
assert(kind_id != 0);
LLVMAttributeRef llvm_attr = LLVMCreateEnumAttribute(LLVMGetGlobalContext(), kind_id, attr_val);
LLVMAddAttributeAtIndex(val, attr_index, llvm_attr);
}
static void addLLVMFnAttr(LLVMValueRef fn_val, const char *attr_name) {
return addLLVMAttr(fn_val, -1, attr_name);
}
static void addLLVMFnAttrStr(LLVMValueRef fn_val, const char *attr_name, const char *attr_val) {
return addLLVMAttrStr(fn_val, -1, attr_name, attr_val);
}
static void addLLVMFnAttrInt(LLVMValueRef fn_val, const char *attr_name, uint64_t attr_val) {
return addLLVMAttrInt(fn_val, -1, attr_name, attr_val);
}
static void addLLVMArgAttr(LLVMValueRef fn_val, unsigned param_index, const char *attr_name) {
return addLLVMAttr(fn_val, param_index + 1, attr_name);
}
static void addLLVMArgAttrInt(LLVMValueRef fn_val, unsigned param_index, const char *attr_name, uint64_t attr_val) {
return addLLVMAttrInt(fn_val, param_index + 1, attr_name, attr_val);
}
static bool is_symbol_available(CodeGen *g, const char *name) {
Buf *buf_name = buf_create_from_str(name);
bool result =
g->exported_symbol_names.maybe_get(buf_name) == nullptr &&
g->external_prototypes.maybe_get(buf_name) == nullptr;
buf_destroy(buf_name);
return result;
}
static const char *get_mangled_name(CodeGen *g, const char *original_name, bool external_linkage) {
if (external_linkage || is_symbol_available(g, original_name)) {
return original_name;
}
int n = 0;
for (;; n += 1) {
const char *new_name = buf_ptr(buf_sprintf("%s.%d", original_name, n));
if (is_symbol_available(g, new_name)) {
return new_name;
}
}
}
static ZigLLVM_CallingConv get_llvm_cc(CodeGen *g, CallingConvention cc) {
switch (cc) {
case CallingConventionUnspecified:
return ZigLLVM_Fast;
case CallingConventionC:
return ZigLLVM_C;
case CallingConventionCold:
if ((g->zig_target->arch == ZigLLVM_x86 ||
g->zig_target->arch == ZigLLVM_x86_64) &&
g->zig_target->os != OsWindows)
return ZigLLVM_Cold;
return ZigLLVM_C;
case CallingConventionNaked:
zig_unreachable();
case CallingConventionStdcall:
if (g->zig_target->arch == ZigLLVM_x86)
return ZigLLVM_X86_StdCall;
return ZigLLVM_C;
case CallingConventionFastcall:
if (g->zig_target->arch == ZigLLVM_x86)
return ZigLLVM_X86_FastCall;
return ZigLLVM_C;
case CallingConventionVectorcall:
if (g->zig_target->arch == ZigLLVM_x86)
return ZigLLVM_X86_VectorCall;
if (target_is_arm(g->zig_target) &&
target_arch_pointer_bit_width(g->zig_target->arch) == 64)
return ZigLLVM_AArch64_VectorCall;
return ZigLLVM_C;
case CallingConventionThiscall:
if (g->zig_target->arch == ZigLLVM_x86)
return ZigLLVM_X86_ThisCall;
return ZigLLVM_C;
case CallingConventionAsync:
return ZigLLVM_Fast;
case CallingConventionAPCS:
if (target_is_arm(g->zig_target))
return ZigLLVM_ARM_APCS;
return ZigLLVM_C;
case CallingConventionAAPCS:
if (target_is_arm(g->zig_target))
return ZigLLVM_ARM_AAPCS;
return ZigLLVM_C;
case CallingConventionAAPCSVFP:
if (target_is_arm(g->zig_target))
return ZigLLVM_ARM_AAPCS_VFP;
return ZigLLVM_C;
case CallingConventionInterrupt:
if (g->zig_target->arch == ZigLLVM_x86 ||
g->zig_target->arch == ZigLLVM_x86_64)
return ZigLLVM_X86_INTR;
if (g->zig_target->arch == ZigLLVM_avr)
return ZigLLVM_AVR_INTR;
if (g->zig_target->arch == ZigLLVM_msp430)
return ZigLLVM_MSP430_INTR;
return ZigLLVM_C;
case CallingConventionSignal:
if (g->zig_target->arch == ZigLLVM_avr)
return ZigLLVM_AVR_SIGNAL;
return ZigLLVM_C;
}
zig_unreachable();
}
static void add_uwtable_attr(CodeGen *g, LLVMValueRef fn_val) {
if (g->zig_target->os == OsWindows) {
addLLVMFnAttr(fn_val, "uwtable");
}
}
static LLVMLinkage to_llvm_linkage(GlobalLinkageId id) {
switch (id) {
case GlobalLinkageIdInternal:
return LLVMInternalLinkage;
case GlobalLinkageIdStrong:
return LLVMExternalLinkage;
case GlobalLinkageIdWeak:
return LLVMWeakODRLinkage;
case GlobalLinkageIdLinkOnce:
return LLVMLinkOnceODRLinkage;
}
zig_unreachable();
}
// label (grep this): [fn_frame_struct_layout]
static uint32_t frame_index_trace_arg(CodeGen *g, ZigType *return_type) {
// [0] *ReturnType (callee's)
// [1] *ReturnType (awaiter's)
// [2] ReturnType
uint32_t return_field_count = type_has_bits(return_type) ? 3 : 0;
return frame_ret_start + return_field_count;
}
// label (grep this): [fn_frame_struct_layout]
static uint32_t frame_index_arg(CodeGen *g, ZigType *return_type) {
bool have_stack_trace = codegen_fn_has_err_ret_tracing_arg(g, return_type);
// [0] *StackTrace (callee's)
// [1] *StackTrace (awaiter's)
uint32_t trace_field_count = have_stack_trace ? 2 : 0;
return frame_index_trace_arg(g, return_type) + trace_field_count;
}
// label (grep this): [fn_frame_struct_layout]
static uint32_t frame_index_trace_stack(CodeGen *g, FnTypeId *fn_type_id) {
uint32_t result = frame_index_arg(g, fn_type_id->return_type);
for (size_t i = 0; i < fn_type_id->param_count; i += 1) {
if (type_has_bits(fn_type_id->param_info->type)) {
result += 1;
}
}
return result;
}
static uint32_t get_err_ret_trace_arg_index(CodeGen *g, ZigFn *fn_table_entry) {
if (!g->have_err_ret_tracing) {
return UINT32_MAX;
}
if (fn_is_async(fn_table_entry)) {
return UINT32_MAX;
}
ZigType *fn_type = fn_table_entry->type_entry;
if (!fn_type_can_fail(&fn_type->data.fn.fn_type_id)) {
return UINT32_MAX;
}
ZigType *return_type = fn_type->data.fn.fn_type_id.return_type;
bool first_arg_ret = type_has_bits(return_type) && handle_is_ptr(return_type);
return first_arg_ret ? 1 : 0;
}
static void maybe_export_dll(CodeGen *g, LLVMValueRef global_value, GlobalLinkageId linkage) {
if (linkage != GlobalLinkageIdInternal && g->zig_target->os == OsWindows && g->is_dynamic) {
LLVMSetDLLStorageClass(global_value, LLVMDLLExportStorageClass);
}
}
static void maybe_import_dll(CodeGen *g, LLVMValueRef global_value, GlobalLinkageId linkage) {
if (linkage != GlobalLinkageIdInternal && g->zig_target->os == OsWindows) {
// TODO come up with a good explanation/understanding for why we never do
// DLLImportStorageClass. Empirically it only causes problems. But let's have
// this documented and then clean up the code accordingly.
//LLVMSetDLLStorageClass(global_value, LLVMDLLImportStorageClass);
}
}
static bool cc_want_sret_attr(CallingConvention cc) {
switch (cc) {
case CallingConventionNaked:
zig_unreachable();
case CallingConventionC:
case CallingConventionCold:
case CallingConventionInterrupt:
case CallingConventionSignal:
case CallingConventionStdcall:
case CallingConventionFastcall:
case CallingConventionVectorcall:
case CallingConventionThiscall:
case CallingConventionAPCS:
case CallingConventionAAPCS:
case CallingConventionAAPCSVFP:
return true;
case CallingConventionAsync:
case CallingConventionUnspecified:
return false;
}
zig_unreachable();
}
static bool codegen_have_frame_pointer(CodeGen *g) {
return g->build_mode == BuildModeDebug;
}
static LLVMValueRef make_fn_llvm_value(CodeGen *g, ZigFn *fn) {
const char *unmangled_name = buf_ptr(&fn->symbol_name);
const char *symbol_name;
GlobalLinkageId linkage;
if (fn->body_node == nullptr) {
symbol_name = unmangled_name;
linkage = GlobalLinkageIdStrong;
} else if (fn->export_list.length == 0) {
symbol_name = get_mangled_name(g, unmangled_name, false);
linkage = GlobalLinkageIdInternal;
} else {
GlobalExport *fn_export = &fn->export_list.items[0];
symbol_name = buf_ptr(&fn_export->name);
linkage = fn_export->linkage;
}
CallingConvention cc = fn->type_entry->data.fn.fn_type_id.cc;
bool is_async = fn_is_async(fn);
ZigType *fn_type = fn->type_entry;
// Make the raw_type_ref populated
resolve_llvm_types_fn(g, fn);
LLVMTypeRef fn_llvm_type = fn->raw_type_ref;
LLVMValueRef llvm_fn = nullptr;
if (fn->body_node == nullptr) {
const unsigned fn_addrspace = ZigLLVMDataLayoutGetProgramAddressSpace(g->target_data_ref);
LLVMValueRef existing_llvm_fn = LLVMGetNamedFunction(g->module, symbol_name);
if (existing_llvm_fn) {
return LLVMConstBitCast(existing_llvm_fn, LLVMPointerType(fn_llvm_type, fn_addrspace));
} else {
Buf *buf_symbol_name = buf_create_from_str(symbol_name);
auto entry = g->exported_symbol_names.maybe_get(buf_symbol_name);
buf_destroy(buf_symbol_name);
if (entry == nullptr) {
llvm_fn = LLVMAddFunction(g->module, symbol_name, fn_llvm_type);
if (target_is_wasm(g->zig_target)) {
assert(fn->proto_node->type == NodeTypeFnProto);
AstNodeFnProto *fn_proto = &fn->proto_node->data.fn_proto;
if (fn_proto-> is_extern && fn_proto->lib_name != nullptr ) {
addLLVMFnAttrStr(llvm_fn, "wasm-import-module", buf_ptr(fn_proto->lib_name));
}
}
} else {
assert(entry->value->id == TldIdFn);
TldFn *tld_fn = reinterpret_cast<TldFn *>(entry->value);
// Make the raw_type_ref populated
resolve_llvm_types_fn(g, tld_fn->fn_entry);
tld_fn->fn_entry->llvm_value = LLVMAddFunction(g->module, symbol_name,
tld_fn->fn_entry->raw_type_ref);
llvm_fn = LLVMConstBitCast(tld_fn->fn_entry->llvm_value, LLVMPointerType(fn_llvm_type, fn_addrspace));
return llvm_fn;
}
}
} else {
if (llvm_fn == nullptr) {
llvm_fn = LLVMAddFunction(g->module, symbol_name, fn_llvm_type);
}
for (size_t i = 1; i < fn->export_list.length; i += 1) {
GlobalExport *fn_export = &fn->export_list.items[i];
LLVMAddAlias(g->module, LLVMTypeOf(llvm_fn), llvm_fn, buf_ptr(&fn_export->name));
}
}
switch (fn->fn_inline) {
case FnInlineAlways:
addLLVMFnAttr(llvm_fn, "alwaysinline");
g->inline_fns.append(fn);
break;
case FnInlineNever:
addLLVMFnAttr(llvm_fn, "noinline");
break;
case FnInlineAuto:
if (fn->alignstack_value != 0) {
addLLVMFnAttr(llvm_fn, "noinline");
}
break;
}
if (cc == CallingConventionNaked) {
addLLVMFnAttr(llvm_fn, "naked");
} else {
ZigLLVMFunctionSetCallingConv(llvm_fn, get_llvm_cc(g, cc));
}
bool want_cold = fn->is_cold || cc == CallingConventionCold;
if (want_cold) {
ZigLLVMAddFunctionAttrCold(llvm_fn);
}
LLVMSetLinkage(llvm_fn, to_llvm_linkage(linkage));
if (linkage == GlobalLinkageIdInternal) {
LLVMSetUnnamedAddr(llvm_fn, true);
}
ZigType *return_type = fn_type->data.fn.fn_type_id.return_type;
if (return_type->id == ZigTypeIdUnreachable) {
addLLVMFnAttr(llvm_fn, "noreturn");
}
if (fn->body_node != nullptr) {
maybe_export_dll(g, llvm_fn, linkage);
bool want_fn_safety = g->build_mode != BuildModeFastRelease &&
g->build_mode != BuildModeSmallRelease &&
!fn->def_scope->safety_off;
if (want_fn_safety) {
if (g->libc_link_lib != nullptr) {
addLLVMFnAttr(llvm_fn, "sspstrong");
addLLVMFnAttrStr(llvm_fn, "stack-protector-buffer-size", "4");
}
}
if (g->have_stack_probing && !fn->def_scope->safety_off) {
addLLVMFnAttrStr(llvm_fn, "probe-stack", "__zig_probe_stack");
} else if (g->zig_target->os == OsUefi) {
addLLVMFnAttrStr(llvm_fn, "no-stack-arg-probe", "");
}
} else {
maybe_import_dll(g, llvm_fn, linkage);
}
if (fn->alignstack_value != 0) {
addLLVMFnAttrInt(llvm_fn, "alignstack", fn->alignstack_value);
}
addLLVMFnAttr(llvm_fn, "nounwind");
add_uwtable_attr(g, llvm_fn);
addLLVMFnAttr(llvm_fn, "nobuiltin");
if (codegen_have_frame_pointer(g) && fn->fn_inline != FnInlineAlways) {
ZigLLVMAddFunctionAttr(llvm_fn, "no-frame-pointer-elim", "true");
ZigLLVMAddFunctionAttr(llvm_fn, "no-frame-pointer-elim-non-leaf", nullptr);
}
if (fn->section_name) {
LLVMSetSection(llvm_fn, buf_ptr(fn->section_name));
}
if (fn->align_bytes > 0) {
LLVMSetAlignment(llvm_fn, (unsigned)fn->align_bytes);
} else {
// We'd like to set the best alignment for the function here, but on Darwin LLVM gives
// "Cannot getTypeInfo() on a type that is unsized!" assertion failure when calling
// any of the functions for getting alignment. Not specifying the alignment should
// use the ABI alignment, which is fine.
}
if (is_async) {
addLLVMArgAttr(llvm_fn, 0, "nonnull");
} else {
unsigned init_gen_i = 0;
if (!type_has_bits(return_type)) {
// nothing to do
} else if (type_is_nonnull_ptr(return_type)) {
addLLVMAttr(llvm_fn, 0, "nonnull");
} else if (want_first_arg_sret(g, &fn_type->data.fn.fn_type_id)) {
// Sret pointers must not be address 0
addLLVMArgAttr(llvm_fn, 0, "nonnull");
addLLVMArgAttr(llvm_fn, 0, "sret");
if (cc_want_sret_attr(cc)) {
addLLVMArgAttr(llvm_fn, 0, "noalias");
}
init_gen_i = 1;
}
// set parameter attributes
FnWalk fn_walk = {};
fn_walk.id = FnWalkIdAttrs;
fn_walk.data.attrs.fn = fn;
fn_walk.data.attrs.llvm_fn = llvm_fn;
fn_walk.data.attrs.gen_i = init_gen_i;
walk_function_params(g, fn_type, &fn_walk);
uint32_t err_ret_trace_arg_index = get_err_ret_trace_arg_index(g, fn);
if (err_ret_trace_arg_index != UINT32_MAX) {
// Error return trace memory is in the stack, which is impossible to be at address 0
// on any architecture.
addLLVMArgAttr(llvm_fn, (unsigned)err_ret_trace_arg_index, "nonnull");
}
}
return llvm_fn;
}
static LLVMValueRef fn_llvm_value(CodeGen *g, ZigFn *fn) {
if (fn->llvm_value)
return fn->llvm_value;
fn->llvm_value = make_fn_llvm_value(g, fn);
fn->llvm_name = strdup(LLVMGetValueName(fn->llvm_value));
return fn->llvm_value;
}
static ZigLLVMDIScope *get_di_scope(CodeGen *g, Scope *scope) {
if (scope->di_scope)
return scope->di_scope;
ZigType *import = get_scope_import(scope);
switch (scope->id) {
case ScopeIdCImport:
zig_unreachable();
case ScopeIdFnDef:
{
assert(scope->parent);
ScopeFnDef *fn_scope = (ScopeFnDef *)scope;
ZigFn *fn_table_entry = fn_scope->fn_entry;
if (!fn_table_entry->proto_node)
return get_di_scope(g, scope->parent);
unsigned line_number = (unsigned)(fn_table_entry->proto_node->line == 0) ?
0 : (fn_table_entry->proto_node->line + 1);
unsigned scope_line = line_number;
bool is_definition = fn_table_entry->body_node != nullptr;
bool is_optimized = g->build_mode != BuildModeDebug;
bool is_internal_linkage = (fn_table_entry->body_node != nullptr &&
fn_table_entry->export_list.length == 0);
unsigned flags = ZigLLVM_DIFlags_StaticMember;
ZigLLVMDIScope *fn_di_scope = get_di_scope(g, scope->parent);
assert(fn_di_scope != nullptr);
assert(fn_table_entry->raw_di_type != nullptr);
ZigLLVMDISubprogram *subprogram = ZigLLVMCreateFunction(g->dbuilder,
fn_di_scope, buf_ptr(&fn_table_entry->symbol_name), "",
import->data.structure.root_struct->di_file, line_number,
fn_table_entry->raw_di_type, is_internal_linkage,
is_definition, scope_line, flags, is_optimized, nullptr);
scope->di_scope = ZigLLVMSubprogramToScope(subprogram);
if (!g->strip_debug_symbols) {
ZigLLVMFnSetSubprogram(fn_llvm_value(g, fn_table_entry), subprogram);
}
return scope->di_scope;
}
case ScopeIdDecls:
if (scope->parent) {
ScopeDecls *decls_scope = (ScopeDecls *)scope;
assert(decls_scope->container_type);
scope->di_scope = ZigLLVMTypeToScope(get_llvm_di_type(g, decls_scope->container_type));
} else {
scope->di_scope = ZigLLVMFileToScope(import->data.structure.root_struct->di_file);
}
return scope->di_scope;
case ScopeIdBlock:
case ScopeIdDefer:
{
assert(scope->parent);
ZigLLVMDILexicalBlock *di_block = ZigLLVMCreateLexicalBlock(g->dbuilder,
get_di_scope(g, scope->parent),
import->data.structure.root_struct->di_file,
(unsigned)scope->source_node->line + 1,
(unsigned)scope->source_node->column + 1);
scope->di_scope = ZigLLVMLexicalBlockToScope(di_block);
return scope->di_scope;
}
case ScopeIdVarDecl:
case ScopeIdDeferExpr:
case ScopeIdLoop:
case ScopeIdSuspend:
case ScopeIdCompTime:
case ScopeIdRuntime:
case ScopeIdTypeOf:
case ScopeIdExpr:
return get_di_scope(g, scope->parent);
}
zig_unreachable();
}
static void clear_debug_source_node(CodeGen *g) {
ZigLLVMClearCurrentDebugLocation(g->builder);
}
static LLVMValueRef get_arithmetic_overflow_fn(CodeGen *g, ZigType *operand_type,
const char *signed_name, const char *unsigned_name)
{
ZigType *int_type = (operand_type->id == ZigTypeIdVector) ? operand_type->data.vector.elem_type : operand_type;
char fn_name[64];
assert(int_type->id == ZigTypeIdInt);
const char *signed_str = int_type->data.integral.is_signed ? signed_name : unsigned_name;
LLVMTypeRef param_types[] = {
get_llvm_type(g, operand_type),
get_llvm_type(g, operand_type),
};
if (operand_type->id == ZigTypeIdVector) {
sprintf(fn_name, "llvm.%s.with.overflow.v%" PRIu32 "i%" PRIu32, signed_str,
operand_type->data.vector.len, int_type->data.integral.bit_count);
LLVMTypeRef return_elem_types[] = {
get_llvm_type(g, operand_type),
LLVMVectorType(LLVMInt1Type(), operand_type->data.vector.len),
};
LLVMTypeRef return_struct_type = LLVMStructType(return_elem_types, 2, false);
LLVMTypeRef fn_type = LLVMFunctionType(return_struct_type, param_types, 2, false);
LLVMValueRef fn_val = LLVMAddFunction(g->module, fn_name, fn_type);
assert(LLVMGetIntrinsicID(fn_val));
return fn_val;
} else {
sprintf(fn_name, "llvm.%s.with.overflow.i%" PRIu32, signed_str, int_type->data.integral.bit_count);
LLVMTypeRef return_elem_types[] = {
get_llvm_type(g, operand_type),
LLVMInt1Type(),
};
LLVMTypeRef return_struct_type = LLVMStructType(return_elem_types, 2, false);
LLVMTypeRef fn_type = LLVMFunctionType(return_struct_type, param_types, 2, false);
LLVMValueRef fn_val = LLVMAddFunction(g->module, fn_name, fn_type);
assert(LLVMGetIntrinsicID(fn_val));
return fn_val;
}
}
static LLVMValueRef get_int_overflow_fn(CodeGen *g, ZigType *operand_type, AddSubMul add_sub_mul) {
ZigType *int_type = (operand_type->id == ZigTypeIdVector) ? operand_type->data.vector.elem_type : operand_type;
assert(int_type->id == ZigTypeIdInt);
ZigLLVMFnKey key = {};
key.id = ZigLLVMFnIdOverflowArithmetic;
key.data.overflow_arithmetic.is_signed = int_type->data.integral.is_signed;
key.data.overflow_arithmetic.add_sub_mul = add_sub_mul;
key.data.overflow_arithmetic.bit_count = (uint32_t)int_type->data.integral.bit_count;
key.data.overflow_arithmetic.vector_len = (operand_type->id == ZigTypeIdVector) ?
operand_type->data.vector.len : 0;
auto existing_entry = g->llvm_fn_table.maybe_get(key);
if (existing_entry)
return existing_entry->value;
LLVMValueRef fn_val;
switch (add_sub_mul) {
case AddSubMulAdd:
fn_val = get_arithmetic_overflow_fn(g, operand_type, "sadd", "uadd");
break;
case AddSubMulSub:
fn_val = get_arithmetic_overflow_fn(g, operand_type, "ssub", "usub");
break;
case AddSubMulMul:
fn_val = get_arithmetic_overflow_fn(g, operand_type, "smul", "umul");
break;
}
g->llvm_fn_table.put(key, fn_val);
return fn_val;
}
static LLVMValueRef get_float_fn(CodeGen *g, ZigType *type_entry, ZigLLVMFnId fn_id, BuiltinFnId op) {
assert(type_entry->id == ZigTypeIdFloat ||
type_entry->id == ZigTypeIdVector);
bool is_vector = (type_entry->id == ZigTypeIdVector);
ZigType *float_type = is_vector ? type_entry->data.vector.elem_type : type_entry;
ZigLLVMFnKey key = {};
key.id = fn_id;
key.data.floating.bit_count = (uint32_t)float_type->data.floating.bit_count;
key.data.floating.vector_len = is_vector ? (uint32_t)type_entry->data.vector.len : 0;
key.data.floating.op = op;
auto existing_entry = g->llvm_fn_table.maybe_get(key);
if (existing_entry)
return existing_entry->value;
const char *name;
uint32_t num_args;
if (fn_id == ZigLLVMFnIdFMA) {
name = "fma";
num_args = 3;
} else if (fn_id == ZigLLVMFnIdFloatOp) {
name = float_op_to_name(op);
num_args = 1;
} else {
zig_unreachable();
}
char fn_name[64];
if (is_vector)
sprintf(fn_name, "llvm.%s.v%" PRIu32 "f%" PRIu32, name, key.data.floating.vector_len, key.data.floating.bit_count);
else
sprintf(fn_name, "llvm.%s.f%" PRIu32, name, key.data.floating.bit_count);
LLVMTypeRef float_type_ref = get_llvm_type(g, type_entry);
LLVMTypeRef return_elem_types[3] = {
float_type_ref,
float_type_ref,
float_type_ref,
};
LLVMTypeRef fn_type = LLVMFunctionType(float_type_ref, return_elem_types, num_args, false);
LLVMValueRef fn_val = LLVMAddFunction(g->module, fn_name, fn_type);
assert(LLVMGetIntrinsicID(fn_val));
g->llvm_fn_table.put(key, fn_val);
return fn_val;
}
static LLVMValueRef gen_store_untyped(CodeGen *g, LLVMValueRef value, LLVMValueRef ptr,
uint32_t alignment, bool is_volatile)
{
LLVMValueRef instruction = LLVMBuildStore(g->builder, value, ptr);
if (is_volatile) LLVMSetVolatile(instruction, true);
if (alignment != 0) {
LLVMSetAlignment(instruction, alignment);
}
return instruction;
}
static LLVMValueRef gen_store(CodeGen *g, LLVMValueRef value, LLVMValueRef ptr, ZigType *ptr_type) {
assert(ptr_type->id == ZigTypeIdPointer);
uint32_t alignment = get_ptr_align(g, ptr_type);
return gen_store_untyped(g, value, ptr, alignment, ptr_type->data.pointer.is_volatile);
}
static LLVMValueRef gen_load_untyped(CodeGen *g, LLVMValueRef ptr, uint32_t alignment, bool is_volatile,
const char *name)
{
LLVMValueRef result = LLVMBuildLoad(g->builder, ptr, name);
if (is_volatile) LLVMSetVolatile(result, true);
if (alignment == 0) {
LLVMSetAlignment(result, LLVMABIAlignmentOfType(g->target_data_ref, LLVMGetElementType(LLVMTypeOf(ptr))));
} else {
LLVMSetAlignment(result, alignment);
}
return result;
}
static LLVMValueRef gen_load(CodeGen *g, LLVMValueRef ptr, ZigType *ptr_type, const char *name) {
assert(ptr_type->id == ZigTypeIdPointer);
uint32_t alignment = get_ptr_align(g, ptr_type);
return gen_load_untyped(g, ptr, alignment, ptr_type->data.pointer.is_volatile, name);
}
static LLVMValueRef get_handle_value(CodeGen *g, LLVMValueRef ptr, ZigType *type, ZigType *ptr_type) {
if (type_has_bits(type)) {
if (handle_is_ptr(type)) {
return ptr;
} else {
assert(ptr_type->id == ZigTypeIdPointer);
return gen_load(g, ptr, ptr_type, "");
}
} else {
return nullptr;
}
}
static void ir_assert(bool ok, IrInstruction *source_instruction) {
if (ok) return;
src_assert(ok, source_instruction->source_node);
}
static bool ir_want_fast_math(CodeGen *g, IrInstruction *instruction) {
// TODO memoize
Scope *scope = instruction->scope;
while (scope) {
if (scope->id == ScopeIdBlock) {
ScopeBlock *block_scope = (ScopeBlock *)scope;
if (block_scope->fast_math_set_node)
return block_scope->fast_math_on;
} else if (scope->id == ScopeIdDecls) {
ScopeDecls *decls_scope = (ScopeDecls *)scope;
if (decls_scope->fast_math_set_node)
return decls_scope->fast_math_on;
}
scope = scope->parent;
}
return false;
}
static bool ir_want_runtime_safety_scope(CodeGen *g, Scope *scope) {
// TODO memoize
while (scope) {
if (scope->id == ScopeIdBlock) {
ScopeBlock *block_scope = (ScopeBlock *)scope;
if (block_scope->safety_set_node)
return !block_scope->safety_off;
} else if (scope->id == ScopeIdDecls) {
ScopeDecls *decls_scope = (ScopeDecls *)scope;
if (decls_scope->safety_set_node)
return !decls_scope->safety_off;
}
scope = scope->parent;
}
return (g->build_mode != BuildModeFastRelease &&
g->build_mode != BuildModeSmallRelease);
}
static bool ir_want_runtime_safety(CodeGen *g, IrInstruction *instruction) {
return ir_want_runtime_safety_scope(g, instruction->scope);
}
static Buf *panic_msg_buf(PanicMsgId msg_id) {
switch (msg_id) {
case PanicMsgIdCount:
zig_unreachable();
case PanicMsgIdBoundsCheckFailure:
return buf_create_from_str("index out of bounds");
case PanicMsgIdCastNegativeToUnsigned:
return buf_create_from_str("attempt to cast negative value to unsigned integer");
case PanicMsgIdCastTruncatedData:
return buf_create_from_str("integer cast truncated bits");
case PanicMsgIdIntegerOverflow:
return buf_create_from_str("integer overflow");
case PanicMsgIdShlOverflowedBits:
return buf_create_from_str("left shift overflowed bits");
case PanicMsgIdShrOverflowedBits:
return buf_create_from_str("right shift overflowed bits");
case PanicMsgIdDivisionByZero:
return buf_create_from_str("division by zero");
case PanicMsgIdRemainderDivisionByZero:
return buf_create_from_str("remainder division by zero or negative value");
case PanicMsgIdExactDivisionRemainder:
return buf_create_from_str("exact division produced remainder");
case PanicMsgIdSliceWidenRemainder:
return buf_create_from_str("slice widening size mismatch");
case PanicMsgIdUnwrapOptionalFail:
return buf_create_from_str("attempt to unwrap null");
case PanicMsgIdUnreachable:
return buf_create_from_str("reached unreachable code");
case PanicMsgIdInvalidErrorCode:
return buf_create_from_str("invalid error code");
case PanicMsgIdIncorrectAlignment:
return buf_create_from_str("incorrect alignment");
case PanicMsgIdBadUnionField:
return buf_create_from_str("access of inactive union field");
case PanicMsgIdBadEnumValue:
return buf_create_from_str("invalid enum value");
case PanicMsgIdFloatToInt:
return buf_create_from_str("integer part of floating point value out of bounds");
case PanicMsgIdPtrCastNull:
return buf_create_from_str("cast causes pointer to be null");
case PanicMsgIdBadResume:
return buf_create_from_str("resumed an async function which already returned");
case PanicMsgIdBadAwait:
return buf_create_from_str("async function awaited twice");
case PanicMsgIdBadReturn:
return buf_create_from_str("async function returned twice");
case PanicMsgIdResumedAnAwaitingFn:
return buf_create_from_str("awaiting function resumed");
case PanicMsgIdFrameTooSmall:
return buf_create_from_str("frame too small");
case PanicMsgIdResumedFnPendingAwait:
return buf_create_from_str("resumed an async function which can only be awaited");
case PanicMsgIdBadNoAsyncCall:
return buf_create_from_str("async function called with noasync suspended");
case PanicMsgIdResumeNotSuspendedFn:
return buf_create_from_str("resumed a non-suspended function");
case PanicMsgIdBadSentinel:
return buf_create_from_str("sentinel mismatch");
}
zig_unreachable();
}
static LLVMValueRef get_panic_msg_ptr_val(CodeGen *g, PanicMsgId msg_id) {
ZigValue *val = &g->panic_msg_vals[msg_id];
if (!val->llvm_global) {
Buf *buf_msg = panic_msg_buf(msg_id);
ZigValue *array_val = create_const_str_lit(g, buf_msg)->data.x_ptr.data.ref.pointee;
init_const_slice(g, val, array_val, 0, buf_len(buf_msg), true);
render_const_val(g, val, "");
render_const_val_global(g, val, "");
assert(val->llvm_global);
}