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