1 /*****************************************************************************/
5 /* Optimizer subroutines */
9 /* (C) 2001-2012, Ullrich von Bassewitz */
10 /* Roemerstrasse 52 */
11 /* D-70794 Filderstadt */
12 /* EMail: uz@cc65.org */
15 /* This software is provided 'as-is', without any expressed or implied */
16 /* warranty. In no event will the authors be held liable for any damages */
17 /* arising from the use of this software. */
19 /* Permission is granted to anyone to use this software for any purpose, */
20 /* including commercial applications, and to alter it and redistribute it */
21 /* freely, subject to the following restrictions: */
23 /* 1. The origin of this software must not be misrepresented; you must not */
24 /* claim that you wrote the original software. If you use this software */
25 /* in a product, an acknowledgment in the product documentation would be */
26 /* appreciated but is not required. */
27 /* 2. Altered source versions must be plainly marked as such, and must not */
28 /* be misrepresented as being the original software. */
29 /* 3. This notice may not be removed or altered from any source */
32 /*****************************************************************************/
44 #include "debugflag.h"
60 #include "coptptrload.h"
61 #include "coptptrstore.h"
63 #include "coptshift.h"
66 #include "coptstore.h"
75 /*****************************************************************************/
77 /*****************************************************************************/
81 static unsigned OptLoad1 (CodeSeg* S)
82 /* Search for a call to ldaxysp where X is not used later and replace it by
83 ** a load of just the A register.
89 /* Walk over the entries */
91 while (I < CS_GetEntryCount (S)) {
96 E = CS_GetEntry (S, I);
98 /* Check for the sequence */
99 if (CE_IsCallTo (E, "ldaxysp") &&
100 RegValIsKnown (E->RI->In.RegY) &&
101 !RegXUsed (S, I+1)) {
105 /* Reload the Y register */
106 const char* Arg = MakeHexArg (E->RI->In.RegY - 1);
107 X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
108 CS_InsertEntry (S, X, I+1);
110 /* Load from stack */
111 X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "sp", 0, E->LI);
112 CS_InsertEntry (S, X, I+2);
114 /* Now remove the call to the subroutine */
117 /* Remember, we had changes */
127 /* Return the number of changes made */
133 static unsigned OptLoad2 (CodeSeg* S)
134 /* Replace calls to ldaxysp by inline code */
137 unsigned Changes = 0;
139 /* Walk over the entries */
141 while (I < CS_GetEntryCount (S)) {
146 L[0] = CS_GetEntry (S, I);
148 /* Check for the sequence */
149 if (CE_IsCallTo (L[0], "ldaxysp")) {
153 /* Followed by sta abs/stx abs? */
154 if (CS_GetEntries (S, L+1, I+1, 2) &&
155 L[1]->OPC == OP65_STA &&
156 L[2]->OPC == OP65_STX &&
159 strcmp (L[1]->Arg, L[2]->Arg) != 0) &&
160 !CS_RangeHasLabel (S, I+1, 2) &&
161 !RegXUsed (S, I+3)) {
163 /* A/X are stored into memory somewhere and X is not used
168 X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "sp", 0, L[0]->LI);
169 CS_InsertEntry (S, X, I+3);
172 X = NewCodeEntry (OP65_STA, L[2]->AM, L[2]->Arg, 0, L[2]->LI);
173 CS_InsertEntry (S, X, I+4);
176 X = NewCodeEntry (OP65_DEY, AM65_IMP, 0, 0, L[0]->LI);
177 CS_InsertEntry (S, X, I+5);
180 X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "sp", 0, L[0]->LI);
181 CS_InsertEntry (S, X, I+6);
184 X = NewCodeEntry (OP65_STA, L[1]->AM, L[1]->Arg, 0, L[1]->LI);
185 CS_InsertEntry (S, X, I+7);
187 /* Now remove the call to the subroutine and the sta/stx */
188 CS_DelEntries (S, I, 3);
192 /* Standard replacement */
195 X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "sp", 0, L[0]->LI);
196 CS_InsertEntry (S, X, I+1);
199 X = NewCodeEntry (OP65_TAX, AM65_IMP, 0, 0, L[0]->LI);
200 CS_InsertEntry (S, X, I+2);
203 X = NewCodeEntry (OP65_DEY, AM65_IMP, 0, 0, L[0]->LI);
204 CS_InsertEntry (S, X, I+3);
207 X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "sp", 0, L[0]->LI);
208 CS_InsertEntry (S, X, I+4);
210 /* Now remove the call to the subroutine */
215 /* Remember, we had changes */
224 /* Return the number of changes made */
230 static unsigned OptLoad3 (CodeSeg* S)
231 /* Remove repeated loads from one and the same memory location */
233 unsigned Changes = 0;
236 /* Walk over the entries */
238 while (I < CS_GetEntryCount (S)) {
241 CodeEntry* E = CS_GetEntry (S, I);
243 /* Forget a preceeding load if we have a label */
244 if (Load && CE_HasLabel (E)) {
248 /* Check if this insn is a load */
249 if (E->Info & OF_LOAD) {
253 /* If we had a preceeding load that is identical, remove this one.
254 ** If it is not identical, or we didn't have one, remember it.
257 E->OPC == Load->OPC &&
259 ((E->Arg == 0 && Load->Arg == 0) ||
260 strcmp (E->Arg, Load->Arg) == 0) &&
261 (N = CS_GetNextEntry (S, I)) != 0 &&
262 (N->Info & OF_CBRA) == 0) {
264 /* Now remove the call to the subroutine */
267 /* Remember, we had changes */
279 } else if ((E->Info & OF_CMP) == 0 && (E->Info & OF_CBRA) == 0) {
280 /* Forget the first load on occurance of any insn we don't like */
288 /* Return the number of changes made */
294 /*****************************************************************************/
295 /* Decouple operations */
296 /*****************************************************************************/
300 static unsigned OptDecouple (CodeSeg* S)
301 /* Decouple operations, that is, do the following replacements:
311 ** lda zp -> lda #imm
312 ** ldx zp -> ldx #imm
313 ** ldy zp -> ldy #imm
315 ** Provided that the register values are known of course.
318 unsigned Changes = 0;
321 /* Walk over the entries */
323 while (I < CS_GetEntryCount (S)) {
327 /* Get next entry and it's input register values */
328 CodeEntry* E = CS_GetEntry (S, I);
329 const RegContents* In = &E->RI->In;
331 /* Assume we have no replacement */
334 /* Check the instruction */
338 if (RegValIsKnown (In->RegA)) {
339 Arg = MakeHexArg ((In->RegA - 1) & 0xFF);
340 X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
345 if (RegValIsKnown (In->RegX)) {
346 Arg = MakeHexArg ((In->RegX - 1) & 0xFF);
347 X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
352 if (RegValIsKnown (In->RegY)) {
353 Arg = MakeHexArg ((In->RegY - 1) & 0xFF);
354 X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
359 if (RegValIsKnown (In->RegA)) {
360 Arg = MakeHexArg ((In->RegA + 1) & 0xFF);
361 X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
366 if (RegValIsKnown (In->RegX)) {
367 Arg = MakeHexArg ((In->RegX + 1) & 0xFF);
368 X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
373 if (RegValIsKnown (In->RegY)) {
374 Arg = MakeHexArg ((In->RegY + 1) & 0xFF);
375 X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
380 if (E->AM == AM65_ZP) {
381 switch (GetKnownReg (E->Use & REG_ZP, In)) {
383 Arg = MakeHexArg (In->Tmp1);
384 X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
388 Arg = MakeHexArg (In->Ptr1Lo);
389 X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
393 Arg = MakeHexArg (In->Ptr1Hi);
394 X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
398 Arg = MakeHexArg (In->SRegLo);
399 X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
403 Arg = MakeHexArg (In->SRegHi);
404 X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
411 if (E->AM == AM65_ZP) {
412 switch (GetKnownReg (E->Use & REG_ZP, In)) {
414 Arg = MakeHexArg (In->Tmp1);
415 X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
419 Arg = MakeHexArg (In->Ptr1Lo);
420 X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
424 Arg = MakeHexArg (In->Ptr1Hi);
425 X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
429 Arg = MakeHexArg (In->SRegLo);
430 X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
434 Arg = MakeHexArg (In->SRegHi);
435 X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
442 if (E->AM == AM65_ZP) {
443 switch (GetKnownReg (E->Use, In)) {
445 Arg = MakeHexArg (In->Tmp1);
446 X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
450 Arg = MakeHexArg (In->Ptr1Lo);
451 X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
455 Arg = MakeHexArg (In->Ptr1Hi);
456 X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
460 Arg = MakeHexArg (In->SRegLo);
461 X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
465 Arg = MakeHexArg (In->SRegHi);
466 X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
473 if (E->RI->In.RegA >= 0) {
474 Arg = MakeHexArg (In->RegA);
475 X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
480 if (E->RI->In.RegA >= 0) {
481 Arg = MakeHexArg (In->RegA);
482 X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
487 if (E->RI->In.RegX >= 0) {
488 Arg = MakeHexArg (In->RegX);
489 X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
494 if (E->RI->In.RegY >= 0) {
495 Arg = MakeHexArg (In->RegY);
496 X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
501 /* Avoid gcc warnings */
506 /* Insert the replacement if we have one */
508 CS_InsertEntry (S, X, I+1);
518 /* Return the number of changes made */
524 /*****************************************************************************/
525 /* Optimize stack pointer ops */
526 /*****************************************************************************/
530 static unsigned IsDecSP (const CodeEntry* E)
531 /* Check if this is an insn that decrements the stack pointer. If so, return
532 ** the decrement. If not, return zero.
533 ** The function expects E to be a subroutine call.
536 if (strncmp (E->Arg, "decsp", 5) == 0) {
537 if (E->Arg[5] >= '1' && E->Arg[5] <= '8') {
538 return (E->Arg[5] - '0');
540 } else if (strcmp (E->Arg, "subysp") == 0 && RegValIsKnown (E->RI->In.RegY)) {
541 return E->RI->In.RegY;
544 /* If we come here, it's not a decsp op */
550 static unsigned OptStackPtrOps (CodeSeg* S)
551 /* Merge adjacent calls to decsp into one. NOTE: This function won't merge all
555 unsigned Changes = 0;
558 /* Walk over the entries */
560 while (I < CS_GetEntryCount (S)) {
566 /* Get the next entry */
567 const CodeEntry* E = CS_GetEntry (S, I);
569 /* Check for decspn or subysp */
570 if (E->OPC == OP65_JSR &&
571 (Dec1 = IsDecSP (E)) > 0 &&
572 (N = CS_GetNextEntry (S, I)) != 0 &&
573 (Dec2 = IsDecSP (N)) > 0 &&
574 (Dec1 += Dec2) <= 255 &&
580 /* We can combine the two */
582 /* Insert a call to decsp */
583 xsprintf (Buf, sizeof (Buf), "decsp%u", Dec1);
584 X = NewCodeEntry (OP65_JSR, AM65_ABS, Buf, 0, N->LI);
585 CS_InsertEntry (S, X, I+2);
587 /* Insert a call to subysp */
588 const char* Arg = MakeHexArg (Dec1);
589 X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, N->LI);
590 CS_InsertEntry (S, X, I+2);
591 X = NewCodeEntry (OP65_JSR, AM65_ABS, "subysp", 0, N->LI);
592 CS_InsertEntry (S, X, I+3);
595 /* Delete the old code */
596 CS_DelEntries (S, I, 2);
598 /* Regenerate register info */
601 /* Remember we had changes */
612 /* Return the number of changes made */
616 static unsigned OptGotoSPAdj (CodeSeg* S)
617 /* Remove unnecessary SP adjustment while gotoing
620 unsigned Changes = 0;
623 /* Walk over the entries */
625 while (I < CS_GetEntryCount (S)) {
627 CodeEntry* L[10], *X;
628 unsigned short adjustment;
632 L[0] = CS_GetEntry (S, I);
634 /* Check for the sequence */
635 if (L[0]->OPC == OP65_PHA &&
636 CS_GetEntries (S, L+1, I+1, 9) &&
637 L[1]->OPC == OP65_LDA &&
638 L[1]->AM == AM65_ABS &&
639 L[2]->OPC == OP65_CLC &&
640 L[3]->OPC == OP65_ADC &&
641 strcmp (L[3]->Arg, "sp") == 0 &&
642 L[6]->OPC == OP65_ADC &&
643 strcmp (L[6]->Arg, "sp+1") == 0 &&
644 L[9]->OPC == OP65_JMP
646 printf("Goto SP adjustment found. Jump to: %s, data Label: %s\n", L[9]->Arg, L[1]->Arg);
647 adjustment = FindSPAdjustment(L[1]->Arg);
649 if (adjustment == 0) {
650 CS_DelEntries (S, I, 9);
652 else if (adjustment > 255) {
653 Arg = MakeHexArg (adjustment & 0xff);
654 X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, L[1]->LI);
655 CS_InsertEntry(S, X, I + 1);
656 Arg = MakeHexArg (adjustment >> 8);
657 X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, L[5]->LI);
658 CS_InsertEntry(S, X, I + 6);
660 CS_DelEntry(S, I + 2);
661 CS_DelEntry(S, I + 6);
663 else if (adjustment > 8) {
664 Arg = MakeHexArg (adjustment & 0xff);
665 X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, L[1]->LI);
666 CS_InsertEntry (S, X, I);
667 X = NewCodeEntry (OP65_JSR, AM65_ABS, "addysp", 0, L[1]->LI);
668 CS_InsertEntry (S, X, I + 1);
670 CS_DelEntries(S, I + 2, 9);
674 xsprintf (Buf, sizeof (Buf), "incsp%u", adjustment);
675 X = NewCodeEntry (OP65_JSR, AM65_ABS, Buf, 0, L[1]->LI);
676 CS_InsertEntry (S, X, I);
678 CS_DelEntries(S, I + 1, 9);
680 /* Regenerate register info */
683 /* Remember we had changes */
693 /* Return the number of changes made */
697 /*****************************************************************************/
699 /*****************************************************************************/
703 typedef struct OptFunc OptFunc;
705 unsigned (*Func) (CodeSeg*); /* Optimizer function */
706 const char* Name; /* Name of the function/group */
707 unsigned CodeSizeFactor; /* Code size factor for this opt func */
708 unsigned long TotalRuns; /* Total number of runs */
709 unsigned long LastRuns; /* Last number of runs */
710 unsigned long TotalChanges; /* Total number of changes */
711 unsigned long LastChanges; /* Last number of changes */
712 char Disabled; /* True if function disabled */
717 /*****************************************************************************/
719 /*****************************************************************************/
723 /* A list of all the function descriptions */
724 static OptFunc DOpt65C02BitOps = { Opt65C02BitOps, "Opt65C02BitOps", 66, 0, 0, 0, 0, 0 };
725 static OptFunc DOpt65C02Ind = { Opt65C02Ind, "Opt65C02Ind", 100, 0, 0, 0, 0, 0 };
726 static OptFunc DOpt65C02Stores = { Opt65C02Stores, "Opt65C02Stores", 100, 0, 0, 0, 0, 0 };
727 static OptFunc DOptAdd1 = { OptAdd1, "OptAdd1", 125, 0, 0, 0, 0, 0 };
728 static OptFunc DOptAdd2 = { OptAdd2, "OptAdd2", 200, 0, 0, 0, 0, 0 };
729 static OptFunc DOptAdd3 = { OptAdd3, "OptAdd3", 65, 0, 0, 0, 0, 0 };
730 static OptFunc DOptAdd4 = { OptAdd4, "OptAdd4", 90, 0, 0, 0, 0, 0 };
731 static OptFunc DOptAdd5 = { OptAdd5, "OptAdd5", 100, 0, 0, 0, 0, 0 };
732 static OptFunc DOptAdd6 = { OptAdd6, "OptAdd6", 40, 0, 0, 0, 0, 0 };
733 static OptFunc DOptBNegA1 = { OptBNegA1, "OptBNegA1", 100, 0, 0, 0, 0, 0 };
734 static OptFunc DOptBNegA2 = { OptBNegA2, "OptBNegA2", 100, 0, 0, 0, 0, 0 };
735 static OptFunc DOptBNegAX1 = { OptBNegAX1, "OptBNegAX1", 100, 0, 0, 0, 0, 0 };
736 static OptFunc DOptBNegAX2 = { OptBNegAX2, "OptBNegAX2", 100, 0, 0, 0, 0, 0 };
737 static OptFunc DOptBNegAX3 = { OptBNegAX3, "OptBNegAX3", 100, 0, 0, 0, 0, 0 };
738 static OptFunc DOptBNegAX4 = { OptBNegAX4, "OptBNegAX4", 100, 0, 0, 0, 0, 0 };
739 static OptFunc DOptBoolTrans = { OptBoolTrans, "OptBoolTrans", 100, 0, 0, 0, 0, 0 };
740 static OptFunc DOptBranchDist = { OptBranchDist, "OptBranchDist", 0, 0, 0, 0, 0, 0 };
741 static OptFunc DOptCmp1 = { OptCmp1, "OptCmp1", 42, 0, 0, 0, 0, 0 };
742 static OptFunc DOptCmp2 = { OptCmp2, "OptCmp2", 85, 0, 0, 0, 0, 0 };
743 static OptFunc DOptCmp3 = { OptCmp3, "OptCmp3", 75, 0, 0, 0, 0, 0 };
744 static OptFunc DOptCmp4 = { OptCmp4, "OptCmp4", 75, 0, 0, 0, 0, 0 };
745 static OptFunc DOptCmp5 = { OptCmp5, "OptCmp5", 100, 0, 0, 0, 0, 0 };
746 static OptFunc DOptCmp6 = { OptCmp6, "OptCmp6", 100, 0, 0, 0, 0, 0 };
747 static OptFunc DOptCmp7 = { OptCmp7, "OptCmp7", 85, 0, 0, 0, 0, 0 };
748 static OptFunc DOptCmp8 = { OptCmp8, "OptCmp8", 50, 0, 0, 0, 0, 0 };
749 static OptFunc DOptCmp9 = { OptCmp9, "OptCmp9", 85, 0, 0, 0, 0, 0 };
750 static OptFunc DOptComplAX1 = { OptComplAX1, "OptComplAX1", 65, 0, 0, 0, 0, 0 };
751 static OptFunc DOptCondBranches1= { OptCondBranches1,"OptCondBranches1", 80, 0, 0, 0, 0, 0 };
752 static OptFunc DOptCondBranches2= { OptCondBranches2,"OptCondBranches2", 0, 0, 0, 0, 0, 0 };
753 static OptFunc DOptDeadCode = { OptDeadCode, "OptDeadCode", 100, 0, 0, 0, 0, 0 };
754 static OptFunc DOptDeadJumps = { OptDeadJumps, "OptDeadJumps", 100, 0, 0, 0, 0, 0 };
755 static OptFunc DOptDecouple = { OptDecouple, "OptDecouple", 100, 0, 0, 0, 0, 0 };
756 static OptFunc DOptDupLoads = { OptDupLoads, "OptDupLoads", 0, 0, 0, 0, 0, 0 };
757 static OptFunc DOptGotoSPAdj = { OptGotoSPAdj, "OptGotoSPAdj", 0, 0, 0, 0, 0, 0 };
758 static OptFunc DOptIndLoads1 = { OptIndLoads1, "OptIndLoads1", 0, 0, 0, 0, 0, 0 };
759 static OptFunc DOptIndLoads2 = { OptIndLoads2, "OptIndLoads2", 0, 0, 0, 0, 0, 0 };
760 static OptFunc DOptJumpCascades = { OptJumpCascades, "OptJumpCascades", 100, 0, 0, 0, 0, 0 };
761 static OptFunc DOptJumpTarget1 = { OptJumpTarget1, "OptJumpTarget1", 100, 0, 0, 0, 0, 0 };
762 static OptFunc DOptJumpTarget2 = { OptJumpTarget2, "OptJumpTarget2", 100, 0, 0, 0, 0, 0 };
763 static OptFunc DOptJumpTarget3 = { OptJumpTarget3, "OptJumpTarget3", 100, 0, 0, 0, 0, 0 };
764 static OptFunc DOptLoad1 = { OptLoad1, "OptLoad1", 100, 0, 0, 0, 0, 0 };
765 static OptFunc DOptLoad2 = { OptLoad2, "OptLoad2", 200, 0, 0, 0, 0, 0 };
766 static OptFunc DOptLoad3 = { OptLoad3, "OptLoad3", 0, 0, 0, 0, 0, 0 };
767 static OptFunc DOptNegAX1 = { OptNegAX1, "OptNegAX1", 165, 0, 0, 0, 0, 0 };
768 static OptFunc DOptNegAX2 = { OptNegAX2, "OptNegAX2", 200, 0, 0, 0, 0, 0 };
769 static OptFunc DOptRTS = { OptRTS, "OptRTS", 100, 0, 0, 0, 0, 0 };
770 static OptFunc DOptRTSJumps1 = { OptRTSJumps1, "OptRTSJumps1", 100, 0, 0, 0, 0, 0 };
771 static OptFunc DOptRTSJumps2 = { OptRTSJumps2, "OptRTSJumps2", 100, 0, 0, 0, 0, 0 };
772 static OptFunc DOptPrecalc = { OptPrecalc, "OptPrecalc", 100, 0, 0, 0, 0, 0 };
773 static OptFunc DOptPtrLoad1 = { OptPtrLoad1, "OptPtrLoad1", 100, 0, 0, 0, 0, 0 };
774 static OptFunc DOptPtrLoad2 = { OptPtrLoad2, "OptPtrLoad2", 100, 0, 0, 0, 0, 0 };
775 static OptFunc DOptPtrLoad3 = { OptPtrLoad3, "OptPtrLoad3", 100, 0, 0, 0, 0, 0 };
776 static OptFunc DOptPtrLoad4 = { OptPtrLoad4, "OptPtrLoad4", 100, 0, 0, 0, 0, 0 };
777 static OptFunc DOptPtrLoad5 = { OptPtrLoad5, "OptPtrLoad5", 50, 0, 0, 0, 0, 0 };
778 static OptFunc DOptPtrLoad6 = { OptPtrLoad6, "OptPtrLoad6", 60, 0, 0, 0, 0, 0 };
779 static OptFunc DOptPtrLoad7 = { OptPtrLoad7, "OptPtrLoad7", 140, 0, 0, 0, 0, 0 };
780 static OptFunc DOptPtrLoad11 = { OptPtrLoad11, "OptPtrLoad11", 92, 0, 0, 0, 0, 0 };
781 static OptFunc DOptPtrLoad12 = { OptPtrLoad12, "OptPtrLoad12", 50, 0, 0, 0, 0, 0 };
782 static OptFunc DOptPtrLoad13 = { OptPtrLoad13, "OptPtrLoad13", 65, 0, 0, 0, 0, 0 };
783 static OptFunc DOptPtrLoad14 = { OptPtrLoad14, "OptPtrLoad14", 108, 0, 0, 0, 0, 0 };
784 static OptFunc DOptPtrLoad15 = { OptPtrLoad15, "OptPtrLoad15", 86, 0, 0, 0, 0, 0 };
785 static OptFunc DOptPtrLoad16 = { OptPtrLoad16, "OptPtrLoad16", 100, 0, 0, 0, 0, 0 };
786 static OptFunc DOptPtrLoad17 = { OptPtrLoad17, "OptPtrLoad17", 190, 0, 0, 0, 0, 0 };
787 static OptFunc DOptPtrStore1 = { OptPtrStore1, "OptPtrStore1", 65, 0, 0, 0, 0, 0 };
788 static OptFunc DOptPtrStore2 = { OptPtrStore2, "OptPtrStore2", 65, 0, 0, 0, 0, 0 };
789 static OptFunc DOptPtrStore3 = { OptPtrStore3, "OptPtrStore3", 100, 0, 0, 0, 0, 0 };
790 static OptFunc DOptPush1 = { OptPush1, "OptPush1", 65, 0, 0, 0, 0, 0 };
791 static OptFunc DOptPush2 = { OptPush2, "OptPush2", 50, 0, 0, 0, 0, 0 };
792 static OptFunc DOptPushPop = { OptPushPop, "OptPushPop", 0, 0, 0, 0, 0, 0 };
793 static OptFunc DOptShift1 = { OptShift1, "OptShift1", 100, 0, 0, 0, 0, 0 };
794 static OptFunc DOptShift2 = { OptShift2, "OptShift2", 100, 0, 0, 0, 0, 0 };
795 static OptFunc DOptShift3 = { OptShift3, "OptShift3", 17, 0, 0, 0, 0, 0 };
796 static OptFunc DOptShift4 = { OptShift4, "OptShift4", 100, 0, 0, 0, 0, 0 };
797 static OptFunc DOptShift5 = { OptShift5, "OptShift5", 110, 0, 0, 0, 0, 0 };
798 static OptFunc DOptShift6 = { OptShift6, "OptShift6", 200, 0, 0, 0, 0, 0 };
799 static OptFunc DOptSize1 = { OptSize1, "OptSize1", 100, 0, 0, 0, 0, 0 };
800 static OptFunc DOptSize2 = { OptSize2, "OptSize2", 100, 0, 0, 0, 0, 0 };
801 static OptFunc DOptStackOps = { OptStackOps, "OptStackOps", 100, 0, 0, 0, 0, 0 };
802 static OptFunc DOptStackPtrOps = { OptStackPtrOps, "OptStackPtrOps", 50, 0, 0, 0, 0, 0 };
803 static OptFunc DOptStore1 = { OptStore1, "OptStore1", 70, 0, 0, 0, 0, 0 };
804 static OptFunc DOptStore2 = { OptStore2, "OptStore2", 115, 0, 0, 0, 0, 0 };
805 static OptFunc DOptStore3 = { OptStore3, "OptStore3", 120, 0, 0, 0, 0, 0 };
806 static OptFunc DOptStore4 = { OptStore4, "OptStore4", 50, 0, 0, 0, 0, 0 };
807 static OptFunc DOptStore5 = { OptStore5, "OptStore5", 100, 0, 0, 0, 0, 0 };
808 static OptFunc DOptStoreLoad = { OptStoreLoad, "OptStoreLoad", 0, 0, 0, 0, 0, 0 };
809 static OptFunc DOptSub1 = { OptSub1, "OptSub1", 100, 0, 0, 0, 0, 0 };
810 static OptFunc DOptSub2 = { OptSub2, "OptSub2", 100, 0, 0, 0, 0, 0 };
811 static OptFunc DOptSub3 = { OptSub3, "OptSub3", 100, 0, 0, 0, 0, 0 };
812 static OptFunc DOptTest1 = { OptTest1, "OptTest1", 65, 0, 0, 0, 0, 0 };
813 static OptFunc DOptTest2 = { OptTest2, "OptTest2", 50, 0, 0, 0, 0, 0 };
814 static OptFunc DOptTransfers1 = { OptTransfers1, "OptTransfers1", 0, 0, 0, 0, 0, 0 };
815 static OptFunc DOptTransfers2 = { OptTransfers2, "OptTransfers2", 60, 0, 0, 0, 0, 0 };
816 static OptFunc DOptTransfers3 = { OptTransfers3, "OptTransfers3", 65, 0, 0, 0, 0, 0 };
817 static OptFunc DOptTransfers4 = { OptTransfers4, "OptTransfers4", 65, 0, 0, 0, 0, 0 };
818 static OptFunc DOptUnusedLoads = { OptUnusedLoads, "OptUnusedLoads", 0, 0, 0, 0, 0, 0 };
819 static OptFunc DOptUnusedStores = { OptUnusedStores, "OptUnusedStores", 0, 0, 0, 0, 0, 0 };
822 /* Table containing all the steps in alphabetical order */
823 static OptFunc* OptFuncs[] = {
921 #define OPTFUNC_COUNT (sizeof(OptFuncs) / sizeof(OptFuncs[0]))
925 static int CmpOptStep (const void* Key, const void* Func)
926 /* Compare function for bsearch */
928 return strcmp (Key, (*(const OptFunc**)Func)->Name);
933 static OptFunc* FindOptFunc (const char* Name)
934 /* Find an optimizer step by name in the table and return a pointer. Return
935 ** NULL if no such step is found.
938 /* Search for the function in the list */
939 OptFunc** O = bsearch (Name, OptFuncs, OPTFUNC_COUNT, sizeof (OptFuncs[0]), CmpOptStep);
945 static OptFunc* GetOptFunc (const char* Name)
946 /* Find an optimizer step by name in the table and return a pointer. Print an
947 ** error and call AbEnd if not found.
950 /* Search for the function in the list */
951 OptFunc* F = FindOptFunc (Name);
954 AbEnd ("Optimization step `%s' not found", Name);
961 void DisableOpt (const char* Name)
962 /* Disable the optimization with the given name */
964 if (strcmp (Name, "any") == 0) {
966 for (I = 0; I < OPTFUNC_COUNT; ++I) {
967 OptFuncs[I]->Disabled = 1;
970 GetOptFunc(Name)->Disabled = 1;
976 void EnableOpt (const char* Name)
977 /* Enable the optimization with the given name */
979 if (strcmp (Name, "any") == 0) {
981 for (I = 0; I < OPTFUNC_COUNT; ++I) {
982 OptFuncs[I]->Disabled = 0;
985 GetOptFunc(Name)->Disabled = 0;
991 void ListOptSteps (FILE* F)
992 /* List all optimization steps */
996 fprintf (F, "any\n");
997 for (I = 0; I < OPTFUNC_COUNT; ++I) {
998 fprintf (F, "%s\n", OptFuncs[I]->Name);
1004 static void ReadOptStats (const char* Name)
1005 /* Read the optimizer statistics file */
1010 /* Try to open the file */
1011 FILE* F = fopen (Name, "r");
1013 /* Ignore the error */
1017 /* Read and parse the lines */
1019 while (fgets (Buf, sizeof (Buf), F) != 0) {
1027 unsigned long TotalRuns;
1028 unsigned long TotalChanges;
1033 /* Remove trailing white space including the line terminator */
1036 while (Len > 0 && IsSpace (B[Len-1])) {
1041 /* Remove leading whitespace */
1042 while (IsSpace (*B)) {
1046 /* Check for empty and comment lines */
1047 if (*B == '\0' || *B == ';' || *B == '#') {
1051 /* Parse the line */
1052 if (sscanf (B, "%31s %lu %*u %lu %*u", Name, &TotalRuns, &TotalChanges) != 3) {
1057 /* Search for the optimizer step. */
1058 Func = FindOptFunc (Name);
1064 /* Found the step, set the fields */
1065 Func->TotalRuns = TotalRuns;
1066 Func->TotalChanges = TotalChanges;
1070 /* Close the file, ignore errors here. */
1076 static void WriteOptStats (const char* Name)
1077 /* Write the optimizer statistics file */
1081 /* Try to open the file */
1082 FILE* F = fopen (Name, "w");
1084 /* Ignore the error */
1088 /* Write a header */
1090 "; Optimizer Total Last Total Last\n"
1091 "; Step Runs Runs Chg Chg\n");
1094 /* Write the data */
1095 for (I = 0; I < OPTFUNC_COUNT; ++I) {
1096 const OptFunc* O = OptFuncs[I];
1098 "%-20s %10lu %10lu %10lu %10lu\n",
1106 /* Close the file, ignore errors here. */
1112 static void OpenDebugFile (const CodeSeg* S)
1113 /* Open the debug file for the given segment if the flag is on */
1115 if (DebugOptOutput) {
1116 StrBuf Name = AUTO_STRBUF_INITIALIZER;
1118 SB_CopyStr (&Name, S->Func->Name);
1120 SB_CopyStr (&Name, "global");
1122 SB_AppendStr (&Name, ".opt");
1123 SB_Terminate (&Name);
1124 OpenDebugOutputFile (SB_GetConstBuf (&Name));
1131 static void WriteDebugOutput (CodeSeg* S, const char* Step)
1132 /* Write a separator line into the debug file if the flag is on */
1134 if (DebugOptOutput) {
1135 /* Output a separator */
1136 WriteOutput ("=========================================================================\n");
1138 /* Output a header line */
1140 /* Initial output */
1141 WriteOutput ("Initial code for function `%s':\n",
1142 S->Func? S->Func->Name : "<global>");
1144 WriteOutput ("Code after applying `%s':\n", Step);
1147 /* Output the code segment */
1154 static unsigned RunOptFunc (CodeSeg* S, OptFunc* F, unsigned Max)
1155 /* Run one optimizer function Max times or until there are no more changes */
1157 unsigned Changes, C;
1159 /* Don't run the function if it is disabled or if it is prohibited by the
1162 if (F->Disabled || F->CodeSizeFactor > S->CodeSizeFactor) {
1166 /* Run this until there are no more changes */
1170 /* Run the function */
1177 F->TotalChanges += C;
1178 F->LastChanges += C;
1180 /* If we had changes, output stuff and regenerate register info */
1183 printf ("Applied %s: %u changes\n", F->Name, C);
1185 WriteDebugOutput (S, F->Name);
1189 } while (--Max && C > 0);
1191 /* Return the number of changes */
1197 static unsigned RunOptGroup1 (CodeSeg* S)
1198 /* Run the first group of optimization steps. These steps translate known
1199 ** patterns emitted by the code generator into more optimal patterns. Order
1200 ** of the steps is important, because some of the steps done earlier cover
1201 ** the same patterns as later steps as subpatterns.
1204 unsigned Changes = 0;
1206 Changes += RunOptFunc (S, &DOptGotoSPAdj, 1);
1207 Changes += RunOptFunc (S, &DOptStackPtrOps, 5);
1208 Changes += RunOptFunc (S, &DOptPtrStore1, 1);
1209 Changes += RunOptFunc (S, &DOptPtrStore2, 1);
1210 Changes += RunOptFunc (S, &DOptPtrStore3, 1);
1211 Changes += RunOptFunc (S, &DOptAdd3, 1); /* Before OptPtrLoad5! */
1212 Changes += RunOptFunc (S, &DOptPtrLoad1, 1);
1213 Changes += RunOptFunc (S, &DOptPtrLoad2, 1);
1214 Changes += RunOptFunc (S, &DOptPtrLoad3, 1);
1215 Changes += RunOptFunc (S, &DOptPtrLoad4, 1);
1216 Changes += RunOptFunc (S, &DOptPtrLoad5, 1);
1217 Changes += RunOptFunc (S, &DOptPtrLoad6, 1);
1218 Changes += RunOptFunc (S, &DOptPtrLoad7, 1);
1219 Changes += RunOptFunc (S, &DOptPtrLoad11, 1);
1220 Changes += RunOptFunc (S, &DOptPtrLoad12, 1);
1221 Changes += RunOptFunc (S, &DOptPtrLoad13, 1);
1222 Changes += RunOptFunc (S, &DOptPtrLoad14, 1);
1223 Changes += RunOptFunc (S, &DOptPtrLoad15, 1);
1224 Changes += RunOptFunc (S, &DOptPtrLoad16, 1);
1225 Changes += RunOptFunc (S, &DOptPtrLoad17, 1);
1226 Changes += RunOptFunc (S, &DOptBNegAX1, 1);
1227 Changes += RunOptFunc (S, &DOptBNegAX2, 1);
1228 Changes += RunOptFunc (S, &DOptBNegAX3, 1);
1229 Changes += RunOptFunc (S, &DOptBNegAX4, 1);
1230 Changes += RunOptFunc (S, &DOptAdd1, 1);
1231 Changes += RunOptFunc (S, &DOptAdd2, 1);
1232 Changes += RunOptFunc (S, &DOptAdd4, 1);
1233 Changes += RunOptFunc (S, &DOptAdd5, 1);
1234 Changes += RunOptFunc (S, &DOptAdd6, 1);
1235 Changes += RunOptFunc (S, &DOptSub1, 1);
1236 Changes += RunOptFunc (S, &DOptSub3, 1);
1237 Changes += RunOptFunc (S, &DOptStore4, 1);
1238 Changes += RunOptFunc (S, &DOptStore5, 1);
1239 Changes += RunOptFunc (S, &DOptShift1, 1);
1240 Changes += RunOptFunc (S, &DOptShift2, 1);
1241 Changes += RunOptFunc (S, &DOptShift5, 1);
1242 Changes += RunOptFunc (S, &DOptShift6, 1);
1243 Changes += RunOptFunc (S, &DOptStore1, 1);
1244 Changes += RunOptFunc (S, &DOptStore2, 5);
1245 Changes += RunOptFunc (S, &DOptStore3, 5);
1247 /* Return the number of changes */
1253 static unsigned RunOptGroup2 (CodeSeg* S)
1254 /* Run one group of optimization steps. This step involves just decoupling
1255 ** instructions by replacing them by instructions that do not depend on
1256 ** previous instructions. This makes it easier to find instructions that
1260 unsigned Changes = 0;
1262 Changes += RunOptFunc (S, &DOptDecouple, 1);
1264 /* Return the number of changes */
1270 static unsigned RunOptGroup3 (CodeSeg* S)
1271 /* Run one group of optimization steps. These steps depend on each other,
1272 ** that means that one step may allow another step to do additional work,
1273 ** so we will repeat the steps as long as we see any changes.
1276 unsigned Changes, C;
1282 C += RunOptFunc (S, &DOptBNegA1, 1);
1283 C += RunOptFunc (S, &DOptBNegA2, 1);
1284 C += RunOptFunc (S, &DOptNegAX1, 1);
1285 C += RunOptFunc (S, &DOptNegAX2, 1);
1286 C += RunOptFunc (S, &DOptStackOps, 3);
1287 C += RunOptFunc (S, &DOptShift1, 1);
1288 C += RunOptFunc (S, &DOptShift4, 1);
1289 C += RunOptFunc (S, &DOptComplAX1, 1);
1290 C += RunOptFunc (S, &DOptSub1, 1);
1291 C += RunOptFunc (S, &DOptSub2, 1);
1292 C += RunOptFunc (S, &DOptSub3, 1);
1293 C += RunOptFunc (S, &DOptAdd5, 1);
1294 C += RunOptFunc (S, &DOptAdd6, 1);
1295 C += RunOptFunc (S, &DOptJumpCascades, 1);
1296 C += RunOptFunc (S, &DOptDeadJumps, 1);
1297 C += RunOptFunc (S, &DOptRTS, 1);
1298 C += RunOptFunc (S, &DOptDeadCode, 1);
1299 C += RunOptFunc (S, &DOptBoolTrans, 1);
1300 C += RunOptFunc (S, &DOptJumpTarget1, 1);
1301 C += RunOptFunc (S, &DOptJumpTarget2, 1);
1302 C += RunOptFunc (S, &DOptCondBranches1, 1);
1303 C += RunOptFunc (S, &DOptCondBranches2, 1);
1304 C += RunOptFunc (S, &DOptRTSJumps1, 1);
1305 C += RunOptFunc (S, &DOptCmp1, 1);
1306 C += RunOptFunc (S, &DOptCmp2, 1);
1307 C += RunOptFunc (S, &DOptCmp8, 1); /* Must run before OptCmp3 */
1308 C += RunOptFunc (S, &DOptCmp3, 1);
1309 C += RunOptFunc (S, &DOptCmp4, 1);
1310 C += RunOptFunc (S, &DOptCmp5, 1);
1311 C += RunOptFunc (S, &DOptCmp6, 1);
1312 C += RunOptFunc (S, &DOptCmp7, 1);
1313 C += RunOptFunc (S, &DOptCmp9, 1);
1315 C += RunOptFunc (S, &DOptTest1, 1);
1316 C += RunOptFunc (S, &DOptLoad1, 1);
1317 C += RunOptFunc (S, &DOptJumpTarget3, 1); /* After OptCondBranches2 */
1318 C += RunOptFunc (S, &DOptUnusedLoads, 1);
1319 C += RunOptFunc (S, &DOptUnusedStores, 1);
1320 C += RunOptFunc (S, &DOptDupLoads, 1);
1321 C += RunOptFunc (S, &DOptStoreLoad, 1);
1322 C += RunOptFunc (S, &DOptTransfers1, 1);
1323 C += RunOptFunc (S, &DOptTransfers3, 1);
1324 C += RunOptFunc (S, &DOptTransfers4, 1);
1325 C += RunOptFunc (S, &DOptStore1, 1);
1326 C += RunOptFunc (S, &DOptStore5, 1);
1327 C += RunOptFunc (S, &DOptPushPop, 1);
1328 C += RunOptFunc (S, &DOptPrecalc, 1);
1334 /* Return the number of changes */
1340 static unsigned RunOptGroup4 (CodeSeg* S)
1341 /* Run another round of pattern replacements. These are done late, since there
1342 ** may be better replacements before.
1345 unsigned Changes = 0;
1347 /* Repeat some of the steps here */
1348 Changes += RunOptFunc (S, &DOptShift3, 1);
1349 Changes += RunOptFunc (S, &DOptPush1, 1);
1350 Changes += RunOptFunc (S, &DOptPush2, 1);
1351 Changes += RunOptFunc (S, &DOptUnusedLoads, 1);
1352 Changes += RunOptFunc (S, &DOptTest2, 1);
1353 Changes += RunOptFunc (S, &DOptTransfers2, 1);
1354 Changes += RunOptFunc (S, &DOptLoad2, 1);
1355 Changes += RunOptFunc (S, &DOptLoad3, 1);
1356 Changes += RunOptFunc (S, &DOptDupLoads, 1);
1358 /* Return the number of changes */
1364 static unsigned RunOptGroup5 (CodeSeg* S)
1365 /* 65C02 specific optimizations. */
1367 unsigned Changes = 0;
1369 if (CPUIsets[CPU] & CPU_ISET_65SC02) {
1370 Changes += RunOptFunc (S, &DOpt65C02BitOps, 1);
1371 Changes += RunOptFunc (S, &DOpt65C02Ind, 1);
1372 Changes += RunOptFunc (S, &DOpt65C02Stores, 1);
1374 /* The 65C02 replacement codes do often make the use of a register
1375 ** value unnecessary, so if we have changes, run another load
1378 Changes += RunOptFunc (S, &DOptUnusedLoads, 1);
1382 /* Return the number of changes */
1388 static unsigned RunOptGroup6 (CodeSeg* S)
1389 /* This one is quite special. It tries to replace "lda (sp),y" by "lda (sp,x)".
1390 ** The latter is ony cycle slower, but if we're able to remove the necessary
1391 ** load of the Y register, because X is zero anyway, we gain 1 cycle and
1392 ** shorten the code by one (transfer) or two bytes (load). So what we do is
1393 ** to replace the insns, remove unused loads, and then change back all insns
1394 ** where Y is still zero (meaning that the load has not been removed).
1397 unsigned Changes = 0;
1399 /* This group will only run for a standard 6502, because the 65C02 has a
1400 ** better addressing mode that covers this case.
1402 if ((CPUIsets[CPU] & CPU_ISET_65SC02) == 0) {
1403 Changes += RunOptFunc (S, &DOptIndLoads1, 1);
1404 Changes += RunOptFunc (S, &DOptUnusedLoads, 1);
1405 Changes += RunOptFunc (S, &DOptIndLoads2, 1);
1408 /* Return the number of changes */
1414 static unsigned RunOptGroup7 (CodeSeg* S)
1415 /* The last group of optimization steps. Adjust branches, do size optimizations.
1418 unsigned Changes = 0;
1421 /* Optimize for size, that is replace operations by shorter ones, even
1422 ** if this does hinder further optimizations (no problem since we're
1425 C = RunOptFunc (S, &DOptSize1, 1);
1428 /* Run some optimization passes again, since the size optimizations
1429 ** may have opened new oportunities.
1431 Changes += RunOptFunc (S, &DOptUnusedLoads, 1);
1432 Changes += RunOptFunc (S, &DOptUnusedStores, 1);
1433 Changes += RunOptFunc (S, &DOptJumpTarget1, 5);
1434 Changes += RunOptFunc (S, &DOptStore5, 1);
1437 C = RunOptFunc (S, &DOptSize2, 1);
1440 /* Run some optimization passes again, since the size optimizations
1441 ** may have opened new oportunities.
1443 Changes += RunOptFunc (S, &DOptUnusedLoads, 1);
1444 Changes += RunOptFunc (S, &DOptJumpTarget1, 5);
1445 Changes += RunOptFunc (S, &DOptStore5, 1);
1446 Changes += RunOptFunc (S, &DOptTransfers1, 1);
1447 Changes += RunOptFunc (S, &DOptTransfers3, 1);
1450 /* Adjust branch distances */
1451 Changes += RunOptFunc (S, &DOptBranchDist, 3);
1453 /* Replace conditional branches to RTS. If we had changes, we must run dead
1454 ** code elimination again, since the change may have introduced dead code.
1456 C = RunOptFunc (S, &DOptRTSJumps2, 1);
1459 Changes += RunOptFunc (S, &DOptDeadCode, 1);
1462 /* Return the number of changes */
1468 void RunOpt (CodeSeg* S)
1469 /* Run the optimizer */
1471 const char* StatFileName;
1473 /* If we shouldn't run the optimizer, bail out */
1478 /* Check if we are requested to write optimizer statistics */
1479 StatFileName = getenv ("CC65_OPTSTATS");
1481 ReadOptStats (StatFileName);
1484 /* Print the name of the function we are working on */
1486 Print (stdout, 1, "Running optimizer for function `%s'\n", S->Func->Name);
1488 Print (stdout, 1, "Running optimizer for global code segment\n");
1491 /* If requested, open an output file */
1493 WriteDebugOutput (S, 0);
1495 /* Generate register info for all instructions */
1498 /* Run groups of optimizations */
1507 /* Free register info */
1510 /* Close output file if necessary */
1511 if (DebugOptOutput) {
1515 /* Write statistics */
1517 WriteOptStats (StatFileName);