blob: 567f11d3859b1970afab85f658bc3eab9727eb3b [file] [log] [blame]
Nicolas Capens41a73022020-01-30 00:30:14 -05001// Copyright 2020 The SwiftShader Authors. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include "LLVMReactor.hpp"
16
17#include "Debug.hpp"
18#include "ExecutableMemory.hpp"
19#include "Routine.hpp"
20
Nicolas Capens41a73022020-01-30 00:30:14 -050021// TODO(b/143539525): Eliminate when warning has been fixed.
22#ifdef _MSC_VER
23__pragma(warning(push))
24 __pragma(warning(disable : 4146)) // unary minus operator applied to unsigned type, result still unsigned
25#endif
26
Nicolas Capens41a73022020-01-30 00:30:14 -050027#include "llvm/ExecutionEngine/Orc/CompileUtils.h"
28#include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
Nicolas Capens41a73022020-01-30 00:30:14 -050029#include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
Nicolas Capens41a73022020-01-30 00:30:14 -050030#include "llvm/ExecutionEngine/SectionMemoryManager.h"
Nicolas Capens41a73022020-01-30 00:30:14 -050031#include "llvm/IR/LegacyPassManager.h"
Nicolas Capens827e9a22020-11-02 11:04:24 -050032#include "llvm/Support/Host.h"
Nicolas Capens41a73022020-01-30 00:30:14 -050033#include "llvm/Support/TargetSelect.h"
Nicolas Capens41a73022020-01-30 00:30:14 -050034#include "llvm/Transforms/InstCombine/InstCombine.h"
35#include "llvm/Transforms/Scalar.h"
36#include "llvm/Transforms/Scalar/GVN.h"
37
Nicolas Capens41a73022020-01-30 00:30:14 -050038#ifdef _MSC_VER
39 __pragma(warning(pop))
40#endif
41
Nicolas Capens41a73022020-01-30 00:30:14 -050042#if defined(_WIN64)
43 extern "C" void __chkstk();
44#elif defined(_WIN32)
45extern "C" void _chkstk();
46#endif
47
Anton D. Kachalovac4e1d22020-02-11 15:44:27 +010048#ifdef __ARM_EABI__
49extern "C" signed __aeabi_idivmod();
50#endif
51
Nicolas Capens47c3ca12020-11-02 16:33:08 -050052#if __has_feature(memory_sanitizer)
53# include "sanitizer/msan_interface.h" // TODO(b/155148722): Remove when we no longer unpoison all writes.
54
55# include <dlfcn.h> // dlsym()
56#endif
57
Nicolas Capens41a73022020-01-30 00:30:14 -050058namespace {
59
Nicolas Capens41a73022020-01-30 00:30:14 -050060// JITGlobals is a singleton that holds all the immutable machine specific
61// information for the host device.
62class JITGlobals
63{
64public:
Nicolas Capens41a73022020-01-30 00:30:14 -050065 static JITGlobals *get();
66
Ben Claytonee18f392020-10-19 16:54:21 -040067 llvm::orc::JITTargetMachineBuilder getTargetMachineBuilder(rr::Optimization::Level optLevel) const;
68 const llvm::DataLayout &getDataLayout() const;
Nicolas Capens827e9a22020-11-02 11:04:24 -050069 const llvm::Triple &getTargetTriple() const;
Nicolas Capens41a73022020-01-30 00:30:14 -050070
71private:
Nicolas Capens827e9a22020-11-02 11:04:24 -050072 JITGlobals(llvm::orc::JITTargetMachineBuilder &&jitTargetMachineBuilder, llvm::DataLayout &&dataLayout);
Ben Claytonee18f392020-10-19 16:54:21 -040073
Nicolas Capens41a73022020-01-30 00:30:14 -050074 static llvm::CodeGenOpt::Level toLLVM(rr::Optimization::Level level);
Nicolas Capens827e9a22020-11-02 11:04:24 -050075
76 const llvm::orc::JITTargetMachineBuilder jitTargetMachineBuilder;
Ben Claytonee18f392020-10-19 16:54:21 -040077 const llvm::DataLayout dataLayout;
Nicolas Capens41a73022020-01-30 00:30:14 -050078};
79
80JITGlobals *JITGlobals::get()
81{
Ben Claytonee18f392020-10-19 16:54:21 -040082 static JITGlobals instance = [] {
83 llvm::InitializeNativeTarget();
84 llvm::InitializeNativeTargetAsmPrinter();
85 llvm::InitializeNativeTargetAsmParser();
86
Nicolas Capens827e9a22020-11-02 11:04:24 -050087 // TODO(b/171236524): JITTargetMachineBuilder::detectHost() currently uses the target triple of the host,
88 // rather than a valid triple for the current process. Once fixed, we can use that function instead.
89 llvm::orc::JITTargetMachineBuilder jitTargetMachineBuilder(llvm::Triple(LLVM_DEFAULT_TARGET_TRIPLE));
90
91 // Retrieve host CPU name and sub-target features and add them to builder.
92 // Relocation model, code model and codegen opt level are kept to default values.
93 llvm::StringMap<bool> cpuFeatures;
94 bool ok = llvm::sys::getHostCPUFeatures(cpuFeatures);
95
96#if defined(__i386__) || defined(__x86_64__) || \
97 (defined(__linux__) && (defined(__arm__) || defined(__aarch64__)))
98 ASSERT_MSG(ok, "llvm::sys::getHostCPUFeatures returned false");
99#else
100 (void)ok; // getHostCPUFeatures always returns false on other platforms
101#endif
102
103 for(auto &feature : cpuFeatures)
104 {
105 jitTargetMachineBuilder.getFeatures().AddFeature(feature.first(), feature.second);
106 }
107
108#if LLVM_VERSION_MAJOR >= 11 /* TODO(b/165000222): Unconditional after LLVM 11 upgrade */
109 jitTargetMachineBuilder.setCPU(std::string(llvm::sys::getHostCPUName()));
110#else
111 jitTargetMachineBuilder.setCPU(llvm::sys::getHostCPUName());
112#endif
113
114 auto dataLayout = jitTargetMachineBuilder.getDefaultDataLayoutForTarget();
Ben Claytonee18f392020-10-19 16:54:21 -0400115 ASSERT_MSG(dataLayout, "JITTargetMachineBuilder::getDefaultDataLayoutForTarget() failed");
Nicolas Capens827e9a22020-11-02 11:04:24 -0500116
117 return JITGlobals(std::move(jitTargetMachineBuilder), std::move(dataLayout.get()));
Ben Claytonee18f392020-10-19 16:54:21 -0400118 }();
Nicolas Capens827e9a22020-11-02 11:04:24 -0500119
Nicolas Capens41a73022020-01-30 00:30:14 -0500120 return &instance;
121}
122
Ben Claytonee18f392020-10-19 16:54:21 -0400123llvm::orc::JITTargetMachineBuilder JITGlobals::getTargetMachineBuilder(rr::Optimization::Level optLevel) const
Nicolas Capens41a73022020-01-30 00:30:14 -0500124{
Nicolas Capens827e9a22020-11-02 11:04:24 -0500125 llvm::orc::JITTargetMachineBuilder out = jitTargetMachineBuilder;
Ben Claytonee18f392020-10-19 16:54:21 -0400126 out.setCodeGenOptLevel(toLLVM(optLevel));
Nicolas Capens827e9a22020-11-02 11:04:24 -0500127
Ben Claytonee18f392020-10-19 16:54:21 -0400128 return out;
Nicolas Capens41a73022020-01-30 00:30:14 -0500129}
130
Ben Claytonee18f392020-10-19 16:54:21 -0400131const llvm::DataLayout &JITGlobals::getDataLayout() const
Nicolas Capens41a73022020-01-30 00:30:14 -0500132{
Ben Claytonee18f392020-10-19 16:54:21 -0400133 return dataLayout;
134}
Nicolas Capens41a73022020-01-30 00:30:14 -0500135
Nicolas Capens827e9a22020-11-02 11:04:24 -0500136const llvm::Triple &JITGlobals::getTargetTriple() const
Ben Claytonee18f392020-10-19 16:54:21 -0400137{
Nicolas Capens827e9a22020-11-02 11:04:24 -0500138 return jitTargetMachineBuilder.getTargetTriple();
Ben Claytonee18f392020-10-19 16:54:21 -0400139}
Nicolas Capens41a73022020-01-30 00:30:14 -0500140
Nicolas Capens827e9a22020-11-02 11:04:24 -0500141JITGlobals::JITGlobals(llvm::orc::JITTargetMachineBuilder &&jitTargetMachineBuilder, llvm::DataLayout &&dataLayout)
142 : jitTargetMachineBuilder(jitTargetMachineBuilder)
Ben Claytonee18f392020-10-19 16:54:21 -0400143 , dataLayout(dataLayout)
144{
Nicolas Capens41a73022020-01-30 00:30:14 -0500145}
146
147llvm::CodeGenOpt::Level JITGlobals::toLLVM(rr::Optimization::Level level)
148{
149 switch(level)
150 {
Nicolas Capens00ecdf92020-10-30 21:13:40 -0400151 case rr::Optimization::Level::None: return llvm::CodeGenOpt::None;
152 case rr::Optimization::Level::Less: return llvm::CodeGenOpt::Less;
153 case rr::Optimization::Level::Default: return llvm::CodeGenOpt::Default;
154 case rr::Optimization::Level::Aggressive: return llvm::CodeGenOpt::Aggressive;
Nicolas Capens41a73022020-01-30 00:30:14 -0500155 default: UNREACHABLE("Unknown Optimization Level %d", int(level));
156 }
Nicolas Capens00ecdf92020-10-30 21:13:40 -0400157 return llvm::CodeGenOpt::Default;
Nicolas Capens41a73022020-01-30 00:30:14 -0500158}
159
David 'Digit' Turner48f3f6c2020-03-23 14:23:10 +0100160class MemoryMapper final : public llvm::SectionMemoryManager::MemoryMapper
Nicolas Capens41a73022020-01-30 00:30:14 -0500161{
162public:
163 MemoryMapper() {}
164 ~MemoryMapper() final {}
165
166 llvm::sys::MemoryBlock allocateMappedMemory(
167 llvm::SectionMemoryManager::AllocationPurpose purpose,
168 size_t numBytes, const llvm::sys::MemoryBlock *const nearBlock,
169 unsigned flags, std::error_code &errorCode) final
170 {
171 errorCode = std::error_code();
172
173 // Round up numBytes to page size.
174 size_t pageSize = rr::memoryPageSize();
175 numBytes = (numBytes + pageSize - 1) & ~(pageSize - 1);
176
177 bool need_exec =
178 purpose == llvm::SectionMemoryManager::AllocationPurpose::Code;
179 void *addr = rr::allocateMemoryPages(
180 numBytes, flagsToPermissions(flags), need_exec);
181 if(!addr)
182 return llvm::sys::MemoryBlock();
183 return llvm::sys::MemoryBlock(addr, numBytes);
184 }
185
186 std::error_code protectMappedMemory(const llvm::sys::MemoryBlock &block,
187 unsigned flags)
188 {
189 // Round down base address to align with a page boundary. This matches
190 // DefaultMMapper behavior.
191 void *addr = block.base();
Nicolas Capens41a73022020-01-30 00:30:14 -0500192 size_t size = block.allocatedSize();
Nicolas Capens41a73022020-01-30 00:30:14 -0500193 size_t pageSize = rr::memoryPageSize();
194 addr = reinterpret_cast<void *>(
195 reinterpret_cast<uintptr_t>(addr) & ~(pageSize - 1));
196 size += reinterpret_cast<uintptr_t>(block.base()) -
197 reinterpret_cast<uintptr_t>(addr);
198
199 rr::protectMemoryPages(addr, size, flagsToPermissions(flags));
200 return std::error_code();
201 }
202
203 std::error_code releaseMappedMemory(llvm::sys::MemoryBlock &block)
204 {
Nicolas Capens41a73022020-01-30 00:30:14 -0500205 size_t size = block.allocatedSize();
Nicolas Capens41a73022020-01-30 00:30:14 -0500206
207 rr::deallocateMemoryPages(block.base(), size);
208 return std::error_code();
209 }
210
211private:
212 int flagsToPermissions(unsigned flags)
213 {
214 int result = 0;
215 if(flags & llvm::sys::Memory::MF_READ)
216 {
217 result |= rr::PERMISSION_READ;
218 }
219 if(flags & llvm::sys::Memory::MF_WRITE)
220 {
221 result |= rr::PERMISSION_WRITE;
222 }
223 if(flags & llvm::sys::Memory::MF_EXEC)
224 {
225 result |= rr::PERMISSION_EXECUTE;
226 }
227 return result;
228 }
229};
230
231template<typename T>
232T alignUp(T val, T alignment)
233{
234 return alignment * ((val + alignment - 1) / alignment);
235}
236
237void *alignedAlloc(size_t size, size_t alignment)
238{
239 ASSERT(alignment < 256);
240 auto allocation = new uint8_t[size + sizeof(uint8_t) + alignment];
241 auto aligned = allocation;
242 aligned += sizeof(uint8_t); // Make space for the base-address offset.
243 aligned = reinterpret_cast<uint8_t *>(alignUp(reinterpret_cast<uintptr_t>(aligned), alignment)); // align
244 auto offset = static_cast<uint8_t>(aligned - allocation);
245 aligned[-1] = offset;
246 return aligned;
247}
248
249void alignedFree(void *ptr)
250{
251 auto aligned = reinterpret_cast<uint8_t *>(ptr);
252 auto offset = aligned[-1];
253 auto allocation = aligned - offset;
254 delete[] allocation;
255}
256
257template<typename T>
258static void atomicLoad(void *ptr, void *ret, llvm::AtomicOrdering ordering)
259{
260 *reinterpret_cast<T *>(ret) = std::atomic_load_explicit<T>(reinterpret_cast<std::atomic<T> *>(ptr), rr::atomicOrdering(ordering));
261}
262
263template<typename T>
264static void atomicStore(void *ptr, void *val, llvm::AtomicOrdering ordering)
265{
266 std::atomic_store_explicit<T>(reinterpret_cast<std::atomic<T> *>(ptr), *reinterpret_cast<T *>(val), rr::atomicOrdering(ordering));
267}
268
269#ifdef __ANDROID__
270template<typename F>
271static uint32_t sync_fetch_and_op(uint32_t volatile *ptr, uint32_t val, F f)
272{
273 // Build an arbitrary op out of looped CAS
274 for(;;)
275 {
276 uint32_t expected = *ptr;
277 uint32_t desired = f(expected, val);
278
279 if(expected == __sync_val_compare_and_swap_4(ptr, expected, desired))
280 {
281 return expected;
282 }
283 }
284}
285#endif
286
Antonio Maioranoc1839ee2020-10-26 10:16:29 -0400287#if LLVM_VERSION_MAJOR >= 11 /* TODO(b/165000222): Unconditional after LLVM 11 upgrade */
288class ExternalSymbolGenerator : public llvm::orc::DefinitionGenerator
289#else
Ben Claytonee18f392020-10-19 16:54:21 -0400290class ExternalSymbolGenerator : public llvm::orc::JITDylib::DefinitionGenerator
Antonio Maioranoc1839ee2020-10-26 10:16:29 -0400291#endif
Nicolas Capens41a73022020-01-30 00:30:14 -0500292{
293 struct Atomic
294 {
295 static void load(size_t size, void *ptr, void *ret, llvm::AtomicOrdering ordering)
296 {
297 switch(size)
298 {
299 case 1: atomicLoad<uint8_t>(ptr, ret, ordering); break;
300 case 2: atomicLoad<uint16_t>(ptr, ret, ordering); break;
301 case 4: atomicLoad<uint32_t>(ptr, ret, ordering); break;
302 case 8: atomicLoad<uint64_t>(ptr, ret, ordering); break;
303 default:
Ben Claytonce54c592020-02-07 11:30:51 +0000304 UNIMPLEMENTED_NO_BUG("Atomic::load(size: %d)", int(size));
Nicolas Capens41a73022020-01-30 00:30:14 -0500305 }
306 }
307 static void store(size_t size, void *ptr, void *ret, llvm::AtomicOrdering ordering)
308 {
309 switch(size)
310 {
311 case 1: atomicStore<uint8_t>(ptr, ret, ordering); break;
312 case 2: atomicStore<uint16_t>(ptr, ret, ordering); break;
313 case 4: atomicStore<uint32_t>(ptr, ret, ordering); break;
314 case 8: atomicStore<uint64_t>(ptr, ret, ordering); break;
315 default:
Ben Claytonce54c592020-02-07 11:30:51 +0000316 UNIMPLEMENTED_NO_BUG("Atomic::store(size: %d)", int(size));
Nicolas Capens41a73022020-01-30 00:30:14 -0500317 }
318 }
319 };
320
Ben Claytonee18f392020-10-19 16:54:21 -0400321 static void nop() {}
322 static void neverCalled() { UNREACHABLE("Should never be called"); }
Nicolas Capens41a73022020-01-30 00:30:14 -0500323
Ben Claytonee18f392020-10-19 16:54:21 -0400324 static void *coroutine_alloc_frame(size_t size) { return alignedAlloc(size, 16); }
325 static void coroutine_free_frame(void *ptr) { alignedFree(ptr); }
Nicolas Capens41a73022020-01-30 00:30:14 -0500326
327#ifdef __ANDROID__
Ben Claytonee18f392020-10-19 16:54:21 -0400328 // forwarders since we can't take address of builtins
329 static void sync_synchronize() { __sync_synchronize(); }
330 static uint32_t sync_fetch_and_add_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_add_4(ptr, val); }
331 static uint32_t sync_fetch_and_and_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_and_4(ptr, val); }
332 static uint32_t sync_fetch_and_or_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_or_4(ptr, val); }
333 static uint32_t sync_fetch_and_xor_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_xor_4(ptr, val); }
334 static uint32_t sync_fetch_and_sub_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_sub_4(ptr, val); }
335 static uint32_t sync_lock_test_and_set_4(uint32_t *ptr, uint32_t val) { return __sync_lock_test_and_set_4(ptr, val); }
336 static uint32_t sync_val_compare_and_swap_4(uint32_t *ptr, uint32_t expected, uint32_t desired) { return __sync_val_compare_and_swap_4(ptr, expected, desired); }
Nicolas Capens41a73022020-01-30 00:30:14 -0500337
Ben Claytonee18f392020-10-19 16:54:21 -0400338 static uint32_t sync_fetch_and_max_4(uint32_t *ptr, uint32_t val)
339 {
340 return sync_fetch_and_op(ptr, val, [](int32_t a, int32_t b) { return std::max(a, b); });
341 }
342 static uint32_t sync_fetch_and_min_4(uint32_t *ptr, uint32_t val)
343 {
344 return sync_fetch_and_op(ptr, val, [](int32_t a, int32_t b) { return std::min(a, b); });
345 }
346 static uint32_t sync_fetch_and_umax_4(uint32_t *ptr, uint32_t val)
347 {
348 return sync_fetch_and_op(ptr, val, [](uint32_t a, uint32_t b) { return std::max(a, b); });
349 }
350 static uint32_t sync_fetch_and_umin_4(uint32_t *ptr, uint32_t val)
351 {
352 return sync_fetch_and_op(ptr, val, [](uint32_t a, uint32_t b) { return std::min(a, b); });
353 }
Nicolas Capens41a73022020-01-30 00:30:14 -0500354#endif
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500355
Nicolas Capens41a73022020-01-30 00:30:14 -0500356 class Resolver
357 {
358 public:
Ben Claytonee18f392020-10-19 16:54:21 -0400359 using FunctionMap = llvm::StringMap<void *>;
Nicolas Capens41a73022020-01-30 00:30:14 -0500360
361 FunctionMap functions;
362
363 Resolver()
364 {
Antonio Maiorano8cbee412020-06-10 15:59:20 -0400365#ifdef ENABLE_RR_PRINT
Ben Claytonee18f392020-10-19 16:54:21 -0400366 functions.try_emplace("rr::DebugPrintf", reinterpret_cast<void *>(rr::DebugPrintf));
Antonio Maiorano8cbee412020-06-10 15:59:20 -0400367#endif
Ben Claytonee18f392020-10-19 16:54:21 -0400368 functions.try_emplace("nop", reinterpret_cast<void *>(nop));
369 functions.try_emplace("floorf", reinterpret_cast<void *>(floorf));
370 functions.try_emplace("nearbyintf", reinterpret_cast<void *>(nearbyintf));
371 functions.try_emplace("truncf", reinterpret_cast<void *>(truncf));
372 functions.try_emplace("printf", reinterpret_cast<void *>(printf));
373 functions.try_emplace("puts", reinterpret_cast<void *>(puts));
374 functions.try_emplace("fmodf", reinterpret_cast<void *>(fmodf));
Nicolas Capens41a73022020-01-30 00:30:14 -0500375
Ben Claytonee18f392020-10-19 16:54:21 -0400376 functions.try_emplace("sinf", reinterpret_cast<void *>(sinf));
377 functions.try_emplace("cosf", reinterpret_cast<void *>(cosf));
378 functions.try_emplace("asinf", reinterpret_cast<void *>(asinf));
379 functions.try_emplace("acosf", reinterpret_cast<void *>(acosf));
380 functions.try_emplace("atanf", reinterpret_cast<void *>(atanf));
381 functions.try_emplace("sinhf", reinterpret_cast<void *>(sinhf));
382 functions.try_emplace("coshf", reinterpret_cast<void *>(coshf));
383 functions.try_emplace("tanhf", reinterpret_cast<void *>(tanhf));
384 functions.try_emplace("asinhf", reinterpret_cast<void *>(asinhf));
385 functions.try_emplace("acoshf", reinterpret_cast<void *>(acoshf));
386 functions.try_emplace("atanhf", reinterpret_cast<void *>(atanhf));
387 functions.try_emplace("atan2f", reinterpret_cast<void *>(atan2f));
388 functions.try_emplace("powf", reinterpret_cast<void *>(powf));
389 functions.try_emplace("expf", reinterpret_cast<void *>(expf));
390 functions.try_emplace("logf", reinterpret_cast<void *>(logf));
391 functions.try_emplace("exp2f", reinterpret_cast<void *>(exp2f));
392 functions.try_emplace("log2f", reinterpret_cast<void *>(log2f));
Nicolas Capens41a73022020-01-30 00:30:14 -0500393
Ben Claytonee18f392020-10-19 16:54:21 -0400394 functions.try_emplace("sin", reinterpret_cast<void *>(static_cast<double (*)(double)>(sin)));
395 functions.try_emplace("cos", reinterpret_cast<void *>(static_cast<double (*)(double)>(cos)));
396 functions.try_emplace("asin", reinterpret_cast<void *>(static_cast<double (*)(double)>(asin)));
397 functions.try_emplace("acos", reinterpret_cast<void *>(static_cast<double (*)(double)>(acos)));
398 functions.try_emplace("atan", reinterpret_cast<void *>(static_cast<double (*)(double)>(atan)));
399 functions.try_emplace("sinh", reinterpret_cast<void *>(static_cast<double (*)(double)>(sinh)));
400 functions.try_emplace("cosh", reinterpret_cast<void *>(static_cast<double (*)(double)>(cosh)));
401 functions.try_emplace("tanh", reinterpret_cast<void *>(static_cast<double (*)(double)>(tanh)));
402 functions.try_emplace("asinh", reinterpret_cast<void *>(static_cast<double (*)(double)>(asinh)));
403 functions.try_emplace("acosh", reinterpret_cast<void *>(static_cast<double (*)(double)>(acosh)));
404 functions.try_emplace("atanh", reinterpret_cast<void *>(static_cast<double (*)(double)>(atanh)));
405 functions.try_emplace("atan2", reinterpret_cast<void *>(static_cast<double (*)(double, double)>(atan2)));
406 functions.try_emplace("pow", reinterpret_cast<void *>(static_cast<double (*)(double, double)>(pow)));
407 functions.try_emplace("exp", reinterpret_cast<void *>(static_cast<double (*)(double)>(exp)));
408 functions.try_emplace("log", reinterpret_cast<void *>(static_cast<double (*)(double)>(log)));
409 functions.try_emplace("exp2", reinterpret_cast<void *>(static_cast<double (*)(double)>(exp2)));
410 functions.try_emplace("log2", reinterpret_cast<void *>(static_cast<double (*)(double)>(log2)));
Nicolas Capens41a73022020-01-30 00:30:14 -0500411
Ben Claytonee18f392020-10-19 16:54:21 -0400412 functions.try_emplace("atomic_load", reinterpret_cast<void *>(Atomic::load));
413 functions.try_emplace("atomic_store", reinterpret_cast<void *>(Atomic::store));
Nicolas Capens41a73022020-01-30 00:30:14 -0500414
415 // FIXME(b/119409619): use an allocator here so we can control all memory allocations
Ben Claytonee18f392020-10-19 16:54:21 -0400416 functions.try_emplace("coroutine_alloc_frame", reinterpret_cast<void *>(coroutine_alloc_frame));
417 functions.try_emplace("coroutine_free_frame", reinterpret_cast<void *>(coroutine_free_frame));
Nicolas Capens41a73022020-01-30 00:30:14 -0500418
419#ifdef __APPLE__
Ben Claytonee18f392020-10-19 16:54:21 -0400420 functions.try_emplace("sincosf_stret", reinterpret_cast<void *>(__sincosf_stret));
Nicolas Capens41a73022020-01-30 00:30:14 -0500421#elif defined(__linux__)
Ben Claytonee18f392020-10-19 16:54:21 -0400422 functions.try_emplace("sincosf", reinterpret_cast<void *>(sincosf));
Nicolas Capens41a73022020-01-30 00:30:14 -0500423#elif defined(_WIN64)
Ben Claytonee18f392020-10-19 16:54:21 -0400424 functions.try_emplace("chkstk", reinterpret_cast<void *>(__chkstk));
Nicolas Capens41a73022020-01-30 00:30:14 -0500425#elif defined(_WIN32)
Ben Claytonee18f392020-10-19 16:54:21 -0400426 functions.try_emplace("chkstk", reinterpret_cast<void *>(_chkstk));
Nicolas Capens41a73022020-01-30 00:30:14 -0500427#endif
428
Anton D. Kachalovac4e1d22020-02-11 15:44:27 +0100429#ifdef __ARM_EABI__
Ben Claytonee18f392020-10-19 16:54:21 -0400430 functions.try_emplace("aeabi_idivmod", reinterpret_cast<void *>(__aeabi_idivmod));
Anton D. Kachalovac4e1d22020-02-11 15:44:27 +0100431#endif
Nicolas Capens41a73022020-01-30 00:30:14 -0500432#ifdef __ANDROID__
Antonio Maiorano84f5eeb2020-10-20 20:39:34 -0400433 functions.try_emplace("aeabi_unwind_cpp_pr0", reinterpret_cast<void *>(neverCalled));
434 functions.try_emplace("sync_synchronize", reinterpret_cast<void *>(sync_synchronize));
435 functions.try_emplace("sync_fetch_and_add_4", reinterpret_cast<void *>(sync_fetch_and_add_4));
436 functions.try_emplace("sync_fetch_and_and_4", reinterpret_cast<void *>(sync_fetch_and_and_4));
437 functions.try_emplace("sync_fetch_and_or_4", reinterpret_cast<void *>(sync_fetch_and_or_4));
438 functions.try_emplace("sync_fetch_and_xor_4", reinterpret_cast<void *>(sync_fetch_and_xor_4));
439 functions.try_emplace("sync_fetch_and_sub_4", reinterpret_cast<void *>(sync_fetch_and_sub_4));
440 functions.try_emplace("sync_lock_test_and_set_4", reinterpret_cast<void *>(sync_lock_test_and_set_4));
441 functions.try_emplace("sync_val_compare_and_swap_4", reinterpret_cast<void *>(sync_val_compare_and_swap_4));
442 functions.try_emplace("sync_fetch_and_max_4", reinterpret_cast<void *>(sync_fetch_and_max_4));
443 functions.try_emplace("sync_fetch_and_min_4", reinterpret_cast<void *>(sync_fetch_and_min_4));
444 functions.try_emplace("sync_fetch_and_umax_4", reinterpret_cast<void *>(sync_fetch_and_umax_4));
445 functions.try_emplace("sync_fetch_and_umin_4", reinterpret_cast<void *>(sync_fetch_and_umin_4));
Nicolas Capens41a73022020-01-30 00:30:14 -0500446#endif
Antonio Maioranodd48b7e2020-02-05 13:17:07 -0500447#if __has_feature(memory_sanitizer)
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500448 functions.try_emplace("msan_unpoison", reinterpret_cast<void *>(__msan_unpoison)); // TODO(b/155148722): Remove when we no longer unpoison all writes.
Antonio Maioranodd48b7e2020-02-05 13:17:07 -0500449#endif
Nicolas Capens41a73022020-01-30 00:30:14 -0500450 }
451 };
452
Antonio Maioranoc1839ee2020-10-26 10:16:29 -0400453 llvm::Error tryToGenerate(
454#if LLVM_VERSION_MAJOR >= 11 /* TODO(b/165000222): Unconditional after LLVM 11 upgrade */
455 llvm::orc::LookupState &state,
456#endif
457 llvm::orc::LookupKind kind,
458 llvm::orc::JITDylib &dylib,
459 llvm::orc::JITDylibLookupFlags flags,
460 const llvm::orc::SymbolLookupSet &set) override
Ben Claytonee18f392020-10-19 16:54:21 -0400461 {
462 static Resolver resolver;
Nicolas Capens41a73022020-01-30 00:30:14 -0500463
Ben Claytonee18f392020-10-19 16:54:21 -0400464 llvm::orc::SymbolMap symbols;
Nicolas Capens41a73022020-01-30 00:30:14 -0500465
Ben Claytonee18f392020-10-19 16:54:21 -0400466#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)
467 std::string missing;
468#endif // !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)
469
470 for(auto symbol : set)
471 {
472 auto name = symbol.first;
473
474 // Trim off any underscores from the start of the symbol. LLVM likes
475 // to append these on macOS.
476 auto trimmed = (*name).drop_while([](char c) { return c == '_'; });
477
478 auto it = resolver.functions.find(trimmed.str());
479 if(it != resolver.functions.end())
480 {
481 symbols[name] = llvm::JITEvaluatedSymbol(
482 static_cast<llvm::JITTargetAddress>(reinterpret_cast<uintptr_t>(it->second)),
483 llvm::JITSymbolFlags::Exported);
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500484
485 continue;
Ben Claytonee18f392020-10-19 16:54:21 -0400486 }
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500487
488#if __has_feature(memory_sanitizer)
489 // MemorySanitizer uses a dynamically linked runtime. Instrumented routines reference
490 // some symbols from this library. Look them up dynamically in the default namespace.
491 // Note this approach should not be used for other symbols, since they might not be
492 // visible (e.g. due to static linking), we may wish to provide an alternate
493 // implementation, and/or it would be a security vulnerability.
494
495 void *address = dlsym(RTLD_DEFAULT, (*symbol.first).data());
496
497 if(address)
Ben Claytonee18f392020-10-19 16:54:21 -0400498 {
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500499 symbols[name] = llvm::JITEvaluatedSymbol(
500 static_cast<llvm::JITTargetAddress>(reinterpret_cast<uintptr_t>(address)),
501 llvm::JITSymbolFlags::Exported);
502
503 continue;
Ben Claytonee18f392020-10-19 16:54:21 -0400504 }
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500505#endif
506
507#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)
508 missing += (missing.empty() ? "'" : ", '") + (*name).str() + "'";
509#endif
Ben Claytonee18f392020-10-19 16:54:21 -0400510 }
511
512#if !defined(NDEBUG) || defined(DCHECK_ALWAYS_ON)
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500513 // Missing functions will likely make the module fail in non-obvious ways.
Ben Claytonee18f392020-10-19 16:54:21 -0400514 if(!missing.empty())
515 {
516 WARN("Missing external functions: %s", missing.c_str());
517 }
Nicolas Capens47c3ca12020-11-02 16:33:08 -0500518#endif
Ben Claytonee18f392020-10-19 16:54:21 -0400519
520 if(symbols.empty())
521 {
522 return llvm::Error::success();
523 }
524
525 return dylib.define(llvm::orc::absoluteSymbols(std::move(symbols)));
526 }
527};
Nicolas Capens41a73022020-01-30 00:30:14 -0500528
Antonio Maioranoec526ab2020-10-21 09:55:50 -0400529// As we must support different LLVM versions, add a generic Unwrap for functions that return Expected<T> or the actual T.
530// TODO(b/165000222): Remove after LLVM 11 upgrade
531template<typename T>
532auto &Unwrap(llvm::Expected<T> &&v)
533{
534 return v.get();
535}
536template<typename T>
537auto &Unwrap(T &&v)
538{
539 return v;
540}
541
Nicolas Capens41a73022020-01-30 00:30:14 -0500542// JITRoutine is a rr::Routine that holds a LLVM JIT session, compiler and
543// object layer as each routine may require different target machine
544// settings and no Reactor routine directly links against another.
545class JITRoutine : public rr::Routine
546{
Antonio Maioranobb66fa42020-10-22 13:53:09 -0400547 llvm::orc::ExecutionSession session;
Ben Claytonee18f392020-10-19 16:54:21 -0400548 llvm::orc::RTDyldObjectLinkingLayer objectLayer;
549 llvm::orc::IRCompileLayer compileLayer;
550 llvm::orc::MangleAndInterner mangle;
551 llvm::orc::ThreadSafeContext ctx;
Ben Claytonee18f392020-10-19 16:54:21 -0400552 llvm::orc::JITDylib &dylib;
553 std::vector<const void *> addresses;
Nicolas Capens41a73022020-01-30 00:30:14 -0500554
555public:
556 JITRoutine(
557 std::unique_ptr<llvm::Module> module,
558 llvm::Function **funcs,
559 size_t count,
560 const rr::Config &config)
Ben Claytone02d8932020-10-21 18:37:33 +0100561 : objectLayer(session, []() {
Nicolas Capens827e9a22020-11-02 11:04:24 -0500562 static MemoryMapper memoryMapper;
563 return std::make_unique<llvm::SectionMemoryManager>(&memoryMapper);
Ben Claytone02d8932020-10-21 18:37:33 +0100564 })
Ben Claytonee18f392020-10-19 16:54:21 -0400565 , compileLayer(session, objectLayer, std::make_unique<llvm::orc::ConcurrentIRCompiler>(JITGlobals::get()->getTargetMachineBuilder(config.getOptimization().getLevel())))
566 , mangle(session, JITGlobals::get()->getDataLayout())
567 , ctx(std::make_unique<llvm::LLVMContext>())
Antonio Maioranoec526ab2020-10-21 09:55:50 -0400568 , dylib(Unwrap(session.createJITDylib("<routine>")))
Nicolas Capens41a73022020-01-30 00:30:14 -0500569 , addresses(count)
570 {
Ben Claytona7bc2b92020-03-26 11:24:49 +0000571
Ben Claytonee18f392020-10-19 16:54:21 -0400572#ifdef ENABLE_RR_DEBUG_INFO
573 // TODO(b/165000222): Update this on next LLVM roll.
574 // https://github.com/llvm/llvm-project/commit/98f2bb4461072347dcca7d2b1b9571b3a6525801
575 // introduces RTDyldObjectLinkingLayer::registerJITEventListener().
576 // The current API does not appear to have any way to bind the
577 // rr::DebugInfo::NotifyFreeingObject event.
578 objectLayer.setNotifyLoaded([](llvm::orc::VModuleKey,
579 const llvm::object::ObjectFile &obj,
580 const llvm::RuntimeDyld::LoadedObjectInfo &l) {
581 static std::atomic<uint64_t> unique_key{ 0 };
582 rr::DebugInfo::NotifyObjectEmitted(unique_key++, obj, l);
583 });
584#endif // ENABLE_RR_DEBUG_INFO
Ben Claytona7bc2b92020-03-26 11:24:49 +0000585
Ben Claytonee18f392020-10-19 16:54:21 -0400586 if(JITGlobals::get()->getTargetTriple().isOSBinFormatCOFF())
587 {
588 // Hack to support symbol visibility in COFF.
589 // Matches hack in llvm::orc::LLJIT::createObjectLinkingLayer().
590 // See documentation on these functions for more detail.
591 objectLayer.setOverrideObjectFlagsWithResponsibilityFlags(true);
592 objectLayer.setAutoClaimResponsibilityForObjectSymbols(true);
593 }
594
595 dylib.addGenerator(std::make_unique<ExternalSymbolGenerator>());
596
597 llvm::SmallVector<llvm::orc::SymbolStringPtr, 8> names(count);
Nicolas Capens41a73022020-01-30 00:30:14 -0500598 for(size_t i = 0; i < count; i++)
599 {
600 auto func = funcs[i];
Nicolas Capens41a73022020-01-30 00:30:14 -0500601 func->setLinkage(llvm::GlobalValue::ExternalLinkage);
602 func->setDoesNotThrow();
Ben Claytonee18f392020-10-19 16:54:21 -0400603 if(!func->hasName())
604 {
605 func->setName("f" + llvm::Twine(i).str());
606 }
607 names[i] = mangle(func->getName());
Nicolas Capens41a73022020-01-30 00:30:14 -0500608 }
609
Nicolas Capens41a73022020-01-30 00:30:14 -0500610 // Once the module is passed to the compileLayer, the
611 // llvm::Functions are freed. Make sure funcs are not referenced
612 // after this point.
613 funcs = nullptr;
614
Ben Claytonee18f392020-10-19 16:54:21 -0400615 llvm::cantFail(compileLayer.add(dylib, llvm::orc::ThreadSafeModule(std::move(module), ctx)));
Nicolas Capens41a73022020-01-30 00:30:14 -0500616
617 // Resolve the function addresses.
618 for(size_t i = 0; i < count; i++)
619 {
Ben Claytonee18f392020-10-19 16:54:21 -0400620 auto symbol = session.lookup({ &dylib }, names[i]);
621 ASSERT_MSG(symbol, "Failed to lookup address of routine function %d: %s",
622 (int)i, llvm::toString(symbol.takeError()).c_str());
623 addresses[i] = reinterpret_cast<void *>(static_cast<intptr_t>(symbol->getAddress()));
Nicolas Capens41a73022020-01-30 00:30:14 -0500624 }
625 }
626
Antonio Maioranobb66fa42020-10-22 13:53:09 -0400627 ~JITRoutine()
628 {
Antonio Maioranoc1839ee2020-10-26 10:16:29 -0400629#if LLVM_VERSION_MAJOR >= 11 /* TODO(b/165000222): Unconditional after LLVM 11 upgrade */
630 if(auto err = session.endSession())
631 {
632 session.reportError(std::move(err));
633 }
Antonio Maioranobb66fa42020-10-22 13:53:09 -0400634#endif
635 }
636
Nicolas Capens41a73022020-01-30 00:30:14 -0500637 const void *getEntry(int index) const override
638 {
639 return addresses[index];
640 }
Nicolas Capens41a73022020-01-30 00:30:14 -0500641};
642
643} // anonymous namespace
644
645namespace rr {
646
647JITBuilder::JITBuilder(const rr::Config &config)
648 : config(config)
649 , module(new llvm::Module("", context))
650 , builder(new llvm::IRBuilder<>(context))
651{
Nicolas Capens959f4192020-11-02 15:30:30 -0500652 module->setTargetTriple(LLVM_DEFAULT_TARGET_TRIPLE);
Ben Claytonee18f392020-10-19 16:54:21 -0400653 module->setDataLayout(JITGlobals::get()->getDataLayout());
Nicolas Capens41a73022020-01-30 00:30:14 -0500654}
655
656void JITBuilder::optimize(const rr::Config &cfg)
657{
Nicolas Capens41a73022020-01-30 00:30:14 -0500658#ifdef ENABLE_RR_DEBUG_INFO
659 if(debugInfo != nullptr)
660 {
661 return; // Don't optimize if we're generating debug info.
662 }
663#endif // ENABLE_RR_DEBUG_INFO
664
Ben Claytonee18f392020-10-19 16:54:21 -0400665 llvm::legacy::PassManager passManager;
Nicolas Capens41a73022020-01-30 00:30:14 -0500666
667 for(auto pass : cfg.getOptimization().getPasses())
668 {
669 switch(pass)
670 {
671 case rr::Optimization::Pass::Disabled: break;
Ben Claytonee18f392020-10-19 16:54:21 -0400672 case rr::Optimization::Pass::CFGSimplification: passManager.add(llvm::createCFGSimplificationPass()); break;
673 case rr::Optimization::Pass::LICM: passManager.add(llvm::createLICMPass()); break;
674 case rr::Optimization::Pass::AggressiveDCE: passManager.add(llvm::createAggressiveDCEPass()); break;
675 case rr::Optimization::Pass::GVN: passManager.add(llvm::createGVNPass()); break;
676 case rr::Optimization::Pass::InstructionCombining: passManager.add(llvm::createInstructionCombiningPass()); break;
677 case rr::Optimization::Pass::Reassociate: passManager.add(llvm::createReassociatePass()); break;
678 case rr::Optimization::Pass::DeadStoreElimination: passManager.add(llvm::createDeadStoreEliminationPass()); break;
679 case rr::Optimization::Pass::SCCP: passManager.add(llvm::createSCCPPass()); break;
680 case rr::Optimization::Pass::ScalarReplAggregates: passManager.add(llvm::createSROAPass()); break;
681 case rr::Optimization::Pass::EarlyCSEPass: passManager.add(llvm::createEarlyCSEPass()); break;
Nicolas Capens41a73022020-01-30 00:30:14 -0500682 default:
683 UNREACHABLE("pass: %d", int(pass));
684 }
685 }
686
Ben Claytonee18f392020-10-19 16:54:21 -0400687 passManager.run(*module);
Nicolas Capens41a73022020-01-30 00:30:14 -0500688}
689
690std::shared_ptr<rr::Routine> JITBuilder::acquireRoutine(llvm::Function **funcs, size_t count, const rr::Config &cfg)
691{
692 ASSERT(module);
693 return std::make_shared<JITRoutine>(std::move(module), funcs, count, cfg);
694}
695
696} // namespace rr