In the previous post I introduced r64m, an emulator that runs x86-64 containers on Arm Linux at more than twice the speed of QEMU. At that point r64m claimed to be an x86-64-v1 CPU: the first generation, nothing beyond SSE2.
This is the follow-up. r64m now implements everything an Ivy Bridge CPU executes in user mode, from SSE3 to AVX, and its CPUID says “Ivy Bridge”. The interesting part is not that the instructions were added. It is how each one was checked against real hardware, and what turned up along the way: places where code written straight from the manual did not match the machine.
Repository: github.com/y6ui3i/r64m
Why all at once, and not a few at a time
Adding new instructions a handful at a time has two problems.
The first is that you keep touching the same places: the decoder, the register state, the signal frame, CPUID. Every addition means re-reading the same code.
The second matters more. Add a few instructions, set one more CPUID bit, and r64m becomes a CPU that sits somewhere between v1 and Ivy Bridge, which is a processor that does not exist. r64m takes all of its expected results from real hardware. The hardware is one machine on a desk (a Core i7-3770K, Ivy Bridge), and you cannot ask it what an in-between CPU would do.
So the order was fixed like this:
- Put every Ivy Bridge instruction into the interpreter first. CPUID stays at v1.
- Check each one against the real machine.
- When all of it is there, raise CPUID once.
- Make it fast afterwards: count what is slow, and move those into the JIT.
Step 3 is done as of this post. Step 4 is next, which means r64m today is correct and probably slower than before. More on that at the end.
The instruction table is the list of tests
The instructions live in one table. A row is found by its opcode map, its mandatory prefix and its opcode, and says which encodings it has (legacy, VEX 128-bit, VEX 256-bit), the shape of its operands, and the function that runs it. The rule for the upper bits (legacy forms leave them alone, VEX forms zero them) is written in exactly one place.
A test program is generated from each row: zeros, signed and unsigned edges, NaNs, denormals, every rounding mode, and random values. That program is single-stepped on the real machine, which writes out the registers after every instruction. If r64m prints the same lines for the same program, the row passes.
A row with no test fails the build of the test suite, so there is no way to add an instruction and forget to test it. The table has 376 rows today, and there are 386 traces taken from the real machine.
Some things need more than stepping one instruction at a time:
- Approximate reciprocals (RCPPS, RSQRTPS): the input is 32 bits, so all 2^32 inputs were compared against the real instruction.
- Floating-point arithmetic: a billion random operands, across rounding modes and both denormal settings, comparing results and exception flags.
- Half-precision conversion (F16C): all 2^32 single-precision values, by eight ways of rounding.
And every time, I broke the implementation on purpose and made sure a test failed. A test that cannot fail protects nothing. In fact the first MMX test missed one of those deliberate breaks: because of the order of its steps, the property under test had already been satisfied by an earlier instruction. One more case closed that gap.
What the manual did not say
Compare against the machine and you find places where an implementation written from the manual is wrong. A few of them:
The approximate reciprocal is a table lookup. The manual only promises that RCPPS is within some error bound. Collect every answer from the real CPU and they turn out to be what you would get from a 2,048-entry table. The table was taken from the machine.
Which NaN comes out of a dot product (DPPS, DPPD) when there is more than one. It depends on the order of the additions. The order in the manual’s pseudocode does not match; the real CPU adds in a different order for different elements of the result.
FNINIT does not clear the registers. It initializes the x87, and r64m zeroed all eight registers. The real CPU only marks them empty and leaves their contents. No ordinary program can tell, but FXSAVE can. The traces showed it when MMX went in, since MMX borrows the x87’s registers.
MXCSR had been wrong for a long time. This one is not about new instructions. r64m’s interpreter ignored the rounding mode, always rounded to nearest, and never raised a single exception flag. The moment MXCSR was added to the trace line, everything failed. IEEE 754 was reimplemented on integers, compared against the machine on a billion operands, and three disagreements were fixed (for example, which flags a denormal divided by zero raises).
Asking the machine how it says no
This was the most satisfying part.
Matching results is not the whole story. There is also what the CPU does when it refuses. What happens when MOVAPS is given an unaligned address? What about a prefix the instruction does not have? r64m was sloppy on both. It executed the first without checking anything, and on the second it said “an instruction not written yet” and exited.
To ask the real machine, a test has to survive a signal. The oracle (the program that single-steps a test on real hardware) used to kill the test at the first signal. Now it passes the signal on. The test installs a handler that loads the signal number and address into registers and jumps to the next question. Reading the trace then tells you, for each question, whether the instruction ran or raised SIGILL.
That way 9,925 questions went to the machine.
| Question | Count | What the machine said |
|---|---|---|
| Each row’s memory operand at an unaligned address (legacy) | 363 | 167 ran, 167 general protection, 29 invalid opcode |
| The same behind VEX, plus wrong lengths, a stray register, the W bit | 1,643 | 1,035 ran, 580 invalid opcode, 28 general protection |
| A table opcode behind a prefix it has no row for | 978 | all invalid opcode |
| Every opcode behind VEX that the table lacks | 5,594 | all invalid opcode |
| Every opcode behind 0F 38 and 0F 3A that the table lacks | 1,656 | all invalid opcode |
| UD2, HLT, divide by zero, page faults and the like | 52 | as each should |
r64m disagreed in twelve places. Here are the ones that were fun to track down.
On entry to a handler, the XMM registers are zero
At first every case failed. The difference was on the first line inside the handler: on the real machine XMM0 and XMM1 had changed to zero. In r64m they had not.
When Linux enters a signal handler it saves the floating-point state into the frame and then resets the registers to their initial state. A handler starts clean. r64m saved the state and did not clear it.
Something else came out of this. RSP at the handler’s first instruction, which is where the frame was put on the stack, matched the real machine at all 9,074 signals. The frame’s layout had been worked out earlier from the bytes of a single real frame. Seeing it land in the right place 9,074 times was a good moment.
Memory that nothing had written was different
One mismatch had no obvious cause. The question was a masked load (VMASKMOVPS) of eight bytes from a position that straddles the end of the mapped region. The real machine read zero. r64m read something else.
The load is simple and hard to get wrong. So the memory itself had to be different. But this was the very top of the stack, where nobody should have written anything.
The culprit was a question several steps earlier: a MOVDQU that stores 16 bytes at the same position. The last eight bytes are unmapped, so the store faults. The real machine faults and writes nothing. r64m wrote the first eight bytes and then faulted on the rest. Those eight bytes stayed there, and the later load picked them up.
The trace only shows registers, so nothing is visible at the time of the store. It only shows up when the bytes are read back. A store across pages now checks that all of it can be written before writing any of it.
The fault address of a store is not the first bad byte
The store form of VMASKMOVPS had another surprise. When it faults, the address the kernel reports is not the first byte that could not be written. With all four elements written it is the last byte (600007h, with the mapping ending at 600000h). I asked with four different masks:
- all elements: 600007h
- the first and third: 600003h
- the third alone: 600000h
- the fourth alone: 600004h
“The first byte of the lowest element to be written if that cannot be written, otherwise the last byte of the highest” fits all four. Presumably the microcode touches the two ends first. But that is a rule fitted to four observations. The double-precision form and the 256-bit forms were not asked, and the ledger says so.
One answer from the machine that r64m does not repeat
The memory form of 0F C7 /6 is a VMX instruction and should be an invalid opcode unless virtualization is in use. The real machine raised a general protection fault instead, because KVM had VMX switched on. That is a property of that machine’s kernel, not of the CPU. r64m is a CPU without VMX and says invalid opcode, and the question was taken out of the test. The principle is to tell the guest only what the real machine says, but you still have to read what that answer depends on.
The JIT had the same mistake
It was not only the interpreter that skipped the alignment check. Blocks made by the JIT ran MOVAPS and PXOR without looking either. A block now emits two Arm instructions before each memory operand that must be aligned, and hands the instruction to the interpreter on a violation. They do not touch the flags. What this costs in speed has not been measured yet.
Holes of my own making
The verification procedure had holes too. They belong in this post.
First: the commit that added RDRAND did not build for Linux. It called a function musl does not have. Only the tests on the Mac had been run, not the full set that includes the Linux build.
Second: the script that runs r64m in a Linux container and compares it with the real machine was hiding build failures. A fix went in and the result did not change. Another fix, no change. The code looked right and the difference would not go away. The build had been failing the whole time, and every run had measured the same old binary. What gave it away was that the results changed too little.
In both cases the broken thing was the measuring tool, not the thing being measured.
Raising CPUID
With the instructions in place, CPUID went up. There is one rule: set a bit only if the real machine sets it and r64m can back it.
Every CPUID leaf of the real machine is stored in the repository. A unit test checks, line by line, that r64m sets no bit the machine does not. Each bit the machine sets and r64m does not is listed with a reason. Most are for a kernel (VMX, PCID, MSRs) or belong to that particular machine (the count of logical processors).
The cache layout and the brand string, on the other hand, are the real machine’s as they are. A C library chooses how to copy memory by looking at the cache sizes, and a program should take the same path under r64m that it takes on the real CPU.
There is also a new option, --cpu=v1. With it r64m goes back to being the r64m it was, and the new instructions raise SIGILL. Only whole CPUs can be named. Something like “Ivy Bridge without AVX” is not possible, because no such CPU exists to be asked.
What happened when it was raised:
- The existing container tests, 405 of them (about 130 cases, each by the interpreter, the JIT and the checked JIT), all passed on the first run.
- glibc’s loader now reports
x86-64-v2 (supported, searched). Under--cpu=v1it does not. Programs really do see the new CPU. - A build of NetHack produces the same files under either CPU (172 hashes match; the other two files contain the build time).
- MongoDB’s
mongod, which could not start for lack of AVX, now starts.
Running the same tests under --cpu=v1 broke exactly one thing, HAProxy. It uses CMPXCHG16B without checking CPUID. I had made v1 refuse that instruction as “a v2 instruction”, but the earlier r64m had it. If v1 means the r64m that was, it has to have it. A one-line fix.
What is still not known
- Speed has not been measured, and has probably dropped. Only SSE and SSE2 are in the JIT’s blocks. Everything added here is run by the interpreter. Floating point was rebuilt on integer arithmetic, which made it about 1.5 times slower in the interpreter alone.
- Nobody has counted how much of the new code those 405 tests reach. glibc does not choose AVX for its copies on an Ivy Bridge. Most likely the tests exercise the SSSE3 and SSE4.2 paths, and AVX rests on the per-row traces alone.
mongodhas not actually been queried. The shell that ships with it,mongosh, crashes under r64m. It crashes under the older CPU too, so that bug predates this work.- Unmasked floating-point exceptions deliver no signal, and
/proc/cpuinfostill shows the host’s Arm CPU.
Next
Speed. The first step is a counter: which instruction ran, in which form, how many times, and whether the interpreter or a block ran it. That list is the order in which things go into the JIT. Then the same images get measured again beside QEMU, box64 and native code.
There is a yardstick as well. A Graviton instance is said to cost roughly 20% less per hour than a comparable x86 one. If so, emulation that is more than 1.25 times slower than native loses money on compute. 1.25 is a long way off and is not a promise. It is there to say how close things have come.
One more thing this work made clear: you do not have to own the hardware to check against it. The oracle only single-steps a program with ptrace, so any x86-64 Linux machine reachable over SSH will do. Renting a cloud instance of the right generation for a few hours would open the way to AVX2 and beyond (x86-64-v3). That has not been tried yet, so it is a plan.
Every experiment so far, including the ones that failed and my own mistakes, is recorded in docs/experiments.md in the repository.

コメント