blob: 4b6bb779d1b825d7f08a6e133ad86efc2188421c [file] [log] [blame]
Nicolas Capens0bac2852016-05-07 06:09:58 -04001// Copyright 2016 The SwiftShader Authors. All Rights Reserved.
John Bauman89401822014-05-06 15:04:28 -04002//
Nicolas Capens0bac2852016-05-07 06:09:58 -04003// 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
John Bauman89401822014-05-06 15:04:28 -04006//
Nicolas Capens0bac2852016-05-07 06:09:58 -04007// http://www.apache.org/licenses/LICENSE-2.0
John Bauman89401822014-05-06 15:04:28 -04008//
Nicolas Capens0bac2852016-05-07 06:09:58 -04009// 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.
John Bauman89401822014-05-06 15:04:28 -040014
Nicolas Capenscb986762017-01-20 11:34:37 -050015#include "Reactor.hpp"
Ben Claytoneb50d252019-04-15 13:50:01 -040016#include "Debug.hpp"
Ben Claytonac07ed82019-03-26 14:17:41 +000017#include "LLVMReactor.hpp"
18#include "LLVMReactorDebugInfo.hpp"
John Bauman89401822014-05-06 15:04:28 -040019
Nicolas Capensc07dc4b2018-08-06 14:20:45 -040020#include "x86.hpp"
21#include "CPUID.hpp"
22#include "Thread.hpp"
Nicolas Capens1a3ce872018-10-10 10:42:36 -040023#include "ExecutableMemory.hpp"
Nicolas Capensc07dc4b2018-08-06 14:20:45 -040024#include "MutexLock.hpp"
25
26#undef min
27#undef max
28
Ben Clayton09a7f452019-04-25 15:22:43 +010029#if defined(__clang__)
30// LLVM has occurances of the extra-semi warning in its headers, which will be
31// treated as an error in SwiftShader targets.
32#pragma clang diagnostic push
33#pragma clang diagnostic ignored "-Wextra-semi"
34#endif // defined(__clang__)
35
Antonio Maiorano992bf9d2019-10-22 09:41:17 -040036#ifdef _MSC_VER
37__pragma(warning(push))
38__pragma(warning(disable : 4146)) // unary minus operator applied to unsigned type, result still unsigned
39#endif
40
Ben Clayton5875be52019-04-11 14:57:40 -040041#include "llvm/Analysis/LoopPass.h"
42#include "llvm/ExecutionEngine/ExecutionEngine.h"
43#include "llvm/ExecutionEngine/JITSymbol.h"
44#include "llvm/ExecutionEngine/Orc/CompileUtils.h"
45#include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
46#include "llvm/ExecutionEngine/Orc/LambdaResolver.h"
47#include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
48#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
49#include "llvm/ExecutionEngine/SectionMemoryManager.h"
50#include "llvm/IR/Constants.h"
51#include "llvm/IR/DataLayout.h"
52#include "llvm/IR/Function.h"
53#include "llvm/IR/GlobalVariable.h"
Ben Clayton5875be52019-04-11 14:57:40 -040054#include "llvm/IR/Intrinsics.h"
Ben Clayton1c82c7b2019-04-30 12:49:27 +010055#include "llvm/IR/IRBuilder.h"
Ben Clayton5875be52019-04-11 14:57:40 -040056#include "llvm/IR/LegacyPassManager.h"
Ben Clayton1c82c7b2019-04-30 12:49:27 +010057#include "llvm/IR/LLVMContext.h"
Ben Clayton5875be52019-04-11 14:57:40 -040058#include "llvm/IR/Mangler.h"
59#include "llvm/IR/Module.h"
Ben Clayton4b944652019-05-02 10:56:19 +010060#include "llvm/IR/Verifier.h"
Ben Clayton5875be52019-04-11 14:57:40 -040061#include "llvm/Support/Error.h"
62#include "llvm/Support/TargetSelect.h"
63#include "llvm/Target/TargetOptions.h"
Ben Clayton1c82c7b2019-04-30 12:49:27 +010064#include "llvm/Transforms/Coroutines.h"
Ben Clayton5875be52019-04-11 14:57:40 -040065#include "llvm/Transforms/InstCombine/InstCombine.h"
Ben Clayton1c82c7b2019-04-30 12:49:27 +010066#include "llvm/Transforms/IPO.h"
67#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Ben Clayton5875be52019-04-11 14:57:40 -040068#include "llvm/Transforms/Scalar.h"
69#include "llvm/Transforms/Scalar/GVN.h"
Ben Clayton20507fa2019-04-20 01:40:15 -040070
Ben Clayton09a7f452019-04-25 15:22:43 +010071#if defined(__clang__)
72#pragma clang diagnostic pop
73#endif // defined(__clang__)
74
Antonio Maiorano992bf9d2019-10-22 09:41:17 -040075#ifdef _MSC_VER
76__pragma(warning(pop))
77#endif
78
Ben Clayton5875be52019-04-11 14:57:40 -040079#define ARGS(...) {__VA_ARGS__}
80#define CreateCall2 CreateCall
81#define CreateCall3 CreateCall
Logan Chien0eedc8c2018-08-21 09:34:28 +080082
Ben Clayton5875be52019-04-11 14:57:40 -040083#include <unordered_map>
Logan Chien0eedc8c2018-08-21 09:34:28 +080084
John Bauman89401822014-05-06 15:04:28 -040085#include <fstream>
Ben Claytoncee3dff2019-05-22 12:01:22 +010086#include <iostream>
87#include <mutex>
Ben Clayton1bc7ee92019-02-14 18:43:22 +000088#include <numeric>
89#include <thread>
John Bauman89401822014-05-06 15:04:28 -040090
Nicolas Capens47dc8672017-04-25 12:54:39 -040091#if defined(__i386__) || defined(__x86_64__)
92#include <xmmintrin.h>
93#endif
94
Logan Chien40a60052018-09-26 19:03:53 +080095#include <math.h>
96
Nicolas Capenscb122582014-05-06 23:34:44 -040097#if defined(__x86_64__) && defined(_WIN32)
Ben Clayton2f58df32019-06-23 21:29:25 +010098 extern "C" void X86CompilationCallback()
99 {
100 UNIMPLEMENTED("X86CompilationCallback");
101 }
102#endif
103
104#if defined(_WIN64)
105 extern "C" void __chkstk();
106#elif defined(_WIN32)
107 extern "C" void _chkstk();
John Bauman66b8ab22014-05-06 15:57:45 -0400108#endif
109
Nicolas Capens157ba262019-12-10 17:49:14 -0500110namespace rr {
111
112void* resolveExternalSymbol(const char*);
113
114} // namespace rr
115
116namespace {
117
118// Default configuration settings. Must be accessed under mutex lock.
119std::mutex defaultConfigLock;
120rr::Config &defaultConfig()
Logan Chien52cde602018-09-03 19:37:57 +0800121{
Nicolas Capens157ba262019-12-10 17:49:14 -0500122 // This uses a static in a function to avoid the cost of a global static
123 // initializer. See http://neugierig.org/software/chromium/notes/2011/08/static-initializers.html
124 static rr::Config config = rr::Config::Edit()
125 .add(rr::Optimization::Pass::ScalarReplAggregates)
126 .add(rr::Optimization::Pass::InstructionCombining)
127 .apply({});
128 return config;
Logan Chien52cde602018-09-03 19:37:57 +0800129}
130
Nicolas Capens157ba262019-12-10 17:49:14 -0500131// Cache provides a simple, thread-safe key-value store.
132template <typename KEY, typename VALUE>
133class Cache
Nicolas Capens5c1f5cc2016-09-23 16:45:13 -0400134{
Nicolas Capens157ba262019-12-10 17:49:14 -0500135public:
136 Cache() = default;
137 Cache(const Cache& other);
138 VALUE getOrCreate(KEY key, std::function<VALUE()> create);
139private:
140 mutable std::mutex mutex; // mutable required for copy constructor.
141 std::unordered_map<KEY, VALUE> map;
142};
143
144template <typename KEY, typename VALUE>
145Cache<KEY, VALUE>::Cache(const Cache& other)
146{
147 std::unique_lock<std::mutex> lock(other.mutex);
148 map = other.map;
149}
150
151template <typename KEY, typename VALUE>
152VALUE Cache<KEY, VALUE>::getOrCreate(KEY key, std::function<VALUE()> create)
153{
154 std::unique_lock<std::mutex> lock(mutex);
155 auto it = map.find(key);
Nicolas Capens81bc9d92019-12-16 15:05:57 -0500156 if(it != map.end())
Ben Clayton55bc37a2019-07-04 12:17:12 +0100157 {
Nicolas Capens157ba262019-12-10 17:49:14 -0500158 return it->second;
Ben Clayton55bc37a2019-07-04 12:17:12 +0100159 }
Nicolas Capens157ba262019-12-10 17:49:14 -0500160 auto value = create();
161 map.emplace(key, value);
162 return value;
163}
Ben Clayton55bc37a2019-07-04 12:17:12 +0100164
Nicolas Capens157ba262019-12-10 17:49:14 -0500165// JITGlobals is a singleton that holds all the immutable machine specific
166// information for the host device.
167class JITGlobals
168{
169public:
170 using TargetMachineSPtr = std::shared_ptr<llvm::TargetMachine>;
Nicolas Capens3bbc5e12016-09-27 10:49:52 -0400171
Nicolas Capens157ba262019-12-10 17:49:14 -0500172 static JITGlobals * get();
Ben Clayton52ce1e92019-07-15 11:41:00 +0100173
Nicolas Capens157ba262019-12-10 17:49:14 -0500174 const std::string mcpu;
175 const std::vector<std::string> mattrs;
176 const char* const march;
177 const llvm::TargetOptions targetOptions;
178 const llvm::DataLayout dataLayout;
Ben Clayton52ce1e92019-07-15 11:41:00 +0100179
Nicolas Capens157ba262019-12-10 17:49:14 -0500180 TargetMachineSPtr getTargetMachine(rr::Optimization::Level optlevel);
Ben Clayton6f8e5652019-06-29 01:58:02 +0100181
Nicolas Capens157ba262019-12-10 17:49:14 -0500182private:
183 static JITGlobals create();
184 static llvm::CodeGenOpt::Level toLLVM(rr::Optimization::Level level);
185 JITGlobals(const char *mcpu,
186 const std::vector<std::string> &mattrs,
187 const char *march,
188 const llvm::TargetOptions &targetOptions,
189 const llvm::DataLayout &dataLayout);
190 JITGlobals(const JITGlobals&) = default;
Ben Clayton52ce1e92019-07-15 11:41:00 +0100191
Nicolas Capens157ba262019-12-10 17:49:14 -0500192 // The cache key here is actually a rr::Optimization::Level. We use int
193 // as 'enum class' types do not provide builtin hash functions until
194 // C++14. See: https://stackoverflow.com/a/29618545.
195 Cache<int, TargetMachineSPtr> targetMachines;
196};
Ben Clayton52ce1e92019-07-15 11:41:00 +0100197
Nicolas Capens157ba262019-12-10 17:49:14 -0500198JITGlobals * JITGlobals::get()
199{
200 static JITGlobals instance = create();
201 return &instance;
202}
Ben Clayton6f8e5652019-06-29 01:58:02 +0100203
Nicolas Capens157ba262019-12-10 17:49:14 -0500204JITGlobals::TargetMachineSPtr JITGlobals::getTargetMachine(rr::Optimization::Level optlevel)
205{
206 return targetMachines.getOrCreate(static_cast<int>(optlevel), [&]() {
207 return TargetMachineSPtr(llvm::EngineBuilder()
Ben Clayton52ce1e92019-07-15 11:41:00 +0100208#ifdef ENABLE_RR_DEBUG_INFO
Nicolas Capens157ba262019-12-10 17:49:14 -0500209 .setOptLevel(toLLVM(rr::Optimization::Level::None))
Ben Clayton52ce1e92019-07-15 11:41:00 +0100210#else
Nicolas Capens157ba262019-12-10 17:49:14 -0500211 .setOptLevel(toLLVM(optlevel))
Ben Clayton52ce1e92019-07-15 11:41:00 +0100212#endif // ENABLE_RR_DEBUG_INFO
Nicolas Capens157ba262019-12-10 17:49:14 -0500213 .setMCPU(mcpu)
214 .setMArch(march)
215 .setMAttrs(mattrs)
216 .setTargetOptions(targetOptions)
217 .selectTarget());
218 });
219}
Ben Clayton49f80512019-07-04 17:30:54 +0100220
Nicolas Capens157ba262019-12-10 17:49:14 -0500221JITGlobals JITGlobals::create()
222{
223 struct LLVMInitializer
Ben Clayton52ce1e92019-07-15 11:41:00 +0100224 {
Nicolas Capens157ba262019-12-10 17:49:14 -0500225 LLVMInitializer()
Ben Clayton52ce1e92019-07-15 11:41:00 +0100226 {
Nicolas Capens157ba262019-12-10 17:49:14 -0500227 llvm::InitializeNativeTarget();
228 llvm::InitializeNativeTargetAsmPrinter();
229 llvm::InitializeNativeTargetAsmParser();
230 }
231 };
232 static LLVMInitializer initializeLLVM;
Ben Clayton52ce1e92019-07-15 11:41:00 +0100233
Nicolas Capens157ba262019-12-10 17:49:14 -0500234 auto mcpu = llvm::sys::getHostCPUName();
Ben Clayton52ce1e92019-07-15 11:41:00 +0100235
Nicolas Capens157ba262019-12-10 17:49:14 -0500236 llvm::StringMap<bool> features;
237 bool ok = llvm::sys::getHostCPUFeatures(features);
Ben Clayton6f8e5652019-06-29 01:58:02 +0100238
239#if defined(__i386__) || defined(__x86_64__) || \
240(defined(__linux__) && (defined(__arm__) || defined(__aarch64__)))
Nicolas Capens157ba262019-12-10 17:49:14 -0500241 ASSERT_MSG(ok, "llvm::sys::getHostCPUFeatures returned false");
Ben Clayton6f8e5652019-06-29 01:58:02 +0100242#else
Nicolas Capens157ba262019-12-10 17:49:14 -0500243 (void) ok; // getHostCPUFeatures always returns false on other platforms
Ben Claytonac07ed82019-03-26 14:17:41 +0000244#endif
245
Nicolas Capens157ba262019-12-10 17:49:14 -0500246 std::vector<std::string> mattrs;
Nicolas Capens81bc9d92019-12-16 15:05:57 -0500247 for(auto &feature : features)
Nicolas Capens157ba262019-12-10 17:49:14 -0500248 {
Nicolas Capens81bc9d92019-12-16 15:05:57 -0500249 if(feature.second) { mattrs.push_back(feature.first()); }
Nicolas Capens157ba262019-12-10 17:49:14 -0500250 }
Ben Clayton6f8e5652019-06-29 01:58:02 +0100251
Nicolas Capens157ba262019-12-10 17:49:14 -0500252 const char* march = nullptr;
Ben Clayton6f8e5652019-06-29 01:58:02 +0100253#if defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -0500254 march = "x86-64";
Ben Clayton6f8e5652019-06-29 01:58:02 +0100255#elif defined(__i386__)
Nicolas Capens157ba262019-12-10 17:49:14 -0500256 march = "x86";
Ben Clayton6f8e5652019-06-29 01:58:02 +0100257#elif defined(__aarch64__)
Nicolas Capens157ba262019-12-10 17:49:14 -0500258 march = "arm64";
Ben Clayton6f8e5652019-06-29 01:58:02 +0100259#elif defined(__arm__)
Nicolas Capens157ba262019-12-10 17:49:14 -0500260 march = "arm";
Ben Clayton6f8e5652019-06-29 01:58:02 +0100261#elif defined(__mips__)
262#if defined(__mips64)
Nicolas Capens157ba262019-12-10 17:49:14 -0500263 march = "mips64el";
Ben Clayton6f8e5652019-06-29 01:58:02 +0100264#else
Nicolas Capens157ba262019-12-10 17:49:14 -0500265 march = "mipsel";
Ben Clayton6f8e5652019-06-29 01:58:02 +0100266#endif
267#elif defined(__powerpc64__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
Nicolas Capens157ba262019-12-10 17:49:14 -0500268 march = "ppc64le";
Ben Clayton6f8e5652019-06-29 01:58:02 +0100269#else
Nicolas Capens157ba262019-12-10 17:49:14 -0500270 #error "unknown architecture"
Ben Clayton6f8e5652019-06-29 01:58:02 +0100271#endif
272
Nicolas Capens157ba262019-12-10 17:49:14 -0500273 llvm::TargetOptions targetOptions;
274 targetOptions.UnsafeFPMath = false;
Ben Clayton6f8e5652019-06-29 01:58:02 +0100275
Nicolas Capens157ba262019-12-10 17:49:14 -0500276 auto targetMachine = std::unique_ptr<llvm::TargetMachine>(
277 llvm::EngineBuilder()
278 .setOptLevel(llvm::CodeGenOpt::None)
279 .setMCPU(mcpu)
280 .setMArch(march)
281 .setMAttrs(mattrs)
282 .setTargetOptions(targetOptions)
283 .selectTarget());
Ben Clayton6f8e5652019-06-29 01:58:02 +0100284
Nicolas Capens157ba262019-12-10 17:49:14 -0500285 auto dataLayout = targetMachine->createDataLayout();
Ben Clayton52ce1e92019-07-15 11:41:00 +0100286
Nicolas Capens157ba262019-12-10 17:49:14 -0500287 return JITGlobals(mcpu.data(), mattrs, march, targetOptions, dataLayout);
288}
Ben Clayton52ce1e92019-07-15 11:41:00 +0100289
Nicolas Capens157ba262019-12-10 17:49:14 -0500290llvm::CodeGenOpt::Level JITGlobals::toLLVM(rr::Optimization::Level level)
291{
Nicolas Capens81bc9d92019-12-16 15:05:57 -0500292 switch(level)
Ben Clayton52ce1e92019-07-15 11:41:00 +0100293 {
Nicolas Capens157ba262019-12-10 17:49:14 -0500294 case rr::Optimization::Level::None: return ::llvm::CodeGenOpt::None;
295 case rr::Optimization::Level::Less: return ::llvm::CodeGenOpt::Less;
296 case rr::Optimization::Level::Default: return ::llvm::CodeGenOpt::Default;
297 case rr::Optimization::Level::Aggressive: return ::llvm::CodeGenOpt::Aggressive;
298 default: UNREACHABLE("Unknown Optimization Level %d", int(level));
Ben Clayton52ce1e92019-07-15 11:41:00 +0100299 }
Nicolas Capens157ba262019-12-10 17:49:14 -0500300 return ::llvm::CodeGenOpt::Default;
301}
Ben Clayton52ce1e92019-07-15 11:41:00 +0100302
Nicolas Capens157ba262019-12-10 17:49:14 -0500303JITGlobals::JITGlobals(const char* mcpu,
304 const std::vector<std::string> &mattrs,
305 const char* march,
306 const llvm::TargetOptions &targetOptions,
307 const llvm::DataLayout &dataLayout) :
308 mcpu(mcpu),
309 mattrs(mattrs),
310 march(march),
311 targetOptions(targetOptions),
312 dataLayout(dataLayout)
313{
314}
Ben Clayton6f8e5652019-06-29 01:58:02 +0100315
Sergey Ulanovebb0bec2019-12-12 11:53:04 -0800316class MemoryMapper : public llvm::SectionMemoryManager::MemoryMapper
317{
318public:
319 MemoryMapper() {}
320 ~MemoryMapper() final {}
321
322 llvm::sys::MemoryBlock allocateMappedMemory(
323 llvm::SectionMemoryManager::AllocationPurpose purpose,
324 size_t numBytes, const llvm::sys::MemoryBlock *const nearBlock,
325 unsigned flags, std::error_code &errorCode) final {
326 errorCode = std::error_code();
327
328 // Round up numBytes to page size.
329 size_t pageSize = rr::memoryPageSize();
330 numBytes = (numBytes + pageSize - 1) & ~(pageSize - 1);
331
332 bool need_exec =
333 purpose == llvm::SectionMemoryManager::AllocationPurpose::Code;
334 void* addr = rr::allocateMemoryPages(
335 numBytes, flagsToPermissions(flags), need_exec);
Nicolas Capens81bc9d92019-12-16 15:05:57 -0500336 if(!addr)
Sergey Ulanovebb0bec2019-12-12 11:53:04 -0800337 return llvm::sys::MemoryBlock();
338 return llvm::sys::MemoryBlock(addr, numBytes);
339 }
340
341 std::error_code protectMappedMemory(const llvm::sys::MemoryBlock &block,
342 unsigned flags) {
343 // Round down base address to align with a page boundary. This matches
344 // DefaultMMapper behavior.
345 void* addr = block.base();
346 size_t size = block.size();
347 size_t pageSize = rr::memoryPageSize();
348 addr = reinterpret_cast<void*>(
349 reinterpret_cast<uintptr_t>(addr) & ~(pageSize - 1));
350 size += reinterpret_cast<uintptr_t>(block.base()) -
351 reinterpret_cast<uintptr_t>(addr);
352
353 rr::protectMemoryPages(addr, size, flagsToPermissions(flags));
354 return std::error_code();
355 }
356
357 std::error_code releaseMappedMemory(llvm::sys::MemoryBlock &block) {
358 rr::deallocateMemoryPages(block.base(), block.size());
359 return std::error_code();
360 }
361
362private:
363 int flagsToPermissions(unsigned flags) {
364 int result = 0;
Nicolas Capens81bc9d92019-12-16 15:05:57 -0500365 if(flags & llvm::sys::Memory::MF_READ)
Sergey Ulanovebb0bec2019-12-12 11:53:04 -0800366 {
367 result |= rr::PERMISSION_READ;
368 }
Nicolas Capens81bc9d92019-12-16 15:05:57 -0500369 if(flags & llvm::sys::Memory::MF_WRITE)
Sergey Ulanovebb0bec2019-12-12 11:53:04 -0800370 {
371 result |= rr::PERMISSION_WRITE;
372 }
Nicolas Capens81bc9d92019-12-16 15:05:57 -0500373 if(flags & llvm::sys::Memory::MF_EXEC)
Sergey Ulanovebb0bec2019-12-12 11:53:04 -0800374 {
375 result |= rr::PERMISSION_EXECUTE;
376 }
377 return result;
378 }
379
380};
381
Nicolas Capens157ba262019-12-10 17:49:14 -0500382// JITRoutine is a rr::Routine that holds a LLVM JIT session, compiler and
383// object layer as each routine may require different target machine
384// settings and no Reactor routine directly links against another.
385class JITRoutine : public rr::Routine
386{
Preston Jacksonee1af662019-09-27 15:26:26 -0600387#if LLVM_VERSION_MAJOR >= 8
Nicolas Capens157ba262019-12-10 17:49:14 -0500388 using ObjLayer = llvm::orc::LegacyRTDyldObjectLinkingLayer;
389 using CompileLayer = llvm::orc::LegacyIRCompileLayer<ObjLayer, llvm::orc::SimpleCompiler>;
Preston Jacksonee1af662019-09-27 15:26:26 -0600390#else
Nicolas Capens157ba262019-12-10 17:49:14 -0500391 using ObjLayer = llvm::orc::RTDyldObjectLinkingLayer;
392 using CompileLayer = llvm::orc::IRCompileLayer<ObjLayer, llvm::orc::SimpleCompiler>;
Preston Jacksonee1af662019-09-27 15:26:26 -0600393#endif
394
Nicolas Capens157ba262019-12-10 17:49:14 -0500395public:
396 JITRoutine(
397 std::unique_ptr<llvm::Module> module,
398 llvm::Function **funcs,
399 size_t count,
400 const rr::Config &config) :
401 resolver(createLegacyLookupResolver(
402 session,
403 [&](const std::string &name) {
404 void *func = rr::resolveExternalSymbol(name.c_str());
Nicolas Capens81bc9d92019-12-16 15:05:57 -0500405 if(func != nullptr)
Ben Clayton6f8e5652019-06-29 01:58:02 +0100406 {
Nicolas Capens157ba262019-12-10 17:49:14 -0500407 return llvm::JITSymbol(
408 reinterpret_cast<uintptr_t>(func), llvm::JITSymbolFlags::Absolute);
Ben Clayton6f8e5652019-06-29 01:58:02 +0100409 }
Nicolas Capens157ba262019-12-10 17:49:14 -0500410 return objLayer.findSymbol(name, true);
411 },
412 [](llvm::Error err) {
Nicolas Capens81bc9d92019-12-16 15:05:57 -0500413 if(err)
Nicolas Capens157ba262019-12-10 17:49:14 -0500414 {
415 // TODO: Log the symbol resolution errors.
416 return;
417 }
418 })),
419 targetMachine(JITGlobals::get()->getTargetMachine(config.getOptimization().getLevel())),
420 compileLayer(objLayer, llvm::orc::SimpleCompiler(*targetMachine)),
421 objLayer(
422 session,
423 [this](llvm::orc::VModuleKey) {
Sergey Ulanovebb0bec2019-12-12 11:53:04 -0800424 return ObjLayer::Resources{std::make_shared<llvm::SectionMemoryManager>(&memoryMapper), resolver};
Nicolas Capens157ba262019-12-10 17:49:14 -0500425 },
426 ObjLayer::NotifyLoadedFtor(),
427 [](llvm::orc::VModuleKey, const llvm::object::ObjectFile &Obj, const llvm::RuntimeDyld::LoadedObjectInfo &L) {
428#ifdef ENABLE_RR_DEBUG_INFO
429 rr::DebugInfo::NotifyObjectEmitted(Obj, L);
430#endif // ENABLE_RR_DEBUG_INFO
431 },
432 [](llvm::orc::VModuleKey, const llvm::object::ObjectFile &Obj) {
433#ifdef ENABLE_RR_DEBUG_INFO
434 rr::DebugInfo::NotifyFreeingObject(Obj);
435#endif // ENABLE_RR_DEBUG_INFO
Ben Clayton6f8e5652019-06-29 01:58:02 +0100436 }
Nicolas Capens157ba262019-12-10 17:49:14 -0500437 ),
438 addresses(count)
Ben Clayton6f8e5652019-06-29 01:58:02 +0100439 {
Nicolas Capens157ba262019-12-10 17:49:14 -0500440 std::vector<std::string> mangledNames(count);
Nicolas Capens81bc9d92019-12-16 15:05:57 -0500441 for(size_t i = 0; i < count; i++)
Ben Clayton6f8e5652019-06-29 01:58:02 +0100442 {
Nicolas Capens157ba262019-12-10 17:49:14 -0500443 auto func = funcs[i];
444 static size_t numEmittedFunctions = 0;
445 std::string name = "f" + llvm::Twine(numEmittedFunctions++).str();
446 func->setName(name);
447 func->setLinkage(llvm::GlobalValue::ExternalLinkage);
448 func->setDoesNotThrow();
449
450 llvm::raw_string_ostream mangledNameStream(mangledNames[i]);
451 llvm::Mangler::getNameWithPrefix(mangledNameStream, name, JITGlobals::get()->dataLayout);
Ben Clayton6f8e5652019-06-29 01:58:02 +0100452 }
453
Nicolas Capens157ba262019-12-10 17:49:14 -0500454 auto moduleKey = session.allocateVModule();
455
456 // Once the module is passed to the compileLayer, the
457 // llvm::Functions are freed. Make sure funcs are not referenced
458 // after this point.
459 funcs = nullptr;
460
461 llvm::cantFail(compileLayer.addModule(moduleKey, std::move(module)));
462
463 // Resolve the function addresses.
Nicolas Capens81bc9d92019-12-16 15:05:57 -0500464 for(size_t i = 0; i < count; i++)
Ben Clayton6f8e5652019-06-29 01:58:02 +0100465 {
Nicolas Capens157ba262019-12-10 17:49:14 -0500466 auto symbol = compileLayer.findSymbolIn(moduleKey, mangledNames[i], false);
467 if(auto address = symbol.getAddress())
468 {
469 addresses[i] = reinterpret_cast<void *>(static_cast<intptr_t>(address.get()));
470 }
471 }
472 }
473
474 const void *getEntry(int index) const override
475 {
476 return addresses[index];
477 }
478
479private:
480 std::shared_ptr<llvm::orc::SymbolResolver> resolver;
481 std::shared_ptr<llvm::TargetMachine> targetMachine;
482 llvm::orc::ExecutionSession session;
483 CompileLayer compileLayer;
Sergey Ulanovebb0bec2019-12-12 11:53:04 -0800484 MemoryMapper memoryMapper;
Nicolas Capens157ba262019-12-10 17:49:14 -0500485 ObjLayer objLayer;
486 std::vector<const void *> addresses;
487};
488
489// JITBuilder holds all the LLVM state for building routines.
490class JITBuilder
491{
492public:
493 JITBuilder(const rr::Config &config) :
494 config(config),
495 module(new llvm::Module("", context)),
496 builder(new llvm::IRBuilder<>(context))
497 {
498 module->setDataLayout(JITGlobals::get()->dataLayout);
499 }
500
501 void optimize(const rr::Config &cfg)
502 {
Ben Clayton55bc37a2019-07-04 12:17:12 +0100503
Ben Clayton6f8e5652019-06-29 01:58:02 +0100504#ifdef ENABLE_RR_DEBUG_INFO
Nicolas Capens81bc9d92019-12-16 15:05:57 -0500505 if(debugInfo != nullptr)
Nicolas Capens157ba262019-12-10 17:49:14 -0500506 {
507 return; // Don't optimize if we're generating debug info.
508 }
Ben Clayton6f8e5652019-06-29 01:58:02 +0100509#endif // ENABLE_RR_DEBUG_INFO
510
Nicolas Capens157ba262019-12-10 17:49:14 -0500511 std::unique_ptr<llvm::legacy::PassManager> passManager(
512 new llvm::legacy::PassManager());
Ben Clayton6f8e5652019-06-29 01:58:02 +0100513
Nicolas Capens157ba262019-12-10 17:49:14 -0500514 for(auto pass : cfg.getOptimization().getPasses())
515 {
516 switch(pass)
Ben Clayton6f8e5652019-06-29 01:58:02 +0100517 {
Nicolas Capens157ba262019-12-10 17:49:14 -0500518 case rr::Optimization::Pass::Disabled: break;
519 case rr::Optimization::Pass::CFGSimplification: passManager->add(llvm::createCFGSimplificationPass()); break;
520 case rr::Optimization::Pass::LICM: passManager->add(llvm::createLICMPass()); break;
521 case rr::Optimization::Pass::AggressiveDCE: passManager->add(llvm::createAggressiveDCEPass()); break;
522 case rr::Optimization::Pass::GVN: passManager->add(llvm::createGVNPass()); break;
523 case rr::Optimization::Pass::InstructionCombining: passManager->add(llvm::createInstructionCombiningPass()); break;
524 case rr::Optimization::Pass::Reassociate: passManager->add(llvm::createReassociatePass()); break;
525 case rr::Optimization::Pass::DeadStoreElimination: passManager->add(llvm::createDeadStoreEliminationPass()); break;
526 case rr::Optimization::Pass::SCCP: passManager->add(llvm::createSCCPPass()); break;
527 case rr::Optimization::Pass::ScalarReplAggregates: passManager->add(llvm::createSROAPass()); break;
528 case rr::Optimization::Pass::EarlyCSEPass: passManager->add(llvm::createEarlyCSEPass()); break;
529 default:
530 UNREACHABLE("pass: %d", int(pass));
Ben Clayton6f8e5652019-06-29 01:58:02 +0100531 }
Ben Clayton6f8e5652019-06-29 01:58:02 +0100532 }
533
Nicolas Capens157ba262019-12-10 17:49:14 -0500534 passManager->run(*module);
535 }
Ben Clayton6f8e5652019-06-29 01:58:02 +0100536
Nicolas Capens157ba262019-12-10 17:49:14 -0500537 std::shared_ptr<rr::Routine> acquireRoutine(llvm::Function **funcs, size_t count, const rr::Config &cfg)
538 {
539 ASSERT(module);
540 return std::make_shared<JITRoutine>(std::move(module), funcs, count, cfg);
541 }
Ben Clayton6f8e5652019-06-29 01:58:02 +0100542
Nicolas Capens157ba262019-12-10 17:49:14 -0500543 const rr::Config config;
544 llvm::LLVMContext context;
545 std::unique_ptr<llvm::Module> module;
546 std::unique_ptr<llvm::IRBuilder<>> builder;
547 llvm::Function *function = nullptr;
548
549 struct CoroutineState
550 {
551 llvm::Function *await = nullptr;
552 llvm::Function *destroy = nullptr;
553 llvm::Value *handle = nullptr;
554 llvm::Value *id = nullptr;
555 llvm::Value *promise = nullptr;
556 llvm::Type *yieldType = nullptr;
557 llvm::BasicBlock *entryBlock = nullptr;
558 llvm::BasicBlock *suspendBlock = nullptr;
559 llvm::BasicBlock *endBlock = nullptr;
560 llvm::BasicBlock *destroyBlock = nullptr;
561 };
562 CoroutineState coroutine;
Ben Clayton6f8e5652019-06-29 01:58:02 +0100563
564#ifdef ENABLE_RR_DEBUG_INFO
Nicolas Capens157ba262019-12-10 17:49:14 -0500565 std::unique_ptr<rr::DebugInfo> debugInfo;
Ben Clayton6f8e5652019-06-29 01:58:02 +0100566#endif
Nicolas Capens157ba262019-12-10 17:49:14 -0500567};
Ben Clayton6f8e5652019-06-29 01:58:02 +0100568
Nicolas Capens157ba262019-12-10 17:49:14 -0500569std::unique_ptr<JITBuilder> jit;
570std::mutex codegenMutex;
Logan Chien0eedc8c2018-08-21 09:34:28 +0800571
Ben Clayton60a3d6f2019-02-26 17:24:46 +0000572#ifdef ENABLE_RR_PRINT
Nicolas Capens157ba262019-12-10 17:49:14 -0500573std::string replace(std::string str, const std::string& substr, const std::string& replacement)
574{
575 size_t pos = 0;
576 while((pos = str.find(substr, pos)) != std::string::npos) {
577 str.replace(pos, substr.length(), replacement);
578 pos += replacement.length();
Ben Clayton1bc7ee92019-02-14 18:43:22 +0000579 }
Nicolas Capens157ba262019-12-10 17:49:14 -0500580 return str;
581}
Ben Clayton60a3d6f2019-02-26 17:24:46 +0000582#endif // ENABLE_RR_PRINT
Ben Clayton1bc7ee92019-02-14 18:43:22 +0000583
Nicolas Capens157ba262019-12-10 17:49:14 -0500584template <typename T>
585T alignUp(T val, T alignment)
586{
587 return alignment * ((val + alignment - 1) / alignment);
588}
Ben Clayton40a885e2019-06-23 19:12:48 +0100589
Nicolas Capens157ba262019-12-10 17:49:14 -0500590void* alignedAlloc(size_t size, size_t alignment)
591{
592 ASSERT(alignment < 256);
593 auto allocation = new uint8_t[size + sizeof(uint8_t) + alignment];
594 auto aligned = allocation;
595 aligned += sizeof(uint8_t); // Make space for the base-address offset.
596 aligned = reinterpret_cast<uint8_t*>(alignUp(reinterpret_cast<uintptr_t>(aligned), alignment)); // align
597 auto offset = static_cast<uint8_t>(aligned - allocation);
598 aligned[-1] = offset;
599 return aligned;
600}
Ben Clayton40a885e2019-06-23 19:12:48 +0100601
Nicolas Capens157ba262019-12-10 17:49:14 -0500602void alignedFree(void* ptr)
603{
604 auto aligned = reinterpret_cast<uint8_t*>(ptr);
605 auto offset = aligned[-1];
606 auto allocation = aligned - offset;
607 delete[] allocation;
608}
Ben Clayton40a885e2019-06-23 19:12:48 +0100609
Nicolas Capens157ba262019-12-10 17:49:14 -0500610llvm::Value *lowerPAVG(llvm::Value *x, llvm::Value *y)
611{
612 llvm::VectorType *ty = llvm::cast<llvm::VectorType>(x->getType());
Logan Chien0eedc8c2018-08-21 09:34:28 +0800613
Nicolas Capens157ba262019-12-10 17:49:14 -0500614 llvm::VectorType *extTy =
615 llvm::VectorType::getExtendedElementVectorType(ty);
616 x = jit->builder->CreateZExt(x, extTy);
617 y = jit->builder->CreateZExt(y, extTy);
Logan Chien0eedc8c2018-08-21 09:34:28 +0800618
Nicolas Capens157ba262019-12-10 17:49:14 -0500619 // (x + y + 1) >> 1
620 llvm::Constant *one = llvm::ConstantInt::get(extTy, 1);
621 llvm::Value *res = jit->builder->CreateAdd(x, y);
622 res = jit->builder->CreateAdd(res, one);
623 res = jit->builder->CreateLShr(res, one);
624 return jit->builder->CreateTrunc(res, ty);
625}
Logan Chien0eedc8c2018-08-21 09:34:28 +0800626
Nicolas Capens157ba262019-12-10 17:49:14 -0500627llvm::Value *lowerPMINMAX(llvm::Value *x, llvm::Value *y,
628 llvm::ICmpInst::Predicate pred)
629{
630 return jit->builder->CreateSelect(jit->builder->CreateICmp(pred, x, y), x, y);
631}
Logan Chien0eedc8c2018-08-21 09:34:28 +0800632
Nicolas Capens157ba262019-12-10 17:49:14 -0500633llvm::Value *lowerPCMP(llvm::ICmpInst::Predicate pred, llvm::Value *x,
634 llvm::Value *y, llvm::Type *dstTy)
635{
636 return jit->builder->CreateSExt(jit->builder->CreateICmp(pred, x, y), dstTy, "");
637}
Logan Chien0eedc8c2018-08-21 09:34:28 +0800638
Logan Chiene3191012018-08-24 22:01:50 +0800639#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -0500640llvm::Value *lowerPMOV(llvm::Value *op, llvm::Type *dstType, bool sext)
641{
642 llvm::VectorType *srcTy = llvm::cast<llvm::VectorType>(op->getType());
643 llvm::VectorType *dstTy = llvm::cast<llvm::VectorType>(dstType);
Logan Chien0eedc8c2018-08-21 09:34:28 +0800644
Nicolas Capens157ba262019-12-10 17:49:14 -0500645 llvm::Value *undef = llvm::UndefValue::get(srcTy);
646 llvm::SmallVector<uint32_t, 16> mask(dstTy->getNumElements());
647 std::iota(mask.begin(), mask.end(), 0);
648 llvm::Value *v = jit->builder->CreateShuffleVector(op, undef, mask);
Logan Chien0eedc8c2018-08-21 09:34:28 +0800649
Nicolas Capens157ba262019-12-10 17:49:14 -0500650 return sext ? jit->builder->CreateSExt(v, dstTy)
651 : jit->builder->CreateZExt(v, dstTy);
652}
Logan Chien0eedc8c2018-08-21 09:34:28 +0800653
Nicolas Capens157ba262019-12-10 17:49:14 -0500654llvm::Value *lowerPABS(llvm::Value *v)
655{
656 llvm::Value *zero = llvm::Constant::getNullValue(v->getType());
657 llvm::Value *cmp = jit->builder->CreateICmp(llvm::ICmpInst::ICMP_SGT, v, zero);
658 llvm::Value *neg = jit->builder->CreateNeg(v);
659 return jit->builder->CreateSelect(cmp, v, neg);
660}
Logan Chien0eedc8c2018-08-21 09:34:28 +0800661#endif // defined(__i386__) || defined(__x86_64__)
Logan Chiene3191012018-08-24 22:01:50 +0800662
663#if !defined(__i386__) && !defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -0500664llvm::Value *lowerPFMINMAX(llvm::Value *x, llvm::Value *y,
665 llvm::FCmpInst::Predicate pred)
666{
667 return jit->builder->CreateSelect(jit->builder->CreateFCmp(pred, x, y), x, y);
668}
669
670llvm::Value *lowerRound(llvm::Value *x)
671{
672 llvm::Function *nearbyint = llvm::Intrinsic::getDeclaration(
673 jit->module.get(), llvm::Intrinsic::nearbyint, {x->getType()});
674 return jit->builder->CreateCall(nearbyint, ARGS(x));
675}
676
677llvm::Value *lowerRoundInt(llvm::Value *x, llvm::Type *ty)
678{
679 return jit->builder->CreateFPToSI(lowerRound(x), ty);
680}
681
682llvm::Value *lowerFloor(llvm::Value *x)
683{
684 llvm::Function *floor = llvm::Intrinsic::getDeclaration(
685 jit->module.get(), llvm::Intrinsic::floor, {x->getType()});
686 return jit->builder->CreateCall(floor, ARGS(x));
687}
688
689llvm::Value *lowerTrunc(llvm::Value *x)
690{
691 llvm::Function *trunc = llvm::Intrinsic::getDeclaration(
692 jit->module.get(), llvm::Intrinsic::trunc, {x->getType()});
693 return jit->builder->CreateCall(trunc, ARGS(x));
694}
695
696// Packed add/sub with saturation
697llvm::Value *lowerPSAT(llvm::Value *x, llvm::Value *y, bool isAdd, bool isSigned)
698{
699 llvm::VectorType *ty = llvm::cast<llvm::VectorType>(x->getType());
700 llvm::VectorType *extTy = llvm::VectorType::getExtendedElementVectorType(ty);
701
702 unsigned numBits = ty->getScalarSizeInBits();
703
704 llvm::Value *max, *min, *extX, *extY;
Nicolas Capens81bc9d92019-12-16 15:05:57 -0500705 if(isSigned)
Logan Chiene3191012018-08-24 22:01:50 +0800706 {
Nicolas Capens157ba262019-12-10 17:49:14 -0500707 max = llvm::ConstantInt::get(extTy, (1LL << (numBits - 1)) - 1, true);
708 min = llvm::ConstantInt::get(extTy, (-1LL << (numBits - 1)), true);
709 extX = jit->builder->CreateSExt(x, extTy);
710 extY = jit->builder->CreateSExt(y, extTy);
711 }
712 else
713 {
714 ASSERT_MSG(numBits <= 64, "numBits: %d", int(numBits));
715 uint64_t maxVal = (numBits == 64) ? ~0ULL : (1ULL << numBits) - 1;
716 max = llvm::ConstantInt::get(extTy, maxVal, false);
717 min = llvm::ConstantInt::get(extTy, 0, false);
718 extX = jit->builder->CreateZExt(x, extTy);
719 extY = jit->builder->CreateZExt(y, extTy);
Logan Chiene3191012018-08-24 22:01:50 +0800720 }
721
Nicolas Capens157ba262019-12-10 17:49:14 -0500722 llvm::Value *res = isAdd ? jit->builder->CreateAdd(extX, extY)
723 : jit->builder->CreateSub(extX, extY);
724
725 res = lowerPMINMAX(res, min, llvm::ICmpInst::ICMP_SGT);
726 res = lowerPMINMAX(res, max, llvm::ICmpInst::ICMP_SLT);
727
728 return jit->builder->CreateTrunc(res, ty);
729}
730
731llvm::Value *lowerSQRT(llvm::Value *x)
732{
733 llvm::Function *sqrt = llvm::Intrinsic::getDeclaration(
734 jit->module.get(), llvm::Intrinsic::sqrt, {x->getType()});
735 return jit->builder->CreateCall(sqrt, ARGS(x));
736}
737
738llvm::Value *lowerRCP(llvm::Value *x)
739{
740 llvm::Type *ty = x->getType();
741 llvm::Constant *one;
Nicolas Capens81bc9d92019-12-16 15:05:57 -0500742 if(llvm::VectorType *vectorTy = llvm::dyn_cast<llvm::VectorType>(ty))
Logan Chien83fc07a2018-09-26 22:14:00 +0800743 {
Nicolas Capens157ba262019-12-10 17:49:14 -0500744 one = llvm::ConstantVector::getSplat(
745 vectorTy->getNumElements(),
746 llvm::ConstantFP::get(vectorTy->getElementType(), 1));
747 }
748 else
749 {
750 one = llvm::ConstantFP::get(ty, 1);
751 }
752 return jit->builder->CreateFDiv(one, x);
753}
754
755llvm::Value *lowerRSQRT(llvm::Value *x)
756{
757 return lowerRCP(lowerSQRT(x));
758}
759
760llvm::Value *lowerVectorShl(llvm::Value *x, uint64_t scalarY)
761{
762 llvm::VectorType *ty = llvm::cast<llvm::VectorType>(x->getType());
763 llvm::Value *y = llvm::ConstantVector::getSplat(
764 ty->getNumElements(),
765 llvm::ConstantInt::get(ty->getElementType(), scalarY));
766 return jit->builder->CreateShl(x, y);
767}
768
769llvm::Value *lowerVectorAShr(llvm::Value *x, uint64_t scalarY)
770{
771 llvm::VectorType *ty = llvm::cast<llvm::VectorType>(x->getType());
772 llvm::Value *y = llvm::ConstantVector::getSplat(
773 ty->getNumElements(),
774 llvm::ConstantInt::get(ty->getElementType(), scalarY));
775 return jit->builder->CreateAShr(x, y);
776}
777
778llvm::Value *lowerVectorLShr(llvm::Value *x, uint64_t scalarY)
779{
780 llvm::VectorType *ty = llvm::cast<llvm::VectorType>(x->getType());
781 llvm::Value *y = llvm::ConstantVector::getSplat(
782 ty->getNumElements(),
783 llvm::ConstantInt::get(ty->getElementType(), scalarY));
784 return jit->builder->CreateLShr(x, y);
785}
786
787llvm::Value *lowerMulAdd(llvm::Value *x, llvm::Value *y)
788{
789 llvm::VectorType *ty = llvm::cast<llvm::VectorType>(x->getType());
790 llvm::VectorType *extTy = llvm::VectorType::getExtendedElementVectorType(ty);
791
792 llvm::Value *extX = jit->builder->CreateSExt(x, extTy);
793 llvm::Value *extY = jit->builder->CreateSExt(y, extTy);
794 llvm::Value *mult = jit->builder->CreateMul(extX, extY);
795
796 llvm::Value *undef = llvm::UndefValue::get(extTy);
797
798 llvm::SmallVector<uint32_t, 16> evenIdx;
799 llvm::SmallVector<uint32_t, 16> oddIdx;
Nicolas Capens81bc9d92019-12-16 15:05:57 -0500800 for(uint64_t i = 0, n = ty->getNumElements(); i < n; i += 2)
Nicolas Capens157ba262019-12-10 17:49:14 -0500801 {
802 evenIdx.push_back(i);
803 oddIdx.push_back(i + 1);
Logan Chien83fc07a2018-09-26 22:14:00 +0800804 }
805
Nicolas Capens157ba262019-12-10 17:49:14 -0500806 llvm::Value *lhs = jit->builder->CreateShuffleVector(mult, undef, evenIdx);
807 llvm::Value *rhs = jit->builder->CreateShuffleVector(mult, undef, oddIdx);
808 return jit->builder->CreateAdd(lhs, rhs);
809}
810
811llvm::Value *lowerPack(llvm::Value *x, llvm::Value *y, bool isSigned)
812{
813 llvm::VectorType *srcTy = llvm::cast<llvm::VectorType>(x->getType());
814 llvm::VectorType *dstTy = llvm::VectorType::getTruncatedElementVectorType(srcTy);
815
816 llvm::IntegerType *dstElemTy =
817 llvm::cast<llvm::IntegerType>(dstTy->getElementType());
818
819 uint64_t truncNumBits = dstElemTy->getIntegerBitWidth();
820 ASSERT_MSG(truncNumBits < 64, "shift 64 must be handled separately. truncNumBits: %d", int(truncNumBits));
821 llvm::Constant *max, *min;
Nicolas Capens81bc9d92019-12-16 15:05:57 -0500822 if(isSigned)
Logan Chien2faa24a2018-09-26 19:59:32 +0800823 {
Nicolas Capens157ba262019-12-10 17:49:14 -0500824 max = llvm::ConstantInt::get(srcTy, (1LL << (truncNumBits - 1)) - 1, true);
825 min = llvm::ConstantInt::get(srcTy, (-1LL << (truncNumBits - 1)), true);
826 }
827 else
828 {
829 max = llvm::ConstantInt::get(srcTy, (1ULL << truncNumBits) - 1, false);
830 min = llvm::ConstantInt::get(srcTy, 0, false);
Logan Chien2faa24a2018-09-26 19:59:32 +0800831 }
832
Nicolas Capens157ba262019-12-10 17:49:14 -0500833 x = lowerPMINMAX(x, min, llvm::ICmpInst::ICMP_SGT);
834 x = lowerPMINMAX(x, max, llvm::ICmpInst::ICMP_SLT);
835 y = lowerPMINMAX(y, min, llvm::ICmpInst::ICMP_SGT);
836 y = lowerPMINMAX(y, max, llvm::ICmpInst::ICMP_SLT);
837
838 x = jit->builder->CreateTrunc(x, dstTy);
839 y = jit->builder->CreateTrunc(y, dstTy);
840
841 llvm::SmallVector<uint32_t, 16> index(srcTy->getNumElements() * 2);
842 std::iota(index.begin(), index.end(), 0);
843
844 return jit->builder->CreateShuffleVector(x, y, index);
845}
846
847llvm::Value *lowerSignMask(llvm::Value *x, llvm::Type *retTy)
848{
849 llvm::VectorType *ty = llvm::cast<llvm::VectorType>(x->getType());
850 llvm::Constant *zero = llvm::ConstantInt::get(ty, 0);
851 llvm::Value *cmp = jit->builder->CreateICmpSLT(x, zero);
852
853 llvm::Value *ret = jit->builder->CreateZExt(
854 jit->builder->CreateExtractElement(cmp, static_cast<uint64_t>(0)), retTy);
Nicolas Capens81bc9d92019-12-16 15:05:57 -0500855 for(uint64_t i = 1, n = ty->getNumElements(); i < n; ++i)
Logan Chien40a60052018-09-26 19:03:53 +0800856 {
Nicolas Capens157ba262019-12-10 17:49:14 -0500857 llvm::Value *elem = jit->builder->CreateZExt(
858 jit->builder->CreateExtractElement(cmp, i), retTy);
859 ret = jit->builder->CreateOr(ret, jit->builder->CreateShl(elem, i));
Logan Chien40a60052018-09-26 19:03:53 +0800860 }
Nicolas Capens157ba262019-12-10 17:49:14 -0500861 return ret;
862}
Logan Chien40a60052018-09-26 19:03:53 +0800863
Nicolas Capens157ba262019-12-10 17:49:14 -0500864llvm::Value *lowerFPSignMask(llvm::Value *x, llvm::Type *retTy)
865{
866 llvm::VectorType *ty = llvm::cast<llvm::VectorType>(x->getType());
867 llvm::Constant *zero = llvm::ConstantFP::get(ty, 0);
868 llvm::Value *cmp = jit->builder->CreateFCmpULT(x, zero);
869
870 llvm::Value *ret = jit->builder->CreateZExt(
871 jit->builder->CreateExtractElement(cmp, static_cast<uint64_t>(0)), retTy);
Nicolas Capens81bc9d92019-12-16 15:05:57 -0500872 for(uint64_t i = 1, n = ty->getNumElements(); i < n; ++i)
Logan Chien8c5ca8d2018-09-27 21:05:53 +0800873 {
Nicolas Capens157ba262019-12-10 17:49:14 -0500874 llvm::Value *elem = jit->builder->CreateZExt(
875 jit->builder->CreateExtractElement(cmp, i), retTy);
876 ret = jit->builder->CreateOr(ret, jit->builder->CreateShl(elem, i));
Logan Chien8c5ca8d2018-09-27 21:05:53 +0800877 }
Nicolas Capens157ba262019-12-10 17:49:14 -0500878 return ret;
879}
Logan Chiene3191012018-08-24 22:01:50 +0800880#endif // !defined(__i386__) && !defined(__x86_64__)
Chris Forbese86b6dc2019-03-01 09:08:47 -0800881
Nicolas Capens81bc9d92019-12-16 15:05:57 -0500882#if(LLVM_VERSION_MAJOR >= 8) || (!defined(__i386__) && !defined(__x86_64__))
Nicolas Capens157ba262019-12-10 17:49:14 -0500883llvm::Value *lowerPUADDSAT(llvm::Value *x, llvm::Value *y)
884{
885 #if LLVM_VERSION_MAJOR >= 8
886 return jit->builder->CreateBinaryIntrinsic(llvm::Intrinsic::uadd_sat, x, y);
887 #else
888 return lowerPSAT(x, y, true, false);
889 #endif
890}
Preston Jacksonee1af662019-09-27 15:26:26 -0600891
Nicolas Capens157ba262019-12-10 17:49:14 -0500892llvm::Value *lowerPSADDSAT(llvm::Value *x, llvm::Value *y)
893{
894 #if LLVM_VERSION_MAJOR >= 8
895 return jit->builder->CreateBinaryIntrinsic(llvm::Intrinsic::sadd_sat, x, y);
896 #else
897 return lowerPSAT(x, y, true, true);
898 #endif
899}
Preston Jacksonee1af662019-09-27 15:26:26 -0600900
Nicolas Capens157ba262019-12-10 17:49:14 -0500901llvm::Value *lowerPUSUBSAT(llvm::Value *x, llvm::Value *y)
902{
903 #if LLVM_VERSION_MAJOR >= 8
904 return jit->builder->CreateBinaryIntrinsic(llvm::Intrinsic::usub_sat, x, y);
905 #else
906 return lowerPSAT(x, y, false, false);
907 #endif
908}
Preston Jacksonee1af662019-09-27 15:26:26 -0600909
Nicolas Capens157ba262019-12-10 17:49:14 -0500910llvm::Value *lowerPSSUBSAT(llvm::Value *x, llvm::Value *y)
911{
912 #if LLVM_VERSION_MAJOR >= 8
913 return jit->builder->CreateBinaryIntrinsic(llvm::Intrinsic::ssub_sat, x, y);
914 #else
915 return lowerPSAT(x, y, false, true);
916 #endif
917}
Preston Jacksonee1af662019-09-27 15:26:26 -0600918#endif // (LLVM_VERSION_MAJOR >= 8) || (!defined(__i386__) && !defined(__x86_64__))
919
Nicolas Capens157ba262019-12-10 17:49:14 -0500920llvm::Value *lowerMulHigh(llvm::Value *x, llvm::Value *y, bool sext)
921{
922 llvm::VectorType *ty = llvm::cast<llvm::VectorType>(x->getType());
923 llvm::VectorType *extTy = llvm::VectorType::getExtendedElementVectorType(ty);
924
925 llvm::Value *extX, *extY;
Nicolas Capens81bc9d92019-12-16 15:05:57 -0500926 if(sext)
Chris Forbese86b6dc2019-03-01 09:08:47 -0800927 {
Nicolas Capens157ba262019-12-10 17:49:14 -0500928 extX = jit->builder->CreateSExt(x, extTy);
929 extY = jit->builder->CreateSExt(y, extTy);
930 }
931 else
932 {
933 extX = jit->builder->CreateZExt(x, extTy);
934 extY = jit->builder->CreateZExt(y, extTy);
Chris Forbese86b6dc2019-03-01 09:08:47 -0800935 }
Antonio Maioranoe6ab4702019-11-29 11:26:30 -0500936
Nicolas Capens157ba262019-12-10 17:49:14 -0500937 llvm::Value *mult = jit->builder->CreateMul(extX, extY);
938
939 llvm::IntegerType *intTy = llvm::cast<llvm::IntegerType>(ty->getElementType());
940 llvm::Value *mulh = jit->builder->CreateAShr(mult, intTy->getBitWidth());
941 return jit->builder->CreateTrunc(mulh, ty);
942}
943
944llvm::Value *createGather(llvm::Value *base, llvm::Type *elTy, llvm::Value *offsets, llvm::Value *mask, unsigned int alignment, bool zeroMaskedLanes)
945{
946 ASSERT(base->getType()->isPointerTy());
947 ASSERT(offsets->getType()->isVectorTy());
948 ASSERT(mask->getType()->isVectorTy());
949
950 auto numEls = mask->getType()->getVectorNumElements();
951 auto i1Ty = ::llvm::Type::getInt1Ty(jit->context);
952 auto i32Ty = ::llvm::Type::getInt32Ty(jit->context);
953 auto i8Ty = ::llvm::Type::getInt8Ty(jit->context);
954 auto i8PtrTy = i8Ty->getPointerTo();
955 auto elPtrTy = elTy->getPointerTo();
956 auto elVecTy = ::llvm::VectorType::get(elTy, numEls);
957 auto elPtrVecTy = ::llvm::VectorType::get(elPtrTy, numEls);
958 auto i8Base = jit->builder->CreatePointerCast(base, i8PtrTy);
959 auto i8Ptrs = jit->builder->CreateGEP(i8Base, offsets);
960 auto elPtrs = jit->builder->CreatePointerCast(i8Ptrs, elPtrVecTy);
961 auto i8Mask = jit->builder->CreateIntCast(mask, ::llvm::VectorType::get(i1Ty, numEls), false); // vec<int, int, ...> -> vec<bool, bool, ...>
962 auto passthrough = zeroMaskedLanes ? ::llvm::Constant::getNullValue(elVecTy) : llvm::UndefValue::get(elVecTy);
963 auto align = ::llvm::ConstantInt::get(i32Ty, alignment);
964 auto func = ::llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::masked_gather, { elVecTy, elPtrVecTy } );
965 return jit->builder->CreateCall(func, { elPtrs, align, i8Mask, passthrough });
966}
967
968void createScatter(llvm::Value *base, llvm::Value *val, llvm::Value *offsets, llvm::Value *mask, unsigned int alignment)
969{
970 ASSERT(base->getType()->isPointerTy());
971 ASSERT(val->getType()->isVectorTy());
972 ASSERT(offsets->getType()->isVectorTy());
973 ASSERT(mask->getType()->isVectorTy());
974
975 auto numEls = mask->getType()->getVectorNumElements();
976 auto i1Ty = ::llvm::Type::getInt1Ty(jit->context);
977 auto i32Ty = ::llvm::Type::getInt32Ty(jit->context);
978 auto i8Ty = ::llvm::Type::getInt8Ty(jit->context);
979 auto i8PtrTy = i8Ty->getPointerTo();
980 auto elVecTy = val->getType();
981 auto elTy = elVecTy->getVectorElementType();
982 auto elPtrTy = elTy->getPointerTo();
983 auto elPtrVecTy = ::llvm::VectorType::get(elPtrTy, numEls);
984 auto i8Base = jit->builder->CreatePointerCast(base, i8PtrTy);
985 auto i8Ptrs = jit->builder->CreateGEP(i8Base, offsets);
986 auto elPtrs = jit->builder->CreatePointerCast(i8Ptrs, elPtrVecTy);
987 auto i8Mask = jit->builder->CreateIntCast(mask, ::llvm::VectorType::get(i1Ty, numEls), false); // vec<int, int, ...> -> vec<bool, bool, ...>
988 auto align = ::llvm::ConstantInt::get(i32Ty, alignment);
989 auto func = ::llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::masked_scatter, { elVecTy, elPtrVecTy } );
990 jit->builder->CreateCall(func, { val, elPtrs, align, i8Mask });
991}
992}
993
994namespace rr {
995
996const Capabilities Caps =
997{
998 true, // CoroutinesSupported
999};
1000
1001static std::memory_order atomicOrdering(llvm::AtomicOrdering memoryOrder)
1002{
1003 switch(memoryOrder)
Antonio Maioranoe6ab4702019-11-29 11:26:30 -05001004 {
Nicolas Capens157ba262019-12-10 17:49:14 -05001005 case llvm::AtomicOrdering::Monotonic: return std::memory_order_relaxed; // https://llvm.org/docs/Atomics.html#monotonic
1006 case llvm::AtomicOrdering::Acquire: return std::memory_order_acquire;
1007 case llvm::AtomicOrdering::Release: return std::memory_order_release;
1008 case llvm::AtomicOrdering::AcquireRelease: return std::memory_order_acq_rel;
1009 case llvm::AtomicOrdering::SequentiallyConsistent: return std::memory_order_seq_cst;
1010 default:
1011 UNREACHABLE("memoryOrder: %d", int(memoryOrder));
1012 return std::memory_order_acq_rel;
Antonio Maioranoe6ab4702019-11-29 11:26:30 -05001013 }
Nicolas Capens5c1f5cc2016-09-23 16:45:13 -04001014}
1015
Nicolas Capens157ba262019-12-10 17:49:14 -05001016static llvm::AtomicOrdering atomicOrdering(bool atomic, std::memory_order memoryOrder)
John Bauman89401822014-05-06 15:04:28 -04001017{
Nicolas Capens157ba262019-12-10 17:49:14 -05001018 if(!atomic)
Ben Claytonc7904162019-04-17 17:35:48 -04001019 {
Nicolas Capens157ba262019-12-10 17:49:14 -05001020 return llvm::AtomicOrdering::NotAtomic;
1021 }
1022
1023 switch(memoryOrder)
1024 {
1025 case std::memory_order_relaxed: return llvm::AtomicOrdering::Monotonic; // https://llvm.org/docs/Atomics.html#monotonic
1026 case std::memory_order_consume: return llvm::AtomicOrdering::Acquire; // https://llvm.org/docs/Atomics.html#acquire: "It should also be used for C++11/C11 memory_order_consume."
1027 case std::memory_order_acquire: return llvm::AtomicOrdering::Acquire;
1028 case std::memory_order_release: return llvm::AtomicOrdering::Release;
1029 case std::memory_order_acq_rel: return llvm::AtomicOrdering::AcquireRelease;
1030 case std::memory_order_seq_cst: return llvm::AtomicOrdering::SequentiallyConsistent;
1031 default:
1032 UNREACHABLE("memoryOrder: %d", int(memoryOrder));
1033 return llvm::AtomicOrdering::AcquireRelease;
1034 }
1035}
1036
1037template <typename T>
1038static void atomicLoad(void *ptr, void *ret, llvm::AtomicOrdering ordering)
1039{
1040 *reinterpret_cast<T*>(ret) = std::atomic_load_explicit<T>(reinterpret_cast<std::atomic<T>*>(ptr), atomicOrdering(ordering));
1041}
1042
1043template <typename T>
1044static void atomicStore(void *ptr, void *val, llvm::AtomicOrdering ordering)
1045{
1046 std::atomic_store_explicit<T>(reinterpret_cast<std::atomic<T>*>(ptr), *reinterpret_cast<T*>(val), atomicOrdering(ordering));
1047}
1048
1049#ifdef __ANDROID__
1050template<typename F>
1051static uint32_t sync_fetch_and_op(uint32_t volatile *ptr, uint32_t val, F f)
1052{
1053 // Build an arbitrary op out of looped CAS
Nicolas Capens81bc9d92019-12-16 15:05:57 -05001054 for(;;)
Nicolas Capens157ba262019-12-10 17:49:14 -05001055 {
1056 uint32_t expected = *ptr;
1057 uint32_t desired = f(expected, val);
1058
Nicolas Capens81bc9d92019-12-16 15:05:57 -05001059 if(expected == __sync_val_compare_and_swap_4(ptr, expected, desired))
Nicolas Capens157ba262019-12-10 17:49:14 -05001060 return expected;
1061 }
1062}
1063#endif
1064
1065void* resolveExternalSymbol(const char* name)
1066{
1067 struct Atomic
1068 {
1069 static void load(size_t size, void *ptr, void *ret, llvm::AtomicOrdering ordering)
1070 {
Nicolas Capens81bc9d92019-12-16 15:05:57 -05001071 switch(size)
Nicolas Capens157ba262019-12-10 17:49:14 -05001072 {
1073 case 1: atomicLoad<uint8_t>(ptr, ret, ordering); break;
1074 case 2: atomicLoad<uint16_t>(ptr, ret, ordering); break;
1075 case 4: atomicLoad<uint32_t>(ptr, ret, ordering); break;
1076 case 8: atomicLoad<uint64_t>(ptr, ret, ordering); break;
1077 default:
1078 UNIMPLEMENTED("Atomic::load(size: %d)", int(size));
1079 }
1080 }
1081 static void store(size_t size, void *ptr, void *ret, llvm::AtomicOrdering ordering)
1082 {
Nicolas Capens81bc9d92019-12-16 15:05:57 -05001083 switch(size)
Nicolas Capens157ba262019-12-10 17:49:14 -05001084 {
1085 case 1: atomicStore<uint8_t>(ptr, ret, ordering); break;
1086 case 2: atomicStore<uint16_t>(ptr, ret, ordering); break;
1087 case 4: atomicStore<uint32_t>(ptr, ret, ordering); break;
1088 case 8: atomicStore<uint64_t>(ptr, ret, ordering); break;
1089 default:
1090 UNIMPLEMENTED("Atomic::store(size: %d)", int(size));
1091 }
1092 }
Ben Claytonc7904162019-04-17 17:35:48 -04001093 };
1094
Nicolas Capens157ba262019-12-10 17:49:14 -05001095 struct F
Ben Clayton4d1f8d02019-04-17 23:47:35 -04001096 {
Nicolas Capens157ba262019-12-10 17:49:14 -05001097 static void nop() {}
1098 static void neverCalled() { UNREACHABLE("Should never be called"); }
Ben Clayton4d1f8d02019-04-17 23:47:35 -04001099
Nicolas Capens157ba262019-12-10 17:49:14 -05001100 static void* coroutine_alloc_frame(size_t size) { return alignedAlloc(size, 16); }
1101 static void coroutine_free_frame(void* ptr) { alignedFree(ptr); }
Ben Clayton4d1f8d02019-04-17 23:47:35 -04001102
Chris Forbesfd4c96d2019-06-20 11:20:42 -07001103#ifdef __ANDROID__
Nicolas Capens157ba262019-12-10 17:49:14 -05001104 // forwarders since we can't take address of builtins
1105 static void sync_synchronize() { __sync_synchronize(); }
1106 static uint32_t sync_fetch_and_add_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_add_4(ptr, val); }
1107 static uint32_t sync_fetch_and_and_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_and_4(ptr, val); }
1108 static uint32_t sync_fetch_and_or_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_or_4(ptr, val); }
1109 static uint32_t sync_fetch_and_xor_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_xor_4(ptr, val); }
1110 static uint32_t sync_fetch_and_sub_4(uint32_t *ptr, uint32_t val) { return __sync_fetch_and_sub_4(ptr, val); }
1111 static uint32_t sync_lock_test_and_set_4(uint32_t *ptr, uint32_t val) { return __sync_lock_test_and_set_4(ptr, val); }
1112 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); }
Chris Forbesfd4c96d2019-06-20 11:20:42 -07001113
Nicolas Capens157ba262019-12-10 17:49:14 -05001114 static uint32_t sync_fetch_and_max_4(uint32_t *ptr, uint32_t val) { return sync_fetch_and_op(ptr, val, [](int32_t a, int32_t b) { return std::max(a,b);}); }
1115 static uint32_t sync_fetch_and_min_4(uint32_t *ptr, uint32_t val) { return sync_fetch_and_op(ptr, val, [](int32_t a, int32_t b) { return std::min(a,b);}); }
1116 static uint32_t sync_fetch_and_umax_4(uint32_t *ptr, uint32_t val) { return sync_fetch_and_op(ptr, val, [](uint32_t a, uint32_t b) { return std::max(a,b);}); }
1117 static uint32_t sync_fetch_and_umin_4(uint32_t *ptr, uint32_t val) { return sync_fetch_and_op(ptr, val, [](uint32_t a, uint32_t b) { return std::min(a,b);}); }
Chris Forbesfd4c96d2019-06-20 11:20:42 -07001118#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05001119 };
Chris Forbesfd4c96d2019-06-20 11:20:42 -07001120
Nicolas Capens157ba262019-12-10 17:49:14 -05001121 class Resolver
Logan Chien40a60052018-09-26 19:03:53 +08001122 {
Nicolas Capens157ba262019-12-10 17:49:14 -05001123 public:
1124 using FunctionMap = std::unordered_map<std::string, void *>;
1125
1126 FunctionMap functions;
1127
1128 Resolver()
Logan Chien40a60052018-09-26 19:03:53 +08001129 {
Nicolas Capens157ba262019-12-10 17:49:14 -05001130 functions.emplace("nop", reinterpret_cast<void*>(F::nop));
1131 functions.emplace("floorf", reinterpret_cast<void*>(floorf));
1132 functions.emplace("nearbyintf", reinterpret_cast<void*>(nearbyintf));
1133 functions.emplace("truncf", reinterpret_cast<void*>(truncf));
1134 functions.emplace("printf", reinterpret_cast<void*>(printf));
1135 functions.emplace("puts", reinterpret_cast<void*>(puts));
1136 functions.emplace("fmodf", reinterpret_cast<void*>(fmodf));
Chris Forbes9283b252019-06-17 09:44:28 -07001137
Nicolas Capens157ba262019-12-10 17:49:14 -05001138 functions.emplace("sinf", reinterpret_cast<void*>(sinf));
1139 functions.emplace("cosf", reinterpret_cast<void*>(cosf));
1140 functions.emplace("asinf", reinterpret_cast<void*>(asinf));
1141 functions.emplace("acosf", reinterpret_cast<void*>(acosf));
1142 functions.emplace("atanf", reinterpret_cast<void*>(atanf));
1143 functions.emplace("sinhf", reinterpret_cast<void*>(sinhf));
1144 functions.emplace("coshf", reinterpret_cast<void*>(coshf));
1145 functions.emplace("tanhf", reinterpret_cast<void*>(tanhf));
1146 functions.emplace("asinhf", reinterpret_cast<void*>(asinhf));
1147 functions.emplace("acoshf", reinterpret_cast<void*>(acoshf));
1148 functions.emplace("atanhf", reinterpret_cast<void*>(atanhf));
1149 functions.emplace("atan2f", reinterpret_cast<void*>(atan2f));
1150 functions.emplace("powf", reinterpret_cast<void*>(powf));
1151 functions.emplace("expf", reinterpret_cast<void*>(expf));
1152 functions.emplace("logf", reinterpret_cast<void*>(logf));
1153 functions.emplace("exp2f", reinterpret_cast<void*>(exp2f));
1154 functions.emplace("log2f", reinterpret_cast<void*>(log2f));
Ben Clayton6f8e5652019-06-29 01:58:02 +01001155
Nicolas Capens157ba262019-12-10 17:49:14 -05001156 functions.emplace("sin", reinterpret_cast<void*>(static_cast<double(*)(double)>(sin)));
1157 functions.emplace("cos", reinterpret_cast<void*>(static_cast<double(*)(double)>(cos)));
1158 functions.emplace("asin", reinterpret_cast<void*>(static_cast<double(*)(double)>(asin)));
1159 functions.emplace("acos", reinterpret_cast<void*>(static_cast<double(*)(double)>(acos)));
1160 functions.emplace("atan", reinterpret_cast<void*>(static_cast<double(*)(double)>(atan)));
1161 functions.emplace("sinh", reinterpret_cast<void*>(static_cast<double(*)(double)>(sinh)));
1162 functions.emplace("cosh", reinterpret_cast<void*>(static_cast<double(*)(double)>(cosh)));
1163 functions.emplace("tanh", reinterpret_cast<void*>(static_cast<double(*)(double)>(tanh)));
1164 functions.emplace("asinh", reinterpret_cast<void*>(static_cast<double(*)(double)>(asinh)));
1165 functions.emplace("acosh", reinterpret_cast<void*>(static_cast<double(*)(double)>(acosh)));
1166 functions.emplace("atanh", reinterpret_cast<void*>(static_cast<double(*)(double)>(atanh)));
1167 functions.emplace("atan2", reinterpret_cast<void*>(static_cast<double(*)(double,double)>(atan2)));
1168 functions.emplace("pow", reinterpret_cast<void*>(static_cast<double(*)(double,double)>(pow)));
1169 functions.emplace("exp", reinterpret_cast<void*>(static_cast<double(*)(double)>(exp)));
1170 functions.emplace("log", reinterpret_cast<void*>(static_cast<double(*)(double)>(log)));
1171 functions.emplace("exp2", reinterpret_cast<void*>(static_cast<double(*)(double)>(exp2)));
1172 functions.emplace("log2", reinterpret_cast<void*>(static_cast<double(*)(double)>(log2)));
Ben Clayton40a885e2019-06-23 19:12:48 +01001173
Nicolas Capens157ba262019-12-10 17:49:14 -05001174 functions.emplace("atomic_load", reinterpret_cast<void*>(Atomic::load));
1175 functions.emplace("atomic_store", reinterpret_cast<void*>(Atomic::store));
Chris Forbesfd4c96d2019-06-20 11:20:42 -07001176
Nicolas Capens157ba262019-12-10 17:49:14 -05001177 // FIXME (b/119409619): use an allocator here so we can control all memory allocations
1178 functions.emplace("coroutine_alloc_frame", reinterpret_cast<void*>(F::coroutine_alloc_frame));
1179 functions.emplace("coroutine_free_frame", reinterpret_cast<void*>(F::coroutine_free_frame));
Ben Clayton1c82c7b2019-04-30 12:49:27 +01001180
Ben Clayton14740062019-04-09 13:48:41 -04001181#ifdef __APPLE__
Nicolas Capens157ba262019-12-10 17:49:14 -05001182 functions.emplace("sincosf_stret", reinterpret_cast<void*>(__sincosf_stret));
Ben Clayton14740062019-04-09 13:48:41 -04001183#elif defined(__linux__)
Nicolas Capens157ba262019-12-10 17:49:14 -05001184 functions.emplace("sincosf", reinterpret_cast<void*>(sincosf));
Ben Clayton2f58df32019-06-23 21:29:25 +01001185#elif defined(_WIN64)
Nicolas Capens157ba262019-12-10 17:49:14 -05001186 functions.emplace("chkstk", reinterpret_cast<void*>(__chkstk));
Ben Clayton2f58df32019-06-23 21:29:25 +01001187#elif defined(_WIN32)
Nicolas Capens157ba262019-12-10 17:49:14 -05001188 functions.emplace("chkstk", reinterpret_cast<void*>(_chkstk));
Ben Clayton2f58df32019-06-23 21:29:25 +01001189#endif
Chris Forbes9283b252019-06-17 09:44:28 -07001190
1191#ifdef __ANDROID__
Nicolas Capens157ba262019-12-10 17:49:14 -05001192 functions.emplace("aeabi_unwind_cpp_pr0", reinterpret_cast<void*>(F::neverCalled));
1193 functions.emplace("sync_synchronize", reinterpret_cast<void*>(F::sync_synchronize));
1194 functions.emplace("sync_fetch_and_add_4", reinterpret_cast<void*>(F::sync_fetch_and_add_4));
1195 functions.emplace("sync_fetch_and_and_4", reinterpret_cast<void*>(F::sync_fetch_and_and_4));
1196 functions.emplace("sync_fetch_and_or_4", reinterpret_cast<void*>(F::sync_fetch_and_or_4));
1197 functions.emplace("sync_fetch_and_xor_4", reinterpret_cast<void*>(F::sync_fetch_and_xor_4));
1198 functions.emplace("sync_fetch_and_sub_4", reinterpret_cast<void*>(F::sync_fetch_and_sub_4));
1199 functions.emplace("sync_lock_test_and_set_4", reinterpret_cast<void*>(F::sync_lock_test_and_set_4));
1200 functions.emplace("sync_val_compare_and_swap_4", reinterpret_cast<void*>(F::sync_val_compare_and_swap_4));
1201 functions.emplace("sync_fetch_and_max_4", reinterpret_cast<void*>(F::sync_fetch_and_max_4));
1202 functions.emplace("sync_fetch_and_min_4", reinterpret_cast<void*>(F::sync_fetch_and_min_4));
1203 functions.emplace("sync_fetch_and_umax_4", reinterpret_cast<void*>(F::sync_fetch_and_umax_4));
1204 functions.emplace("sync_fetch_and_umin_4", reinterpret_cast<void*>(F::sync_fetch_and_umin_4));
1205#endif
1206 }
Nicolas Capensfbf2bc52017-07-26 17:26:17 -04001207 };
1208
Nicolas Capens157ba262019-12-10 17:49:14 -05001209 static Resolver resolver;
Nicolas Capens1a5c3b92019-03-08 17:26:43 -05001210
Nicolas Capens157ba262019-12-10 17:49:14 -05001211 // Trim off any underscores from the start of the symbol. LLVM likes
1212 // to append these on macOS.
1213 const char* trimmed = name;
Nicolas Capens81bc9d92019-12-16 15:05:57 -05001214 while(trimmed[0] == '_') { trimmed++; }
Nicolas Capens157ba262019-12-10 17:49:14 -05001215
1216 auto it = resolver.functions.find(trimmed);
1217 // Missing functions will likely make the module fail in exciting non-obvious ways.
1218 ASSERT_MSG(it != resolver.functions.end(), "Missing external function: '%s'", name);
1219 return it->second;
1220}
1221
1222// The abstract Type* types are implemented as LLVM types, except that
1223// 64-bit vectors are emulated using 128-bit ones to avoid use of MMX in x86
1224// and VFP in ARM, and eliminate the overhead of converting them to explicit
1225// 128-bit ones. LLVM types are pointers, so we can represent emulated types
1226// as abstract pointers with small enum values.
1227enum InternalType : uintptr_t
1228{
1229 // Emulated types:
1230 Type_v2i32,
1231 Type_v4i16,
1232 Type_v2i16,
1233 Type_v8i8,
1234 Type_v4i8,
1235 Type_v2f32,
1236 EmulatedTypeCount,
1237 // Returned by asInternalType() to indicate that the abstract Type*
1238 // should be interpreted as LLVM type pointer:
1239 Type_LLVM
1240};
1241
1242inline InternalType asInternalType(Type *type)
1243{
1244 InternalType t = static_cast<InternalType>(reinterpret_cast<uintptr_t>(type));
1245 return (t < EmulatedTypeCount) ? t : Type_LLVM;
1246}
1247
1248llvm::Type *T(Type *t)
1249{
1250 // Use 128-bit vectors to implement logically shorter ones.
1251 switch(asInternalType(t))
Nicolas Capensfbf2bc52017-07-26 17:26:17 -04001252 {
Nicolas Capens157ba262019-12-10 17:49:14 -05001253 case Type_v2i32: return T(Int4::getType());
1254 case Type_v4i16: return T(Short8::getType());
1255 case Type_v2i16: return T(Short8::getType());
1256 case Type_v8i8: return T(Byte16::getType());
1257 case Type_v4i8: return T(Byte16::getType());
1258 case Type_v2f32: return T(Float4::getType());
1259 case Type_LLVM: return reinterpret_cast<llvm::Type*>(t);
1260 default:
1261 UNREACHABLE("asInternalType(t): %d", int(asInternalType(t)));
1262 return nullptr;
1263 }
1264}
1265
1266Type *T(InternalType t)
1267{
1268 return reinterpret_cast<Type*>(t);
1269}
1270
1271inline std::vector<llvm::Type*> &T(std::vector<Type*> &t)
1272{
1273 return reinterpret_cast<std::vector<llvm::Type*>&>(t);
1274}
1275
1276inline llvm::BasicBlock *B(BasicBlock *t)
1277{
1278 return reinterpret_cast<llvm::BasicBlock*>(t);
1279}
1280
1281inline BasicBlock *B(llvm::BasicBlock *t)
1282{
1283 return reinterpret_cast<BasicBlock*>(t);
1284}
1285
1286static size_t typeSize(Type *type)
1287{
1288 switch(asInternalType(type))
1289 {
1290 case Type_v2i32: return 8;
1291 case Type_v4i16: return 8;
1292 case Type_v2i16: return 4;
1293 case Type_v8i8: return 8;
1294 case Type_v4i8: return 4;
1295 case Type_v2f32: return 8;
1296 case Type_LLVM:
Nicolas Capensfbf2bc52017-07-26 17:26:17 -04001297 {
Nicolas Capens157ba262019-12-10 17:49:14 -05001298 llvm::Type *t = T(type);
Nicolas Capensfbf2bc52017-07-26 17:26:17 -04001299
Nicolas Capens157ba262019-12-10 17:49:14 -05001300 if(t->isPointerTy())
Nicolas Capens01a97962017-07-28 17:30:51 -04001301 {
Nicolas Capens157ba262019-12-10 17:49:14 -05001302 return sizeof(void*);
Nicolas Capens1a5c3b92019-03-08 17:26:43 -05001303 }
Nicolas Capens157ba262019-12-10 17:49:14 -05001304
1305 // At this point we should only have LLVM 'primitive' types.
1306 unsigned int bits = t->getPrimitiveSizeInBits();
1307 ASSERT_MSG(bits != 0, "bits: %d", int(bits));
1308
1309 // TODO(capn): Booleans are 1 bit integers in LLVM's SSA type system,
1310 // but are typically stored as one byte. The DataLayout structure should
1311 // be used here and many other places if this assumption fails.
1312 return (bits + 7) / 8;
Nicolas Capens1a5c3b92019-03-08 17:26:43 -05001313 }
Nicolas Capens157ba262019-12-10 17:49:14 -05001314 break;
1315 default:
1316 UNREACHABLE("asInternalType(type): %d", int(asInternalType(type)));
1317 return 0;
Nicolas Capens01a97962017-07-28 17:30:51 -04001318 }
Nicolas Capens157ba262019-12-10 17:49:14 -05001319}
Nicolas Capens01a97962017-07-28 17:30:51 -04001320
Nicolas Capens157ba262019-12-10 17:49:14 -05001321static unsigned int elementCount(Type *type)
1322{
1323 switch(asInternalType(type))
Nicolas Capens69674fb2017-09-01 11:08:44 -04001324 {
Nicolas Capens157ba262019-12-10 17:49:14 -05001325 case Type_v2i32: return 2;
1326 case Type_v4i16: return 4;
1327 case Type_v2i16: return 2;
1328 case Type_v8i8: return 8;
1329 case Type_v4i8: return 4;
1330 case Type_v2f32: return 2;
1331 case Type_LLVM: return llvm::cast<llvm::VectorType>(T(type))->getNumElements();
1332 default:
1333 UNREACHABLE("asInternalType(type): %d", int(asInternalType(type)));
1334 return 0;
1335 }
1336}
1337
1338static ::llvm::Function* createFunction(const char *name, ::llvm::Type *retTy, const std::vector<::llvm::Type*> &params)
1339{
1340 llvm::FunctionType *functionType = llvm::FunctionType::get(retTy, params, false);
1341 auto func = llvm::Function::Create(functionType, llvm::GlobalValue::InternalLinkage, name, jit->module.get());
1342 func->setDoesNotThrow();
1343 func->setCallingConv(llvm::CallingConv::C);
1344 return func;
1345}
1346
1347Nucleus::Nucleus()
1348{
1349 ::codegenMutex.lock(); // Reactor and LLVM are currently not thread safe
1350
1351 ASSERT(jit == nullptr);
1352 jit.reset(new JITBuilder(Nucleus::getDefaultConfig()));
1353}
1354
1355Nucleus::~Nucleus()
1356{
1357 jit.reset();
1358 ::codegenMutex.unlock();
1359}
1360
1361void Nucleus::setDefaultConfig(const Config &cfg)
1362{
1363 std::unique_lock<std::mutex> lock(::defaultConfigLock);
1364 ::defaultConfig() = cfg;
1365}
1366
1367void Nucleus::adjustDefaultConfig(const Config::Edit &cfgEdit)
1368{
1369 std::unique_lock<std::mutex> lock(::defaultConfigLock);
1370 auto &config = ::defaultConfig();
1371 config = cfgEdit.apply(config);
1372}
1373
1374Config Nucleus::getDefaultConfig()
1375{
1376 std::unique_lock<std::mutex> lock(::defaultConfigLock);
1377 return ::defaultConfig();
1378}
1379
1380std::shared_ptr<Routine> Nucleus::acquireRoutine(const char *name, const Config::Edit &cfgEdit /* = Config::Edit::None */)
1381{
1382 auto cfg = cfgEdit.apply(jit->config);
1383
1384 if(jit->builder->GetInsertBlock()->empty() || !jit->builder->GetInsertBlock()->back().isTerminator())
1385 {
1386 llvm::Type *type = jit->function->getReturnType();
1387
1388 if(type->isVoidTy())
Nicolas Capens69674fb2017-09-01 11:08:44 -04001389 {
Nicolas Capens157ba262019-12-10 17:49:14 -05001390 createRetVoid();
John Bauman89401822014-05-06 15:04:28 -04001391 }
1392 else
1393 {
Nicolas Capens157ba262019-12-10 17:49:14 -05001394 createRet(V(llvm::UndefValue::get(type)));
John Bauman89401822014-05-06 15:04:28 -04001395 }
John Bauman89401822014-05-06 15:04:28 -04001396 }
1397
Ben Claytonac07ed82019-03-26 14:17:41 +00001398#ifdef ENABLE_RR_DEBUG_INFO
Nicolas Capens81bc9d92019-12-16 15:05:57 -05001399 if(jit->debugInfo != nullptr)
Nicolas Capens157ba262019-12-10 17:49:14 -05001400 {
1401 jit->debugInfo->Finalize();
1402 }
Ben Claytonac07ed82019-03-26 14:17:41 +00001403#endif // ENABLE_RR_DEBUG_INFO
1404
Nicolas Capens157ba262019-12-10 17:49:14 -05001405 if(false)
1406 {
1407 std::error_code error;
1408 llvm::raw_fd_ostream file(std::string(name) + "-llvm-dump-unopt.txt", error);
1409 jit->module->print(file, 0);
John Bauman89401822014-05-06 15:04:28 -04001410 }
1411
Nicolas Capens157ba262019-12-10 17:49:14 -05001412#if defined(ENABLE_RR_LLVM_IR_VERIFICATION) || !defined(NDEBUG)
John Bauman89401822014-05-06 15:04:28 -04001413 {
Nicolas Capens157ba262019-12-10 17:49:14 -05001414 llvm::legacy::PassManager pm;
1415 pm.add(llvm::createVerifierPass());
1416 pm.run(*jit->module);
1417 }
1418#endif // defined(ENABLE_RR_LLVM_IR_VERIFICATION) || !defined(NDEBUG)
John Bauman89401822014-05-06 15:04:28 -04001419
Nicolas Capens157ba262019-12-10 17:49:14 -05001420 jit->optimize(cfg);
John Bauman89401822014-05-06 15:04:28 -04001421
Nicolas Capens157ba262019-12-10 17:49:14 -05001422 if(false)
1423 {
1424 std::error_code error;
1425 llvm::raw_fd_ostream file(std::string(name) + "-llvm-dump-opt.txt", error);
1426 jit->module->print(file, 0);
John Bauman89401822014-05-06 15:04:28 -04001427 }
1428
Nicolas Capens157ba262019-12-10 17:49:14 -05001429 auto routine = jit->acquireRoutine(&jit->function, 1, cfg);
1430 jit.reset();
1431
1432 return routine;
1433}
1434
1435Value *Nucleus::allocateStackVariable(Type *type, int arraySize)
1436{
1437 // Need to allocate it in the entry block for mem2reg to work
1438 llvm::BasicBlock &entryBlock = jit->function->getEntryBlock();
1439
1440 llvm::Instruction *declaration;
1441
1442 if(arraySize)
John Bauman89401822014-05-06 15:04:28 -04001443 {
Nicolas Capens157ba262019-12-10 17:49:14 -05001444 declaration = new llvm::AllocaInst(T(type), 0, V(Nucleus::createConstantInt(arraySize)));
1445 }
1446 else
1447 {
1448 declaration = new llvm::AllocaInst(T(type), 0, (llvm::Value*)nullptr);
John Bauman89401822014-05-06 15:04:28 -04001449 }
1450
Nicolas Capens157ba262019-12-10 17:49:14 -05001451 entryBlock.getInstList().push_front(declaration);
1452
1453 return V(declaration);
1454}
1455
1456BasicBlock *Nucleus::createBasicBlock()
1457{
1458 return B(llvm::BasicBlock::Create(jit->context, "", jit->function));
1459}
1460
1461BasicBlock *Nucleus::getInsertBlock()
1462{
1463 return B(jit->builder->GetInsertBlock());
1464}
1465
1466void Nucleus::setInsertBlock(BasicBlock *basicBlock)
1467{
1468// assert(jit->builder->GetInsertBlock()->back().isTerminator());
1469
1470 Variable::materializeAll();
1471
1472 jit->builder->SetInsertPoint(B(basicBlock));
1473}
1474
1475void Nucleus::createFunction(Type *ReturnType, std::vector<Type*> &Params)
1476{
1477 jit->function = rr::createFunction("", T(ReturnType), T(Params));
1478
1479#ifdef ENABLE_RR_DEBUG_INFO
1480 jit->debugInfo = std::unique_ptr<DebugInfo>(new DebugInfo(jit->builder.get(), &jit->context, jit->module.get(), jit->function));
1481#endif // ENABLE_RR_DEBUG_INFO
1482
1483 jit->builder->SetInsertPoint(llvm::BasicBlock::Create(jit->context, "", jit->function));
1484}
1485
1486Value *Nucleus::getArgument(unsigned int index)
1487{
1488 llvm::Function::arg_iterator args = jit->function->arg_begin();
1489
1490 while(index)
John Bauman89401822014-05-06 15:04:28 -04001491 {
Nicolas Capens157ba262019-12-10 17:49:14 -05001492 args++;
1493 index--;
John Bauman89401822014-05-06 15:04:28 -04001494 }
1495
Nicolas Capens157ba262019-12-10 17:49:14 -05001496 return V(&*args);
1497}
1498
1499void Nucleus::createRetVoid()
1500{
1501 RR_DEBUG_INFO_UPDATE_LOC();
1502
1503 ASSERT_MSG(jit->function->getReturnType() == T(Void::getType()), "Return type mismatch");
1504
1505 // Code generated after this point is unreachable, so any variables
1506 // being read can safely return an undefined value. We have to avoid
1507 // materializing variables after the terminator ret instruction.
1508 Variable::killUnmaterialized();
1509
1510 jit->builder->CreateRetVoid();
1511}
1512
1513void Nucleus::createRet(Value *v)
1514{
1515 RR_DEBUG_INFO_UPDATE_LOC();
1516
1517 ASSERT_MSG(jit->function->getReturnType() == V(v)->getType(), "Return type mismatch");
1518
1519 // Code generated after this point is unreachable, so any variables
1520 // being read can safely return an undefined value. We have to avoid
1521 // materializing variables after the terminator ret instruction.
1522 Variable::killUnmaterialized();
1523
1524 jit->builder->CreateRet(V(v));
1525}
1526
1527void Nucleus::createBr(BasicBlock *dest)
1528{
1529 RR_DEBUG_INFO_UPDATE_LOC();
1530 Variable::materializeAll();
1531
1532 jit->builder->CreateBr(B(dest));
1533}
1534
1535void Nucleus::createCondBr(Value *cond, BasicBlock *ifTrue, BasicBlock *ifFalse)
1536{
1537 RR_DEBUG_INFO_UPDATE_LOC();
1538 Variable::materializeAll();
1539 jit->builder->CreateCondBr(V(cond), B(ifTrue), B(ifFalse));
1540}
1541
1542Value *Nucleus::createAdd(Value *lhs, Value *rhs)
1543{
1544 RR_DEBUG_INFO_UPDATE_LOC();
1545 return V(jit->builder->CreateAdd(V(lhs), V(rhs)));
1546}
1547
1548Value *Nucleus::createSub(Value *lhs, Value *rhs)
1549{
1550 RR_DEBUG_INFO_UPDATE_LOC();
1551 return V(jit->builder->CreateSub(V(lhs), V(rhs)));
1552}
1553
1554Value *Nucleus::createMul(Value *lhs, Value *rhs)
1555{
1556 RR_DEBUG_INFO_UPDATE_LOC();
1557 return V(jit->builder->CreateMul(V(lhs), V(rhs)));
1558}
1559
1560Value *Nucleus::createUDiv(Value *lhs, Value *rhs)
1561{
1562 RR_DEBUG_INFO_UPDATE_LOC();
1563 return V(jit->builder->CreateUDiv(V(lhs), V(rhs)));
1564}
1565
1566Value *Nucleus::createSDiv(Value *lhs, Value *rhs)
1567{
1568 RR_DEBUG_INFO_UPDATE_LOC();
1569 return V(jit->builder->CreateSDiv(V(lhs), V(rhs)));
1570}
1571
1572Value *Nucleus::createFAdd(Value *lhs, Value *rhs)
1573{
1574 RR_DEBUG_INFO_UPDATE_LOC();
1575 return V(jit->builder->CreateFAdd(V(lhs), V(rhs)));
1576}
1577
1578Value *Nucleus::createFSub(Value *lhs, Value *rhs)
1579{
1580 RR_DEBUG_INFO_UPDATE_LOC();
1581 return V(jit->builder->CreateFSub(V(lhs), V(rhs)));
1582}
1583
1584Value *Nucleus::createFMul(Value *lhs, Value *rhs)
1585{
1586 RR_DEBUG_INFO_UPDATE_LOC();
1587 return V(jit->builder->CreateFMul(V(lhs), V(rhs)));
1588}
1589
1590Value *Nucleus::createFDiv(Value *lhs, Value *rhs)
1591{
1592 RR_DEBUG_INFO_UPDATE_LOC();
1593 return V(jit->builder->CreateFDiv(V(lhs), V(rhs)));
1594}
1595
1596Value *Nucleus::createURem(Value *lhs, Value *rhs)
1597{
1598 RR_DEBUG_INFO_UPDATE_LOC();
1599 return V(jit->builder->CreateURem(V(lhs), V(rhs)));
1600}
1601
1602Value *Nucleus::createSRem(Value *lhs, Value *rhs)
1603{
1604 RR_DEBUG_INFO_UPDATE_LOC();
1605 return V(jit->builder->CreateSRem(V(lhs), V(rhs)));
1606}
1607
1608Value *Nucleus::createFRem(Value *lhs, Value *rhs)
1609{
1610 RR_DEBUG_INFO_UPDATE_LOC();
1611 return V(jit->builder->CreateFRem(V(lhs), V(rhs)));
1612}
1613
1614Value *Nucleus::createShl(Value *lhs, Value *rhs)
1615{
1616 RR_DEBUG_INFO_UPDATE_LOC();
1617 return V(jit->builder->CreateShl(V(lhs), V(rhs)));
1618}
1619
1620Value *Nucleus::createLShr(Value *lhs, Value *rhs)
1621{
1622 RR_DEBUG_INFO_UPDATE_LOC();
1623 return V(jit->builder->CreateLShr(V(lhs), V(rhs)));
1624}
1625
1626Value *Nucleus::createAShr(Value *lhs, Value *rhs)
1627{
1628 RR_DEBUG_INFO_UPDATE_LOC();
1629 return V(jit->builder->CreateAShr(V(lhs), V(rhs)));
1630}
1631
1632Value *Nucleus::createAnd(Value *lhs, Value *rhs)
1633{
1634 RR_DEBUG_INFO_UPDATE_LOC();
1635 return V(jit->builder->CreateAnd(V(lhs), V(rhs)));
1636}
1637
1638Value *Nucleus::createOr(Value *lhs, Value *rhs)
1639{
1640 RR_DEBUG_INFO_UPDATE_LOC();
1641 return V(jit->builder->CreateOr(V(lhs), V(rhs)));
1642}
1643
1644Value *Nucleus::createXor(Value *lhs, Value *rhs)
1645{
1646 RR_DEBUG_INFO_UPDATE_LOC();
1647 return V(jit->builder->CreateXor(V(lhs), V(rhs)));
1648}
1649
1650Value *Nucleus::createNeg(Value *v)
1651{
1652 RR_DEBUG_INFO_UPDATE_LOC();
1653 return V(jit->builder->CreateNeg(V(v)));
1654}
1655
1656Value *Nucleus::createFNeg(Value *v)
1657{
1658 RR_DEBUG_INFO_UPDATE_LOC();
1659 return V(jit->builder->CreateFNeg(V(v)));
1660}
1661
1662Value *Nucleus::createNot(Value *v)
1663{
1664 RR_DEBUG_INFO_UPDATE_LOC();
1665 return V(jit->builder->CreateNot(V(v)));
1666}
1667
1668Value *Nucleus::createLoad(Value *ptr, Type *type, bool isVolatile, unsigned int alignment, bool atomic, std::memory_order memoryOrder)
1669{
1670 RR_DEBUG_INFO_UPDATE_LOC();
1671 switch(asInternalType(type))
John Bauman89401822014-05-06 15:04:28 -04001672 {
Nicolas Capens157ba262019-12-10 17:49:14 -05001673 case Type_v2i32:
1674 case Type_v4i16:
1675 case Type_v8i8:
1676 case Type_v2f32:
Logan Chien191b3052018-08-31 16:57:15 +08001677 return createBitCast(
Nicolas Capens157ba262019-12-10 17:49:14 -05001678 createInsertElement(
1679 V(llvm::UndefValue::get(llvm::VectorType::get(T(Long::getType()), 2))),
1680 createLoad(createBitCast(ptr, Pointer<Long>::getType()), Long::getType(), isVolatile, alignment, atomic, memoryOrder),
1681 0),
1682 type);
1683 case Type_v2i16:
1684 case Type_v4i8:
1685 if(alignment != 0) // Not a local variable (all vectors are 128-bit).
Nicolas Capens01a97962017-07-28 17:30:51 -04001686 {
Nicolas Capens157ba262019-12-10 17:49:14 -05001687 Value *u = V(llvm::UndefValue::get(llvm::VectorType::get(T(Long::getType()), 2)));
1688 Value *i = createLoad(createBitCast(ptr, Pointer<Int>::getType()), Int::getType(), isVolatile, alignment, atomic, memoryOrder);
1689 i = createZExt(i, Long::getType());
1690 Value *v = createInsertElement(u, i, 0);
1691 return createBitCast(v, type);
Nicolas Capens01a97962017-07-28 17:30:51 -04001692 }
Nicolas Capens157ba262019-12-10 17:49:14 -05001693 // Fallthrough to non-emulated case.
1694 case Type_LLVM:
Nicolas Capens01a97962017-07-28 17:30:51 -04001695 {
Nicolas Capens157ba262019-12-10 17:49:14 -05001696 auto elTy = T(type);
1697 ASSERT(V(ptr)->getType()->getContainedType(0) == elTy);
1698
Nicolas Capens81bc9d92019-12-16 15:05:57 -05001699 if(!atomic)
Nicolas Capens157ba262019-12-10 17:49:14 -05001700 {
1701 return V(jit->builder->CreateAlignedLoad(V(ptr), alignment, isVolatile));
1702 }
Nicolas Capens81bc9d92019-12-16 15:05:57 -05001703 else if(elTy->isIntegerTy() || elTy->isPointerTy())
Nicolas Capens157ba262019-12-10 17:49:14 -05001704 {
1705 // Integers and pointers can be atomically loaded by setting
1706 // the ordering constraint on the load instruction.
1707 auto load = jit->builder->CreateAlignedLoad(V(ptr), alignment, isVolatile);
1708 load->setAtomic(atomicOrdering(atomic, memoryOrder));
1709 return V(load);
1710 }
Nicolas Capens81bc9d92019-12-16 15:05:57 -05001711 else if(elTy->isFloatTy() || elTy->isDoubleTy())
Nicolas Capens157ba262019-12-10 17:49:14 -05001712 {
1713 // LLVM claims to support atomic loads of float types as
1714 // above, but certain backends cannot deal with this.
1715 // Load as an integer and bitcast. See b/136037244.
1716 auto size = jit->module->getDataLayout().getTypeStoreSize(elTy);
1717 auto elAsIntTy = ::llvm::IntegerType::get(jit->context, size * 8);
1718 auto ptrCast = jit->builder->CreatePointerCast(V(ptr), elAsIntTy->getPointerTo());
1719 auto load = jit->builder->CreateAlignedLoad(ptrCast, alignment, isVolatile);
1720 load->setAtomic(atomicOrdering(atomic, memoryOrder));
1721 auto loadCast = jit->builder->CreateBitCast(load, elTy);
1722 return V(loadCast);
1723 }
1724 else
1725 {
1726 // More exotic types require falling back to the extern:
1727 // void __atomic_load(size_t size, void *ptr, void *ret, int ordering)
1728 auto sizetTy = ::llvm::IntegerType::get(jit->context, sizeof(size_t) * 8);
1729 auto intTy = ::llvm::IntegerType::get(jit->context, sizeof(int) * 8);
1730 auto i8Ty = ::llvm::Type::getInt8Ty(jit->context);
1731 auto i8PtrTy = i8Ty->getPointerTo();
1732 auto voidTy = ::llvm::Type::getVoidTy(jit->context);
1733 auto funcTy = ::llvm::FunctionType::get(voidTy, {sizetTy, i8PtrTy, i8PtrTy, intTy}, false);
1734 auto func = jit->module->getOrInsertFunction("__atomic_load", funcTy);
1735 auto size = jit->module->getDataLayout().getTypeStoreSize(elTy);
1736 auto out = allocateStackVariable(type);
1737 jit->builder->CreateCall(func, {
1738 ::llvm::ConstantInt::get(sizetTy, size),
1739 jit->builder->CreatePointerCast(V(ptr), i8PtrTy),
1740 jit->builder->CreatePointerCast(V(out), i8PtrTy),
1741 ::llvm::ConstantInt::get(intTy, uint64_t(atomicOrdering(true, memoryOrder))),
1742 });
1743 return V(jit->builder->CreateLoad(V(out)));
1744 }
Nicolas Capens01a97962017-07-28 17:30:51 -04001745 }
Nicolas Capens157ba262019-12-10 17:49:14 -05001746 default:
1747 UNREACHABLE("asInternalType(type): %d", int(asInternalType(type)));
1748 return nullptr;
John Bauman89401822014-05-06 15:04:28 -04001749 }
Nicolas Capens157ba262019-12-10 17:49:14 -05001750}
John Bauman89401822014-05-06 15:04:28 -04001751
Nicolas Capens157ba262019-12-10 17:49:14 -05001752Value *Nucleus::createStore(Value *value, Value *ptr, Type *type, bool isVolatile, unsigned int alignment, bool atomic, std::memory_order memoryOrder)
1753{
1754 RR_DEBUG_INFO_UPDATE_LOC();
1755 switch(asInternalType(type))
Ben Clayton204a4102019-07-31 13:17:47 +01001756 {
Nicolas Capens157ba262019-12-10 17:49:14 -05001757 case Type_v2i32:
1758 case Type_v4i16:
1759 case Type_v8i8:
1760 case Type_v2f32:
1761 createStore(
1762 createExtractElement(
1763 createBitCast(value, T(llvm::VectorType::get(T(Long::getType()), 2))), Long::getType(), 0),
1764 createBitCast(ptr, Pointer<Long>::getType()),
1765 Long::getType(), isVolatile, alignment, atomic, memoryOrder);
1766 return value;
1767 case Type_v2i16:
1768 case Type_v4i8:
1769 if(alignment != 0) // Not a local variable (all vectors are 128-bit).
Nicolas Capense89cd582016-09-30 14:23:47 -04001770 {
Nicolas Capens157ba262019-12-10 17:49:14 -05001771 createStore(
1772 createExtractElement(createBitCast(value, Int4::getType()), Int::getType(), 0),
1773 createBitCast(ptr, Pointer<Int>::getType()),
1774 Int::getType(), isVolatile, alignment, atomic, memoryOrder);
1775 return value;
Nicolas Capense89cd582016-09-30 14:23:47 -04001776 }
Nicolas Capens157ba262019-12-10 17:49:14 -05001777 // Fallthrough to non-emulated case.
1778 case Type_LLVM:
Nicolas Capens13ac2322016-10-13 14:52:12 -04001779 {
Nicolas Capens157ba262019-12-10 17:49:14 -05001780 auto elTy = T(type);
1781 ASSERT(V(ptr)->getType()->getContainedType(0) == elTy);
1782
Nicolas Capens81bc9d92019-12-16 15:05:57 -05001783 if(!atomic)
Nicolas Capens157ba262019-12-10 17:49:14 -05001784 {
1785 jit->builder->CreateAlignedStore(V(value), V(ptr), alignment, isVolatile);
1786 }
Nicolas Capens81bc9d92019-12-16 15:05:57 -05001787 else if(elTy->isIntegerTy() || elTy->isPointerTy())
Nicolas Capens157ba262019-12-10 17:49:14 -05001788 {
1789 // Integers and pointers can be atomically stored by setting
1790 // the ordering constraint on the store instruction.
1791 auto store = jit->builder->CreateAlignedStore(V(value), V(ptr), alignment, isVolatile);
1792 store->setAtomic(atomicOrdering(atomic, memoryOrder));
1793 }
Nicolas Capens81bc9d92019-12-16 15:05:57 -05001794 else if(elTy->isFloatTy() || elTy->isDoubleTy())
Nicolas Capens157ba262019-12-10 17:49:14 -05001795 {
1796 // LLVM claims to support atomic stores of float types as
1797 // above, but certain backends cannot deal with this.
1798 // Store as an bitcast integer. See b/136037244.
1799 auto size = jit->module->getDataLayout().getTypeStoreSize(elTy);
1800 auto elAsIntTy = ::llvm::IntegerType::get(jit->context, size * 8);
1801 auto valCast = jit->builder->CreateBitCast(V(value), elAsIntTy);
1802 auto ptrCast = jit->builder->CreatePointerCast(V(ptr), elAsIntTy->getPointerTo());
1803 auto store = jit->builder->CreateAlignedStore(valCast, ptrCast, alignment, isVolatile);
1804 store->setAtomic(atomicOrdering(atomic, memoryOrder));
1805 }
1806 else
1807 {
1808 // More exotic types require falling back to the extern:
1809 // void __atomic_store(size_t size, void *ptr, void *val, int ordering)
1810 auto sizetTy = ::llvm::IntegerType::get(jit->context, sizeof(size_t) * 8);
1811 auto intTy = ::llvm::IntegerType::get(jit->context, sizeof(int) * 8);
1812 auto i8Ty = ::llvm::Type::getInt8Ty(jit->context);
1813 auto i8PtrTy = i8Ty->getPointerTo();
1814 auto voidTy = ::llvm::Type::getVoidTy(jit->context);
1815 auto funcTy = ::llvm::FunctionType::get(voidTy, {sizetTy, i8PtrTy, i8PtrTy, intTy}, false);
1816 auto func = jit->module->getOrInsertFunction("__atomic_store", funcTy);
1817 auto size = jit->module->getDataLayout().getTypeStoreSize(elTy);
1818 auto copy = allocateStackVariable(type);
1819 jit->builder->CreateStore(V(value), V(copy));
1820 jit->builder->CreateCall(func, {
1821 ::llvm::ConstantInt::get(sizetTy, size),
1822 jit->builder->CreatePointerCast(V(ptr), i8PtrTy),
1823 jit->builder->CreatePointerCast(V(copy), i8PtrTy),
1824 ::llvm::ConstantInt::get(intTy, uint64_t(atomicOrdering(true, memoryOrder))),
1825 });
1826 }
1827
1828 return value;
Nicolas Capens13ac2322016-10-13 14:52:12 -04001829 }
Nicolas Capens157ba262019-12-10 17:49:14 -05001830 default:
1831 UNREACHABLE("asInternalType(type): %d", int(asInternalType(type)));
1832 return nullptr;
1833 }
1834}
Nicolas Capens13ac2322016-10-13 14:52:12 -04001835
Nicolas Capens157ba262019-12-10 17:49:14 -05001836Value *Nucleus::createMaskedLoad(Value *ptr, Type *elTy, Value *mask, unsigned int alignment, bool zeroMaskedLanes)
1837{
1838 ASSERT(V(ptr)->getType()->isPointerTy());
1839 ASSERT(V(mask)->getType()->isVectorTy());
1840
1841 auto numEls = V(mask)->getType()->getVectorNumElements();
1842 auto i1Ty = ::llvm::Type::getInt1Ty(jit->context);
1843 auto i32Ty = ::llvm::Type::getInt32Ty(jit->context);
1844 auto elVecTy = ::llvm::VectorType::get(T(elTy), numEls);
1845 auto elVecPtrTy = elVecTy->getPointerTo();
1846 auto i8Mask = jit->builder->CreateIntCast(V(mask), ::llvm::VectorType::get(i1Ty, numEls), false); // vec<int, int, ...> -> vec<bool, bool, ...>
1847 auto passthrough = zeroMaskedLanes ? ::llvm::Constant::getNullValue(elVecTy) : llvm::UndefValue::get(elVecTy);
1848 auto align = ::llvm::ConstantInt::get(i32Ty, alignment);
1849 auto func = ::llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::masked_load, { elVecTy, elVecPtrTy } );
1850 return V(jit->builder->CreateCall(func, { V(ptr), align, i8Mask, passthrough }));
1851}
1852
1853void Nucleus::createMaskedStore(Value *ptr, Value *val, Value *mask, unsigned int alignment)
1854{
1855 ASSERT(V(ptr)->getType()->isPointerTy());
1856 ASSERT(V(val)->getType()->isVectorTy());
1857 ASSERT(V(mask)->getType()->isVectorTy());
1858
1859 auto numEls = V(mask)->getType()->getVectorNumElements();
1860 auto i1Ty = ::llvm::Type::getInt1Ty(jit->context);
1861 auto i32Ty = ::llvm::Type::getInt32Ty(jit->context);
1862 auto elVecTy = V(val)->getType();
1863 auto elVecPtrTy = elVecTy->getPointerTo();
1864 auto i8Mask = jit->builder->CreateIntCast(V(mask), ::llvm::VectorType::get(i1Ty, numEls), false); // vec<int, int, ...> -> vec<bool, bool, ...>
1865 auto align = ::llvm::ConstantInt::get(i32Ty, alignment);
1866 auto func = ::llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::masked_store, { elVecTy, elVecPtrTy } );
1867 jit->builder->CreateCall(func, { V(val), V(ptr), align, i8Mask });
1868}
1869
1870RValue<Float4> Gather(RValue<Pointer<Float>> base, RValue<Int4> offsets, RValue<Int4> mask, unsigned int alignment, bool zeroMaskedLanes /* = false */)
1871{
1872 return As<Float4>(V(createGather(V(base.value), T(Float::getType()), V(offsets.value), V(mask.value), alignment, zeroMaskedLanes)));
1873}
1874
1875RValue<Int4> Gather(RValue<Pointer<Int>> base, RValue<Int4> offsets, RValue<Int4> mask, unsigned int alignment, bool zeroMaskedLanes /* = false */)
1876{
1877 return As<Int4>(V(createGather(V(base.value), T(Float::getType()), V(offsets.value), V(mask.value), alignment, zeroMaskedLanes)));
1878}
1879
1880void Scatter(RValue<Pointer<Float>> base, RValue<Float4> val, RValue<Int4> offsets, RValue<Int4> mask, unsigned int alignment)
1881{
1882 return createScatter(V(base.value), V(val.value), V(offsets.value), V(mask.value), alignment);
1883}
1884
1885void Scatter(RValue<Pointer<Int>> base, RValue<Int4> val, RValue<Int4> offsets, RValue<Int4> mask, unsigned int alignment)
1886{
1887 return createScatter(V(base.value), V(val.value), V(offsets.value), V(mask.value), alignment);
1888}
1889
1890void Nucleus::createFence(std::memory_order memoryOrder)
1891{
1892 jit->builder->CreateFence(atomicOrdering(true, memoryOrder));
1893}
1894
1895Value *Nucleus::createGEP(Value *ptr, Type *type, Value *index, bool unsignedIndex)
1896{
1897 RR_DEBUG_INFO_UPDATE_LOC();
1898 ASSERT(V(ptr)->getType()->getContainedType(0) == T(type));
1899 if(sizeof(void*) == 8)
1900 {
1901 // LLVM manual: "When indexing into an array, pointer or vector,
1902 // integers of any width are allowed, and they are not required to
1903 // be constant. These integers are treated as signed values where
1904 // relevant."
1905 //
1906 // Thus if we want indexes to be treated as unsigned we have to
1907 // zero-extend them ourselves.
1908 //
1909 // Note that this is not because we want to address anywhere near
1910 // 4 GB of data. Instead this is important for performance because
1911 // x86 supports automatic zero-extending of 32-bit registers to
1912 // 64-bit. Thus when indexing into an array using a uint32 is
1913 // actually faster than an int32.
1914 index = unsignedIndex ?
1915 createZExt(index, Long::getType()) :
1916 createSExt(index, Long::getType());
Nicolas Capens13ac2322016-10-13 14:52:12 -04001917 }
1918
Nicolas Capens157ba262019-12-10 17:49:14 -05001919 // For non-emulated types we can rely on LLVM's GEP to calculate the
1920 // effective address correctly.
1921 if(asInternalType(type) == Type_LLVM)
Nicolas Capens13ac2322016-10-13 14:52:12 -04001922 {
Nicolas Capens157ba262019-12-10 17:49:14 -05001923 return V(jit->builder->CreateGEP(V(ptr), V(index)));
John Bauman89401822014-05-06 15:04:28 -04001924 }
1925
Nicolas Capens157ba262019-12-10 17:49:14 -05001926 // For emulated types we have to multiply the index by the intended
1927 // type size ourselves to obain the byte offset.
1928 index = (sizeof(void*) == 8) ?
1929 createMul(index, createConstantLong((int64_t)typeSize(type))) :
1930 createMul(index, createConstantInt((int)typeSize(type)));
1931
1932 // Cast to a byte pointer, apply the byte offset, and cast back to the
1933 // original pointer type.
1934 return createBitCast(
1935 V(jit->builder->CreateGEP(V(createBitCast(ptr, T(llvm::PointerType::get(T(Byte::getType()), 0)))), V(index))),
1936 T(llvm::PointerType::get(T(type), 0)));
1937}
1938
1939Value *Nucleus::createAtomicAdd(Value *ptr, Value *value, std::memory_order memoryOrder)
1940{
1941 RR_DEBUG_INFO_UPDATE_LOC();
1942 return V(jit->builder->CreateAtomicRMW(llvm::AtomicRMWInst::Add, V(ptr), V(value), atomicOrdering(true, memoryOrder)));
1943}
1944
1945Value *Nucleus::createAtomicSub(Value *ptr, Value *value, std::memory_order memoryOrder)
1946{
1947 RR_DEBUG_INFO_UPDATE_LOC();
1948 return V(jit->builder->CreateAtomicRMW(llvm::AtomicRMWInst::Sub, V(ptr), V(value), atomicOrdering(true, memoryOrder)));
1949}
1950
1951Value *Nucleus::createAtomicAnd(Value *ptr, Value *value, std::memory_order memoryOrder)
1952{
1953 RR_DEBUG_INFO_UPDATE_LOC();
1954 return V(jit->builder->CreateAtomicRMW(llvm::AtomicRMWInst::And, V(ptr), V(value), atomicOrdering(true, memoryOrder)));
1955}
1956
1957Value *Nucleus::createAtomicOr(Value *ptr, Value *value, std::memory_order memoryOrder)
1958{
1959 RR_DEBUG_INFO_UPDATE_LOC();
1960 return V(jit->builder->CreateAtomicRMW(llvm::AtomicRMWInst::Or, V(ptr), V(value), atomicOrdering(true, memoryOrder)));
1961}
1962
1963Value *Nucleus::createAtomicXor(Value *ptr, Value *value, std::memory_order memoryOrder)
1964{
1965 RR_DEBUG_INFO_UPDATE_LOC();
1966 return V(jit->builder->CreateAtomicRMW(llvm::AtomicRMWInst::Xor, V(ptr), V(value), atomicOrdering(true, memoryOrder)));
1967}
1968
1969Value *Nucleus::createAtomicMin(Value *ptr, Value *value, std::memory_order memoryOrder)
1970{
1971 RR_DEBUG_INFO_UPDATE_LOC();
1972 return V(jit->builder->CreateAtomicRMW(llvm::AtomicRMWInst::Min, V(ptr), V(value), atomicOrdering(true, memoryOrder)));
1973}
1974
1975Value *Nucleus::createAtomicMax(Value *ptr, Value *value, std::memory_order memoryOrder)
1976{
1977 RR_DEBUG_INFO_UPDATE_LOC();
1978 return V(jit->builder->CreateAtomicRMW(llvm::AtomicRMWInst::Max, V(ptr), V(value), atomicOrdering(true, memoryOrder)));
1979}
1980
1981Value *Nucleus::createAtomicUMin(Value *ptr, Value *value, std::memory_order memoryOrder)
1982{
1983 RR_DEBUG_INFO_UPDATE_LOC();
1984 return V(jit->builder->CreateAtomicRMW(llvm::AtomicRMWInst::UMin, V(ptr), V(value), atomicOrdering(true, memoryOrder)));
1985}
1986
1987Value *Nucleus::createAtomicUMax(Value *ptr, Value *value, std::memory_order memoryOrder)
1988{
1989 RR_DEBUG_INFO_UPDATE_LOC();
1990 return V(jit->builder->CreateAtomicRMW(llvm::AtomicRMWInst::UMax, V(ptr), V(value), atomicOrdering(true, memoryOrder)));
1991}
1992
1993
1994Value *Nucleus::createAtomicExchange(Value *ptr, Value *value, std::memory_order memoryOrder)
1995{
1996 RR_DEBUG_INFO_UPDATE_LOC();
1997 return V(jit->builder->CreateAtomicRMW(llvm::AtomicRMWInst::Xchg, V(ptr), V(value), atomicOrdering(true, memoryOrder)));
1998}
1999
2000Value *Nucleus::createAtomicCompareExchange(Value *ptr, Value *value, Value *compare, std::memory_order memoryOrderEqual, std::memory_order memoryOrderUnequal)
2001{
2002 RR_DEBUG_INFO_UPDATE_LOC();
2003 // Note: AtomicCmpXchgInstruction returns a 2-member struct containing {result, success-flag}, not the result directly.
2004 return V(jit->builder->CreateExtractValue(
2005 jit->builder->CreateAtomicCmpXchg(V(ptr), V(compare), V(value), atomicOrdering(true, memoryOrderEqual), atomicOrdering(true, memoryOrderUnequal)),
2006 llvm::ArrayRef<unsigned>(0u)));
2007}
2008
2009Value *Nucleus::createTrunc(Value *v, Type *destType)
2010{
2011 RR_DEBUG_INFO_UPDATE_LOC();
2012 return V(jit->builder->CreateTrunc(V(v), T(destType)));
2013}
2014
2015Value *Nucleus::createZExt(Value *v, Type *destType)
2016{
2017 RR_DEBUG_INFO_UPDATE_LOC();
2018 return V(jit->builder->CreateZExt(V(v), T(destType)));
2019}
2020
2021Value *Nucleus::createSExt(Value *v, Type *destType)
2022{
2023 RR_DEBUG_INFO_UPDATE_LOC();
2024 return V(jit->builder->CreateSExt(V(v), T(destType)));
2025}
2026
2027Value *Nucleus::createFPToUI(Value *v, Type *destType)
2028{
2029 RR_DEBUG_INFO_UPDATE_LOC();
2030 return V(jit->builder->CreateFPToUI(V(v), T(destType)));
2031}
2032
2033Value *Nucleus::createFPToSI(Value *v, Type *destType)
2034{
2035 RR_DEBUG_INFO_UPDATE_LOC();
2036 return V(jit->builder->CreateFPToSI(V(v), T(destType)));
2037}
2038
2039Value *Nucleus::createSIToFP(Value *v, Type *destType)
2040{
2041 RR_DEBUG_INFO_UPDATE_LOC();
2042 return V(jit->builder->CreateSIToFP(V(v), T(destType)));
2043}
2044
2045Value *Nucleus::createFPTrunc(Value *v, Type *destType)
2046{
2047 RR_DEBUG_INFO_UPDATE_LOC();
2048 return V(jit->builder->CreateFPTrunc(V(v), T(destType)));
2049}
2050
2051Value *Nucleus::createFPExt(Value *v, Type *destType)
2052{
2053 RR_DEBUG_INFO_UPDATE_LOC();
2054 return V(jit->builder->CreateFPExt(V(v), T(destType)));
2055}
2056
2057Value *Nucleus::createBitCast(Value *v, Type *destType)
2058{
2059 RR_DEBUG_INFO_UPDATE_LOC();
2060 // Bitcasts must be between types of the same logical size. But with emulated narrow vectors we need
2061 // support for casting between scalars and wide vectors. Emulate them by writing to the stack and
2062 // reading back as the destination type.
2063 if(!V(v)->getType()->isVectorTy() && T(destType)->isVectorTy())
John Bauman89401822014-05-06 15:04:28 -04002064 {
Nicolas Capens157ba262019-12-10 17:49:14 -05002065 Value *readAddress = allocateStackVariable(destType);
2066 Value *writeAddress = createBitCast(readAddress, T(llvm::PointerType::get(V(v)->getType(), 0)));
2067 createStore(v, writeAddress, T(V(v)->getType()));
2068 return createLoad(readAddress, destType);
2069 }
2070 else if(V(v)->getType()->isVectorTy() && !T(destType)->isVectorTy())
2071 {
2072 Value *writeAddress = allocateStackVariable(T(V(v)->getType()));
2073 createStore(v, writeAddress, T(V(v)->getType()));
2074 Value *readAddress = createBitCast(writeAddress, T(llvm::PointerType::get(T(destType), 0)));
2075 return createLoad(readAddress, destType);
John Bauman89401822014-05-06 15:04:28 -04002076 }
2077
Nicolas Capens157ba262019-12-10 17:49:14 -05002078 return V(jit->builder->CreateBitCast(V(v), T(destType)));
2079}
2080
2081Value *Nucleus::createPtrEQ(Value *lhs, Value *rhs)
2082{
2083 RR_DEBUG_INFO_UPDATE_LOC();
2084 return V(jit->builder->CreateICmpEQ(V(lhs), V(rhs)));
2085}
2086
2087Value *Nucleus::createICmpEQ(Value *lhs, Value *rhs)
2088{
2089 RR_DEBUG_INFO_UPDATE_LOC();
2090 return V(jit->builder->CreateICmpEQ(V(lhs), V(rhs)));
2091}
2092
2093Value *Nucleus::createICmpNE(Value *lhs, Value *rhs)
2094{
2095 RR_DEBUG_INFO_UPDATE_LOC();
2096 return V(jit->builder->CreateICmpNE(V(lhs), V(rhs)));
2097}
2098
2099Value *Nucleus::createICmpUGT(Value *lhs, Value *rhs)
2100{
2101 RR_DEBUG_INFO_UPDATE_LOC();
2102 return V(jit->builder->CreateICmpUGT(V(lhs), V(rhs)));
2103}
2104
2105Value *Nucleus::createICmpUGE(Value *lhs, Value *rhs)
2106{
2107 RR_DEBUG_INFO_UPDATE_LOC();
2108 return V(jit->builder->CreateICmpUGE(V(lhs), V(rhs)));
2109}
2110
2111Value *Nucleus::createICmpULT(Value *lhs, Value *rhs)
2112{
2113 RR_DEBUG_INFO_UPDATE_LOC();
2114 return V(jit->builder->CreateICmpULT(V(lhs), V(rhs)));
2115}
2116
2117Value *Nucleus::createICmpULE(Value *lhs, Value *rhs)
2118{
2119 RR_DEBUG_INFO_UPDATE_LOC();
2120 return V(jit->builder->CreateICmpULE(V(lhs), V(rhs)));
2121}
2122
2123Value *Nucleus::createICmpSGT(Value *lhs, Value *rhs)
2124{
2125 RR_DEBUG_INFO_UPDATE_LOC();
2126 return V(jit->builder->CreateICmpSGT(V(lhs), V(rhs)));
2127}
2128
2129Value *Nucleus::createICmpSGE(Value *lhs, Value *rhs)
2130{
2131 RR_DEBUG_INFO_UPDATE_LOC();
2132 return V(jit->builder->CreateICmpSGE(V(lhs), V(rhs)));
2133}
2134
2135Value *Nucleus::createICmpSLT(Value *lhs, Value *rhs)
2136{
2137 RR_DEBUG_INFO_UPDATE_LOC();
2138 return V(jit->builder->CreateICmpSLT(V(lhs), V(rhs)));
2139}
2140
2141Value *Nucleus::createICmpSLE(Value *lhs, Value *rhs)
2142{
2143 RR_DEBUG_INFO_UPDATE_LOC();
2144 return V(jit->builder->CreateICmpSLE(V(lhs), V(rhs)));
2145}
2146
2147Value *Nucleus::createFCmpOEQ(Value *lhs, Value *rhs)
2148{
2149 RR_DEBUG_INFO_UPDATE_LOC();
2150 return V(jit->builder->CreateFCmpOEQ(V(lhs), V(rhs)));
2151}
2152
2153Value *Nucleus::createFCmpOGT(Value *lhs, Value *rhs)
2154{
2155 RR_DEBUG_INFO_UPDATE_LOC();
2156 return V(jit->builder->CreateFCmpOGT(V(lhs), V(rhs)));
2157}
2158
2159Value *Nucleus::createFCmpOGE(Value *lhs, Value *rhs)
2160{
2161 RR_DEBUG_INFO_UPDATE_LOC();
2162 return V(jit->builder->CreateFCmpOGE(V(lhs), V(rhs)));
2163}
2164
2165Value *Nucleus::createFCmpOLT(Value *lhs, Value *rhs)
2166{
2167 RR_DEBUG_INFO_UPDATE_LOC();
2168 return V(jit->builder->CreateFCmpOLT(V(lhs), V(rhs)));
2169}
2170
2171Value *Nucleus::createFCmpOLE(Value *lhs, Value *rhs)
2172{
2173 RR_DEBUG_INFO_UPDATE_LOC();
2174 return V(jit->builder->CreateFCmpOLE(V(lhs), V(rhs)));
2175}
2176
2177Value *Nucleus::createFCmpONE(Value *lhs, Value *rhs)
2178{
2179 RR_DEBUG_INFO_UPDATE_LOC();
2180 return V(jit->builder->CreateFCmpONE(V(lhs), V(rhs)));
2181}
2182
2183Value *Nucleus::createFCmpORD(Value *lhs, Value *rhs)
2184{
2185 RR_DEBUG_INFO_UPDATE_LOC();
2186 return V(jit->builder->CreateFCmpORD(V(lhs), V(rhs)));
2187}
2188
2189Value *Nucleus::createFCmpUNO(Value *lhs, Value *rhs)
2190{
2191 RR_DEBUG_INFO_UPDATE_LOC();
2192 return V(jit->builder->CreateFCmpUNO(V(lhs), V(rhs)));
2193}
2194
2195Value *Nucleus::createFCmpUEQ(Value *lhs, Value *rhs)
2196{
2197 RR_DEBUG_INFO_UPDATE_LOC();
2198 return V(jit->builder->CreateFCmpUEQ(V(lhs), V(rhs)));
2199}
2200
2201Value *Nucleus::createFCmpUGT(Value *lhs, Value *rhs)
2202{
2203 RR_DEBUG_INFO_UPDATE_LOC();
2204 return V(jit->builder->CreateFCmpUGT(V(lhs), V(rhs)));
2205}
2206
2207Value *Nucleus::createFCmpUGE(Value *lhs, Value *rhs)
2208{
2209 RR_DEBUG_INFO_UPDATE_LOC();
2210 return V(jit->builder->CreateFCmpUGE(V(lhs), V(rhs)));
2211}
2212
2213Value *Nucleus::createFCmpULT(Value *lhs, Value *rhs)
2214{
2215 RR_DEBUG_INFO_UPDATE_LOC();
2216 return V(jit->builder->CreateFCmpULT(V(lhs), V(rhs)));
2217}
2218
2219Value *Nucleus::createFCmpULE(Value *lhs, Value *rhs)
2220{
2221 RR_DEBUG_INFO_UPDATE_LOC();
2222 return V(jit->builder->CreateFCmpULE(V(lhs), V(rhs)));
2223}
2224
2225Value *Nucleus::createFCmpUNE(Value *lhs, Value *rhs)
2226{
2227 RR_DEBUG_INFO_UPDATE_LOC();
2228 return V(jit->builder->CreateFCmpUNE(V(lhs), V(rhs)));
2229}
2230
2231Value *Nucleus::createExtractElement(Value *vector, Type *type, int index)
2232{
2233 RR_DEBUG_INFO_UPDATE_LOC();
2234 ASSERT(V(vector)->getType()->getContainedType(0) == T(type));
2235 return V(jit->builder->CreateExtractElement(V(vector), V(createConstantInt(index))));
2236}
2237
2238Value *Nucleus::createInsertElement(Value *vector, Value *element, int index)
2239{
2240 RR_DEBUG_INFO_UPDATE_LOC();
2241 return V(jit->builder->CreateInsertElement(V(vector), V(element), V(createConstantInt(index))));
2242}
2243
2244Value *Nucleus::createShuffleVector(Value *v1, Value *v2, const int *select)
2245{
2246 RR_DEBUG_INFO_UPDATE_LOC();
2247
2248 int size = llvm::cast<llvm::VectorType>(V(v1)->getType())->getNumElements();
2249 const int maxSize = 16;
2250 llvm::Constant *swizzle[maxSize];
2251 ASSERT(size <= maxSize);
2252
2253 for(int i = 0; i < size; i++)
John Bauman89401822014-05-06 15:04:28 -04002254 {
Nicolas Capens157ba262019-12-10 17:49:14 -05002255 swizzle[i] = llvm::ConstantInt::get(llvm::Type::getInt32Ty(jit->context), select[i]);
John Bauman89401822014-05-06 15:04:28 -04002256 }
2257
Nicolas Capens157ba262019-12-10 17:49:14 -05002258 llvm::Value *shuffle = llvm::ConstantVector::get(llvm::ArrayRef<llvm::Constant*>(swizzle, size));
2259
2260 return V(jit->builder->CreateShuffleVector(V(v1), V(v2), shuffle));
2261}
2262
2263Value *Nucleus::createSelect(Value *c, Value *ifTrue, Value *ifFalse)
2264{
2265 RR_DEBUG_INFO_UPDATE_LOC();
2266 return V(jit->builder->CreateSelect(V(c), V(ifTrue), V(ifFalse)));
2267}
2268
2269SwitchCases *Nucleus::createSwitch(Value *control, BasicBlock *defaultBranch, unsigned numCases)
2270{
2271 RR_DEBUG_INFO_UPDATE_LOC();
2272 return reinterpret_cast<SwitchCases*>(jit->builder->CreateSwitch(V(control), B(defaultBranch), numCases));
2273}
2274
2275void Nucleus::addSwitchCase(SwitchCases *switchCases, int label, BasicBlock *branch)
2276{
2277 RR_DEBUG_INFO_UPDATE_LOC();
2278 llvm::SwitchInst *sw = reinterpret_cast<llvm::SwitchInst *>(switchCases);
2279 sw->addCase(llvm::ConstantInt::get(llvm::Type::getInt32Ty(jit->context), label, true), B(branch));
2280}
2281
2282void Nucleus::createUnreachable()
2283{
2284 RR_DEBUG_INFO_UPDATE_LOC();
2285 jit->builder->CreateUnreachable();
2286}
2287
2288Type *Nucleus::getPointerType(Type *ElementType)
2289{
2290 return T(llvm::PointerType::get(T(ElementType), 0));
2291}
2292
2293Value *Nucleus::createNullValue(Type *Ty)
2294{
2295 RR_DEBUG_INFO_UPDATE_LOC();
2296 return V(llvm::Constant::getNullValue(T(Ty)));
2297}
2298
2299Value *Nucleus::createConstantLong(int64_t i)
2300{
2301 RR_DEBUG_INFO_UPDATE_LOC();
2302 return V(llvm::ConstantInt::get(llvm::Type::getInt64Ty(jit->context), i, true));
2303}
2304
2305Value *Nucleus::createConstantInt(int i)
2306{
2307 RR_DEBUG_INFO_UPDATE_LOC();
2308 return V(llvm::ConstantInt::get(llvm::Type::getInt32Ty(jit->context), i, true));
2309}
2310
2311Value *Nucleus::createConstantInt(unsigned int i)
2312{
2313 RR_DEBUG_INFO_UPDATE_LOC();
2314 return V(llvm::ConstantInt::get(llvm::Type::getInt32Ty(jit->context), i, false));
2315}
2316
2317Value *Nucleus::createConstantBool(bool b)
2318{
2319 RR_DEBUG_INFO_UPDATE_LOC();
2320 return V(llvm::ConstantInt::get(llvm::Type::getInt1Ty(jit->context), b));
2321}
2322
2323Value *Nucleus::createConstantByte(signed char i)
2324{
2325 RR_DEBUG_INFO_UPDATE_LOC();
2326 return V(llvm::ConstantInt::get(llvm::Type::getInt8Ty(jit->context), i, true));
2327}
2328
2329Value *Nucleus::createConstantByte(unsigned char i)
2330{
2331 RR_DEBUG_INFO_UPDATE_LOC();
2332 return V(llvm::ConstantInt::get(llvm::Type::getInt8Ty(jit->context), i, false));
2333}
2334
2335Value *Nucleus::createConstantShort(short i)
2336{
2337 RR_DEBUG_INFO_UPDATE_LOC();
2338 return V(llvm::ConstantInt::get(llvm::Type::getInt16Ty(jit->context), i, true));
2339}
2340
2341Value *Nucleus::createConstantShort(unsigned short i)
2342{
2343 RR_DEBUG_INFO_UPDATE_LOC();
2344 return V(llvm::ConstantInt::get(llvm::Type::getInt16Ty(jit->context), i, false));
2345}
2346
2347Value *Nucleus::createConstantFloat(float x)
2348{
2349 RR_DEBUG_INFO_UPDATE_LOC();
2350 return V(llvm::ConstantFP::get(T(Float::getType()), x));
2351}
2352
2353Value *Nucleus::createNullPointer(Type *Ty)
2354{
2355 RR_DEBUG_INFO_UPDATE_LOC();
2356 return V(llvm::ConstantPointerNull::get(llvm::PointerType::get(T(Ty), 0)));
2357}
2358
2359Value *Nucleus::createConstantVector(const int64_t *constants, Type *type)
2360{
2361 ASSERT(llvm::isa<llvm::VectorType>(T(type)));
2362 const int numConstants = elementCount(type); // Number of provided constants for the (emulated) type.
2363 const int numElements = llvm::cast<llvm::VectorType>(T(type))->getNumElements(); // Number of elements of the underlying vector type.
2364 ASSERT(numElements <= 16 && numConstants <= numElements);
2365 llvm::Constant *constantVector[16];
2366
2367 for(int i = 0; i < numElements; i++)
John Bauman89401822014-05-06 15:04:28 -04002368 {
Nicolas Capens157ba262019-12-10 17:49:14 -05002369 constantVector[i] = llvm::ConstantInt::get(T(type)->getContainedType(0), constants[i % numConstants]);
John Bauman89401822014-05-06 15:04:28 -04002370 }
2371
Nicolas Capens157ba262019-12-10 17:49:14 -05002372 return V(llvm::ConstantVector::get(llvm::ArrayRef<llvm::Constant*>(constantVector, numElements)));
2373}
2374
2375Value *Nucleus::createConstantVector(const double *constants, Type *type)
2376{
2377 ASSERT(llvm::isa<llvm::VectorType>(T(type)));
2378 const int numConstants = elementCount(type); // Number of provided constants for the (emulated) type.
2379 const int numElements = llvm::cast<llvm::VectorType>(T(type))->getNumElements(); // Number of elements of the underlying vector type.
2380 ASSERT(numElements <= 8 && numConstants <= numElements);
2381 llvm::Constant *constantVector[8];
2382
2383 for(int i = 0; i < numElements; i++)
John Bauman89401822014-05-06 15:04:28 -04002384 {
Nicolas Capens157ba262019-12-10 17:49:14 -05002385 constantVector[i] = llvm::ConstantFP::get(T(type)->getContainedType(0), constants[i % numConstants]);
John Bauman89401822014-05-06 15:04:28 -04002386 }
2387
Nicolas Capens157ba262019-12-10 17:49:14 -05002388 return V(llvm::ConstantVector::get(llvm::ArrayRef<llvm::Constant*>(constantVector, numElements)));
2389}
John Bauman89401822014-05-06 15:04:28 -04002390
Nicolas Capens157ba262019-12-10 17:49:14 -05002391Type *Void::getType()
2392{
2393 return T(llvm::Type::getVoidTy(jit->context));
2394}
John Bauman89401822014-05-06 15:04:28 -04002395
Nicolas Capens157ba262019-12-10 17:49:14 -05002396Type *Bool::getType()
2397{
2398 return T(llvm::Type::getInt1Ty(jit->context));
2399}
John Bauman89401822014-05-06 15:04:28 -04002400
Nicolas Capens157ba262019-12-10 17:49:14 -05002401Type *Byte::getType()
2402{
2403 return T(llvm::Type::getInt8Ty(jit->context));
2404}
John Bauman89401822014-05-06 15:04:28 -04002405
Nicolas Capens157ba262019-12-10 17:49:14 -05002406Type *SByte::getType()
2407{
2408 return T(llvm::Type::getInt8Ty(jit->context));
2409}
2410
2411Type *Short::getType()
2412{
2413 return T(llvm::Type::getInt16Ty(jit->context));
2414}
2415
2416Type *UShort::getType()
2417{
2418 return T(llvm::Type::getInt16Ty(jit->context));
2419}
2420
2421Type *Byte4::getType()
2422{
2423 return T(Type_v4i8);
2424}
2425
2426Type *SByte4::getType()
2427{
2428 return T(Type_v4i8);
2429}
2430
2431RValue<Byte8> AddSat(RValue<Byte8> x, RValue<Byte8> y)
2432{
2433 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002434#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002435 return x86::paddusb(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002436#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002437 return As<Byte8>(V(lowerPUADDSAT(V(x.value), V(y.value))));
Logan Chiene3191012018-08-24 22:01:50 +08002438#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002439}
John Bauman66b8ab22014-05-06 15:57:45 -04002440
Nicolas Capens157ba262019-12-10 17:49:14 -05002441RValue<Byte8> SubSat(RValue<Byte8> x, RValue<Byte8> y)
2442{
2443 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002444#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002445 return x86::psubusb(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002446#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002447 return As<Byte8>(V(lowerPUSUBSAT(V(x.value), V(y.value))));
Logan Chiene3191012018-08-24 22:01:50 +08002448#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002449}
John Bauman89401822014-05-06 15:04:28 -04002450
Nicolas Capens157ba262019-12-10 17:49:14 -05002451RValue<Int> SignMask(RValue<Byte8> x)
2452{
2453 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002454#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002455 return x86::pmovmskb(x);
Logan Chiene3191012018-08-24 22:01:50 +08002456#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002457 return As<Int>(V(lowerSignMask(V(x.value), T(Int::getType()))));
Logan Chiene3191012018-08-24 22:01:50 +08002458#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002459}
John Bauman89401822014-05-06 15:04:28 -04002460
John Bauman19bac1e2014-05-06 15:23:49 -04002461// RValue<Byte8> CmpGT(RValue<Byte8> x, RValue<Byte8> y)
John Bauman89401822014-05-06 15:04:28 -04002462// {
Logan Chiene3191012018-08-24 22:01:50 +08002463//#if defined(__i386__) || defined(__x86_64__)
John Bauman89401822014-05-06 15:04:28 -04002464// return x86::pcmpgtb(x, y); // FIXME: Signedness
Logan Chiene3191012018-08-24 22:01:50 +08002465//#else
2466// return As<Byte8>(V(lowerPCMP(llvm::ICmpInst::ICMP_SGT, V(x.value), V(y.value), T(Byte8::getType()))));
2467//#endif
John Bauman89401822014-05-06 15:04:28 -04002468// }
John Bauman66b8ab22014-05-06 15:57:45 -04002469
Nicolas Capens157ba262019-12-10 17:49:14 -05002470RValue<Byte8> CmpEQ(RValue<Byte8> x, RValue<Byte8> y)
2471{
2472 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002473#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002474 return x86::pcmpeqb(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002475#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002476 return As<Byte8>(V(lowerPCMP(llvm::ICmpInst::ICMP_EQ, V(x.value), V(y.value), T(Byte8::getType()))));
Logan Chiene3191012018-08-24 22:01:50 +08002477#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002478}
John Bauman89401822014-05-06 15:04:28 -04002479
Nicolas Capens157ba262019-12-10 17:49:14 -05002480Type *Byte8::getType()
2481{
2482 return T(Type_v8i8);
2483}
John Bauman89401822014-05-06 15:04:28 -04002484
Nicolas Capens157ba262019-12-10 17:49:14 -05002485RValue<SByte8> AddSat(RValue<SByte8> x, RValue<SByte8> y)
2486{
2487 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002488#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002489 return x86::paddsb(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002490#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002491 return As<SByte8>(V(lowerPSADDSAT(V(x.value), V(y.value))));
Logan Chiene3191012018-08-24 22:01:50 +08002492#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002493}
John Bauman66b8ab22014-05-06 15:57:45 -04002494
Nicolas Capens157ba262019-12-10 17:49:14 -05002495RValue<SByte8> SubSat(RValue<SByte8> x, RValue<SByte8> y)
2496{
2497 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002498#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002499 return x86::psubsb(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002500#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002501 return As<SByte8>(V(lowerPSSUBSAT(V(x.value), V(y.value))));
Logan Chiene3191012018-08-24 22:01:50 +08002502#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002503}
John Bauman89401822014-05-06 15:04:28 -04002504
Nicolas Capens157ba262019-12-10 17:49:14 -05002505RValue<Int> SignMask(RValue<SByte8> x)
2506{
2507 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002508#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002509 return x86::pmovmskb(As<Byte8>(x));
Logan Chiene3191012018-08-24 22:01:50 +08002510#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002511 return As<Int>(V(lowerSignMask(V(x.value), T(Int::getType()))));
Logan Chiene3191012018-08-24 22:01:50 +08002512#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002513}
John Bauman89401822014-05-06 15:04:28 -04002514
Nicolas Capens157ba262019-12-10 17:49:14 -05002515RValue<Byte8> CmpGT(RValue<SByte8> x, RValue<SByte8> y)
2516{
2517 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002518#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002519 return x86::pcmpgtb(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002520#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002521 return As<Byte8>(V(lowerPCMP(llvm::ICmpInst::ICMP_SGT, V(x.value), V(y.value), T(Byte8::getType()))));
Logan Chiene3191012018-08-24 22:01:50 +08002522#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002523}
John Bauman66b8ab22014-05-06 15:57:45 -04002524
Nicolas Capens157ba262019-12-10 17:49:14 -05002525RValue<Byte8> CmpEQ(RValue<SByte8> x, RValue<SByte8> y)
2526{
2527 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002528#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002529 return x86::pcmpeqb(As<Byte8>(x), As<Byte8>(y));
Logan Chiene3191012018-08-24 22:01:50 +08002530#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002531 return As<Byte8>(V(lowerPCMP(llvm::ICmpInst::ICMP_EQ, V(x.value), V(y.value), T(Byte8::getType()))));
Logan Chiene3191012018-08-24 22:01:50 +08002532#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002533}
John Bauman89401822014-05-06 15:04:28 -04002534
Nicolas Capens157ba262019-12-10 17:49:14 -05002535Type *SByte8::getType()
2536{
2537 return T(Type_v8i8);
2538}
John Bauman89401822014-05-06 15:04:28 -04002539
Nicolas Capens157ba262019-12-10 17:49:14 -05002540Type *Byte16::getType()
2541{
2542 return T(llvm::VectorType::get(T(Byte::getType()), 16));
2543}
John Bauman89401822014-05-06 15:04:28 -04002544
Nicolas Capens157ba262019-12-10 17:49:14 -05002545Type *SByte16::getType()
2546{
2547 return T(llvm::VectorType::get(T(SByte::getType()), 16));
2548}
John Bauman89401822014-05-06 15:04:28 -04002549
Nicolas Capens157ba262019-12-10 17:49:14 -05002550Type *Short2::getType()
2551{
2552 return T(Type_v2i16);
2553}
Nicolas Capens16b5f152016-10-13 13:39:01 -04002554
Nicolas Capens157ba262019-12-10 17:49:14 -05002555Type *UShort2::getType()
2556{
2557 return T(Type_v2i16);
2558}
Nicolas Capens16b5f152016-10-13 13:39:01 -04002559
Nicolas Capens157ba262019-12-10 17:49:14 -05002560Short4::Short4(RValue<Int4> cast)
2561{
2562 RR_DEBUG_INFO_UPDATE_LOC();
2563 int select[8] = {0, 2, 4, 6, 0, 2, 4, 6};
2564 Value *short8 = Nucleus::createBitCast(cast.value, Short8::getType());
John Bauman89401822014-05-06 15:04:28 -04002565
Nicolas Capens157ba262019-12-10 17:49:14 -05002566 Value *packed = Nucleus::createShuffleVector(short8, short8, select);
2567 Value *short4 = As<Short4>(Int2(As<Int4>(packed))).value;
John Bauman89401822014-05-06 15:04:28 -04002568
Nicolas Capens157ba262019-12-10 17:49:14 -05002569 storeValue(short4);
2570}
John Bauman89401822014-05-06 15:04:28 -04002571
John Bauman19bac1e2014-05-06 15:23:49 -04002572// Short4::Short4(RValue<Float> cast)
John Bauman89401822014-05-06 15:04:28 -04002573// {
2574// }
2575
Nicolas Capens157ba262019-12-10 17:49:14 -05002576Short4::Short4(RValue<Float4> cast)
2577{
2578 RR_DEBUG_INFO_UPDATE_LOC();
2579 Int4 v4i32 = Int4(cast);
Logan Chiene3191012018-08-24 22:01:50 +08002580#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002581 v4i32 = As<Int4>(x86::packssdw(v4i32, v4i32));
Logan Chiene3191012018-08-24 22:01:50 +08002582#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002583 Value *v = v4i32.loadValue();
2584 v4i32 = As<Int4>(V(lowerPack(V(v), V(v), true)));
Logan Chiene3191012018-08-24 22:01:50 +08002585#endif
John Bauman66b8ab22014-05-06 15:57:45 -04002586
Nicolas Capens157ba262019-12-10 17:49:14 -05002587 storeValue(As<Short4>(Int2(v4i32)).value);
2588}
John Bauman89401822014-05-06 15:04:28 -04002589
Nicolas Capens157ba262019-12-10 17:49:14 -05002590RValue<Short4> operator<<(RValue<Short4> lhs, unsigned char rhs)
2591{
2592 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002593#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002594// return RValue<Short4>(Nucleus::createShl(lhs.value, rhs.value));
John Bauman89401822014-05-06 15:04:28 -04002595
Nicolas Capens157ba262019-12-10 17:49:14 -05002596 return x86::psllw(lhs, rhs);
Logan Chiene3191012018-08-24 22:01:50 +08002597#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002598 return As<Short4>(V(lowerVectorShl(V(lhs.value), rhs)));
Logan Chiene3191012018-08-24 22:01:50 +08002599#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002600}
John Bauman89401822014-05-06 15:04:28 -04002601
Nicolas Capens157ba262019-12-10 17:49:14 -05002602RValue<Short4> operator>>(RValue<Short4> lhs, unsigned char rhs)
2603{
2604 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002605#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002606 return x86::psraw(lhs, rhs);
Logan Chiene3191012018-08-24 22:01:50 +08002607#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002608 return As<Short4>(V(lowerVectorAShr(V(lhs.value), rhs)));
Logan Chiene3191012018-08-24 22:01:50 +08002609#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002610}
John Bauman89401822014-05-06 15:04:28 -04002611
Nicolas Capens157ba262019-12-10 17:49:14 -05002612RValue<Short4> Max(RValue<Short4> x, RValue<Short4> y)
2613{
2614 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002615#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002616 return x86::pmaxsw(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002617#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002618 return RValue<Short4>(V(lowerPMINMAX(V(x.value), V(y.value), llvm::ICmpInst::ICMP_SGT)));
Logan Chiene3191012018-08-24 22:01:50 +08002619#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002620}
John Bauman89401822014-05-06 15:04:28 -04002621
Nicolas Capens157ba262019-12-10 17:49:14 -05002622RValue<Short4> Min(RValue<Short4> x, RValue<Short4> y)
2623{
2624 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002625#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002626 return x86::pminsw(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002627#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002628 return RValue<Short4>(V(lowerPMINMAX(V(x.value), V(y.value), llvm::ICmpInst::ICMP_SLT)));
Logan Chiene3191012018-08-24 22:01:50 +08002629#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002630}
John Bauman89401822014-05-06 15:04:28 -04002631
Nicolas Capens157ba262019-12-10 17:49:14 -05002632RValue<Short4> AddSat(RValue<Short4> x, RValue<Short4> y)
2633{
2634 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002635#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002636 return x86::paddsw(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002637#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002638 return As<Short4>(V(lowerPSADDSAT(V(x.value), V(y.value))));
Logan Chiene3191012018-08-24 22:01:50 +08002639#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002640}
John Bauman89401822014-05-06 15:04:28 -04002641
Nicolas Capens157ba262019-12-10 17:49:14 -05002642RValue<Short4> SubSat(RValue<Short4> x, RValue<Short4> y)
2643{
2644 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002645#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002646 return x86::psubsw(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002647#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002648 return As<Short4>(V(lowerPSSUBSAT(V(x.value), V(y.value))));
Logan Chiene3191012018-08-24 22:01:50 +08002649#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002650}
John Bauman89401822014-05-06 15:04:28 -04002651
Nicolas Capens157ba262019-12-10 17:49:14 -05002652RValue<Short4> MulHigh(RValue<Short4> x, RValue<Short4> y)
2653{
2654 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002655#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002656 return x86::pmulhw(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002657#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002658 return As<Short4>(V(lowerMulHigh(V(x.value), V(y.value), true)));
Logan Chiene3191012018-08-24 22:01:50 +08002659#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002660}
John Bauman89401822014-05-06 15:04:28 -04002661
Nicolas Capens157ba262019-12-10 17:49:14 -05002662RValue<Int2> MulAdd(RValue<Short4> x, RValue<Short4> y)
2663{
2664 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002665#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002666 return x86::pmaddwd(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002667#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002668 return As<Int2>(V(lowerMulAdd(V(x.value), V(y.value))));
Logan Chiene3191012018-08-24 22:01:50 +08002669#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002670}
John Bauman89401822014-05-06 15:04:28 -04002671
Nicolas Capens157ba262019-12-10 17:49:14 -05002672RValue<SByte8> PackSigned(RValue<Short4> x, RValue<Short4> y)
2673{
2674 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002675#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002676 auto result = x86::packsswb(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002677#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002678 auto result = V(lowerPack(V(x.value), V(y.value), true));
Logan Chiene3191012018-08-24 22:01:50 +08002679#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002680 return As<SByte8>(Swizzle(As<Int4>(result), 0x0202));
2681}
John Bauman89401822014-05-06 15:04:28 -04002682
Nicolas Capens157ba262019-12-10 17:49:14 -05002683RValue<Byte8> PackUnsigned(RValue<Short4> x, RValue<Short4> y)
2684{
2685 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002686#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002687 auto result = x86::packuswb(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002688#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002689 auto result = V(lowerPack(V(x.value), V(y.value), false));
Logan Chiene3191012018-08-24 22:01:50 +08002690#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002691 return As<Byte8>(Swizzle(As<Int4>(result), 0x0202));
2692}
Nicolas Capens33438a62017-09-27 11:47:35 -04002693
Nicolas Capens157ba262019-12-10 17:49:14 -05002694RValue<Short4> CmpGT(RValue<Short4> x, RValue<Short4> y)
2695{
2696 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002697#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002698 return x86::pcmpgtw(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002699#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002700 return As<Short4>(V(lowerPCMP(llvm::ICmpInst::ICMP_SGT, V(x.value), V(y.value), T(Short4::getType()))));
Logan Chiene3191012018-08-24 22:01:50 +08002701#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002702}
John Bauman89401822014-05-06 15:04:28 -04002703
Nicolas Capens157ba262019-12-10 17:49:14 -05002704RValue<Short4> CmpEQ(RValue<Short4> x, RValue<Short4> y)
2705{
2706 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002707#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002708 return x86::pcmpeqw(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002709#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002710 return As<Short4>(V(lowerPCMP(llvm::ICmpInst::ICMP_EQ, V(x.value), V(y.value), T(Short4::getType()))));
Logan Chiene3191012018-08-24 22:01:50 +08002711#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002712}
John Bauman89401822014-05-06 15:04:28 -04002713
Nicolas Capens157ba262019-12-10 17:49:14 -05002714Type *Short4::getType()
2715{
2716 return T(Type_v4i16);
2717}
John Bauman89401822014-05-06 15:04:28 -04002718
Nicolas Capens157ba262019-12-10 17:49:14 -05002719UShort4::UShort4(RValue<Float4> cast, bool saturate)
2720{
2721 RR_DEBUG_INFO_UPDATE_LOC();
2722 if(saturate)
John Bauman89401822014-05-06 15:04:28 -04002723 {
Nicolas Capens157ba262019-12-10 17:49:14 -05002724#if defined(__i386__) || defined(__x86_64__)
2725 if(CPUID::supportsSSE4_1())
John Bauman89401822014-05-06 15:04:28 -04002726 {
Nicolas Capens157ba262019-12-10 17:49:14 -05002727 Int4 int4(Min(cast, Float4(0xFFFF))); // packusdw takes care of 0x0000 saturation
2728 *this = As<Short4>(PackUnsigned(int4, int4));
John Bauman89401822014-05-06 15:04:28 -04002729 }
2730 else
Nicolas Capens157ba262019-12-10 17:49:14 -05002731#endif
John Bauman89401822014-05-06 15:04:28 -04002732 {
Nicolas Capens157ba262019-12-10 17:49:14 -05002733 *this = Short4(Int4(Max(Min(cast, Float4(0xFFFF)), Float4(0x0000))));
John Bauman89401822014-05-06 15:04:28 -04002734 }
2735 }
Nicolas Capens157ba262019-12-10 17:49:14 -05002736 else
John Bauman89401822014-05-06 15:04:28 -04002737 {
Nicolas Capens157ba262019-12-10 17:49:14 -05002738 *this = Short4(Int4(cast));
2739 }
2740}
2741
2742RValue<UShort4> operator<<(RValue<UShort4> lhs, unsigned char rhs)
2743{
2744 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002745#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002746// return RValue<Short4>(Nucleus::createShl(lhs.value, rhs.value));
John Bauman89401822014-05-06 15:04:28 -04002747
Nicolas Capens157ba262019-12-10 17:49:14 -05002748 return As<UShort4>(x86::psllw(As<Short4>(lhs), rhs));
Logan Chiene3191012018-08-24 22:01:50 +08002749#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002750 return As<UShort4>(V(lowerVectorShl(V(lhs.value), rhs)));
Logan Chiene3191012018-08-24 22:01:50 +08002751#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002752}
John Bauman89401822014-05-06 15:04:28 -04002753
Nicolas Capens157ba262019-12-10 17:49:14 -05002754RValue<UShort4> operator>>(RValue<UShort4> lhs, unsigned char rhs)
2755{
2756 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002757#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002758// return RValue<Short4>(Nucleus::createLShr(lhs.value, rhs.value));
John Bauman89401822014-05-06 15:04:28 -04002759
Nicolas Capens157ba262019-12-10 17:49:14 -05002760 return x86::psrlw(lhs, rhs);
Logan Chiene3191012018-08-24 22:01:50 +08002761#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002762 return As<UShort4>(V(lowerVectorLShr(V(lhs.value), rhs)));
Logan Chiene3191012018-08-24 22:01:50 +08002763#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002764}
John Bauman89401822014-05-06 15:04:28 -04002765
Nicolas Capens157ba262019-12-10 17:49:14 -05002766RValue<UShort4> Max(RValue<UShort4> x, RValue<UShort4> y)
2767{
2768 RR_DEBUG_INFO_UPDATE_LOC();
2769 return RValue<UShort4>(Max(As<Short4>(x) - Short4(0x8000u, 0x8000u, 0x8000u, 0x8000u), As<Short4>(y) - Short4(0x8000u, 0x8000u, 0x8000u, 0x8000u)) + Short4(0x8000u, 0x8000u, 0x8000u, 0x8000u));
2770}
John Bauman89401822014-05-06 15:04:28 -04002771
Nicolas Capens157ba262019-12-10 17:49:14 -05002772RValue<UShort4> Min(RValue<UShort4> x, RValue<UShort4> y)
2773{
2774 RR_DEBUG_INFO_UPDATE_LOC();
2775 return RValue<UShort4>(Min(As<Short4>(x) - Short4(0x8000u, 0x8000u, 0x8000u, 0x8000u), As<Short4>(y) - Short4(0x8000u, 0x8000u, 0x8000u, 0x8000u)) + Short4(0x8000u, 0x8000u, 0x8000u, 0x8000u));
2776}
John Bauman89401822014-05-06 15:04:28 -04002777
Nicolas Capens157ba262019-12-10 17:49:14 -05002778RValue<UShort4> AddSat(RValue<UShort4> x, RValue<UShort4> y)
2779{
2780 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002781#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002782 return x86::paddusw(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002783#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002784 return As<UShort4>(V(lowerPUADDSAT(V(x.value), V(y.value))));
Logan Chiene3191012018-08-24 22:01:50 +08002785#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002786}
John Bauman89401822014-05-06 15:04:28 -04002787
Nicolas Capens157ba262019-12-10 17:49:14 -05002788RValue<UShort4> SubSat(RValue<UShort4> x, RValue<UShort4> y)
2789{
2790 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002791#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002792 return x86::psubusw(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002793#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002794 return As<UShort4>(V(lowerPUSUBSAT(V(x.value), V(y.value))));
Logan Chiene3191012018-08-24 22:01:50 +08002795#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002796}
John Bauman89401822014-05-06 15:04:28 -04002797
Nicolas Capens157ba262019-12-10 17:49:14 -05002798RValue<UShort4> MulHigh(RValue<UShort4> x, RValue<UShort4> y)
2799{
2800 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002801#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002802 return x86::pmulhuw(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002803#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002804 return As<UShort4>(V(lowerMulHigh(V(x.value), V(y.value), false)));
Logan Chiene3191012018-08-24 22:01:50 +08002805#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002806}
John Bauman89401822014-05-06 15:04:28 -04002807
Nicolas Capens157ba262019-12-10 17:49:14 -05002808RValue<UShort4> Average(RValue<UShort4> x, RValue<UShort4> y)
2809{
2810 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002811#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002812 return x86::pavgw(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002813#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002814 return As<UShort4>(V(lowerPAVG(V(x.value), V(y.value))));
Logan Chiene3191012018-08-24 22:01:50 +08002815#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002816}
John Bauman89401822014-05-06 15:04:28 -04002817
Nicolas Capens157ba262019-12-10 17:49:14 -05002818Type *UShort4::getType()
2819{
2820 return T(Type_v4i16);
2821}
John Bauman89401822014-05-06 15:04:28 -04002822
Nicolas Capens157ba262019-12-10 17:49:14 -05002823RValue<Short8> operator<<(RValue<Short8> lhs, unsigned char rhs)
2824{
2825 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002826#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002827 return x86::psllw(lhs, rhs);
Logan Chiene3191012018-08-24 22:01:50 +08002828#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002829 return As<Short8>(V(lowerVectorShl(V(lhs.value), rhs)));
Logan Chiene3191012018-08-24 22:01:50 +08002830#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002831}
John Bauman89401822014-05-06 15:04:28 -04002832
Nicolas Capens157ba262019-12-10 17:49:14 -05002833RValue<Short8> operator>>(RValue<Short8> lhs, unsigned char rhs)
2834{
2835 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002836#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002837 return x86::psraw(lhs, rhs);
Logan Chiene3191012018-08-24 22:01:50 +08002838#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002839 return As<Short8>(V(lowerVectorAShr(V(lhs.value), rhs)));
Logan Chiene3191012018-08-24 22:01:50 +08002840#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002841}
John Bauman89401822014-05-06 15:04:28 -04002842
Nicolas Capens157ba262019-12-10 17:49:14 -05002843RValue<Int4> MulAdd(RValue<Short8> x, RValue<Short8> y)
2844{
2845 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002846#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002847 return x86::pmaddwd(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002848#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002849 return As<Int4>(V(lowerMulAdd(V(x.value), V(y.value))));
Logan Chiene3191012018-08-24 22:01:50 +08002850#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002851}
John Bauman89401822014-05-06 15:04:28 -04002852
Nicolas Capens157ba262019-12-10 17:49:14 -05002853RValue<Short8> MulHigh(RValue<Short8> x, RValue<Short8> y)
2854{
2855 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002856#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002857 return x86::pmulhw(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002858#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002859 return As<Short8>(V(lowerMulHigh(V(x.value), V(y.value), true)));
Logan Chiene3191012018-08-24 22:01:50 +08002860#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002861}
John Bauman89401822014-05-06 15:04:28 -04002862
Nicolas Capens157ba262019-12-10 17:49:14 -05002863Type *Short8::getType()
2864{
2865 return T(llvm::VectorType::get(T(Short::getType()), 8));
2866}
John Bauman89401822014-05-06 15:04:28 -04002867
Nicolas Capens157ba262019-12-10 17:49:14 -05002868RValue<UShort8> operator<<(RValue<UShort8> lhs, unsigned char rhs)
2869{
2870 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002871#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002872 return As<UShort8>(x86::psllw(As<Short8>(lhs), rhs));
Logan Chiene3191012018-08-24 22:01:50 +08002873#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002874 return As<UShort8>(V(lowerVectorShl(V(lhs.value), rhs)));
Logan Chiene3191012018-08-24 22:01:50 +08002875#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002876}
John Bauman89401822014-05-06 15:04:28 -04002877
Nicolas Capens157ba262019-12-10 17:49:14 -05002878RValue<UShort8> operator>>(RValue<UShort8> lhs, unsigned char rhs)
2879{
2880 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002881#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002882 return x86::psrlw(lhs, rhs); // FIXME: Fallback required
Logan Chiene3191012018-08-24 22:01:50 +08002883#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002884 return As<UShort8>(V(lowerVectorLShr(V(lhs.value), rhs)));
Logan Chiene3191012018-08-24 22:01:50 +08002885#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002886}
John Bauman89401822014-05-06 15:04:28 -04002887
Nicolas Capens157ba262019-12-10 17:49:14 -05002888RValue<UShort8> Swizzle(RValue<UShort8> x, char select0, char select1, char select2, char select3, char select4, char select5, char select6, char select7)
2889{
2890 RR_DEBUG_INFO_UPDATE_LOC();
2891 int pshufb[16] =
John Bauman89401822014-05-06 15:04:28 -04002892 {
Nicolas Capens157ba262019-12-10 17:49:14 -05002893 select0 + 0,
2894 select0 + 1,
2895 select1 + 0,
2896 select1 + 1,
2897 select2 + 0,
2898 select2 + 1,
2899 select3 + 0,
2900 select3 + 1,
2901 select4 + 0,
2902 select4 + 1,
2903 select5 + 0,
2904 select5 + 1,
2905 select6 + 0,
2906 select6 + 1,
2907 select7 + 0,
2908 select7 + 1,
2909 };
John Bauman89401822014-05-06 15:04:28 -04002910
Nicolas Capens157ba262019-12-10 17:49:14 -05002911 Value *byte16 = Nucleus::createBitCast(x.value, Byte16::getType());
2912 Value *shuffle = Nucleus::createShuffleVector(byte16, byte16, pshufb);
2913 Value *short8 = Nucleus::createBitCast(shuffle, UShort8::getType());
John Bauman89401822014-05-06 15:04:28 -04002914
Nicolas Capens157ba262019-12-10 17:49:14 -05002915 return RValue<UShort8>(short8);
2916}
John Bauman89401822014-05-06 15:04:28 -04002917
Nicolas Capens157ba262019-12-10 17:49:14 -05002918RValue<UShort8> MulHigh(RValue<UShort8> x, RValue<UShort8> y)
2919{
2920 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002921#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002922 return x86::pmulhuw(x, y);
Logan Chiene3191012018-08-24 22:01:50 +08002923#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002924 return As<UShort8>(V(lowerMulHigh(V(x.value), V(y.value), false)));
Logan Chiene3191012018-08-24 22:01:50 +08002925#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002926}
John Bauman89401822014-05-06 15:04:28 -04002927
Nicolas Capens157ba262019-12-10 17:49:14 -05002928Type *UShort8::getType()
2929{
2930 return T(llvm::VectorType::get(T(UShort::getType()), 8));
2931}
John Bauman89401822014-05-06 15:04:28 -04002932
Nicolas Capens157ba262019-12-10 17:49:14 -05002933RValue<Int> operator++(Int &val, int) // Post-increment
2934{
2935 RR_DEBUG_INFO_UPDATE_LOC();
2936 RValue<Int> res = val;
John Bauman89401822014-05-06 15:04:28 -04002937
Nicolas Capens157ba262019-12-10 17:49:14 -05002938 Value *inc = Nucleus::createAdd(res.value, Nucleus::createConstantInt(1));
2939 val.storeValue(inc);
John Bauman89401822014-05-06 15:04:28 -04002940
Nicolas Capens157ba262019-12-10 17:49:14 -05002941 return res;
2942}
John Bauman89401822014-05-06 15:04:28 -04002943
Nicolas Capens157ba262019-12-10 17:49:14 -05002944const Int &operator++(Int &val) // Pre-increment
2945{
2946 RR_DEBUG_INFO_UPDATE_LOC();
2947 Value *inc = Nucleus::createAdd(val.loadValue(), Nucleus::createConstantInt(1));
2948 val.storeValue(inc);
John Bauman89401822014-05-06 15:04:28 -04002949
Nicolas Capens157ba262019-12-10 17:49:14 -05002950 return val;
2951}
John Bauman89401822014-05-06 15:04:28 -04002952
Nicolas Capens157ba262019-12-10 17:49:14 -05002953RValue<Int> operator--(Int &val, int) // Post-decrement
2954{
2955 RR_DEBUG_INFO_UPDATE_LOC();
2956 RValue<Int> res = val;
John Bauman89401822014-05-06 15:04:28 -04002957
Nicolas Capens157ba262019-12-10 17:49:14 -05002958 Value *inc = Nucleus::createSub(res.value, Nucleus::createConstantInt(1));
2959 val.storeValue(inc);
John Bauman89401822014-05-06 15:04:28 -04002960
Nicolas Capens157ba262019-12-10 17:49:14 -05002961 return res;
2962}
John Bauman89401822014-05-06 15:04:28 -04002963
Nicolas Capens157ba262019-12-10 17:49:14 -05002964const Int &operator--(Int &val) // Pre-decrement
2965{
2966 RR_DEBUG_INFO_UPDATE_LOC();
2967 Value *inc = Nucleus::createSub(val.loadValue(), Nucleus::createConstantInt(1));
2968 val.storeValue(inc);
John Bauman89401822014-05-06 15:04:28 -04002969
Nicolas Capens157ba262019-12-10 17:49:14 -05002970 return val;
2971}
John Bauman89401822014-05-06 15:04:28 -04002972
Nicolas Capens157ba262019-12-10 17:49:14 -05002973RValue<Int> RoundInt(RValue<Float> cast)
2974{
2975 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08002976#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05002977 return x86::cvtss2si(cast);
Logan Chiene3191012018-08-24 22:01:50 +08002978#else
Nicolas Capens157ba262019-12-10 17:49:14 -05002979 return RValue<Int>(V(lowerRoundInt(V(cast.value), T(Int::getType()))));
Logan Chiene3191012018-08-24 22:01:50 +08002980#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05002981}
John Bauman89401822014-05-06 15:04:28 -04002982
Nicolas Capens157ba262019-12-10 17:49:14 -05002983Type *Int::getType()
2984{
2985 return T(llvm::Type::getInt32Ty(jit->context));
2986}
John Bauman89401822014-05-06 15:04:28 -04002987
Nicolas Capens157ba262019-12-10 17:49:14 -05002988Type *Long::getType()
2989{
2990 return T(llvm::Type::getInt64Ty(jit->context));
2991}
John Bauman89401822014-05-06 15:04:28 -04002992
Nicolas Capens157ba262019-12-10 17:49:14 -05002993UInt::UInt(RValue<Float> cast)
2994{
2995 RR_DEBUG_INFO_UPDATE_LOC();
2996 Value *integer = Nucleus::createFPToUI(cast.value, UInt::getType());
2997 storeValue(integer);
2998}
John Bauman89401822014-05-06 15:04:28 -04002999
Nicolas Capens157ba262019-12-10 17:49:14 -05003000RValue<UInt> operator++(UInt &val, int) // Post-increment
3001{
3002 RR_DEBUG_INFO_UPDATE_LOC();
3003 RValue<UInt> res = val;
John Bauman89401822014-05-06 15:04:28 -04003004
Nicolas Capens157ba262019-12-10 17:49:14 -05003005 Value *inc = Nucleus::createAdd(res.value, Nucleus::createConstantInt(1));
3006 val.storeValue(inc);
John Bauman89401822014-05-06 15:04:28 -04003007
Nicolas Capens157ba262019-12-10 17:49:14 -05003008 return res;
3009}
John Bauman89401822014-05-06 15:04:28 -04003010
Nicolas Capens157ba262019-12-10 17:49:14 -05003011const UInt &operator++(UInt &val) // Pre-increment
3012{
3013 RR_DEBUG_INFO_UPDATE_LOC();
3014 Value *inc = Nucleus::createAdd(val.loadValue(), Nucleus::createConstantInt(1));
3015 val.storeValue(inc);
John Bauman89401822014-05-06 15:04:28 -04003016
Nicolas Capens157ba262019-12-10 17:49:14 -05003017 return val;
3018}
John Bauman89401822014-05-06 15:04:28 -04003019
Nicolas Capens157ba262019-12-10 17:49:14 -05003020RValue<UInt> operator--(UInt &val, int) // Post-decrement
3021{
3022 RR_DEBUG_INFO_UPDATE_LOC();
3023 RValue<UInt> res = val;
John Bauman89401822014-05-06 15:04:28 -04003024
Nicolas Capens157ba262019-12-10 17:49:14 -05003025 Value *inc = Nucleus::createSub(res.value, Nucleus::createConstantInt(1));
3026 val.storeValue(inc);
John Bauman89401822014-05-06 15:04:28 -04003027
Nicolas Capens157ba262019-12-10 17:49:14 -05003028 return res;
3029}
John Bauman89401822014-05-06 15:04:28 -04003030
Nicolas Capens157ba262019-12-10 17:49:14 -05003031const UInt &operator--(UInt &val) // Pre-decrement
3032{
3033 RR_DEBUG_INFO_UPDATE_LOC();
3034 Value *inc = Nucleus::createSub(val.loadValue(), Nucleus::createConstantInt(1));
3035 val.storeValue(inc);
John Bauman89401822014-05-06 15:04:28 -04003036
Nicolas Capens157ba262019-12-10 17:49:14 -05003037 return val;
3038}
John Bauman89401822014-05-06 15:04:28 -04003039
John Bauman19bac1e2014-05-06 15:23:49 -04003040// RValue<UInt> RoundUInt(RValue<Float> cast)
John Bauman89401822014-05-06 15:04:28 -04003041// {
Logan Chiene3191012018-08-24 22:01:50 +08003042//#if defined(__i386__) || defined(__x86_64__)
John Bauman89401822014-05-06 15:04:28 -04003043// return x86::cvtss2si(val); // FIXME: Unsigned
Logan Chiene3191012018-08-24 22:01:50 +08003044//#else
3045// return IfThenElse(cast > 0.0f, Int(cast + 0.5f), Int(cast - 0.5f));
3046//#endif
John Bauman89401822014-05-06 15:04:28 -04003047// }
3048
Nicolas Capens157ba262019-12-10 17:49:14 -05003049Type *UInt::getType()
3050{
3051 return T(llvm::Type::getInt32Ty(jit->context));
3052}
John Bauman89401822014-05-06 15:04:28 -04003053
John Bauman19bac1e2014-05-06 15:23:49 -04003054// Int2::Int2(RValue<Int> cast)
3055// {
John Bauman19bac1e2014-05-06 15:23:49 -04003056// Value *extend = Nucleus::createZExt(cast.value, Long::getType());
3057// Value *vector = Nucleus::createBitCast(extend, Int2::getType());
John Bauman66b8ab22014-05-06 15:57:45 -04003058//
Nicolas Capense89cd582016-09-30 14:23:47 -04003059// int shuffle[2] = {0, 0};
3060// Value *replicate = Nucleus::createShuffleVector(vector, vector, shuffle);
John Bauman19bac1e2014-05-06 15:23:49 -04003061//
John Bauman66b8ab22014-05-06 15:57:45 -04003062// storeValue(replicate);
John Bauman19bac1e2014-05-06 15:23:49 -04003063// }
John Bauman89401822014-05-06 15:04:28 -04003064
Nicolas Capens157ba262019-12-10 17:49:14 -05003065RValue<Int2> operator<<(RValue<Int2> lhs, unsigned char rhs)
3066{
3067 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08003068#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05003069// return RValue<Int2>(Nucleus::createShl(lhs.value, rhs.value));
John Bauman89401822014-05-06 15:04:28 -04003070
Nicolas Capens157ba262019-12-10 17:49:14 -05003071 return x86::pslld(lhs, rhs);
Logan Chiene3191012018-08-24 22:01:50 +08003072#else
Nicolas Capens157ba262019-12-10 17:49:14 -05003073 return As<Int2>(V(lowerVectorShl(V(lhs.value), rhs)));
Logan Chiene3191012018-08-24 22:01:50 +08003074#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05003075}
John Bauman89401822014-05-06 15:04:28 -04003076
Nicolas Capens157ba262019-12-10 17:49:14 -05003077RValue<Int2> operator>>(RValue<Int2> lhs, unsigned char rhs)
3078{
3079 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08003080#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05003081// return RValue<Int2>(Nucleus::createAShr(lhs.value, rhs.value));
John Bauman89401822014-05-06 15:04:28 -04003082
Nicolas Capens157ba262019-12-10 17:49:14 -05003083 return x86::psrad(lhs, rhs);
Logan Chiene3191012018-08-24 22:01:50 +08003084#else
Nicolas Capens157ba262019-12-10 17:49:14 -05003085 return As<Int2>(V(lowerVectorAShr(V(lhs.value), rhs)));
Logan Chiene3191012018-08-24 22:01:50 +08003086#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05003087}
John Bauman89401822014-05-06 15:04:28 -04003088
Nicolas Capens157ba262019-12-10 17:49:14 -05003089Type *Int2::getType()
3090{
3091 return T(Type_v2i32);
3092}
John Bauman89401822014-05-06 15:04:28 -04003093
Nicolas Capens157ba262019-12-10 17:49:14 -05003094RValue<UInt2> operator<<(RValue<UInt2> lhs, unsigned char rhs)
3095{
3096 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08003097#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05003098// return RValue<UInt2>(Nucleus::createShl(lhs.value, rhs.value));
John Bauman89401822014-05-06 15:04:28 -04003099
Nicolas Capens157ba262019-12-10 17:49:14 -05003100 return As<UInt2>(x86::pslld(As<Int2>(lhs), rhs));
Logan Chiene3191012018-08-24 22:01:50 +08003101#else
Nicolas Capens157ba262019-12-10 17:49:14 -05003102 return As<UInt2>(V(lowerVectorShl(V(lhs.value), rhs)));
Logan Chiene3191012018-08-24 22:01:50 +08003103#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05003104}
John Bauman89401822014-05-06 15:04:28 -04003105
Nicolas Capens157ba262019-12-10 17:49:14 -05003106RValue<UInt2> operator>>(RValue<UInt2> lhs, unsigned char rhs)
3107{
3108 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08003109#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05003110// return RValue<UInt2>(Nucleus::createLShr(lhs.value, rhs.value));
John Bauman89401822014-05-06 15:04:28 -04003111
Nicolas Capens157ba262019-12-10 17:49:14 -05003112 return x86::psrld(lhs, rhs);
Logan Chiene3191012018-08-24 22:01:50 +08003113#else
Nicolas Capens157ba262019-12-10 17:49:14 -05003114 return As<UInt2>(V(lowerVectorLShr(V(lhs.value), rhs)));
Logan Chiene3191012018-08-24 22:01:50 +08003115#endif
Nicolas Capens157ba262019-12-10 17:49:14 -05003116}
John Bauman89401822014-05-06 15:04:28 -04003117
Nicolas Capens157ba262019-12-10 17:49:14 -05003118Type *UInt2::getType()
3119{
3120 return T(Type_v2i32);
3121}
John Bauman89401822014-05-06 15:04:28 -04003122
Nicolas Capens157ba262019-12-10 17:49:14 -05003123Int4::Int4(RValue<Byte4> cast) : XYZW(this)
3124{
3125 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08003126#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05003127 if(CPUID::supportsSSE4_1())
3128 {
3129 *this = x86::pmovzxbd(As<Byte16>(cast));
3130 }
3131 else
Logan Chiene3191012018-08-24 22:01:50 +08003132#endif
Meng-Lin Wu601d0052016-06-10 14:18:41 -04003133 {
Nicolas Capens157ba262019-12-10 17:49:14 -05003134 int swizzle[16] = {0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23};
3135 Value *a = Nucleus::createBitCast(cast.value, Byte16::getType());
3136 Value *b = Nucleus::createShuffleVector(a, Nucleus::createNullValue(Byte16::getType()), swizzle);
Meng-Lin Wu601d0052016-06-10 14:18:41 -04003137
Nicolas Capens157ba262019-12-10 17:49:14 -05003138 int swizzle2[8] = {0, 8, 1, 9, 2, 10, 3, 11};
3139 Value *c = Nucleus::createBitCast(b, Short8::getType());
3140 Value *d = Nucleus::createShuffleVector(c, Nucleus::createNullValue(Short8::getType()), swizzle2);
Meng-Lin Wu601d0052016-06-10 14:18:41 -04003141
Nicolas Capens157ba262019-12-10 17:49:14 -05003142 *this = As<Int4>(d);
Nicolas Capens9770a462019-06-25 10:47:10 -04003143 }
John Bauman89401822014-05-06 15:04:28 -04003144}
3145
Nicolas Capens157ba262019-12-10 17:49:14 -05003146Int4::Int4(RValue<SByte4> cast) : XYZW(this)
John Bauman89401822014-05-06 15:04:28 -04003147{
Nicolas Capens157ba262019-12-10 17:49:14 -05003148 RR_DEBUG_INFO_UPDATE_LOC();
Logan Chiene3191012018-08-24 22:01:50 +08003149#if defined(__i386__) || defined(__x86_64__)
Nicolas Capens157ba262019-12-10 17:49:14 -05003150 if(CPUID::supportsSSE4_1())
John Bauman89401822014-05-06 15:04:28 -04003151 {
Nicolas Capens157ba262019-12-10 17:49:14 -05003152 *this = x86::pmovsxbd(As<SByte16>(cast));
John Bauman89401822014-05-06 15:04:28 -04003153 }
Nicolas Capens157ba262019-12-10 17:49:14 -05003154 else
3155#endif
3156 {
3157 int swizzle[16] = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7};
3158 Value *a = Nucleus::createBitCast(cast.value, Byte16::getType());
3159 Value *b = Nucleus::createShuffleVector(a, a, swizzle);
3160
3161 int swizzle2[8] = {0, 0, 1, 1, 2, 2, 3, 3};
3162 Value *c = Nucleus::createBitCast(b, Short8::getType());
3163 Value *d = Nucleus::createShuffleVector(c, c, swizzle2);
3164
3165 *this = As<Int4>(d) >> 24;
3166 }
3167}
3168
3169Int4::Int4(RValue<Short4> cast) : XYZW(this)
3170{
3171 RR_DEBUG_INFO_UPDATE_LOC();
3172#if defined(__i386__) || defined(__x86_64__)
3173 if(CPUID::supportsSSE4_1())
3174 {
3175 *this = x86::pmovsxwd(As<Short8>(cast));
3176 }
3177 else
3178#endif
3179 {
3180 int swizzle[8] = {0, 0, 1, 1, 2, 2, 3, 3};
3181 Value *c = Nucleus::createShuffleVector(cast.value, cast.value, swizzle);
3182 *this = As<Int4>(c) >> 16;
3183 }
3184}
3185
3186Int4::Int4(RValue<UShort4> cast) : XYZW(this)
3187{
3188 RR_DEBUG_INFO_UPDATE_LOC();
3189#if defined(__i386__) || defined(__x86_64__)
3190 if(CPUID::supportsSSE4_1())
3191 {
3192 *this = x86::pmovzxwd(As<UShort8>(cast));
3193 }
3194 else
3195#endif
3196 {
3197 int swizzle[8] = {0, 8, 1, 9, 2, 10, 3, 11};
3198 Value *c = Nucleus::createShuffleVector(cast.value, Short8(0, 0, 0, 0, 0, 0, 0, 0).loadValue(), swizzle);
3199 *this = As<Int4>(c);
3200 }
3201}
3202
3203Int4::Int4(RValue<Int> rhs) : XYZW(this)
3204{
3205 RR_DEBUG_INFO_UPDATE_LOC();
3206 Value *vector = loadValue();
3207 Value *insert = Nucleus::createInsertElement(vector, rhs.value, 0);
3208
3209 int swizzle[4] = {0, 0, 0, 0};
3210 Value *replicate = Nucleus::createShuffleVector(insert, insert, swizzle);
3211
3212 storeValue(replicate);
3213}
3214
3215RValue<Int4> operator<<(RValue<Int4> lhs, unsigned char rhs)
3216{
3217 RR_DEBUG_INFO_UPDATE_LOC();
3218#if defined(__i386__) || defined(__x86_64__)
3219 return x86::pslld(lhs, rhs);
3220#else
3221 return As<Int4>(V(lowerVectorShl(V(lhs.value), rhs)));
3222#endif
3223}
3224
3225RValue<Int4> operator>>(RValue<Int4> lhs, unsigned char rhs)
3226{
3227 RR_DEBUG_INFO_UPDATE_LOC();
3228#if defined(__i386__) || defined(__x86_64__)
3229 return x86::psrad(lhs, rhs);
3230#else
3231 return As<Int4>(V(lowerVectorAShr(V(lhs.value), rhs)));
3232#endif
3233}
3234
3235RValue<Int4> CmpEQ(RValue<Int4> x, RValue<Int4> y)
3236{
3237 RR_DEBUG_INFO_UPDATE_LOC();
3238 return RValue<Int4>(Nucleus::createSExt(Nucleus::createICmpEQ(x.value, y.value), Int4::getType()));
3239}
3240
3241RValue<Int4> CmpLT(RValue<Int4> x, RValue<Int4> y)
3242{
3243 RR_DEBUG_INFO_UPDATE_LOC();
3244 return RValue<Int4>(Nucleus::createSExt(Nucleus::createICmpSLT(x.value, y.value), Int4::getType()));
3245}
3246
3247RValue<Int4> CmpLE(RValue<Int4> x, RValue<Int4> y)
3248{
3249 RR_DEBUG_INFO_UPDATE_LOC();
3250 return RValue<Int4>(Nucleus::createSExt(Nucleus::createICmpSLE(x.value, y.value), Int4::getType()));
3251}
3252
3253RValue<Int4> CmpNEQ(RValue<Int4> x, RValue<Int4> y)
3254{
3255 RR_DEBUG_INFO_UPDATE_LOC();
3256 return RValue<Int4>(Nucleus::createSExt(Nucleus::createICmpNE(x.value, y.value), Int4::getType()));
3257}
3258
3259RValue<Int4> CmpNLT(RValue<Int4> x, RValue<Int4> y)
3260{
3261 RR_DEBUG_INFO_UPDATE_LOC();
3262 return RValue<Int4>(Nucleus::createSExt(Nucleus::createICmpSGE(x.value, y.value), Int4::getType()));
3263}
3264
3265RValue<Int4> CmpNLE(RValue<Int4> x, RValue<Int4> y)
3266{
3267 RR_DEBUG_INFO_UPDATE_LOC();
3268 return RValue<Int4>(Nucleus::createSExt(Nucleus::createICmpSGT(x.value, y.value), Int4::getType()));
3269}
3270
3271RValue<Int4> Max(RValue<Int4> x, RValue<Int4> y)
3272{
3273 RR_DEBUG_INFO_UPDATE_LOC();
3274#if defined(__i386__) || defined(__x86_64__)
3275 if(CPUID::supportsSSE4_1())
3276 {
3277 return x86::pmaxsd(x, y);
3278 }
3279 else
3280#endif
3281 {
3282 RValue<Int4> greater = CmpNLE(x, y);
3283 return (x & greater) | (y & ~greater);
3284 }
3285}
3286
3287RValue<Int4> Min(RValue<Int4> x, RValue<Int4> y)
3288{
3289 RR_DEBUG_INFO_UPDATE_LOC();
3290#if defined(__i386__) || defined(__x86_64__)
3291 if(CPUID::supportsSSE4_1())
3292 {
3293 return x86::pminsd(x, y);
3294 }
3295 else
3296#endif
3297 {
3298 RValue<Int4> less = CmpLT(x, y);
3299 return (x & less) | (y & ~less);
3300 }
3301}
3302
3303RValue<Int4> RoundInt(RValue<Float4> cast)
3304{
3305 RR_DEBUG_INFO_UPDATE_LOC();
3306#if defined(__i386__) || defined(__x86_64__)
3307 return x86::cvtps2dq(cast);
3308#else
3309 return As<Int4>(V(lowerRoundInt(V(cast.value), T(Int4::getType()))));
3310#endif
3311}
3312
3313RValue<Int4> MulHigh(RValue<Int4> x, RValue<Int4> y)
3314{
3315 RR_DEBUG_INFO_UPDATE_LOC();
3316 // TODO: For x86, build an intrinsics version of this which uses shuffles + pmuludq.
3317 return As<Int4>(V(lowerMulHigh(V(x.value), V(y.value), true)));
3318}
3319
3320RValue<UInt4> MulHigh(RValue<UInt4> x, RValue<UInt4> y)
3321{
3322 RR_DEBUG_INFO_UPDATE_LOC();
3323 // TODO: For x86, build an intrinsics version of this which uses shuffles + pmuludq.
3324 return As<UInt4>(V(lowerMulHigh(V(x.value), V(y.value), false)));
3325}
3326
3327RValue<Short8> PackSigned(RValue<Int4> x, RValue<Int4> y)
3328{
3329 RR_DEBUG_INFO_UPDATE_LOC();
3330#if defined(__i386__) || defined(__x86_64__)
3331 return x86::packssdw(x, y);
3332#else
3333 return As<Short8>(V(lowerPack(V(x.value), V(y.value), true)));
3334#endif
3335}
3336
3337RValue<UShort8> PackUnsigned(RValue<Int4> x, RValue<Int4> y)
3338{
3339 RR_DEBUG_INFO_UPDATE_LOC();
3340#if defined(__i386__) || defined(__x86_64__)
3341 return x86::packusdw(x, y);
3342#else
3343 return As<UShort8>(V(lowerPack(V(x.value), V(y.value), false)));
3344#endif
3345}
3346
3347RValue<Int> SignMask(RValue<Int4> x)
3348{
3349 RR_DEBUG_INFO_UPDATE_LOC();
3350#if defined(__i386__) || defined(__x86_64__)
3351 return x86::movmskps(As<Float4>(x));
3352#else
3353 return As<Int>(V(lowerSignMask(V(x.value), T(Int::getType()))));
3354#endif
3355}
3356
3357Type *Int4::getType()
3358{
3359 return T(llvm::VectorType::get(T(Int::getType()), 4));
3360}
3361
3362UInt4::UInt4(RValue<Float4> cast) : XYZW(this)
3363{
3364 RR_DEBUG_INFO_UPDATE_LOC();
3365 Value *xyzw = Nucleus::createFPToUI(cast.value, UInt4::getType());
3366 storeValue(xyzw);
3367}
3368
3369UInt4::UInt4(RValue<UInt> rhs) : XYZW(this)
3370{
3371 RR_DEBUG_INFO_UPDATE_LOC();
3372 Value *vector = loadValue();
3373 Value *insert = Nucleus::createInsertElement(vector, rhs.value, 0);
3374
3375 int swizzle[4] = {0, 0, 0, 0};
3376 Value *replicate = Nucleus::createShuffleVector(insert, insert, swizzle);
3377
3378 storeValue(replicate);
3379}
3380
3381RValue<UInt4> operator<<(RValue<UInt4> lhs, unsigned char rhs)
3382{
3383 RR_DEBUG_INFO_UPDATE_LOC();
3384#if defined(__i386__) || defined(__x86_64__)
3385 return As<UInt4>(x86::pslld(As<Int4>(lhs), rhs));
3386#else
3387 return As<UInt4>(V(lowerVectorShl(V(lhs.value), rhs)));
3388#endif
3389}
3390
3391RValue<UInt4> operator>>(RValue<UInt4> lhs, unsigned char rhs)
3392{
3393 RR_DEBUG_INFO_UPDATE_LOC();
3394#if defined(__i386__) || defined(__x86_64__)
3395 return x86::psrld(lhs, rhs);
3396#else
3397 return As<UInt4>(V(lowerVectorLShr(V(lhs.value), rhs)));
3398#endif
3399}
3400
3401RValue<UInt4> CmpEQ(RValue<UInt4> x, RValue<UInt4> y)
3402{
3403 RR_DEBUG_INFO_UPDATE_LOC();
3404 return RValue<UInt4>(Nucleus::createSExt(Nucleus::createICmpEQ(x.value, y.value), Int4::getType()));
3405}
3406
3407RValue<UInt4> CmpLT(RValue<UInt4> x, RValue<UInt4> y)
3408{
3409 RR_DEBUG_INFO_UPDATE_LOC();
3410 return RValue<UInt4>(Nucleus::createSExt(Nucleus::createICmpULT(x.value, y.value), Int4::getType()));
3411}
3412
3413RValue<UInt4> CmpLE(RValue<UInt4> x, RValue<UInt4> y)
3414{
3415 RR_DEBUG_INFO_UPDATE_LOC();
3416 return RValue<UInt4>(Nucleus::createSExt(Nucleus::createICmpULE(x.value, y.value), Int4::getType()));
3417}
3418
3419RValue<UInt4> CmpNEQ(RValue<UInt4> x, RValue<UInt4> y)
3420{
3421 RR_DEBUG_INFO_UPDATE_LOC();
3422 return RValue<UInt4>(Nucleus::createSExt(Nucleus::createICmpNE(x.value, y.value), Int4::getType()));
3423}
3424
3425RValue<UInt4> CmpNLT(RValue<UInt4> x, RValue<UInt4> y)
3426{
3427 RR_DEBUG_INFO_UPDATE_LOC();
3428 return RValue<UInt4>(Nucleus::createSExt(Nucleus::createICmpUGE(x.value, y.value), Int4::getType()));
3429}
3430
3431RValue<UInt4> CmpNLE(RValue<UInt4> x, RValue<UInt4> y)
3432{
3433 RR_DEBUG_INFO_UPDATE_LOC();
3434 return RValue<UInt4>(Nucleus::createSExt(Nucleus::createICmpUGT(x.value, y.value), Int4::getType()));
3435}
3436
3437RValue<UInt4> Max(RValue<UInt4> x, RValue<UInt4> y)
3438{
3439 RR_DEBUG_INFO_UPDATE_LOC();
3440#if defined(__i386__) || defined(__x86_64__)
3441 if(CPUID::supportsSSE4_1())
3442 {
3443 return x86::pmaxud(x, y);
3444 }
3445 else
3446#endif
3447 {
3448 RValue<UInt4> greater = CmpNLE(x, y);
3449 return (x & greater) | (y & ~greater);
3450 }
3451}
3452
3453RValue<UInt4> Min(RValue<UInt4> x, RValue<UInt4> y)
3454{
3455 RR_DEBUG_INFO_UPDATE_LOC();
3456#if defined(__i386__) || defined(__x86_64__)
3457 if(CPUID::supportsSSE4_1())
3458 {
3459 return x86::pminud(x, y);
3460 }
3461 else
3462#endif
3463 {
3464 RValue<UInt4> less = CmpLT(x, y);
3465 return (x & less) | (y & ~less);
3466 }
3467}
3468
3469Type *UInt4::getType()
3470{
3471 return T(llvm::VectorType::get(T(UInt::getType()), 4));
3472}
3473
3474Type *Half::getType()
3475{
3476 return T(llvm::Type::getInt16Ty(jit->context));
3477}
3478
3479RValue<Float> Rcp_pp(RValue<Float> x, bool exactAtPow2)
3480{
3481 RR_DEBUG_INFO_UPDATE_LOC();
3482#if defined(__i386__) || defined(__x86_64__)
3483 if(exactAtPow2)
3484 {
3485 // rcpss uses a piecewise-linear approximation which minimizes the relative error
3486 // but is not exact at power-of-two values. Rectify by multiplying by the inverse.
3487 return x86::rcpss(x) * Float(1.0f / _mm_cvtss_f32(_mm_rcp_ss(_mm_set_ps1(1.0f))));
3488 }
3489 return x86::rcpss(x);
3490#else
3491 return As<Float>(V(lowerRCP(V(x.value))));
3492#endif
3493}
3494
3495RValue<Float> RcpSqrt_pp(RValue<Float> x)
3496{
3497 RR_DEBUG_INFO_UPDATE_LOC();
3498#if defined(__i386__) || defined(__x86_64__)
3499 return x86::rsqrtss(x);
3500#else
3501 return As<Float>(V(lowerRSQRT(V(x.value))));
3502#endif
3503}
3504
3505RValue<Float> Sqrt(RValue<Float> x)
3506{
3507 RR_DEBUG_INFO_UPDATE_LOC();
3508#if defined(__i386__) || defined(__x86_64__)
3509 return x86::sqrtss(x);
3510#else
3511 return As<Float>(V(lowerSQRT(V(x.value))));
3512#endif
3513}
3514
3515RValue<Float> Round(RValue<Float> x)
3516{
3517 RR_DEBUG_INFO_UPDATE_LOC();
3518#if defined(__i386__) || defined(__x86_64__)
3519 if(CPUID::supportsSSE4_1())
3520 {
3521 return x86::roundss(x, 0);
3522 }
3523 else
3524 {
3525 return Float4(Round(Float4(x))).x;
3526 }
3527#else
3528 return RValue<Float>(V(lowerRound(V(x.value))));
3529#endif
3530}
3531
3532RValue<Float> Trunc(RValue<Float> x)
3533{
3534 RR_DEBUG_INFO_UPDATE_LOC();
3535#if defined(__i386__) || defined(__x86_64__)
3536 if(CPUID::supportsSSE4_1())
3537 {
3538 return x86::roundss(x, 3);
3539 }
3540 else
3541 {
3542 return Float(Int(x)); // Rounded toward zero
3543 }
3544#else
3545 return RValue<Float>(V(lowerTrunc(V(x.value))));
3546#endif
3547}
3548
3549RValue<Float> Frac(RValue<Float> x)
3550{
3551 RR_DEBUG_INFO_UPDATE_LOC();
3552#if defined(__i386__) || defined(__x86_64__)
3553 if(CPUID::supportsSSE4_1())
3554 {
3555 return x - x86::floorss(x);
3556 }
3557 else
3558 {
3559 return Float4(Frac(Float4(x))).x;
3560 }
3561#else
3562 // x - floor(x) can be 1.0 for very small negative x.
3563 // Clamp against the value just below 1.0.
3564 return Min(x - Floor(x), As<Float>(Int(0x3F7FFFFF)));
3565#endif
3566}
3567
3568RValue<Float> Floor(RValue<Float> x)
3569{
3570 RR_DEBUG_INFO_UPDATE_LOC();
3571#if defined(__i386__) || defined(__x86_64__)
3572 if(CPUID::supportsSSE4_1())
3573 {
3574 return x86::floorss(x);
3575 }
3576 else
3577 {
3578 return Float4(Floor(Float4(x))).x;
3579 }
3580#else
3581 return RValue<Float>(V(lowerFloor(V(x.value))));
3582#endif
3583}
3584
3585RValue<Float> Ceil(RValue<Float> x)
3586{
3587 RR_DEBUG_INFO_UPDATE_LOC();
3588#if defined(__i386__) || defined(__x86_64__)
3589 if(CPUID::supportsSSE4_1())
3590 {
3591 return x86::ceilss(x);
3592 }
3593 else
3594#endif
3595 {
3596 return Float4(Ceil(Float4(x))).x;
3597 }
3598}
3599
3600Type *Float::getType()
3601{
3602 return T(llvm::Type::getFloatTy(jit->context));
3603}
3604
3605Type *Float2::getType()
3606{
3607 return T(Type_v2f32);
3608}
3609
3610RValue<Float> Exp2(RValue<Float> v)
3611{
3612 auto func = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::exp2, { T(Float::getType()) } );
3613 return RValue<Float>(V(jit->builder->CreateCall(func, V(v.value))));
3614}
3615
3616RValue<Float> Log2(RValue<Float> v)
3617{
3618 auto func = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::log2, { T(Float::getType()) } );
3619 return RValue<Float>(V(jit->builder->CreateCall(func, V(v.value))));
3620}
3621
3622Float4::Float4(RValue<Float> rhs) : XYZW(this)
3623{
3624 RR_DEBUG_INFO_UPDATE_LOC();
3625 Value *vector = loadValue();
3626 Value *insert = Nucleus::createInsertElement(vector, rhs.value, 0);
3627
3628 int swizzle[4] = {0, 0, 0, 0};
3629 Value *replicate = Nucleus::createShuffleVector(insert, insert, swizzle);
3630
3631 storeValue(replicate);
3632}
3633
3634RValue<Float4> Max(RValue<Float4> x, RValue<Float4> y)
3635{
3636 RR_DEBUG_INFO_UPDATE_LOC();
3637#if defined(__i386__) || defined(__x86_64__)
3638 return x86::maxps(x, y);
3639#else
3640 return As<Float4>(V(lowerPFMINMAX(V(x.value), V(y.value), llvm::FCmpInst::FCMP_OGT)));
3641#endif
3642}
3643
3644RValue<Float4> Min(RValue<Float4> x, RValue<Float4> y)
3645{
3646 RR_DEBUG_INFO_UPDATE_LOC();
3647#if defined(__i386__) || defined(__x86_64__)
3648 return x86::minps(x, y);
3649#else
3650 return As<Float4>(V(lowerPFMINMAX(V(x.value), V(y.value), llvm::FCmpInst::FCMP_OLT)));
3651#endif
3652}
3653
3654RValue<Float4> Rcp_pp(RValue<Float4> x, bool exactAtPow2)
3655{
3656 RR_DEBUG_INFO_UPDATE_LOC();
3657#if defined(__i386__) || defined(__x86_64__)
3658 if(exactAtPow2)
3659 {
3660 // rcpps uses a piecewise-linear approximation which minimizes the relative error
3661 // but is not exact at power-of-two values. Rectify by multiplying by the inverse.
3662 return x86::rcpps(x) * Float4(1.0f / _mm_cvtss_f32(_mm_rcp_ss(_mm_set_ps1(1.0f))));
3663 }
3664 return x86::rcpps(x);
3665#else
3666 return As<Float4>(V(lowerRCP(V(x.value))));
3667#endif
3668}
3669
3670RValue<Float4> RcpSqrt_pp(RValue<Float4> x)
3671{
3672 RR_DEBUG_INFO_UPDATE_LOC();
3673#if defined(__i386__) || defined(__x86_64__)
3674 return x86::rsqrtps(x);
3675#else
3676 return As<Float4>(V(lowerRSQRT(V(x.value))));
3677#endif
3678}
3679
3680RValue<Float4> Sqrt(RValue<Float4> x)
3681{
3682 RR_DEBUG_INFO_UPDATE_LOC();
3683#if defined(__i386__) || defined(__x86_64__)
3684 return x86::sqrtps(x);
3685#else
3686 return As<Float4>(V(lowerSQRT(V(x.value))));
3687#endif
3688}
3689
3690RValue<Int> SignMask(RValue<Float4> x)
3691{
3692 RR_DEBUG_INFO_UPDATE_LOC();
3693#if defined(__i386__) || defined(__x86_64__)
3694 return x86::movmskps(x);
3695#else
3696 return As<Int>(V(lowerFPSignMask(V(x.value), T(Int::getType()))));
3697#endif
3698}
3699
3700RValue<Int4> CmpEQ(RValue<Float4> x, RValue<Float4> y)
3701{
3702 RR_DEBUG_INFO_UPDATE_LOC();
3703// return As<Int4>(x86::cmpeqps(x, y));
3704 return RValue<Int4>(Nucleus::createSExt(Nucleus::createFCmpOEQ(x.value, y.value), Int4::getType()));
3705}
3706
3707RValue<Int4> CmpLT(RValue<Float4> x, RValue<Float4> y)
3708{
3709 RR_DEBUG_INFO_UPDATE_LOC();
3710// return As<Int4>(x86::cmpltps(x, y));
3711 return RValue<Int4>(Nucleus::createSExt(Nucleus::createFCmpOLT(x.value, y.value), Int4::getType()));
3712}
3713
3714RValue<Int4> CmpLE(RValue<Float4> x, RValue<Float4> y)
3715{
3716 RR_DEBUG_INFO_UPDATE_LOC();
3717// return As<Int4>(x86::cmpleps(x, y));
3718 return RValue<Int4>(Nucleus::createSExt(Nucleus::createFCmpOLE(x.value, y.value), Int4::getType()));
3719}
3720
3721RValue<Int4> CmpNEQ(RValue<Float4> x, RValue<Float4> y)
3722{
3723 RR_DEBUG_INFO_UPDATE_LOC();
3724// return As<Int4>(x86::cmpneqps(x, y));
3725 return RValue<Int4>(Nucleus::createSExt(Nucleus::createFCmpONE(x.value, y.value), Int4::getType()));
3726}
3727
3728RValue<Int4> CmpNLT(RValue<Float4> x, RValue<Float4> y)
3729{
3730 RR_DEBUG_INFO_UPDATE_LOC();
3731// return As<Int4>(x86::cmpnltps(x, y));
3732 return RValue<Int4>(Nucleus::createSExt(Nucleus::createFCmpOGE(x.value, y.value), Int4::getType()));
3733}
3734
3735RValue<Int4> CmpNLE(RValue<Float4> x, RValue<Float4> y)
3736{
3737 RR_DEBUG_INFO_UPDATE_LOC();
3738// return As<Int4>(x86::cmpnleps(x, y));
3739 return RValue<Int4>(Nucleus::createSExt(Nucleus::createFCmpOGT(x.value, y.value), Int4::getType()));
3740}
3741
3742RValue<Int4> CmpUEQ(RValue<Float4> x, RValue<Float4> y)
3743{
3744 RR_DEBUG_INFO_UPDATE_LOC();
3745 return RValue<Int4>(Nucleus::createSExt(Nucleus::createFCmpUEQ(x.value, y.value), Int4::getType()));
3746}
3747
3748RValue<Int4> CmpULT(RValue<Float4> x, RValue<Float4> y)
3749{
3750 RR_DEBUG_INFO_UPDATE_LOC();
3751 return RValue<Int4>(Nucleus::createSExt(Nucleus::createFCmpULT(x.value, y.value), Int4::getType()));
3752}
3753
3754RValue<Int4> CmpULE(RValue<Float4> x, RValue<Float4> y)
3755{
3756 RR_DEBUG_INFO_UPDATE_LOC();
3757 return RValue<Int4>(Nucleus::createSExt(Nucleus::createFCmpULE(x.value, y.value), Int4::getType()));
3758}
3759
3760RValue<Int4> CmpUNEQ(RValue<Float4> x, RValue<Float4> y)
3761{
3762 RR_DEBUG_INFO_UPDATE_LOC();
3763 return RValue<Int4>(Nucleus::createSExt(Nucleus::createFCmpUNE(x.value, y.value), Int4::getType()));
3764}
3765
3766RValue<Int4> CmpUNLT(RValue<Float4> x, RValue<Float4> y)
3767{
3768 RR_DEBUG_INFO_UPDATE_LOC();
3769 return RValue<Int4>(Nucleus::createSExt(Nucleus::createFCmpUGE(x.value, y.value), Int4::getType()));
3770}
3771
3772RValue<Int4> CmpUNLE(RValue<Float4> x, RValue<Float4> y)
3773{
3774 RR_DEBUG_INFO_UPDATE_LOC();
3775 return RValue<Int4>(Nucleus::createSExt(Nucleus::createFCmpUGT(x.value, y.value), Int4::getType()));
3776}
3777
3778RValue<Float4> Round(RValue<Float4> x)
3779{
3780 RR_DEBUG_INFO_UPDATE_LOC();
3781#if defined(__i386__) || defined(__x86_64__)
3782 if(CPUID::supportsSSE4_1())
3783 {
3784 return x86::roundps(x, 0);
3785 }
3786 else
3787 {
3788 return Float4(RoundInt(x));
3789 }
3790#else
3791 return RValue<Float4>(V(lowerRound(V(x.value))));
3792#endif
3793}
3794
3795RValue<Float4> Trunc(RValue<Float4> x)
3796{
3797 RR_DEBUG_INFO_UPDATE_LOC();
3798#if defined(__i386__) || defined(__x86_64__)
3799 if(CPUID::supportsSSE4_1())
3800 {
3801 return x86::roundps(x, 3);
3802 }
3803 else
3804 {
3805 return Float4(Int4(x));
3806 }
3807#else
3808 return RValue<Float4>(V(lowerTrunc(V(x.value))));
3809#endif
3810}
3811
3812RValue<Float4> Frac(RValue<Float4> x)
3813{
3814 RR_DEBUG_INFO_UPDATE_LOC();
3815 Float4 frc;
3816
3817#if defined(__i386__) || defined(__x86_64__)
3818 if(CPUID::supportsSSE4_1())
3819 {
3820 frc = x - Floor(x);
3821 }
3822 else
3823 {
3824 frc = x - Float4(Int4(x)); // Signed fractional part.
3825
3826 frc += As<Float4>(As<Int4>(CmpNLE(Float4(0.0f), frc)) & As<Int4>(Float4(1.0f))); // Add 1.0 if negative.
3827 }
3828#else
3829 frc = x - Floor(x);
3830#endif
3831
3832 // x - floor(x) can be 1.0 for very small negative x.
3833 // Clamp against the value just below 1.0.
3834 return Min(frc, As<Float4>(Int4(0x3F7FFFFF)));
3835}
3836
3837RValue<Float4> Floor(RValue<Float4> x)
3838{
3839 RR_DEBUG_INFO_UPDATE_LOC();
3840#if defined(__i386__) || defined(__x86_64__)
3841 if(CPUID::supportsSSE4_1())
3842 {
3843 return x86::floorps(x);
3844 }
3845 else
3846 {
3847 return x - Frac(x);
3848 }
3849#else
3850 return RValue<Float4>(V(lowerFloor(V(x.value))));
3851#endif
3852}
3853
3854RValue<Float4> Ceil(RValue<Float4> x)
3855{
3856 RR_DEBUG_INFO_UPDATE_LOC();
3857#if defined(__i386__) || defined(__x86_64__)
3858 if(CPUID::supportsSSE4_1())
3859 {
3860 return x86::ceilps(x);
3861 }
3862 else
3863#endif
3864 {
3865 return -Floor(-x);
3866 }
3867}
3868
3869RValue<Float4> Sin(RValue<Float4> v)
3870{
3871 auto func = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::sin, { V(v.value)->getType() } );
3872 return RValue<Float4>(V(jit->builder->CreateCall(func, V(v.value))));
3873}
3874
3875RValue<Float4> Cos(RValue<Float4> v)
3876{
3877 auto func = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::cos, { V(v.value)->getType() } );
3878 return RValue<Float4>(V(jit->builder->CreateCall(func, V(v.value))));
3879}
3880
3881RValue<Float4> Tan(RValue<Float4> v)
3882{
3883 return Sin(v) / Cos(v);
3884}
3885
3886static RValue<Float4> TransformFloat4PerElement(RValue<Float4> v, const char* name)
3887{
3888 auto funcTy = ::llvm::FunctionType::get(T(Float::getType()), ::llvm::ArrayRef<llvm::Type*>(T(Float::getType())), false);
3889 auto func = jit->module->getOrInsertFunction(name, funcTy);
3890 llvm::Value *out = ::llvm::UndefValue::get(T(Float4::getType()));
Nicolas Capens81bc9d92019-12-16 15:05:57 -05003891 for(uint64_t i = 0; i < 4; i++)
Nicolas Capens157ba262019-12-10 17:49:14 -05003892 {
3893 auto el = jit->builder->CreateCall(func, V(Nucleus::createExtractElement(v.value, Float::getType(), i)));
3894 out = V(Nucleus::createInsertElement(V(out), V(el), i));
3895 }
3896 return RValue<Float4>(V(out));
3897}
3898
3899RValue<Float4> Asin(RValue<Float4> v)
3900{
3901 return TransformFloat4PerElement(v, "asinf");
3902}
3903
3904RValue<Float4> Acos(RValue<Float4> v)
3905{
3906 return TransformFloat4PerElement(v, "acosf");
3907}
3908
3909RValue<Float4> Atan(RValue<Float4> v)
3910{
3911 return TransformFloat4PerElement(v, "atanf");
3912}
3913
3914RValue<Float4> Sinh(RValue<Float4> v)
3915{
3916 return Float4(0.5f) * (Exp(v) - Exp(-v));
3917}
3918
3919RValue<Float4> Cosh(RValue<Float4> v)
3920{
3921 return Float4(0.5f) * (Exp(v) + Exp(-v));
3922}
3923
3924RValue<Float4> Tanh(RValue<Float4> v)
3925{
3926 return TransformFloat4PerElement(v, "tanhf");
3927}
3928
3929RValue<Float4> Asinh(RValue<Float4> v)
3930{
3931 return TransformFloat4PerElement(v, "asinhf");
3932}
3933
3934RValue<Float4> Acosh(RValue<Float4> v)
3935{
3936 return TransformFloat4PerElement(v, "acoshf");
3937}
3938
3939RValue<Float4> Atanh(RValue<Float4> v)
3940{
3941 return TransformFloat4PerElement(v, "atanhf");
3942}
3943
3944RValue<Float4> Atan2(RValue<Float4> x, RValue<Float4> y)
3945{
3946 ::llvm::SmallVector<::llvm::Type*, 2> paramTys;
3947 paramTys.push_back(T(Float::getType()));
3948 paramTys.push_back(T(Float::getType()));
3949 auto funcTy = ::llvm::FunctionType::get(T(Float::getType()), paramTys, false);
3950 auto func = jit->module->getOrInsertFunction("atan2f", funcTy);
3951 llvm::Value *out = ::llvm::UndefValue::get(T(Float4::getType()));
Nicolas Capens81bc9d92019-12-16 15:05:57 -05003952 for(uint64_t i = 0; i < 4; i++)
Nicolas Capens157ba262019-12-10 17:49:14 -05003953 {
3954 auto el = jit->builder->CreateCall2(func, ARGS(
3955 V(Nucleus::createExtractElement(x.value, Float::getType(), i)),
3956 V(Nucleus::createExtractElement(y.value, Float::getType(), i))
3957 ));
3958 out = V(Nucleus::createInsertElement(V(out), V(el), i));
3959 }
3960 return RValue<Float4>(V(out));
3961}
3962
3963RValue<Float4> Pow(RValue<Float4> x, RValue<Float4> y)
3964{
3965 auto func = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::pow, { T(Float4::getType()) });
3966 return RValue<Float4>(V(jit->builder->CreateCall2(func, ARGS(V(x.value), V(y.value)))));
3967}
3968
3969RValue<Float4> Exp(RValue<Float4> v)
3970{
3971 auto func = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::exp, { T(Float4::getType()) } );
3972 return RValue<Float4>(V(jit->builder->CreateCall(func, V(v.value))));
3973}
3974
3975RValue<Float4> Log(RValue<Float4> v)
3976{
3977 auto func = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::log, { T(Float4::getType()) } );
3978 return RValue<Float4>(V(jit->builder->CreateCall(func, V(v.value))));
3979}
3980
3981RValue<Float4> Exp2(RValue<Float4> v)
3982{
3983 auto func = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::exp2, { T(Float4::getType()) } );
3984 return RValue<Float4>(V(jit->builder->CreateCall(func, V(v.value))));
3985}
3986
3987RValue<Float4> Log2(RValue<Float4> v)
3988{
3989 auto func = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::log2, { T(Float4::getType()) } );
3990 return RValue<Float4>(V(jit->builder->CreateCall(func, V(v.value))));
3991}
3992
3993RValue<UInt> Ctlz(RValue<UInt> v, bool isZeroUndef)
3994{
3995 auto func = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::ctlz, { T(UInt::getType()) } );
3996 return RValue<UInt>(V(jit->builder->CreateCall2(func, ARGS(
3997 V(v.value),
3998 isZeroUndef ? ::llvm::ConstantInt::getTrue(jit->context) : ::llvm::ConstantInt::getFalse(jit->context)
3999 ))));
4000}
4001
4002RValue<UInt4> Ctlz(RValue<UInt4> v, bool isZeroUndef)
4003{
4004 auto func = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::ctlz, { T(UInt4::getType()) } );
4005 return RValue<UInt4>(V(jit->builder->CreateCall2(func, ARGS(
4006 V(v.value),
4007 isZeroUndef ? ::llvm::ConstantInt::getTrue(jit->context) : ::llvm::ConstantInt::getFalse(jit->context)
4008 ))));
4009}
4010
4011RValue<UInt> Cttz(RValue<UInt> v, bool isZeroUndef)
4012{
4013 auto func = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::cttz, { T(UInt::getType()) } );
4014 return RValue<UInt>(V(jit->builder->CreateCall2(func, ARGS(
4015 V(v.value),
4016 isZeroUndef ? ::llvm::ConstantInt::getTrue(jit->context) : ::llvm::ConstantInt::getFalse(jit->context)
4017 ))));
4018}
4019
4020RValue<UInt4> Cttz(RValue<UInt4> v, bool isZeroUndef)
4021{
4022 auto func = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::cttz, { T(UInt4::getType()) } );
4023 return RValue<UInt4>(V(jit->builder->CreateCall2(func, ARGS(
4024 V(v.value),
4025 isZeroUndef ? ::llvm::ConstantInt::getTrue(jit->context) : ::llvm::ConstantInt::getFalse(jit->context)
4026 ))));
4027}
4028
4029Type *Float4::getType()
4030{
4031 return T(llvm::VectorType::get(T(Float::getType()), 4));
4032}
4033
4034RValue<Long> Ticks()
4035{
4036 RR_DEBUG_INFO_UPDATE_LOC();
4037 llvm::Function *rdtsc = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::readcyclecounter);
4038
4039 return RValue<Long>(V(jit->builder->CreateCall(rdtsc)));
4040}
4041
4042RValue<Pointer<Byte>> ConstantPointer(void const * ptr)
4043{
4044 // Note: this should work for 32-bit pointers as well because 'inttoptr'
4045 // is defined to truncate (and zero extend) if necessary.
4046 auto ptrAsInt = ::llvm::ConstantInt::get(::llvm::Type::getInt64Ty(jit->context), reinterpret_cast<uintptr_t>(ptr));
4047 return RValue<Pointer<Byte>>(V(jit->builder->CreateIntToPtr(ptrAsInt, T(Pointer<Byte>::getType()))));
4048}
4049
4050RValue<Pointer<Byte>> ConstantData(void const * data, size_t size)
4051{
4052 auto str = ::llvm::StringRef(reinterpret_cast<const char*>(data), size);
4053 auto ptr = jit->builder->CreateGlobalStringPtr(str);
4054 return RValue<Pointer<Byte>>(V(ptr));
4055}
4056
4057Value* Call(RValue<Pointer<Byte>> fptr, Type* retTy, std::initializer_list<Value*> args, std::initializer_list<Type*> argTys)
4058{
4059 ::llvm::SmallVector<::llvm::Type*, 8> paramTys;
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004060 for(auto ty : argTys) { paramTys.push_back(T(ty)); }
Nicolas Capens157ba262019-12-10 17:49:14 -05004061 auto funcTy = ::llvm::FunctionType::get(T(retTy), paramTys, false);
4062
4063 auto funcPtrTy = funcTy->getPointerTo();
4064 auto funcPtr = jit->builder->CreatePointerCast(V(fptr.value), funcPtrTy);
4065
4066 ::llvm::SmallVector<::llvm::Value*, 8> arguments;
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004067 for(auto arg : args) { arguments.push_back(V(arg)); }
Nicolas Capens157ba262019-12-10 17:49:14 -05004068 return V(jit->builder->CreateCall(funcPtr, arguments));
4069}
4070
4071void Breakpoint()
4072{
4073 llvm::Function *debugtrap = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::debugtrap);
4074
4075 jit->builder->CreateCall(debugtrap);
4076}
4077
4078} // namespace rr
4079
4080namespace rr {
4081
4082#if defined(__i386__) || defined(__x86_64__)
4083namespace x86 {
4084
4085RValue<Int> cvtss2si(RValue<Float> val)
4086{
4087 llvm::Function *cvtss2si = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse_cvtss2si);
4088
4089 Float4 vector;
4090 vector.x = val;
4091
4092 return RValue<Int>(V(jit->builder->CreateCall(cvtss2si, ARGS(V(RValue<Float4>(vector).value)))));
4093}
4094
4095RValue<Int4> cvtps2dq(RValue<Float4> val)
4096{
4097 llvm::Function *cvtps2dq = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_cvtps2dq);
4098
4099 return RValue<Int4>(V(jit->builder->CreateCall(cvtps2dq, ARGS(V(val.value)))));
4100}
4101
4102RValue<Float> rcpss(RValue<Float> val)
4103{
4104 llvm::Function *rcpss = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse_rcp_ss);
4105
4106 Value *vector = Nucleus::createInsertElement(V(llvm::UndefValue::get(T(Float4::getType()))), val.value, 0);
4107
4108 return RValue<Float>(Nucleus::createExtractElement(V(jit->builder->CreateCall(rcpss, ARGS(V(vector)))), Float::getType(), 0));
4109}
4110
4111RValue<Float> sqrtss(RValue<Float> val)
4112{
4113 llvm::Function *sqrt = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::sqrt, {V(val.value)->getType()});
4114 return RValue<Float>(V(jit->builder->CreateCall(sqrt, ARGS(V(val.value)))));
4115}
4116
4117RValue<Float> rsqrtss(RValue<Float> val)
4118{
4119 llvm::Function *rsqrtss = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse_rsqrt_ss);
4120
4121 Value *vector = Nucleus::createInsertElement(V(llvm::UndefValue::get(T(Float4::getType()))), val.value, 0);
4122
4123 return RValue<Float>(Nucleus::createExtractElement(V(jit->builder->CreateCall(rsqrtss, ARGS(V(vector)))), Float::getType(), 0));
4124}
4125
4126RValue<Float4> rcpps(RValue<Float4> val)
4127{
4128 llvm::Function *rcpps = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse_rcp_ps);
4129
4130 return RValue<Float4>(V(jit->builder->CreateCall(rcpps, ARGS(V(val.value)))));
4131}
4132
4133RValue<Float4> sqrtps(RValue<Float4> val)
4134{
4135 llvm::Function *sqrtps = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::sqrt, {V(val.value)->getType()});
4136
4137 return RValue<Float4>(V(jit->builder->CreateCall(sqrtps, ARGS(V(val.value)))));
4138}
4139
4140RValue<Float4> rsqrtps(RValue<Float4> val)
4141{
4142 llvm::Function *rsqrtps = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse_rsqrt_ps);
4143
4144 return RValue<Float4>(V(jit->builder->CreateCall(rsqrtps, ARGS(V(val.value)))));
4145}
4146
4147RValue<Float4> maxps(RValue<Float4> x, RValue<Float4> y)
4148{
4149 llvm::Function *maxps = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse_max_ps);
4150
4151 return RValue<Float4>(V(jit->builder->CreateCall2(maxps, ARGS(V(x.value), V(y.value)))));
4152}
4153
4154RValue<Float4> minps(RValue<Float4> x, RValue<Float4> y)
4155{
4156 llvm::Function *minps = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse_min_ps);
4157
4158 return RValue<Float4>(V(jit->builder->CreateCall2(minps, ARGS(V(x.value), V(y.value)))));
4159}
4160
4161RValue<Float> roundss(RValue<Float> val, unsigned char imm)
4162{
4163 llvm::Function *roundss = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse41_round_ss);
4164
4165 Value *undef = V(llvm::UndefValue::get(T(Float4::getType())));
4166 Value *vector = Nucleus::createInsertElement(undef, val.value, 0);
4167
4168 return RValue<Float>(Nucleus::createExtractElement(V(jit->builder->CreateCall3(roundss, ARGS(V(undef), V(vector), V(Nucleus::createConstantInt(imm))))), Float::getType(), 0));
4169}
4170
4171RValue<Float> floorss(RValue<Float> val)
4172{
4173 return roundss(val, 1);
4174}
4175
4176RValue<Float> ceilss(RValue<Float> val)
4177{
4178 return roundss(val, 2);
4179}
4180
4181RValue<Float4> roundps(RValue<Float4> val, unsigned char imm)
4182{
4183 llvm::Function *roundps = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse41_round_ps);
4184
4185 return RValue<Float4>(V(jit->builder->CreateCall2(roundps, ARGS(V(val.value), V(Nucleus::createConstantInt(imm))))));
4186}
4187
4188RValue<Float4> floorps(RValue<Float4> val)
4189{
4190 return roundps(val, 1);
4191}
4192
4193RValue<Float4> ceilps(RValue<Float4> val)
4194{
4195 return roundps(val, 2);
4196}
4197
4198RValue<Int4> pabsd(RValue<Int4> x)
4199{
4200 return RValue<Int4>(V(lowerPABS(V(x.value))));
4201}
4202
4203RValue<Short4> paddsw(RValue<Short4> x, RValue<Short4> y)
4204{
4205 #if LLVM_VERSION_MAJOR >= 8
4206 return As<Short4>(V(lowerPSADDSAT(V(x.value), V(y.value))));
4207 #else
4208 llvm::Function *paddsw = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_padds_w);
4209
4210 return As<Short4>(V(jit->builder->CreateCall2(paddsw, ARGS(V(x.value), V(y.value)))));
4211 #endif
4212}
4213
4214RValue<Short4> psubsw(RValue<Short4> x, RValue<Short4> y)
4215{
4216 #if LLVM_VERSION_MAJOR >= 8
4217 return As<Short4>(V(lowerPSSUBSAT(V(x.value), V(y.value))));
4218 #else
4219 llvm::Function *psubsw = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_psubs_w);
4220
4221 return As<Short4>(V(jit->builder->CreateCall2(psubsw, ARGS(V(x.value), V(y.value)))));
4222 #endif
4223}
4224
4225RValue<UShort4> paddusw(RValue<UShort4> x, RValue<UShort4> y)
4226{
4227 #if LLVM_VERSION_MAJOR >= 8
4228 return As<UShort4>(V(lowerPUADDSAT(V(x.value), V(y.value))));
4229 #else
4230 llvm::Function *paddusw = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_paddus_w);
4231
4232 return As<UShort4>(V(jit->builder->CreateCall2(paddusw, ARGS(V(x.value), V(y.value)))));
4233 #endif
4234}
4235
4236RValue<UShort4> psubusw(RValue<UShort4> x, RValue<UShort4> y)
4237{
4238 #if LLVM_VERSION_MAJOR >= 8
4239 return As<UShort4>(V(lowerPUSUBSAT(V(x.value), V(y.value))));
4240 #else
4241 llvm::Function *psubusw = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_psubus_w);
4242
4243 return As<UShort4>(V(jit->builder->CreateCall2(psubusw, ARGS(V(x.value), V(y.value)))));
4244 #endif
4245}
4246
4247RValue<SByte8> paddsb(RValue<SByte8> x, RValue<SByte8> y)
4248{
4249 #if LLVM_VERSION_MAJOR >= 8
4250 return As<SByte8>(V(lowerPSADDSAT(V(x.value), V(y.value))));
4251 #else
4252 llvm::Function *paddsb = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_padds_b);
4253
4254 return As<SByte8>(V(jit->builder->CreateCall2(paddsb, ARGS(V(x.value), V(y.value)))));
4255 #endif
4256}
4257
4258RValue<SByte8> psubsb(RValue<SByte8> x, RValue<SByte8> y)
4259{
4260 #if LLVM_VERSION_MAJOR >= 8
4261 return As<SByte8>(V(lowerPSSUBSAT(V(x.value), V(y.value))));
4262 #else
4263 llvm::Function *psubsb = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_psubs_b);
4264
4265 return As<SByte8>(V(jit->builder->CreateCall2(psubsb, ARGS(V(x.value), V(y.value)))));
4266 #endif
4267}
4268
4269RValue<Byte8> paddusb(RValue<Byte8> x, RValue<Byte8> y)
4270{
4271 #if LLVM_VERSION_MAJOR >= 8
4272 return As<Byte8>(V(lowerPUADDSAT(V(x.value), V(y.value))));
4273 #else
4274 llvm::Function *paddusb = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_paddus_b);
4275
4276 return As<Byte8>(V(jit->builder->CreateCall2(paddusb, ARGS(V(x.value), V(y.value)))));
4277 #endif
4278}
4279
4280RValue<Byte8> psubusb(RValue<Byte8> x, RValue<Byte8> y)
4281{
4282 #if LLVM_VERSION_MAJOR >= 8
4283 return As<Byte8>(V(lowerPUSUBSAT(V(x.value), V(y.value))));
4284 #else
4285 llvm::Function *psubusb = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_psubus_b);
4286
4287 return As<Byte8>(V(jit->builder->CreateCall2(psubusb, ARGS(V(x.value), V(y.value)))));
4288 #endif
4289}
4290
4291RValue<UShort4> pavgw(RValue<UShort4> x, RValue<UShort4> y)
4292{
4293 return As<UShort4>(V(lowerPAVG(V(x.value), V(y.value))));
4294}
4295
4296RValue<Short4> pmaxsw(RValue<Short4> x, RValue<Short4> y)
4297{
4298 return As<Short4>(V(lowerPMINMAX(V(x.value), V(y.value), llvm::ICmpInst::ICMP_SGT)));
4299}
4300
4301RValue<Short4> pminsw(RValue<Short4> x, RValue<Short4> y)
4302{
4303 return As<Short4>(V(lowerPMINMAX(V(x.value), V(y.value), llvm::ICmpInst::ICMP_SLT)));
4304}
4305
4306RValue<Short4> pcmpgtw(RValue<Short4> x, RValue<Short4> y)
4307{
4308 return As<Short4>(V(lowerPCMP(llvm::ICmpInst::ICMP_SGT, V(x.value), V(y.value), T(Short4::getType()))));
4309}
4310
4311RValue<Short4> pcmpeqw(RValue<Short4> x, RValue<Short4> y)
4312{
4313 return As<Short4>(V(lowerPCMP(llvm::ICmpInst::ICMP_EQ, V(x.value), V(y.value), T(Short4::getType()))));
4314}
4315
4316RValue<Byte8> pcmpgtb(RValue<SByte8> x, RValue<SByte8> y)
4317{
4318 return As<Byte8>(V(lowerPCMP(llvm::ICmpInst::ICMP_SGT, V(x.value), V(y.value), T(Byte8::getType()))));
4319}
4320
4321RValue<Byte8> pcmpeqb(RValue<Byte8> x, RValue<Byte8> y)
4322{
4323 return As<Byte8>(V(lowerPCMP(llvm::ICmpInst::ICMP_EQ, V(x.value), V(y.value), T(Byte8::getType()))));
4324}
4325
4326RValue<Short4> packssdw(RValue<Int2> x, RValue<Int2> y)
4327{
4328 llvm::Function *packssdw = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_packssdw_128);
4329
4330 return As<Short4>(V(jit->builder->CreateCall2(packssdw, ARGS(V(x.value), V(y.value)))));
4331}
4332
4333RValue<Short8> packssdw(RValue<Int4> x, RValue<Int4> y)
4334{
4335 llvm::Function *packssdw = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_packssdw_128);
4336
4337 return RValue<Short8>(V(jit->builder->CreateCall2(packssdw, ARGS(V(x.value), V(y.value)))));
4338}
4339
4340RValue<SByte8> packsswb(RValue<Short4> x, RValue<Short4> y)
4341{
4342 llvm::Function *packsswb = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_packsswb_128);
4343
4344 return As<SByte8>(V(jit->builder->CreateCall2(packsswb, ARGS(V(x.value), V(y.value)))));
4345}
4346
4347RValue<Byte8> packuswb(RValue<Short4> x, RValue<Short4> y)
4348{
4349 llvm::Function *packuswb = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_packuswb_128);
4350
4351 return As<Byte8>(V(jit->builder->CreateCall2(packuswb, ARGS(V(x.value), V(y.value)))));
4352}
4353
4354RValue<UShort8> packusdw(RValue<Int4> x, RValue<Int4> y)
4355{
4356 if(CPUID::supportsSSE4_1())
4357 {
4358 llvm::Function *packusdw = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse41_packusdw);
4359
4360 return RValue<UShort8>(V(jit->builder->CreateCall2(packusdw, ARGS(V(x.value), V(y.value)))));
4361 }
4362 else
4363 {
4364 RValue<Int4> bx = (x & ~(x >> 31)) - Int4(0x8000);
4365 RValue<Int4> by = (y & ~(y >> 31)) - Int4(0x8000);
4366
4367 return As<UShort8>(packssdw(bx, by) + Short8(0x8000u));
4368 }
4369}
4370
4371RValue<UShort4> psrlw(RValue<UShort4> x, unsigned char y)
4372{
4373 llvm::Function *psrlw = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_psrli_w);
4374
4375 return As<UShort4>(V(jit->builder->CreateCall2(psrlw, ARGS(V(x.value), V(Nucleus::createConstantInt(y))))));
4376}
4377
4378RValue<UShort8> psrlw(RValue<UShort8> x, unsigned char y)
4379{
4380 llvm::Function *psrlw = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_psrli_w);
4381
4382 return RValue<UShort8>(V(jit->builder->CreateCall2(psrlw, ARGS(V(x.value), V(Nucleus::createConstantInt(y))))));
4383}
4384
4385RValue<Short4> psraw(RValue<Short4> x, unsigned char y)
4386{
4387 llvm::Function *psraw = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_psrai_w);
4388
4389 return As<Short4>(V(jit->builder->CreateCall2(psraw, ARGS(V(x.value), V(Nucleus::createConstantInt(y))))));
4390}
4391
4392RValue<Short8> psraw(RValue<Short8> x, unsigned char y)
4393{
4394 llvm::Function *psraw = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_psrai_w);
4395
4396 return RValue<Short8>(V(jit->builder->CreateCall2(psraw, ARGS(V(x.value), V(Nucleus::createConstantInt(y))))));
4397}
4398
4399RValue<Short4> psllw(RValue<Short4> x, unsigned char y)
4400{
4401 llvm::Function *psllw = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_pslli_w);
4402
4403 return As<Short4>(V(jit->builder->CreateCall2(psllw, ARGS(V(x.value), V(Nucleus::createConstantInt(y))))));
4404}
4405
4406RValue<Short8> psllw(RValue<Short8> x, unsigned char y)
4407{
4408 llvm::Function *psllw = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_pslli_w);
4409
4410 return RValue<Short8>(V(jit->builder->CreateCall2(psllw, ARGS(V(x.value), V(Nucleus::createConstantInt(y))))));
4411}
4412
4413RValue<Int2> pslld(RValue<Int2> x, unsigned char y)
4414{
4415 llvm::Function *pslld = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_pslli_d);
4416
4417 return As<Int2>(V(jit->builder->CreateCall2(pslld, ARGS(V(x.value), V(Nucleus::createConstantInt(y))))));
4418}
4419
4420RValue<Int4> pslld(RValue<Int4> x, unsigned char y)
4421{
4422 llvm::Function *pslld = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_pslli_d);
4423
4424 return RValue<Int4>(V(jit->builder->CreateCall2(pslld, ARGS(V(x.value), V(Nucleus::createConstantInt(y))))));
4425}
4426
4427RValue<Int2> psrad(RValue<Int2> x, unsigned char y)
4428{
4429 llvm::Function *psrad = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_psrai_d);
4430
4431 return As<Int2>(V(jit->builder->CreateCall2(psrad, ARGS(V(x.value), V(Nucleus::createConstantInt(y))))));
4432}
4433
4434RValue<Int4> psrad(RValue<Int4> x, unsigned char y)
4435{
4436 llvm::Function *psrad = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_psrai_d);
4437
4438 return RValue<Int4>(V(jit->builder->CreateCall2(psrad, ARGS(V(x.value), V(Nucleus::createConstantInt(y))))));
4439}
4440
4441RValue<UInt2> psrld(RValue<UInt2> x, unsigned char y)
4442{
4443 llvm::Function *psrld = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_psrli_d);
4444
4445 return As<UInt2>(V(jit->builder->CreateCall2(psrld, ARGS(V(x.value), V(Nucleus::createConstantInt(y))))));
4446}
4447
4448RValue<UInt4> psrld(RValue<UInt4> x, unsigned char y)
4449{
4450 llvm::Function *psrld = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_psrli_d);
4451
4452 return RValue<UInt4>(V(jit->builder->CreateCall2(psrld, ARGS(V(x.value), V(Nucleus::createConstantInt(y))))));
4453}
4454
4455RValue<Int4> pmaxsd(RValue<Int4> x, RValue<Int4> y)
4456{
4457 return RValue<Int4>(V(lowerPMINMAX(V(x.value), V(y.value), llvm::ICmpInst::ICMP_SGT)));
4458}
4459
4460RValue<Int4> pminsd(RValue<Int4> x, RValue<Int4> y)
4461{
4462 return RValue<Int4>(V(lowerPMINMAX(V(x.value), V(y.value), llvm::ICmpInst::ICMP_SLT)));
4463}
4464
4465RValue<UInt4> pmaxud(RValue<UInt4> x, RValue<UInt4> y)
4466{
4467 return RValue<UInt4>(V(lowerPMINMAX(V(x.value), V(y.value), llvm::ICmpInst::ICMP_UGT)));
4468}
4469
4470RValue<UInt4> pminud(RValue<UInt4> x, RValue<UInt4> y)
4471{
4472 return RValue<UInt4>(V(lowerPMINMAX(V(x.value), V(y.value), llvm::ICmpInst::ICMP_ULT)));
4473}
4474
4475RValue<Short4> pmulhw(RValue<Short4> x, RValue<Short4> y)
4476{
4477 llvm::Function *pmulhw = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_pmulh_w);
4478
4479 return As<Short4>(V(jit->builder->CreateCall2(pmulhw, ARGS(V(x.value), V(y.value)))));
4480}
4481
4482RValue<UShort4> pmulhuw(RValue<UShort4> x, RValue<UShort4> y)
4483{
4484 llvm::Function *pmulhuw = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_pmulhu_w);
4485
4486 return As<UShort4>(V(jit->builder->CreateCall2(pmulhuw, ARGS(V(x.value), V(y.value)))));
4487}
4488
4489RValue<Int2> pmaddwd(RValue<Short4> x, RValue<Short4> y)
4490{
4491 llvm::Function *pmaddwd = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_pmadd_wd);
4492
4493 return As<Int2>(V(jit->builder->CreateCall2(pmaddwd, ARGS(V(x.value), V(y.value)))));
4494}
4495
4496RValue<Short8> pmulhw(RValue<Short8> x, RValue<Short8> y)
4497{
4498 llvm::Function *pmulhw = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_pmulh_w);
4499
4500 return RValue<Short8>(V(jit->builder->CreateCall2(pmulhw, ARGS(V(x.value), V(y.value)))));
4501}
4502
4503RValue<UShort8> pmulhuw(RValue<UShort8> x, RValue<UShort8> y)
4504{
4505 llvm::Function *pmulhuw = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_pmulhu_w);
4506
4507 return RValue<UShort8>(V(jit->builder->CreateCall2(pmulhuw, ARGS(V(x.value), V(y.value)))));
4508}
4509
4510RValue<Int4> pmaddwd(RValue<Short8> x, RValue<Short8> y)
4511{
4512 llvm::Function *pmaddwd = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_pmadd_wd);
4513
4514 return RValue<Int4>(V(jit->builder->CreateCall2(pmaddwd, ARGS(V(x.value), V(y.value)))));
4515}
4516
4517RValue<Int> movmskps(RValue<Float4> x)
4518{
4519 llvm::Function *movmskps = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse_movmsk_ps);
4520
4521 return RValue<Int>(V(jit->builder->CreateCall(movmskps, ARGS(V(x.value)))));
4522}
4523
4524RValue<Int> pmovmskb(RValue<Byte8> x)
4525{
4526 llvm::Function *pmovmskb = llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::x86_sse2_pmovmskb_128);
4527
4528 return RValue<Int>(V(jit->builder->CreateCall(pmovmskb, ARGS(V(x.value))))) & 0xFF;
4529}
4530
4531RValue<Int4> pmovzxbd(RValue<Byte16> x)
4532{
4533 return RValue<Int4>(V(lowerPMOV(V(x.value), T(Int4::getType()), false)));
4534}
4535
4536RValue<Int4> pmovsxbd(RValue<SByte16> x)
4537{
4538 return RValue<Int4>(V(lowerPMOV(V(x.value), T(Int4::getType()), true)));
4539}
4540
4541RValue<Int4> pmovzxwd(RValue<UShort8> x)
4542{
4543 return RValue<Int4>(V(lowerPMOV(V(x.value), T(Int4::getType()), false)));
4544}
4545
4546RValue<Int4> pmovsxwd(RValue<Short8> x)
4547{
4548 return RValue<Int4>(V(lowerPMOV(V(x.value), T(Int4::getType()), true)));
4549}
4550
4551} // namespace x86
Logan Chiene3191012018-08-24 22:01:50 +08004552#endif // defined(__i386__) || defined(__x86_64__)
Ben Clayton1bc7ee92019-02-14 18:43:22 +00004553
Ben Clayton60a3d6f2019-02-26 17:24:46 +00004554#ifdef ENABLE_RR_PRINT
Nicolas Capens157ba262019-12-10 17:49:14 -05004555// extractAll returns a vector containing the extracted n scalar value of
4556// the vector vec.
4557static std::vector<Value*> extractAll(Value* vec, int n)
4558{
4559 std::vector<Value*> elements;
4560 elements.reserve(n);
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004561 for(int i = 0; i < n; i++)
Ben Clayton1bc7ee92019-02-14 18:43:22 +00004562 {
Nicolas Capens157ba262019-12-10 17:49:14 -05004563 auto el = V(jit->builder->CreateExtractElement(V(vec), i));
4564 elements.push_back(el);
4565 }
4566 return elements;
4567}
4568
4569// toInt returns all the integer values in vals extended to a native width
4570// integer.
4571static std::vector<Value*> toInt(const std::vector<Value*>& vals, bool isSigned)
4572{
4573 auto intTy = ::llvm::Type::getIntNTy(jit->context, sizeof(int) * 8); // Natural integer width.
4574 std::vector<Value*> elements;
4575 elements.reserve(vals.size());
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004576 for(auto v : vals)
Nicolas Capens157ba262019-12-10 17:49:14 -05004577 {
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004578 if(isSigned)
Ben Clayton1bc7ee92019-02-14 18:43:22 +00004579 {
Nicolas Capens157ba262019-12-10 17:49:14 -05004580 elements.push_back(V(jit->builder->CreateSExt(V(v), intTy)));
Ben Clayton1bc7ee92019-02-14 18:43:22 +00004581 }
Nicolas Capens157ba262019-12-10 17:49:14 -05004582 else
4583 {
4584 elements.push_back(V(jit->builder->CreateZExt(V(v), intTy)));
4585 }
4586 }
4587 return elements;
4588}
4589
4590// toDouble returns all the float values in vals extended to doubles.
4591static std::vector<Value*> toDouble(const std::vector<Value*>& vals)
4592{
4593 auto doubleTy = ::llvm::Type::getDoubleTy(jit->context);
4594 std::vector<Value*> elements;
4595 elements.reserve(vals.size());
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004596 for(auto v : vals)
Nicolas Capens157ba262019-12-10 17:49:14 -05004597 {
4598 elements.push_back(V(jit->builder->CreateFPExt(V(v), doubleTy)));
4599 }
4600 return elements;
4601}
4602
4603std::vector<Value*> PrintValue::Ty<Byte>::val(const RValue<Byte>& v) { return toInt({v.value}, false); }
4604std::vector<Value*> PrintValue::Ty<Byte4>::val(const RValue<Byte4>& v) { return toInt(extractAll(v.value, 4), false); }
4605std::vector<Value*> PrintValue::Ty<Int>::val(const RValue<Int>& v) { return toInt({v.value}, true); }
4606std::vector<Value*> PrintValue::Ty<Int2>::val(const RValue<Int2>& v) { return toInt(extractAll(v.value, 2), true); }
4607std::vector<Value*> PrintValue::Ty<Int4>::val(const RValue<Int4>& v) { return toInt(extractAll(v.value, 4), true); }
4608std::vector<Value*> PrintValue::Ty<UInt>::val(const RValue<UInt>& v) { return toInt({v.value}, false); }
4609std::vector<Value*> PrintValue::Ty<UInt2>::val(const RValue<UInt2>& v) { return toInt(extractAll(v.value, 2), false); }
4610std::vector<Value*> PrintValue::Ty<UInt4>::val(const RValue<UInt4>& v) { return toInt(extractAll(v.value, 4), false); }
4611std::vector<Value*> PrintValue::Ty<Short>::val(const RValue<Short>& v) { return toInt({v.value}, true); }
4612std::vector<Value*> PrintValue::Ty<Short4>::val(const RValue<Short4>& v) { return toInt(extractAll(v.value, 4), true); }
4613std::vector<Value*> PrintValue::Ty<UShort>::val(const RValue<UShort>& v) { return toInt({v.value}, false); }
4614std::vector<Value*> PrintValue::Ty<UShort4>::val(const RValue<UShort4>& v) { return toInt(extractAll(v.value, 4), false); }
4615std::vector<Value*> PrintValue::Ty<Float>::val(const RValue<Float>& v) { return toDouble({v.value}); }
4616std::vector<Value*> PrintValue::Ty<Float4>::val(const RValue<Float4>& v) { return toDouble(extractAll(v.value, 4)); }
4617std::vector<Value*> PrintValue::Ty<const char*>::val(const char* v) { return {V(jit->builder->CreateGlobalStringPtr(v))}; }
4618
4619void Printv(const char* function, const char* file, int line, const char* fmt, std::initializer_list<PrintValue> args)
4620{
4621 // LLVM types used below.
4622 auto i32Ty = ::llvm::Type::getInt32Ty(jit->context);
4623 auto intTy = ::llvm::Type::getIntNTy(jit->context, sizeof(int) * 8); // Natural integer width.
4624 auto i8PtrTy = ::llvm::Type::getInt8PtrTy(jit->context);
4625 auto funcTy = ::llvm::FunctionType::get(i32Ty, {i8PtrTy}, true);
4626
4627 auto func = jit->module->getOrInsertFunction("printf", funcTy);
4628
4629 // Build the printf format message string.
4630 std::string str;
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004631 if(file != nullptr) { str += (line > 0) ? "%s:%d " : "%s "; }
4632 if(function != nullptr) { str += "%s "; }
Nicolas Capens157ba262019-12-10 17:49:14 -05004633 str += fmt;
4634
4635 // Perform subsitution on all '{n}' bracketed indices in the format
4636 // message.
4637 int i = 0;
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004638 for(const PrintValue& arg : args)
Nicolas Capens157ba262019-12-10 17:49:14 -05004639 {
4640 str = replace(str, "{" + std::to_string(i++) + "}", arg.format);
Ben Clayton1bc7ee92019-02-14 18:43:22 +00004641 }
4642
Nicolas Capens157ba262019-12-10 17:49:14 -05004643 ::llvm::SmallVector<::llvm::Value*, 8> vals;
4644
4645 // The format message is always the first argument.
4646 vals.push_back(jit->builder->CreateGlobalStringPtr(str));
4647
4648 // Add optional file, line and function info if provided.
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004649 if(file != nullptr)
Ben Claytonca8e3d72019-05-14 16:51:05 +01004650 {
Nicolas Capens157ba262019-12-10 17:49:14 -05004651 vals.push_back(jit->builder->CreateGlobalStringPtr(file));
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004652 if(line > 0)
Ben Claytonca8e3d72019-05-14 16:51:05 +01004653 {
Nicolas Capens157ba262019-12-10 17:49:14 -05004654 vals.push_back(::llvm::ConstantInt::get(intTy, line));
Ben Claytonca8e3d72019-05-14 16:51:05 +01004655 }
Nicolas Capens157ba262019-12-10 17:49:14 -05004656 }
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004657 if(function != nullptr)
Nicolas Capens157ba262019-12-10 17:49:14 -05004658 {
4659 vals.push_back(jit->builder->CreateGlobalStringPtr(function));
Ben Claytonca8e3d72019-05-14 16:51:05 +01004660 }
4661
Nicolas Capens157ba262019-12-10 17:49:14 -05004662 // Add all format arguments.
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004663 for(const PrintValue& arg : args)
Ben Clayton1bc7ee92019-02-14 18:43:22 +00004664 {
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004665 for(auto val : arg.values)
Ben Clayton1bc7ee92019-02-14 18:43:22 +00004666 {
Nicolas Capens157ba262019-12-10 17:49:14 -05004667 vals.push_back(V(val));
Ben Clayton1bc7ee92019-02-14 18:43:22 +00004668 }
Ben Clayton1bc7ee92019-02-14 18:43:22 +00004669 }
4670
Nicolas Capens157ba262019-12-10 17:49:14 -05004671 jit->builder->CreateCall(func, vals);
4672}
Ben Clayton1bc7ee92019-02-14 18:43:22 +00004673#endif // ENABLE_RR_PRINT
4674
Nicolas Capens157ba262019-12-10 17:49:14 -05004675void Nop()
4676{
4677 auto voidTy = ::llvm::Type::getVoidTy(jit->context);
4678 auto funcTy = ::llvm::FunctionType::get(voidTy, {}, false);
4679 auto func = jit->module->getOrInsertFunction("nop", funcTy);
4680 jit->builder->CreateCall(func);
4681}
Ben Claytonac07ed82019-03-26 14:17:41 +00004682
Nicolas Capens157ba262019-12-10 17:49:14 -05004683void EmitDebugLocation()
4684{
Ben Claytonac07ed82019-03-26 14:17:41 +00004685#ifdef ENABLE_RR_DEBUG_INFO
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004686 if(jit->debugInfo != nullptr)
Ben Claytonac07ed82019-03-26 14:17:41 +00004687 {
Nicolas Capens157ba262019-12-10 17:49:14 -05004688 jit->debugInfo->EmitLocation();
Ben Claytonac07ed82019-03-26 14:17:41 +00004689 }
Nicolas Capens157ba262019-12-10 17:49:14 -05004690#endif // ENABLE_RR_DEBUG_INFO
4691}
Ben Claytonac07ed82019-03-26 14:17:41 +00004692
Nicolas Capens157ba262019-12-10 17:49:14 -05004693void EmitDebugVariable(Value* value)
4694{
4695#ifdef ENABLE_RR_DEBUG_INFO
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004696 if(jit->debugInfo != nullptr)
Ben Claytonac07ed82019-03-26 14:17:41 +00004697 {
Nicolas Capens157ba262019-12-10 17:49:14 -05004698 jit->debugInfo->EmitVariable(value);
Ben Claytonac07ed82019-03-26 14:17:41 +00004699 }
Nicolas Capens157ba262019-12-10 17:49:14 -05004700#endif // ENABLE_RR_DEBUG_INFO
4701}
Ben Claytonac07ed82019-03-26 14:17:41 +00004702
Nicolas Capens157ba262019-12-10 17:49:14 -05004703void FlushDebug()
4704{
4705#ifdef ENABLE_RR_DEBUG_INFO
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004706 if(jit->debugInfo != nullptr)
Nicolas Capens157ba262019-12-10 17:49:14 -05004707 {
4708 jit->debugInfo->Flush();
4709 }
4710#endif // ENABLE_RR_DEBUG_INFO
4711}
4712
4713} // namespace rr
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004714
4715// ------------------------------ Coroutines ------------------------------
4716
4717namespace {
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004718
Nicolas Capens157ba262019-12-10 17:49:14 -05004719// Magic values retuned by llvm.coro.suspend.
4720// See: https://llvm.org/docs/Coroutines.html#llvm-coro-suspend-intrinsic
4721enum SuspendAction
4722{
4723 SuspendActionSuspend = -1,
4724 SuspendActionResume = 0,
4725 SuspendActionDestroy = 1
4726};
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004727
Ben Clayton16da2812019-07-09 23:28:51 +01004728void promoteFunctionToCoroutine()
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004729{
Ben Clayton16da2812019-07-09 23:28:51 +01004730 ASSERT(jit->coroutine.id == nullptr);
4731
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004732 // Types
Ben Clayton6f8e5652019-06-29 01:58:02 +01004733 auto voidTy = ::llvm::Type::getVoidTy(jit->context);
4734 auto i1Ty = ::llvm::Type::getInt1Ty(jit->context);
4735 auto i8Ty = ::llvm::Type::getInt8Ty(jit->context);
4736 auto i32Ty = ::llvm::Type::getInt32Ty(jit->context);
4737 auto i8PtrTy = ::llvm::Type::getInt8PtrTy(jit->context);
Ben Clayton16da2812019-07-09 23:28:51 +01004738 auto promiseTy = jit->coroutine.yieldType;
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004739 auto promisePtrTy = promiseTy->getPointerTo();
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004740
4741 // LLVM intrinsics
Ben Clayton6f8e5652019-06-29 01:58:02 +01004742 auto coro_id = ::llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::coro_id);
4743 auto coro_size = ::llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::coro_size, {i32Ty});
4744 auto coro_begin = ::llvm::Intrinsic::getDeclaration(jit->module.get(), llvm::Intrinsic::coro_begin);
4745 auto coro_resume = ::llvm::Intrinsic::getDeclaration(jit->module.get(), ::llvm::Intrinsic::coro_resume);
4746 auto coro_end = ::llvm::Intrinsic::getDeclaration(jit->module.get(), ::llvm::Intrinsic::coro_end);
4747 auto coro_free = ::llvm::Intrinsic::getDeclaration(jit->module.get(), ::llvm::Intrinsic::coro_free);
4748 auto coro_destroy = ::llvm::Intrinsic::getDeclaration(jit->module.get(), ::llvm::Intrinsic::coro_destroy);
4749 auto coro_promise = ::llvm::Intrinsic::getDeclaration(jit->module.get(), ::llvm::Intrinsic::coro_promise);
4750 auto coro_done = ::llvm::Intrinsic::getDeclaration(jit->module.get(), ::llvm::Intrinsic::coro_done);
4751 auto coro_suspend = ::llvm::Intrinsic::getDeclaration(jit->module.get(), ::llvm::Intrinsic::coro_suspend);
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004752
4753 auto allocFrameTy = ::llvm::FunctionType::get(i8PtrTy, {i32Ty}, false);
Ben Clayton6f8e5652019-06-29 01:58:02 +01004754 auto allocFrame = jit->module->getOrInsertFunction("coroutine_alloc_frame", allocFrameTy);
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004755 auto freeFrameTy = ::llvm::FunctionType::get(voidTy, {i8PtrTy}, false);
Ben Clayton6f8e5652019-06-29 01:58:02 +01004756 auto freeFrame = jit->module->getOrInsertFunction("coroutine_free_frame", freeFrameTy);
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004757
Ben Clayton16da2812019-07-09 23:28:51 +01004758 auto oldInsertionPoint = jit->builder->saveIP();
4759
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004760 // Build the coroutine_await() function:
4761 //
4762 // bool coroutine_await(CoroutineHandle* handle, YieldType* out)
4763 // {
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004764 // if(llvm.coro.done(handle))
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004765 // {
4766 // return false;
4767 // }
4768 // else
4769 // {
4770 // *value = (T*)llvm.coro.promise(handle);
4771 // llvm.coro.resume(handle);
4772 // return true;
4773 // }
4774 // }
4775 //
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004776 {
Ben Clayton6f8e5652019-06-29 01:58:02 +01004777 auto args = jit->coroutine.await->arg_begin();
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004778 auto handle = args++;
4779 auto outPtr = args++;
Ben Clayton6f8e5652019-06-29 01:58:02 +01004780 jit->builder->SetInsertPoint(llvm::BasicBlock::Create(jit->context, "co_await", jit->coroutine.await));
4781 auto doneBlock = llvm::BasicBlock::Create(jit->context, "done", jit->coroutine.await);
4782 auto resumeBlock = llvm::BasicBlock::Create(jit->context, "resume", jit->coroutine.await);
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004783
Ben Clayton6f8e5652019-06-29 01:58:02 +01004784 auto done = jit->builder->CreateCall(coro_done, {handle}, "done");
4785 jit->builder->CreateCondBr(done, doneBlock, resumeBlock);
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004786
Ben Clayton6f8e5652019-06-29 01:58:02 +01004787 jit->builder->SetInsertPoint(doneBlock);
4788 jit->builder->CreateRet(::llvm::ConstantInt::getFalse(i1Ty));
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004789
Ben Clayton6f8e5652019-06-29 01:58:02 +01004790 jit->builder->SetInsertPoint(resumeBlock);
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004791 auto promiseAlignment = ::llvm::ConstantInt::get(i32Ty, 4); // TODO: Get correct alignment.
Ben Clayton6f8e5652019-06-29 01:58:02 +01004792 auto promisePtr = jit->builder->CreateCall(coro_promise, {handle, promiseAlignment, ::llvm::ConstantInt::get(i1Ty, 0)});
4793 auto promise = jit->builder->CreateLoad(jit->builder->CreatePointerCast(promisePtr, promisePtrTy));
4794 jit->builder->CreateStore(promise, outPtr);
4795 jit->builder->CreateCall(coro_resume, {handle});
4796 jit->builder->CreateRet(::llvm::ConstantInt::getTrue(i1Ty));
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004797 }
4798
4799 // Build the coroutine_destroy() function:
4800 //
4801 // void coroutine_destroy(CoroutineHandle* handle)
4802 // {
4803 // llvm.coro.destroy(handle);
4804 // }
4805 //
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004806 {
Ben Clayton6f8e5652019-06-29 01:58:02 +01004807 auto handle = jit->coroutine.destroy->arg_begin();
4808 jit->builder->SetInsertPoint(llvm::BasicBlock::Create(jit->context, "", jit->coroutine.destroy));
4809 jit->builder->CreateCall(coro_destroy, {handle});
4810 jit->builder->CreateRetVoid();
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004811 }
4812
4813 // Begin building the main coroutine_begin() function.
4814 //
4815 // CoroutineHandle* coroutine_begin(<Arguments>)
4816 // {
4817 // YieldType promise;
4818 // auto id = llvm.coro.id(0, &promise, nullptr, nullptr);
4819 // void* frame = coroutine_alloc_frame(llvm.coro.size.i32());
4820 // CoroutineHandle *handle = llvm.coro.begin(id, frame);
4821 //
4822 // ... <REACTOR CODE> ...
4823 //
4824 // end:
4825 // SuspendAction action = llvm.coro.suspend(none, true /* final */); // <-- RESUME POINT
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004826 // switch(action)
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004827 // {
4828 // case SuspendActionResume:
4829 // UNREACHABLE(); // Illegal to resume after final suspend.
4830 // case SuspendActionDestroy:
4831 // goto destroy;
4832 // default: // (SuspendActionSuspend)
4833 // goto suspend;
4834 // }
4835 //
4836 // destroy:
4837 // coroutine_free_frame(llvm.coro.free(id, handle));
4838 // goto suspend;
4839 //
4840 // suspend:
4841 // llvm.coro.end(handle, false);
4842 // return handle;
4843 // }
4844 //
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004845
4846#ifdef ENABLE_RR_DEBUG_INFO
Ben Clayton16da2812019-07-09 23:28:51 +01004847 jit->debugInfo = std::unique_ptr<rr::DebugInfo>(new rr::DebugInfo(jit->builder.get(), &jit->context, jit->module.get(), jit->function));
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004848#endif // ENABLE_RR_DEBUG_INFO
4849
Ben Clayton6f8e5652019-06-29 01:58:02 +01004850 jit->coroutine.suspendBlock = llvm::BasicBlock::Create(jit->context, "suspend", jit->function);
4851 jit->coroutine.endBlock = llvm::BasicBlock::Create(jit->context, "end", jit->function);
4852 jit->coroutine.destroyBlock = llvm::BasicBlock::Create(jit->context, "destroy", jit->function);
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004853
Ben Clayton16da2812019-07-09 23:28:51 +01004854 jit->builder->SetInsertPoint(jit->coroutine.entryBlock, jit->coroutine.entryBlock->begin());
4855 jit->coroutine.promise = jit->builder->CreateAlloca(promiseTy, nullptr, "promise");
Ben Clayton6f8e5652019-06-29 01:58:02 +01004856 jit->coroutine.id = jit->builder->CreateCall(coro_id, {
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004857 ::llvm::ConstantInt::get(i32Ty, 0),
Ben Clayton6f8e5652019-06-29 01:58:02 +01004858 jit->builder->CreatePointerCast(jit->coroutine.promise, i8PtrTy),
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004859 ::llvm::ConstantPointerNull::get(i8PtrTy),
4860 ::llvm::ConstantPointerNull::get(i8PtrTy),
4861 });
Ben Clayton6f8e5652019-06-29 01:58:02 +01004862 auto size = jit->builder->CreateCall(coro_size, {});
4863 auto frame = jit->builder->CreateCall(allocFrame, {size});
4864 jit->coroutine.handle = jit->builder->CreateCall(coro_begin, {jit->coroutine.id, frame});
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004865
4866 // Build the suspend block
Ben Clayton6f8e5652019-06-29 01:58:02 +01004867 jit->builder->SetInsertPoint(jit->coroutine.suspendBlock);
4868 jit->builder->CreateCall(coro_end, {jit->coroutine.handle, ::llvm::ConstantInt::get(i1Ty, 0)});
4869 jit->builder->CreateRet(jit->coroutine.handle);
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004870
4871 // Build the end block
Ben Clayton6f8e5652019-06-29 01:58:02 +01004872 jit->builder->SetInsertPoint(jit->coroutine.endBlock);
4873 auto action = jit->builder->CreateCall(coro_suspend, {
4874 ::llvm::ConstantTokenNone::get(jit->context),
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004875 ::llvm::ConstantInt::get(i1Ty, 1), // final: true
4876 });
Ben Clayton6f8e5652019-06-29 01:58:02 +01004877 auto switch_ = jit->builder->CreateSwitch(action, jit->coroutine.suspendBlock, 3);
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004878 // switch_->addCase(::llvm::ConstantInt::get(i8Ty, SuspendActionResume), trapBlock); // TODO: Trap attempting to resume after final suspend
Ben Clayton6f8e5652019-06-29 01:58:02 +01004879 switch_->addCase(::llvm::ConstantInt::get(i8Ty, SuspendActionDestroy), jit->coroutine.destroyBlock);
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004880
4881 // Build the destroy block
Ben Clayton6f8e5652019-06-29 01:58:02 +01004882 jit->builder->SetInsertPoint(jit->coroutine.destroyBlock);
4883 auto memory = jit->builder->CreateCall(coro_free, {jit->coroutine.id, jit->coroutine.handle});
4884 jit->builder->CreateCall(freeFrame, {memory});
4885 jit->builder->CreateBr(jit->coroutine.suspendBlock);
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004886
Ben Clayton16da2812019-07-09 23:28:51 +01004887 // Switch back to original insert point to continue building the coroutine.
4888 jit->builder->restoreIP(oldInsertionPoint);
4889}
4890
4891} // anonymous namespace
4892
4893namespace rr {
4894
4895void Nucleus::createCoroutine(Type *YieldType, std::vector<Type*> &Params)
4896{
4897 // Coroutines are initially created as a regular function.
4898 // Upon the first call to Yield(), the function is promoted to a true
4899 // coroutine.
4900 auto voidTy = ::llvm::Type::getVoidTy(jit->context);
4901 auto i1Ty = ::llvm::Type::getInt1Ty(jit->context);
4902 auto i8PtrTy = ::llvm::Type::getInt8PtrTy(jit->context);
4903 auto handleTy = i8PtrTy;
4904 auto boolTy = i1Ty;
4905 auto promiseTy = T(YieldType);
4906 auto promisePtrTy = promiseTy->getPointerTo();
4907
4908 jit->function = rr::createFunction("coroutine_begin", handleTy, T(Params));
4909 jit->coroutine.await = rr::createFunction("coroutine_await", boolTy, {handleTy, promisePtrTy});
4910 jit->coroutine.destroy = rr::createFunction("coroutine_destroy", voidTy, {handleTy});
4911 jit->coroutine.yieldType = promiseTy;
4912 jit->coroutine.entryBlock = llvm::BasicBlock::Create(jit->context, "function", jit->function);
4913
4914 jit->builder->SetInsertPoint(jit->coroutine.entryBlock);
John Bauman89401822014-05-06 15:04:28 -04004915}
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004916
4917void Nucleus::yield(Value* val)
4918{
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004919 if(jit->coroutine.id == nullptr)
Ben Clayton16da2812019-07-09 23:28:51 +01004920 {
4921 // First call to yield().
4922 // Promote the function to a full coroutine.
4923 promoteFunctionToCoroutine();
4924 ASSERT(jit->coroutine.id != nullptr);
4925 }
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004926
4927 // promise = val;
4928 //
4929 // auto action = llvm.coro.suspend(none, false /* final */); // <-- RESUME POINT
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004930 // switch(action)
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004931 // {
4932 // case SuspendActionResume:
4933 // goto resume;
4934 // case SuspendActionDestroy:
4935 // goto destroy;
4936 // default: // (SuspendActionSuspend)
4937 // goto suspend;
4938 // }
4939 // resume:
4940 //
4941
4942 RR_DEBUG_INFO_UPDATE_LOC();
4943 Variable::materializeAll();
4944
4945 // Types
Ben Clayton6f8e5652019-06-29 01:58:02 +01004946 auto i1Ty = ::llvm::Type::getInt1Ty(jit->context);
4947 auto i8Ty = ::llvm::Type::getInt8Ty(jit->context);
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004948
4949 // Intrinsics
Ben Clayton6f8e5652019-06-29 01:58:02 +01004950 auto coro_suspend = ::llvm::Intrinsic::getDeclaration(jit->module.get(), ::llvm::Intrinsic::coro_suspend);
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004951
4952 // Create a block to resume execution.
Ben Clayton6f8e5652019-06-29 01:58:02 +01004953 auto resumeBlock = llvm::BasicBlock::Create(jit->context, "resume", jit->function);
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004954
4955 // Store the promise (yield value)
Ben Clayton6f8e5652019-06-29 01:58:02 +01004956 jit->builder->CreateStore(V(val), jit->coroutine.promise);
4957 auto action = jit->builder->CreateCall(coro_suspend, {
4958 ::llvm::ConstantTokenNone::get(jit->context),
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004959 ::llvm::ConstantInt::get(i1Ty, 0), // final: true
4960 });
Ben Clayton6f8e5652019-06-29 01:58:02 +01004961 auto switch_ = jit->builder->CreateSwitch(action, jit->coroutine.suspendBlock, 3);
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004962 switch_->addCase(::llvm::ConstantInt::get(i8Ty, SuspendActionResume), resumeBlock);
Ben Clayton6f8e5652019-06-29 01:58:02 +01004963 switch_->addCase(::llvm::ConstantInt::get(i8Ty, SuspendActionDestroy), jit->coroutine.destroyBlock);
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004964
4965 // Continue building in the resume block.
Ben Clayton6f8e5652019-06-29 01:58:02 +01004966 jit->builder->SetInsertPoint(resumeBlock);
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004967}
4968
Ben Clayton6897e9b2019-07-16 17:27:27 +01004969std::shared_ptr<Routine> Nucleus::acquireCoroutine(const char *name, const Config::Edit &cfgEdit /* = Config::Edit::None */)
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004970{
Ben Clayton16da2812019-07-09 23:28:51 +01004971 bool isCoroutine = jit->coroutine.id != nullptr;
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004972 if(isCoroutine)
Ben Clayton16da2812019-07-09 23:28:51 +01004973 {
4974 jit->builder->CreateBr(jit->coroutine.endBlock);
4975 }
4976 else
4977 {
4978 // Coroutine without a Yield acts as a regular function.
4979 // The 'coroutine_begin' function returns a nullptr for the coroutine
4980 // handle.
4981 jit->builder->CreateRet(llvm::Constant::getNullValue(jit->function->getReturnType()));
4982 // The 'coroutine_await' function always returns false (coroutine done).
4983 jit->builder->SetInsertPoint(llvm::BasicBlock::Create(jit->context, "", jit->coroutine.await));
4984 jit->builder->CreateRet(llvm::Constant::getNullValue(jit->coroutine.await->getReturnType()));
4985 // The 'coroutine_destroy' does nothing, returns void.
4986 jit->builder->SetInsertPoint(llvm::BasicBlock::Create(jit->context, "", jit->coroutine.destroy));
4987 jit->builder->CreateRetVoid();
4988 }
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004989
4990#ifdef ENABLE_RR_DEBUG_INFO
Nicolas Capens81bc9d92019-12-16 15:05:57 -05004991 if(jit->debugInfo != nullptr)
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004992 {
Ben Clayton6f8e5652019-06-29 01:58:02 +01004993 jit->debugInfo->Finalize();
Ben Clayton1c82c7b2019-04-30 12:49:27 +01004994 }
4995#endif // ENABLE_RR_DEBUG_INFO
4996
4997 if(false)
4998 {
4999 std::error_code error;
5000 llvm::raw_fd_ostream file(std::string(name) + "-llvm-dump-unopt.txt", error);
Ben Clayton6f8e5652019-06-29 01:58:02 +01005001 jit->module->print(file, 0);
Ben Clayton1c82c7b2019-04-30 12:49:27 +01005002 }
5003
Nicolas Capens81bc9d92019-12-16 15:05:57 -05005004 if(isCoroutine)
Ben Clayton16da2812019-07-09 23:28:51 +01005005 {
5006 // Run manadory coroutine transforms.
5007 llvm::legacy::PassManager pm;
5008 pm.add(llvm::createCoroEarlyPass());
5009 pm.add(llvm::createCoroSplitPass());
5010 pm.add(llvm::createCoroElidePass());
5011 pm.add(llvm::createBarrierNoopPass());
5012 pm.add(llvm::createCoroCleanupPass());
5013 pm.run(*jit->module);
5014 }
5015
5016#if defined(ENABLE_RR_LLVM_IR_VERIFICATION) || !defined(NDEBUG)
5017 {
5018 llvm::legacy::PassManager pm;
5019 pm.add(llvm::createVerifierPass());
5020 pm.run(*jit->module);
5021 }
5022#endif // defined(ENABLE_RR_LLVM_IR_VERIFICATION) || !defined(NDEBUG)
Ben Clayton1c82c7b2019-04-30 12:49:27 +01005023
Ben Clayton55bc37a2019-07-04 12:17:12 +01005024 auto cfg = cfgEdit.apply(jit->config);
5025 jit->optimize(cfg);
Ben Clayton1c82c7b2019-04-30 12:49:27 +01005026
5027 if(false)
5028 {
5029 std::error_code error;
5030 llvm::raw_fd_ostream file(std::string(name) + "-llvm-dump-opt.txt", error);
Ben Clayton6f8e5652019-06-29 01:58:02 +01005031 jit->module->print(file, 0);
Ben Clayton1c82c7b2019-04-30 12:49:27 +01005032 }
5033
5034 llvm::Function *funcs[Nucleus::CoroutineEntryCount];
Ben Clayton6f8e5652019-06-29 01:58:02 +01005035 funcs[Nucleus::CoroutineEntryBegin] = jit->function;
5036 funcs[Nucleus::CoroutineEntryAwait] = jit->coroutine.await;
5037 funcs[Nucleus::CoroutineEntryDestroy] = jit->coroutine.destroy;
Ben Clayton55bc37a2019-07-04 12:17:12 +01005038 auto routine = jit->acquireRoutine(funcs, Nucleus::CoroutineEntryCount, cfg);
Ben Clayton6f8e5652019-06-29 01:58:02 +01005039 jit.reset();
Ben Clayton1c82c7b2019-04-30 12:49:27 +01005040
5041 return routine;
5042}
5043
5044} // namespace rr