]> git.sur5r.net Git - cc65/blob - src/cc65/coptind.c
New optimization step
[cc65] / src / cc65 / coptind.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 coptind.c                                 */
4 /*                                                                           */
5 /*              Environment independent low level optimizations              */
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 /* common */
37 #include "cpu.h"
38
39 /* cc65 */
40 #include "codeent.h"
41 #include "coptind.h"
42 #include "codeinfo.h"
43 #include "codeopt.h"
44 #include "error.h"
45
46
47
48 /*****************************************************************************/
49 /*                             Helper functions                              */
50 /*****************************************************************************/
51
52
53
54 static int MemAccess (CodeSeg* S, unsigned From, unsigned To, const CodeEntry* N)
55 /* Checks a range of code entries if there are any memory accesses to N->Arg */
56 {
57     /* Get the length of the argument */
58     unsigned NLen = strlen (N->Arg);
59
60     /* What to check for? */
61     enum {
62         None    = 0x00,
63         Base    = 0x01,         /* Check for location without "+1" */
64         Word    = 0x02,         /* Check for location with "+1" added */
65     } What = None;
66
67
68     /* If the argument of N is a zero page location that ends with "+1", we
69      * must also check for word accesses to the location without +1.
70      */
71     if (N->AM == AM65_ZP && NLen > 2 && strcmp (N->Arg + NLen - 2, "+1") == 0) {
72         What |= Base;
73     }
74
75     /* If the argument is zero page indirect, we must also check for accesses
76      * to "arg+1"
77      */
78     if (N->AM == AM65_ZP_INDY || N->AM == AM65_ZPX_IND || N->AM == AM65_ZP_IND) {
79         What |= Word;
80     }
81
82     /* Walk over all code entries */
83     while (From <= To) {
84
85         /* Get the next entry */
86         CodeEntry* E = CS_GetEntry (S, From);
87
88         /* Check if there is an argument and if this argument equals Arg in
89          * some variants.
90          */
91         if (E->Arg[0] != '\0') {
92
93             unsigned ELen;
94
95             if (strcmp (E->Arg, N->Arg) == 0) {
96                 /* Found an access */
97                 return 1;
98             }
99
100             ELen = strlen (E->Arg);
101             if ((What & Base) != 0) {
102                 if (ELen == NLen - 2 && strncmp (E->Arg, N->Arg, NLen-2) == 0) {
103                     /* Found an access */
104                     return 1;
105                 }
106             }
107
108             if ((What & Word) != 0) {
109                 if (ELen == NLen + 2 && strncmp (E->Arg, N->Arg, NLen) == 0 &&
110                     E->Arg[NLen] == '+' && E->Arg[NLen+1] == '1') {
111                     /* Found an access */
112                     return 1;
113                 }
114             }
115         }
116
117         /* Next entry */
118         ++From;
119     }
120
121     /* Nothing found */
122     return 0;
123 }
124
125
126
127 static int GetBranchDist (CodeSeg* S, unsigned From, CodeEntry* To)
128 /* Get the branch distance between the two entries and return it. The distance
129  * will be negative for backward jumps and positive for forward jumps.
130  */
131 {
132     /* Get the index of the branch target */
133     unsigned TI = CS_GetEntryIndex (S, To);
134
135     /* Determine the branch distance */
136     int Distance = 0;
137     if (TI >= From) {
138         /* Forward branch, do not count the current insn */
139         unsigned J = From+1;
140         while (J < TI) {
141             CodeEntry* N = CS_GetEntry (S, J++);
142             Distance += N->Size;
143         }
144     } else {
145         /* Backward branch */
146         unsigned J = TI;
147         while (J < From) {
148             CodeEntry* N = CS_GetEntry (S, J++);
149             Distance -= N->Size;
150         }
151     }
152
153     /* Return the calculated distance */
154     return Distance;
155 }
156
157
158
159 static int IsShortDist (int Distance)
160 /* Return true if the given distance is a short branch distance */
161 {
162     return (Distance >= -125 && Distance <= 125);
163 }
164
165
166
167 static short ZPRegVal (unsigned short Use, const RegContents* RC)
168 /* Return the contents of the given zeropage register */
169 {
170     if ((Use & REG_TMP1) != 0) {
171         return RC->Tmp1;
172     } else if ((Use & REG_PTR1_LO) != 0) {
173         return RC->Ptr1Lo;
174     } else if ((Use & REG_PTR1_HI) != 0) {
175         return RC->Ptr1Hi;
176     } else if ((Use & REG_SREG_LO) != 0) {
177         return RC->SRegLo;
178     } else if ((Use & REG_SREG_HI) != 0) {
179         return RC->SRegHi;
180     } else {
181         return UNKNOWN_REGVAL;
182     }
183 }
184
185
186
187 static short RegVal (unsigned short Use, const RegContents* RC)
188 /* Return the contents of the given register */
189 {
190     if ((Use & REG_A) != 0) {
191         return RC->RegA;
192     } else if ((Use & REG_X) != 0) {
193         return RC->RegX;
194     } else if ((Use & REG_Y) != 0) {
195         return RC->RegY;
196     } else {
197         return ZPRegVal (Use, RC);
198     }
199 }
200
201
202
203 /*****************************************************************************/
204 /*                        Replace jumps to RTS by RTS                        */
205 /*****************************************************************************/
206
207
208
209 unsigned OptRTSJumps1 (CodeSeg* S)
210 /* Replace jumps to RTS by RTS */
211 {
212     unsigned Changes = 0;
213
214     /* Walk over all entries minus the last one */
215     unsigned I = 0;
216     while (I < CS_GetEntryCount (S)) {
217
218         /* Get the next entry */
219         CodeEntry* E = CS_GetEntry (S, I);
220
221         /* Check if it's an unconditional branch to a local target */
222         if ((E->Info & OF_UBRA) != 0            &&
223             E->JumpTo != 0                      &&
224             E->JumpTo->Owner->OPC == OP65_RTS) {
225
226             /* Insert an RTS instruction */
227             CodeEntry* X = NewCodeEntry (OP65_RTS, AM65_IMP, 0, 0, E->LI);
228             CS_InsertEntry (S, X, I+1);
229
230             /* Delete the jump */
231             CS_DelEntry (S, I);
232
233             /* Remember, we had changes */
234             ++Changes;
235
236         }
237
238         /* Next entry */
239         ++I;
240
241     }
242
243     /* Return the number of changes made */
244     return Changes;
245 }
246
247
248
249 unsigned OptRTSJumps2 (CodeSeg* S)
250 /* Replace long conditional jumps to RTS */
251 {
252     unsigned Changes = 0;
253
254     /* Walk over all entries minus the last one */
255     unsigned I = 0;
256     while (I < CS_GetEntryCount (S)) {
257
258         CodeEntry* N;
259
260         /* Get the next entry */
261         CodeEntry* E = CS_GetEntry (S, I);
262
263         /* Check if it's an unconditional branch to a local target */
264         if ((E->Info & OF_CBRA) != 0            &&   /* Conditional branch */
265             (E->Info & OF_LBRA) != 0            &&   /* Long branch */
266             E->JumpTo != 0                      &&   /* Local label */
267             E->JumpTo->Owner->OPC == OP65_RTS   &&   /* Target is an RTS */
268             (N = CS_GetNextEntry (S, I)) != 0) {     /* There is a next entry */
269
270             CodeEntry* X;
271             CodeLabel* LN;
272             opc_t      NewBranch;
273
274             /* We will create a jump around an RTS instead of the long branch */
275             X = NewCodeEntry (OP65_RTS, AM65_IMP, 0, 0, E->JumpTo->Owner->LI);
276             CS_InsertEntry (S, X, I+1);
277
278             /* Get the new branch opcode */
279             NewBranch = MakeShortBranch (GetInverseBranch (E->OPC));
280
281             /* Get the label attached to N, create a new one if needed */
282             LN = CS_GenLabel (S, N);
283
284             /* Generate the branch */
285             X = NewCodeEntry (NewBranch, AM65_BRA, LN->Name, LN, E->LI);
286             CS_InsertEntry (S, X, I+1);
287
288             /* Delete the long branch */
289             CS_DelEntry (S, I);
290
291             /* Remember, we had changes */
292             ++Changes;
293
294         }
295
296         /* Next entry */
297         ++I;
298
299     }
300
301     /* Return the number of changes made */
302     return Changes;
303 }
304
305
306
307 /*****************************************************************************/
308 /*                             Remove dead jumps                             */
309 /*****************************************************************************/
310
311
312
313 unsigned OptDeadJumps (CodeSeg* S)
314 /* Remove dead jumps (jumps to the next instruction) */
315 {
316     unsigned Changes = 0;
317
318     /* Walk over all entries minus the last one */
319     unsigned I = 0;
320     while (I < CS_GetEntryCount (S)) {
321
322         /* Get the next entry */
323         CodeEntry* E = CS_GetEntry (S, I);
324
325         /* Check if it's a branch, if it has a local target, and if the target
326          * is the next instruction.
327          */
328         if (E->AM == AM65_BRA                               &&
329             E->JumpTo                                       &&
330             E->JumpTo->Owner == CS_GetNextEntry (S, I)) {
331
332             /* Delete the dead jump */
333             CS_DelEntry (S, I);
334
335             /* Remember, we had changes */
336             ++Changes;
337
338         } else {
339
340             /* Next entry */
341             ++I;
342
343         }
344     }
345
346     /* Return the number of changes made */
347     return Changes;
348 }
349
350
351
352 /*****************************************************************************/
353 /*                             Remove dead code                              */
354 /*****************************************************************************/
355
356
357
358 unsigned OptDeadCode (CodeSeg* S)
359 /* Remove dead code (code that follows an unconditional jump or an rts/rti
360  * and has no label)
361  */
362 {
363     unsigned Changes = 0;
364
365     /* Walk over all entries */
366     unsigned I = 0;
367     while (I < CS_GetEntryCount (S)) {
368
369         CodeEntry* N;
370         CodeLabel* LN;
371
372         /* Get this entry */
373         CodeEntry* E = CS_GetEntry (S, I);
374
375         /* Check if it's an unconditional branch, and if the next entry has
376          * no labels attached, or if the label is just used so that the insn
377          * can jump to itself.
378          */
379         if ((E->Info & OF_DEAD) != 0                     &&     /* Dead code follows */
380             (N = CS_GetNextEntry (S, I)) != 0            &&     /* Has next entry */
381             (!CE_HasLabel (N)                        ||         /* Don't has a label */
382              ((N->Info & OF_UBRA) != 0          &&              /* Uncond branch */
383               (LN = N->JumpTo) != 0             &&              /* Jumps to known label */
384               LN->Owner == N                    &&              /* Attached to insn */
385               CL_GetRefCount (LN) == 1))) {                     /* Only reference */
386
387             /* Delete the next entry */
388             CS_DelEntry (S, I+1);
389
390             /* Remember, we had changes */
391             ++Changes;
392
393         } else {
394
395             /* Next entry */
396             ++I;
397
398         }
399     }
400
401     /* Return the number of changes made */
402     return Changes;
403 }
404
405
406
407 /*****************************************************************************/
408 /*                          Optimize jump cascades                           */
409 /*****************************************************************************/
410
411
412
413 unsigned OptJumpCascades (CodeSeg* S)
414 /* Optimize jump cascades (jumps to jumps). In such a case, the jump is
415  * replaced by a jump to the final location. This will in some cases produce
416  * worse code, because some jump targets are no longer reachable by short
417  * branches, but this is quite rare, so there are more advantages than
418  * disadvantages.
419  */
420 {
421     unsigned Changes = 0;
422
423     /* Walk over all entries */
424     unsigned I = 0;
425     while (I < CS_GetEntryCount (S)) {
426
427         CodeEntry* N;
428         CodeLabel* OldLabel;
429
430         /* Get this entry */
431         CodeEntry* E = CS_GetEntry (S, I);
432
433         /* Check if it's a branch, if it has a jump label, if this jump
434          * label is not attached to the instruction itself, and if the
435          * target instruction is itself a branch.
436          */
437         if ((E->Info & OF_BRA) != 0        &&
438             (OldLabel = E->JumpTo) != 0    &&
439             (N = OldLabel->Owner) != E     &&
440             (N->Info & OF_BRA) != 0) {
441
442             /* Check if we can use the final target label. This is the case,
443              * if the target branch is an absolut branch, or if it is a
444              * conditional branch checking the same condition as the first one.
445              */
446             if ((N->Info & OF_UBRA) != 0 ||
447                 ((E->Info & OF_CBRA) != 0 &&
448                  GetBranchCond (E->OPC)  == GetBranchCond (N->OPC))) {
449
450                 /* This is a jump cascade and we may jump to the final target,
451                  * provided that the other insn does not jump to itself. If
452                  * this is the case, we can also jump to ourselves, otherwise
453                  * insert a jump to the new instruction and remove the old one.
454                  */
455                 CodeEntry* X;
456                 CodeLabel* LN = N->JumpTo;
457
458                 if (LN != 0 && LN->Owner == N) {
459
460                     /* We found a jump to a jump to itself. Replace our jump
461                      * by a jump to itself.
462                      */
463                     CodeLabel* LE = CS_GenLabel (S, E);
464                     X = NewCodeEntry (E->OPC, E->AM, LE->Name, LE, E->LI);
465
466                 } else {
467
468                     /* Jump to the final jump target */
469                     X = NewCodeEntry (E->OPC, E->AM, N->Arg, N->JumpTo, E->LI);
470
471                 }
472
473                 /* Insert it behind E */
474                 CS_InsertEntry (S, X, I+1);
475
476                 /* Remove E */
477                 CS_DelEntry (S, I);
478
479                 /* Remember, we had changes */
480                 ++Changes;
481
482             /* Check if both are conditional branches, and the condition of
483              * the second is the inverse of that of the first. In this case,
484              * the second branch will never be taken, and we may jump directly
485              * to the instruction behind this one.
486              */
487             } else if ((E->Info & OF_CBRA) != 0 && (N->Info & OF_CBRA) != 0) {
488
489                 CodeEntry* X;   /* Instruction behind N */
490                 CodeLabel* LX;  /* Label attached to X */
491
492                 /* Get the branch conditions of both branches */
493                 bc_t BC1 = GetBranchCond (E->OPC);
494                 bc_t BC2 = GetBranchCond (N->OPC);
495
496                 /* Check the branch conditions */
497                 if (BC1 != GetInverseCond (BC2)) {
498                     /* Condition not met */
499                     goto NextEntry;
500                 }
501
502                 /* We may jump behind this conditional branch. Get the
503                  * pointer to the next instruction
504                  */
505                 if ((X = CS_GetNextEntry (S, CS_GetEntryIndex (S, N))) == 0) {
506                     /* N is the last entry, bail out */
507                     goto NextEntry;
508                 }
509
510                 /* Get the label attached to X, create a new one if needed */
511                 LX = CS_GenLabel (S, X);
512
513                 /* Move the reference from E to the new label */
514                 CS_MoveLabelRef (S, E, LX);
515
516                 /* Remember, we had changes */
517                 ++Changes;
518             }
519         }
520
521 NextEntry:
522         /* Next entry */
523         ++I;
524
525     }
526
527     /* Return the number of changes made */
528     return Changes;
529 }
530
531
532
533 /*****************************************************************************/
534 /*                             Optimize jsr/rts                              */
535 /*****************************************************************************/
536
537
538
539 unsigned OptRTS (CodeSeg* S)
540 /* Optimize subroutine calls followed by an RTS. The subroutine call will get
541  * replaced by a jump. Don't bother to delete the RTS if it does not have a
542  * label, the dead code elimination should take care of it.
543  */
544 {
545     unsigned Changes = 0;
546
547     /* Walk over all entries minus the last one */
548     unsigned I = 0;
549     while (I < CS_GetEntryCount (S)) {
550
551         CodeEntry* N;
552
553         /* Get this entry */
554         CodeEntry* E = CS_GetEntry (S, I);
555
556         /* Check if it's a subroutine call and if the following insn is RTS */
557         if (E->OPC == OP65_JSR                    &&
558             (N = CS_GetNextEntry (S, I)) != 0 &&
559             N->OPC == OP65_RTS) {
560
561             /* Change the jsr to a jmp and use the additional info for a jump */
562             E->AM = AM65_BRA;
563             CE_ReplaceOPC (E, OP65_JMP);
564
565             /* Remember, we had changes */
566             ++Changes;
567
568         }
569
570         /* Next entry */
571         ++I;
572
573     }
574
575     /* Return the number of changes made */
576     return Changes;
577 }
578
579
580
581 /*****************************************************************************/
582 /*                           Optimize jump targets                           */
583 /*****************************************************************************/
584
585
586
587 unsigned OptJumpTarget1 (CodeSeg* S)
588 /* If the instruction preceeding an unconditional branch is the same as the
589  * instruction preceeding the jump target, the jump target may be moved
590  * one entry back. This is a size optimization, since the instruction before
591  * the branch gets removed.
592  */
593 {
594     unsigned Changes = 0;
595     CodeEntry* E1;              /* Entry 1 */
596     CodeEntry* E2;              /* Entry 2 */
597     CodeEntry* T1;              /* Jump target entry 1 */
598     CodeLabel* TL1;             /* Target label 1 */
599
600     /* Walk over the entries */
601     unsigned I = 0;
602     while (I < CS_GetEntryCount (S)) {
603
604         /* Get next entry */
605         E2 = CS_GetNextEntry (S, I);
606
607         /* Check if we have a jump or branch without a label attached, and
608          * a jump target, which is not attached to the jump itself
609          */
610         if (E2 != 0                     &&
611             (E2->Info & OF_UBRA) != 0   &&
612             !CE_HasLabel (E2)           &&
613             E2->JumpTo                  &&
614             E2->JumpTo->Owner != E2) {
615
616             /* Get the entry preceeding the branch target */
617             T1 = CS_GetPrevEntry (S, CS_GetEntryIndex (S, E2->JumpTo->Owner));
618             if (T1 == 0) {
619                 /* There is no such entry */
620                 goto NextEntry;
621             }
622
623             /* The entry preceeding the branch target may not be the branch
624              * insn.
625              */
626             if (T1 == E2) {
627                 goto NextEntry;
628             }
629
630             /* Get the entry preceeding the jump */
631             E1 = CS_GetEntry (S, I);
632
633             /* Check if both preceeding instructions are identical */
634             if (!CodeEntriesAreEqual (E1, T1)) {
635                 /* Not equal, try next */
636                 goto NextEntry;
637             }
638
639             /* Get the label for the instruction preceeding the jump target.
640              * This routine will create a new label if the instruction does
641              * not already have one.
642              */
643             TL1 = CS_GenLabel (S, T1);
644
645             /* Change the jump target to point to this new label */
646             CS_MoveLabelRef (S, E2, TL1);
647
648             /* If the instruction preceeding the jump has labels attached,
649              * move references to this label to the new label.
650              */
651             if (CE_HasLabel (E1)) {
652                 CS_MoveLabels (S, E1, T1);
653             }
654
655             /* Remove the entry preceeding the jump */
656             CS_DelEntry (S, I);
657
658             /* Remember, we had changes */
659             ++Changes;
660
661         } else {
662 NextEntry:
663             /* Next entry */
664             ++I;
665         }
666     }
667
668     /* Return the number of changes made */
669     return Changes;
670 }
671
672
673
674 unsigned OptJumpTarget2 (CodeSeg* S)
675 /* If a bcs jumps to a sec insn or a bcc jumps to clc, skip this insn, since
676  * it's job is already done.
677  */
678 {
679     unsigned Changes = 0;
680
681     /* Walk over the entries */
682     unsigned I = 0;
683     while (I < CS_GetEntryCount (S)) {
684
685         /* OP that may be skipped */
686         opc_t OPC;
687
688         /* Jump target insn, old and new */
689         CodeEntry* T;
690         CodeEntry* N;
691
692         /* New jump label */
693         CodeLabel* L;
694
695         /* Get next entry */
696         CodeEntry* E = CS_GetEntry (S, I);
697
698         /* Check if this is a bcc insn */
699         if (E->OPC == OP65_BCC || E->OPC == OP65_JCC) {
700             OPC = OP65_CLC;
701         } else if (E->OPC == OP65_BCS || E->OPC == OP65_JCS) {
702             OPC = OP65_SEC;
703         } else {
704             /* Not what we're looking for */
705             goto NextEntry;
706         }
707
708         /* Must have a jump target */
709         if (E->JumpTo == 0) {
710             goto NextEntry;
711         }
712
713         /* Get the owner insn of the jump target and check if it's the one, we
714          * will skip if present.
715          */
716         T = E->JumpTo->Owner;
717         if (T->OPC != OPC) {
718             goto NextEntry;
719         }
720
721         /* Get the entry following the branch target */
722         N = CS_GetNextEntry (S, CS_GetEntryIndex (S, T));
723         if (N == 0) {
724             /* There is no such entry */
725             goto NextEntry;
726         }
727
728         /* Get the label for the instruction following the jump target.
729          * This routine will create a new label if the instruction does
730          * not already have one.
731          */
732         L = CS_GenLabel (S, N);
733
734         /* Change the jump target to point to this new label */
735         CS_MoveLabelRef (S, E, L);
736
737         /* Remember that we had changes */
738         ++Changes;
739
740 NextEntry:
741         /* Next entry */
742         ++I;
743     }
744
745     /* Return the number of changes made */
746     return Changes;
747 }
748
749
750
751 unsigned OptJumpTarget3 (CodeSeg* S)
752 /* Jumps to load instructions of a register, that do already have the matching
753  * register contents may skip the load instruction, since it's job is already
754  * done.
755  */
756 {
757     unsigned Changes = 0;
758     unsigned I;
759
760     /* Generate register info for this step */
761     CS_GenRegInfo (S);
762
763     /* Walk over the entries */
764     I = 0;
765     while (I < CS_GetEntryCount (S)) {
766
767         unsigned J, K;
768         CodeEntry* N;
769
770         /* New jump label */
771         CodeLabel* LN = 0;
772
773         /* Get next entry */
774         CodeEntry* E = CS_GetEntry (S, I);  
775
776         /* Check if this is a load insn with a label */
777         if ((E->Info & OF_LOAD) != 0            &&
778             CE_IsConstImm (E)                   &&
779             CE_HasLabel (E)                     &&
780             (N = CS_GetNextEntry (S, I)) != 0)    {
781
782             /* Walk over all insn that jump here */
783             for (J = 0; J < CE_GetLabelCount (E); ++J) {
784
785                 /* Get the label */
786                 CodeLabel* L = CE_GetLabel (E, J);
787                 for (K = 0; K < CL_GetRefCount (L); ++K) {
788
789                     /* Get the entry that jumps here */
790                     CodeEntry* Jump = CL_GetRef (L, K);
791
792                     /* Get the register info from this insn */
793                     short Val = RegVal (E->Chg, &Jump->RI->Out2);
794
795                     /* Check if the outgoing value is the one thatr's loaded */
796                     if (Val == (unsigned char) E->Num) {
797
798                         /* Ok, skip the insn. First, generate a label */
799                         if (LN == 0) {
800                             LN = CS_GenLabel (S, N);
801                         }
802
803                         /* Change the jump target to point to this new label */
804                         CS_MoveLabelRef (S, Jump, LN);
805
806                         /* Remember that we had changes */
807                         ++Changes;
808                     }
809                 }
810             }
811
812         }
813
814         /* Next entry */
815         ++I;
816     }
817
818     /* Free register info */
819     CS_FreeRegInfo (S);
820
821     /* Return the number of changes made */
822     return Changes;
823 }
824
825
826
827 /*****************************************************************************/
828 /*                       Optimize conditional branches                       */
829 /*****************************************************************************/
830
831
832
833 unsigned OptCondBranches1 (CodeSeg* S)
834 /* Performs several optimization steps:
835  *
836  *  - If an immidiate load of a register is followed by a conditional jump that
837  *    is never taken because the load of the register sets the flags in such a
838  *    manner, remove the conditional branch.
839  *  - If the conditional branch is always taken because of the register load,
840  *    replace it by a jmp.
841  *  - If a conditional branch jumps around an unconditional branch, remove the
842  *    conditional branch and make the jump a conditional branch with the
843  *    inverse condition of the first one.
844  */
845 {
846     unsigned Changes = 0;
847
848     /* Walk over the entries */
849     unsigned I = 0;
850     while (I < CS_GetEntryCount (S)) {
851
852         CodeEntry* N;
853         CodeLabel* L;
854
855         /* Get next entry */
856         CodeEntry* E = CS_GetEntry (S, I);
857
858         /* Check if it's a register load */
859         if ((E->Info & OF_LOAD) != 0              &&  /* It's a load instruction */
860             E->AM == AM65_IMM                     &&  /* ..with immidiate addressing */
861             (E->Flags & CEF_NUMARG) != 0          &&  /* ..and a numeric argument. */
862             (N = CS_GetNextEntry (S, I)) != 0     &&  /* There is a following entry */
863             (N->Info & OF_CBRA) != 0              &&  /* ..which is a conditional branch */
864             !CE_HasLabel (N)) {               /* ..and does not have a label */
865
866             /* Get the branch condition */
867             bc_t BC = GetBranchCond (N->OPC);
868
869             /* Check the argument against the branch condition */
870             if ((BC == BC_EQ && E->Num != 0)            ||
871                 (BC == BC_NE && E->Num == 0)            ||
872                 (BC == BC_PL && (E->Num & 0x80) != 0)   ||
873                 (BC == BC_MI && (E->Num & 0x80) == 0)) {
874
875                 /* Remove the conditional branch */
876                 CS_DelEntry (S, I+1);
877
878                 /* Remember, we had changes */
879                 ++Changes;
880
881             } else if ((BC == BC_EQ && E->Num == 0)             ||
882                        (BC == BC_NE && E->Num != 0)             ||
883                        (BC == BC_PL && (E->Num & 0x80) == 0)    ||
884                        (BC == BC_MI && (E->Num & 0x80) != 0)) {
885
886                 /* The branch is always taken, replace it by a jump */
887                 CE_ReplaceOPC (N, OP65_JMP);
888
889                 /* Remember, we had changes */
890                 ++Changes;
891             }
892
893         }
894
895         if ((E->Info & OF_CBRA) != 0              &&  /* It's a conditional branch */
896             (L = E->JumpTo) != 0                  &&  /* ..referencing a local label */
897             (N = CS_GetNextEntry (S, I)) != 0     &&  /* There is a following entry */
898             (N->Info & OF_UBRA) != 0              &&  /* ..which is an uncond branch, */
899             !CE_HasLabel (N)                      &&  /* ..has no label attached */
900             L->Owner == CS_GetNextEntry (S, I+1)) {/* ..and jump target follows */
901
902             /* Replace the jump by a conditional branch with the inverse branch
903              * condition than the branch around it.
904              */
905             CE_ReplaceOPC (N, GetInverseBranch (E->OPC));
906
907             /* Remove the conditional branch */
908             CS_DelEntry (S, I);
909
910             /* Remember, we had changes */
911             ++Changes;
912
913         }
914
915         /* Next entry */
916         ++I;
917
918     }
919
920     /* Return the number of changes made */
921     return Changes;
922 }
923
924
925
926 unsigned OptCondBranches2 (CodeSeg* S)
927 /* If on entry to a "rol a" instruction the accu is zero, and a beq/bne follows,
928  * we can remove the rol and branch on the state of the carry flag.
929  */
930 {
931     unsigned Changes = 0;
932     unsigned I;
933
934     /* Generate register info for this step */
935     CS_GenRegInfo (S);
936
937     /* Walk over the entries */
938     I = 0;
939     while (I < CS_GetEntryCount (S)) {
940
941         CodeEntry* N;
942
943         /* Get next entry */
944         CodeEntry* E = CS_GetEntry (S, I);
945
946         /* Check if it's a rol insn with A in accu and a branch follows */
947         if (E->OPC == OP65_ROL                  &&
948             E->AM == AM65_ACC                   &&
949             E->RI->In.RegA == 0                 &&
950             !CE_HasLabel (E)                    &&
951             (N = CS_GetNextEntry (S, I)) != 0   &&
952             (N->Info & OF_ZBRA) != 0            &&
953             !RegAUsed (S, I+1)) {
954
955             /* Replace the branch condition */
956             switch (GetBranchCond (N->OPC)) {
957                 case BC_EQ:     CE_ReplaceOPC (N, OP65_JCC); break;
958                 case BC_NE:     CE_ReplaceOPC (N, OP65_JCS); break;
959                 default:        Internal ("Unknown branch condition in OptCondBranches2");
960             }
961
962             /* Delete the rol insn */
963             CS_DelEntry (S, I);
964
965             /* Remember, we had changes */
966             ++Changes;
967         }
968
969         /* Next entry */
970         ++I;
971     }
972
973     /* Free register info */
974     CS_FreeRegInfo (S);
975
976     /* Return the number of changes made */
977     return Changes;
978 }
979
980
981
982 /*****************************************************************************/
983 /*                      Remove unused loads and stores                       */
984 /*****************************************************************************/
985
986
987
988 unsigned OptUnusedLoads (CodeSeg* S)
989 /* Remove loads of registers where the value loaded is not used later. */
990 {
991     unsigned Changes = 0;
992
993     /* Walk over the entries */
994     unsigned I = 0;
995     while (I < CS_GetEntryCount (S)) {
996
997         CodeEntry* N;
998
999         /* Get next entry */
1000         CodeEntry* E = CS_GetEntry (S, I);
1001
1002         /* Check if it's a register load or transfer insn */
1003         if ((E->Info & (OF_LOAD | OF_XFR | OF_REG_INCDEC)) != 0         &&
1004             (N = CS_GetNextEntry (S, I)) != 0                           &&
1005             !CE_UseLoadFlags (N)) {
1006
1007             /* Check which sort of load or transfer it is */
1008             unsigned R;
1009             switch (E->OPC) {
1010                 case OP65_DEA:
1011                 case OP65_INA:
1012                 case OP65_LDA:
1013                 case OP65_TXA:
1014                 case OP65_TYA:  R = REG_A;      break;
1015                 case OP65_DEX:
1016                 case OP65_INX:
1017                 case OP65_LDX:
1018                 case OP65_TAX:  R = REG_X;      break;
1019                 case OP65_DEY:
1020                 case OP65_INY:
1021                 case OP65_LDY:
1022                 case OP65_TAY:  R = REG_Y;      break;
1023                 default:        goto NextEntry;         /* OOPS */
1024             }
1025
1026             /* Get register usage and check if the register value is used later */
1027             if ((GetRegInfo (S, I+1, R) & R) == 0) {
1028
1029                 /* Register value is not used, remove the load */
1030                 CS_DelEntry (S, I);
1031
1032                 /* Remember, we had changes. Account the deleted entry in I. */
1033                 ++Changes;
1034                 --I;
1035
1036             }
1037         }
1038
1039 NextEntry:
1040         /* Next entry */
1041         ++I;
1042
1043     }
1044
1045     /* Return the number of changes made */
1046     return Changes;
1047 }
1048
1049
1050
1051 unsigned OptUnusedStores (CodeSeg* S)
1052 /* Remove stores into zero page registers that aren't used later */
1053 {
1054     unsigned Changes = 0;
1055
1056     /* Walk over the entries */
1057     unsigned I = 0;
1058     while (I < CS_GetEntryCount (S)) {
1059
1060         /* Get next entry */
1061         CodeEntry* E = CS_GetEntry (S, I);
1062
1063         /* Check if it's a register load or transfer insn */
1064         if ((E->Info & OF_STORE) != 0    &&
1065             E->AM == AM65_ZP             &&
1066             (E->Chg & REG_ZP) != 0) {
1067
1068             /* Check for the zero page location. We know that there cannot be
1069              * more than one zero page location involved in the store.
1070              */
1071             unsigned R = E->Chg & REG_ZP;
1072
1073             /* Get register usage and check if the register value is used later */
1074             if ((GetRegInfo (S, I+1, R) & R) == 0) {
1075
1076                 /* Register value is not used, remove the load */
1077                 CS_DelEntry (S, I);
1078
1079                 /* Remember, we had changes */
1080                 ++Changes;
1081
1082                 /* Continue with next insn */
1083                 continue;
1084             }
1085         }
1086
1087         /* Next entry */
1088         ++I;
1089
1090     }
1091
1092     /* Return the number of changes made */
1093     return Changes;
1094 }
1095
1096
1097
1098 unsigned OptDupLoads (CodeSeg* S)
1099 /* Remove loads of registers where the value loaded is already in the register. */
1100 {
1101     unsigned Changes = 0;
1102     unsigned I;
1103
1104     /* Generate register info for this step */
1105     CS_GenRegInfo (S);
1106
1107     /* Walk over the entries */
1108     I = 0;
1109     while (I < CS_GetEntryCount (S)) {
1110
1111         CodeEntry* N;
1112
1113         /* Get next entry */
1114         CodeEntry* E = CS_GetEntry (S, I);
1115
1116         /* Assume we won't delete the entry */
1117         int Delete = 0;
1118
1119         /* Get a pointer to the input registers of the insn */
1120         const RegContents* In  = &E->RI->In;
1121
1122         /* Handle the different instructions */
1123         switch (E->OPC) {
1124
1125             case OP65_LDA:
1126                 if (RegValIsKnown (In->RegA)          && /* Value of A is known */
1127                     CE_IsKnownImm (E, In->RegA)       && /* Value to be loaded is known */
1128                     (N = CS_GetNextEntry (S, I)) != 0 && /* There is a next entry */
1129                     !CE_UseLoadFlags (N)) {              /* Which does not use the flags */
1130                     Delete = 1;
1131                 }
1132                 break;
1133
1134             case OP65_LDX:
1135                 if (RegValIsKnown (In->RegX)          && /* Value of X is known */
1136                     CE_IsKnownImm (E, In->RegX)       && /* Value to be loaded is known */
1137                     (N = CS_GetNextEntry (S, I)) != 0 && /* There is a next entry */
1138                     !CE_UseLoadFlags (N)) {              /* Which does not use the flags */
1139                     Delete = 1;
1140                 }
1141                 break;
1142
1143             case OP65_LDY:
1144                 if (RegValIsKnown (In->RegY)          && /* Value of Y is known */
1145                     CE_IsKnownImm (E, In->RegY)       && /* Value to be loaded is known */
1146                     (N = CS_GetNextEntry (S, I)) != 0 && /* There is a next entry */
1147                     !CE_UseLoadFlags (N)) {              /* Which does not use the flags */
1148                     Delete = 1;
1149                 }
1150                 break;
1151
1152             case OP65_STA:
1153                 /* If we store into a known zero page location, and this
1154                  * location does already contain the value to be stored,
1155                  * remove the store.
1156                  */
1157                 if (RegValIsKnown (In->RegA)          && /* Value of A is known */
1158                     E->AM == AM65_ZP                  && /* Store into zp */
1159                     In->RegA == ZPRegVal (E->Chg, In)) { /* Value identical */
1160
1161                     Delete = 1;
1162                 }
1163                 break;
1164
1165             case OP65_STX:
1166                 /* If we store into a known zero page location, and this
1167                  * location does already contain the value to be stored,
1168                  * remove the store.
1169                  */
1170                 if (RegValIsKnown (In->RegX)          && /* Value of A is known */
1171                     E->AM == AM65_ZP                  && /* Store into zp */
1172                     In->RegX == ZPRegVal (E->Chg, In)) { /* Value identical */
1173
1174                     Delete = 1;
1175
1176                 /* If the value in the X register is known and the same as
1177                  * that in the A register, replace the store by a STA. The
1178                  * optimizer will then remove the load instruction for X
1179                  * later. STX does support the zeropage,y addressing mode,
1180                  * so be sure to check for that.
1181                  */
1182                 } else if (RegValIsKnown (In->RegX)   &&
1183                            In->RegX == In->RegA       &&
1184                            E->AM != AM65_ABSY         &&
1185                            E->AM != AM65_ZPY) {
1186                     /* Use the A register instead */
1187                     CE_ReplaceOPC (E, OP65_STA);
1188                 }
1189                 break;
1190
1191             case OP65_STY:
1192                 /* If we store into a known zero page location, and this
1193                  * location does already contain the value to be stored,
1194                  * remove the store.
1195                  */
1196                 if (RegValIsKnown (In->RegY)          && /* Value of Y is known */
1197                     E->AM == AM65_ZP                  && /* Store into zp */
1198                     In->RegY == ZPRegVal (E->Chg, In)) { /* Value identical */
1199
1200                     Delete = 1;
1201
1202                 /* If the value in the Y register is known and the same as
1203                  * that in the A register, replace the store by a STA. The
1204                  * optimizer will then remove the load instruction for Y
1205                  * later. If replacement by A is not possible try a
1206                  * replacement by X, but check for invalid addressing modes
1207                  * in this case.
1208                  */
1209                 } else if (RegValIsKnown (In->RegY)) {
1210                     if (In->RegY == In->RegA) {
1211                         CE_ReplaceOPC (E, OP65_STA);
1212                     } else if (In->RegY == In->RegX   &&
1213                                E->AM != AM65_ABSX     &&
1214                                E->AM != AM65_ZPX) {
1215                         CE_ReplaceOPC (E, OP65_STX);
1216                     }
1217                 }
1218                 break;
1219
1220             case OP65_STZ:
1221                 /* If we store into a known zero page location, and this
1222                  * location does already contain the value to be stored,
1223                  * remove the store.
1224                  */
1225                 if ((CPUIsets[CPU] & CPU_ISET_65SC02) != 0 && E->AM == AM65_ZP) {
1226                     if (ZPRegVal (E->Chg, In) == 0) {
1227                         Delete = 1;
1228                     }
1229                 }
1230                 break;
1231
1232             case OP65_TAX:
1233                 if (RegValIsKnown (In->RegA)          &&
1234                     In->RegA == In->RegX              &&
1235                     (N = CS_GetNextEntry (S, I)) != 0 &&
1236                     !CE_UseLoadFlags (N)) {
1237                     /* Value is identical and not followed by a branch */
1238                     Delete = 1;
1239                 }
1240                 break;
1241
1242             case OP65_TAY:
1243                 if (RegValIsKnown (In->RegA)            &&
1244                     In->RegA == In->RegY                &&
1245                     (N = CS_GetNextEntry (S, I)) != 0   &&
1246                     !CE_UseLoadFlags (N)) {
1247                     /* Value is identical and not followed by a branch */
1248                     Delete = 1;
1249                 }
1250                 break;
1251
1252             case OP65_TXA:
1253                 if (RegValIsKnown (In->RegX)            &&
1254                     In->RegX == In->RegA                &&
1255                     (N = CS_GetNextEntry (S, I)) != 0   &&
1256                     !CE_UseLoadFlags (N)) {
1257                     /* Value is identical and not followed by a branch */
1258                     Delete = 1;
1259                 }
1260                 break;
1261
1262             case OP65_TYA:
1263                 if (RegValIsKnown (In->RegY)            &&
1264                     In->RegY == In->RegA                &&
1265                     (N = CS_GetNextEntry (S, I)) != 0   &&
1266                     !CE_UseLoadFlags (N)) {
1267                     /* Value is identical and not followed by a branch */
1268                     Delete = 1;
1269                 }
1270                 break;
1271
1272             default:
1273                 break;
1274
1275         }
1276
1277         /* Delete the entry if requested */
1278         if (Delete) {
1279
1280             /* Register value is not used, remove the load */
1281             CS_DelEntry (S, I);
1282
1283             /* Remember, we had changes */
1284             ++Changes;
1285
1286         } else {
1287
1288             /* Next entry */
1289             ++I;
1290
1291         }
1292
1293     }
1294
1295     /* Free register info */
1296     CS_FreeRegInfo (S);
1297
1298     /* Return the number of changes made */
1299     return Changes;
1300 }
1301
1302
1303
1304 unsigned OptStoreLoad (CodeSeg* S)
1305 /* Remove a store followed by a load from the same location. */
1306 {
1307     unsigned Changes = 0;
1308
1309     /* Walk over the entries */
1310     unsigned I = 0;
1311     while (I < CS_GetEntryCount (S)) {
1312
1313         CodeEntry* N;
1314         CodeEntry* X;
1315
1316         /* Get next entry */
1317         CodeEntry* E = CS_GetEntry (S, I);
1318
1319         /* Check if it is a store instruction followed by a load from the
1320          * same address which is itself not followed by a conditional branch.
1321          */
1322         if ((E->Info & OF_STORE) != 0                       &&
1323             (N = CS_GetNextEntry (S, I)) != 0               &&
1324             !CE_HasLabel (N)                                &&
1325             E->AM == N->AM                                  &&
1326             ((E->OPC == OP65_STA && N->OPC == OP65_LDA) ||
1327              (E->OPC == OP65_STX && N->OPC == OP65_LDX) ||
1328              (E->OPC == OP65_STY && N->OPC == OP65_LDY))    &&
1329             strcmp (E->Arg, N->Arg) == 0                    &&
1330             (X = CS_GetNextEntry (S, I+1)) != 0             &&
1331             !CE_UseLoadFlags (X)) {
1332
1333             /* Register has already the correct value, remove the load */
1334             CS_DelEntry (S, I+1);
1335
1336             /* Remember, we had changes */
1337             ++Changes;
1338
1339         }
1340
1341         /* Next entry */
1342         ++I;
1343
1344     }
1345
1346     /* Return the number of changes made */
1347     return Changes;
1348 }
1349
1350
1351
1352 unsigned OptTransfers1 (CodeSeg* S)
1353 /* Remove transfers from one register to another and back */
1354 {
1355     unsigned Changes = 0;
1356
1357     /* Walk over the entries */
1358     unsigned I = 0;
1359     while (I < CS_GetEntryCount (S)) {
1360
1361         CodeEntry* N;
1362         CodeEntry* X;
1363         CodeEntry* P;
1364
1365         /* Get next entry */
1366         CodeEntry* E = CS_GetEntry (S, I);
1367
1368         /* Check if we have two transfer instructions */
1369         if ((E->Info & OF_XFR) != 0                 &&
1370             (N = CS_GetNextEntry (S, I)) != 0       &&
1371             !CE_HasLabel (N)                        &&
1372             (N->Info & OF_XFR) != 0) {
1373
1374             /* Check if it's a transfer and back */
1375             if ((E->OPC == OP65_TAX && N->OPC == OP65_TXA && !RegXUsed (S, I+2)) ||
1376                 (E->OPC == OP65_TAY && N->OPC == OP65_TYA && !RegYUsed (S, I+2)) ||
1377                 (E->OPC == OP65_TXA && N->OPC == OP65_TAX && !RegAUsed (S, I+2)) ||
1378                 (E->OPC == OP65_TYA && N->OPC == OP65_TAY && !RegAUsed (S, I+2))) {
1379
1380                 /* If the next insn is a conditional branch, check if the insn
1381                  * preceeding the first xfr will set the flags right, otherwise we
1382                  * may not remove the sequence.
1383                  */
1384                 if ((X = CS_GetNextEntry (S, I+1)) == 0) {
1385                     goto NextEntry;
1386                 }
1387                 if (CE_UseLoadFlags (X)) {
1388                     if (I == 0) {
1389                         /* No preceeding entry */
1390                         goto NextEntry;
1391                     }
1392                     P = CS_GetEntry (S, I-1);
1393                     if ((P->Info & OF_SETF) == 0) {
1394                         /* Does not set the flags */
1395                         goto NextEntry;
1396                     }
1397                 }
1398
1399                 /* Remove both transfers */
1400                 CS_DelEntry (S, I+1);
1401                 CS_DelEntry (S, I);
1402
1403                 /* Remember, we had changes */
1404                 ++Changes;
1405             }
1406         }
1407
1408 NextEntry:
1409         /* Next entry */
1410         ++I;
1411
1412     }
1413
1414     /* Return the number of changes made */
1415     return Changes;
1416 }
1417
1418
1419
1420 unsigned OptTransfers2 (CodeSeg* S)
1421 /* Replace loads followed by a register transfer by a load with the second
1422  * register if possible.
1423  */
1424 {
1425     unsigned Changes = 0;
1426
1427     /* Walk over the entries */
1428     unsigned I = 0;
1429     while (I < CS_GetEntryCount (S)) {
1430
1431         CodeEntry* N;
1432
1433         /* Get next entry */
1434         CodeEntry* E = CS_GetEntry (S, I);
1435
1436         /* Check if we have a load followed by a transfer where the loaded
1437          * register is not used later.
1438          */
1439         if ((E->Info & OF_LOAD) != 0                &&
1440             (N = CS_GetNextEntry (S, I)) != 0       &&
1441             !CE_HasLabel (N)                        &&
1442             (N->Info & OF_XFR) != 0                 &&
1443             GetRegInfo (S, I+2, E->Chg) != E->Chg) {
1444
1445             CodeEntry* X = 0;
1446
1447             if (E->OPC == OP65_LDA && N->OPC == OP65_TAX) {
1448                 /* LDA/TAX - check for the right addressing modes */
1449                 if (E->AM == AM65_IMM ||
1450                     E->AM == AM65_ZP  ||
1451                     E->AM == AM65_ABS ||
1452                     E->AM == AM65_ABSY) {
1453                     /* Replace */
1454                     X = NewCodeEntry (OP65_LDX, E->AM, E->Arg, 0, N->LI);
1455                 }
1456             } else if (E->OPC == OP65_LDA && N->OPC == OP65_TAY) {
1457                 /* LDA/TAY - check for the right addressing modes */
1458                 if (E->AM == AM65_IMM ||
1459                     E->AM == AM65_ZP  ||
1460                     E->AM == AM65_ZPX ||
1461                     E->AM == AM65_ABS ||
1462                     E->AM == AM65_ABSX) {
1463                     /* Replace */
1464                     X = NewCodeEntry (OP65_LDY, E->AM, E->Arg, 0, N->LI);
1465                 }
1466             } else if (E->OPC == OP65_LDY && N->OPC == OP65_TYA) {
1467                 /* LDY/TYA. LDA supports all addressing modes LDY does */
1468                 X = NewCodeEntry (OP65_LDA, E->AM, E->Arg, 0, N->LI);
1469             } else if (E->OPC == OP65_LDX && N->OPC == OP65_TXA) {
1470                 /* LDX/TXA. LDA doesn't support zp,y, so we must map it to
1471                  * abs,y instead.
1472                  */
1473                 am_t AM = (E->AM == AM65_ZPY)? AM65_ABSY : E->AM;
1474                 X = NewCodeEntry (OP65_LDA, AM, E->Arg, 0, N->LI);
1475             }
1476
1477             /* If we have a load entry, add it and remove the old stuff */
1478             if (X) {
1479                 CS_InsertEntry (S, X, I+2);
1480                 CS_DelEntries (S, I, 2);
1481                 ++Changes;
1482                 --I;    /* Correct for one entry less */
1483             }
1484         }
1485
1486         /* Next entry */
1487         ++I;
1488     }
1489
1490     /* Return the number of changes made */
1491     return Changes;
1492 }
1493
1494
1495
1496 unsigned OptTransfers3 (CodeSeg* S)
1497 /* Replace a register transfer followed by a store of the second register by a
1498  * store of the first register if this is possible.
1499  */
1500 {
1501     unsigned Changes      = 0;
1502     unsigned UsedRegs     = REG_NONE;   /* Track used registers */
1503     unsigned Xfer         = 0;          /* Index of transfer insn */
1504     unsigned Store        = 0;          /* Index of store insn */
1505     CodeEntry* XferEntry  = 0;          /* Pointer to xfer insn */
1506     CodeEntry* StoreEntry = 0;          /* Pointer to store insn */
1507
1508     enum {
1509         Initialize,
1510         Search,
1511         FoundXfer,
1512         FoundStore
1513     } State = Initialize;
1514
1515     /* Walk over the entries. Look for a xfer instruction that is followed by
1516      * a store later, where the value of the register is not used later.
1517      */
1518     unsigned I = 0;
1519     while (I < CS_GetEntryCount (S)) {
1520
1521         /* Get next entry */
1522         CodeEntry* E = CS_GetEntry (S, I);
1523
1524         switch (State) {
1525
1526             case Initialize:
1527                 /* Clear the list of used registers */
1528                 UsedRegs = REG_NONE;
1529                 /* FALLTHROUGH */
1530
1531             case Search:
1532                 if (E->Info & OF_XFR) {
1533                     /* Found start of sequence */
1534                     Xfer = I;
1535                     XferEntry = E;
1536                     State = FoundXfer;
1537                 }
1538                 break;
1539
1540             case FoundXfer:
1541                 /* If we find a conditional jump, abort the sequence, since
1542                  * handling them makes things really complicated.
1543                  */
1544                 if (E->Info & OF_CBRA) {
1545
1546                     /* Switch back to searching */
1547                     I = Xfer;
1548                     State = Initialize;
1549
1550                 /* Does this insn use the target register of the transfer? */
1551                 } else if ((E->Use & XferEntry->Chg) != 0) {
1552
1553                     /* It it's a store instruction, and the block is a basic
1554                      * block, proceed. Otherwise restart
1555                      */
1556                     if ((E->Info & OF_STORE) != 0       &&
1557                         CS_IsBasicBlock (S, Xfer, I)) {
1558                         Store = I;
1559                         StoreEntry = E;
1560                         State = FoundStore;
1561                     } else {
1562                         I = Xfer;
1563                         State = Initialize;
1564                     }
1565
1566                 /* Does this insn change the target register of the transfer? */
1567                 } else if (E->Chg & XferEntry->Chg) {
1568
1569                     /* We *may* add code here to remove the transfer, but I'm
1570                      * currently not sure about the consequences, so I won't
1571                      * do that and bail out instead.
1572                      */
1573                     I = Xfer;
1574                     State = Initialize;
1575
1576                 /* Does this insn have a label? */
1577                 } else if (CE_HasLabel (E)) {
1578
1579                     /* Too complex to handle - bail out */
1580                     I = Xfer;
1581                     State = Initialize;
1582
1583                 } else {
1584                     /* Track used registers */
1585                     UsedRegs |= E->Use;
1586                 }
1587                 break;
1588
1589             case FoundStore:
1590                 /* We are at the instruction behind the store. If the register
1591                  * isn't used later, and we have an address mode match, we can
1592                  * replace the transfer by a store and remove the store here.
1593                  */
1594                 if ((GetRegInfo (S, I, XferEntry->Chg) & XferEntry->Chg) == 0   &&
1595                     (StoreEntry->AM == AM65_ABS         ||
1596                      StoreEntry->AM == AM65_ZP)                                 &&
1597                     (StoreEntry->AM != AM65_ZP ||
1598                      (StoreEntry->Chg & UsedRegs) == 0)                         &&
1599                     !MemAccess (S, Xfer+1, Store-1, StoreEntry)) {
1600
1601                     /* Generate the replacement store insn */
1602                     CodeEntry* X = 0;
1603                     switch (XferEntry->OPC) {
1604
1605                         case OP65_TXA:
1606                             X = NewCodeEntry (OP65_STX,
1607                                               StoreEntry->AM,
1608                                               StoreEntry->Arg,
1609                                               0,
1610                                               StoreEntry->LI);
1611                             break;
1612
1613                         case OP65_TAX:
1614                             X = NewCodeEntry (OP65_STA,
1615                                               StoreEntry->AM,
1616                                               StoreEntry->Arg,
1617                                               0,
1618                                               StoreEntry->LI);
1619                             break;
1620
1621                         case OP65_TYA:
1622                             X = NewCodeEntry (OP65_STY,
1623                                               StoreEntry->AM,
1624                                               StoreEntry->Arg,
1625                                               0,
1626                                               StoreEntry->LI);
1627                             break;
1628
1629                         case OP65_TAY:
1630                             X = NewCodeEntry (OP65_STA,
1631                                               StoreEntry->AM,
1632                                               StoreEntry->Arg,
1633                                               0,
1634                                               StoreEntry->LI);
1635                             break;
1636
1637                         default:
1638                             break;
1639                     }
1640
1641                     /* If we have a replacement store, change the code */
1642                     if (X) {
1643                         /* Insert after the xfer insn */
1644                         CS_InsertEntry (S, X, Xfer+1);
1645
1646                         /* Remove the xfer instead */
1647                         CS_DelEntry (S, Xfer);
1648
1649                         /* Remove the final store */
1650                         CS_DelEntry (S, Store);
1651
1652                         /* Correct I so we continue with the next insn */
1653                         I -= 2;
1654
1655                         /* Remember we had changes */
1656                         ++Changes;
1657                     } else {
1658                         /* Restart after last xfer insn */
1659                         I = Xfer;
1660                     }
1661                 } else {
1662                     /* Restart after last xfer insn */
1663                     I = Xfer;
1664                 }
1665                 State = Initialize;
1666                 break;
1667
1668         }
1669
1670         /* Next entry */
1671         ++I;
1672     }
1673
1674     /* Return the number of changes made */
1675     return Changes;
1676 }
1677
1678
1679
1680 unsigned OptTransfers4 (CodeSeg* S)
1681 /* Replace a load of a register followed by a transfer insn of the same register
1682  * by a load of the second register if possible.
1683  */
1684 {
1685     unsigned Changes      = 0;
1686     unsigned Load         = 0;  /* Index of load insn */
1687     unsigned Xfer         = 0;  /* Index of transfer insn */
1688     CodeEntry* LoadEntry  = 0;  /* Pointer to load insn */
1689     CodeEntry* XferEntry  = 0;  /* Pointer to xfer insn */
1690
1691     enum {
1692         Search,
1693         FoundLoad,
1694         FoundXfer
1695     } State = Search;
1696
1697     /* Walk over the entries. Look for a load instruction that is followed by
1698      * a load later.
1699      */
1700     unsigned I = 0;
1701     while (I < CS_GetEntryCount (S)) {
1702
1703         /* Get next entry */
1704         CodeEntry* E = CS_GetEntry (S, I);
1705
1706         switch (State) {
1707
1708             case Search:
1709                 if (E->Info & OF_LOAD) {
1710                     /* Found start of sequence */
1711                     Load = I;
1712                     LoadEntry = E;
1713                     State = FoundLoad;
1714                 }
1715                 break;
1716
1717             case FoundLoad:
1718                 /* If we find a conditional jump, abort the sequence, since
1719                  * handling them makes things really complicated.
1720                  */
1721                 if (E->Info & OF_CBRA) {
1722
1723                     /* Switch back to searching */
1724                     I = Load;
1725                     State = Search;
1726
1727                 /* Does this insn use the target register of the load? */
1728                 } else if ((E->Use & LoadEntry->Chg) != 0) {
1729
1730                     /* It it's a xfer instruction, and the block is a basic
1731                      * block, proceed. Otherwise restart
1732                      */
1733                     if ((E->Info & OF_XFR) != 0       &&
1734                         CS_IsBasicBlock (S, Load, I)) {
1735                         Xfer = I;
1736                         XferEntry = E;
1737                         State = FoundXfer;
1738                     } else {
1739                         I = Load;
1740                         State = Search;
1741                     }
1742
1743                 /* Does this insn change the target register of the load? */
1744                 } else if (E->Chg & LoadEntry->Chg) {
1745
1746                     /* We *may* add code here to remove the load, but I'm
1747                      * currently not sure about the consequences, so I won't
1748                      * do that and bail out instead.
1749                      */
1750                     I = Load;
1751                     State = Search;
1752                 }
1753                 break;
1754
1755             case FoundXfer:
1756                 /* We are at the instruction behind the xfer. If the register
1757                  * isn't used later, and we have an address mode match, we can
1758                  * replace the transfer by a load and remove the initial load.
1759                  */
1760                 if ((GetRegInfo (S, I, LoadEntry->Chg) & LoadEntry->Chg) == 0   &&
1761                     (LoadEntry->AM == AM65_ABS          ||
1762                      LoadEntry->AM == AM65_ZP           ||
1763                      LoadEntry->AM == AM65_IMM)                                 &&
1764                     !MemAccess (S, Load+1, Xfer-1, LoadEntry)) {
1765
1766                     /* Generate the replacement load insn */
1767                     CodeEntry* X = 0;
1768                     switch (XferEntry->OPC) {
1769
1770                         case OP65_TXA:
1771                         case OP65_TYA:
1772                             X = NewCodeEntry (OP65_LDA,
1773                                               LoadEntry->AM,
1774                                               LoadEntry->Arg,
1775                                               0,
1776                                               LoadEntry->LI);
1777                             break;
1778
1779                         case OP65_TAX:
1780                             X = NewCodeEntry (OP65_LDX,
1781                                               LoadEntry->AM,
1782                                               LoadEntry->Arg,
1783                                               0,
1784                                               LoadEntry->LI);
1785                             break;
1786
1787                         case OP65_TAY:
1788                             X = NewCodeEntry (OP65_LDY,
1789                                               LoadEntry->AM,
1790                                               LoadEntry->Arg,
1791                                               0,
1792                                               LoadEntry->LI);
1793                             break;
1794
1795                         default:
1796                             break;
1797                     }
1798
1799                     /* If we have a replacement load, change the code */
1800                     if (X) {
1801                         /* Insert after the xfer insn */
1802                         CS_InsertEntry (S, X, Xfer+1);
1803
1804                         /* Remove the xfer instead */
1805                         CS_DelEntry (S, Xfer);
1806
1807                         /* Remove the initial load */
1808                         CS_DelEntry (S, Load);
1809
1810                         /* Correct I so we continue with the next insn */
1811                         I -= 2;
1812
1813                         /* Remember we had changes */
1814                         ++Changes;
1815                     } else {
1816                         /* Restart after last xfer insn */
1817                         I = Xfer;
1818                     }
1819                 } else {
1820                     /* Restart after last xfer insn */
1821                     I = Xfer;
1822                 }
1823                 State = Search;
1824                 break;
1825
1826         }
1827
1828         /* Next entry */
1829         ++I;
1830     }
1831
1832     /* Return the number of changes made */
1833     return Changes;
1834 }
1835
1836
1837
1838 unsigned OptPushPop (CodeSeg* S)
1839 /* Remove a PHA/PLA sequence were A is not used later */
1840 {
1841     unsigned Changes = 0;
1842     unsigned Push    = 0;       /* Index of push insn */
1843     unsigned Pop     = 0;       /* Index of pop insn */
1844     unsigned ChgA    = 0;       /* Flag for A changed */
1845     enum {
1846         Searching,
1847         FoundPush,
1848         FoundPop
1849     } State = Searching;
1850
1851     /* Walk over the entries. Look for a push instruction that is followed by
1852      * a pop later, where the pop is not followed by an conditional branch,
1853      * and where the value of the A register is not used later on.
1854      * Look out for the following problems:
1855      *
1856      *  - There may be another PHA/PLA inside the sequence: Restart it.
1857      *  - If the PLA has a label, all jumps to this label must be inside
1858      *    the sequence, otherwise we cannot remove the PHA/PLA.
1859      */
1860     unsigned I = 0;
1861     while (I < CS_GetEntryCount (S)) {
1862
1863         CodeEntry* X;
1864
1865         /* Get next entry */
1866         CodeEntry* E = CS_GetEntry (S, I);
1867
1868         switch (State) {
1869
1870             case Searching:
1871                 if (E->OPC == OP65_PHA) {
1872                     /* Found start of sequence */
1873                     Push  = I;
1874                     ChgA  = 0;
1875                     State = FoundPush;
1876                 }
1877                 break;
1878
1879             case FoundPush:
1880                 if (E->OPC == OP65_PHA) {
1881                     /* Inner push/pop, restart */
1882                     Push = I;
1883                     ChgA = 0;
1884                 } else if (E->OPC == OP65_PLA) {
1885                     /* Found a matching pop */
1886                     Pop = I;
1887                     /* Check that the block between Push and Pop is a basic
1888                      * block (one entry, one exit). Otherwise ignore it.
1889                      */
1890                     if (CS_IsBasicBlock (S, Push, Pop)) {
1891                         State = FoundPop;
1892                     } else {
1893                         /* Go into searching mode again */
1894                         State = Searching;
1895                     }
1896                 } else if (E->Chg & REG_A) {
1897                     ChgA = 1;
1898                 }
1899                 break;
1900
1901             case FoundPop:
1902                 /* We're at the instruction after the PLA.
1903                  * Check for the following conditions:
1904                  *   - If this instruction is a store of A, and A is not used
1905                  *     later, we may replace the PHA by the store and remove
1906                  *     pla if several other conditions are met.
1907                  *   - If this instruction is not a conditional branch, and A
1908                  *     is either unused later, or not changed by the code
1909                  *     between push and pop, we may remove PHA and PLA.
1910                  */
1911                 if (E->OPC == OP65_STA                  &&
1912                     !RegAUsed (S, I+1)                  &&
1913                     !MemAccess (S, Push+1, Pop-1, E)) {
1914
1915                     /* Insert a STA after the PHA */
1916                     X = NewCodeEntry (E->OPC, E->AM, E->Arg, E->JumpTo, E->LI);
1917                     CS_InsertEntry (S, X, Push+1);
1918
1919                     /* Remove the PHA instead */
1920                     CS_DelEntry (S, Push);
1921
1922                     /* Remove the PLA/STA sequence */
1923                     CS_DelEntries (S, Pop, 2);
1924
1925                     /* Correct I so we continue with the next insn */
1926                     I -= 2;
1927
1928                     /* Remember we had changes */
1929                     ++Changes;
1930
1931                 } else if ((E->Info & OF_CBRA) == 0     &&
1932                            (!RegAUsed (S, I) || !ChgA)) {
1933
1934                     /* We can remove the PHA and PLA instructions */
1935                     CS_DelEntry (S, Pop);
1936                     CS_DelEntry (S, Push);
1937
1938                     /* Correct I so we continue with the next insn */
1939                     I -= 2;
1940
1941                     /* Remember we had changes */
1942                     ++Changes;
1943
1944                 }
1945                 /* Go into search mode again */
1946                 State = Searching;
1947                 break;
1948
1949         }
1950
1951         /* Next entry */
1952         ++I;
1953     }
1954
1955     /* Return the number of changes made */
1956     return Changes;
1957 }
1958
1959
1960
1961 unsigned OptPrecalc (CodeSeg* S)
1962 /* Replace immediate operations with the accu where the current contents are
1963  * known by a load of the final value.
1964  */
1965 {
1966     unsigned Changes = 0;
1967     unsigned I;
1968
1969     /* Generate register info for this step */
1970     CS_GenRegInfo (S);
1971
1972     /* Walk over the entries */
1973     I = 0;
1974     while (I < CS_GetEntryCount (S)) {
1975
1976         /* Get next entry */
1977         CodeEntry* E = CS_GetEntry (S, I);
1978
1979         /* Get pointers to the input and output registers of the insn */
1980         const RegContents* Out = &E->RI->Out;
1981         const RegContents* In  = &E->RI->In;
1982
1983         /* Argument for LDn and flag */
1984         const char* Arg = 0;
1985         opc_t OPC = OP65_LDA;
1986
1987         /* Handle the different instructions */
1988         switch (E->OPC) {
1989
1990             case OP65_LDA:
1991                 if (E->AM != AM65_IMM && RegValIsKnown (Out->RegA)) {
1992                     /* Result of load is known */
1993                     Arg = MakeHexArg (Out->RegA);
1994                 }
1995                 break;
1996
1997             case OP65_LDX:
1998                 if (E->AM != AM65_IMM && RegValIsKnown (Out->RegX)) {
1999                     /* Result of load is known but register is X */
2000                     Arg = MakeHexArg (Out->RegX);
2001                     OPC = OP65_LDX;
2002                 }
2003                 break;
2004
2005             case OP65_LDY:
2006                 if (E->AM != AM65_IMM && RegValIsKnown (Out->RegY)) {
2007                     /* Result of load is known but register is Y */
2008                     Arg = MakeHexArg (Out->RegY);
2009                     OPC = OP65_LDY;
2010                 }
2011                 break;
2012
2013             case OP65_EOR:
2014                 if (RegValIsKnown (Out->RegA)) {
2015                     /* Accu op zp with known contents */
2016                     Arg = MakeHexArg (Out->RegA);
2017                 }
2018                 break;
2019
2020             case OP65_ADC:
2021             case OP65_SBC:
2022                 /* If this is an operation with an immediate operand of zero,
2023                  * and the register is zero, the operation won't give us any
2024                  * results we don't already have (including the flags), so
2025                  * remove it. Something like this is generated as a result of
2026                  * a compare where parts of the values are known to be zero.
2027                  */
2028                 if (In->RegA == 0 && CE_IsKnownImm (E, 0x00)) {
2029                     /* 0-0 or 0+0 -> remove */
2030                     CS_DelEntry (S, I);
2031                     ++Changes;
2032                 }
2033                 break;
2034
2035             case OP65_AND:
2036                 if (CE_IsKnownImm (E, 0xFF)) {
2037                     /* AND with 0xFF, remove */
2038                     CS_DelEntry (S, I);
2039                     ++Changes;
2040                 } else if (CE_IsKnownImm (E, 0x00)) {
2041                     /* AND with 0x00, replace by lda #$00 */
2042                     Arg = MakeHexArg (0x00);
2043                 } else if (RegValIsKnown (Out->RegA)) {
2044                     /* Accu AND zp with known contents */
2045                     Arg = MakeHexArg (Out->RegA);
2046                 } else if (In->RegA == 0xFF) {
2047                     /* AND but A contains 0xFF - replace by lda */
2048                     CE_ReplaceOPC (E, OP65_LDA);
2049                     ++Changes;
2050                 }
2051                 break;
2052
2053             case OP65_ORA:
2054                 if (CE_IsKnownImm (E, 0x00)) {
2055                     /* ORA with zero, remove */
2056                     CS_DelEntry (S, I);
2057                     ++Changes;
2058                 } else if (CE_IsKnownImm (E, 0xFF)) {
2059                     /* ORA with 0xFF, replace by lda #$ff */
2060                     Arg = MakeHexArg (0xFF);
2061                 } else if (RegValIsKnown (Out->RegA)) {
2062                     /* Accu AND zp with known contents */
2063                     Arg = MakeHexArg (Out->RegA);
2064                 } else if (In->RegA == 0) {
2065                     /* ORA but A contains 0x00 - replace by lda */
2066                     CE_ReplaceOPC (E, OP65_LDA);
2067                     ++Changes;
2068                 }
2069                 break;
2070
2071             default:
2072                 break;
2073
2074         }
2075
2076         /* Check if we have to replace the insn by LDA */
2077         if (Arg) {
2078             CodeEntry* X = NewCodeEntry (OPC, AM65_IMM, Arg, 0, E->LI);
2079             CS_InsertEntry (S, X, I+1);
2080             CS_DelEntry (S, I);
2081             ++Changes;
2082         }
2083
2084         /* Next entry */
2085         ++I;
2086     }
2087
2088     /* Free register info */
2089     CS_FreeRegInfo (S);
2090
2091     /* Return the number of changes made */
2092     return Changes;
2093 }
2094
2095
2096
2097 /*****************************************************************************/
2098 /*                           Optimize branch types                           */
2099 /*****************************************************************************/
2100
2101
2102
2103 unsigned OptBranchDist (CodeSeg* S)
2104 /* Change branches for the distance needed. */
2105 {
2106     unsigned Changes = 0;
2107
2108     /* Walk over the entries */
2109     unsigned I = 0;
2110     while (I < CS_GetEntryCount (S)) {
2111
2112         /* Get next entry */
2113         CodeEntry* E = CS_GetEntry (S, I);
2114
2115         /* Check if it's a conditional branch to a local label. */
2116         if (E->Info & OF_CBRA) {
2117
2118             /* Is this a branch to a local symbol? */
2119             if (E->JumpTo != 0) {
2120
2121                 /* Check if the branch distance is short */
2122                 int IsShort = IsShortDist (GetBranchDist (S, I, E->JumpTo->Owner));
2123
2124                 /* Make the branch short/long according to distance */
2125                 if ((E->Info & OF_LBRA) == 0 && !IsShort) {
2126                     /* Short branch but long distance */
2127                     CE_ReplaceOPC (E, MakeLongBranch (E->OPC));
2128                     ++Changes;
2129                 } else if ((E->Info & OF_LBRA) != 0 && IsShort) {
2130                     /* Long branch but short distance */
2131                     CE_ReplaceOPC (E, MakeShortBranch (E->OPC));
2132                     ++Changes;
2133                 }
2134
2135             } else if ((E->Info & OF_LBRA) == 0) {
2136
2137                 /* Short branch to external symbol - make it long */
2138                 CE_ReplaceOPC (E, MakeLongBranch (E->OPC));
2139                 ++Changes;
2140
2141             }
2142
2143         } else if ((CPUIsets[CPU] & CPU_ISET_65SC02) != 0 &&
2144                    (E->Info & OF_UBRA) != 0               &&
2145                    E->JumpTo != 0                         &&
2146                    IsShortDist (GetBranchDist (S, I, E->JumpTo->Owner))) {
2147
2148             /* The jump is short and may be replaced by a BRA on the 65C02 CPU */
2149             CE_ReplaceOPC (E, OP65_BRA);
2150             ++Changes;
2151         }
2152
2153         /* Next entry */
2154         ++I;
2155
2156     }
2157
2158     /* Return the number of changes made */
2159     return Changes;
2160 }
2161
2162
2163
2164 /*****************************************************************************/
2165 /*                          Optimize indirect loads                          */
2166 /*****************************************************************************/
2167
2168
2169
2170 unsigned OptIndLoads1 (CodeSeg* S)
2171 /* Change
2172  *
2173  *     lda      (zp),y
2174  *
2175  * into
2176  *
2177  *     lda      (zp,x)
2178  *
2179  * provided that x and y are both zero.
2180  */
2181 {
2182     unsigned Changes = 0;
2183     unsigned I;
2184
2185     /* Generate register info for this step */
2186     CS_GenRegInfo (S);
2187
2188     /* Walk over the entries */
2189     I = 0;
2190     while (I < CS_GetEntryCount (S)) {
2191
2192         /* Get next entry */
2193         CodeEntry* E = CS_GetEntry (S, I);
2194
2195         /* Check if it's what we're looking for */
2196         if (E->OPC == OP65_LDA          &&
2197             E->AM == AM65_ZP_INDY       &&
2198             E->RI->In.RegY == 0         &&
2199             E->RI->In.RegX == 0) {
2200
2201             /* Replace by the same insn with other addressing mode */
2202             CodeEntry* X = NewCodeEntry (E->OPC, AM65_ZPX_IND, E->Arg, 0, E->LI);
2203             CS_InsertEntry (S, X, I+1);
2204
2205             /* Remove the old insn */
2206             CS_DelEntry (S, I);
2207             ++Changes;
2208         }
2209
2210         /* Next entry */
2211         ++I;
2212
2213     }
2214
2215     /* Free register info */
2216     CS_FreeRegInfo (S);
2217
2218     /* Return the number of changes made */
2219     return Changes;
2220 }
2221
2222
2223
2224 unsigned OptIndLoads2 (CodeSeg* S)
2225 /* Change
2226  *
2227  *     lda      (zp,x)
2228  *
2229  * into
2230  *
2231  *     lda      (zp),y
2232  *
2233  * provided that x and y are both zero.
2234  */
2235 {
2236     unsigned Changes = 0;
2237     unsigned I;
2238
2239     /* Generate register info for this step */
2240     CS_GenRegInfo (S);
2241
2242     /* Walk over the entries */
2243     I = 0;
2244     while (I < CS_GetEntryCount (S)) {
2245
2246         /* Get next entry */
2247         CodeEntry* E = CS_GetEntry (S, I);
2248
2249         /* Check if it's what we're looking for */
2250         if (E->OPC == OP65_LDA          &&
2251             E->AM == AM65_ZPX_IND       &&
2252             E->RI->In.RegY == 0         &&
2253             E->RI->In.RegX == 0) {
2254
2255             /* Replace by the same insn with other addressing mode */
2256             CodeEntry* X = NewCodeEntry (E->OPC, AM65_ZP_INDY, E->Arg, 0, E->LI);
2257             CS_InsertEntry (S, X, I+1);
2258
2259             /* Remove the old insn */
2260             CS_DelEntry (S, I);
2261             ++Changes;
2262         }
2263
2264         /* Next entry */
2265         ++I;
2266
2267     }
2268
2269     /* Free register info */
2270     CS_FreeRegInfo (S);
2271
2272     /* Return the number of changes made */
2273     return Changes;
2274 }
2275
2276
2277