-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathJITModule.cpp
More file actions
1362 lines (1175 loc) · 50.1 KB
/
JITModule.cpp
File metadata and controls
1362 lines (1175 loc) · 50.1 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
#include <cstdint>
#include <mutex>
#include <set>
#include <string>
#ifdef _WIN32
#ifdef _MSC_VER
#define NOMINMAX
#endif
#include <windows.h>
#else
#include <dlfcn.h>
#include <sys/mman.h>
#endif
#include "CodeGen_Internal.h"
#include "CodeGen_LLVM.h"
#include "Debug.h"
#include "JITModule.h"
#include "LLVM_Headers.h"
#include "LLVM_Output.h"
#include "LLVM_Runtime_Linker.h"
#include "Pipeline.h"
#include "Util.h"
#include "WasmExecutor.h"
namespace Halide {
namespace Internal {
using std::string;
// On 32-bit targets, LLVM JIT code may reference libgcc helper functions
// that dlsym can't always resolve (e.g. under QEMU, or when the host
// compiler inlined them). We provide wrappers and register them in a
// builtins map that getSymbolAddress consults as a fallback.
#if defined(__GNUC__) && defined(__i386__)
extern "C" unsigned long __udivdi3(unsigned long a, unsigned long b);
static const std::map<std::string, uint64_t> i386_builtins = {
{"__udivdi3", (uintptr_t)&__udivdi3},
};
#endif
// On arm-32, LLVM generates calls to __sync_* libgcc functions for atomic
// operations. We provide wrappers using GCC's __sync_* builtins, guarded
// by the __GCC_HAVE_SYNC_COMPARE_AND_SWAP_N predefined macros.
#if defined(__arm__)
static void halide__sync_synchronize() {
__sync_synchronize();
}
#ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1
static uint8_t halide__sync_lock_test_and_set_1(volatile uint8_t *ptr, uint8_t val) {
return __sync_lock_test_and_set(ptr, val);
}
#endif
#ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4
static uint32_t halide__sync_fetch_and_add_4(volatile uint32_t *ptr, uint32_t val) {
return __sync_fetch_and_add(ptr, val);
}
static uint32_t halide__sync_fetch_and_sub_4(volatile uint32_t *ptr, uint32_t val) {
return __sync_fetch_and_sub(ptr, val);
}
static uint32_t halide__sync_fetch_and_or_4(volatile uint32_t *ptr, uint32_t val) {
return __sync_fetch_and_or(ptr, val);
}
static uint32_t halide__sync_fetch_and_and_4(volatile uint32_t *ptr, uint32_t val) {
return __sync_fetch_and_and(ptr, val);
}
static uint32_t halide__sync_val_compare_and_swap_4(volatile uint32_t *ptr, uint32_t oldval, uint32_t newval) {
return __sync_val_compare_and_swap(ptr, oldval, newval);
}
#endif
#ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8
static uint64_t halide__sync_fetch_and_add_8(volatile uint64_t *ptr, uint64_t val) {
return __sync_fetch_and_add(ptr, val);
}
static uint64_t halide__sync_fetch_and_sub_8(volatile uint64_t *ptr, uint64_t val) {
return __sync_fetch_and_sub(ptr, val);
}
static uint64_t halide__sync_val_compare_and_swap_8(volatile uint64_t *ptr, uint64_t oldval, uint64_t newval) {
return __sync_val_compare_and_swap(ptr, oldval, newval);
}
#endif
static const std::map<std::string, uint64_t> arm32_sync_builtins = {
{"__sync_synchronize", (uintptr_t)&halide__sync_synchronize},
#ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1
{"__sync_lock_test_and_set_1", (uintptr_t)&halide__sync_lock_test_and_set_1},
#endif
#ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4
{"__sync_fetch_and_add_4", (uintptr_t)&halide__sync_fetch_and_add_4},
{"__sync_fetch_and_sub_4", (uintptr_t)&halide__sync_fetch_and_sub_4},
{"__sync_fetch_and_or_4", (uintptr_t)&halide__sync_fetch_and_or_4},
{"__sync_fetch_and_and_4", (uintptr_t)&halide__sync_fetch_and_and_4},
{"__sync_val_compare_and_swap_4", (uintptr_t)&halide__sync_val_compare_and_swap_4},
#endif
#ifdef __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8
{"__sync_fetch_and_add_8", (uintptr_t)&halide__sync_fetch_and_add_8},
{"__sync_fetch_and_sub_8", (uintptr_t)&halide__sync_fetch_and_sub_8},
{"__sync_val_compare_and_swap_8", (uintptr_t)&halide__sync_val_compare_and_swap_8},
#endif
};
#endif // defined(__arm__)
#ifdef _WIN32
void *get_symbol_address(const char *s) {
return (void *)GetProcAddress(GetModuleHandle(nullptr), s);
}
#else
void *get_symbol_address(const char *s) {
// Mac OS 10.11 fails to return a symbol address if nullptr or RTLD_DEFAULT
// is passed to dlsym. This seems to work.
void *handle = dlopen(nullptr, RTLD_LAZY);
void *result = dlsym(handle, s);
dlclose(handle);
return result;
}
#endif
namespace {
bool have_symbol(const char *s) {
return get_symbol_address(s) != nullptr;
}
typedef struct CUctx_st *CUcontext;
typedef struct cl_context_st *cl_context;
typedef struct cl_command_queue_st *cl_command_queue;
void load_metal() {
#if defined(__APPLE__)
if (have_symbol("MTLCreateSystemDefaultDevice")) {
debug(1) << "Metal framework already linked in...\n";
} else {
debug(1) << "Looking for Metal framework...\n";
string error;
llvm::sys::DynamicLibrary::LoadLibraryPermanently("/System/Library/Frameworks/Metal.framework/Metal", &error);
user_assert(error.empty()) << "Could not find Metal.framework\n";
}
#else
internal_error << "JIT support for Metal only implemented on OS X\n";
#endif
}
void load_vulkan() {
if (have_symbol("vkGetInstanceProcAddr")) {
debug(1) << "Vulkan support code already linked in...\n";
} else {
debug(1) << "Looking for Vulkan support code...\n";
const auto try_load = [](const char *libname) -> string {
debug(1) << "Trying " << libname << "... ";
string error;
llvm::sys::DynamicLibrary::LoadLibraryPermanently(libname, &error);
debug(1) << (error.empty() ? "found!\n" : "not found.\n");
return error;
};
string error;
auto env_libname = get_env_variable("HL_VK_LOADER_LIB");
if (!env_libname.empty()) {
error = try_load(env_libname.c_str());
}
// First, attempt to find the versioned library (per the Vulkan API docs), otherwise
// fallback to unversioned libs, and known common paths
if (!error.empty()) {
const char *libnames[] = {
#if defined(__APPLE__)
"libvulkan.1.dylib",
"libvulkan.dylib",
"/usr/local/lib/libvulkan.dylib",
"libMoltenVK.dylib",
"vulkan.framework/vulkan",
"MoltenVK.framework/MoltenVK"
#elif defined(_WIN32)
"vulkan-1.dll",
#else
"libvulkan.so.1",
"libvulkan.so",
#endif
};
for (const char *libname : libnames) {
error = try_load(libname);
if (error.empty()) {
break;
}
}
}
user_assert(error.empty()) << "Could not find a Vulkan loader library: " << error << "\n"
<< "(Try setting the env var HL_VK_LOADER_LIB to an explicit path to fix this.)\n";
}
}
void load_webgpu() {
debug(1) << "Looking for a native WebGPU implementation...\n";
const auto try_load = [](const char *libname) -> string {
debug(1) << "Trying " << libname << "... ";
string error;
llvm::sys::DynamicLibrary::LoadLibraryPermanently(libname, &error);
debug(1) << (error.empty() ? "found!\n" : "not found.\n");
return error;
};
string error;
auto env_libname = get_env_variable("HL_WEBGPU_NATIVE_LIB");
if (!env_libname.empty()) {
error = try_load(env_libname.c_str());
}
if (!error.empty()) {
const char *libnames[] = {
// Dawn (Chromium).
"libwebgpu_dawn.so",
"libwebgpu_dawn.dylib",
"webgpu_dawn.dll",
// wgpu (Firefox).
"libwgpu.so",
"libwgpu.dylib",
"wgpu.dll",
};
for (const char *libname : libnames) {
error = try_load(libname);
if (error.empty()) {
break;
}
}
}
user_assert(error.empty()) << "Could not find a native WebGPU library: " << error << "\n"
<< "(Try setting the env var HL_WEBGPU_NATIVE_LIB to an explicit path to fix this.)\n";
}
} // namespace
using namespace llvm;
class JITModuleContents {
public:
mutable RefCount ref_count;
// Just construct a module with symbols to import into other modules.
JITModuleContents() = default;
~JITModuleContents() {
if (JIT != nullptr) {
auto err = dtorRunner->run();
internal_assert(!err) << llvm::toString(std::move(err)) << "\n";
}
}
std::map<std::string, JITModule::Symbol> exports;
std::unique_ptr<llvm::LLVMContext> context = std::make_unique<llvm::LLVMContext>();
std::unique_ptr<llvm::orc::LLJIT> JIT = nullptr;
std::unique_ptr<llvm::orc::CtorDtorRunner> dtorRunner = nullptr;
std::vector<JITModule> dependencies;
JITModule::Symbol entrypoint;
JITModule::Symbol argv_entrypoint;
std::string name;
};
template<>
RefCount &ref_count<JITModuleContents>(const JITModuleContents *f) noexcept {
return f->ref_count;
}
template<>
void destroy<JITModuleContents>(const JITModuleContents *f) {
delete f;
}
namespace {
// Retrieve a function pointer from an llvm module, possibly by compiling it.
JITModule::Symbol compile_and_get_function(llvm::orc::LLJIT &JIT, const string &name) {
debug(2) << "JIT Compiling " << name << "\n";
auto addr = JIT.lookup(name);
internal_assert(addr) << llvm::toString(addr.takeError()) << "\n";
void *f = (void *)addr->getValue();
if (!f) {
internal_error << "Compiling " << name << " returned nullptr\n";
}
JITModule::Symbol symbol(f);
debug(2) << "Function " << name << " is at " << f << "\n";
return symbol;
}
// Expand LLVM's search for symbols to include code contained in a set of JITModule.
class HalideJITMemoryManager : public SectionMemoryManager {
std::vector<JITModule> modules;
public:
HalideJITMemoryManager(const std::vector<JITModule> &modules)
: modules(modules) {
}
uint64_t getSymbolAddress(const std::string &name) override {
for (const auto &module : modules) {
std::map<std::string, JITModule::Symbol>::const_iterator iter = module.exports().find(name);
if (iter == module.exports().end() && starts_with(name, "_")) {
iter = module.exports().find(name.substr(1));
}
if (iter != module.exports().end()) {
return (uint64_t)iter->second.address;
}
}
uint64_t result = SectionMemoryManager::getSymbolAddress(name);
internal_assert(result != 0)
<< "HalideJITMemoryManager: unable to find address for " << name << "\n";
return result;
}
// We don't support throwing C++ exceptions through JIT-compiled code. Avoid
// any issues with it by just opting out.
void registerEHFrames(uint8_t *, uint64_t, size_t) override {};
void deregisterEHFrames() override {};
};
} // namespace
JITModule::JITModule() {
jit_module = new JITModuleContents();
}
JITModule::JITModule(const Module &m, const LoweredFunc &fn,
const std::vector<JITModule> &dependencies) {
jit_module = new JITModuleContents();
std::unique_ptr<llvm::Module> llvm_module(compile_module_to_llvm_module(m, *jit_module->context));
std::vector<JITModule> deps_with_runtime = dependencies;
std::vector<JITModule> shared_runtime = JITSharedRuntime::get(llvm_module.get(), m.target());
deps_with_runtime.insert(deps_with_runtime.end(), shared_runtime.begin(), shared_runtime.end());
compile_module(std::move(llvm_module), fn.name, m.target(), deps_with_runtime);
// If -time-passes is in HL_LLVM_ARGS, this will print llvm pass time
// statistics. Otherwise it's a no-op.
llvm::reportAndResetTimings();
}
namespace {
void compile_module_impl(
IntrusivePtr<JITModuleContents> &jit_module,
std::unique_ptr<llvm::Module> m, const string &function_name, const Target &target,
const std::vector<JITModule> &dependencies,
const std::vector<std::string> &requested_exports) {
// Ensure that LLVM is initialized
CodeGen_LLVM::initialize_llvm();
// Make the execution engine
debug(2) << "Creating new execution engine\n";
debug(2) << "Target triple: " << m->getTargetTriple().str() << "\n";
string error_string;
llvm::for_each(*m, set_function_attributes_from_halide_target_options);
llvm::TargetOptions options;
get_target_options(*m, options);
DataLayout initial_module_data_layout = m->getDataLayout();
string module_name = m->getModuleIdentifier();
// Build TargetMachine
llvm::orc::JITTargetMachineBuilder tm_builder(llvm::Triple(m->getTargetTriple()));
tm_builder.setOptions(options);
tm_builder.setCodeGenOptLevel(CodeGenOptLevel::Aggressive);
if (target.arch == Target::Arch::RISCV) {
tm_builder.setCodeModel(llvm::CodeModel::Medium);
}
auto tm = tm_builder.createTargetMachine();
internal_assert(tm) << llvm::toString(tm.takeError()) << "\n";
DataLayout target_data_layout(tm.get()->createDataLayout());
if (initial_module_data_layout != target_data_layout) {
internal_error << "Warning: data layout mismatch between module ("
<< initial_module_data_layout.getStringRepresentation()
<< ") and what the execution engine expects ("
<< target_data_layout.getStringRepresentation() << ")\n";
}
// Create LLJIT
const auto compilerBuilder = [&](const llvm::orc::JITTargetMachineBuilder & /*jtmb*/)
-> llvm::Expected<std::unique_ptr<llvm::orc::IRCompileLayer::IRCompiler>> {
return std::make_unique<llvm::orc::TMOwningSimpleCompiler>(std::move(*tm));
};
llvm::orc::LLJITBuilderState::ObjectLinkingLayerCreator linkerBuilder;
if ((target.arch == Target::Arch::X86 && target.bits == 32) ||
(target.arch == Target::Arch::ARM && target.bits == 32) ||
target.os == Target::Windows) {
// Fallback to RTDyld-based linking to workaround errors:
// i386: "JIT session error: Unsupported i386 relocation:4" (R_386_PLT32)
// ARM 32bit: Unsupported target machine architecture in ELF object shared runtime-jitted-objectbuffer
// Windows 64-bit: JIT session error: could not register eh-frame: __register_frame function not found
linkerBuilder = [&](llvm::orc::ExecutionSession &session) {
return std::make_unique<llvm::orc::RTDyldObjectLinkingLayer>(session, [&](const llvm::MemoryBuffer &) {
return std::make_unique<HalideJITMemoryManager>(dependencies);
});
};
} else {
linkerBuilder = [](llvm::orc::ExecutionSession &session) {
return std::make_unique<llvm::orc::ObjectLinkingLayer>(session);
};
}
auto JIT = llvm::cantFail(llvm::orc::LLJITBuilder()
.setDataLayout(target_data_layout)
.setCompileFunctionCreator(compilerBuilder)
.setObjectLinkingLayerCreator(linkerBuilder)
.create());
auto ctors = llvm::orc::getConstructors(*m);
llvm::orc::CtorDtorRunner ctorRunner(JIT->getMainJITDylib());
ctorRunner.add(ctors);
auto dtors = llvm::orc::getDestructors(*m);
auto dtorRunner = std::make_unique<llvm::orc::CtorDtorRunner>(JIT->getMainJITDylib());
dtorRunner->add(dtors);
// Resolve system symbols (like pthread, dl and others)
auto gen = llvm::orc::DynamicLibrarySearchGenerator::GetForCurrentProcess(target_data_layout.getGlobalPrefix());
internal_assert(gen) << llvm::toString(gen.takeError()) << "\n";
JIT->getMainJITDylib().addGenerator(std::move(gen.get()));
llvm::orc::ThreadSafeModule tsm(std::move(m), std::move(jit_module->context));
auto err = JIT->addIRModule(std::move(tsm));
internal_assert(!err) << llvm::toString(std::move(err)) << "\n";
// Resolve symbol dependencies
llvm::orc::SymbolMap newSymbols;
auto symbolStringPool = JIT->getExecutionSession().getExecutorProcessControl().getSymbolStringPool();
for (const auto &module : dependencies) {
for (auto const &iter : module.exports()) {
orc::SymbolStringPtr name = symbolStringPool->intern(iter.first);
orc::SymbolStringPtr _name = symbolStringPool->intern("_" + iter.first);
auto symbol = llvm::orc::ExecutorAddr::fromPtr(iter.second.address);
if (!newSymbols.count(name)) {
newSymbols.insert({name, {symbol, JITSymbolFlags::Exported}});
}
if (!newSymbols.count(_name)) {
newSymbols.insert({_name, {symbol, JITSymbolFlags::Exported}});
}
}
}
// On 32-bit targets, add libgcc builtins that dlsym can't find.
#if defined(__GNUC__) && defined(__i386__)
for (const auto &[sym_name, sym_addr] : i386_builtins) {
auto name = symbolStringPool->intern(sym_name);
if (!newSymbols.count(name)) {
newSymbols.insert({name, {llvm::orc::ExecutorAddr(sym_addr), JITSymbolFlags::Exported}});
}
}
#endif
#if defined(__arm__)
for (const auto &[sym_name, sym_addr] : arm32_sync_builtins) {
auto name = symbolStringPool->intern(sym_name);
if (!newSymbols.count(name)) {
newSymbols.insert({name, {llvm::orc::ExecutorAddr(sym_addr), JITSymbolFlags::Exported}});
}
}
#endif
err = JIT->getMainJITDylib().define(orc::absoluteSymbols(std::move(newSymbols)));
internal_assert(!err) << llvm::toString(std::move(err)) << "\n";
// Retrieve function pointers from the compiled module (which also
// triggers compilation)
debug(1) << "JIT compiling " << module_name
<< " for " << target.to_string() << "\n";
using Symbol = JITModule::Symbol;
std::map<std::string, Symbol> exports;
Symbol entrypoint;
Symbol argv_entrypoint;
if (!function_name.empty()) {
entrypoint = compile_and_get_function(*JIT, function_name);
exports[function_name] = entrypoint;
argv_entrypoint = compile_and_get_function(*JIT, function_name + "_argv");
exports[function_name + "_argv"] = argv_entrypoint;
}
for (const auto &requested_export : requested_exports) {
exports[requested_export] = compile_and_get_function(*JIT, requested_export);
}
err = ctorRunner.run();
internal_assert(!err) << llvm::toString(std::move(err)) << "\n";
// Stash the various objects that need to stay alive behind a reference-counted pointer.
jit_module->exports = exports;
jit_module->JIT = std::move(JIT);
jit_module->dtorRunner = std::move(dtorRunner);
jit_module->dependencies = dependencies;
jit_module->entrypoint = entrypoint;
jit_module->argv_entrypoint = argv_entrypoint;
jit_module->name = function_name;
}
} // namespace
void JITModule::compile_module(std::unique_ptr<llvm::Module> m, const string &function_name, const Target &target,
const std::vector<JITModule> &dependencies,
const std::vector<std::string> &requested_exports) {
// LLJIT's SimpleCompiler triggers LLVM's AsmPrinter, which can use a large
// amount of stack (observed stack overflows on macOS worker threads with
// 512KB default stacks). Use run_with_large_stack to ensure enough space.
run_with_large_stack([&]() {
compile_module_impl(jit_module, std::move(m), function_name, target, dependencies, requested_exports);
});
}
/*static*/
JITModule JITModule::make_trampolines_module(const Target &target_arg,
const std::map<std::string, JITExtern> &externs,
const std::string &suffix,
const std::vector<JITModule> &deps) {
Target target = target_arg;
target.set_feature(Target::JIT);
JITModule result;
std::vector<std::pair<std::string, ExternSignature>> extern_signatures;
std::vector<std::string> requested_exports;
for (const std::pair<const std::string, JITExtern> &e : externs) {
const std::string &callee_name = e.first;
const std::string wrapper_name = callee_name + suffix;
const ExternCFunction &extern_c = e.second.extern_c_function();
result.add_extern_for_export(callee_name, extern_c);
requested_exports.push_back(wrapper_name);
extern_signatures.emplace_back(callee_name, extern_c.signature());
}
std::unique_ptr<llvm::Module> llvm_module = CodeGen_LLVM::compile_trampolines(
target, *result.jit_module->context, suffix, extern_signatures);
result.compile_module(std::move(llvm_module), /*function_name*/ "", target, deps, requested_exports);
return result;
}
const std::map<std::string, JITModule::Symbol> &JITModule::exports() const {
return jit_module->exports;
}
JITModule::Symbol JITModule::find_symbol_by_name(const std::string &name) const {
std::map<std::string, JITModule::Symbol>::iterator it = jit_module->exports.find(name);
if (it != jit_module->exports.end()) {
return it->second;
}
for (const JITModule &dep : jit_module->dependencies) {
JITModule::Symbol s = dep.find_symbol_by_name(name);
if (s.address) {
return s;
}
}
return JITModule::Symbol();
}
void *JITModule::main_function() const {
return jit_module->entrypoint.address;
}
JITModule::Symbol JITModule::entrypoint_symbol() const {
return jit_module->entrypoint;
}
int (*JITModule::argv_function() const)(const void *const *) {
return (int (*)(const void *const *))jit_module->argv_entrypoint.address;
}
JITModule::Symbol JITModule::argv_entrypoint_symbol() const {
return jit_module->argv_entrypoint;
}
namespace {
bool module_already_in_graph(const JITModuleContents *start, const JITModuleContents *target, std::set<const JITModuleContents *> &already_seen) {
if (start == target) {
return true;
}
if (already_seen.count(start) != 0) {
return false;
}
already_seen.insert(start);
for (const JITModule &dep_holder : start->dependencies) {
const JITModuleContents *dep = dep_holder.jit_module.get();
if (module_already_in_graph(dep, target, already_seen)) {
return true;
}
}
return false;
}
} // namespace
void JITModule::add_dependency(JITModule &dep) {
std::set<const JITModuleContents *> already_seen;
internal_assert(!module_already_in_graph(dep.jit_module.get(), jit_module.get(), already_seen)) << "JITModule::add_dependency: creating circular dependency graph.\n";
jit_module->dependencies.push_back(dep);
}
void JITModule::add_symbol_for_export(const std::string &name, const Symbol &extern_symbol) {
jit_module->exports[name] = extern_symbol;
}
void JITModule::add_extern_for_export(const std::string &name,
const ExternCFunction &extern_c_function) {
Symbol symbol(extern_c_function.address());
jit_module->exports[name] = symbol;
}
void JITModule::memoization_cache_set_size(int64_t size) const {
std::map<std::string, Symbol>::const_iterator f =
exports().find("halide_memoization_cache_set_size");
if (f != exports().end()) {
(reinterpret_bits<void (*)(int64_t)>(f->second.address))(size);
}
}
void JITModule::memoization_cache_evict(uint64_t eviction_key) const {
std::map<std::string, Symbol>::const_iterator f =
exports().find("halide_memoization_cache_evict");
if (f != exports().end()) {
(reinterpret_bits<void (*)(void *, uint64_t)>(f->second.address))(nullptr, eviction_key);
}
}
void JITModule::reuse_device_allocations(bool b) const {
std::map<std::string, Symbol>::const_iterator f =
exports().find("halide_reuse_device_allocations");
if (f != exports().end()) {
(reinterpret_bits<int (*)(void *, bool)>(f->second.address))(nullptr, b);
}
}
int JITModule::get_num_threads() const {
std::map<std::string, Symbol>::const_iterator f =
exports().find("halide_get_num_threads");
if (f != exports().end()) {
return (reinterpret_bits<int (*)()>(f->second.address))();
}
return 1;
}
int JITModule::set_num_threads(int n) const {
std::map<std::string, Symbol>::const_iterator f =
exports().find("halide_set_num_threads");
if (f != exports().end()) {
return (reinterpret_bits<int (*)(int)>(f->second.address))(n);
}
return 1;
}
bool JITModule::compiled() const {
return jit_module->JIT != nullptr;
}
namespace {
JITHandlers runtime_internal_handlers;
JITHandlers default_handlers;
JITHandlers active_handlers;
int64_t default_cache_size;
void merge_handlers(JITHandlers &base, const JITHandlers &addins) {
if (addins.custom_print) {
base.custom_print = addins.custom_print;
}
if (addins.custom_malloc) {
base.custom_malloc = addins.custom_malloc;
}
if (addins.custom_free) {
base.custom_free = addins.custom_free;
}
if (addins.custom_do_task) {
base.custom_do_task = addins.custom_do_task;
}
if (addins.custom_do_par_for) {
base.custom_do_par_for = addins.custom_do_par_for;
}
if (addins.custom_error) {
base.custom_error = addins.custom_error;
}
if (addins.custom_trace) {
base.custom_trace = addins.custom_trace;
}
if (addins.custom_get_symbol) {
base.custom_get_symbol = addins.custom_get_symbol;
}
if (addins.custom_load_library) {
base.custom_load_library = addins.custom_load_library;
}
if (addins.custom_get_library_symbol) {
base.custom_get_library_symbol = addins.custom_get_library_symbol;
}
if (addins.custom_cuda_acquire_context) {
base.custom_cuda_acquire_context = addins.custom_cuda_acquire_context;
}
if (addins.custom_cuda_release_context) {
base.custom_cuda_release_context = addins.custom_cuda_release_context;
}
if (addins.custom_cuda_get_stream) {
base.custom_cuda_get_stream = addins.custom_cuda_get_stream;
}
}
void print_handler(JITUserContext *context, const char *msg) {
if (context && context->handlers.custom_print) {
context->handlers.custom_print(context, msg);
} else {
active_handlers.custom_print(context, msg);
}
}
void *malloc_handler(JITUserContext *context, size_t x) {
if (context && context->handlers.custom_malloc) {
return context->handlers.custom_malloc(context, x);
} else {
return active_handlers.custom_malloc(context, x);
}
}
void free_handler(JITUserContext *context, void *ptr) {
if (context && context->handlers.custom_free) {
context->handlers.custom_free(context, ptr);
} else {
active_handlers.custom_free(context, ptr);
}
}
int do_task_handler(JITUserContext *context, int (*f)(JITUserContext *, int, uint8_t *), int idx,
uint8_t *closure) {
if (context && context->handlers.custom_do_task) {
return context->handlers.custom_do_task(context, f, idx, closure);
} else {
return active_handlers.custom_do_task(context, f, idx, closure);
}
}
int do_par_for_handler(JITUserContext *context, int (*f)(JITUserContext *, int, uint8_t *),
int min, int size, uint8_t *closure) {
if (context && context->handlers.custom_do_par_for) {
return context->handlers.custom_do_par_for(context, f, min, size, closure);
} else {
return active_handlers.custom_do_par_for(context, f, min, size, closure);
}
}
void error_handler_handler(JITUserContext *context, const char *msg) {
if (context && context->handlers.custom_error) {
context->handlers.custom_error(context, msg);
} else {
active_handlers.custom_error(context, msg);
}
}
int32_t trace_handler(JITUserContext *context, const halide_trace_event_t *e) {
if (context && context->handlers.custom_trace) {
return context->handlers.custom_trace(context, e);
} else {
return active_handlers.custom_trace(context, e);
}
}
void *get_symbol_handler(const char *name) {
return (*active_handlers.custom_get_symbol)(name);
}
void *load_library_handler(const char *name) {
return (*active_handlers.custom_load_library)(name);
}
void *get_library_symbol_handler(void *lib, const char *name) {
return (*active_handlers.custom_get_library_symbol)(lib, name);
}
int cuda_acquire_context_handler(JITUserContext *context, void **cuda_context_ptr, bool create) {
if (context && context->handlers.custom_cuda_acquire_context) {
return context->handlers.custom_cuda_acquire_context(context, cuda_context_ptr, create);
} else {
return active_handlers.custom_cuda_acquire_context(context, cuda_context_ptr, create);
}
}
int cuda_release_context_handler(JITUserContext *context) {
if (context && context->handlers.custom_cuda_release_context) {
return context->handlers.custom_cuda_release_context(context);
} else {
return active_handlers.custom_cuda_release_context(context);
}
}
int cuda_get_stream_handler(JITUserContext *context, void *cuda_context, void **cuda_stream_ptr) {
if (context && context->handlers.custom_cuda_get_stream) {
return context->handlers.custom_cuda_get_stream(context, cuda_context, cuda_stream_ptr);
} else {
return active_handlers.custom_cuda_get_stream(context, cuda_context, cuda_stream_ptr);
}
}
template<typename function_t>
function_t hook_function(const std::map<std::string, JITModule::Symbol> &exports, const char *hook_name, function_t hook) {
auto iter = exports.find(hook_name);
internal_assert(iter != exports.end()) << "Failed to find function " << hook_name << "\n";
function_t (*hook_setter)(function_t) =
reinterpret_bits<function_t (*)(function_t)>(iter->second.address);
return (*hook_setter)(hook);
}
void adjust_module_ref_count(void *arg, int32_t count) {
JITModuleContents *module = (JITModuleContents *)arg;
debug(2) << "Adjusting refcount for module " << module->name << " by " << count << "\n";
if (count > 0) {
module->ref_count.increment();
} else {
module->ref_count.decrement();
}
}
std::mutex shared_runtimes_mutex;
// The Halide runtime is broken up into pieces so that state can be
// shared across JIT compilations that do not use the same target
// options. At present, the split is into a MainShared module that
// contains most of the runtime except for device API specific code
// (GPU runtimes). There is one shared runtime per device API and a
// the JITModule for a Func depends on all device API modules
// specified in the target when it is JITted. (Instruction set variant
// specific code, such as math routines, is inlined into the module
// produced by compiling a Func so it can be specialized exactly for
// each target.)
enum RuntimeKind {
MainShared,
OpenCL,
Metal,
CUDA,
Hexagon,
D3D12Compute,
Vulkan,
WebGPU,
OpenCLDebug,
MetalDebug,
CUDADebug,
HexagonDebug,
D3D12ComputeDebug,
VulkanDebug,
WebGPUDebug,
MaxRuntimeKind
};
JITModule &shared_runtimes(RuntimeKind k) {
// We're already guarded by the shared_runtimes_mutex
static JITModule *m = nullptr;
if (!m) {
// Note that this is never freed. On windows this would invoke
// static destructors that use threading objects, and these
// don't work (crash or deadlock) after main exits.
m = new JITModule[MaxRuntimeKind];
}
return m[k];
}
JITModule &make_module(llvm::Module *for_module, Target target,
RuntimeKind runtime_kind, const std::vector<JITModule> &deps,
bool create) {
JITModule &runtime = shared_runtimes(runtime_kind);
if (!runtime.compiled() && create) {
// Ensure that JIT feature is set on target as it must be in
// order for the right runtime components to be added.
target.set_feature(Target::JIT);
// msan doesn't work for jit modules
target.set_feature(Target::MSAN, false);
Target one_gpu(target);
one_gpu.set_feature(Target::Debug, false);
one_gpu.set_feature(Target::OpenCL, false);
one_gpu.set_feature(Target::Metal, false);
one_gpu.set_feature(Target::CUDA, false);
one_gpu.set_feature(Target::HVX, false);
one_gpu.set_feature(Target::D3D12Compute, false);
one_gpu.set_feature(Target::Vulkan, false);
one_gpu.set_feature(Target::WebGPU, false);
string module_name;
switch (runtime_kind) {
case OpenCLDebug:
one_gpu.set_feature(Target::Debug);
one_gpu.set_feature(Target::OpenCL);
module_name = "debug_opencl";
break;
case OpenCL:
one_gpu.set_feature(Target::OpenCL);
module_name += "opencl";
break;
case MetalDebug:
one_gpu.set_feature(Target::Debug);
one_gpu.set_feature(Target::Metal);
load_metal();
module_name = "debug_metal";
break;
case Metal:
one_gpu.set_feature(Target::Metal);
module_name += "metal";
load_metal();
break;
case CUDADebug:
one_gpu.set_feature(Target::Debug);
one_gpu.set_feature(Target::CUDA);
module_name = "debug_cuda";
break;
case CUDA:
one_gpu.set_feature(Target::CUDA);
module_name += "cuda";
break;
case HexagonDebug:
one_gpu.set_feature(Target::Debug);
one_gpu.set_feature(Target::HVX);
module_name = "debug_hexagon";
break;
case Hexagon:
one_gpu.set_feature(Target::HVX);
module_name += "hexagon";
break;
case D3D12ComputeDebug:
one_gpu.set_feature(Target::Debug);
one_gpu.set_feature(Target::D3D12Compute);
module_name = "debug_d3d12compute";
break;
case D3D12Compute:
one_gpu.set_feature(Target::D3D12Compute);
module_name += "d3d12compute";
#if !defined(_WIN32)
internal_error << "JIT support for Direct3D 12 is only implemented on Windows 10 and above.\n";
#endif
break;
case VulkanDebug:
one_gpu.set_feature(Target::Debug);
one_gpu.set_feature(Target::Vulkan);
load_vulkan();
module_name = "debug_vulkan";
break;
case Vulkan:
one_gpu.set_feature(Target::Vulkan);
load_vulkan();
module_name += "vulkan";
break;
case WebGPUDebug:
one_gpu.set_feature(Target::Debug);
one_gpu.set_feature(Target::WebGPU);
module_name = "debug_webgpu";
load_webgpu();
break;
case WebGPU:
one_gpu.set_feature(Target::WebGPU);
module_name += "webgpu";
load_webgpu();
break;
default:
module_name = "shared runtime";
break;
}
// This function is protected by a mutex so this is thread safe.
auto module =
get_initial_module_for_target(one_gpu,
runtime.jit_module->context.get(),
true,
runtime_kind != MainShared);
if (for_module) {
clone_target_options(*for_module, *module);
}
module->setModuleIdentifier(module_name);
std::set<std::string> halide_exports_unique;
// Enumerate the functions.
for (auto &f : *module) {
// LLVM_Runtime_Linker has marked everything that should be exported as weak
if (f.hasWeakLinkage()) {
halide_exports_unique.insert(get_llvm_function_name(f));
}
}