5 ms·
IMHO there's no much simpler way to write a CPU emulator than as a huge switch inside a loop as that models quite well what a real CPU does. Anything more just
by userbinator 13y ago
IMHO there's no much simpler way to write a CPU emulator than as a huge switch inside a loop as that models quite well what a real CPU does. Anything more just obfuscates the essence of the functionality.
- jimmaswell 13y agoI suppose you could create a dictionary of opcode -> function pointers. In C# that'd be like var ops = new Dictionary<Opcode, Action<opcodeArgs>> () { {0, nop }, {1, add }, ... } or even better, maybe I'd get a list of the opcodes with their names, name all the functions after those names exactly, then use reflection to automatically create this dictionary. Then in the main loop, ops[opcode].Invoke(args); I don't know if something like that would be any use in C, though.
- grapeshot 13y agoIt's possible to do something like that in C. In C++, you can even do some template magic to create all the appropriate functions for each opcode based on something like the original instruction decode ROM. Brilliant and short code, but very difficult to write in the first place. Here's a very apropos example of this technique as applied to the 6502. http://www.youtube.com/watch?v=y71lli8MS8s http://www.youtube.com/watch?v=y71lli8MS8s
- haldean 13y agoThe problem with that method is that it's inefficient; with the switch statement, there's no hashing or significant computation involved in finding the location to jump to. With an object-based method, you have (at least) a memory access to get the method object, a lookup in a vtable to find the location of the Invoke method and a function call (which means pushing a new stack frame) before you start processing the instruction. With the switch statement, none of that happens; instead, it compiles to (essentially) two jump instructions; one into a lookup table, then one from the lookup table to the opcode handler. Getting out of the handler and back into the loop is also a single constant jump (no stack frame popping).
- jimmaswell 13y agoThese are mostly O(1) things and shouldn't matter. The dictionary lookup can become O(1) if you turn it into an array of function pointers indexed by ints, the opcodes.
- breckinloggins 13y agoBut remember that O(n) is really c*n. The problem is that, when emulating a CPU, the "c" can dominate in these cases.
- haldean 13y agoYup, that's definitely true, but opcode parsing and dispatch needs to be a really tight loop. Keep in mind that function calls still involve pushing/popping stack frames, which while super, super cheap, are still not free. There are no loops other than the main loop in here, and every instruction takes constant time, which means that constant factors in opcode parsing and dispatch are going to really dominate.
- haberman 13y agoIn these kinds of situations, O(1) means nothing; any (reasonable) approach will be O(1), but constant factors will dominate. For example, there are measurable differences in branch prediction based on whether each opcode's implementation ends with its own dispatch code or branches back to a common dispatch routine. The sequence of instructions is basically the same in both cases, but there is an icache/branch prediction tradeoff to be made. Subtle stuff (see http://repo.or.cz/w/luajit-2.0.git/blob/0ded8e82a88fadb40b4dd7e6632311781f1b2f91:/src/vm_x86.dasc#l283 http://repo.or.cz/w/luajit-2.0.git/blob/0ded8e82a88fadb40b4d...)
- weland 13y ago> These are mostly O(1) things and shouldn't matter. I often hear this from programmers coming from a higher-level background. O(1) only means constant time. It doesn't mean quickly. This function: int foo(int x) { sleep(3600); return x; } is O(1), just as this: int bar(int x) { return x; } Foo takes an hour to commplete, but it's just as O(1) as bar :-).
- haberman 13y agoYes you could do that. But why go to such contortions when "switch" is an idiomatic and efficient way of expressing this pattern directly?
- jsaxton86 13y agoAt a previous job, there was a legacy UI application that had a 10,000+ line file called "messloop.c". It consisted of a function called messloop(), which was an infinite loop with a massive switch statement inside of it. I never had to work on it, but I'm told it was a maintenance nightmare. So when I read the author's code and saw the way he handled a similar problem, I was intrigued. If you had to deal with a massive switch statement with thousands of cases, it would probably be easier to maintain IMHO. For a hobby project, the author's solution is 100% correct and I'm not critiquing it at all. In fact, the only reason I even commented was because I thought his solution was better than any other procedural solution I had seen before. With that said, in an enterprise environment, where maintainability is crucial, I'd argue that a massive switch statement is probably a bad idea. Going back to messloop.c, what happens if the user tries to change a floating point value through the UI? Well, I can tell you that there is a case statement for that somewhere in messloop.c. What is that case statement called? I'm not sure, all I know is it's a #define that I'm sure made sense to the original author. It's basically a needle-in-a-haystack problem.
- userbinator 13y agoThe problem in your case (no pun intended) seems to be the difficulty of "finding the right branch". With a CPU emulator, it's not so hard: look up the opcode and there it is. Would you rather scan through a single file or several dozen?
- csmuk 13y agoThat's what the debugger is for (if you inherited it). However, a lot of desktop applications are written that way. If you've ever dealt with Win32, you'll see nested switch statements from hell on your average project. If you have a pure OO language like Java or C# then there's no excuse but some legacy applications built in C tend to be "switchy" because the older APIs seem to favour that form of message dispatch. There is still no excuse as you can have decent abstraction in C or C++. However for what is effectively a jump table, a switch statement is exactly spot on for this project.