forked from JuliaLang/julia
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjitlayers.cpp
More file actions
2720 lines (2483 loc) · 108 KB
/
Copy pathjitlayers.cpp
File metadata and controls
2720 lines (2483 loc) · 108 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
// This file is a part of Julia. License is MIT: https://julialang.org/license
#include "llvm-version.h"
#include "platform.h"
#include <pthread.h>
#include <stdint.h>
#include <string>
#include "llvm/IR/Mangler.h"
#include <llvm/ADT/BitmaskEnum.h>
#include <llvm/ADT/Statistic.h>
#include <llvm/ADT/StringMap.h>
#include <llvm/Analysis/TargetLibraryInfo.h>
#include <llvm/Analysis/TargetTransformInfo.h>
#include <llvm/ExecutionEngine/Orc/CompileUtils.h>
#include <llvm/ExecutionEngine/Orc/ExecutionUtils.h>
#include <llvm/ExecutionEngine/Orc/DebugObjectManagerPlugin.h>
#if JL_LLVM_VERSION >= 210000
# include <llvm/ExecutionEngine/Orc/SelfExecutorProcessControl.h>
#endif
#include <llvm/ExecutionEngine/Orc/TargetProcess/JITLoaderGDB.h>
#if JL_LLVM_VERSION >= 200000
#include <llvm/ExecutionEngine/Orc/AbsoluteSymbols.h>
#include <llvm/ExecutionEngine/Orc/EHFrameRegistrationPlugin.h>
#endif
#if JL_LLVM_VERSION >= 180000
#include <llvm/ExecutionEngine/Orc/Debugging/DebugInfoSupport.h>
#include <llvm/ExecutionEngine/Orc/Debugging/PerfSupportPlugin.h>
#include <llvm/ExecutionEngine/Orc/TargetProcess/JITLoaderPerf.h>
#endif
#if JL_LLVM_VERSION >= 190000
#include <llvm/ExecutionEngine/Orc/Debugging/VTuneSupportPlugin.h>
#include <llvm/ExecutionEngine/Orc/TargetProcess/JITLoaderVTune.h>
#endif
#include <llvm/ExecutionEngine/Orc/ExecutorProcessControl.h>
#include <llvm/IR/Verifier.h>
#include <llvm/Support/DynamicLibrary.h>
#include <llvm/Support/FormattedStream.h>
#include <llvm/Support/TimeProfiler.h>
#include <llvm/Support/SmallVectorMemoryBuffer.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Transforms/Utils/Cloning.h>
#include <llvm/Transforms/Utils/ModuleUtils.h>
#include <llvm/Bitcode/BitcodeWriter.h>
#include <llvm/ExecutionEngine/JITLink/JITLink.h>
#if JL_LLVM_VERSION >= 210000
#include <llvm/ExecutionEngine/JITLink/EHFrameSupport.h>
#include <llvm/ExecutionEngine/Orc/Shared/WrapperFunctionUtils.h>
#endif
#include <llvm/ExecutionEngine/Orc/ObjectFileInterface.h>
#include <llvm/ExecutionEngine/Orc/DebugUtils.h>
#include <llvm/Object/MachO.h>
#include <llvm/Object/ObjectFile.h>
// target machine computation
#include <llvm/CodeGen/TargetSubtargetInfo.h>
#include <llvm/MC/TargetRegistry.h>
#include <llvm/Target/TargetOptions.h>
#include <llvm/TargetParser/Host.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Object/SymbolSize.h>
using namespace llvm;
#include "jitlayers.h"
#include "julia_assert.h"
#include "processor.h"
#include "julia-task-dispatcher.h"
#if JL_LLVM_VERSION >= 180000
# include <llvm/ExecutionEngine/Orc/Debugging/DebuggerSupportPlugin.h>
#else
# include <llvm/ExecutionEngine/Orc/DebuggerSupportPlugin.h>
#endif
# include <llvm/ExecutionEngine/JITLink/EHFrameSupport.h>
# include <llvm/ExecutionEngine/JITLink/JITLinkMemoryManager.h>
# include <llvm/ExecutionEngine/Orc/MapperJITLinkMemoryManager.h>
# include <llvm/ExecutionEngine/SectionMemoryManager.h>
#define DEBUG_TYPE "julia_jitlayers"
STATISTIC(LinkedGlobals, "Number of globals linked");
STATISTIC(SpecFPtrCount, "Number of specialized function pointers compiled");
STATISTIC(UnspecFPtrCount, "Number of unspecialized function pointers compiled");
STATISTIC(ModulesAdded, "Number of modules added to the JIT");
STATISTIC(ModulesOptimized, "Number of modules optimized by the JIT");
STATISTIC(OptO0, "Number of modules optimized at level -O0");
STATISTIC(OptO1, "Number of modules optimized at level -O1");
STATISTIC(OptO2, "Number of modules optimized at level -O2");
STATISTIC(OptO3, "Number of modules optimized at level -O3");
STATISTIC(InternedGlobals, "Number of global constants interned in the string pool");
#ifdef _COMPILER_MSAN_ENABLED_
// TODO: This should not be necessary on ELF x86_64, but LLVM's implementation
// of the TLS relocations is currently broken, so enable this unconditionally.
#define MSAN_EMUTLS_WORKAROUND 1
// See https://github.com/google/sanitizers/wiki/MemorySanitizerJIT
namespace msan_workaround {
extern "C" {
extern __thread unsigned long long __msan_param_tls[];
extern __thread unsigned int __msan_param_origin_tls[];
extern __thread unsigned long long __msan_retval_tls[];
extern __thread unsigned int __msan_retval_origin_tls;
extern __thread unsigned long long __msan_va_arg_tls[];
extern __thread unsigned int __msan_va_arg_origin_tls[];
extern __thread unsigned long long __msan_va_arg_overflow_size_tls;
extern __thread unsigned int __msan_origin_tls;
}
enum class MSanTLS
{
param = 1, // __msan_param_tls
param_origin, //__msan_param_origin_tls
retval, // __msan_retval_tls
retval_origin, //__msan_retval_origin_tls
va_arg, // __msan_va_arg_tls
va_arg_origin, // __msan_va_arg_origin_tls
va_arg_overflow_size, // __msan_va_arg_overflow_size_tls
origin, //__msan_origin_tls
};
static void *getTLSAddress(void *control)
{
auto tlsIndex = static_cast<MSanTLS>(reinterpret_cast<uintptr_t>(control));
switch(tlsIndex)
{
case MSanTLS::param: return reinterpret_cast<void *>(&__msan_param_tls);
case MSanTLS::param_origin: return reinterpret_cast<void *>(&__msan_param_origin_tls);
case MSanTLS::retval: return reinterpret_cast<void *>(&__msan_retval_tls);
case MSanTLS::retval_origin: return reinterpret_cast<void *>(&__msan_retval_origin_tls);
case MSanTLS::va_arg: return reinterpret_cast<void *>(&__msan_va_arg_tls);
case MSanTLS::va_arg_origin: return reinterpret_cast<void *>(&__msan_va_arg_origin_tls);
case MSanTLS::va_arg_overflow_size: return reinterpret_cast<void *>(&__msan_va_arg_overflow_size_tls);
case MSanTLS::origin: return reinterpret_cast<void *>(&__msan_origin_tls);
default:
assert(false && "BAD MSAN TLS INDEX");
return nullptr;
}
}
}
#endif
#ifdef _OS_OPENBSD_
extern "C" {
__int128 __divti3(__int128, __int128);
__int128 __modti3(__int128, __int128);
unsigned __int128 __udivti3(unsigned __int128, unsigned __int128);
unsigned __int128 __umodti3(unsigned __int128, unsigned __int128);
}
#endif
// Snooping on which functions are being compiled, and how long it takes
extern "C" JL_DLLEXPORT_CODEGEN
void jl_dump_compiles_impl(void *s)
{
**jl_ExecutionEngine->get_dump_compiles_stream() = (ios_t*)s;
}
extern "C" JL_DLLEXPORT_CODEGEN
void jl_dump_llvm_opt_impl(void *s)
{
**jl_ExecutionEngine->get_dump_llvm_opt_stream() = (ios_t*)s;
}
static void decorate_module(Module &M) JL_NOTSAFEPOINT;
// convert local roots into global roots, if they are needed
static void jl_promote_method_roots(jl_codegen_output_t &out, jl_method_instance_t *mi) JL_CANSAFEPOINT
{
JL_GC_PROMISE_ROOTED(out.temporary_roots); // rooted by caller
if (jl_array_dim0(out.temporary_roots) == 0)
return;
jl_method_t *m = mi->def.method;
if (jl_is_method(m))
// the method might have a root for this already; use it if so
JL_LOCK(&m->writelock);
for (size_t i = 0; i < jl_array_dim0(out.temporary_roots); i++) {
jl_value_t *val = jl_array_ptr_ref(out.temporary_roots, i);
auto ref = out.global_targets.find((void*)val);
if (ref == out.global_targets.end())
continue;
auto get_global_root = [val, m]() JL_CANSAFEPOINT {
if (jl_is_globally_rooted(val))
return val;
if (jl_is_method(m) && m->roots) {
size_t j, len = jl_array_dim0(m->roots);
for (j = 0; j < len; j++) {
jl_value_t *mval = jl_array_ptr_ref(m->roots, j);
if (jl_egal(mval, val)) {
return mval;
}
}
}
return jl_as_global_root(val, 1);
};
jl_value_t *mval = get_global_root();
if (mval != val) {
GlobalVariable *GV = ref->second;
out.global_targets.erase(ref);
auto mref = out.global_targets.find((void*)mval);
if (mref != out.global_targets.end()) {
GV->replaceAllUsesWith(mref->second);
GV->eraseFromParent();
}
else {
out.global_targets[(void*)mval] = GV;
}
}
}
if (jl_is_method(m))
JL_UNLOCK(&m->writelock);
}
StringRef jl_codegen_output_t::strip_linux(StringRef name)
{
if (TargetTriple.isOSLinux()) {
if (name[0] == '@')
return name.drop_front();
}
return name;
}
std::string jl_codegen_output_t::make_name(jl_symbol_prefix_t type, jl_invoke_api_t api,
StringRef orig_name)
{
return make_name(jl_symbol_prefix(type, api), orig_name);
}
static std::atomic<size_t> global_name_counter;
template<class... Ts>
static std::string make_name_unique(Ts... args) JL_NOTSAFEPOINT
{
std::string name;
raw_string_ostream s{name};
(s << ... << args);
s << global_name_counter.fetch_add(1, memory_order_relaxed);
return name;
}
std::string jl_codegen_output_t::make_name(StringRef prefix, StringRef orig_name)
{
if (params->unique_names)
return make_name_unique(prefix, strip_linux(orig_name), "_");
return names(prefix, strip_linux(orig_name), "_");
}
std::string jl_codegen_output_t::make_name(StringRef orig_name)
{
if (params->unique_names)
return make_name_unique(strip_linux(orig_name));
return names(strip_linux(orig_name));
}
// TODO: Don't repeat so much work in this and `emit_call_specfun_other`
// TODO: just take jl_invoke_api_t argument instead of specsig?
StringRef jl_codegen_output_t::get_call_target(jl_code_instance_t *ci, bool specsig,
bool always_inline)
{
jl_invoke_api_t api = specsig ? JL_INVOKE_SPECSIG : JL_INVOKE_ARGS;
auto it = call_targets.find({ci, api});
if (it != call_targets.end()) {
it->second.external_linkage |= !always_inline;
it->second.private_linkage |= always_inline;
return it->second.decl->getName();
}
std::string protoname = make_name(JL_SYMBOL_SPECPTR_PROTO, api,
name_from_method_instance(jl_get_ci_mi(ci)));
jl_codegen_call_target_t &target = call_targets[{ci, api}];
target.external_linkage = !always_inline;
target.private_linkage = always_inline;
if (specsig) {
jl_method_instance_t *mi = jl_get_ci_mi(ci);
bool is_opaque_closure =
jl_is_method(mi->def.value) && mi->def.method->is_for_opaque_closure;
jl_returninfo_t info =
get_specsig_function(*this, &get_module(), nullptr, protoname, get_ci_abi(ci),
ci->rettype, is_opaque_closure);
target.decl = cast<Function>(info.decl.getCallee());
}
else {
target.decl = get_or_emit_fptr1(protoname, &get_module());
}
return target.decl->getName();
}
jl_emitted_output_t jl_codegen_output_t::finish(std::unique_ptr<LLVMContext> ctx,
std::unique_ptr<Module> mod,
orc::SymbolStringPool &SSP)
{
auto info = std::make_unique<jl_linker_info_t>();
auto intern = [&](StringRef name) JL_NOTSAFEPOINT {
SmallString<128> buf;
Mangler::getNameWithPrefix(buf, name, DL);
return SSP.intern(buf);
};
// Mangle and intern each part of the linking metadata, before all the
// pointers to LLVM values are invalidated.
for (auto &[ci, funcs] : ci_funcs) {
info->ci_funcs[ci] = {funcs.invoke_api,
funcs.invoke ? intern(funcs.invoke->getName()) : nullptr,
funcs.specptr ? intern(funcs.specptr->getName()) : nullptr};
}
for (auto &[call, target] : call_targets)
info->call_targets[call] = intern(target.decl->getName());
for (auto [val, gv] : global_targets) {
info->global_targets[val] = intern(gv->getName());
}
return {std::move(ctx), std::move(mod), std::move(info)};
}
// Return a specptr that is ABI-compatible with `from_abi` which invokes `codeinst`.
//
// If `codeinst` is NULL, the returned specptr instead performs a standard `apply_generic`
// call via a dynamic dispatch.
extern "C" JL_DLLEXPORT_CODEGEN
void *jl_jit_abi_converter_impl(jl_task_t *ct, jl_abi_t from_abi,
jl_code_instance_t *codeinst)
{
void *target = nullptr;
bool target_specsig = false;
jl_callptr_t invoke = nullptr;
if (codeinst != nullptr) {
uint8_t specsigflags;
jl_method_instance_t *mi = jl_get_ci_mi(codeinst);
void *specptr = nullptr;
jl_read_codeinst_invoke(codeinst, &specsigflags, &invoke, &specptr, /* waitcompile */ 1);
if (invoke != nullptr) {
if (invoke == jl_fptr_const_return_addr) {
target = nullptr;
target_specsig = false;
}
else if (invoke == jl_fptr_args_addr) {
assert(specptr != nullptr);
if (!from_abi.specsig && jl_subtype(codeinst->rettype, from_abi.rt))
return specptr; // no adapter required
target = specptr;
target_specsig = false;
}
else if (specsigflags & JL_CI_FLAGS_SPECPTR_SPECIALIZED) {
assert(specptr != nullptr);
if (from_abi.specsig && jl_egal(mi->specTypes, from_abi.sigt) && jl_egal(codeinst->rettype, from_abi.rt))
return specptr; // no adapter required
target = specptr;
target_specsig = true;
}
}
}
orc::ThreadSafeModule result_m;
std::string gf_thunk_name;
auto ctx = std::make_unique<LLVMContext>();
auto mod = jl_create_llvm_module("gfthunk", *ctx, jl_ExecutionEngine->getDataLayout(),
jl_ExecutionEngine->getTargetTriple());
jl_codegen_output_t out{*mod};
// root the wrapper types that `mark_julia_const` mints for egality-pinned
// (`TypeEgal`) argument slots while the thunk is emitted
out.temporary_roots = jl_alloc_array_1d(jl_array_any_type, 0);
JL_GC_PUSH1(&out.temporary_roots);
{
ctx->setDiscardValueNames(true);
out.imaging_mode = 0;
if (target) {
Value *llvmtarget = literal_static_pointer_val((void*)target, PointerType::get(*ctx, 0));
gf_thunk_name = emit_abi_converter(out, from_abi, codeinst, llvmtarget, target_specsig);
}
else if (invoke == jl_fptr_const_return_addr) {
assert(codeinst); // Convince the static analyzer
gf_thunk_name = emit_abi_constreturn(out, from_abi, codeinst->rettype_const);
}
else {
Value *llvminvoke = invoke ? literal_static_pointer_val((void*)invoke, PointerType::get(*ctx, 0)) : nullptr;
gf_thunk_name = emit_abi_dispatcher(out, from_abi, codeinst, llvminvoke);
}
}
auto &ES = jl_ExecutionEngine->getExecutionSession();
auto emitted = out.finish(std::move(ctx), std::move(mod), *ES.getSymbolStringPool());
out.temporary_roots = nullptr;
out.temporary_roots_set.clear();
JL_GC_POP();
jl_ExecutionEngine->addOutput(std::move(emitted));
uintptr_t Addr = jl_ExecutionEngine->getFunctionAddress(gf_thunk_name);
assert(Addr);
return (void*)Addr;
}
// lock for places where only single threaded behavior is implemented, so we need GC support
static jl_mutex_t jitlock;
// Lock hierarchy here:
// jitlock is outermost, can contain others and allows GC
// ThreadSafeContext locks are next, they should not be nested
// jl_ExecutionEngine internal locks are exclusive to this list, since OrcJIT promises to never hold a lock over a materialization unit:
// construct a query object from a query set and query handler
// lock the session
// lodge query against requested symbols, collect required materializers (if any)
// unlock the session
// dispatch materializers (if any)
// However, this guarantee relies on Julia releasing all TSC locks before causing any materialization units to be dispatched
// as materialization may need to acquire TSC locks.
static void jl_publish_compiled_ci(jl_code_instance_t *ci,
const jl_codeinst_funcs_t<void *> &addrs) JL_NOTSAFEPOINT
{
void *spec = addrs.specptr;
jl_callptr_t invoke = addrs.invoke_api == JL_INVOKE_SPECSIG ?
(jl_callptr_t)addrs.invoke :
jl_invoke_api_callptr(addrs.invoke_api);
void *prev = nullptr;
if (jl_atomic_cmpswap_acqrel(&ci->specptr.fptr, &prev, spec)) {
// only set specsig and invoke if we were the first to set specptr
// Clear compilation state bits, then set SPECPTR_SPECIALIZED if needed
if (addrs.invoke_api == JL_INVOKE_SPECSIG)
jl_atomic_fetch_or_relaxed(&ci->flags, JL_CI_FLAGS_SPECPTR_SPECIALIZED);
// we might overwrite invokeptr here; that's ok, anybody who relied on the identity
// of invokeptr either assumes that specptr was null, doesn't care about specptr, or
// will wait until flags has 0b10 set before reloading invoke
jl_atomic_store_release(&ci->invoke, invoke);
// Set INVOKE_MATCHES_SPECPTR to signal completion
jl_atomic_fetch_or_relaxed(&ci->flags, JL_CI_FLAGS_INVOKE_MATCHES_SPECPTR);
}
else {
// someone else beat us, don't commit any results
while (!(jl_atomic_load_acquire(&ci->flags) & JL_CI_FLAGS_INVOKE_MATCHES_SPECPTR))
jl_cpu_pause();
}
}
static void jl_do_dump_compile(jl_code_instance_t *codeinst, uint64_t time) JL_NOTSAFEPOINT
{
jl_method_instance_t *mi = jl_get_ci_mi(codeinst);
if (jl_is_method(mi->def.method)) {
auto stream = *jl_ExecutionEngine->get_dump_compiles_stream();
if (stream) {
ios_printf(stream, "%" PRIu64 "\t\"", time);
jl_static_show((JL_STREAM *)stream, mi->specTypes);
ios_printf(stream, "\"\n");
}
}
float orig_time = julia_half_to_float(jl_atomic_load_relaxed(&codeinst->time_compile));
jl_atomic_store_relaxed(&codeinst->time_compile,
julia_double_to_half(orig_time + time * 1e-9));
}
extern "C" JL_DLLEXPORT_CODEGEN void
jl_emit_codeinsts_to_jit_impl(jl_code_instance_t **codeinsts, jl_code_info_t **srcs, int len)
{
if (len == 0)
return;
JL_TIMING(CODEINST_COMPILE, CODEINST_COMPILE);
const char *name = name_from_method_instance(jl_get_ci_mi(codeinsts[len - 1]));
auto ctx = std::make_unique<LLVMContext>();
auto &dl = jl_ExecutionEngine->getDataLayout();
auto &tt = jl_ExecutionEngine->getTargetTriple();
auto mod = jl_create_llvm_module(name, *ctx, dl, tt);
jl_codegen_output_t out{*mod};
out.get_context().setDiscardValueNames(true);
out.imaging_mode = false;
JL_GC_PUSH1(&out.temporary_roots);
for (int i = 0; i < len; ++i) {
jl_code_instance_t *codeinst = codeinsts[i];
jl_code_info_t *src = srcs[i];
jl_method_instance_t *mi = jl_get_ci_mi(codeinst);
if (jl_atomic_load_relaxed(&codeinst->invoke))
continue;
out.temporary_roots = jl_alloc_array_1d(jl_array_any_type, 0);
out.temporary_roots_set.clear();
if (!jl_emit_codeinst(out, codeinst, src)) { // contains safepoints
JL_GC_POP();
return;
}
// contains safepoints
jl_promote_method_roots(out, mi);
emit_always_inline(out, jl_get_method_ir); // contains safepoints
// Non-opaque-closure MethodInstances are considered globally rooted
// through their methods, but for OC, we need to create a global root
// here.
if (jl_is_method(mi->def.value) && mi->def.method->is_for_opaque_closure)
jl_as_global_root((jl_value_t*)mi, 1);
}
out.temporary_roots = nullptr;
out.temporary_roots_set.clear();
JL_GC_POP();
if (out.ci_funcs.empty())
return;
emit_llvmcall_modules(out);
auto &ES = jl_ExecutionEngine->getExecutionSession();
jl_emitted_output_t emitted =
out.finish(std::move(ctx), std::move(mod), *ES.getSymbolStringPool());
jl_ExecutionEngine->addOutput(std::move(emitted));
}
extern "C" JL_DLLEXPORT_CODEGEN
int jl_compile_codeinst_impl(jl_code_instance_t *ci)
{
int newly_compiled = 0;
if (!jl_is_compiled_codeinst(ci)) {
++SpecFPtrCount;
uint64_t start = jl_typeinf_timing_begin();
jl_ExecutionEngine->publishCIs(ci, true);
jl_typeinf_timing_end(start, 0);
newly_compiled = 1;
}
return newly_compiled;
}
extern "C" JL_DLLEXPORT_CODEGEN
void jl_generate_fptr_for_unspecialized_impl(jl_code_instance_t *unspec)
{
if (jl_atomic_load_relaxed(&unspec->invoke) != NULL) {
return;
}
auto ct = jl_current_task;
bool timed = (ct->reentrant_timing & 1) == 0;
if (timed)
ct->reentrant_timing |= 1;
uint64_t compiler_start_time = 0;
uint8_t measure_compile_time_enabled = jl_atomic_load_relaxed(&jl_measure_compile_time_enabled);
if (measure_compile_time_enabled)
compiler_start_time = jl_hrtime();
jl_code_info_t *src = NULL;
JL_GC_PUSH1(&src);
jl_method_t *def = jl_get_ci_mi(unspec)->def.method;
if (jl_is_method(def)) {
src = (jl_code_info_t*)def->source;
if (src && (jl_value_t*)src != jl_nothing)
src = jl_uncompress_ir(def, NULL, (jl_value_t*)src);
}
else {
jl_method_instance_t *mi = jl_get_ci_mi(unspec);
jl_code_instance_t *uninferred = jl_cached_uninferred(jl_atomic_load_relaxed(&mi->cache), 1);
assert(uninferred);
src = (jl_code_info_t*)jl_atomic_load_relaxed(&uninferred->inferred);
assert(src);
}
if (src) {
// TODO: first prepare recursive_compile_graph(unspec, src) before taking this lock to avoid recursion?
JL_LOCK(&jitlock); // TODO: use a better lock
if (!jl_is_compiled_codeinst(unspec)) {
assert(jl_is_code_info(src));
++UnspecFPtrCount;
jl_svec_t *edges = (jl_svec_t*)src->edges;
if (jl_is_svec(edges)) {
jl_gc_write_atomic(unspec, unspec->edges, jl_svec_t, edges, release); // n.b. this assumes the field was always empty svec(), which is not entirely true
}
jl_debuginfo_t *debuginfo = src->debuginfo;
jl_gc_write_atomic(unspec, unspec->debuginfo, jl_debuginfo_t, debuginfo, release); // n.b. this assumes the field was previously NULL, which is not entirely true
jl_emit_codeinsts_to_jit(&unspec, &src, 1);
jl_ExecutionEngine->publishCIs(unspec, true);
}
JL_UNLOCK(&jitlock); // Might GC
}
JL_GC_POP();
jl_callptr_t null = nullptr;
// if we hit a codegen bug (or ran into a broken generated function or llvmcall), fall back to the interpreter as a last resort
jl_atomic_cmpswap(&unspec->invoke, &null, jl_fptr_interpret_call_addr);
if (timed) {
if (measure_compile_time_enabled) {
auto end = jl_hrtime();
jl_atomic_fetch_add_relaxed(&jl_cumulative_compile_time, end - compiler_start_time);
}
ct->reentrant_timing &= ~1ull;
}
}
// get a native disassembly for a compiled method
extern "C" JL_DLLEXPORT_CODEGEN
jl_value_t *jl_dump_method_asm_impl(jl_method_instance_t *mi, size_t world,
char emit_mc, char getwrapper, const char* asm_variant, const char *debuginfo, char binary)
{
// printing via disassembly
jl_code_instance_t *codeinst = jl_compile_method_internal(mi, world);
if (codeinst) {
uintptr_t fptr = (uintptr_t)jl_atomic_load_acquire(&codeinst->invoke);
uintptr_t specfptr = (uintptr_t)jl_atomic_load_relaxed(&codeinst->specptr.fptr);
if (getwrapper || specfptr == 0)
specfptr = fptr;
if (specfptr != 0)
return jl_dump_fptr_asm(specfptr, emit_mc, asm_variant, debuginfo, binary);
}
return jl_an_empty_string;
}
#if JL_LLVM_VERSION >= 180000
CodeGenOptLevel CodeGenOptLevelFor(int optlevel)
{
#ifdef DISABLE_OPT
return CodeGenOptLevel::None;
#else
return optlevel == 0 ? CodeGenOptLevel::None :
optlevel == 1 ? CodeGenOptLevel::Less :
optlevel == 2 ? CodeGenOptLevel::Default :
CodeGenOptLevel::Aggressive;
#endif
}
#else
CodeGenOpt::Level CodeGenOptLevelFor(int optlevel)
{
#ifdef DISABLE_OPT
return CodeGenOpt::None;
#else
return optlevel == 0 ? CodeGenOpt::None :
optlevel == 1 ? CodeGenOpt::Less :
optlevel == 2 ? CodeGenOpt::Default :
CodeGenOpt::Aggressive;
#endif
}
#endif
static auto countBasicBlocks(const Function &F) JL_NOTSAFEPOINT
{
return std::distance(F.begin(), F.end());
}
static constexpr size_t N_optlevels = 4;
static void selectOptLevel(Module &M) JL_NOTSAFEPOINT {
size_t opt_level = std::max(static_cast<int>(jl_options.opt_level), 0);
do {
if (jl_generating_output()) {
opt_level = 0;
break;
}
size_t opt_level_min = std::max(static_cast<int>(jl_options.opt_level_min), 0);
for (auto &F : M) {
if (!F.isDeclaration()) {
Attribute attr = F.getFnAttribute("julia-optimization-level");
StringRef val = attr.getValueAsString();
if (val != "") {
size_t ol = (size_t)val[0] - '0';
if (ol < opt_level)
opt_level = ol;
}
}
}
if (opt_level < opt_level_min)
opt_level = opt_level_min;
} while (0);
// currently -O3 is max
opt_level = std::min(opt_level, N_optlevels - 1);
M.addModuleFlag(Module::Warning, "julia.optlevel", opt_level);
}
static bool isJITLinkEHFrameSection(StringRef Name) JL_NOTSAFEPOINT
{
// EH-frame sections are handled by the EH-frame registration plugin. Its
// post-allocation graph state is not suitable for generic section range
// walks here.
return Name == ".eh_frame" || Name == "__eh_frame" || Name.ends_with(",__eh_frame");
}
void JLDebuginfoPlugin::notifyMaterializingWithInfo(
orc::MaterializationResponsibility &MR, jitlink::LinkGraph &G,
MemoryBufferRef InputObject, std::unique_ptr<jl_linker_info_t> LinkerInfo)
{
auto NewBuffer =
MemoryBuffer::getMemBufferCopy(InputObject.getBuffer(), G.getName());
// Re-parsing the InputObject is wasteful, but for now, this lets us
// reuse the existing debuginfo.cpp code. Should look into just
// directly pulling out all the information required in a JITLink pass
// and just keeping the required tables/DWARF sections around (perhaps
// using the LLVM DebuggerSupportPlugin as a reference).
auto NewObj =
cantFail(object::ObjectFile::createObjectFile(NewBuffer->getMemBufferRef()));
{
std::lock_guard<std::mutex> lock{PluginMutex};
assert(PendingObjs.count(&MR) == 0);
PendingObjs[&MR] = std::unique_ptr<JITObjectInfo>(new JITObjectInfo{
std::move(NewBuffer), std::move(NewObj), {}, std::move(LinkerInfo)});
}
}
// TODO: analysis disabled since we aren't able to annotate that it was safe to lock
// std::mutex here because we asserted !jl_gcunsaferegion, so we don't need to assert jl_notsafepoint
Error JLDebuginfoPlugin::notifyEmitted(MaterializationResponsibility &MR) JL_NO_SAFEPOINT_ANALYSIS // NOLINT[julia-first-decl-annotations]
{
{
std::lock_guard<std::mutex> lock(PluginMutex);
auto It = PendingObjs.find(&MR);
if (It == PendingObjs.end())
return Error::success();
auto NewInfo = PendingObjs[&MR].get();
auto getLoadAddress = [NewInfo](const StringRef &Name) -> uint64_t {
auto result = NewInfo->SectionLoadAddresses.find(Name);
if (result == NewInfo->SectionLoadAddresses.end()) {
LLVM_DEBUG({
dbgs() << "JLDebuginfoPlugin: No load address found for section '"
<< Name << "'\n";
});
return 0;
}
return result->second;
};
jl_register_jit_object(*NewInfo->Object, getLoadAddress, *NewInfo->LinkerInfo);
PendingObjs.erase(&MR);
}
return Error::success();
}
Error JLDebuginfoPlugin::notifyFailed(MaterializationResponsibility &MR)
{
std::lock_guard<std::mutex> lock(PluginMutex);
PendingObjs.erase(&MR);
return Error::success();
}
Error JLDebuginfoPlugin::notifyRemovingResources(JITDylib &JD, orc::ResourceKey K)
{
return Error::success();
}
void JLDebuginfoPlugin::notifyTransferringResources(JITDylib &JD, orc::ResourceKey DstKey,
orc::ResourceKey SrcKey) {}
void JLDebuginfoPlugin::modifyPassConfig(MaterializationResponsibility &MR, jitlink::LinkGraph &,
jitlink::PassConfiguration &PassConfig)
{
std::lock_guard<std::mutex> lock(PluginMutex);
auto It = PendingObjs.find(&MR);
if (It == PendingObjs.end())
return;
JITObjectInfo &Info = *It->second;
PassConfig.PostAllocationPasses.push_back([&Info, this](jitlink::LinkGraph &G) -> Error {
std::lock_guard<std::mutex> lock(PluginMutex);
for (const jitlink::Section &Sec : G.sections()) {
#if defined(_OS_DARWIN_)
// Canonical JITLink section names have the segment name included, e.g.
// "__TEXT,__text" or "__DWARF,__debug_str". There are some special internal
// sections without a comma separator, which we can just ignore.
size_t SepPos = Sec.getName().find(',');
if (SepPos >= 16 || (Sec.getName().size() - (SepPos + 1) > 16)) {
LLVM_DEBUG({
dbgs() << "JLDebuginfoPlugin: Ignoring section '" << Sec.getName()
<< "'\n";
});
continue;
}
auto SecName = Sec.getName().substr(SepPos + 1);
#else
auto SecName = Sec.getName();
#endif
if (isJITLinkEHFrameSection(SecName))
continue;
if (Sec.blocks().empty())
continue;
// https://github.com/llvm/llvm-project/commit/118e953b18ff07d00b8f822dfbf2991e41d6d791
Info.SectionLoadAddresses[SecName] = jitlink::SectionRange(Sec).getStart().getValue();
}
return Error::success();
});
}
namespace {
using namespace llvm::orc;
class JLMemoryUsagePlugin : public ObjectLinkingLayer::Plugin {
private:
_Atomic(size_t)* jit_bytes_size;
public:
JLMemoryUsagePlugin(_Atomic(size_t)* jit_bytes_size)
: jit_bytes_size(jit_bytes_size) {}
Error notifyFailed(orc::MaterializationResponsibility &MR) override {
return Error::success();
}
Error notifyRemovingResources(JITDylib &JD, orc::ResourceKey K) override
{
return Error::success();
}
void notifyTransferringResources(JITDylib &JD, orc::ResourceKey DstKey,
orc::ResourceKey SrcKey) override {}
void modifyPassConfig(orc::MaterializationResponsibility &,
jitlink::LinkGraph &,
jitlink::PassConfiguration &Config) override {
Config.PostAllocationPasses.push_back([this](jitlink::LinkGraph &G) {
// `G.blocks()` is exactly the union of the sections' blocks, so a
// single pass over the (non-EH-frame) sections counts every block
// once; `graph_size == code_size + data_size`
size_t graph_size = 0;
size_t code_size = 0;
size_t data_size = 0;
for (auto §ion : G.sections()) {
if (isJITLinkEHFrameSection(section.getName()))
continue;
size_t secsize = 0;
for (auto block : section.blocks()) {
secsize += block->getSize();
}
if ((section.getMemProt() & orc::MemProt::Exec) == orc::MemProt::None) {
data_size += secsize;
} else {
code_size += secsize;
}
graph_size += secsize;
}
(void) code_size;
(void) data_size;
jl_atomic_fetch_add_relaxed(this->jit_bytes_size, graph_size);
jl_timing_counter_inc(JL_TIMING_COUNTER_JITSize, graph_size);
jl_timing_counter_inc(JL_TIMING_COUNTER_JITCodeSize, code_size);
jl_timing_counter_inc(JL_TIMING_COUNTER_JITDataSize, data_size);
return Error::success();
});
}
};
} // namespace anonymous
class JLMaterializationUnit : public orc::MaterializationUnit {
public:
// Must hold LinkerMutex when calling Create and until the
// MaterializationUnit has been added to the JITDylib.
static JLMaterializationUnit Create(JuliaOJIT &JIT, ObjectLinkingLayer &OL,
jl_emitted_output_t Out) JL_NOTSAFEPOINT
{
Interface I;
auto &Syms = I.SymbolFlags;
SmallSet<SymbolStringPtr, 2> CISyms;
for (auto &[CI, Funcs] : Out.linker_info->ci_funcs) {
if (Funcs.invoke)
CISyms.insert(Funcs.invoke);
if (Funcs.specptr)
CISyms.insert(Funcs.specptr);
// If we discover that another thread added this CI to the JIT
// first, we'll still add the original symbols to CISyms (so they
// will be filtered out of the MU Interface), but we won't register them in
// CISymbols.
jl_callptr_t Expected = NULL;
CISymbolPtr Unique{};
if (jl_atomic_cmpswap_relaxed(&CI->invoke, &Expected,
jl_fptr_wait_for_compiled_addr))
Unique = JIT.makeUniqueCIName(CI, Funcs);
if (Unique.invoke)
Syms[Unique.invoke] = JITSymbolFlags::Callable | JITSymbolFlags::Exported;
if (Unique.specptr)
Syms[Unique.specptr] = JITSymbolFlags::Callable | JITSymbolFlags::Exported;
}
// Tell ORC about all the other definition in this module. When
// linker_info contains enough information to produce the full
// Interface, remove this.
auto SSP = JIT.getExecutionSession().getSymbolStringPool();
for (auto &G : Out.module->global_objects()) {
if (G.isDeclaration() || !G.hasExternalLinkage())
continue;
auto Flags = JITSymbolFlags::Exported;
if (isa<Function>(&G))
Flags |= JITSymbolFlags::Callable;
auto S = JIT.mangle(G.getName());
if (CISyms.contains(S))
continue;
Syms[S] = Flags;
}
return JLMaterializationUnit{JIT, OL, std::move(Out), std::move(I)};
}
// During materialization: finalizers disabled, GC safe
void materialize(std::unique_ptr<MaterializationResponsibility> R) JL_CANSAFEPOINT_ENTER_LEAVE override // NOLINT[julia-first-decl-annotations]
{
auto &ES = R->getExecutionSession();
std::unique_ptr<MemoryBuffer> Obj;
uint64_t start_time = jl_hrtime();
{
TimeTraceScope CompileScope("JIT Compile", Out.module->getModuleIdentifier());
// Embeds the optlevel, CPU, and features into the module, so they form part of
// the cache key.
selectOptLevel(*Out.module);
Out.module->addModuleFlag(Module::Warning, "julia.cpu",
MDString::get(*Out.ctx, JIT.getTargetCPU()));
Out.module->addModuleFlag(Module::Warning, "julia.cpu.features",
MDString::get(*Out.ctx,
JIT.getTargetFeatureString()));
Obj = JIT.OCache.get(*Out.module,
[this]() JL_CANSAFEPOINT_ENTER_LEAVE {
JIT.optimizeModule(*Out.module);
return JIT.compileModule(*Out.module);
});
if (!Obj) {
R->failMaterialization();
return;
}
// Save some memory
auto Ctx = std::move(Out.ctx);
auto M = std::move(Out.module);
}
uint64_t end_time = jl_hrtime();
for (auto [CI, _] : Out.linker_info->ci_funcs) {
JL_GC_PROMISE_ROOTED(CI);
jl_do_dump_compile(CI, end_time - start_time);
}
auto G = jitlink::createLinkGraphFromObject(Obj->getMemBufferRef(),
ES.getSymbolStringPool());
if (!G) {
#ifndef __clang_gcanalyzer__ // reportError runs an unknown callback, which cannot be annotated as safe here (but is)
ES.reportError(G.takeError());
#endif
R->failMaterialization();
return;
}
// Causes the invoke/specptr to be published when the symbols are emitted
SmallVector<jl_code_instance_t *> CIs;
for (auto [CI, _] : Out.linker_info->ci_funcs)
CIs.push_back(CI);
jl_task_t *ct = jl_current_task;
uint8_t gc_state = jl_gc_unsafe_enter(ct->ptls);
JIT.publishCIs(CIs);
jl_gc_unsafe_leave(ct->ptls, gc_state);
if (!JIT.linkOutput(*R, Obj->getMemBufferRef(), **G, std::move(Out.linker_info)))
return;
OL.emit(std::move(R), std::move(*G), std::move(Obj));
}
StringRef getName() const override JL_NOTSAFEPOINT
{
return Out.module->getName();
}
void discard(const JITDylib &JD, const SymbolStringPtr &Name) override {}
protected:
JLMaterializationUnit(JuliaOJIT &JIT, ObjectLinkingLayer &OL, jl_emitted_output_t Out,
Interface I) JL_NOTSAFEPOINT : orc::MaterializationUnit(I),
JIT(JIT),
OL(OL),
Out(std::move(Out))
{
}
private:
JuliaOJIT &JIT;
ObjectLinkingLayer &OL;
jl_emitted_output_t Out;
};
class JLTrampolineMaterializationUnit : public orc::MaterializationUnit {
public:
JLTrampolineMaterializationUnit(JuliaOJIT &JIT, ObjectLinkingLayer &OL,
SymbolStringPtr Sym, jl_code_instance_t *CI,
jl_invoke_api_t API) JL_NOTSAFEPOINT
: orc::MaterializationUnit({{{JIT.mangle(*Sym),
JITSymbolFlags::Exported | JITSymbolFlags::Callable}},
{}}),
JIT(JIT),
OL(OL),
Sym(Sym),
CI(CI),
API(API)
{
assert(API == JL_INVOKE_ARGS || API == JL_INVOKE_SPECSIG);
};
// During materialization: finalizers disabled, GC safe
void materialize(std::unique_ptr<MaterializationResponsibility> R) JL_CANSAFEPOINT_ENTER_LEAVE override // NOLINT[julia-first-decl-annotations]
{
auto Ctx = std::make_unique<LLVMContext>();
auto Mod =
jl_create_llvm_module(*Sym, *Ctx, JIT.getDataLayout(), JIT.getTargetTriple());
jl_codegen_output_t Out{*Mod};
jl_task_t *ct = jl_current_task;
uint8_t state = jl_gc_unsafe_enter(ct->ptls);
Function *F = emit_tojlinvoke(CI, "", Out);
if (API == JL_INVOKE_SPECSIG)
F = emit_specsig_to_fptr1(Out, CI, F); // may safepoint
jl_gc_unsafe_leave(ct->ptls, state);