]> git.sur5r.net Git - cc65/blob - src/cc65/coptind.c
Another small change in OptJumpTarget3.
[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 and the next insn is not
777          * a conditional branch that needs the flags from the load.
778          */
779         if ((E->Info & OF_LOAD) != 0            &&
780             CE_IsConstImm (E)                   &&
781             CE_HasLabel (E)                     &&
782             (N = CS_GetNextEntry (S, I)) != 0   &&
783             !CE_UseLoadFlags (N)) {
784
785             /* Walk over all insn that jump here */
786             for (J = 0; J < CE_GetLabelCount (E); ++J) {
787
788                 /* Get the label */
789                 CodeLabel* L = CE_GetLabel (E, J);
790                 for (K = 0; K < CL_GetRefCount (L); ++K) {
791
792                     /* Get the entry that jumps here */
793                     CodeEntry* Jump = CL_GetRef (L, K);
794
795                     /* Get the register info from this insn */
796                     short Val = RegVal (E->Chg, &Jump->RI->Out2);
797
798                     /* Check if the outgoing value is the one thatr's loaded */
799                     if (Val == (unsigned char) E->Num) {
800
801                         /* Ok, skip the insn. First, generate a label */
802                         if (LN == 0) {
803                             LN = CS_GenLabel (S, N);
804                         }
805
806                         /* Change the jump target to point to this new label */
807                         CS_MoveLabelRef (S, Jump, LN);
808
809                         /* Remember that we had changes */
810                         ++Changes;
811                     }
812                 }
813             }
814
815         }
816
817         /* Next entry */
818         ++I;
819     }
820
821     /* Free register info */
822     CS_FreeRegInfo (S);
823
824     /* Return the number of changes made */
825     return Changes;
826 }
827
828
829
830 /*****************************************************************************/
831 /*                       Optimize conditional branches                       */
832 /*****************************************************************************/
833
834
835
836 unsigned OptCondBranches1 (CodeSeg* S)
837 /* Performs several optimization steps:
838  *
839  *  - If an immidiate load of a register is followed by a conditional jump that
840  *    is never taken because the load of the register sets the flags in such a
841  *    manner, remove the conditional branch.
842  *  - If the conditional branch is always taken because of the register load,
843  *    replace it by a jmp.
844  *  - If a conditional branch jumps around an unconditional branch, remove the
845  *    conditional branch and make the jump a conditional branch with the
846  *    inverse condition of the first one.
847  */
848 {
849     unsigned Changes = 0;
850
851     /* Walk over the entries */
852     unsigned I = 0;
853     while (I < CS_GetEntryCount (S)) {
854
855         CodeEntry* N;
856         CodeLabel* L;
857
858         /* Get next entry */
859         CodeEntry* E = CS_GetEntry (S, I);
860
861         /* Check if it's a register load */
862         if ((E->Info & OF_LOAD) != 0              &&  /* It's a load instruction */
863             E->AM == AM65_IMM                     &&  /* ..with immidiate addressing */
864             (E->Flags & CEF_NUMARG) != 0          &&  /* ..and a numeric argument. */
865             (N = CS_GetNextEntry (S, I)) != 0     &&  /* There is a following entry */
866             (N->Info & OF_CBRA) != 0              &&  /* ..which is a conditional branch */
867             !CE_HasLabel (N)) {               /* ..and does not have a label */
868
869             /* Get the branch condition */
870             bc_t BC = GetBranchCond (N->OPC);
871
872             /* Check the argument against the branch condition */
873             if ((BC == BC_EQ && E->Num != 0)            ||
874                 (BC == BC_NE && E->Num == 0)            ||
875                 (BC == BC_PL && (E->Num & 0x80) != 0)   ||
876                 (BC == BC_MI && (E->Num & 0x80) == 0)) {
877
878                 /* Remove the conditional branch */
879                 CS_DelEntry (S, I+1);
880
881                 /* Remember, we had changes */
882                 ++Changes;
883
884             } else if ((BC == BC_EQ && E->Num == 0)             ||
885                        (BC == BC_NE && E->Num != 0)             ||
886                        (BC == BC_PL && (E->Num & 0x80) == 0)    ||
887                        (BC == BC_MI && (E->Num & 0x80) != 0)) {
888
889                 /* The branch is always taken, replace it by a jump */
890                 CE_ReplaceOPC (N, OP65_JMP);
891
892                 /* Remember, we had changes */
893                 ++Changes;
894             }
895
896         }
897
898         if ((E->Info & OF_CBRA) != 0              &&  /* It's a conditional branch */
899             (L = E->JumpTo) != 0                  &&  /* ..referencing a local label */
900             (N = CS_GetNextEntry (S, I)) != 0     &&  /* There is a following entry */
901             (N->Info & OF_UBRA) != 0              &&  /* ..which is an uncond branch, */
902             !CE_HasLabel (N)                      &&  /* ..has no label attached */
903             L->Owner == CS_GetNextEntry (S, I+1)) {/* ..and jump target follows */
904
905             /* Replace the jump by a conditional branch with the inverse branch
906              * condition than the branch around it.
907              */
908             CE_ReplaceOPC (N, GetInverseBranch (E->OPC));
909
910             /* Remove the conditional branch */
911             CS_DelEntry (S, I);
912
913             /* Remember, we had changes */
914             ++Changes;
915
916         }
917
918         /* Next entry */
919         ++I;
920
921     }
922
923     /* Return the number of changes made */
924     return Changes;
925 }
926
927
928
929 unsigned OptCondBranches2 (CodeSeg* S)
930 /* If on entry to a "rol a" instruction the accu is zero, and a beq/bne follows,
931  * we can remove the rol and branch on the state of the carry flag.
932  */
933 {
934     unsigned Changes = 0;
935     unsigned I;
936
937     /* Generate register info for this step */
938     CS_GenRegInfo (S);
939
940     /* Walk over the entries */
941     I = 0;
942     while (I < CS_GetEntryCount (S)) {
943
944         CodeEntry* N;
945
946         /* Get next entry */
947         CodeEntry* E = CS_GetEntry (S, I);
948
949         /* Check if it's a rol insn with A in accu and a branch follows */
950         if (E->OPC == OP65_ROL                  &&
951             E->AM == AM65_ACC                   &&
952             E->RI->In.RegA == 0                 &&
953             !CE_HasLabel (E)                    &&
954             (N = CS_GetNextEntry (S, I)) != 0   &&
955             (N->Info & OF_ZBRA) != 0            &&
956             !RegAUsed (S, I+1)) {
957
958             /* Replace the branch condition */
959             switch (GetBranchCond (N->OPC)) {
960                 case BC_EQ:     CE_ReplaceOPC (N, OP65_JCC); break;
961                 case BC_NE:     CE_ReplaceOPC (N, OP65_JCS); break;
962                 default:        Internal ("Unknown branch condition in OptCondBranches2");
963             }
964
965             /* Delete the rol insn */
966             CS_DelEntry (S, I);
967
968             /* Remember, we had changes */
969             ++Changes;
970         }
971
972         /* Next entry */
973         ++I;
974     }
975
976     /* Free register info */
977     CS_FreeRegInfo (S);
978
979     /* Return the number of changes made */
980     return Changes;
981 }
982
983
984
985 /*****************************************************************************/
986 /*                      Remove unused loads and stores                       */
987 /*****************************************************************************/
988
989
990
991 unsigned OptUnusedLoads (CodeSeg* S)
992 /* Remove loads of registers where the value loaded is not used later. */
993 {
994     unsigned Changes = 0;
995
996     /* Walk over the entries */
997     unsigned I = 0;
998     while (I < CS_GetEntryCount (S)) {
999
1000         CodeEntry* N;
1001
1002         /* Get next entry */
1003         CodeEntry* E = CS_GetEntry (S, I);
1004
1005         /* Check if it's a register load or transfer insn */
1006         if ((E->Info & (OF_LOAD | OF_XFR | OF_REG_INCDEC)) != 0         &&
1007             (N = CS_GetNextEntry (S, I)) != 0                           &&
1008             !CE_UseLoadFlags (N)) {
1009
1010             /* Check which sort of load or transfer it is */
1011             unsigned R;
1012             switch (E->OPC) {
1013                 case OP65_DEA:
1014                 case OP65_INA:
1015                 case OP65_LDA:
1016                 case OP65_TXA:
1017                 case OP65_TYA:  R = REG_A;      break;
1018                 case OP65_DEX:
1019                 case OP65_INX:
1020                 case OP65_LDX:
1021                 case OP65_TAX:  R = REG_X;      break;
1022                 case OP65_DEY:
1023                 case OP65_INY:
1024                 case OP65_LDY:
1025                 case OP65_TAY:  R = REG_Y;      break;
1026                 default:        goto NextEntry;         /* OOPS */
1027             }
1028
1029             /* Get register usage and check if the register value is used later */
1030             if ((GetRegInfo (S, I+1, R) & R) == 0) {
1031
1032                 /* Register value is not used, remove the load */
1033                 CS_DelEntry (S, I);
1034
1035                 /* Remember, we had changes. Account the deleted entry in I. */
1036                 ++Changes;
1037                 --I;
1038
1039             }
1040         }
1041
1042 NextEntry:
1043         /* Next entry */
1044         ++I;
1045
1046     }
1047
1048     /* Return the number of changes made */
1049     return Changes;
1050 }
1051
1052
1053
1054 unsigned OptUnusedStores (CodeSeg* S)
1055 /* Remove stores into zero page registers that aren't used later */
1056 {
1057     unsigned Changes = 0;
1058
1059     /* Walk over the entries */
1060     unsigned I = 0;
1061     while (I < CS_GetEntryCount (S)) {
1062
1063         /* Get next entry */
1064         CodeEntry* E = CS_GetEntry (S, I);
1065
1066         /* Check if it's a register load or transfer insn */
1067         if ((E->Info & OF_STORE) != 0    &&
1068             E->AM == AM65_ZP             &&
1069             (E->Chg & REG_ZP) != 0) {
1070
1071             /* Check for the zero page location. We know that there cannot be
1072              * more than one zero page location involved in the store.
1073              */
1074             unsigned R = E->Chg & REG_ZP;
1075
1076             /* Get register usage and check if the register value is used later */
1077             if ((GetRegInfo (S, I+1, R) & R) == 0) {
1078
1079                 /* Register value is not used, remove the load */
1080                 CS_DelEntry (S, I);
1081
1082                 /* Remember, we had changes */
1083                 ++Changes;
1084
1085                 /* Continue with next insn */
1086                 continue;
1087             }
1088         }
1089
1090         /* Next entry */
1091         ++I;
1092
1093     }
1094
1095     /* Return the number of changes made */
1096     return Changes;
1097 }
1098
1099
1100
1101 unsigned OptDupLoads (CodeSeg* S)
1102 /* Remove loads of registers where the value loaded is already in the register. */
1103 {
1104     unsigned Changes = 0;
1105     unsigned I;
1106
1107     /* Generate register info for this step */
1108     CS_GenRegInfo (S);
1109
1110     /* Walk over the entries */
1111     I = 0;
1112     while (I < CS_GetEntryCount (S)) {
1113
1114         CodeEntry* N;
1115
1116         /* Get next entry */
1117         CodeEntry* E = CS_GetEntry (S, I);
1118
1119         /* Assume we won't delete the entry */
1120         int Delete = 0;
1121
1122         /* Get a pointer to the input registers of the insn */
1123         const RegContents* In  = &E->RI->In;
1124
1125         /* Handle the different instructions */
1126         switch (E->OPC) {
1127
1128             case OP65_LDA:
1129                 if (RegValIsKnown (In->RegA)          && /* Value of A is known */
1130                     CE_IsKnownImm (E, In->RegA)       && /* Value to be loaded is known */
1131                     (N = CS_GetNextEntry (S, I)) != 0 && /* There is a next entry */
1132                     !CE_UseLoadFlags (N)) {              /* Which does not use the flags */
1133                     Delete = 1;
1134                 }
1135                 break;
1136
1137             case OP65_LDX:
1138                 if (RegValIsKnown (In->RegX)          && /* Value of X is known */
1139                     CE_IsKnownImm (E, In->RegX)       && /* Value to be loaded is known */
1140                     (N = CS_GetNextEntry (S, I)) != 0 && /* There is a next entry */
1141                     !CE_UseLoadFlags (N)) {              /* Which does not use the flags */
1142                     Delete = 1;
1143                 }
1144                 break;
1145
1146             case OP65_LDY:
1147                 if (RegValIsKnown (In->RegY)          && /* Value of Y is known */
1148                     CE_IsKnownImm (E, In->RegY)       && /* Value to be loaded is known */
1149                     (N = CS_GetNextEntry (S, I)) != 0 && /* There is a next entry */
1150                     !CE_UseLoadFlags (N)) {              /* Which does not use the flags */
1151                     Delete = 1;
1152                 }
1153                 break;
1154
1155             case OP65_STA:
1156                 /* If we store into a known zero page location, and this
1157                  * location does already contain the value to be stored,
1158                  * remove the store.
1159                  */
1160                 if (RegValIsKnown (In->RegA)          && /* Value of A is known */
1161                     E->AM == AM65_ZP                  && /* Store into zp */
1162                     In->RegA == ZPRegVal (E->Chg, In)) { /* Value identical */
1163
1164                     Delete = 1;
1165                 }
1166                 break;
1167
1168             case OP65_STX:
1169                 /* If we store into a known zero page location, and this
1170                  * location does already contain the value to be stored,
1171                  * remove the store.
1172                  */
1173                 if (RegValIsKnown (In->RegX)          && /* Value of A is known */
1174                     E->AM == AM65_ZP                  && /* Store into zp */
1175                     In->RegX == ZPRegVal (E->Chg, In)) { /* Value identical */
1176
1177                     Delete = 1;
1178
1179                 /* If the value in the X register is known and the same as
1180                  * that in the A register, replace the store by a STA. The
1181                  * optimizer will then remove the load instruction for X
1182                  * later. STX does support the zeropage,y addressing mode,
1183                  * so be sure to check for that.
1184                  */
1185                 } else if (RegValIsKnown (In->RegX)   &&
1186                            In->RegX == In->RegA       &&
1187                            E->AM != AM65_ABSY         &&
1188                            E->AM != AM65_ZPY) {
1189                     /* Use the A register instead */
1190                     CE_ReplaceOPC (E, OP65_STA);
1191                 }
1192                 break;
1193
1194             case OP65_STY:
1195                 /* If we store into a known zero page location, and this
1196                  * location does already contain the value to be stored,
1197                  * remove the store.
1198                  */
1199                 if (RegValIsKnown (In->RegY)          && /* Value of Y is known */
1200                     E->AM == AM65_ZP                  && /* Store into zp */
1201                     In->RegY == ZPRegVal (E->Chg, In)) { /* Value identical */
1202
1203                     Delete = 1;
1204
1205                 /* If the value in the Y register is known and the same as
1206                  * that in the A register, replace the store by a STA. The
1207                  * optimizer will then remove the load instruction for Y
1208                  * later. If replacement by A is not possible try a
1209                  * replacement by X, but check for invalid addressing modes
1210                  * in this case.
1211                  */
1212                 } else if (RegValIsKnown (In->RegY)) {
1213                     if (In->RegY == In->RegA) {
1214                         CE_ReplaceOPC (E, OP65_STA);
1215                     } else if (In->RegY == In->RegX   &&
1216                                E->AM != AM65_ABSX     &&
1217                                E->AM != AM65_ZPX) {
1218                         CE_ReplaceOPC (E, OP65_STX);
1219                     }
1220                 }
1221                 break;
1222
1223             case OP65_STZ:
1224                 /* If we store into a known zero page location, and this
1225                  * location does already contain the value to be stored,
1226                  * remove the store.
1227                  */
1228                 if ((CPUIsets[CPU] & CPU_ISET_65SC02) != 0 && E->AM == AM65_ZP) {
1229                     if (ZPRegVal (E->Chg, In) == 0) {
1230                         Delete = 1;
1231                     }
1232                 }
1233                 break;
1234
1235             case OP65_TAX:
1236                 if (RegValIsKnown (In->RegA)          &&
1237                     In->RegA == In->RegX              &&
1238                     (N = CS_GetNextEntry (S, I)) != 0 &&
1239                     !CE_UseLoadFlags (N)) {
1240                     /* Value is identical and not followed by a branch */
1241                     Delete = 1;
1242                 }
1243                 break;
1244
1245             case OP65_TAY:
1246                 if (RegValIsKnown (In->RegA)            &&
1247                     In->RegA == In->RegY                &&
1248                     (N = CS_GetNextEntry (S, I)) != 0   &&
1249                     !CE_UseLoadFlags (N)) {
1250                     /* Value is identical and not followed by a branch */
1251                     Delete = 1;
1252                 }
1253                 break;
1254
1255             case OP65_TXA:
1256                 if (RegValIsKnown (In->RegX)            &&
1257                     In->RegX == In->RegA                &&
1258                     (N = CS_GetNextEntry (S, I)) != 0   &&
1259                     !CE_UseLoadFlags (N)) {
1260                     /* Value is identical and not followed by a branch */
1261                     Delete = 1;
1262                 }
1263                 break;
1264
1265             case OP65_TYA:
1266                 if (RegValIsKnown (In->RegY)            &&
1267                     In->RegY == In->RegA                &&
1268                     (N = CS_GetNextEntry (S, I)) != 0   &&
1269                     !CE_UseLoadFlags (N)) {
1270                     /* Value is identical and not followed by a branch */
1271                     Delete = 1;
1272                 }
1273                 break;
1274
1275             default:
1276                 break;
1277
1278         }
1279
1280         /* Delete the entry if requested */
1281         if (Delete) {
1282
1283             /* Register value is not used, remove the load */
1284             CS_DelEntry (S, I);
1285
1286             /* Remember, we had changes */
1287             ++Changes;
1288
1289         } else {
1290
1291             /* Next entry */
1292             ++I;
1293
1294         }
1295
1296     }
1297
1298     /* Free register info */
1299     CS_FreeRegInfo (S);
1300
1301     /* Return the number of changes made */
1302     return Changes;
1303 }
1304
1305
1306
1307 unsigned OptStoreLoad (CodeSeg* S)
1308 /* Remove a store followed by a load from the same location. */
1309 {
1310     unsigned Changes = 0;
1311
1312     /* Walk over the entries */
1313     unsigned I = 0;
1314     while (I < CS_GetEntryCount (S)) {
1315
1316         CodeEntry* N;
1317         CodeEntry* X;
1318
1319         /* Get next entry */
1320         CodeEntry* E = CS_GetEntry (S, I);
1321
1322         /* Check if it is a store instruction followed by a load from the
1323          * same address which is itself not followed by a conditional branch.
1324          */
1325         if ((E->Info & OF_STORE) != 0                       &&
1326             (N = CS_GetNextEntry (S, I)) != 0               &&
1327             !CE_HasLabel (N)                                &&
1328             E->AM == N->AM                                  &&
1329             ((E->OPC == OP65_STA && N->OPC == OP65_LDA) ||
1330              (E->OPC == OP65_STX && N->OPC == OP65_LDX) ||
1331              (E->OPC == OP65_STY && N->OPC == OP65_LDY))    &&
1332             strcmp (E->Arg, N->Arg) == 0                    &&
1333             (X = CS_GetNextEntry (S, I+1)) != 0             &&
1334             !CE_UseLoadFlags (X)) {
1335
1336             /* Register has already the correct value, remove the load */
1337             CS_DelEntry (S, I+1);
1338
1339             /* Remember, we had changes */
1340             ++Changes;
1341
1342         }
1343
1344         /* Next entry */
1345         ++I;
1346
1347     }
1348
1349     /* Return the number of changes made */
1350     return Changes;
1351 }
1352
1353
1354
1355 unsigned OptTransfers1 (CodeSeg* S)
1356 /* Remove transfers from one register to another and back */
1357 {
1358     unsigned Changes = 0;
1359
1360     /* Walk over the entries */
1361     unsigned I = 0;
1362     while (I < CS_GetEntryCount (S)) {
1363
1364         CodeEntry* N;
1365         CodeEntry* X;
1366         CodeEntry* P;
1367
1368         /* Get next entry */
1369         CodeEntry* E = CS_GetEntry (S, I);
1370
1371         /* Check if we have two transfer instructions */
1372         if ((E->Info & OF_XFR) != 0                 &&
1373             (N = CS_GetNextEntry (S, I)) != 0       &&
1374             !CE_HasLabel (N)                        &&
1375             (N->Info & OF_XFR) != 0) {
1376
1377             /* Check if it's a transfer and back */
1378             if ((E->OPC == OP65_TAX && N->OPC == OP65_TXA && !RegXUsed (S, I+2)) ||
1379                 (E->OPC == OP65_TAY && N->OPC == OP65_TYA && !RegYUsed (S, I+2)) ||
1380                 (E->OPC == OP65_TXA && N->OPC == OP65_TAX && !RegAUsed (S, I+2)) ||
1381                 (E->OPC == OP65_TYA && N->OPC == OP65_TAY && !RegAUsed (S, I+2))) {
1382
1383                 /* If the next insn is a conditional branch, check if the insn
1384                  * preceeding the first xfr will set the flags right, otherwise we
1385                  * may not remove the sequence.
1386                  */
1387                 if ((X = CS_GetNextEntry (S, I+1)) == 0) {
1388                     goto NextEntry;
1389                 }
1390                 if (CE_UseLoadFlags (X)) {
1391                     if (I == 0) {
1392                         /* No preceeding entry */
1393                         goto NextEntry;
1394                     }
1395                     P = CS_GetEntry (S, I-1);
1396                     if ((P->Info & OF_SETF) == 0) {
1397                         /* Does not set the flags */
1398                         goto NextEntry;
1399                     }
1400                 }
1401
1402                 /* Remove both transfers */
1403                 CS_DelEntry (S, I+1);
1404                 CS_DelEntry (S, I);
1405
1406                 /* Remember, we had changes */
1407                 ++Changes;
1408             }
1409         }
1410
1411 NextEntry:
1412         /* Next entry */
1413         ++I;
1414
1415     }
1416
1417     /* Return the number of changes made */
1418     return Changes;
1419 }
1420
1421
1422
1423 unsigned OptTransfers2 (CodeSeg* S)
1424 /* Replace loads followed by a register transfer by a load with the second
1425  * register if possible.
1426  */
1427 {
1428     unsigned Changes = 0;
1429
1430     /* Walk over the entries */
1431     unsigned I = 0;
1432     while (I < CS_GetEntryCount (S)) {
1433
1434         CodeEntry* N;
1435
1436         /* Get next entry */
1437         CodeEntry* E = CS_GetEntry (S, I);
1438
1439         /* Check if we have a load followed by a transfer where the loaded
1440          * register is not used later.
1441          */
1442         if ((E->Info & OF_LOAD) != 0                &&
1443             (N = CS_GetNextEntry (S, I)) != 0       &&
1444             !CE_HasLabel (N)                        &&
1445             (N->Info & OF_XFR) != 0                 &&
1446             GetRegInfo (S, I+2, E->Chg) != E->Chg) {
1447
1448             CodeEntry* X = 0;
1449
1450             if (E->OPC == OP65_LDA && N->OPC == OP65_TAX) {
1451                 /* LDA/TAX - check for the right addressing modes */
1452                 if (E->AM == AM65_IMM ||
1453                     E->AM == AM65_ZP  ||
1454                     E->AM == AM65_ABS ||
1455                     E->AM == AM65_ABSY) {
1456                     /* Replace */
1457                     X = NewCodeEntry (OP65_LDX, E->AM, E->Arg, 0, N->LI);
1458                 }
1459             } else if (E->OPC == OP65_LDA && N->OPC == OP65_TAY) {
1460                 /* LDA/TAY - check for the right addressing modes */
1461                 if (E->AM == AM65_IMM ||
1462                     E->AM == AM65_ZP  ||
1463                     E->AM == AM65_ZPX ||
1464                     E->AM == AM65_ABS ||
1465                     E->AM == AM65_ABSX) {
1466                     /* Replace */
1467                     X = NewCodeEntry (OP65_LDY, E->AM, E->Arg, 0, N->LI);
1468                 }
1469             } else if (E->OPC == OP65_LDY && N->OPC == OP65_TYA) {
1470                 /* LDY/TYA. LDA supports all addressing modes LDY does */
1471                 X = NewCodeEntry (OP65_LDA, E->AM, E->Arg, 0, N->LI);
1472             } else if (E->OPC == OP65_LDX && N->OPC == OP65_TXA) {
1473                 /* LDX/TXA. LDA doesn't support zp,y, so we must map it to
1474                  * abs,y instead.
1475                  */
1476                 am_t AM = (E->AM == AM65_ZPY)? AM65_ABSY : E->AM;
1477                 X = NewCodeEntry (OP65_LDA, AM, E->Arg, 0, N->LI);
1478             }
1479
1480             /* If we have a load entry, add it and remove the old stuff */
1481             if (X) {
1482                 CS_InsertEntry (S, X, I+2);
1483                 CS_DelEntries (S, I, 2);
1484                 ++Changes;
1485                 --I;    /* Correct for one entry less */
1486             }
1487         }
1488
1489         /* Next entry */
1490         ++I;
1491     }
1492
1493     /* Return the number of changes made */
1494     return Changes;
1495 }
1496
1497
1498
1499 unsigned OptTransfers3 (CodeSeg* S)
1500 /* Replace a register transfer followed by a store of the second register by a
1501  * store of the first register if this is possible.
1502  */
1503 {
1504     unsigned Changes      = 0;
1505     unsigned UsedRegs     = REG_NONE;   /* Track used registers */
1506     unsigned Xfer         = 0;          /* Index of transfer insn */
1507     unsigned Store        = 0;          /* Index of store insn */
1508     CodeEntry* XferEntry  = 0;          /* Pointer to xfer insn */
1509     CodeEntry* StoreEntry = 0;          /* Pointer to store insn */
1510
1511     enum {
1512         Initialize,
1513         Search,
1514         FoundXfer,
1515         FoundStore
1516     } State = Initialize;
1517
1518     /* Walk over the entries. Look for a xfer instruction that is followed by
1519      * a store later, where the value of the register is not used later.
1520      */
1521     unsigned I = 0;
1522     while (I < CS_GetEntryCount (S)) {
1523
1524         /* Get next entry */
1525         CodeEntry* E = CS_GetEntry (S, I);
1526
1527         switch (State) {
1528
1529             case Initialize:
1530                 /* Clear the list of used registers */
1531                 UsedRegs = REG_NONE;
1532                 /* FALLTHROUGH */
1533
1534             case Search:
1535                 if (E->Info & OF_XFR) {
1536                     /* Found start of sequence */
1537                     Xfer = I;
1538                     XferEntry = E;
1539                     State = FoundXfer;
1540                 }
1541                 break;
1542
1543             case FoundXfer:
1544                 /* If we find a conditional jump, abort the sequence, since
1545                  * handling them makes things really complicated.
1546                  */
1547                 if (E->Info & OF_CBRA) {
1548
1549                     /* Switch back to searching */
1550                     I = Xfer;
1551                     State = Initialize;
1552
1553                 /* Does this insn use the target register of the transfer? */
1554                 } else if ((E->Use & XferEntry->Chg) != 0) {
1555
1556                     /* It it's a store instruction, and the block is a basic
1557                      * block, proceed. Otherwise restart
1558                      */
1559                     if ((E->Info & OF_STORE) != 0       &&
1560                         CS_IsBasicBlock (S, Xfer, I)) {
1561                         Store = I;
1562                         StoreEntry = E;
1563                         State = FoundStore;
1564                     } else {
1565                         I = Xfer;
1566                         State = Initialize;
1567                     }
1568
1569                 /* Does this insn change the target register of the transfer? */
1570                 } else if (E->Chg & XferEntry->Chg) {
1571
1572                     /* We *may* add code here to remove the transfer, but I'm
1573                      * currently not sure about the consequences, so I won't
1574                      * do that and bail out instead.
1575                      */
1576                     I = Xfer;
1577                     State = Initialize;
1578
1579                 /* Does this insn have a label? */
1580                 } else if (CE_HasLabel (E)) {
1581
1582                     /* Too complex to handle - bail out */
1583                     I = Xfer;
1584                     State = Initialize;
1585
1586                 } else {
1587                     /* Track used registers */
1588                     UsedRegs |= E->Use;
1589                 }
1590                 break;
1591
1592             case FoundStore:
1593                 /* We are at the instruction behind the store. If the register
1594                  * isn't used later, and we have an address mode match, we can
1595                  * replace the transfer by a store and remove the store here.
1596                  */
1597                 if ((GetRegInfo (S, I, XferEntry->Chg) & XferEntry->Chg) == 0   &&
1598                     (StoreEntry->AM == AM65_ABS         ||
1599                      StoreEntry->AM == AM65_ZP)                                 &&
1600                     (StoreEntry->AM != AM65_ZP ||
1601                      (StoreEntry->Chg & UsedRegs) == 0)                         &&
1602                     !MemAccess (S, Xfer+1, Store-1, StoreEntry)) {
1603
1604                     /* Generate the replacement store insn */
1605                     CodeEntry* X = 0;
1606                     switch (XferEntry->OPC) {
1607
1608                         case OP65_TXA:
1609                             X = NewCodeEntry (OP65_STX,
1610                                               StoreEntry->AM,
1611                                               StoreEntry->Arg,
1612                                               0,
1613                                               StoreEntry->LI);
1614                             break;
1615
1616                         case OP65_TAX:
1617                             X = NewCodeEntry (OP65_STA,
1618                                               StoreEntry->AM,
1619                                               StoreEntry->Arg,
1620                                               0,
1621                                               StoreEntry->LI);
1622                             break;
1623
1624                         case OP65_TYA:
1625                             X = NewCodeEntry (OP65_STY,
1626                                               StoreEntry->AM,
1627                                               StoreEntry->Arg,
1628                                               0,
1629                                               StoreEntry->LI);
1630                             break;
1631
1632                         case OP65_TAY:
1633                             X = NewCodeEntry (OP65_STA,
1634                                               StoreEntry->AM,
1635                                               StoreEntry->Arg,
1636                                               0,
1637                                               StoreEntry->LI);
1638                             break;
1639
1640                         default:
1641                             break;
1642                     }
1643
1644                     /* If we have a replacement store, change the code */
1645                     if (X) {
1646                         /* Insert after the xfer insn */
1647                         CS_InsertEntry (S, X, Xfer+1);
1648
1649                         /* Remove the xfer instead */
1650                         CS_DelEntry (S, Xfer);
1651
1652                         /* Remove the final store */
1653                         CS_DelEntry (S, Store);
1654
1655                         /* Correct I so we continue with the next insn */
1656                         I -= 2;
1657
1658                         /* Remember we had changes */
1659                         ++Changes;
1660                     } else {
1661                         /* Restart after last xfer insn */
1662                         I = Xfer;
1663                     }
1664                 } else {
1665                     /* Restart after last xfer insn */
1666                     I = Xfer;
1667                 }
1668                 State = Initialize;
1669                 break;
1670
1671         }
1672
1673         /* Next entry */
1674         ++I;
1675     }
1676
1677     /* Return the number of changes made */
1678     return Changes;
1679 }
1680
1681
1682
1683 unsigned OptTransfers4 (CodeSeg* S)
1684 /* Replace a load of a register followed by a transfer insn of the same register
1685  * by a load of the second register if possible.
1686  */
1687 {
1688     unsigned Changes      = 0;
1689     unsigned Load         = 0;  /* Index of load insn */
1690     unsigned Xfer         = 0;  /* Index of transfer insn */
1691     CodeEntry* LoadEntry  = 0;  /* Pointer to load insn */
1692     CodeEntry* XferEntry  = 0;  /* Pointer to xfer insn */
1693
1694     enum {
1695         Search,
1696         FoundLoad,
1697         FoundXfer
1698     } State = Search;
1699
1700     /* Walk over the entries. Look for a load instruction that is followed by
1701      * a load later.
1702      */
1703     unsigned I = 0;
1704     while (I < CS_GetEntryCount (S)) {
1705
1706         /* Get next entry */
1707         CodeEntry* E = CS_GetEntry (S, I);
1708
1709         switch (State) {
1710
1711             case Search:
1712                 if (E->Info & OF_LOAD) {
1713                     /* Found start of sequence */
1714                     Load = I;
1715                     LoadEntry = E;
1716                     State = FoundLoad;
1717                 }
1718                 break;
1719
1720             case FoundLoad:
1721                 /* If we find a conditional jump, abort the sequence, since
1722                  * handling them makes things really complicated.
1723                  */
1724                 if (E->Info & OF_CBRA) {
1725
1726                     /* Switch back to searching */
1727                     I = Load;
1728                     State = Search;
1729
1730                 /* Does this insn use the target register of the load? */
1731                 } else if ((E->Use & LoadEntry->Chg) != 0) {
1732
1733                     /* It it's a xfer instruction, and the block is a basic
1734                      * block, proceed. Otherwise restart
1735                      */
1736                     if ((E->Info & OF_XFR) != 0       &&
1737                         CS_IsBasicBlock (S, Load, I)) {
1738                         Xfer = I;
1739                         XferEntry = E;
1740                         State = FoundXfer;
1741                     } else {
1742                         I = Load;
1743                         State = Search;
1744                     }
1745
1746                 /* Does this insn change the target register of the load? */
1747                 } else if (E->Chg & LoadEntry->Chg) {
1748
1749                     /* We *may* add code here to remove the load, but I'm
1750                      * currently not sure about the consequences, so I won't
1751                      * do that and bail out instead.
1752                      */
1753                     I = Load;
1754                     State = Search;
1755                 }
1756                 break;
1757
1758             case FoundXfer:
1759                 /* We are at the instruction behind the xfer. If the register
1760                  * isn't used later, and we have an address mode match, we can
1761                  * replace the transfer by a load and remove the initial load.
1762                  */
1763                 if ((GetRegInfo (S, I, LoadEntry->Chg) & LoadEntry->Chg) == 0   &&
1764                     (LoadEntry->AM == AM65_ABS          ||
1765                      LoadEntry->AM == AM65_ZP           ||
1766                      LoadEntry->AM == AM65_IMM)                                 &&
1767                     !MemAccess (S, Load+1, Xfer-1, LoadEntry)) {
1768
1769                     /* Generate the replacement load insn */
1770                     CodeEntry* X = 0;
1771                     switch (XferEntry->OPC) {
1772
1773                         case OP65_TXA:
1774                         case OP65_TYA:
1775                             X = NewCodeEntry (OP65_LDA,
1776                                               LoadEntry->AM,
1777                                               LoadEntry->Arg,
1778                                               0,
1779                                               LoadEntry->LI);
1780                             break;
1781
1782                         case OP65_TAX:
1783                             X = NewCodeEntry (OP65_LDX,
1784                                               LoadEntry->AM,
1785                                               LoadEntry->Arg,
1786                                               0,
1787                                               LoadEntry->LI);
1788                             break;
1789
1790                         case OP65_TAY:
1791                             X = NewCodeEntry (OP65_LDY,
1792                                               LoadEntry->AM,
1793                                               LoadEntry->Arg,
1794                                               0,
1795                                               LoadEntry->LI);
1796                             break;
1797
1798                         default:
1799                             break;
1800                     }
1801
1802                     /* If we have a replacement load, change the code */
1803                     if (X) {
1804                         /* Insert after the xfer insn */
1805                         CS_InsertEntry (S, X, Xfer+1);
1806
1807                         /* Remove the xfer instead */
1808                         CS_DelEntry (S, Xfer);
1809
1810                         /* Remove the initial load */
1811                         CS_DelEntry (S, Load);
1812
1813                         /* Correct I so we continue with the next insn */
1814                         I -= 2;
1815
1816                         /* Remember we had changes */
1817                         ++Changes;
1818                     } else {
1819                         /* Restart after last xfer insn */
1820                         I = Xfer;
1821                     }
1822                 } else {
1823                     /* Restart after last xfer insn */
1824                     I = Xfer;
1825                 }
1826                 State = Search;
1827                 break;
1828
1829         }
1830
1831         /* Next entry */
1832         ++I;
1833     }
1834
1835     /* Return the number of changes made */
1836     return Changes;
1837 }
1838
1839
1840
1841 unsigned OptPushPop (CodeSeg* S)
1842 /* Remove a PHA/PLA sequence were A is not used later */
1843 {
1844     unsigned Changes = 0;
1845     unsigned Push    = 0;       /* Index of push insn */
1846     unsigned Pop     = 0;       /* Index of pop insn */
1847     unsigned ChgA    = 0;       /* Flag for A changed */
1848     enum {
1849         Searching,
1850         FoundPush,
1851         FoundPop
1852     } State = Searching;
1853
1854     /* Walk over the entries. Look for a push instruction that is followed by
1855      * a pop later, where the pop is not followed by an conditional branch,
1856      * and where the value of the A register is not used later on.
1857      * Look out for the following problems:
1858      *
1859      *  - There may be another PHA/PLA inside the sequence: Restart it.
1860      *  - If the PLA has a label, all jumps to this label must be inside
1861      *    the sequence, otherwise we cannot remove the PHA/PLA.
1862      */
1863     unsigned I = 0;
1864     while (I < CS_GetEntryCount (S)) {
1865
1866         CodeEntry* X;
1867
1868         /* Get next entry */
1869         CodeEntry* E = CS_GetEntry (S, I);
1870
1871         switch (State) {
1872
1873             case Searching:
1874                 if (E->OPC == OP65_PHA) {
1875                     /* Found start of sequence */
1876                     Push  = I;
1877                     ChgA  = 0;
1878                     State = FoundPush;
1879                 }
1880                 break;
1881
1882             case FoundPush:
1883                 if (E->OPC == OP65_PHA) {
1884                     /* Inner push/pop, restart */
1885                     Push = I;
1886                     ChgA = 0;
1887                 } else if (E->OPC == OP65_PLA) {
1888                     /* Found a matching pop */
1889                     Pop = I;
1890                     /* Check that the block between Push and Pop is a basic
1891                      * block (one entry, one exit). Otherwise ignore it.
1892                      */
1893                     if (CS_IsBasicBlock (S, Push, Pop)) {
1894                         State = FoundPop;
1895                     } else {
1896                         /* Go into searching mode again */
1897                         State = Searching;
1898                     }
1899                 } else if (E->Chg & REG_A) {
1900                     ChgA = 1;
1901                 }
1902                 break;
1903
1904             case FoundPop:
1905                 /* We're at the instruction after the PLA.
1906                  * Check for the following conditions:
1907                  *   - If this instruction is a store of A, and A is not used
1908                  *     later, we may replace the PHA by the store and remove
1909                  *     pla if several other conditions are met.
1910                  *   - If this instruction is not a conditional branch, and A
1911                  *     is either unused later, or not changed by the code
1912                  *     between push and pop, we may remove PHA and PLA.
1913                  */
1914                 if (E->OPC == OP65_STA                  &&
1915                     !RegAUsed (S, I+1)                  &&
1916                     !MemAccess (S, Push+1, Pop-1, E)) {
1917
1918                     /* Insert a STA after the PHA */
1919                     X = NewCodeEntry (E->OPC, E->AM, E->Arg, E->JumpTo, E->LI);
1920                     CS_InsertEntry (S, X, Push+1);
1921
1922                     /* Remove the PHA instead */
1923                     CS_DelEntry (S, Push);
1924
1925                     /* Remove the PLA/STA sequence */
1926                     CS_DelEntries (S, Pop, 2);
1927
1928                     /* Correct I so we continue with the next insn */
1929                     I -= 2;
1930
1931                     /* Remember we had changes */
1932                     ++Changes;
1933
1934                 } else if ((E->Info & OF_CBRA) == 0     &&
1935                            (!RegAUsed (S, I) || !ChgA)) {
1936
1937                     /* We can remove the PHA and PLA instructions */
1938                     CS_DelEntry (S, Pop);
1939                     CS_DelEntry (S, Push);
1940
1941                     /* Correct I so we continue with the next insn */
1942                     I -= 2;
1943
1944                     /* Remember we had changes */
1945                     ++Changes;
1946
1947                 }
1948                 /* Go into search mode again */
1949                 State = Searching;
1950                 break;
1951
1952         }
1953
1954         /* Next entry */
1955         ++I;
1956     }
1957
1958     /* Return the number of changes made */
1959     return Changes;
1960 }
1961
1962
1963
1964 unsigned OptPrecalc (CodeSeg* S)
1965 /* Replace immediate operations with the accu where the current contents are
1966  * known by a load of the final value.
1967  */
1968 {
1969     unsigned Changes = 0;
1970     unsigned I;
1971
1972     /* Generate register info for this step */
1973     CS_GenRegInfo (S);
1974
1975     /* Walk over the entries */
1976     I = 0;
1977     while (I < CS_GetEntryCount (S)) {
1978
1979         /* Get next entry */
1980         CodeEntry* E = CS_GetEntry (S, I);
1981
1982         /* Get pointers to the input and output registers of the insn */
1983         const RegContents* Out = &E->RI->Out;
1984         const RegContents* In  = &E->RI->In;
1985
1986         /* Argument for LDn and flag */
1987         const char* Arg = 0;
1988         opc_t OPC = OP65_LDA;
1989
1990         /* Handle the different instructions */
1991         switch (E->OPC) {
1992
1993             case OP65_LDA:
1994                 if (E->AM != AM65_IMM && RegValIsKnown (Out->RegA)) {
1995                     /* Result of load is known */
1996                     Arg = MakeHexArg (Out->RegA);
1997                 }
1998                 break;
1999
2000             case OP65_LDX:
2001                 if (E->AM != AM65_IMM && RegValIsKnown (Out->RegX)) {
2002                     /* Result of load is known but register is X */
2003                     Arg = MakeHexArg (Out->RegX);
2004                     OPC = OP65_LDX;
2005                 }
2006                 break;
2007
2008             case OP65_LDY:
2009                 if (E->AM != AM65_IMM && RegValIsKnown (Out->RegY)) {
2010                     /* Result of load is known but register is Y */
2011                     Arg = MakeHexArg (Out->RegY);
2012                     OPC = OP65_LDY;
2013                 }
2014                 break;
2015
2016             case OP65_EOR:
2017                 if (RegValIsKnown (Out->RegA)) {
2018                     /* Accu op zp with known contents */
2019                     Arg = MakeHexArg (Out->RegA);
2020                 }
2021                 break;
2022
2023             case OP65_ADC:
2024             case OP65_SBC:
2025                 /* If this is an operation with an immediate operand of zero,
2026                  * and the register is zero, the operation won't give us any
2027                  * results we don't already have (including the flags), so
2028                  * remove it. Something like this is generated as a result of
2029                  * a compare where parts of the values are known to be zero.
2030                  */
2031                 if (In->RegA == 0 && CE_IsKnownImm (E, 0x00)) {
2032                     /* 0-0 or 0+0 -> remove */
2033                     CS_DelEntry (S, I);
2034                     ++Changes;
2035                 }
2036                 break;
2037
2038             case OP65_AND:
2039                 if (CE_IsKnownImm (E, 0xFF)) {
2040                     /* AND with 0xFF, remove */
2041                     CS_DelEntry (S, I);
2042                     ++Changes;
2043                 } else if (CE_IsKnownImm (E, 0x00)) {
2044                     /* AND with 0x00, replace by lda #$00 */
2045                     Arg = MakeHexArg (0x00);
2046                 } else if (RegValIsKnown (Out->RegA)) {
2047                     /* Accu AND zp with known contents */
2048                     Arg = MakeHexArg (Out->RegA);
2049                 } else if (In->RegA == 0xFF) {
2050                     /* AND but A contains 0xFF - replace by lda */
2051                     CE_ReplaceOPC (E, OP65_LDA);
2052                     ++Changes;
2053                 }
2054                 break;
2055
2056             case OP65_ORA:
2057                 if (CE_IsKnownImm (E, 0x00)) {
2058                     /* ORA with zero, remove */
2059                     CS_DelEntry (S, I);
2060                     ++Changes;
2061                 } else if (CE_IsKnownImm (E, 0xFF)) {
2062                     /* ORA with 0xFF, replace by lda #$ff */
2063                     Arg = MakeHexArg (0xFF);
2064                 } else if (RegValIsKnown (Out->RegA)) {
2065                     /* Accu AND zp with known contents */
2066                     Arg = MakeHexArg (Out->RegA);
2067                 } else if (In->RegA == 0) {
2068                     /* ORA but A contains 0x00 - replace by lda */
2069                     CE_ReplaceOPC (E, OP65_LDA);
2070                     ++Changes;
2071                 }
2072                 break;
2073
2074             default:
2075                 break;
2076
2077         }
2078
2079         /* Check if we have to replace the insn by LDA */
2080         if (Arg) {
2081             CodeEntry* X = NewCodeEntry (OPC, AM65_IMM, Arg, 0, E->LI);
2082             CS_InsertEntry (S, X, I+1);
2083             CS_DelEntry (S, I);
2084             ++Changes;
2085         }
2086
2087         /* Next entry */
2088         ++I;
2089     }
2090
2091     /* Free register info */
2092     CS_FreeRegInfo (S);
2093
2094     /* Return the number of changes made */
2095     return Changes;
2096 }
2097
2098
2099
2100 /*****************************************************************************/
2101 /*                           Optimize branch types                           */
2102 /*****************************************************************************/
2103
2104
2105
2106 unsigned OptBranchDist (CodeSeg* S)
2107 /* Change branches for the distance needed. */
2108 {
2109     unsigned Changes = 0;
2110
2111     /* Walk over the entries */
2112     unsigned I = 0;
2113     while (I < CS_GetEntryCount (S)) {
2114
2115         /* Get next entry */
2116         CodeEntry* E = CS_GetEntry (S, I);
2117
2118         /* Check if it's a conditional branch to a local label. */
2119         if (E->Info & OF_CBRA) {
2120
2121             /* Is this a branch to a local symbol? */
2122             if (E->JumpTo != 0) {
2123
2124                 /* Check if the branch distance is short */
2125                 int IsShort = IsShortDist (GetBranchDist (S, I, E->JumpTo->Owner));
2126
2127                 /* Make the branch short/long according to distance */
2128                 if ((E->Info & OF_LBRA) == 0 && !IsShort) {
2129                     /* Short branch but long distance */
2130                     CE_ReplaceOPC (E, MakeLongBranch (E->OPC));
2131                     ++Changes;
2132                 } else if ((E->Info & OF_LBRA) != 0 && IsShort) {
2133                     /* Long branch but short distance */
2134                     CE_ReplaceOPC (E, MakeShortBranch (E->OPC));
2135                     ++Changes;
2136                 }
2137
2138             } else if ((E->Info & OF_LBRA) == 0) {
2139
2140                 /* Short branch to external symbol - make it long */
2141                 CE_ReplaceOPC (E, MakeLongBranch (E->OPC));
2142                 ++Changes;
2143
2144             }
2145
2146         } else if ((CPUIsets[CPU] & CPU_ISET_65SC02) != 0 &&
2147                    (E->Info & OF_UBRA) != 0               &&
2148                    E->JumpTo != 0                         &&
2149                    IsShortDist (GetBranchDist (S, I, E->JumpTo->Owner))) {
2150
2151             /* The jump is short and may be replaced by a BRA on the 65C02 CPU */
2152             CE_ReplaceOPC (E, OP65_BRA);
2153             ++Changes;
2154         }
2155
2156         /* Next entry */
2157         ++I;
2158
2159     }
2160
2161     /* Return the number of changes made */
2162     return Changes;
2163 }
2164
2165
2166
2167 /*****************************************************************************/
2168 /*                          Optimize indirect loads                          */
2169 /*****************************************************************************/
2170
2171
2172
2173 unsigned OptIndLoads1 (CodeSeg* S)
2174 /* Change
2175  *
2176  *     lda      (zp),y
2177  *
2178  * into
2179  *
2180  *     lda      (zp,x)
2181  *
2182  * provided that x and y are both zero.
2183  */
2184 {
2185     unsigned Changes = 0;
2186     unsigned I;
2187
2188     /* Generate register info for this step */
2189     CS_GenRegInfo (S);
2190
2191     /* Walk over the entries */
2192     I = 0;
2193     while (I < CS_GetEntryCount (S)) {
2194
2195         /* Get next entry */
2196         CodeEntry* E = CS_GetEntry (S, I);
2197
2198         /* Check if it's what we're looking for */
2199         if (E->OPC == OP65_LDA          &&
2200             E->AM == AM65_ZP_INDY       &&
2201             E->RI->In.RegY == 0         &&
2202             E->RI->In.RegX == 0) {
2203
2204             /* Replace by the same insn with other addressing mode */
2205             CodeEntry* X = NewCodeEntry (E->OPC, AM65_ZPX_IND, E->Arg, 0, E->LI);
2206             CS_InsertEntry (S, X, I+1);
2207
2208             /* Remove the old insn */
2209             CS_DelEntry (S, I);
2210             ++Changes;
2211         }
2212
2213         /* Next entry */
2214         ++I;
2215
2216     }
2217
2218     /* Free register info */
2219     CS_FreeRegInfo (S);
2220
2221     /* Return the number of changes made */
2222     return Changes;
2223 }
2224
2225
2226
2227 unsigned OptIndLoads2 (CodeSeg* S)
2228 /* Change
2229  *
2230  *     lda      (zp,x)
2231  *
2232  * into
2233  *
2234  *     lda      (zp),y
2235  *
2236  * provided that x and y are both zero.
2237  */
2238 {
2239     unsigned Changes = 0;
2240     unsigned I;
2241
2242     /* Generate register info for this step */
2243     CS_GenRegInfo (S);
2244
2245     /* Walk over the entries */
2246     I = 0;
2247     while (I < CS_GetEntryCount (S)) {
2248
2249         /* Get next entry */
2250         CodeEntry* E = CS_GetEntry (S, I);
2251
2252         /* Check if it's what we're looking for */
2253         if (E->OPC == OP65_LDA          &&
2254             E->AM == AM65_ZPX_IND       &&
2255             E->RI->In.RegY == 0         &&
2256             E->RI->In.RegX == 0) {
2257
2258             /* Replace by the same insn with other addressing mode */
2259             CodeEntry* X = NewCodeEntry (E->OPC, AM65_ZP_INDY, E->Arg, 0, E->LI);
2260             CS_InsertEntry (S, X, I+1);
2261
2262             /* Remove the old insn */
2263             CS_DelEntry (S, I);
2264             ++Changes;
2265         }
2266
2267         /* Next entry */
2268         ++I;
2269
2270     }
2271
2272     /* Free register info */
2273     CS_FreeRegInfo (S);
2274
2275     /* Return the number of changes made */
2276     return Changes;
2277 }
2278
2279
2280