void CPUContext::add()
{
uint16_t val = reg_.readReg(curInst_.reg1) + fetchedData_;
bool is16bit = is16bitReg(curInst_.reg1);
if (is16bit) {
// emu...
}
code
if (curInst_.reg1 == RegType::SP) {
val = reg_.readReg(curInst_.reg1) + static_cast<int8_t>(fetchedData_);
}
int z = (val & 0xFF) == 0;
int h = ((reg_.readReg(curInst_.reg1) & 0xF) + (fetchedData_ & 0xF)) >= 0x10;
int c = (static_cast<int>(reg_.readReg(curInst_.reg1) & 0xFF) + static_cast<int>(fetchedData_ & 0xFF)) >= 0x100;
if (is16bit) {
z = -1;
h = ((reg_.readReg(curInst_.reg1) & 0xFFF) + (static_cast<int8_t>(fetchedData_) & 0xFFF)) >= 0x1000;
c = (static_cast<uint32_t>(reg_.readReg(curInst_.reg1) & 0xFFFF) + static_cast<uint32_t>(fetchedData_ & 0xFFFF)) >= 0x10000;
}
if (curInst_.reg1 == RegType::SP) {
z = 0;
h = ((reg_.readReg(curInst_.reg1) & 0xF) + (static_cast<int8_t>(fetchedData_) & 0xF)) >= 0x10;
c = (static_cast<uint16_t>(reg_.readReg(curInst_.reg1) & 0xFF) + static_cast<uint16_t>(fetchedData_ & 0xFF)) >= 0x100;
}
reg_.writeReg(curInst_.reg1, val & 0xFFFF);
reg_.setFlags(z, 0, h, c);
}
void GBCEmu::CPUContext::sub()
{
uint16_t val = reg_.readReg(curInst_.reg1) - fetchedData_;
code
int z = val == 0;
int h = ((static_cast<int>(reg_.readReg(curInst_.reg1)) & 0xF) - (static_cast<int>(fetchedData_) & 0xF)) < 0;
int c = (static_cast<int>(reg_.readReg(curInst_.reg1)) - static_cast<int>(fetchedData_)) < 0;
reg_.writeReg(curInst_.reg1, val);
reg_.setFlags(z, 1, h, c);
}
void GBCEmu::CPUContext::sbc()
{
uint8_t val = fetchedData_ + reg_.getCFlag();
code
int z = (reg_.readReg(curInst_.reg1) - val) == 0;
int h = ((static_cast<int>(reg_.readReg(curInst_.reg1)) & 0xF) - (static_cast<int>(fetchedData_) & 0xF) - (static_cast<int>(reg_.getCFlag()))) < 0;
int c = (static_cast<int>(reg_.readReg(curInst_.reg1)) - static_cast<int>(fetchedData_)) - reg_.getCFlag() < 0;
reg_.writeReg(curInst_.reg1, (reg_.readReg(curInst_.reg1) - val));
reg_.setFlags(z, 1, h, c);
}
void GBCEmu::CPUContext::adc()
{
uint16_t u = fetchedData_;
uint16_t a = reg_.a_;
uint16_t c = reg_.getCFlag();
code
reg_.a_ = (a + u + c) & 0xFF;
reg_.setFlags(a == 0, 0, (a & 0xF) + (u & 0xF) + c > 0xF, a + u + c > 0xFF);
}
void CPUContext::process()
{
auto it = PROCESSOR_.find(curInst_.type);
if(it != PROCESSOR_.end()) {
(it->second)();
return;
}
throw std::runtime_error("failed to find processor of instType:" + static_cast(curInst_.type));
}
错误描述:
在 ADC 指令中,Z 标志是基于原始的 A 寄存器值 (a == 0) 设置的,而不是基于运算结果 (reg_.a_)。
修复方法:
将 Z 标志基于运算后的 A 寄存器值进行设置。
修正后的代码:
cpp
void GBCEmu::CPUContext::adc()
{
uint16_t u = fetchedData_;
uint16_t a = reg_.a_;
uint16_t c = reg_.getCFlag();
reg_.a_ = (a + u + c) & 0xFF;
reg_.setFlags(reg_.a_ == 0, 0, ((a & 0xF) + (u & 0xF) + c) > 0xF, (a + u + c) > 0xFF);
}