PS3 emulation is fast on ARM now
Comments
Transcript
Machine-transcribed by YouTube. Expect errors in names, commands and version numbers.
6 months ago, RPCS3 was running like this. Today, we're able to emulate the PlayStation 3 60% faster while drawing 25% less power. So, how did we do it? It
all started with this document, the ARM architecture reference manual. It's over 17,000 pages long.
Now, since this document only exists digitally, I stacked some books as an example to show you what 17,000 pages would look like in real life. I scoured every digital page of this document to bring PlayStation 3 emulation to a new class of devices. Last Christmas, I ordered this handheld device, the Ayn Odin 2. It's basically an Android smartphone with controls bolted on. But, rather than using it as an Android device, I actually bought it so that I could install Linux on it and optimize RPCS3 for ARM. Seriously, it's much cheaper than an ARM laptop with similar hardware. Anyways, the first thing I noticed when I received and booted the device in January is that we're spending half of our CPU time in this little four-line function, busy wait.
All right. So, the reason this function exists is to improve performance in multi-threaded code. Imagine a piece of code that's checking if another thread changed a variable over and over again in a loop. That will ensure that the monitoring thread can see the change as fast as possible, but it's going to produce extra heat, burn more power, and put additional pressure on resources shared between cores like cache and memory. In the past, I actually helped our former lead developer Nekotekina in debugging an issue. And what we found is that when we added a busy wait to a particular place in the code, we managed to triple our performance. Under some pretty specific circumstances, but still. Now, to understand why busy wait was so slow on my ARM device, we need to explain how it works on an X86. First, we read the hardware timer and add 3,000 to it to get our target wait time. Then, we call the hardware timer in a loop, waiting until the hardware timer exceeds the initial value plus 3,000.
Additionally, we call the pause instruction in the loop, too, which throttles the hardware even further, offering even greater power savings. Inside busy wait, we added this arbitrary value of 3,000 to the timeout, which works out to about a 1 microsecond wait on most x86 devices. The speed of the hardware timer on x86 devices depends on the specific device, but since the hardware timer is typically running somewhere between 2 to 4 GHz, this works out to about a 1 microsecond wait. Again, remember that this isn't intended as a precise wait or anything, but just a way to save some power. It would be trivial for us to do some math and wait for a precise period. That would require extra memory reads and multiplications, which would defeat the purpose of our simple hardware-friendly busy wait function. When porting the code to arm, we did the straightforward thing. We replaced reading the hardware timer on x86 with reading the hardware timer on arm. We also mapped the pause instruction on x86 to the yield instruction on arm. But what speed does the hardware timer run at on arm? At least on my device, it's running at 19 MHz. That's 150 times slower than what we expect. Meaning that instead of waiting for 1 microsecond, we're actually waiting for 150 microseconds each time we call busy wait.
A solution to this stupid problem is to simply just scale the amount of time spent waiting by the frequency of the timer. Yeah, we have to do the extra math, but it's much better than waiting 150 microseconds each time we call the function. After consulting Google search, we've learned that arm hardware timers typically run between 10 MHz and 1 GHz. So, there's no one value that's good enough for all arm hardware. Just fixing this bug alone provides a 25% boost to performance on average, on top of reducing power draw by 10%. Another user reported going from 5 to 10 frames per second all the way up to a locked 30 frames per second on his arm-based MacBook in Skylanders.
Fixing this tiny issue alone is already enough to let the hardware stretch its legs. The fact that such a simple fix was already having such a large impact filled me with the determination and confidence to tackle the rest of the low-hanging fruit. Yum. Moving back to the present, after all our optimizations, which we will be exhaustively covering in this video, the CPU side of RPCS3 is so fast that many games like Demon Souls are now bottlenecked by the host GPU. We went from being CPU limited in the majority of our games to GPU limited in many of our games. In some other games, the uplift of CPU performance is even more obvious. When looking at Ninja Gaiden 3, there's a similar uplift in performance compared to Demon Souls across many scenes. Not bad, but when we look at actual gameplay, you'll probably notice that the game is running in slow motion with the older code. The game logic can't run at full speed on the older builds.
That's great and all, but the busy wait bug existed from the very first version of RPCS3 on arm back in January of 2022.
It took 4 years to resolve this bug despite how simple the fix actually is. Why did it take so long to fix? Well, Nekotekina, our former lead developer, ported the emulator to arm, but left the project before finishing work on the recompiler, which are needed to run almost any game at full speed. Our lead graphics developer, KD-11, stepped up, purchased arm-based Apple hardware, and got the recompiler functioning. With everything functionally ported, KD-11 moved back onto working with the graphics backends. While the emulator was functionally ported to arm, there were a lot of niggling issues left over with no one actively working on them. Fortunately for you guys, that means you get a dense, interesting video where I talk about a whole ton of niche assembly code. You're all elite hacksors, right?
Remember when people used to call themselves that? Anyways, this handheld is the AYN Odin 2, the arm device I picked up. It's a Chinese Android gaming handheld, and it's several years old now. Unsurprisingly, it's pretty good at playing Android games. You can also run all kinds of emulators on it. It's even capable of playing PC games from Steam, like Silksong, but I didn't order it to play around with it. Actually, by the time I ordered it, the much faster Odin 3 was already released, but I still opted to pick up the Odin 2 because the chip in the Odin 3 has cores that don't support SVE instructions, which was something that I wanted to support in the emulator.
Also, installing Linux was supported for the Odin 2. At the time of making this video, Linux installs are now possible on the Odin 3, but that wasn't a thing last December. There are two PlayStation 3 emulators for Android, both based off of upstream RPCS3. There's APS3E, which was the first to release. When APS3E was initially released, it was closed source, which is a violation of the open source license that RPCS3 is released under. The current versions of APS3E are open source correctly, so kudos to the developer for turning around on that issue. RPCSX is the second PlayStation 3 emulator for Android. RPCSX is headed by DH, who you might also know as the founder of RPCS3.
Despite the presence of these Android PlayStation 3 emulators, I chose to install Linux on my Odin 2 because I work on the upstream version of RPCS3, which works on Windows, Linux, and Mac devices. Some of you are probably wondering, do the optimizations I'm talking about in this video apply to these Android versions of RPCS3? Well, at the time of recording this video, the answer is no. But if these Android versions of RPCS3 were to rebase themselves onto the upstream code, then yeah, they could. With all that background out of the way, let's move back to busy wait because there's one more issue lying in this function. If you recall, we used the ARM yield instruction in place of the x86 pause instruction. Let's review the definition of yield from the ARM manual. Yield is a hint instruction. Software with a multi-threading capability can use a yield instruction to indicate to the hardware that it is performing a task, for example, a spin lock that could be swapped out to improve overall system performance. Oh, awesome. That sounds perfect for our use case. Remember, on x86, the Intel manual refers to pause as a spin loop hint. But if you scroll down to another section of the ARM manual, you'll find this.
In a symmetric multi-threading design, a thread can use the yield instruction to give a hint to the processor that it is running on to indicate that whatever the thread is currently doing is of low importance. Here's the problem. Yield only yields the current thread if the hardware has SMT, but 99% of consumer ARM machines don't use SMT. They use traditional SMP cores. On an SMP system, the manual says it can lower the priority of the snoop bus, but since we aren't reading any memory in our busy wait loop, that doesn't change anything, either. ARM actually published an entire blog post explaining how to port a busy wait-like function that uses x86's pause over to arm.
They call out yield, but explicitly mention that it is treated as a complete knob on systems without SMT. This doesn't technically contradict the 17,000 page reference manual, but it reveals that yield does absolutely nothing on almost every modern arm phone, tablet, and laptop. Instead of using yield, we now use the instruction synchronization barrier instruction, also known as ISB. The same blog also mentions that ISB isn't ideal for replacing pause, as it causes the machine to restart instruction fetch, burning a little more power, rather than properly stalling both instruction fetch and execution. Of course though, saving power isn't the intended use case of ISB. However, despite all the caveats, use of ISB does save a little more power in this loop over yield.
By the way, you can just look for pull requests that mention yield or ISB on GitHub, and you can find code from all sorts of multi-trillion-dollar corporations who ran into the exact same issue we did here. The description of yield in the manual could probably be adjusted to avoid this issue. Here's a little illustration of how ISB helps us throttle our CPU usage. >> True, and yeah, that's pretty true. That's true, and yeah, that's true. That's true. That's true. That's pretty true. That's pretty true. I mean, true, and yeah, that's pretty true. That's true, and >> With ISB, the CPU is able to save power by only checking the condition once per several nanoseconds, rather than multiple times per nanosecond.
These tiny changes have already improved RPCS3 a lot, but from the start, what I had my eyes on was the recompiler. The SPU recompiler is typically the heaviest part of emulating the PlayStation 3 on x86 machines, despite the x86 back end having been relentlessly optimized. I dove straight into the assembly that LLVM produced, and this is what I saw.
>> Just as a recap, RPCS3 uses the LLVM project to translate PlayStation 3 game code to X86 or ARM. We take PlayStation 3 assembly, translate that to LLVM IR, then LLVM takes that and outputs native code for your machine. It's not dissimilar to how games like Unleash Recompiled work, only they're translating to C rather than LLVM IR. Unleash Recompiled even requires use of the LLVM based clang compiler to recompile the C code it produces. So, you can think of it as almost the same approach, really. The advantage of using LLVM over directly writing assembly ourselves is that we can take advantage of all the optimizations that LLVM already knows how to do. Of course, LLVM isn't perfect at optimizing and has done a pretty bad job at it optimizing some instructions.
But before we cover how everything was fixed, let's review the things that ARM and LLVM were able to do better than the X86 back end without any intervention. The SPU instruction abs db takes the absolute difference between two numbers. That is to say, it finds how far apart two numbers are. So, for instance, the absolute difference between three and seven is four. X86 has a number of instructions that calculate absolute difference, but they all sum the values horizontally, too. So, we need this three instruction sequence to calculate the absolute difference, which works out to this expression. On ARM, we just have an instruction that calculates absolute difference the same way as the PlayStation 3. Nice.
For count b, the situation is similar. We have an instruction that just matches PlayStation 3 behavior. This instruction counts the number of bits set in each byte, which is pretty expensive if you don't have an instruction to accelerate this. Anyways, X86 can also do this in a single instruction if you have AVX-512. Else, we need this awful sequence to count bits properly. Similarly with CLZ, we have a single instruction solution for ARM, as well as X86 CPUs with AVX-512. This instruction counts the number of zeros in each byte until it finds a set bit. And again, the non-AVX512 x86 path requires an extreme number of instructions.
CLGT is a simple instruction. Performs an unsigned comparison. Of course, we need four instructions on x86 to emulate it. Why wouldn't we? With AVX512, we need two instructions as AVX512 adds an unsigned comparison instruction. But since AVX512 compares directly into the mask registers, we still need another instruction to move the result into the vector registers. ARM, of course, just has an unsigned comparison instruction. So, we only need one instruction to emulate CLGT. Finally, we have SELB. For ARM, BSL is a single instruction solution here. Again, on x86, we need three bitwise instructions to emulate SELB. If we have AVX512, we can use VPTERNLOG instead, which can do any permutation of three bitwise operations on three sources at once. It's like a Swiss Army knife of bitwise instructions.
So, in some cases, ARM can have more optimal code gen than x86. But in most cases, that gap is closed if our x86 machine supports AVX512. Now, this is all nice, but that's just five instructions where ARM could beat x86. There were dozens of instructions where the ARM code gen was worse than the x86 output. Fortunately, that's all fixed now. And yeah, we're going to review how every single one of them was fixed. For the first instruction, SHFB, that bad code gen was our fault. See, when porting the LLVM recompiler's to ARM, we just emulated the x86 PSHFB instruction instead of properly rewriting the emulation to use ARM shuffle instructions. In LLVM IR, there exist generic shuffle operations that will compile down to whatever shuffle instruction is ideal on the host machine. It's really good at this, actually. But the generic shuffles only take constant indices for the shuffle operations.
This is because variable shuffles, like SHFB on the PlayStation 3, PSHFB on x86, and TBL on ARM, all have differing behaviors. So, there's not a reasonable way to create a generic operation here. And so, the fastest way to get the recompiler is working was to just emulate X86 PSHFB. That way we didn't need to rewrite the emulation of any of our PlayStation 3 instructions. Of course, this has provided us with the lowest hanging of the lowest hanging fruit. And boy, is that fruit ripe. By rewriting emulation of SHFB to properly use the arm shuffles, we cut the number of needed instructions from 10 to five.
Yeah, it's still a lot larger than the one instruction solutions we were discussing for the other instructions, but SHFB is simultaneously one of the most complex PlayStation 3 instructions on top of being one of the most common. So, optimizing it as much as possible is paramount. Let's break down how the unoptimized version works first. I'm going to do it in an order slightly different to how it's laid out here, but bear with me. First, we need to XOR the bottom four bits of the indices since SHFB uses a big endian byte ordering, while TBL on arm uses a little endian byte ordering. Essentially, both these instructions read shuffle indices in reverse order from each other. Next, we need to AND our result with hex 8F to mask out everything but those bottom four bits, as well as the most significant bit. Then, we need to feed these indices into TBL twice. Since TBL will zero the result if any bit outside of the bottom four bits are set, we had to mask off bits four to six, while leaving bits zero to three and bit seven untouched.
Thus, when bit seven, the most significant bit is set, we will place zero in the result, matching SHFB. Next, the sequence of three instructions will combine the results of the two TBL instructions based off of the fourth bit. We shift the fourth bit into the most significant slot, compare to generate a mask based on whether or not that bit was set, then select between our two TBL results from earlier based on the mask. This is needed because the PlayStation 3 SHFB shuffles from two table sources, while TBL only takes one. At this point, we've correctly emulated the shuffle part of SHFB, but SHFB also has three different constants that can be produced when the most significant bit is set. When the most significant bit is set alone, we produce zero. When the most two significant bits are set, we produce hex FF. And when the most three significant bits are set, we produce hex 80.
Three different special cases is a lot. To produce them efficiently, we need to use TBL again. We first shift the three most significant bits such that they're located in the lowest three bits. Then, we use TBL along with this constant to successfully generate our constants in each slot. Finally, we bitwise or our generated constants into the shuffle data from earlier. Since we kept the most significant bit in our shuffle indices, we conveniently have zero in all of our slots where constants are. 10 ARM instructions later, we've emulated one PlayStation 3 instruction. It's rough. Fortunately, there's some very low-hanging fruit here. The instruction TBX is like TBL, but when out-of-range indices are used, it instead takes the value from the destination register instead of filling it with zeros. This allows us to skip the final or instruction. Additionally, TBL and TBX can actually take multiple registers as shuffle inputs.
Between one to four registers may be used in this manner. This means that we can simply use TBX with two input registers, replacing this entire five instruction sequence. That brings us down to just five instructions, half as many as we needed initially. Pretty awesome. It could actually be just four instructions. There's an instruction BCAX, which performs both an and as well as an XOR operation at the same time. This instruction is part of the SHA-3 instruction set intended for accelerating cryptography. But unlike the other cryptography extensions, SHA-3 is full of bitwise instructions that are also useful for general-purpose code. That was a lot to take in, so let's take a break by looking at this family of skunks.
Anyways, LLVM is capable of combining these operations into a single BCAX. It seems like LLVM can only pattern match BCAX when the inputs aren't constants. Of course, we kind of need them to be constants. I opened an issue for this on the LLVM GitHub, so hopefully this is something they'll address. Still, even if they did, four instructions for one of the most common PlayStation 3 instructions isn't exactly ideal. Thankfully, all the other optimizations we've written over RPCS3's existence for shufb will still apply here. For instance, if shufb is used within a loop, we can calculate all of the special cases outside of the loop, reducing our usage of shufb within the loop to just a single TBX2 instruction, which is pretty awesome.
Four instructions to set up our shufb emulation and just one instruction to emulate a thousand times in a loop. When I went to test our optimized shufb, I was able to see an 8% performance uplift, a testament to how important this instruction is to the PlayStation 3. Pretty awesome for optimizing our first instruction on arm. Except half the games now refuse to boot. All right, since using TBX or TBL with two input vectors requires both input vectors to be adjacent in the registers, this places a lot of constraints on the register allocator. And with how LLVM is configured in RPCS3, it just seems to give up at a certain point and crash with this message.
So, I was left with two choices. Give up on the optimization or just enable it for games where it doesn't break. But, that really sucks as we're talking about an 8% uplift here. I was really bummed out. After that fixed the busy wait and now the shufb optimization, I felt like I had real momentum. But, now I didn't know what to do. It took me some time, but after an obscene amount of testing and debugging, I settled on the world's stupid solution. Just catch the crash when LLVM fails to compile a block with two source TBX or TBL. Then retry it with a single source TBX and TBL. It's an absolutely awful solution, but hey, when 10,000 recompiled blocks compile successfully with the two source versions and only three blocks need the fallback method, we can keep our 8% speed up and keep all of our compatibility.
With all of that solved, I've moved on to porting some more optimizations over to arm. I've been making YouTube videos on RPCS3 optimizations for a while now, and since the optimizations I've covered thus far focused on x86 machines, many commenters expressed interest in coverage of simpler instruction sets. Here's the secret though, ARM is every bit as complex as x86. It's an absolute mess actually. You know, when the first M1 MacBooks came out, there was this anecdote from one of the designers of the original ARM system that kept appearing in every YouTube review, where they didn't hook up the power supply to the ARM chip, and yet it was still running off parasitic power from the rest of the system. Look, I'm a YouTuber too. I understand. It's a nice little anecdote, and it adds to the storytelling of a review video, but the ARM chips of the '80s don't have anything to do with the ARM chips of today. I mean, modern ARM chips are massive machines with a massive instruction set. The manual alone is 17,000 pages.
I mean, just look at this. These three instructions have separate encodings, but have identical behavior on a device with ARM's latest consumer-focused cores. It's a mess, man. Look, a lot of people have said something along the lines of, "Wow, instruction. Nice optimization, but what will you do on simpler instruction sets like ARM?" But the ARM instruction US.dot behaves identically
to VPDPBUS D. Having simpler mnemonics doesn't make it a simpler instruction set. Maybe I'm making a mountain out of a molehill here, but the point I'm trying to make is that modern ARM has way more in common with modern x86 than ARM machines from the '80s. There's a silver lining to this, though. This means that a number of optimizations we can make are going to just be straightforward ports of x86 optimizations to ARM. I can't count the number of times I read on Reddit or YouTube that RPCS3 needs a complete rewrite, or a brand new emulator needs to be born to properly take advantage of ARM hardware. And it's like, "No, dude. We just got to put the square in the square hole. It's pretty straightforward, really." I covered sum B in more detail in this earlier video, but to make it short, this instruction sums two vectors horizontally like this, then packs the result like this. x86 and ARM both have dot product instructions, which first multiply bytes vertically, then sum horizontally. So, by using these dot product instructions with a multiplicand of one, we can sum in the same way that sum B does, and then pack the result as needed. Adding this optimization to ARM was as simple as dropping the u. instruction in where we were previously using VPDPBUS D.
Anyways, one more place where dot product instructions are applicable for RPCS3 is in emulating the gather bit family of instructions. On x86, we haven't elected to use the dot product instructions, as x86 has access to the move masked family of instructions, which can emulate the bit gather operations in a fairly idiomatic way. We also have an insanely optimized implementation which uses the Galois field instructions if your machine supports them. Let's take you through the dot product-based optimization. All GBB does, essentially, is take the least significant bit from each byte and pack them, like so, zeroing out the rest of the register. This time, when using the dot product instructions, we're going to make use of another cute trick. Instead of multiplying by one, we instead multiply by powers of two. Essentially, by using a different power of two for each lane, and by masking off everything but the least significant bit, we can use the dot product instruction to essentially gather bits for us. Since each result of our dot product will only contain four bits, we need to shuffle our results into the correct lane, then execute this add pairwise instruction to horizontally sum our results into the correct location. Pretty slick.
But, most of the time the gather bit instructions are used, they use following a comparison instruction. Comparison instructions fill the result with -1 or 0. -1 in two's complement means that all the bits in the number are set. Here's the trick, though. By multiplying with a negative power of two, we can skip isolating the least significant bit, saving another instruction. The dot product instructions on both x86 and ARM were added with the intent of accelerating AI, but they're useful outside of that domain, as well. ARM actually goes further than x86 in this regard, and has even more powerful AI instructions on modern ARM machines. The UMMLA and SMMLA instructions from the i8mm extension help us economize even further on instruction count. These instructions split each half of both input vectors into eight bytes. The first half of the first vector is multiplied against both halves of the second vector, horizontally summing each result, and same with the second half of the first vector, producing four results.
We can apply the same sign trick when the input is a result of a comparison. This means that we only need two instructions to emulate the common case of GBH and GBB, which produce eight bits and 16 bits as a result, respectively. Since GB produces just four bits as a result, the existing dot product optimization from earlier already achieved a two instruction solution. Slick. Let's move on to some more straightforward uses of multiplication. The SPU integer multiplication instructions are all 16-bit * 16-bit, but they produce 32-bit results. To emulate these instructions, we mask off an appropriate number of bits, then just throw 32-bit multiplies of x86 or ARM at them. We also have some pattern matching that follows this 32-bit * 32-bit multiplication pattern from the SPU manuals, and simply emulate that with a single instruction. Sweet.
But ARM actually also has widening multiply instructions. Instructions that do 16-bit * 16-bit and produce a 32-bit result. Only problem is, they expect the inputs to be packed in a form that's quite different from how the SPUs expect them. That being said, we can still save some instructions by using these widening multiplies. Looking at the most straightforward of the SPU multiplies, we have MPY. It's a signed multiplication. Instead of simply masking off the upper bits, we need to first shift the bottom 16 bits left 16 bits, then shift those back right to sign extend those numbers to 32 bits, such that we can properly perform sign multiplication. When using the widening multiplies, it looks like this. We can use the XTN instructions to take the low order 16 bits from each 32-bit lane and pack them in the low 64 bits of the vector. We do this again for the other input, and then we can use the widening multiply, SMLAL, which will take the packed 16-bit values in each 64-bit input and place the 32-bit results in the expected 128-bit vector.
That brings us down from five instructions for MPY down to just three. There's a wide variety of SPU multiply instructions. Here's what we're able to save with similar optimizations for the other SPU multiply instructions. The SVE2 versions of widening multiplies are even more useful for our PCSX2, but there's a lot of caveats to the SVE instruction set extensions that I need to address before we can talk about them. So, let's bury that thought in the sand for now. Let's first cover the rest of the NEON optimizations that all ARM users can benefit from. All right. FC GT is one of those instructions where I compared the ARM LLVM output to X86 earlier. Suffice to say, LLVM completely dropped the ball when it came to optimizing this code.
I'm not even going to attempt to explain what it's doing. I tried massaging the code all over to see if I can get rid of this bug, but nothing seemed to work right. In the end, the only thing that worked was adding inline assembly of the instruction I expected to be there, BSL. FC GT is a difficult instruction to emulate. It's just a floating-point comparison, but on the PlayStation 3's SPUs, NaN and infinity don't exist. So, we need to work around that. To properly emulate the instruction, we need a comparison to see if A is bigger than B, then perform a second comparison to see if B is smaller than A.
Then, based on whether or not both inputs were negative, we select between the two results. The BSL instruction is what does the select. All this nonsense was replaced with BSL, 15 instructions down to just seven. It's unfortunate because using inline assembly to address this issue inhibits further optimizations from LLVM. I opened an issue for upstream LLVM such that we can drop this workaround when it's addressed. The FSM family of instructions exhibit another complete failure to optimize by LLVM. This is despite the same code optimizing just fine on X86, and all the same instructions existing basically one-to-one on ARM. Let's first explain what the X86 code is doing here. FSM is basically the reverse operation of the gather bits family of instructions. It takes the compacted bits from a gather bits operation and expands them into byte, 16-bit, or 32-bit elements of all zeros or all ones.
So, on X86, we broadcast that packed value to all the lanes and that value with a constant to mask off the appropriate bit that will expand into all ones or all zeros, then compare with that same value we ended with. Only three instructions are needed. The ARM code, on the other hand, is absolutely insane. It starts by using this SBFX instruction, sign bit field extract. Essentially, it's grabbing one bit at a time and extending it to all ones or all zeros. Then it grabs those expanded bits and inserts them into a vector. But then it does it again and again and again. It entirely scalarized this vector operation. It's awful. Anyways, I opened an issue on LLVM's GitHub this time, too. The workaround is just to write the LLVM IR to be more idiomatic, basically matching what the x86 code did. The funny thing, this way we end up with a solution that's only two instructions, faster than the x86 way. See, ARM has the instruction CM TST, which is basically a combined and plus compare instruction. It's pretty sweet.
Next, we need to fight LLVM again to optimize all these instructions. The SHL instructions are shift left instructions. The ROTM instructions are shift right instructions. They actually stand for rotate and mask, but a rotate that masks in zeros is basically just a shift. These instructions first mask off a certain number of bits, depending on the size of the elements that the instruction operates on. For instance, the shift left word instruction masks off everything but the bottom six bits. In this case, the bottom five bits indicate how much to shift. If the sixth bit is set, then we fill the result with zero. On x86, shifting works the same way, except it doesn't mask off the upper bits. So, if any of them are set, all zeros will be shifted in. So then, to emulate the PlayStation 3 behavior correctly, we just need one AND instruction to mask off everything but the bottom six bits and then execute one shift instruction. So, just two instructions are needed. The ARM equivalent shift instructions work the same way as x86, with one exception.
Instead of having a shift left instruction and a shift right instruction, the USHL instruction shifts left if the value is positive and shifts right if the value is negative. All right, but that doesn't matter for emulation of PS3 SHL. But then why is the same LLVM code compiling down to four instructions for ARM? Okay, so the LLVM IR for shifts leaves part of the implementation undefined. When you expect to shift in zeros, we actually shift in something known as poison values. So we need this code to replace the potential poison values with zeros. We expect the optimizers to handle this and just realize, "Oh hey, native shift instructions on this machine will shift in zeros." But for whatever reason, that's not working on ARM. Anyways, once again, I've opened an issue with upstream LLVM and implemented a workaround by using the intrinsic for USH in the meantime. That saves two instructions for each shift instruction, mostly matching X86. The raw MM instructions still require one instruction over X86 as USH needs that shift count to be negated to rotate right. With that, we've covered the most catastrophic code gen issues.
But now, it's time for something completely different. So far, we've been optimizing the obvious things, the low-hanging fruit. They're so overripe that they started to ferment. But I wanted something more interesting, the kind of interesting that comes from staring at hardware manuals until you're delirious. And man, ARM hardware like the Snapdragon 8 Gen 2 on this Odin 2 leads to all sorts of interesting. Actually, it's technically a DragonWing QC 8550, which is basically just a Snapdragon 8 Gen 2 without the wireless functionality of a smartphone. But the marketing material for the Odin 2 still calls it a Snapdragon 8 Gen 2, and I'll also be referring to it as such for the rest of this video. Anyways, the Snapdragon 8 Gen 2 is pretty unique as it features four different core types. The Cortex-X3 is the biggest and fastest core and offers high performance at the expense of die area and power consumption. There are two Cortex-A715s, which offer a reasonable balance to performance, power, and size. There are two more A710 cores, which are essentially the previous generation of A715s. Why are they included? Well, the X3 and the A715s dropped support for 32-bit arm instructions. So, Qualcomm included the A710 so that 32-bit programs could still run for one more generation with reasonable performance.
Finally, there are three small cores, the Cortex A510s. These cores are quite slow, but sip power and barely take up any die space. Unfortunately, many of the concessions made make them quite inadequate for PlayStation 3 emulation. For instance, these two Cortex A510s share a single 128-bit vector unit. So, when we're emulating SIMD-heavy PlayStation 3 code, even if every PlayStation 3 instruction was emulated with one host arm instruction, the A510s could still end up being significantly slower than the original PlayStation 3. The third A510 actually doesn't share a vector unit, but it has exclusive access to a 64-bit vector unit. So, 128-bit instructions execute at half the speed.
So, really, if you count the clustered A510s and the unclustered A510s as different core types, you're looking at five different cores in a machine with eight cores total. It's a little ridiculous. You might then consider me absolutely insane for attempting to micro-optimize for this hardware, but let me just explain. The A715 and A710 share almost the same behaviors as they share a lineage. The current lineage of mid cores was sort of crystallized with the A78. Then all these mid cores up to today have a lot of shared behavior. There's one thing that these cores do which is unusual not just for all other arm cores, but any other CPU I've ever seen. They can do more vectorized loads than they can do actual vectorized operations per clock. See, if you look at this random Intel CPU, we can do two 256-bit loads per clock and three 256-bit vector operations per clock. A slightly newer Intel CPU can do three 256-bit loads per clock and three 256-bit vector operations per clock. If you look at the latest AMD core, we can do two 512-bit loads per clock and four 512-bit vector operations per clock.
Moving on to arm CPUs, the Cortex X3, the big core of the Snapdragon 8 Gen 2, is similarly capable of 328-bit loads per clock and 428-bit vector operations per clock. What I'm trying to make here is that you typically expect cores to be capable of more vector operations than loads, or at least an equal number of vector operations to loads. But, the Bent cores, all of them, are capable of 328-bit loads per clock, but only two vector operations per clock. Considering these cores have been so min-maxed in area otherwise, the lopsided load performance is surprising to me. Even if we consider the performance of workloads that stream from memory and need the bare minimum of vector operations, like for instance, with a comparison function, we still need a one-to-one ratio of vector operations to loads. How could this capability ever be useful?
Well, let's actually illustrate this so that we can understand. When comparing, one way of writing it might be to load one value from each source stream, XOR the two values, then OR the result into an accumulator. Then, we repeat that process over and over until all the data is consumed and accumulated. That way, when we check the accumulator at the end, anytime the data wasn't equivalent, we would have accumulated a set bit in the accumulator. This is thanks to a neat property of XOR. Anytime we XOR the same value into itself, we get a result of zero. So, naturally, if you wanted to try and speed up comparison operations on these cores, the first thought is to look at ARM's three-input bitwise instructions.
If each operation could consume an input from each source and accumulate directly, we could save on a lot of instructions and actually utilize all three load ports of our ARM mid cores. BSL, bit, and BIF don't have any XOR operation, so they're not useful here. EOR3 is just three XOR operations chained together, and BCAX is also lacking what we need. So, maybe we can look towards the cryptography instructions. These are also three-input instructions configured to be useful for just a single algorithm. And yeah, none of these are even close to useful for us. So, fine. What are the remaining instructions we have? Well, we've got instructions that take the absolute difference between two values and accumulate that. We've got instructions which multiply two integers and accumulate that. We've got instructions that multiply two floats and accumulate that. And finally, we have the dot product instructions that we used to emulate some B and GBB.
None of these are obviously useful for accelerating something like a comparison, but I simply refuse to believe that there is no use for the three load ports of the most common arm cores out there. So, I just thought about it every day until my third eye opened or some [ __ ] because I realized we can use multiply accumulate instructions to accelerate comparisons. Hear me out. When we execute a comparison instruction, what do we get? When a comparison is true, we get a result of all ones, which can also be interpreted as -1. When a comparison isn't true, we get a result of zero, which can be interpreted as zero.
Okay. Okay. Suppose we tried to multiply two comparison results together and then tr





