--- a/src/ASMText2.cpp +++ b/src/ASMText2.cpp @@ -4159,16 +4159,27 @@ } +// B is the low half of D. Both direct and indirect accumulator-indexed +// addresses can therefore depend on the value of B before a rewrite. +static bool +usesBInAddress(const string &operand) +{ + return startsWith(operand, "B,") || startsWith(operand, "D,") + || startsWith(operand, "[B,") || startsWith(operand, "[D,"); +} + + // Look for: LDB foo; PSHS B; LDB bar; CMPB ,S+. // Change to: LDB bar; CMPB foo. -// LDB args must not involve S. +// Swapping the two reads must preserve their offsets and index registers. // bool ASMText::removePushBFromLdbPushLdbCmp(size_t index) { if (!isInstrAnyArg(index, "LDB")) return false; - if (elements[index].fields[1].find(",S") != string::npos) + if (usesBInAddress(elements[index].fields[1]) || isInstrWithPreDecrOrPostIncr(index) + || elements[index].fields[1].find(",S") != string::npos) return false; size_t pushIndex = findNextInstrBeforeLabel(index + 1); @@ -4178,7 +4189,8 @@ size_t secondLoadIndex = findNextInstrBeforeLabel(pushIndex + 1); if (!isInstrAnyArg(secondLoadIndex, "LDB")) return false; - if (elements[secondLoadIndex].fields[1].find(",S") != string::npos) + if (usesBInAddress(elements[secondLoadIndex].fields[1]) || isInstrWithPreDecrOrPostIncr(secondLoadIndex) + || elements[secondLoadIndex].fields[1].find(",S") != string::npos) return false; size_t cmpIndex = findNextInstrBeforeLabel(secondLoadIndex + 1); @@ -4440,6 +4452,13 @@ if (!isInstr(subIndex, "SUBB", ",S+")) return false; + // NEGB changes B before the load's address is used, and removing the + // push changes S. Keep the original sequence when either matters. + const string &operand = elements[ldbIndex].fields[1]; + if (usesBInAddress(operand) || operand.find(",S") != string::npos + || isInstrWithPreDecrOrPostIncr(ldbIndex)) + return false; + // Apply the optimization. commentOut(index, "optim: removePushBBeforeSubB"); // remove PSHS elements[subIndex].fields[0] = "ADDB"; @@ -4833,6 +4852,11 @@ if (isInstrWithPreDecrOrPostIncr(addb)) return false; + // Swapping the operands also changes which value of B is available + // when each effective address is evaluated. + if (usesBInAddress(elements[index].fields[1]) || usesBInAddress(elements[addb].fields[1])) + return false; + // Apply the optimization. const string ldbArg = elements[index].fields[1]; elements[index].fields[1] = elements[addb].fields[1];