]> git.sur5r.net Git - cc65/blob - src/cc65/codeopt.c
cdf0c193ff955c3c3c9e107293745e8ca2900964
[cc65] / src / cc65 / codeopt.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 codeopt.c                                 */
4 /*                                                                           */
5 /*                           Optimizer subroutines                           */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2001-2009 Ullrich von Bassewitz                                       */
10 /*               Roemerstrasse 52                                            */
11 /*               D-70794 Filderstadt                                         */
12 /* EMail:        uz@cc65.org                                                 */
13 /*                                                                           */
14 /*                                                                           */
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.                                    */
18 /*                                                                           */
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:                            */
22 /*                                                                           */
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              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 #include <stdlib.h>
37 #include <string.h>
38
39 /* common */
40 #include "abend.h"
41 #include "chartype.h"
42 #include "cpu.h"
43 #include "print.h"
44 #include "xmalloc.h"
45 #include "xsprintf.h"
46
47 /* cc65 */
48 #include "asmlabel.h"
49 #include "codeent.h"
50 #include "codeinfo.h"
51 #include "coptadd.h"
52 #include "coptc02.h"
53 #include "coptcmp.h"
54 #include "coptind.h"
55 #include "coptneg.h"
56 #include "coptptrload.h"
57 #include "coptpush.h"
58 #include "coptsize.h"
59 #include "coptstop.h"
60 #include "coptstore.h"
61 #include "coptsub.h"
62 #include "copttest.h"
63 #include "error.h"
64 #include "global.h"
65 #include "codeopt.h"
66
67
68
69 /*****************************************************************************/
70 /*                                     Data                                  */
71 /*****************************************************************************/
72
73
74
75 /* Shift types */
76 enum {
77     SHIFT_NONE,
78     SHIFT_ASR_1,
79     SHIFT_ASL_1,
80     SHIFT_LSR_1,
81     SHIFT_LSL_1
82 };
83
84
85
86 /*****************************************************************************/
87 /*                              Optimize shifts                              */
88 /*****************************************************************************/
89
90
91
92 static unsigned OptShift1 (CodeSeg* S)
93 /* A call to the shlaxN routine may get replaced by one or more asl insns
94  * if the value of X is not used later. If X is used later, but it is zero
95  * on entry and it's a shift by one, it may get replaced by:
96  *
97  *      asl     a
98  *      bcc     L1
99  *      inx
100  *  L1:
101  *
102  */
103 {
104     unsigned Changes = 0;
105     unsigned I;
106
107     /* Generate register info */
108     CS_GenRegInfo (S);
109
110     /* Walk over the entries */
111     I = 0;
112     while (I < CS_GetEntryCount (S)) {
113
114         CodeEntry* N;
115         CodeEntry* X;
116         CodeLabel* L;
117
118         /* Get next entry */
119         CodeEntry* E = CS_GetEntry (S, I);
120
121         /* Check for the sequence */
122         if (E->OPC == OP65_JSR                       &&
123             (strncmp (E->Arg, "shlax", 5) == 0 ||
124              strncmp (E->Arg, "aslax", 5) == 0)      &&
125             strlen (E->Arg) == 6                     &&
126             IsDigit (E->Arg[5])) {
127
128             if (!RegXUsed (S, I+1)) {
129
130                 /* Insert shift insns */
131                 unsigned Count = E->Arg[5] - '0';
132                 while (Count--) {
133                     X = NewCodeEntry (OP65_ASL, AM65_ACC, "a", 0, E->LI);
134                     CS_InsertEntry (S, X, I+1);
135                 }
136
137                 /* Delete the call to shlax */
138                 CS_DelEntry (S, I);
139
140                 /* Remember, we had changes */
141                 ++Changes;
142
143             } else if (E->RI->In.RegX == 0              &&
144                        E->Arg[5] == '1'                 &&
145                        (N = CS_GetNextEntry (S, I)) != 0) {
146
147                 /* asl a */
148                 X = NewCodeEntry (OP65_ASL, AM65_ACC, "a", 0, E->LI);
149                 CS_InsertEntry (S, X, I+1);
150
151                 /* bcc L1 */
152                 L = CS_GenLabel (S, N);
153                 X = NewCodeEntry (OP65_BCC, AM65_BRA, L->Name, L, E->LI);
154                 CS_InsertEntry (S, X, I+2);
155
156                 /* inx */
157                 X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, E->LI);
158                 CS_InsertEntry (S, X, I+3);
159
160                 /* Delete the call to shlax */
161                 CS_DelEntry (S, I);
162
163                 /* Remember, we had changes */
164                 ++Changes;
165             }
166
167         }
168
169         /* Next entry */
170         ++I;
171
172     }
173
174     /* Free the register info */
175     CS_FreeRegInfo (S);
176
177     /* Return the number of changes made */
178     return Changes;
179 }
180
181
182
183 static unsigned OptShift2 (CodeSeg* S)
184 /* A call to the shraxN routine may get replaced by one or more lsr insns
185  * if the value of X is zero.
186  */
187 {
188     unsigned Changes = 0;
189     unsigned I;
190
191     /* Generate register info */
192     CS_GenRegInfo (S);
193
194     /* Walk over the entries */
195     I = 0;
196     while (I < CS_GetEntryCount (S)) {
197
198         /* Get next entry */
199         CodeEntry* E = CS_GetEntry (S, I);
200
201         /* Check for the sequence */
202         if (E->OPC == OP65_JSR                       &&
203             strncmp (E->Arg, "shrax", 5) == 0        &&
204             strlen (E->Arg) == 6                     &&
205             IsDigit (E->Arg[5])                      &&
206             E->RI->In.RegX == 0) {
207
208             /* Insert shift insns */
209             unsigned Count = E->Arg[5] - '0';
210             while (Count--) {
211                 CodeEntry* X = NewCodeEntry (OP65_LSR, AM65_ACC, "a", 0, E->LI);
212                 CS_InsertEntry (S, X, I+1);
213             }
214
215             /* Delete the call to shrax */
216             CS_DelEntry (S, I);
217
218             /* Remember, we had changes */
219             ++Changes;
220
221         }
222
223         /* Next entry */
224         ++I;
225
226     }
227
228     /* Free the register info */
229     CS_FreeRegInfo (S);
230
231     /* Return the number of changes made */
232     return Changes;
233 }
234
235
236
237 static unsigned GetShiftType (const char* Sub)
238 /* Helper function for OptShift3 */
239 {
240     if (*Sub == 'a') {
241         if (strcmp (Sub+1, "slax1") == 0) {
242             return SHIFT_ASL_1;
243         } else if (strcmp (Sub+1, "srax1") == 0) {
244             return SHIFT_ASR_1;
245         }
246     } else if (*Sub == 's') {
247         if (strcmp (Sub+1, "hlax1") == 0) {
248             return SHIFT_LSL_1;
249         } else if (strcmp (Sub+1, "hrax1") == 0) {
250             return SHIFT_LSR_1;
251         }
252     }
253     return SHIFT_NONE;
254 }
255
256
257
258 static unsigned OptShift3 (CodeSeg* S)
259 /* Search for the sequence
260  *
261  *      lda     xxx
262  *      ldx     yyy
263  *      jsr     aslax1/asrax1/shlax1/shrax1
264  *      sta     aaa
265  *      stx     bbb
266  *
267  * and replace it by
268  *
269  *      lda     xxx
270  *      asl     a
271  *      sta     aaa
272  *      lda     yyy
273  *      rol     a
274  *      sta     bbb
275  *
276  * or similar, provided that a/x is not used later
277  */
278 {
279     unsigned Changes = 0;
280
281     /* Walk over the entries */
282     unsigned I = 0;
283     while (I < CS_GetEntryCount (S)) {
284
285         unsigned ShiftType;
286         CodeEntry* L[5];
287
288         /* Get next entry */
289         L[0] = CS_GetEntry (S, I);
290
291         /* Check for the sequence */
292         if (L[0]->OPC == OP65_LDA                               &&
293             (L[0]->AM == AM65_ABS || L[0]->AM == AM65_ZP)       &&
294             CS_GetEntries (S, L+1, I+1, 4)                      &&
295             !CS_RangeHasLabel (S, I+1, 4)                       &&
296             L[1]->OPC == OP65_LDX                               &&
297             (L[1]->AM == AM65_ABS || L[1]->AM == AM65_ZP)       &&
298             L[2]->OPC == OP65_JSR                               &&
299             (ShiftType = GetShiftType (L[2]->Arg)) != SHIFT_NONE&&
300             L[3]->OPC == OP65_STA                               &&
301             (L[3]->AM == AM65_ABS || L[3]->AM == AM65_ZP)       &&
302             L[4]->OPC == OP65_STX                               &&
303             (L[4]->AM == AM65_ABS || L[4]->AM == AM65_ZP)       &&
304             !RegAXUsed (S, I+5)) {
305
306             CodeEntry* X;
307
308             /* Handle the four shift types differently */
309             switch (ShiftType) {
310
311                 case SHIFT_ASR_1:
312                     X = NewCodeEntry (OP65_LDA, L[1]->AM, L[1]->Arg, 0, L[1]->LI);
313                     CS_InsertEntry (S, X, I+5);
314                     X = NewCodeEntry (OP65_CMP, AM65_IMM, "$80", 0, L[2]->LI);
315                     CS_InsertEntry (S, X, I+6);
316                     X = NewCodeEntry (OP65_ROR, AM65_ACC, "a", 0, L[2]->LI);
317                     CS_InsertEntry (S, X, I+7);
318                     X = NewCodeEntry (OP65_STA, L[4]->AM, L[4]->Arg, 0, L[4]->LI);
319                     CS_InsertEntry (S, X, I+8);
320                     X = NewCodeEntry (OP65_LDA, L[0]->AM, L[0]->Arg, 0, L[0]->LI);
321                     CS_InsertEntry (S, X, I+9);
322                     X = NewCodeEntry (OP65_ROR, AM65_ACC, "a", 0, L[2]->LI);
323                     CS_InsertEntry (S, X, I+10);
324                     X = NewCodeEntry (OP65_STA, L[3]->AM, L[3]->Arg, 0, L[3]->LI);
325                     CS_InsertEntry (S, X, I+11);
326                     CS_DelEntries (S, I, 5);
327                     break;
328
329                 case SHIFT_LSR_1:
330                     X = NewCodeEntry (OP65_LDA, L[1]->AM, L[1]->Arg, 0, L[1]->LI);
331                     CS_InsertEntry (S, X, I+5);
332                     X = NewCodeEntry (OP65_LSR, AM65_ACC, "a", 0, L[2]->LI);
333                     CS_InsertEntry (S, X, I+6);
334                     X = NewCodeEntry (OP65_STA, L[4]->AM, L[4]->Arg, 0, L[4]->LI);
335                     CS_InsertEntry (S, X, I+7);
336                     X = NewCodeEntry (OP65_LDA, L[0]->AM, L[0]->Arg, 0, L[0]->LI);
337                     CS_InsertEntry (S, X, I+8);
338                     X = NewCodeEntry (OP65_ROR, AM65_ACC, "a", 0, L[2]->LI);
339                     CS_InsertEntry (S, X, I+9);
340                     X = NewCodeEntry (OP65_STA, L[3]->AM, L[3]->Arg, 0, L[3]->LI);
341                     CS_InsertEntry (S, X, I+10);
342                     CS_DelEntries (S, I, 5);
343                     break;
344
345                 case SHIFT_LSL_1:
346                 case SHIFT_ASL_1:
347                     /* These two are identical */
348                     X = NewCodeEntry (OP65_ASL, AM65_ACC, "a", 0, L[2]->LI);
349                     CS_InsertEntry (S, X, I+1);
350                     X = NewCodeEntry (OP65_STA, L[3]->AM, L[3]->Arg, 0, L[3]->LI);
351                     CS_InsertEntry (S, X, I+2);
352                     X = NewCodeEntry (OP65_LDA, L[1]->AM, L[1]->Arg, 0, L[1]->LI);
353                     CS_InsertEntry (S, X, I+3);
354                     X = NewCodeEntry (OP65_ROL, AM65_ACC, "a", 0, L[2]->LI);
355                     CS_InsertEntry (S, X, I+4);
356                     X = NewCodeEntry (OP65_STA, L[4]->AM, L[4]->Arg, 0, L[4]->LI);
357                     CS_InsertEntry (S, X, I+5);
358                     CS_DelEntries (S, I+6, 4);
359                     break;
360
361             }
362
363             /* Remember, we had changes */
364             ++Changes;
365
366         }
367
368         /* Next entry */
369         ++I;
370
371     }
372
373     /* Return the number of changes made */
374     return Changes;
375 }
376
377
378
379 static unsigned OptShift4 (CodeSeg* S)
380 /* Inline the shift subroutines. */
381 {
382     unsigned Changes = 0;
383
384     /* Walk over the entries */
385     unsigned I = 0;
386     while (I < CS_GetEntryCount (S)) {
387
388         CodeEntry* X;
389         unsigned   IP;
390
391         /* Get next entry */
392         CodeEntry* E = CS_GetEntry (S, I);
393
394         /* Check for a call to one of the shift routine */
395         if (E->OPC == OP65_JSR                          &&
396             (strncmp (E->Arg, "shlax", 5) == 0  ||
397              strncmp (E->Arg, "aslax", 5) == 0)         &&
398             strlen (E->Arg) == 6                        &&
399             IsDigit (E->Arg[5])) {
400
401             /* Get number of shifts */
402             unsigned ShiftCount = (E->Arg[5] - '0');
403
404             /* Code is:
405              *
406              *      stx     tmp1
407              *      asl     a
408              *      rol     tmp1
409              *      (repeat ShiftCount-1 times)
410              *      ldx     tmp1
411              *
412              * which makes 4 + 3 * ShiftCount bytes, compared to the original
413              * 3 bytes for the subroutine call. However, in most cases, the
414              * final load of the X register gets merged with some other insn
415              * and replaces a txa, so for a shift count of 1, we get a factor
416              * of 200, which matches nicely the CodeSizeFactor enabled with -Oi
417              */
418             if (ShiftCount > 1 || S->CodeSizeFactor > 200) {
419                 unsigned Size = 4 + 3 * ShiftCount;
420                 if ((Size * 100 / 3) > S->CodeSizeFactor) {
421                     /* Not acceptable */
422                     goto NextEntry;
423                 }
424             }
425
426             /* Inline the code. Insertion point is behind the subroutine call */
427             IP = (I + 1);
428
429             /* stx tmp1 */
430             X = NewCodeEntry (OP65_STX, AM65_ZP, "tmp1", 0, E->LI);
431             CS_InsertEntry (S, X, IP++);
432
433             while (ShiftCount--) {
434                 /* asl a */
435                 X = NewCodeEntry (OP65_ASL, AM65_ACC, "a", 0, E->LI);
436                 CS_InsertEntry (S, X, IP++);
437
438                 /* rol tmp1 */
439                 X = NewCodeEntry (OP65_ROL, AM65_ZP, "tmp1", 0, E->LI);
440                 CS_InsertEntry (S, X, IP++);
441             }
442
443             /* ldx tmp1 */
444             X = NewCodeEntry (OP65_LDX, AM65_ZP, "tmp1", 0, E->LI);
445             CS_InsertEntry (S, X, IP++);
446
447             /* Remove the subroutine call */
448             CS_DelEntry (S, I);
449
450             /* Remember, we had changes */
451             ++Changes;
452         }
453
454 NextEntry:
455         /* Next entry */
456         ++I;
457
458     }
459
460     /* Return the number of changes made */
461     return Changes;
462 }
463
464
465
466 /*****************************************************************************/
467 /*                              Optimize loads                               */
468 /*****************************************************************************/
469
470
471
472 static unsigned OptLoad1 (CodeSeg* S)
473 /* Search for a call to ldaxysp where X is not used later and replace it by
474  * a load of just the A register.
475  */
476 {
477     unsigned I;
478     unsigned Changes = 0;
479
480     /* Generate register info */
481     CS_GenRegInfo (S);
482
483     /* Walk over the entries */
484     I = 0;
485     while (I < CS_GetEntryCount (S)) {
486
487         CodeEntry* E;
488
489         /* Get next entry */
490         E = CS_GetEntry (S, I);
491
492         /* Check for the sequence */
493         if (CE_IsCallTo (E, "ldaxysp")          &&
494             RegValIsKnown (E->RI->In.RegY)      &&
495             !RegXUsed (S, I+1)) {
496
497             CodeEntry* X;
498
499             /* Reload the Y register */
500             const char* Arg = MakeHexArg (E->RI->In.RegY - 1);
501             X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
502             CS_InsertEntry (S, X, I+1);
503
504             /* Load from stack */
505             X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, "sp", 0, E->LI);
506             CS_InsertEntry (S, X, I+2);
507
508             /* Now remove the call to the subroutine */
509             CS_DelEntry (S, I);
510
511             /* Remember, we had changes */
512             ++Changes;
513
514         }
515
516         /* Next entry */
517         ++I;
518
519     }
520
521     /* Free the register info */
522     CS_FreeRegInfo (S);
523
524     /* Return the number of changes made */
525     return Changes;
526 }
527
528
529
530 /*****************************************************************************/
531 /*                     Optimize stores through pointers                      */
532 /*****************************************************************************/
533
534
535
536 static unsigned OptPtrStore1Sub (CodeSeg* S, unsigned I, CodeEntry** const L)
537 /* Check if this is one of the allowed suboperation for OptPtrStore1 */
538 {
539     /* Check for a label attached to the entry */
540     if (CE_HasLabel (L[0])) {
541         return 0;
542     }
543
544     /* Check for single insn sub ops */
545     if (L[0]->OPC == OP65_AND                                           ||
546         L[0]->OPC == OP65_EOR                                           ||
547         L[0]->OPC == OP65_ORA                                           ||
548         (L[0]->OPC == OP65_JSR && strncmp (L[0]->Arg, "shlax", 5) == 0) ||
549         (L[0]->OPC == OP65_JSR && strncmp (L[0]->Arg, "shrax", 5) == 0)) {
550
551         /* One insn */
552         return 1;
553
554     } else if (L[0]->OPC == OP65_CLC                      &&
555                (L[1] = CS_GetNextEntry (S, I)) != 0       &&
556                L[1]->OPC == OP65_ADC                      &&
557                !CE_HasLabel (L[1])) {
558         return 2;
559     } else if (L[0]->OPC == OP65_SEC                      &&
560                (L[1] = CS_GetNextEntry (S, I)) != 0       &&
561                L[1]->OPC == OP65_SBC                      &&
562                !CE_HasLabel (L[1])) {
563         return 2;
564     }
565
566
567
568     /* Not found */
569     return 0;
570 }
571
572
573
574 static unsigned OptPtrStore1 (CodeSeg* S)
575 /* Search for the sequence:
576  *
577  *      jsr     pushax
578  *      ldy     xxx
579  *      jsr     ldauidx
580  *      subop
581  *      ldy     yyy
582  *      jsr     staspidx
583  *
584  * and replace it by:
585  *
586  *      sta     ptr1
587  *      stx     ptr1+1
588  *      ldy     xxx
589  *      ldx     #$00
590  *      lda     (ptr1),y
591  *      subop
592  *      ldy     yyy
593  *      sta     (ptr1),y
594  *
595  * In case a/x is loaded from the register bank before the pushax, we can even
596  * use the register bank instead of ptr1.
597  */
598 /*
599  *      jsr     pushax
600  *      ldy     xxx
601  *      jsr     ldauidx
602  *      ldx     #$00
603  *      lda     (zp),y
604  *      subop
605  *      ldy     yyy
606  *      sta     (zp),y
607  *      jsr     staspidx
608  */
609 {
610     unsigned Changes = 0;
611
612     /* Walk over the entries */
613     unsigned I = 0;
614     while (I < CS_GetEntryCount (S)) {
615
616         unsigned K;
617         CodeEntry* L[10];
618
619         /* Get next entry */
620         L[0] = CS_GetEntry (S, I);
621
622         /* Check for the sequence */
623         if (CE_IsCallTo (L[0], "pushax")            &&
624             CS_GetEntries (S, L+1, I+1, 3)          &&
625             L[1]->OPC == OP65_LDY                   &&
626             CE_IsConstImm (L[1])                    &&
627             !CE_HasLabel (L[1])                     &&
628             CE_IsCallTo (L[2], "ldauidx")           &&
629             !CE_HasLabel (L[2])                     &&
630             (K = OptPtrStore1Sub (S, I+3, L+3)) > 0 &&
631             CS_GetEntries (S, L+3+K, I+3+K, 2)      &&
632             L[3+K]->OPC == OP65_LDY                 &&
633             CE_IsConstImm (L[3+K])                  &&
634             !CE_HasLabel (L[3+K])                   &&
635             CE_IsCallTo (L[4+K], "staspidx")        &&
636             !CE_HasLabel (L[4+K])) {
637
638
639             const char* RegBank = 0;
640             const char* ZPLoc   = "ptr1";
641             CodeEntry* X;
642
643
644             /* Get the preceeding two instructions and check them. We check
645              * for:
646              *          lda     regbank+n
647              *          ldx     regbank+n+1
648              */
649             if (I > 1) {
650                 CodeEntry* P[2];
651                 P[0] = CS_GetEntry (S, I-2);
652                 P[1] = CS_GetEntry (S, I-1);
653                 if (P[0]->OPC == OP65_LDA &&
654                     P[0]->AM  == AM65_ZP  &&
655                     P[1]->OPC == OP65_LDX &&
656                     P[1]->AM  == AM65_ZP  &&
657                     !CE_HasLabel (P[1])   &&
658                     strncmp (P[0]->Arg, "regbank+", 8) == 0) {
659
660                     unsigned Len = strlen (P[0]->Arg);
661
662                     if (strncmp (P[0]->Arg, P[1]->Arg, Len) == 0 &&
663                         P[1]->Arg[Len+0] == '+'                  &&
664                         P[1]->Arg[Len+1] == '1'                  &&
665                         P[1]->Arg[Len+2] == '\0') {
666
667                         /* Ok, found. Use the name of the register bank */
668                         RegBank = ZPLoc = P[0]->Arg;
669                     }
670                 }
671             }
672
673             /* Insert the load via the zp pointer */
674             X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, L[3]->LI);
675             CS_InsertEntry (S, X, I+3);
676             X = NewCodeEntry (OP65_LDA, AM65_ZP_INDY, ZPLoc, 0, L[2]->LI);
677             CS_InsertEntry (S, X, I+4);
678
679             /* Insert the store through the zp pointer */
680             X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, ZPLoc, 0, L[3]->LI);
681             CS_InsertEntry (S, X, I+6+K);
682
683             /* Delete the old code */
684             CS_DelEntry (S, I+7+K);     /* jsr spaspidx */
685             CS_DelEntry (S, I+2);       /* jsr ldauidx */
686
687             /* Create and insert the stores into the zp pointer if needed */
688             if (RegBank == 0) {
689                 X = NewCodeEntry (OP65_STA, AM65_ZP, "ptr1", 0, L[0]->LI);
690                 CS_InsertEntry (S, X, I+1);
691                 X = NewCodeEntry (OP65_STX, AM65_ZP, "ptr1+1", 0, L[0]->LI);
692                 CS_InsertEntry (S, X, I+2);
693             }
694
695             /* Delete more old code. Do it here to keep a label attached to
696              * entry I in place.
697              */
698             CS_DelEntry (S, I);         /* jsr pushax */
699
700             /* Remember, we had changes */
701             ++Changes;
702
703         }
704
705         /* Next entry */
706         ++I;
707
708     }
709
710     /* Return the number of changes made */
711     return Changes;
712 }
713
714
715
716 static unsigned OptPtrStore2 (CodeSeg* S)
717 /* Search for the sequence:
718  *
719  *      lda     #<(label+0)
720  *      ldx     #>(label+0)
721  *      clc
722  *      adc     xxx
723  *      bcc     L
724  *      inx
725  * L:   jsr     pushax
726  *      ldx     #$00
727  *      lda     yyy
728  *      ldy     #$00
729  *      jsr     staspidx
730  *
731  * and replace it by:
732  *
733  *      ldy     xxx
734  *      ldx     #$00
735  *      lda     yyy
736  *      sta     label,y
737  */
738 {
739     unsigned Changes = 0;
740
741     /* Walk over the entries */
742     unsigned I = 0;
743     while (I < CS_GetEntryCount (S)) {
744
745         CodeEntry* L[11];
746         unsigned Len;
747
748         /* Get next entry */
749         L[0] = CS_GetEntry (S, I);
750
751         /* Check for the sequence */
752         if (L[0]->OPC == OP65_LDA                            &&
753             L[0]->AM == AM65_IMM                             &&
754             CS_GetEntries (S, L+1, I+1, 10)                  &&
755             L[1]->OPC == OP65_LDX                            &&
756             L[1]->AM == AM65_IMM                             &&
757             L[2]->OPC == OP65_CLC                            &&
758             L[3]->OPC == OP65_ADC                            &&
759             (L[3]->AM == AM65_ABS || L[3]->AM == AM65_ZP)    &&
760             (L[4]->OPC == OP65_BCC || L[4]->OPC == OP65_JCC) &&
761             L[4]->JumpTo != 0                                &&
762             L[4]->JumpTo->Owner == L[6]                      &&
763             L[5]->OPC == OP65_INX                            &&
764             CE_IsCallTo (L[6], "pushax")                     &&
765             L[7]->OPC == OP65_LDX                            &&
766             L[8]->OPC == OP65_LDA                            &&
767             L[9]->OPC == OP65_LDY                            &&
768             CE_IsKnownImm (L[9], 0)                          &&
769             CE_IsCallTo (L[10], "staspidx")                  &&
770             !CS_RangeHasLabel (S, I+1, 5)                    &&
771             !CS_RangeHasLabel (S, I+7, 4)                    &&
772             /* Check the label last because this is quite costly */
773             (Len = strlen (L[0]->Arg)) > 3                   &&
774             L[0]->Arg[0] == '<'                              &&
775             L[0]->Arg[1] == '('                              &&
776             strlen (L[1]->Arg) == Len                        &&
777             L[1]->Arg[0] == '>'                              &&
778             memcmp (L[0]->Arg+1, L[1]->Arg+1, Len-1) == 0) {
779
780             CodeEntry* X;
781             char* Label;
782
783             /* We will create all the new stuff behind the current one so
784              * we keep the line references.
785              */
786             X = NewCodeEntry (OP65_LDY, L[3]->AM, L[3]->Arg, 0, L[0]->LI);
787             CS_InsertEntry (S, X, I+11);
788
789             X = NewCodeEntry (OP65_LDX, L[7]->AM, L[7]->Arg, 0, L[7]->LI);
790             CS_InsertEntry (S, X, I+12);
791
792             X = NewCodeEntry (OP65_LDA, L[8]->AM, L[8]->Arg, 0, L[8]->LI);
793             CS_InsertEntry (S, X, I+13);
794
795             Label = memcpy (xmalloc (Len-2), L[0]->Arg+2, Len-3);
796             Label[Len-3] = '\0';
797             X = NewCodeEntry (OP65_STA, AM65_ABSY, Label, 0, L[10]->LI);
798             CS_InsertEntry (S, X, I+14);
799             xfree (Label);
800
801             /* Remove the old code */
802             CS_DelEntries (S, I, 11);
803
804             /* Remember, we had changes */
805             ++Changes;
806
807         }
808
809         /* Next entry */
810         ++I;
811
812     }
813
814     /* Return the number of changes made */
815     return Changes;
816 }
817
818
819
820 /*****************************************************************************/
821 /*                            Decouple operations                            */
822 /*****************************************************************************/
823
824
825
826 static unsigned OptDecouple (CodeSeg* S)
827 /* Decouple operations, that is, do the following replacements:
828  *
829  *   dex        -> ldx #imm
830  *   inx        -> ldx #imm
831  *   dey        -> ldy #imm
832  *   iny        -> ldy #imm
833  *   tax        -> ldx #imm
834  *   txa        -> lda #imm
835  *   tay        -> ldy #imm
836  *   tya        -> lda #imm
837  *   lda zp     -> lda #imm
838  *   ldx zp     -> ldx #imm
839  *   ldy zp     -> ldy #imm
840  *
841  * Provided that the register values are known of course.
842  */
843 {
844     unsigned Changes = 0;
845     unsigned I;
846
847     /* Generate register info for the following step */
848     CS_GenRegInfo (S);
849
850     /* Walk over the entries */
851     I = 0;
852     while (I < CS_GetEntryCount (S)) {
853
854         const char* Arg;
855
856         /* Get next entry and it's input register values */
857         CodeEntry* E = CS_GetEntry (S, I);
858         const RegContents* In = &E->RI->In;
859
860         /* Assume we have no replacement */
861         CodeEntry* X = 0;
862
863         /* Check the instruction */
864         switch (E->OPC) {
865
866             case OP65_DEA:
867                 if (RegValIsKnown (In->RegA)) {
868                     Arg = MakeHexArg ((In->RegA - 1) & 0xFF);
869                     X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
870                 }
871                 break;
872
873             case OP65_DEX:
874                 if (RegValIsKnown (In->RegX)) {
875                     Arg = MakeHexArg ((In->RegX - 1) & 0xFF);
876                     X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
877                 }
878                 break;
879
880             case OP65_DEY:
881                 if (RegValIsKnown (In->RegY)) {
882                     Arg = MakeHexArg ((In->RegY - 1) & 0xFF);
883                     X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
884                 }
885                 break;
886
887             case OP65_INA:
888                 if (RegValIsKnown (In->RegA)) {
889                     Arg = MakeHexArg ((In->RegA + 1) & 0xFF);
890                     X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
891                 }
892                 break;
893
894             case OP65_INX:
895                 if (RegValIsKnown (In->RegX)) {
896                     Arg = MakeHexArg ((In->RegX + 1) & 0xFF);
897                     X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
898                 }
899                 break;
900
901             case OP65_INY:
902                 if (RegValIsKnown (In->RegY)) {
903                     Arg = MakeHexArg ((In->RegY + 1) & 0xFF);
904                     X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
905                 }
906                 break;
907
908             case OP65_LDA:
909                 if (E->AM == AM65_ZP) {
910                     switch (GetKnownReg (E->Use & REG_ZP, In)) {
911                         case REG_TMP1:
912                             Arg = MakeHexArg (In->Tmp1);
913                             X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
914                             break;
915
916                         case REG_PTR1_LO:
917                             Arg = MakeHexArg (In->Ptr1Lo);
918                             X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
919                             break;
920
921                         case REG_PTR1_HI:
922                             Arg = MakeHexArg (In->Ptr1Hi);
923                             X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
924                             break;
925
926                         case REG_SREG_LO:
927                             Arg = MakeHexArg (In->SRegLo);
928                             X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
929                             break;
930
931                         case REG_SREG_HI:
932                             Arg = MakeHexArg (In->SRegHi);
933                             X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
934                             break;
935                     }
936                 }
937                 break;
938
939             case OP65_LDX:
940                 if (E->AM == AM65_ZP) {
941                     switch (GetKnownReg (E->Use & REG_ZP, In)) {
942                         case REG_TMP1:
943                             Arg = MakeHexArg (In->Tmp1);
944                             X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
945                             break;
946
947                         case REG_PTR1_LO:
948                             Arg = MakeHexArg (In->Ptr1Lo);
949                             X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
950                             break;
951
952                         case REG_PTR1_HI:
953                             Arg = MakeHexArg (In->Ptr1Hi);
954                             X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
955                             break;
956
957                         case REG_SREG_LO:
958                             Arg = MakeHexArg (In->SRegLo);
959                             X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
960                             break;
961
962                         case REG_SREG_HI:
963                             Arg = MakeHexArg (In->SRegHi);
964                             X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
965                             break;
966                     }
967                 }
968                 break;
969
970             case OP65_LDY:
971                 if (E->AM == AM65_ZP) {
972                     switch (GetKnownReg (E->Use, In)) {
973                         case REG_TMP1:
974                             Arg = MakeHexArg (In->Tmp1);
975                             X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
976                             break;
977
978                         case REG_PTR1_LO:
979                             Arg = MakeHexArg (In->Ptr1Lo);
980                             X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
981                             break;
982
983                         case REG_PTR1_HI:
984                             Arg = MakeHexArg (In->Ptr1Hi);
985                             X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
986                             break;
987
988                         case REG_SREG_LO:
989                             Arg = MakeHexArg (In->SRegLo);
990                             X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
991                             break;
992
993                         case REG_SREG_HI:
994                             Arg = MakeHexArg (In->SRegHi);
995                             X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
996                             break;
997                     }
998                 }
999                 break;
1000
1001             case OP65_TAX:
1002                 if (E->RI->In.RegA >= 0) {
1003                     Arg = MakeHexArg (In->RegA);
1004                     X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, E->LI);
1005                 }
1006                 break;
1007
1008             case OP65_TAY:
1009                 if (E->RI->In.RegA >= 0) {
1010                     Arg = MakeHexArg (In->RegA);
1011                     X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
1012                 }
1013                 break;
1014
1015             case OP65_TXA:
1016                 if (E->RI->In.RegX >= 0) {
1017                     Arg = MakeHexArg (In->RegX);
1018                     X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
1019                 }
1020                 break;
1021
1022             case OP65_TYA:
1023                 if (E->RI->In.RegY >= 0) {
1024                     Arg = MakeHexArg (In->RegY);
1025                     X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, E->LI);
1026                 }
1027                 break;
1028
1029             default:
1030                 /* Avoid gcc warnings */
1031                 break;
1032
1033         }
1034
1035         /* Insert the replacement if we have one */
1036         if (X) {
1037             CS_InsertEntry (S, X, I+1);
1038             CS_DelEntry (S, I);
1039             ++Changes;
1040         }
1041
1042         /* Next entry */
1043         ++I;
1044
1045     }
1046
1047     /* Free register info */
1048     CS_FreeRegInfo (S);
1049
1050     /* Return the number of changes made */
1051     return Changes;
1052 }
1053
1054
1055
1056 /*****************************************************************************/
1057 /*                        Optimize stack pointer ops                         */
1058 /*****************************************************************************/
1059
1060
1061
1062 static unsigned IsDecSP (const CodeEntry* E)
1063 /* Check if this is an insn that decrements the stack pointer. If so, return
1064  * the decrement. If not, return zero.
1065  * The function expects E to be a subroutine call.
1066  */
1067 {
1068     if (strncmp (E->Arg, "decsp", 5) == 0) {
1069         if (E->Arg[5] >= '1' && E->Arg[5] <= '8') {
1070             return (E->Arg[5] - '0');
1071         }
1072     } else if (strcmp (E->Arg, "subysp") == 0 && RegValIsKnown (E->RI->In.RegY)) {
1073         return E->RI->In.RegY;
1074     }
1075
1076     /* If we come here, it's not a decsp op */
1077     return 0;
1078 }
1079
1080
1081
1082 static unsigned OptStackPtrOps (CodeSeg* S)
1083 /* Merge adjacent calls to decsp into one. NOTE: This function won't merge all
1084  * known cases!
1085  */
1086 {
1087     unsigned Changes = 0;
1088     unsigned I;
1089
1090     /* Generate register info for the following step */
1091     CS_GenRegInfo (S);
1092
1093     /* Walk over the entries */
1094     I = 0;
1095     while (I < CS_GetEntryCount (S)) {
1096
1097         unsigned Dec1;
1098         unsigned Dec2;
1099         const CodeEntry* N;
1100
1101         /* Get the next entry */
1102         const CodeEntry* E = CS_GetEntry (S, I);
1103
1104         /* Check for decspn or subysp */
1105         if (E->OPC == OP65_JSR                          &&
1106             (Dec1 = IsDecSP (E)) > 0                    &&
1107             (N = CS_GetNextEntry (S, I)) != 0           &&
1108             (Dec2 = IsDecSP (N)) > 0                    &&
1109             (Dec1 += Dec2) <= 255                       &&
1110             !CE_HasLabel (N)) {
1111
1112             CodeEntry* X;
1113             char Buf[20];
1114
1115             /* We can combine the two */
1116             if (Dec1 <= 8) {
1117                 /* Insert a call to decsp */
1118                 xsprintf (Buf, sizeof (Buf), "decsp%u", Dec1);
1119                 X = NewCodeEntry (OP65_JSR, AM65_ABS, Buf, 0, N->LI);
1120                 CS_InsertEntry (S, X, I+2);
1121             } else {
1122                 /* Insert a call to subysp */
1123                 const char* Arg = MakeHexArg (Dec1);
1124                 X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, N->LI);
1125                 CS_InsertEntry (S, X, I+2);
1126                 X = NewCodeEntry (OP65_JSR, AM65_ABS, "subysp", 0, N->LI);
1127                 CS_InsertEntry (S, X, I+3);
1128             }
1129
1130             /* Delete the old code */
1131             CS_DelEntries (S, I, 2);
1132
1133             /* Regenerate register info */
1134             CS_GenRegInfo (S);
1135
1136             /* Remember we had changes */
1137             ++Changes;
1138
1139         } else {
1140
1141             /* Next entry */
1142             ++I;
1143         }
1144
1145     }
1146
1147     /* Free register info */
1148     CS_FreeRegInfo (S);
1149
1150     /* Return the number of changes made */
1151     return Changes;
1152 }
1153
1154
1155
1156 /*****************************************************************************/
1157 /*                              struct OptFunc                               */
1158 /*****************************************************************************/
1159
1160
1161
1162 typedef struct OptFunc OptFunc;
1163 struct OptFunc {
1164     unsigned       (*Func) (CodeSeg*);  /* Optimizer function */
1165     const char*    Name;                /* Name of the function/group */
1166     unsigned       CodeSizeFactor;      /* Code size factor for this opt func */
1167     unsigned long  TotalRuns;           /* Total number of runs */
1168     unsigned long  LastRuns;            /* Last number of runs */
1169     unsigned long  TotalChanges;        /* Total number of changes */
1170     unsigned long  LastChanges;         /* Last number of changes */
1171     char           Disabled;            /* True if function disabled */
1172 };
1173
1174
1175
1176 /*****************************************************************************/
1177 /*                                   Code                                    */
1178 /*****************************************************************************/
1179
1180
1181
1182 /* A list of all the function descriptions */
1183 static OptFunc DOpt65C02BitOps  = { Opt65C02BitOps,  "Opt65C02BitOps",   66, 0, 0, 0, 0, 0 };
1184 static OptFunc DOpt65C02Ind     = { Opt65C02Ind,     "Opt65C02Ind",     100, 0, 0, 0, 0, 0 };
1185 static OptFunc DOpt65C02Stores  = { Opt65C02Stores,  "Opt65C02Stores",  100, 0, 0, 0, 0, 0 };
1186 static OptFunc DOptAdd1         = { OptAdd1,         "OptAdd1",         125, 0, 0, 0, 0, 0 };
1187 static OptFunc DOptAdd2         = { OptAdd2,         "OptAdd2",         200, 0, 0, 0, 0, 0 };
1188 static OptFunc DOptAdd3         = { OptAdd3,         "OptAdd3",          65, 0, 0, 0, 0, 0 };
1189 static OptFunc DOptAdd4         = { OptAdd4,         "OptAdd4",          90, 0, 0, 0, 0, 0 };
1190 static OptFunc DOptAdd5         = { OptAdd5,         "OptAdd5",         100, 0, 0, 0, 0, 0 };
1191 static OptFunc DOptAdd6         = { OptAdd6,         "OptAdd6",          40, 0, 0, 0, 0, 0 };
1192 static OptFunc DOptBoolTrans    = { OptBoolTrans,    "OptBoolTrans",    100, 0, 0, 0, 0, 0 };
1193 static OptFunc DOptBranchDist   = { OptBranchDist,   "OptBranchDist",     0, 0, 0, 0, 0, 0 };
1194 static OptFunc DOptCmp1         = { OptCmp1,         "OptCmp1",          42, 0, 0, 0, 0, 0 };
1195 static OptFunc DOptCmp2         = { OptCmp2,         "OptCmp2",          85, 0, 0, 0, 0, 0 };
1196 static OptFunc DOptCmp3         = { OptCmp3,         "OptCmp3",          75, 0, 0, 0, 0, 0 };
1197 static OptFunc DOptCmp4         = { OptCmp4,         "OptCmp4",          75, 0, 0, 0, 0, 0 };
1198 static OptFunc DOptCmp5         = { OptCmp5,         "OptCmp5",         100, 0, 0, 0, 0, 0 };
1199 static OptFunc DOptCmp6         = { OptCmp6,         "OptCmp6",         100, 0, 0, 0, 0, 0 };
1200 static OptFunc DOptCmp7         = { OptCmp7,         "OptCmp7",          85, 0, 0, 0, 0, 0 };
1201 static OptFunc DOptCmp8         = { OptCmp8,         "OptCmp8",          50, 0, 0, 0, 0, 0 };
1202 static OptFunc DOptCmp9         = { OptCmp9,         "OptCmp9",          85, 0, 0, 0, 0, 0 };
1203 static OptFunc DOptCondBranches1= { OptCondBranches1,"OptCondBranches1", 80, 0, 0, 0, 0, 0 };
1204 static OptFunc DOptCondBranches2= { OptCondBranches2,"OptCondBranches2",  0, 0, 0, 0, 0, 0 };
1205 static OptFunc DOptDeadCode     = { OptDeadCode,     "OptDeadCode",     100, 0, 0, 0, 0, 0 };
1206 static OptFunc DOptDeadJumps    = { OptDeadJumps,    "OptDeadJumps",    100, 0, 0, 0, 0, 0 };
1207 static OptFunc DOptDecouple     = { OptDecouple,     "OptDecouple",     100, 0, 0, 0, 0, 0 };
1208 static OptFunc DOptDupLoads     = { OptDupLoads,     "OptDupLoads",       0, 0, 0, 0, 0, 0 };
1209 static OptFunc DOptIndLoads1    = { OptIndLoads1,    "OptIndLoads1",      0, 0, 0, 0, 0, 0 };
1210 static OptFunc DOptIndLoads2    = { OptIndLoads2,    "OptIndLoads2",      0, 0, 0, 0, 0, 0 };
1211 static OptFunc DOptJumpCascades = { OptJumpCascades, "OptJumpCascades", 100, 0, 0, 0, 0, 0 };
1212 static OptFunc DOptJumpTarget1  = { OptJumpTarget1,  "OptJumpTarget1",  100, 0, 0, 0, 0, 0 };
1213 static OptFunc DOptJumpTarget2  = { OptJumpTarget2,  "OptJumpTarget2",  100, 0, 0, 0, 0, 0 };
1214 static OptFunc DOptJumpTarget3  = { OptJumpTarget3,  "OptJumpTarget3",  100, 0, 0, 0, 0, 0 };
1215 static OptFunc DOptLoad1        = { OptLoad1,        "OptLoad1",        100, 0, 0, 0, 0, 0 };
1216 static OptFunc DOptRTS          = { OptRTS,          "OptRTS",          100, 0, 0, 0, 0, 0 };
1217 static OptFunc DOptRTSJumps1    = { OptRTSJumps1,    "OptRTSJumps1",    100, 0, 0, 0, 0, 0 };
1218 static OptFunc DOptRTSJumps2    = { OptRTSJumps2,    "OptRTSJumps2",    100, 0, 0, 0, 0, 0 };
1219 static OptFunc DOptNegA1        = { OptNegA1,        "OptNegA1",        100, 0, 0, 0, 0, 0 };
1220 static OptFunc DOptNegA2        = { OptNegA2,        "OptNegA2",        100, 0, 0, 0, 0, 0 };
1221 static OptFunc DOptNegAX1       = { OptNegAX1,       "OptNegAX1",       100, 0, 0, 0, 0, 0 };
1222 static OptFunc DOptNegAX2       = { OptNegAX2,       "OptNegAX2",       100, 0, 0, 0, 0, 0 };
1223 static OptFunc DOptNegAX3       = { OptNegAX3,       "OptNegAX3",       100, 0, 0, 0, 0, 0 };
1224 static OptFunc DOptNegAX4       = { OptNegAX4,       "OptNegAX4",       100, 0, 0, 0, 0, 0 };
1225 static OptFunc DOptPrecalc      = { OptPrecalc,      "OptPrecalc",      100, 0, 0, 0, 0, 0 };
1226 static OptFunc DOptPtrLoad1     = { OptPtrLoad1,     "OptPtrLoad1",     100, 0, 0, 0, 0, 0 };
1227 static OptFunc DOptPtrLoad2     = { OptPtrLoad2,     "OptPtrLoad2",     100, 0, 0, 0, 0, 0 };
1228 static OptFunc DOptPtrLoad3     = { OptPtrLoad3,     "OptPtrLoad3",     100, 0, 0, 0, 0, 0 };
1229 static OptFunc DOptPtrLoad4     = { OptPtrLoad4,     "OptPtrLoad4",     100, 0, 0, 0, 0, 0 };
1230 static OptFunc DOptPtrLoad5     = { OptPtrLoad5,     "OptPtrLoad5",      50, 0, 0, 0, 0, 0 };
1231 static OptFunc DOptPtrLoad6     = { OptPtrLoad6,     "OptPtrLoad6",      60, 0, 0, 0, 0, 0 };
1232 static OptFunc DOptPtrLoad7     = { OptPtrLoad7,     "OptPtrLoad7",     140, 0, 0, 0, 0, 0 };
1233 static OptFunc DOptPtrLoad11    = { OptPtrLoad11,    "OptPtrLoad11",     92, 0, 0, 0, 0, 0 };
1234 static OptFunc DOptPtrLoad12    = { OptPtrLoad12,    "OptPtrLoad12",    50, 0, 0, 0, 0, 0 };
1235 static OptFunc DOptPtrLoad13    = { OptPtrLoad13,    "OptPtrLoad13",    65, 0, 0, 0, 0, 0 };
1236 static OptFunc DOptPtrLoad14    = { OptPtrLoad14,    "OptPtrLoad14",    108, 0, 0, 0, 0, 0 };
1237 static OptFunc DOptPtrLoad15    = { OptPtrLoad15,    "OptPtrLoad15",     86, 0, 0, 0, 0, 0 };
1238 static OptFunc DOptPtrLoad16    = { OptPtrLoad16,    "OptPtrLoad16",    100, 0, 0, 0, 0, 0 };
1239 static OptFunc DOptPtrLoad17    = { OptPtrLoad17,    "OptPtrLoad17",    190, 0, 0, 0, 0, 0 };
1240 static OptFunc DOptPtrStore1    = { OptPtrStore1,    "OptPtrStore1",    100, 0, 0, 0, 0, 0 };
1241 static OptFunc DOptPtrStore2    = { OptPtrStore2,    "OptPtrStore2",     40, 0, 0, 0, 0, 0 };
1242 static OptFunc DOptPush1        = { OptPush1,        "OptPush1",         65, 0, 0, 0, 0, 0 };
1243 static OptFunc DOptPush2        = { OptPush2,        "OptPush2",         50, 0, 0, 0, 0, 0 };
1244 static OptFunc DOptPushPop      = { OptPushPop,      "OptPushPop",        0, 0, 0, 0, 0, 0 };
1245 static OptFunc DOptShift1       = { OptShift1,       "OptShift1",       100, 0, 0, 0, 0, 0 };
1246 static OptFunc DOptShift2       = { OptShift2,       "OptShift2",       100, 0, 0, 0, 0, 0 };
1247 static OptFunc DOptShift3       = { OptShift3,       "OptShift3",       110, 0, 0, 0, 0, 0 };
1248 static OptFunc DOptShift4       = { OptShift4,       "OptShift4",       200, 0, 0, 0, 0, 0 };
1249 static OptFunc DOptSize1        = { OptSize1,        "OptSize1",        100, 0, 0, 0, 0, 0 };
1250 static OptFunc DOptSize2        = { OptSize2,        "OptSize2",        100, 0, 0, 0, 0, 0 };
1251 static OptFunc DOptStackOps     = { OptStackOps,     "OptStackOps",     100, 0, 0, 0, 0, 0 };
1252 static OptFunc DOptStackPtrOps  = { OptStackPtrOps,  "OptStackPtrOps",   50, 0, 0, 0, 0, 0 };
1253 static OptFunc DOptStore1       = { OptStore1,       "OptStore1",        70, 0, 0, 0, 0, 0 };
1254 static OptFunc DOptStore2       = { OptStore2,       "OptStore2",       220, 0, 0, 0, 0, 0 };
1255 static OptFunc DOptStore3       = { OptStore3,       "OptStore3",       120, 0, 0, 0, 0, 0 };
1256 static OptFunc DOptStore4       = { OptStore4,       "OptStore4",        50, 0, 0, 0, 0, 0 };
1257 static OptFunc DOptStore5       = { OptStore5,       "OptStore5",       100, 0, 0, 0, 0, 0 };
1258 static OptFunc DOptStoreLoad    = { OptStoreLoad,    "OptStoreLoad",      0, 0, 0, 0, 0, 0 };
1259 static OptFunc DOptSub1         = { OptSub1,         "OptSub1",         100, 0, 0, 0, 0, 0 };
1260 static OptFunc DOptSub2         = { OptSub2,         "OptSub2",         100, 0, 0, 0, 0, 0 };
1261 static OptFunc DOptSub3         = { OptSub3,         "OptSub3",         100, 0, 0, 0, 0, 0 };
1262 static OptFunc DOptTest1        = { OptTest1,        "OptTest1",        100, 0, 0, 0, 0, 0 };
1263 static OptFunc DOptTransfers1   = { OptTransfers1,   "OptTransfers1",     0, 0, 0, 0, 0, 0 };
1264 static OptFunc DOptTransfers2   = { OptTransfers2,   "OptTransfers2",    60, 0, 0, 0, 0, 0 };
1265 static OptFunc DOptTransfers3   = { OptTransfers3,   "OptTransfers3",    65, 0, 0, 0, 0, 0 };
1266 static OptFunc DOptTransfers4   = { OptTransfers4,   "OptTransfers4",    65, 0, 0, 0, 0, 0 };
1267 static OptFunc DOptUnusedLoads  = { OptUnusedLoads,  "OptUnusedLoads",    0, 0, 0, 0, 0, 0 };
1268 static OptFunc DOptUnusedStores = { OptUnusedStores, "OptUnusedStores",   0, 0, 0, 0, 0, 0 };
1269
1270
1271 /* Table containing all the steps in alphabetical order */
1272 static OptFunc* OptFuncs[] = {
1273     &DOpt65C02BitOps,
1274     &DOpt65C02Ind,
1275     &DOpt65C02Stores,
1276     &DOptAdd1,
1277     &DOptAdd2,
1278     &DOptAdd3,
1279     &DOptAdd4,
1280     &DOptAdd5,
1281     &DOptAdd6,
1282     &DOptBoolTrans,
1283     &DOptBranchDist,
1284     &DOptCmp1,
1285     &DOptCmp2,
1286     &DOptCmp3,
1287     &DOptCmp4,
1288     &DOptCmp5,
1289     &DOptCmp6,
1290     &DOptCmp7,
1291     &DOptCmp8,
1292     &DOptCmp9,
1293     &DOptCondBranches1,
1294     &DOptCondBranches2,
1295     &DOptDeadCode,
1296     &DOptDeadJumps,
1297     &DOptDecouple,
1298     &DOptDupLoads,
1299     &DOptIndLoads1,
1300     &DOptIndLoads2,
1301     &DOptJumpCascades,
1302     &DOptJumpTarget1,
1303     &DOptJumpTarget2,
1304     &DOptJumpTarget3,
1305     &DOptLoad1,
1306     &DOptNegA1,
1307     &DOptNegA2,
1308     &DOptNegAX1,
1309     &DOptNegAX2,
1310     &DOptNegAX3,
1311     &DOptNegAX4,
1312     &DOptPrecalc,
1313     &DOptPtrLoad1,
1314     &DOptPtrLoad11,
1315     &DOptPtrLoad12,
1316     &DOptPtrLoad13,
1317     &DOptPtrLoad14,
1318     &DOptPtrLoad15,
1319     &DOptPtrLoad16,
1320     &DOptPtrLoad17,
1321     &DOptPtrLoad2,
1322     &DOptPtrLoad3,
1323     &DOptPtrLoad4,
1324     &DOptPtrLoad5,
1325     &DOptPtrLoad6,
1326     &DOptPtrLoad7,
1327     &DOptPtrStore1,
1328     &DOptPtrStore2,
1329     &DOptPush1,
1330     &DOptPush2,
1331     &DOptPushPop,
1332     &DOptRTS,
1333     &DOptRTSJumps1,
1334     &DOptRTSJumps2,
1335     &DOptShift1,
1336     &DOptShift2,
1337     &DOptShift3,
1338     &DOptShift4,
1339     &DOptSize1,
1340     &DOptSize2,
1341     &DOptStackOps,
1342     &DOptStackPtrOps,
1343     &DOptStore1,
1344     &DOptStore2,
1345     &DOptStore3,
1346     &DOptStore4,
1347     &DOptStore5,
1348     &DOptStoreLoad,
1349     &DOptSub1,
1350     &DOptSub2,
1351     &DOptSub3,
1352     &DOptTest1,
1353     &DOptTransfers1,
1354     &DOptTransfers2,
1355     &DOptTransfers3,
1356     &DOptTransfers4,
1357     &DOptUnusedLoads,
1358     &DOptUnusedStores,
1359 };
1360 #define OPTFUNC_COUNT  (sizeof(OptFuncs) / sizeof(OptFuncs[0]))
1361
1362
1363
1364 static int CmpOptStep (const void* Key, const void* Func)
1365 /* Compare function for bsearch */
1366 {
1367     return strcmp (Key, (*(const OptFunc**)Func)->Name);
1368 }
1369
1370
1371
1372 static OptFunc* FindOptFunc (const char* Name)
1373 /* Find an optimizer step by name in the table and return a pointer. Return
1374  * NULL if no such step is found.
1375  */
1376 {
1377     /* Search for the function in the list */
1378     OptFunc** O = bsearch (Name, OptFuncs, OPTFUNC_COUNT, sizeof (OptFuncs[0]), CmpOptStep);
1379     return O? *O : 0;
1380 }
1381
1382
1383
1384 static OptFunc* GetOptFunc (const char* Name)
1385 /* Find an optimizer step by name in the table and return a pointer. Print an
1386  * error and call AbEnd if not found.
1387  */
1388 {
1389     /* Search for the function in the list */
1390     OptFunc* F = FindOptFunc (Name);
1391     if (F == 0) {
1392         /* Not found */
1393         AbEnd ("Optimization step `%s' not found", Name);
1394     }
1395     return F;
1396 }
1397
1398
1399
1400 void DisableOpt (const char* Name)
1401 /* Disable the optimization with the given name */
1402 {
1403     if (strcmp (Name, "any") == 0) {
1404         unsigned I;
1405         for (I = 0; I < OPTFUNC_COUNT; ++I) {
1406             OptFuncs[I]->Disabled = 1;
1407         }
1408     } else {
1409         GetOptFunc(Name)->Disabled = 1;
1410     }
1411 }
1412
1413
1414
1415 void EnableOpt (const char* Name)
1416 /* Enable the optimization with the given name */
1417 {
1418     if (strcmp (Name, "any") == 0) {
1419         unsigned I;
1420         for (I = 0; I < OPTFUNC_COUNT; ++I) {
1421             OptFuncs[I]->Disabled = 0;
1422         }
1423     } else {
1424         GetOptFunc(Name)->Disabled = 0;
1425     }
1426 }
1427
1428
1429
1430 void ListOptSteps (FILE* F)
1431 /* List all optimization steps */
1432 {
1433     unsigned I;
1434     for (I = 0; I < OPTFUNC_COUNT; ++I) {
1435         fprintf (F, "%s\n", OptFuncs[I]->Name);
1436     }
1437 }
1438
1439
1440
1441 static void ReadOptStats (const char* Name)
1442 /* Read the optimizer statistics file */
1443 {
1444     char Buf [256];
1445     unsigned Lines;
1446
1447     /* Try to open the file */
1448     FILE* F = fopen (Name, "r");
1449     if (F == 0) {
1450         /* Ignore the error */
1451         return;
1452     }
1453
1454     /* Read and parse the lines */
1455     Lines = 0;
1456     while (fgets (Buf, sizeof (Buf), F) != 0) {
1457
1458         char* B;
1459         unsigned Len;
1460         OptFunc* Func;
1461
1462         /* Fields */
1463         char Name[32];
1464         unsigned long  TotalRuns;
1465         unsigned long  TotalChanges;
1466
1467         /* Count lines */
1468         ++Lines;
1469
1470         /* Remove trailing white space including the line terminator */
1471         B = Buf;
1472         Len = strlen (B);
1473         while (Len > 0 && IsSpace (B[Len-1])) {
1474             --Len;
1475         }
1476         B[Len] = '\0';
1477
1478         /* Remove leading whitespace */
1479         while (IsSpace (*B)) {
1480             ++B;
1481         }
1482
1483         /* Check for empty and comment lines */
1484         if (*B == '\0' || *B == ';' || *B == '#') {
1485             continue;
1486         }
1487
1488         /* Parse the line */
1489         if (sscanf (B, "%31s %lu %*u %lu %*u", Name, &TotalRuns, &TotalChanges) != 3) {
1490             /* Syntax error */
1491             continue;
1492         }
1493
1494         /* Search for the optimizer step. */
1495         Func = FindOptFunc (Name);
1496         if (Func == 0) {
1497             /* Not found */
1498             continue;
1499         }
1500
1501         /* Found the step, set the fields */
1502         Func->TotalRuns    = TotalRuns;
1503         Func->TotalChanges = TotalChanges;
1504
1505     }
1506
1507     /* Close the file, ignore errors here. */
1508     fclose (F);
1509 }
1510
1511
1512
1513 static void WriteOptStats (const char* Name)
1514 /* Write the optimizer statistics file */
1515 {
1516     unsigned I;
1517
1518     /* Try to open the file */
1519     FILE* F = fopen (Name, "w");
1520     if (F == 0) {
1521         /* Ignore the error */
1522         return;
1523     }
1524
1525     /* Write a header */
1526     fprintf (F,
1527              "; Optimizer               Total      Last       Total      Last\n"
1528              ";   Step                  Runs       Runs        Chg       Chg\n");
1529
1530
1531     /* Write the data */
1532     for (I = 0; I < OPTFUNC_COUNT; ++I) {
1533         const OptFunc* O = OptFuncs[I];
1534         fprintf (F,
1535                  "%-20s %10lu %10lu %10lu %10lu\n",
1536                  O->Name,
1537                  O->TotalRuns,
1538                  O->LastRuns,
1539                  O->TotalChanges,
1540                  O->LastChanges);
1541     }
1542
1543     /* Close the file, ignore errors here. */
1544     fclose (F);
1545 }
1546
1547
1548
1549 static unsigned RunOptFunc (CodeSeg* S, OptFunc* F, unsigned Max)
1550 /* Run one optimizer function Max times or until there are no more changes */
1551 {
1552     unsigned Changes, C;
1553
1554     /* Don't run the function if it is disabled or if it is prohibited by the
1555      * code size factor
1556      */
1557     if (F->Disabled || F->CodeSizeFactor > S->CodeSizeFactor) {
1558         return 0;
1559     }
1560
1561     /* Run this until there are no more changes */
1562     Changes = 0;
1563     do {
1564
1565         /* Run the function */
1566         C = F->Func (S);
1567         Changes += C;
1568
1569         /* Do statistics */
1570         ++F->TotalRuns;
1571         ++F->LastRuns;
1572         F->TotalChanges += C;
1573         F->LastChanges  += C;
1574
1575     } while (--Max && C > 0);
1576
1577     /* Return the number of changes */
1578     return Changes;
1579 }
1580
1581
1582
1583 static unsigned RunOptGroup1 (CodeSeg* S)
1584 /* Run the first group of optimization steps. These steps translate known
1585  * patterns emitted by the code generator into more optimal patterns. Order
1586  * of the steps is important, because some of the steps done earlier cover
1587  * the same patterns as later steps as subpatterns.
1588  */
1589 {
1590     unsigned Changes = 0;
1591
1592     Changes += RunOptFunc (S, &DOptStackPtrOps, 5);
1593     Changes += RunOptFunc (S, &DOptPtrStore1, 1);
1594     Changes += RunOptFunc (S, &DOptPtrStore2, 1);
1595     Changes += RunOptFunc (S, &DOptAdd3, 1);    /* Before OptPtrLoad5! */
1596     Changes += RunOptFunc (S, &DOptPtrLoad1, 1);
1597     Changes += RunOptFunc (S, &DOptPtrLoad2, 1);
1598     Changes += RunOptFunc (S, &DOptPtrLoad3, 1);
1599     Changes += RunOptFunc (S, &DOptPtrLoad4, 1);
1600     Changes += RunOptFunc (S, &DOptPtrLoad5, 1);
1601     Changes += RunOptFunc (S, &DOptPtrLoad6, 1);
1602     Changes += RunOptFunc (S, &DOptPtrLoad7, 1);
1603     Changes += RunOptFunc (S, &DOptPtrLoad11, 1);
1604     Changes += RunOptFunc (S, &DOptPtrLoad12, 1);
1605     Changes += RunOptFunc (S, &DOptPtrLoad13, 1);
1606     Changes += RunOptFunc (S, &DOptPtrLoad14, 1);
1607     Changes += RunOptFunc (S, &DOptPtrLoad15, 1);
1608     Changes += RunOptFunc (S, &DOptPtrLoad16, 1);
1609     Changes += RunOptFunc (S, &DOptPtrLoad17, 1);
1610     Changes += RunOptFunc (S, &DOptNegAX1, 1);
1611     Changes += RunOptFunc (S, &DOptNegAX2, 1);
1612     Changes += RunOptFunc (S, &DOptNegAX3, 1);
1613     Changes += RunOptFunc (S, &DOptNegAX4, 1);
1614     Changes += RunOptFunc (S, &DOptAdd1, 1);
1615     Changes += RunOptFunc (S, &DOptAdd2, 1);
1616     Changes += RunOptFunc (S, &DOptAdd4, 1);
1617     Changes += RunOptFunc (S, &DOptStore4, 1);
1618     Changes += RunOptFunc (S, &DOptStore5, 1);
1619     Changes += RunOptFunc (S, &DOptShift1, 1);
1620     Changes += RunOptFunc (S, &DOptShift2, 1);
1621     Changes += RunOptFunc (S, &DOptShift3, 1);
1622     Changes += RunOptFunc (S, &DOptShift4, 1);
1623     Changes += RunOptFunc (S, &DOptStore1, 1);
1624     Changes += RunOptFunc (S, &DOptStore2, 5);
1625     Changes += RunOptFunc (S, &DOptStore3, 5);
1626
1627     /* Return the number of changes */
1628     return Changes;
1629 }
1630
1631
1632
1633 static unsigned RunOptGroup2 (CodeSeg* S)
1634 /* Run one group of optimization steps. This step involves just decoupling
1635  * instructions by replacing them by instructions that do not depend on
1636  * previous instructions. This makes it easier to find instructions that
1637  * aren't used.
1638  */
1639 {
1640     unsigned Changes = 0;
1641
1642     Changes += RunOptFunc (S, &DOptDecouple, 1);
1643
1644     /* Return the number of changes */
1645     return Changes;
1646 }
1647
1648
1649
1650 static unsigned RunOptGroup3 (CodeSeg* S)
1651 /* Run one group of optimization steps. These steps depend on each other,
1652  * that means that one step may allow another step to do additional work,
1653  * so we will repeat the steps as long as we see any changes.
1654  */
1655 {
1656     unsigned Changes, C;
1657
1658     Changes = 0;
1659     do {
1660         C = 0;
1661
1662         C += RunOptFunc (S, &DOptNegA1, 1);
1663         C += RunOptFunc (S, &DOptNegA2, 1);
1664         C += RunOptFunc (S, &DOptSub1, 1);
1665         C += RunOptFunc (S, &DOptSub2, 1);
1666         C += RunOptFunc (S, &DOptSub3, 1);
1667         C += RunOptFunc (S, &DOptAdd5, 1);
1668         C += RunOptFunc (S, &DOptAdd6, 1);
1669         C += RunOptFunc (S, &DOptStackOps, 1);
1670         C += RunOptFunc (S, &DOptJumpCascades, 1);
1671         C += RunOptFunc (S, &DOptDeadJumps, 1);
1672         C += RunOptFunc (S, &DOptRTS, 1);
1673         C += RunOptFunc (S, &DOptDeadCode, 1);
1674         C += RunOptFunc (S, &DOptBoolTrans, 1);
1675         C += RunOptFunc (S, &DOptJumpTarget1, 1);
1676         C += RunOptFunc (S, &DOptJumpTarget2, 1);
1677         C += RunOptFunc (S, &DOptJumpTarget3, 1);
1678         C += RunOptFunc (S, &DOptCondBranches1, 1);
1679         C += RunOptFunc (S, &DOptCondBranches2, 1);
1680         C += RunOptFunc (S, &DOptRTSJumps1, 1);
1681         C += RunOptFunc (S, &DOptCmp1, 1);
1682         C += RunOptFunc (S, &DOptCmp2, 1);
1683         C += RunOptFunc (S, &DOptCmp3, 1);
1684         C += RunOptFunc (S, &DOptCmp4, 1);
1685         C += RunOptFunc (S, &DOptCmp5, 1);
1686         C += RunOptFunc (S, &DOptCmp6, 1);
1687         C += RunOptFunc (S, &DOptCmp7, 1);
1688         C += RunOptFunc (S, &DOptCmp8, 1);
1689         C += RunOptFunc (S, &DOptCmp9, 1);
1690         C += RunOptFunc (S, &DOptTest1, 1);
1691         C += RunOptFunc (S, &DOptLoad1, 1);
1692         C += RunOptFunc (S, &DOptUnusedLoads, 1);
1693         C += RunOptFunc (S, &DOptUnusedStores, 1);
1694         C += RunOptFunc (S, &DOptDupLoads, 1);
1695         C += RunOptFunc (S, &DOptStoreLoad, 1);
1696         C += RunOptFunc (S, &DOptTransfers1, 1);
1697         C += RunOptFunc (S, &DOptTransfers3, 1);
1698         C += RunOptFunc (S, &DOptTransfers4, 1);
1699         C += RunOptFunc (S, &DOptStore1, 1);
1700         C += RunOptFunc (S, &DOptStore5, 1);
1701         C += RunOptFunc (S, &DOptPushPop, 1);
1702         C += RunOptFunc (S, &DOptPrecalc, 1);
1703
1704         Changes += C;
1705
1706     } while (C);
1707
1708     /* Return the number of changes */
1709     return Changes;
1710 }
1711
1712
1713
1714 static unsigned RunOptGroup4 (CodeSeg* S)
1715 /* 65C02 specific optimizations. */
1716 {
1717     unsigned Changes = 0;
1718
1719     if (CPUIsets[CPU] & CPU_ISET_65SC02) {
1720         Changes += RunOptFunc (S, &DOpt65C02BitOps, 1);
1721         Changes += RunOptFunc (S, &DOpt65C02Ind, 1);
1722         Changes += RunOptFunc (S, &DOpt65C02Stores, 1);
1723         if (Changes) {
1724             /* The 65C02 replacement codes do often make the use of a register
1725              * value unnecessary, so if we have changes, run another load
1726              * removal pass.
1727              */
1728             Changes += RunOptFunc (S, &DOptUnusedLoads, 1);
1729         }
1730     }
1731
1732     /* Return the number of changes */
1733     return Changes;
1734 }
1735
1736
1737
1738 static unsigned RunOptGroup5 (CodeSeg* S)
1739 /* Run another round of pattern replacements. These are done late, since there
1740  * may be better replacements before.
1741  */
1742 {
1743     unsigned Changes = 0;
1744
1745     Changes += RunOptFunc (S, &DOptPush1, 1);
1746     Changes += RunOptFunc (S, &DOptPush2, 1);
1747     /* Repeat some of the other optimizations now */
1748     Changes += RunOptFunc (S, &DOptUnusedLoads, 1);
1749     Changes += RunOptFunc (S, &DOptTransfers2, 1);
1750
1751     /* Return the number of changes */
1752     return Changes;
1753 }
1754
1755
1756
1757 static unsigned RunOptGroup6 (CodeSeg* S)
1758 /* This one is quite special. It tries to replace "lda (sp),y" by "lda (sp,x)".
1759  * The latter is ony cycle slower, but if we're able to remove the necessary
1760  * load of the Y register, because X is zero anyway, we gain 1 cycle and
1761  * shorten the code by one (transfer) or two bytes (load). So what we do is
1762  * to replace the insns, remove unused loads, and then change back all insns
1763  * where Y is still zero (meaning that the load has not been removed).
1764  */
1765 {
1766     unsigned Changes = 0;
1767
1768     /* This group will only run for a standard 6502, because the 65C02 has a
1769      * better addressing mode that covers this case.
1770      */
1771     if ((CPUIsets[CPU] & CPU_ISET_65SC02) == 0) {
1772         Changes += RunOptFunc (S, &DOptIndLoads1, 1);
1773         Changes += RunOptFunc (S, &DOptUnusedLoads, 1);
1774         Changes += RunOptFunc (S, &DOptIndLoads2, 1);
1775     }
1776
1777     /* Return the number of changes */
1778     return Changes;
1779 }
1780
1781
1782
1783 static unsigned RunOptGroup7 (CodeSeg* S)
1784 /* The last group of optimization steps. Adjust branches, do size optimizations.
1785  */
1786 {
1787     unsigned Changes = 0;
1788     unsigned C;
1789
1790     /* Optimize for size, that is replace operations by shorter ones, even
1791      * if this does hinder further optimizations (no problem since we're
1792      * done soon).
1793      */
1794     C = RunOptFunc (S, &DOptSize1, 1);
1795     if (C) {
1796         Changes += C;
1797         /* Run some optimization passes again, since the size optimizations
1798          * may have opened new oportunities.
1799          */
1800         Changes += RunOptFunc (S, &DOptUnusedLoads, 1);
1801         Changes += RunOptFunc (S, &DOptUnusedStores, 1);
1802         Changes += RunOptFunc (S, &DOptJumpTarget1, 5);
1803         Changes += RunOptFunc (S, &DOptStore5, 1);
1804     }
1805
1806     C = RunOptFunc (S, &DOptSize2, 1);
1807     if (C) {
1808         Changes += C;
1809         /* Run some optimization passes again, since the size optimizations
1810          * may have opened new oportunities.
1811          */
1812         Changes += RunOptFunc (S, &DOptUnusedLoads, 1);
1813         Changes += RunOptFunc (S, &DOptJumpTarget1, 5);
1814         Changes += RunOptFunc (S, &DOptStore5, 1);
1815         Changes += RunOptFunc (S, &DOptTransfers3, 1);
1816     }
1817
1818     /* Adjust branch distances */
1819     Changes += RunOptFunc (S, &DOptBranchDist, 3);
1820
1821     /* Replace conditional branches to RTS. If we had changes, we must run dead
1822      * code elimination again, since the change may have introduced dead code.
1823      */
1824     C = RunOptFunc (S, &DOptRTSJumps2, 1);
1825     Changes += C;
1826     if (C) {
1827         Changes += RunOptFunc (S, &DOptDeadCode, 1);
1828     }
1829
1830     /* Return the number of changes */
1831     return Changes;
1832 }
1833
1834
1835
1836 void RunOpt (CodeSeg* S)
1837 /* Run the optimizer */
1838 {
1839     const char* StatFileName;
1840
1841     /* If we shouldn't run the optimizer, bail out */
1842     if (!S->Optimize) {
1843         return;
1844     }
1845
1846     /* Check if we are requested to write optimizer statistics */
1847     StatFileName = getenv ("CC65_OPTSTATS");
1848     if (StatFileName) {
1849         ReadOptStats (StatFileName);
1850     }
1851
1852     /* Print the name of the function we are working on */
1853     if (S->Func) {
1854         Print (stdout, 1, "Running optimizer for function `%s'\n", S->Func->Name);
1855     } else {
1856         Print (stdout, 1, "Running optimizer for global code segment\n");
1857     }
1858
1859     /* Run groups of optimizations */
1860     RunOptGroup1 (S);
1861     RunOptGroup2 (S);
1862     RunOptGroup3 (S);
1863     RunOptGroup4 (S);
1864     RunOptGroup5 (S);
1865     RunOptGroup6 (S);
1866     RunOptGroup7 (S);
1867
1868     /* Write statistics */
1869     if (StatFileName) {
1870         WriteOptStats (StatFileName);
1871     }
1872 }
1873
1874
1875