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