package optimizer // passRegDead eliminates dead stores to REGISTER variables. // A store is dead if no matching load (lda regVar) follows before A is // clobbered or a label is reached. This is safe because REGISTER variables // have a contract: nothing external can observe their memory location. func passRegDead(lines []asmLine, registerVars map[string]bool) []asmLine { var result []asmLine for i := 0; i < len(lines); i++ { line := lines[i] if line.isCode && line.opcode == "sta" && line.operand != "" && registerVars[line.operand] { if isRegStoreDead(lines, i+1, line.operand) { continue } } result = append(result, line) } return result } // isRegStoreDead scans forward from start to determine whether a store to a // REGISTER variable operand is dead. Returns true if the store can be removed. // A store is dead only if no matching lda is found anywhere forward before // a label or control-flow-ending instruction. func isRegStoreDead(lines []asmLine, start int, operand string) bool { for i := start; i < len(lines); i++ { l := lines[i] if l.optMarker || l.isComment { continue } if l.isLabel { return false } if l.isCode && isCallSite(l) { return false // callee may modify A; conservatively keep the store } if l.isCode && blocksFlow(l) { return true // rts/jmp/brk/rti — execution ends here } if l.isCode && l.opcode == "lda" && l.operand == operand { return false // the value IS read from memory later } } return true // end of block reached with no matching load } // blocksFlow returns true for instructions that unconditionally end the current // execution path: rts, jmp, brk, rti func blocksFlow(line asmLine) bool { switch line.opcode { case "rts", "jmp", "brk", "rti": return true } return false } // isCallSite returns true for instructions that transfer control to a callee // that may modify A, X, Y. The store before a call is conservatively kept. func isCallSite(line asmLine) bool { return line.opcode == "jsr" }