1 // Nintendo Game Boy CPU emulator
2 // Treats every instruction as taking 4 cycles
3 
4 // Game_Music_Emu 0.5.5
5 #ifndef GB_CPU_H
6 #define GB_CPU_H
7 
8 #include "blargg_common.h"
9 #include "blargg_endian.h"
10 
11 typedef unsigned gb_addr_t; // 16-bit CPU address
12 
13 class Gb_Cpu {
14 	enum { clocks_per_instr = 4 };
15 public:
16 	// Clear registers and map all pages to unmapped
17 	void reset( void* unmapped = 0 );
18 
19 	// Map code memory (memory accessed via the program counter). Start and size
20 	// must be multiple of page_size.
21 	enum { page_size = 0x2000 };
22 	void map_code( gb_addr_t start, unsigned size, void* code );
23 
24 	uint8_t* get_code( gb_addr_t );
25 
26 	// Push a byte on the stack
27 	void push_byte( int );
28 
29 	// Game Boy Z80 registers. *Not* kept updated during a call to run().
30 	struct core_regs_t {
31 	#if BLARGG_BIG_ENDIAN
32 		uint8_t b, c, d, e, h, l, flags, a;
33 	#else
34 		uint8_t c, b, e, d, l, h, a, flags;
35 	#endif
36 	};
37 
38 	struct registers_t : core_regs_t {
39 		long pc; // more than 16 bits to allow overflow detection
40 		uint16_t sp;
41 	};
42 	registers_t r;
43 
44 	// Interrupt enable flag set by EI and cleared by DI
45 	//bool interrupts_enabled; // unused
46 
47 	// Base address for RST vectors (normally 0)
48 	gb_addr_t rst_base;
49 
50 	// If CPU executes opcode 0xFF at this address, it treats as illegal instruction
51 	enum { idle_addr = 0xF00D };
52 
53 	// Run CPU for at least 'count' cycles and return false, or return true if
54 	// illegal instruction is encountered.
55 	bool run( blargg_long count );
56 
57 	// Number of clock cycles remaining for most recent run() call
remain()58 	blargg_long remain() const { return state->remain * clocks_per_instr; }
59 
60 	// Can read this many bytes past end of a page
61 	enum { cpu_padding = 8 };
62 
63 public:
Gb_Cpu()64 	Gb_Cpu() : rst_base( 0 ) { state = &state_; }
65 	enum { page_shift = 13 };
66 	enum { page_count = 0x10000 >> page_shift };
67 private:
68 	// noncopyable
69 	Gb_Cpu( const Gb_Cpu& );
70 	Gb_Cpu& operator = ( const Gb_Cpu& );
71 
72 	struct state_t {
73 		uint8_t* code_map [page_count + 1];
74 		blargg_long remain;
75 	};
76 	state_t* state; // points to state_ or a local copy within run()
77 	state_t state_;
78 
79 	void set_code_page( int, uint8_t* );
80 };
81 
get_code(gb_addr_t addr)82 inline uint8_t* Gb_Cpu::get_code( gb_addr_t addr )
83 {
84 	return state->code_map [addr >> page_shift] + addr
85 	#if !BLARGG_NONPORTABLE
86 		% (unsigned) page_size
87 	#endif
88 	;
89 }
90 
91 #endif
92