EgonOlsen71 / basicv2

A Commodore (CBM) BASIC V2 interpreter/compiler written in Java
https://egonolsen71.github.io/basicv2/
The Unlicense
84 stars 15 forks source link

further optimize "Highly simplified loading for CMP/6" #21

Closed nippur72 closed 5 years ago

nippur72 commented 5 years ago

I'm looking into how an IF is compiled down to assembly.

I noticed the optimizer rule "Highly simplified loading for CMP/6" uses the integer values #0 and #1 instead of REAL_CONST_ZERO and REAL_CONST_MINUS_ONE which is good, but I think the loading into A is not necessary and it could be further optimized avoiding it, doing the BRANCHES directly.

Example (current):

JSR CMPFAC
; Optimizer rule: Highly simplified loading for CMP/6
BNE NEQ_NEQ9
  LDA #0
  JMP NEQ_SKIP9
NEQ_NEQ9:
  LDA #$1
NEQ_SKIP9:
COMP_SKP9:
  BEQ LINE_SKIP10
; Simplified conditional branch
;
LINE_NSKIP10:
;
;
LINE_SKIP10:

Suggested (something like this):

JSR CMPFAC
; Optimizer rule: Highly simplified loading for CMP/6
BNE LINE_SKIP10
LINE_NSKIP10:
;
;
LINE_SKIP10:

I guess it's much more complex than this because all operators (<=, >= etc..) should be taken into account, perhaps that can be optimized as an additional step in the optimizer?

Also notice that

LDA #0
JMP NEQ_SKIP9

can be shortened by one byte with

LDA #0
BEQ NEQ_SKIP9   ; Z=0 for sure
EgonOlsen71 commented 5 years ago

I've added an additional optimization step for this, which covers these cases under some circumstances, i.e. it relies on all other optimizations to trigger (especially the "Simplified conditional branch" one) and it works only for "equal" and "not equal" but given that these should be the majority of cases and that it doesn't really improve that much anyway, it should be fine this way.