<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.9.0">Jekyll</generator><link href="https://densinh.github.io//DenSinH/feed.xml" rel="self" type="application/atom+xml" /><link href="https://densinh.github.io//DenSinH/" rel="alternate" type="text/html" /><updated>2022-03-31T19:07:06+00:00</updated><id>https://densinh.github.io//DenSinH/feed.xml</id><title type="html">Dennis H</title><subtitle>Blog of a programmer in the Netherlands.</subtitle><entry><title type="html">[GBA] EEPROM Save Type</title><link href="https://densinh.github.io//DenSinH/emulation/2021/02/01/gba-eeprom.html" rel="alternate" type="text/html" title="[GBA] EEPROM Save Type" /><published>2021-02-01T11:00:00+00:00</published><updated>2021-02-01T11:00:00+00:00</updated><id>https://densinh.github.io//DenSinH/emulation/2021/02/01/gba-eeprom</id><content type="html" xml:base="https://densinh.github.io//DenSinH/emulation/2021/02/01/gba-eeprom.html">&lt;h1 id=&quot;eeprom-save-type&quot;&gt;EEPROM Save Type&lt;/h1&gt;

&lt;p&gt;The GBA has games with different sorts of backup memory. There are 3 types:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;SRAM, straightforward RAM on the cartridge&lt;/li&gt;
  &lt;li&gt;Flash, flash storage on the cartridge (explained &lt;a href=&quot;https://dillonbeliveau.com/2020/06/05/GBA-FLASH.html&quot;&gt;here&lt;/a&gt;)&lt;/li&gt;
  &lt;li&gt;EEPROM, which I will attempt to explain in this document.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can see what save type a cartridge uses most accurately by using a game database. If you don’t have one of those available, you can check for certain strings in the cartridge (also explained &lt;a href=&quot;https://dillonbeliveau.com/2020/06/05/GBA-FLASH.html&quot;&gt;here&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;&lt;a href=&quot;http://problemkaputt.de/gbatek.htm#gbacartbackupeeprom&quot;&gt;GBATek&lt;/a&gt; also explains the EEPROM save type, but I found it quite brief, so I will try to add on to this documentation.&lt;/p&gt;

&lt;h3 id=&quot;eeprom-types&quot;&gt;EEPROM types&lt;/h3&gt;

&lt;p&gt;There are 2 different types of EEPROM cartridges:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;512 bytes / 4Kbit EEPROM&lt;/li&gt;
  &lt;li&gt;8KB / 64Kbit EEPROM&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Which of these 2 a cartridge has is impossible to figure out just by looking at the cartridge. Your only options are a game database, or a trick where you check the first access made to it, which I will explain later.&lt;/p&gt;

&lt;h3 id=&quot;addressing-and-waitstates&quot;&gt;Addressing and waitstates&lt;/h3&gt;

&lt;blockquote&gt;
  &lt;p&gt;The eeprom is connected to Bit0 of the data bus, and to the upper 1 bit (or upper 17 bits in case of large 32MB ROM) of the cartridge ROM address bus, communication with the chip takes place serially. (GBATek)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This means that data transferred to or from the EEPROM chip is always 1 bit at a time. Any transfer made to EEPROM will be “masked” to only the bottom bit, and any read will just be 1 or 0.&lt;/p&gt;

&lt;p&gt;On a large ROM (of greater than 16MB in size), ROM is restricted to &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0x0800'000h-0x09ff'feff&lt;/code&gt;. So, EEPROM can be accessed between &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0x09ff'ff00&lt;/code&gt; and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0x09ff'ffff&lt;/code&gt;. This is also mirrored to the higher waitstate cartridge regions. Judging from the source code of certain emulators, it can really onlly be accessed in the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0x0dxx'xxxx&lt;/code&gt; region of ROM (second waitstate), despite what GBATek says. On smaller ROMs, it can also be accessed between &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0x0d00'0000-0x0dff'ffff.&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;The actual address that is accessed for the EEPROM access does not matter, as the “internal address” has to be sent first, and then data can be written or read.&lt;/p&gt;

&lt;p&gt;Data can be read or written. The initial pattern for the access is similar: the mode has to be sent, and the address as well.&lt;/p&gt;

&lt;p&gt;This is also where the different EEPROM sizes come into play. The EEPROM can only transfer data in units of 64 bits. Addressing also works in units of 64 bits. This means, that while for a 512 byte EEPROM, you have 0x200 bytes to address, there are only 0x40 blocks of 64 bits. The address will only be in the range of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0 - 0x3f&lt;/code&gt;. The bus width for a 512 byte EEPROM is 6, and the address that will be sent will also be 6 bits long.&lt;/p&gt;

&lt;p&gt;For an 8KB EEPROM, there are 0x2000 bytes, but only 0x400 blocks of 64 bits. The address will thus only be in the range &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0 - 0x3ff&lt;/code&gt;. The bus width for a 8KB EEPROM is 14 bits, but the address only 10. The address that gets sent will be 14 bits long, but the first 4 bits should be zero, as they don’t correspond with any blocks.&lt;/p&gt;

&lt;p&gt;It is important to actually have the addressing happen in blocks of 8 bytes / 64 bits. I did this wrong in my emulator at first, and it caused some sneaky corrupted saves.&lt;/p&gt;

&lt;h3 id=&quot;reading-data&quot;&gt;Reading data&lt;/h3&gt;

&lt;p&gt;When you want to read data from the EEPROM, you have to send the following sequence of bits:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;2 bits &quot;11&quot; (Read Request)
n bits eeprom address (MSB first, 6 or 14 bits, depending on EEPROM)
1 bit &quot;0&quot;
(GBATek)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;

&lt;h4 id=&quot;eeprom-size-detection&quot;&gt;EEPROM size detection&lt;/h4&gt;
&lt;p&gt;This &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;n&lt;/code&gt; is what you can deduce the EEPROM size from. A trick to detect the EEPROM size is to keep it ambiguous until the first (read) request is made. Requests have to be done by DMA, since normal transfers via LDRH/STRH are too slow, and don’t keep the right bits set during the transfer.&lt;/p&gt;

&lt;p&gt;Since DMA channel 3 is the only DMA channel that can access ROM, you could, on the first (read) access, check the transfer length of DMA channel 3. If it’s of length 9, a 6 bit address will be sent, and the EEPROM is (likely) a 512 byte EEPROM. If it’s of length 17, a 14 bit address will be sent, and the EEPROM is (likely) an 8KB EEPROM.&lt;/p&gt;

&lt;p&gt;This method is not perfect though. Some games, like the NES classic series, try to trick you into thinking it’s the wrong EEPROM size, by doing a transfer of the “wrong” length. Your best bet will be a game database, or some sort of hybrid approach.&lt;/p&gt;

&lt;h4 id=&quot;the-transfer&quot;&gt;The transfer&lt;/h4&gt;

&lt;p&gt;Since it’s annoying to have to place individual bits at a (half)word interval in memory to then transfer data, a common approach for games/programs is to “shift” them into memory. Basically, if I wanted to send a read request to an 8KB EEPROM to block &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0x123&lt;/code&gt;, I would need to transfer: &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;(0b11 &amp;lt;&amp;lt; 15) | (0x123 &amp;lt;&amp;lt; 1) | 0 = 0x18246&lt;/code&gt;. Suppose &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;r1&lt;/code&gt; holds a pointer to a the end of a 17 halfword buffer where we want to store our bits, and &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;r0&lt;/code&gt; holds &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0x18246&lt;/code&gt;. One could simply do&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-ARMASM&quot;&gt;strh r0, [r1], #-2
lsr r0, #1
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;17 times, and the buffer will then be filled with&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;0x0001
...
0x3048
0x6091
0xc123
0x8246
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;such that the 0th bit of each halfword exactly reads out &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0x18246&lt;/code&gt; (MSB first). I can then transfer this buffer to EEPROM. Since only bit 0 is connected to the data bus, it does not matter that there is other data in the other 15 bits of each halfword.&lt;/p&gt;

&lt;p&gt;This is how the address is transferred for a read access. After the address is transferred, we can read back the data. This again has to happen by DMA. There are 68 bytes to be read back with DMA:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;4 bits  - ignore these
64 bits - data (conventionally MSB first)
(GBATek)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;These accesses have to be made in the same region as the address has to be written to, but just read instead of written. After this, it is up to the game how it handles the individual bits returned by the DMA.&lt;/p&gt;

&lt;h3 id=&quot;writing-data&quot;&gt;Writing data&lt;/h3&gt;

&lt;p&gt;The written data immediately follows the address that is written. I have never encountered a game doing a write access before a read access, but it’s possible, so it might be good to check if this is the case when trying to detect the EEPROM’s size.&lt;/p&gt;

&lt;p&gt;The data that has to be written is:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;2 bits &quot;10&quot; (Write Request)
n bits eeprom address (MSB first, 6 or 14 bits, depending on EEPROM)
64 bits data (conventionally MSB first)
1 bit &quot;0&quot;
(GBATek)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;So the start is similar to the read request, except a different “code”. Then the address, again different sizes depending on the EEPROM’s size. Then 64 bits / 8 bytes of data, and one bit to end the transfer.&lt;/p&gt;

&lt;p&gt;These transfers might also be made in a similar way to the read access, where the data is first “shifted” to a buffer, and then transferred by DMA.&lt;/p&gt;

&lt;p&gt;After a write transfer, games likely check if the transfer is complete. They do this by reading from the EEPROM and waiting until it returns 1. Martin Korth describes in GBATek how it’s important to set a timeout if the EEPROM does not respond, but some games might just hang if you don’t return 1 on reads after a write access.&lt;/p&gt;</content><author><name>DenSinH</name></author><category term="emulation" /><summary type="html">EEPROM Save Type</summary></entry><entry><title type="html">[GBA] Writing a cached interpreter</title><link href="https://densinh.github.io//DenSinH/emulation/optimizations/2021/01/31/cached-interpreter.html" rel="alternate" type="text/html" title="[GBA] Writing a cached interpreter" /><published>2021-01-31T18:00:00+00:00</published><updated>2021-01-31T18:00:00+00:00</updated><id>https://densinh.github.io//DenSinH/emulation/optimizations/2021/01/31/cached-interpreter</id><content type="html" xml:base="https://densinh.github.io//DenSinH/emulation/optimizations/2021/01/31/cached-interpreter.html">&lt;h1 id=&quot;writing-a-cached-interpreter&quot;&gt;Writing a cached interpreter&lt;/h1&gt;

&lt;p&gt;A while ago, I rewrote my GBA emulator (GBAC-) in C++ (DSHBA) to make it faster. I wanted to add a hardware renderer, and really focus on optimizing it all the way.
After I was “done”, and had reached framerates higher than I had ever hoped before, I recently came back to it, and wanted to try to write a cached interpreter. 
I have heard a lot of talks about JITs and cached interpreters for performance gain, and since I had reached pretty insane framerates already, I wanted to go even further.&lt;/p&gt;

&lt;p&gt;&lt;b&gt;Note: this is not a general guide for writing a cached interpreter, and this approach might not be viable on every system. In this post I will explain why that is, and focus on my thought
process and the implementation for my cached interpreter.&lt;/b&gt;&lt;/p&gt;

&lt;h3 id=&quot;why-not-a-jit&quot;&gt;Why not a JIT?&lt;/h3&gt;

&lt;p&gt;Something you might ask is: “why did you write a cached interpreter and not a JIT”. The short answer to this is this: accuracy. The GBA is a fairly old system. Usually for older
systems, timings are important. Where for modern systems, you don’t have to worry about cycles for the most part, other than being in the right ballpark (this is mainly because for 
more modern systems, the programmer himself can also rely less on specific timings due to pipelining, OoO execution and other advanced techniques), for the GBA you still sort of have to.
A lot of tests, even in the official AGS Aging Cartridge test from Nintendo, some tests require accuracy within 16 cycles (in a frame of ~1200 cycles, or 1 scanline), or some even perfect
cycle accuracy. Games may also rely on specific timings.&lt;/p&gt;

&lt;p&gt;My old GBA emulator and my new one had the same performance in terms of accuracy. I passed most AGS tests, a lot of Endrift’s tests, but not any of the crazy perfect cycle accuracy ones. This
was good enough for me, but I wouldn’t want to reduce accuracy for the sake of speed. These timings are easiest to emulate in an interpreter. In a JIT, you want to mostly just keep track of
your GPRs (General Purpose Registers), and not of PPU events happening, or audio samples being requested, and most importantly: IRQs firing at the right times. These things, will often require 
me to check the scheduler, or break blocks early at “random” moments. These things combined led me to write a cached interpreter and not a JIT.&lt;/p&gt;

&lt;h3 id=&quot;how-does-a-cached-interpreter-work&quot;&gt;How does a cached interpreter work?&lt;/h3&gt;

&lt;p&gt;First of all, this is how my interpreter loop looked before my cached interpreter:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;check scheduler:
    if there are events to handle: do events 
    otherwise: step once
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;Then let’s first look at the classic interpreter. The idea for this is very simple:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;fetch opcode from memory
decode opcode 
run instruction handler
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;Alright, simple enough. This seems very straight forward, but there is a step here that we can remove. If we decode an instruction, and later on we get to the same address, we
wouldn’t have to decode it again if we store the information on the instruction. This is “caching” the instruction. We can make it even better than this though, we can make entire 
blocks of instructions at once, so that we dont have to look up the cached instruction every time, but just look up a block and run for multiple instructions at once!&lt;/p&gt;

&lt;p&gt;Now, the GBA memory map has some mirroring, and code cannot be ran from all regions. So I decided to split things up a bit. There are 3 regions I allow caching in:&lt;/p&gt;
&lt;ul&gt;
  &lt;li&gt;the BIOS: this region cannot be written to, so once we make a cached block, we never have to delete it again!&lt;/li&gt;
  &lt;li&gt;ROM: this region is also not writeable, so we can save the cache blocks forever!&lt;/li&gt;
  &lt;li&gt;iWRAM: code often gets run from here because it takes very few cycles to fetch data from here. We have to handle this region slightly differently though, because code can get overwritten.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Cache “blocks” are blocks of instructions following each other that can be executed after each other. These blocks have to end somewhere, and the most logical places are branches or
on certain boundaries. I set these boundaries at every 256 bytes. This number is rather arbitrary, but setting this number allows you to only delete certain blocks when writes to
iWRAM happen.&lt;/p&gt;

&lt;p&gt;The idea for the main loop of the emulator becomes slightly different:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;check if current address has a cached block 
if it doesn't have one, and none can be created: 
    run interpreter normally, until it can 
if it doesn't have one, and one can be created:
    make a cache block and run interpreter normally*, but record the instructions
if it has one:
    run the cache block**
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;Now this is not the entire story. As I mentioned before, there is still a scheduler, and IRQs might happen that interrupt a block. Now what I could naively do (and did at first) is just
break whenever we are interrupted by the scheduler. I don’t need to always break though. Some events, like adding a sample to the audio buffer, shouldn’t need to interrupt the CPU at all, since
they don’t have anything to do with it!&lt;/p&gt;

&lt;p&gt;I changed up my scheduler slightly, and made every event return a boolean, whether they directly affected the CPU state or not. Events that do are events like IRQs, or DMAs where an IRQ happened inbetween.
The extra steps will be:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;(*): check if the scheduler interrupted the CPU, and if so, return from making the block

(**): check if the scheduler interrupted the CPU, and if so, return from running the block
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;So in the end, the general idea will be this:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;while true:
    check current address
    if we are not in a cacheable region (not in ROM/BIOS/iWRAM), do:
        while we are not in a cacheable region:
            check scheduler and run events 
            step, and check if we are in a cacheable region now.
    if we are in a cacheable region, but no cache exists:
        make a cache 
        while true:
            check the scheduler and run events
                if the scheduler affected our CPU: break the block and destroy it 
            fetch 
            decode and store in cache 
            run 
            if the block should end (branch): break 
    if we are in a cacheable region, and a cache exists:
        get the cache 
        for every instruction in the cache:
            check the scheduler and run events
                if the scheduler affected our CPU: break
            run the instruction (in ARM mode: only if condition is true)
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;This might seem a bit abstract, so here is some actual code. Before I added the cached interpreter, the main loop essentially looked like this (some details like pipeline stuff are left out):&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-CXX&quot;&gt;while (true) {
    while (!Scheduler.ShouldDoEvents()) {
        CPU.Step();
    }

    Scheduler.DoEvents();
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;with&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;ARM7TDMI::Step() {
    u32 instruction;
    if (ARMMode){ 
        instruction = Mem-&amp;gt;Read&amp;lt;u32&amp;gt;(pc - 8);
        if (CheckCondition(instruction &amp;gt;&amp;gt; 28)) {
            (this-&amp;gt;*ARMInstructions[ARMHash(instruction)])(instruction);
        }
    }
    else {
        instruction = Mem-&amp;gt;Read&amp;lt;u16&amp;gt;(pc - 4);
        (this-&amp;gt;*THUMBInstructions[THUMBHash(instruction)])(instruction);
    }
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;A classic interpreter loop. Now we want to add something to store our cache blocks in.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-CXX&quot;&gt;// a simple struct holding the instruction and the handler
struct CachedInstruction {
    const u32 Instruction;
    const void __fastcall (ARM7TDMI::*Pointer)(u32 instruction);
}

// a struct holding a block of instructions
struct InstructionCache {
    const bool ARM;
    const bool Deletable;  // true in iWRAM
    const u16 AccessTime;
    std::vector&amp;lt;CachedInstruction&amp;gt; Instructions;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And we want some lookup tables for the cache blocks in our CPU.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-CXX&quot;&gt;std::array&amp;lt;std::unique_ptr&amp;lt;InstructionCache&amp;gt;, (Mem::BIOSSize &amp;gt;&amp;gt; 1)&amp;gt; BIOSCache = {};
std::array&amp;lt;std::unique_ptr&amp;lt;InstructionCache&amp;gt;, ((Mem::iWRAMSize - Mem::StackSize) &amp;gt;&amp;gt; 1)&amp;gt; iWRAMCache = {};
std::array&amp;lt;std::unique_ptr&amp;lt;InstructionCache&amp;gt;, (Mem::ROMSize &amp;gt;&amp;gt; 1)&amp;gt; ROMCache = {};
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You might notice some things here. First of all, the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;unique_ptr&lt;/code&gt;s. I know that dynamic allocation is slow in general. I rewrote it to not use dynamic allocation, and I did not notice a difference.
Main reason for this might be that blocks will never be deleted in ROM and in the BIOS, and it might be rare for blocks to be deleted in iWRAM. Another benefit this has is that I don’t have to 
worry about writing a bump allocator (a big region of memory that I push instructions to until it overflows, and then reset the entire thing), the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;unique_ptr&lt;/code&gt;s will handle memory allocation for me!&lt;/p&gt;

&lt;p&gt;Another thing to note is that I shift the size of the respective regions by 1. This is because all instructions must be aligned by 4 in ARM mode, and 2 in THUMB mode.&lt;/p&gt;

&lt;p&gt;Last thing, for the iWRAM cache I subtract &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Mem::StackSize&lt;/code&gt;. This is an arbitrary number (that I think I put at &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;0x400&lt;/code&gt;). I did this, because when writes to iWRAM happen, I have to check out which
blocks have to be deleted. Since the stack is also in iWRAM, a lot of pushes will happen, and I don’t want to check which blocks to delete on every push/pop.&lt;/p&gt;

&lt;p&gt;One last thing then. We need to keep track of our current cache.&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-CXX&quot;&gt;std::unique_ptr&amp;lt;InstructionCache&amp;gt;* CurrentCache = nullptr;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The way this works is very convenient. This might seem like 2 layers of indirection, but while running the cache we can just look at the object that is finally pointed at. In general this is what
we will be doing anyway. This is convenient, because we can use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;nullptr&lt;/code&gt; to encode different states:&lt;/p&gt;
&lt;div class=&quot;language-plaintext highlighter-rouge&quot;&gt;&lt;div class=&quot;highlight&quot;&gt;&lt;pre class=&quot;highlight&quot;&gt;&lt;code&gt;CurrentCache == nullptr: no cache present, no cache can be made
CurrentCache == nullptr*: no cache present, cache can be made
otherwise: cache present!
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;/div&gt;
&lt;p&gt;We also need a way to update the current cache (simplified to remove some range checks etc.):&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-CXX&quot;&gt; constexpr std::unique_ptr&amp;lt;InstructionCache&amp;gt;* ARM7TDMI::GetCache(const u32 address) {
    switch (static_cast&amp;lt;MemoryRegion&amp;gt;(address &amp;gt;&amp;gt; 24)) {
        case MemoryRegion::BIOS: {
            const u32 index = (address &amp;amp; (Mem::BIOSSize - 1)) &amp;gt;&amp;gt; 1;
            // check if cache exists
            if (BIOSCache[index]) {
                return &amp;amp;BIOSCache[index];
            }

            // show that no cache exists, but can be created
            return &amp;amp;BIOSCache[index];
        }
        case MemoryRegion::iWRAM: {
            const u32 index = (address &amp;amp; (Mem::iWRAMSize - 1)) &amp;gt;&amp;gt; 1;
            if ((address &amp;amp; (Mem::iWRAMSize - 1)) &amp;lt; (Mem::iWRAMSize - Mem::StackSize)) {
                if (iWRAMCache[index]) {
                    return &amp;amp;iWRAMCache[index];
                }
                // mark index as filled for faster page clearing
                iWRAMCacheFilled[(address &amp;amp; (Mem::iWRAMSize - 1)) / Mem::InstructionCacheBlockSizeBytes].push_back(index);
                return &amp;amp;iWRAMCache[index];
            }
            return nullptr;
        }
        case MemoryRegion::ROM: {
            const u32 index = (address &amp;amp; (Mem::ROMSize - 1)) &amp;gt;&amp;gt; 1;
            if (ROMCache[index]) {
                return &amp;amp;ROMCache[index];
            }
            return &amp;amp;ROMCache[index];
        }
        default:
            return nullptr;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Ignore the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;iWRAMCacheFilled&lt;/code&gt; line for now. Alright, so now we have everything set up to make caches! First of all, we need different run loops:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-CXX&quot;&gt;ARM7TDMI::Run();
ARM7TDMI::RunMakeCache();
ARM7TDMI::RunCache();
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Running the cache is the simplest method:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-CXX&quot;&gt;void ARM7TDMI::RunCache() {
    // run created cache
    const InstructionCache&amp;amp; cache = **CurrentCache;

    if (cache.ARM) {
        // ARM mode, we need to check the condition now too
        for (const auto&amp;amp; instr : cache.Instructions) {
            if (unlikely(Scheduler-&amp;gt;ShouldDoEvents())) {
                if (unlikely(Scheduler-&amp;gt;DoEvents())) {
                    return;  // CPU state affected
                }
            }

            *timer += cache.AccessTime;  // add time we would otherwise spend fetching the opcode from memory
            if (CheckCondition(instr.Instruction &amp;gt;&amp;gt; 28)) {
                (this-&amp;gt;*instr.Pointer)(instr.Instruction);
            }
            pc += 4;

            // block was destroyed (very unlikely)
            if (cache.Deletable &amp;amp;&amp;amp; unlikely(!CurrentCache)) {
                return;
            }
        }
    }
    else {
        // THUMB mode, no need to check condition
        /*
         * the code here is essentially the same as above
         */
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Making the block looks very similar to the old loop, but then with a twist. 
I templated my basic &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;ARM7TDMI::Step()&lt;/code&gt; to take a boolean &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MakeCache&lt;/code&gt;. If we are not making a cache, I made the step function return a boolean saying whether we are in a cacheable region or not. That
means that &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Step&amp;lt;false&amp;gt;&lt;/code&gt; is the same as the original, basic interpreter step function, except it returns&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-CXX&quot;&gt;InCacheRegion(corrected_pc);  // corrected_pc = pc - (ARMMode ? 8 : 4)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If we are making a cache, we need to record the instructions we find. Then it looks a bit more complex:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-CXX&quot;&gt;template&amp;lt;bool MakeCache&amp;gt;
bool ARM7TDMI::Step&amp;lt;true&amp;gt;() {
    u32 instruction;

    bool block_end = false;
    if (ARMMode) {
        instruction = Memory-&amp;gt;Read&amp;lt;u32, true&amp;gt;(pc - 8);
        auto instr = CachedInstruction(instruction, ARMInstructions[ARMHash(instruction)]);
        (*CurrentCache)-&amp;gt;Instructions.push_back(instr);
        
        // check if instruction is branch or an operation with Rd == pc (does not detect multiplies with pc as destination)
        block_end = IsARMBranch[ARMHash(instruction)]
                 || ((instruction &amp;amp; 0x0000f000) == 0x0000f000)   // any operation with PC as destination
                 || ((instruction &amp;amp; 0x0e108000) == 0x08108000);  // ldm r, { .. pc }
        if (CheckCondition(instruction &amp;gt;&amp;gt; 28)) {
            (this-&amp;gt;*ARMInstructions[ARMHash(instruction)])(instruction);
        }

        pc += 4;
    }
    else {
        // THUMB mode
        instruction = Memory-&amp;gt;Read&amp;lt;u16, true&amp;gt;(pc - 4);
        auto instr = CachedInstruction(instruction, THUMBInstructions[THUMBHash((u16)instruction)]);
        (*CurrentCache)-&amp;gt;Instructions.push_back(instr);
        
        // also check for hi-reg-ops with PC as destination
        block_end = IsTHUMBBranch[THUMBHash((u16)instruction)] || ((instruction &amp;amp; 0xfc87) == 0x4487);
        (this-&amp;gt;*THUMBInstructions[THUMBHash((u16)instruction)])(instruction);
        pc += 2;
    }
    
    if (block_end || !(corrected_pc &amp;amp; (Mem::InstructionCacheBlockSizeBytes - 1))) {
        // branch or block alignment
        return true;
    }
    return false;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Basically, if &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MakeCache&lt;/code&gt; is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Step&lt;/code&gt; returns whether the block has ended or not. If &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;MakeCache&lt;/code&gt; is &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;false&lt;/code&gt;, &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Step()&lt;/code&gt; returns whether a block can be made, or might be available.
The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;RunMakeCache()&lt;/code&gt; method will use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Step&amp;lt;true&amp;gt;&lt;/code&gt;, and the basic &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Run()&lt;/code&gt; method will use &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Step&amp;lt;false&amp;gt;&lt;/code&gt;, while we are not in a region where caches can be made.
The &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;RunMakeCache()&lt;/code&gt; looks like&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-CXX&quot;&gt;void ARM7TDMI::RunMakeCache() {
    // run the interpreter &quot;normally&quot;, but record the instructions we execute in the current cache
    while (true) {
        if (unlikely(Scheduler-&amp;gt;ShouldDoEvents())) {
            if (unlikely(Scheduler-&amp;gt;DoEvents())) {
                // CPU state affected
                // just destroy the cache, we want the caches to be as big as possible
                *CurrentCache = nullptr;
                return;
            }
        }

        if (unlikely(Step&amp;lt;true&amp;gt;())) {
            // cache done
            if (unlikely((*CurrentCache)-&amp;gt;Instructions.empty())) {
                // empty caches will hang the emulator
                // they might happen when branches close to pc get written (self modifying code)
                *CurrentCache = nullptr;
            }
            return;
        }

        if (unlikely(!CurrentCache)) {
            // cache destroyed by near write
            return;
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;You’ll notice that I destroy the cache if we get interrupted by the scheduler. This is because I never recreate any caches in ROM and BIOS, so I want them to be as long as possible. Worst case scenario, a lot of events
happen in a row, and we might make 10 blocks of 1 instruction each, while we could have easily made 1 block of 10 instructions, and saving a lot more cache block lookup time.&lt;/p&gt;

&lt;p&gt;If we end the block because &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Step&lt;/code&gt; returned &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;true&lt;/code&gt;, we save the block unless there are no instructions in it. Normally, you’d say this cannot happen. But since the ARM7TDMI has a pipeline that can 
hold instructions that might be overwritten in memory, it can! I might have started a block with instructions in the pipeline and ended it before it was empty. We don’t want wrong instructions
in our cache block, so I cannot add those pipelined instructions, and the block will be invalid.&lt;/p&gt;

&lt;p&gt;And then there is the normal running:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-CXX&quot;&gt;while (true) {
    if (unlikely(Scheduler-&amp;gt;ShouldDoEvents())) {
        Scheduler-&amp;gt;DoEvents();
    }
    
    // if Step returns true, we are in a region where we can generate a cache
    if (Step&amp;lt;false&amp;gt;()) {
        break;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Basically the same as the classic interpreter loop.
The entire run function becomes this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-CXX&quot;&gt;ARM7TDMI::Run() {
    while(true) {
        CurrentCache = GetCache(corrected_pc);
        if (unlikely(!CurrentCache)) {
            // nullptr: no cache (not iWRAM / ROM / BIOS)
            // run interpreter normally, without recording cache
            while (true) {
                if (unlikely(Scheduler-&amp;gt;ShouldDoEvents())) {
                    Scheduler-&amp;gt;DoEvents();
                }
                // if Step returns true, we are in a region where we can generate a cache
                if (Step&amp;lt;false&amp;gt;()) {
                    break;
                }
            }
        }
        else if (unlikely(!(*CurrentCache))) {
            // possible cache, but none present
            // make new one
            if (ARMMode) {
                const auto access_time = Memory-&amp;gt;GetAccessTime&amp;lt;u32&amp;gt;(static_cast&amp;lt;MemoryRegion&amp;gt;(pc &amp;gt;&amp;gt; 24));
                *CurrentCache = std::make_unique&amp;lt;InstructionCache&amp;gt;(access_time, true, static_cast&amp;lt;MemoryRegion&amp;gt;(pc &amp;gt;&amp;gt; 24) == MemoryRegion::iWRAM);
            }
            else {
                const auto access_time = Memory-&amp;gt;GetAccessTime&amp;lt;u16&amp;gt;(static_cast&amp;lt;MemoryRegion&amp;gt;(pc &amp;gt;&amp;gt; 24));
                *CurrentCache = std::make_unique&amp;lt;InstructionCache&amp;gt;(access_time, false, static_cast&amp;lt;MemoryRegion&amp;gt;(pc &amp;gt;&amp;gt; 24) == MemoryRegion::iWRAM);
            }
            RunMakeCache();
        }
        else {
            // cache possible and present
            RunCache();
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That is essentially it for making and running caches. There is one last, important thing we need to account for though: writes to iWRAM. 
When a write to iWRAM happens, it’s possible that it’s overwriting code that was there before. When we jump to an address, we don’t want to be running code
from our caches that is not there anymore! So, when a write to iWRAM happens, we have to clear a section of our caches in iWRAM. We could do this naively, and loop over
all 128 entries in the block of the write, check if there is a cache and destroy it. This means a lot of checking! Something else we can do, is whenever we make a cache block,
store the index of that cache block to a cache block page table. Then when a write happens to iWRAM, we just have to look up what page this is in (only a shift and a mask), and then destroy
the blocks at the indices that are in the page table. This is what the&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-CXX&quot;&gt;iWRAMCacheFilled[(address &amp;amp; (Mem::iWRAMSize - 1)) / Mem::InstructionCacheBlockSizeBytes].push_back(index);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;line meant in an earlier code block. Writing to iWRAM then has the following callback:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-CXX&quot;&gt;void ARM7TDMI::iWRAMWrite(u32 address) {
    // clear all instruction caches in a CacheBlockSizeBytes sized region
    const u32 cache_page_index = (address &amp;amp; 0x7fff) / Mem::InstructionCacheBlockSizeBytes;

    for (u32 index : iWRAMCacheFilled[cache_page_index]) {
        iWRAMCache[index] = nullptr;
    }
    iWRAMCacheFilled[cache_page_index].clear();

    if ((corrected_pc &amp;amp; ~(Mem::InstructionCacheBlockSizeBytes - 1)) == (address &amp;amp; ~(Mem::InstructionCacheBlockSizeBytes - 1))) {
        // current block destroyed
        if (CurrentCache) {
            *CurrentCache = nullptr;
            CurrentCache = nullptr;
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see, we look up the cache page (the integer division will be optimized out to a single shift, since &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Mem::InstructionCacheBlockSizeBytes&lt;/code&gt; is 256 (256 bytes per cache block). 
We then look up in this table which indices are filled in that page. This will usually be at most 1 or 2 blocks, but will probably be 0 blocks in most cases. That’s a lot fewer loops than 128!&lt;/p&gt;

&lt;p&gt;Then we also need to check if the current block is overwritten. You might recall that we check this in the new run methods. If the address is in the same page as &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;pc&lt;/code&gt;, we destroy the current block,
and show that there is no longer a block there by setting &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;CurrentCache = nullptr&lt;/code&gt;.&lt;/p&gt;

&lt;h3 id=&quot;the-pros-and-the-cons&quot;&gt;The pros and the cons&lt;/h3&gt;

&lt;p&gt;I’ve tried it out on a few games, and got between 10-20% performance increase in most games, but some ROMs that run a lot of code from ROM (like AGS) I gained about 50% more frames per second.
I said this before, but I also tried rewriting it to not dynamically allocate blocks with &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;unique_ptr&lt;/code&gt;, but besides being a lot more annoying in having to deal with a bump allocator, it also didn’t gain
me any more speed over dynamic allocation. And on top of that, this way with dynamic allocation uses a minimal amount of memory.&lt;/p&gt;

&lt;p&gt;The reason that this dynamic allocation probably doesn’t matter performance wise is because a lot of blocks don’t have to be recreated. In the very large ROM region, blocks will always be the same,
and only have to be allocated once. Only in the iWRAM region will blocks have to be recreated and allocated. The big read only code region is a major reason why this might not be the case for other systems.
In a lot of systems, the entire memory range is writeable, and you would spend a lot more time allocating and deallocating memory for the blocks.&lt;/p&gt;

&lt;h3 id=&quot;bump-allocator&quot;&gt;Bump allocator&lt;/h3&gt;

&lt;p&gt;I’ve mentioned this term before, and said that I did not use it, but I will briefly explain an approach to using a bump allocator instead. A bump allocator basically means you have a large array
holding cached instructions, and every time you make a new block you push instructions to that instead of to an allocated &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;InstructionCache&lt;/code&gt;. The caches themselves would look a bit different as well.
When I wrote one to see performance differences, I did something like this:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-CXX&quot;&gt;struct InstructionCache {
    const bool ARM;
    u8 Length;
    CachedInstruction* const Pointer;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;As you can see, the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;InstructionCache&lt;/code&gt; now no longer holds the instructions, but rather a pointer to the instructions in the pre-allocated memory, and a constant of how long the block is.
We would no longer have an array of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;unique_ptr&amp;lt;InstructionCache&amp;gt;&lt;/code&gt;, but rather a straight up array of &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;InstructionCache&lt;/code&gt;s. Our &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;CurrentCache&lt;/code&gt; would be a &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;InstructionCache*&lt;/code&gt;, and to check if 
the cache it points to is empty, we would check if the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Length&lt;/code&gt; field is 0.
You would then have something like a&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-CXX&quot;&gt;std::array&amp;lt;CachedInstruction, 0x0100'0000&amp;gt; Cache;
u32 CacheEnd;  // points to the first non-filled space in Cache
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;to hold the instructions. The length of this &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Cache&lt;/code&gt; is a bit arbitrary, and probably something you’ll have to play around with.
You want it to be big enough so that you are not constantly invalidating your cache because it’s overflowing, but small enough that
your memory usage is not through the roof. &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;InstructionCache&lt;/code&gt; would be pointing into this &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Cache&lt;/code&gt; buffer of instructions.
When making a new cache, I did:&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-CXX&quot;&gt;InstructionCache ARM7TDMI::NewCache() {
    if (CacheEnd &amp;gt;= (Cache.size() - (Mem::InstructionCacheBlockSizeBytes &amp;gt;&amp;gt; 1)) {
        // invalidate entire cache, so go over the array(s) of `InstructionCache`s and set their length to 0
        CacheEnd = 0;
    }
    return InstructionCache(ARMMode, 0, &amp;amp;Cache[CacheEnd]);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The initial check is to see if we can fit an entire new cache in the unused space of the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;Cache&lt;/code&gt; array. If this is not the case, we will have to destroy all the cache blocks and just start again.
And when adding new instructions, instead of pushing them back on the &lt;code class=&quot;language-plaintext highlighter-rouge&quot;&gt;InstructionCache&lt;/code&gt;, I would do&lt;/p&gt;
&lt;pre&gt;&lt;code class=&quot;language-CXX&quot;&gt;void ARM7TDMI::BumpAlloc(CachedInstruction&amp;amp; instr) {
    Cache[CacheEnd++] = instr;
    CurrentCache-&amp;gt;Length++;
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This method can be very advantagious for systems where the entire address space is writeable, as you would have to invalidate blocks anyway. For a system like the GBA, where you have a lot 
of read-only memory, I found that it not as good of a fit, as we wouldn’t want to be destroying blocks that will not change anyway. There might be better ways to write a bump allocator, but this
is just the idea I had for it, and how I wrote it to see the difference.&lt;/p&gt;

&lt;p&gt;I could maybe have taken a hybrid approach, the dynamically allocated blocks for ROM/BIOS and a bump allocator for iWRAM, but it really won’t win much.&lt;/p&gt;

&lt;p&gt;All in all, it was not only a quest for more performance, but also a fun learning experience for trying out the idea I had for the cached interpreter. Thank you for reading!&lt;/p&gt;</content><author><name>DenSinH</name></author><category term="emulation" /><category term="optimizations" /><summary type="html">Writing a cached interpreter</summary></entry></feed>