]> git.sur5r.net Git - cc65/blob - src/cc65/coptind.c
b80610b56b83858fd1ff04b9937014bdc336b566
[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, and a matching label, which
568          * is not attached to the jump itself
569          */
570         if (E2 != 0                     &&
571             (E2->Info & OF_UBRA) != 0   &&
572             E2->JumpTo                  &&
573             E2->JumpTo->Owner != E2) {
574
575             /* Get the entry preceeding the branch target */
576             T1 = CS_GetPrevEntry (S, CS_GetEntryIndex (S, E2->JumpTo->Owner));
577             if (T1 == 0) {
578                 /* There is no such entry */
579                 goto NextEntry;
580             }
581
582             /* Get the entry preceeding the jump */
583             E1 = CS_GetEntry (S, I);
584
585             /* Check if both preceeding instructions are identical */
586             if (!CodeEntriesAreEqual (E1, T1)) {
587                 /* Not equal, try next */
588                 goto NextEntry;
589             }
590
591             /* Get the label for the instruction preceeding the jump target.
592              * This routine will create a new label if the instruction does
593              * not already have one.
594              */
595             TL1 = CS_GenLabel (S, T1);
596
597             /* Change the jump target to point to this new label */
598             CS_MoveLabelRef (S, E2, TL1);
599
600             /* If the instruction preceeding the jump has labels attached,
601              * move references to this label to the new label.
602              */
603             if (CE_HasLabel (E1)) {
604                 CS_MoveLabels (S, E1, T1);
605             }
606
607             /* Remove the entry preceeding the jump */
608             CS_DelEntry (S, I);
609
610             /* Remember, we had changes */
611             ++Changes;
612
613         } else {
614 NextEntry:
615             /* Next entry */
616             ++I;
617         }
618     }
619
620     /* Return the number of changes made */
621     return Changes;
622 }
623
624
625
626 unsigned OptJumpTarget2 (CodeSeg* S)
627 /* If a bcs jumps to a sec insn or a bcc jumps to clc, skip this insn, since
628  * it's job is already done.
629  */
630 {
631     unsigned Changes = 0;
632
633     /* Walk over the entries */
634     unsigned I = 0;
635     while (I < CS_GetEntryCount (S)) {
636
637         /* OP that may be skipped */
638         opc_t OPC;
639
640         /* Jump target insn, old and new */
641         CodeEntry* T;
642         CodeEntry* N;
643
644         /* New jump label */
645         CodeLabel* L;
646
647         /* Get next entry */
648         CodeEntry* E = CS_GetEntry (S, I);
649
650         /* Check if this is a bcc insn */
651         if (E->OPC == OP65_BCC || E->OPC == OP65_JCC) {
652             OPC = OP65_CLC;
653         } else if (E->OPC == OP65_BCS || E->OPC == OP65_JCS) {
654             OPC = OP65_SEC;
655         } else {
656             /* Not what we're looking for */
657             goto NextEntry;
658         }
659
660         /* Must have a jump target */
661         if (E->JumpTo == 0) {
662             goto NextEntry;
663         }
664
665         /* Get the owner insn of the jump target and check if it's the one, we
666          * will skip if present.
667          */
668         T = E->JumpTo->Owner;
669         if (T->OPC != OPC) {
670             goto NextEntry;
671         }
672
673         /* Get the entry following the branch target */
674         N = CS_GetNextEntry (S, CS_GetEntryIndex (S, T));
675         if (N == 0) {
676             /* There is no such entry */
677             goto NextEntry;
678         }
679
680         /* Get the label for the instruction following the jump target.
681          * This routine will create a new label if the instruction does
682          * not already have one.
683          */
684         L = CS_GenLabel (S, N);
685
686         /* Change the jump target to point to this new label */
687         CS_MoveLabelRef (S, E, L);
688
689         /* Remember that we had changes */
690         ++Changes;
691
692 NextEntry:
693         /* Next entry */
694         ++I;
695     }
696
697     /* Return the number of changes made */
698     return Changes;
699 }
700
701
702
703 /*****************************************************************************/
704 /*                       Optimize conditional branches                       */
705 /*****************************************************************************/
706
707
708
709 unsigned OptCondBranches1 (CodeSeg* S)
710 /* Performs several optimization steps:
711  *
712  *  - If an immidiate load of a register is followed by a conditional jump that
713  *    is never taken because the load of the register sets the flags in such a
714  *    manner, remove the conditional branch.
715  *  - If the conditional branch is always taken because of the register load,
716  *    replace it by a jmp.
717  *  - If a conditional branch jumps around an unconditional branch, remove the
718  *    conditional branch and make the jump a conditional branch with the
719  *    inverse condition of the first one.
720  */
721 {
722     unsigned Changes = 0;
723
724     /* Walk over the entries */
725     unsigned I = 0;
726     while (I < CS_GetEntryCount (S)) {
727
728         CodeEntry* N;
729         CodeLabel* L;
730
731         /* Get next entry */
732         CodeEntry* E = CS_GetEntry (S, I);
733
734         /* Check if it's a register load */
735         if ((E->Info & OF_LOAD) != 0              &&  /* It's a load instruction */
736             E->AM == AM65_IMM                     &&  /* ..with immidiate addressing */
737             (E->Flags & CEF_NUMARG) != 0          &&  /* ..and a numeric argument. */
738             (N = CS_GetNextEntry (S, I)) != 0     &&  /* There is a following entry */
739             (N->Info & OF_CBRA) != 0              &&  /* ..which is a conditional branch */
740             !CE_HasLabel (N)) {               /* ..and does not have a label */
741
742             /* Get the branch condition */
743             bc_t BC = GetBranchCond (N->OPC);
744
745             /* Check the argument against the branch condition */
746             if ((BC == BC_EQ && E->Num != 0)            ||
747                 (BC == BC_NE && E->Num == 0)            ||
748                 (BC == BC_PL && (E->Num & 0x80) != 0)   ||
749                 (BC == BC_MI && (E->Num & 0x80) == 0)) {
750
751                 /* Remove the conditional branch */
752                 CS_DelEntry (S, I+1);
753
754                 /* Remember, we had changes */
755                 ++Changes;
756
757             } else if ((BC == BC_EQ && E->Num == 0)             ||
758                        (BC == BC_NE && E->Num != 0)             ||
759                        (BC == BC_PL && (E->Num & 0x80) == 0)    ||
760                        (BC == BC_MI && (E->Num & 0x80) != 0)) {
761
762                 /* The branch is always taken, replace it by a jump */
763                 CE_ReplaceOPC (N, OP65_JMP);
764
765                 /* Remember, we had changes */
766                 ++Changes;
767             }
768
769         }
770
771         if ((E->Info & OF_CBRA) != 0              &&  /* It's a conditional branch */
772             (L = E->JumpTo) != 0                  &&  /* ..referencing a local label */
773             (N = CS_GetNextEntry (S, I)) != 0     &&  /* There is a following entry */
774             (N->Info & OF_UBRA) != 0              &&  /* ..which is an uncond branch, */
775             !CE_HasLabel (N)                      &&  /* ..has no label attached */
776             L->Owner == CS_GetNextEntry (S, I+1)) {/* ..and jump target follows */
777
778             /* Replace the jump by a conditional branch with the inverse branch
779              * condition than the branch around it.
780              */
781             CE_ReplaceOPC (N, GetInverseBranch (E->OPC));
782
783             /* Remove the conditional branch */
784             CS_DelEntry (S, I);
785
786             /* Remember, we had changes */
787             ++Changes;
788
789         }
790
791         /* Next entry */
792         ++I;
793
794     }
795
796     /* Return the number of changes made */
797     return Changes;
798 }
799
800
801
802 unsigned OptCondBranches2 (CodeSeg* S)
803 /* If on entry to a "rol a" instruction the accu is zero, and a beq/bne follows,
804  * we can remove the rol and branch on the state of the carry flag.
805  */
806 {
807     unsigned Changes = 0;
808     unsigned I;
809
810     /* Generate register info for this step */
811     CS_GenRegInfo (S);
812
813     /* Walk over the entries */
814     I = 0;
815     while (I < CS_GetEntryCount (S)) {
816
817         CodeEntry* N;
818
819         /* Get next entry */
820         CodeEntry* E = CS_GetEntry (S, I);
821
822         /* Check if it's a rol insn with A in accu and a branch follows */
823         if (E->OPC == OP65_ROL                  &&
824             E->AM == AM65_ACC                   &&
825             E->RI->In.RegA == 0                 &&
826             !CE_HasLabel (E)                    &&
827             (N = CS_GetNextEntry (S, I)) != 0   &&
828             (N->Info & OF_ZBRA) != 0            &&
829             !RegAUsed (S, I+1)) {
830
831             /* Replace the branch condition */
832             switch (GetBranchCond (N->OPC)) {
833                 case BC_EQ:     CE_ReplaceOPC (N, OP65_JCC); break;
834                 case BC_NE:     CE_ReplaceOPC (N, OP65_JCS); break;
835                 default:        Internal ("Unknown branch condition in OptCondBranches2");
836             }
837
838             /* Delete the rol insn */
839             CS_DelEntry (S, I);
840
841             /* Remember, we had changes */
842             ++Changes;
843         }
844
845         /* Next entry */
846         ++I;
847     }
848
849     /* Free register info */
850     CS_FreeRegInfo (S);
851
852     /* Return the number of changes made */
853     return Changes;
854 }
855
856
857
858 /*****************************************************************************/
859 /*                      Remove unused loads and stores                       */
860 /*****************************************************************************/
861
862
863
864 unsigned OptUnusedLoads (CodeSeg* S)
865 /* Remove loads of registers where the value loaded is not used later. */
866 {
867     unsigned Changes = 0;
868
869     /* Walk over the entries */
870     unsigned I = 0;
871     while (I < CS_GetEntryCount (S)) {
872
873         CodeEntry* N;
874
875         /* Get next entry */
876         CodeEntry* E = CS_GetEntry (S, I);
877
878         /* Check if it's a register load or transfer insn */
879         if ((E->Info & (OF_LOAD | OF_XFR | OF_REG_INCDEC)) != 0         &&
880             (N = CS_GetNextEntry (S, I)) != 0                           &&
881             !CE_UseLoadFlags (N)) {
882
883             /* Check which sort of load or transfer it is */
884             unsigned R;
885             switch (E->OPC) {
886                 case OP65_DEA:
887                 case OP65_INA:
888                 case OP65_LDA:
889                 case OP65_TXA:
890                 case OP65_TYA:  R = REG_A;      break;
891                 case OP65_DEX:
892                 case OP65_INX:
893                 case OP65_LDX:
894                 case OP65_TAX:  R = REG_X;      break;
895                 case OP65_DEY:
896                 case OP65_INY:
897                 case OP65_LDY:
898                 case OP65_TAY:  R = REG_Y;      break;
899                 default:        goto NextEntry;         /* OOPS */
900             }
901
902             /* Get register usage and check if the register value is used later */
903             if ((GetRegInfo (S, I+1, R) & R) == 0) {
904
905                 /* Register value is not used, remove the load */
906                 CS_DelEntry (S, I);
907
908                 /* Remember, we had changes. Account the deleted entry in I. */
909                 ++Changes;
910                 --I;
911
912             }
913         }
914
915 NextEntry:
916         /* Next entry */
917         ++I;
918
919     }
920
921     /* Return the number of changes made */
922     return Changes;
923 }
924
925
926
927 unsigned OptUnusedStores (CodeSeg* S)
928 /* Remove stores into zero page registers that aren't used later */
929 {
930     unsigned Changes = 0;
931
932     /* Walk over the entries */
933     unsigned I = 0;
934     while (I < CS_GetEntryCount (S)) {
935
936         /* Get next entry */
937         CodeEntry* E = CS_GetEntry (S, I);
938
939         /* Check if it's a register load or transfer insn */
940         if ((E->Info & OF_STORE) != 0    &&
941             E->AM == AM65_ZP             &&
942             (E->Chg & REG_ZP) != 0) {
943
944             /* Check for the zero page location. We know that there cannot be
945              * more than one zero page location involved in the store.
946              */
947             unsigned R = E->Chg & REG_ZP;
948
949             /* Get register usage and check if the register value is used later */
950             if ((GetRegInfo (S, I+1, R) & R) == 0) {
951
952                 /* Register value is not used, remove the load */
953                 CS_DelEntry (S, I);
954
955                 /* Remember, we had changes */
956                 ++Changes;
957
958                 /* Continue with next insn */
959                 continue;
960             }
961         }
962
963         /* Next entry */
964         ++I;
965
966     }
967
968     /* Return the number of changes made */
969     return Changes;
970 }
971
972
973
974 unsigned OptDupLoads (CodeSeg* S)
975 /* Remove loads of registers where the value loaded is already in the register. */
976 {
977     unsigned Changes = 0;
978     unsigned I;
979
980     /* Generate register info for this step */
981     CS_GenRegInfo (S);
982
983     /* Walk over the entries */
984     I = 0;
985     while (I < CS_GetEntryCount (S)) {
986
987         CodeEntry* N;
988
989         /* Get next entry */
990         CodeEntry* E = CS_GetEntry (S, I);
991
992         /* Assume we won't delete the entry */
993         int Delete = 0;
994
995         /* Get a pointer to the input registers of the insn */
996         const RegContents* In  = &E->RI->In;
997
998         /* Handle the different instructions */
999         switch (E->OPC) {
1000
1001             case OP65_LDA:
1002                 if (RegValIsKnown (In->RegA)          && /* Value of A is known */
1003                     CE_IsKnownImm (E, In->RegA)       && /* Value to be loaded is known */
1004                     (N = CS_GetNextEntry (S, I)) != 0 && /* There is a next entry */
1005                     !CE_UseLoadFlags (N)) {              /* Which does not use the flags */
1006                     Delete = 1;
1007                 }
1008                 break;
1009
1010             case OP65_LDX:
1011                 if (RegValIsKnown (In->RegX)          && /* Value of X is known */
1012                     CE_IsKnownImm (E, In->RegX)       && /* 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_LDY:
1020                 if (RegValIsKnown (In->RegY)          && /* Value of Y is known */
1021                     CE_IsKnownImm (E, In->RegY)       && /* 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_STA:
1029                 /* If we store into a known zero page location, and this
1030                  * location does already contain the value to be stored,
1031                  * remove the store.
1032                  */
1033                 if (RegValIsKnown (In->RegA)          && /* Value of A is known */
1034                     E->AM == AM65_ZP                  && /* Store into zp */
1035                     In->RegA == ZPRegVal (E->Chg, In)) { /* Value identical */
1036
1037                     Delete = 1;
1038                 }
1039                 break;
1040
1041             case OP65_STX:
1042                 /* If we store into a known zero page location, and this
1043                  * location does already contain the value to be stored,
1044                  * remove the store.
1045                  */
1046                 if (RegValIsKnown (In->RegX)          && /* Value of A is known */
1047                     E->AM == AM65_ZP                  && /* Store into zp */
1048                     In->RegX == ZPRegVal (E->Chg, In)) { /* Value identical */
1049
1050                     Delete = 1;
1051
1052                 /* If the value in the X register is known and the same as
1053                  * that in the A register, replace the store by a STA. The
1054                  * optimizer will then remove the load instruction for X
1055                  * later. STX does support the zeropage,y addressing mode,
1056                  * so be sure to check for that.
1057                  */
1058                 } else if (RegValIsKnown (In->RegX)   &&
1059                            In->RegX == In->RegA       &&
1060                            E->AM != AM65_ABSY         &&
1061                            E->AM != AM65_ZPY) {
1062                     /* Use the A register instead */
1063                     CE_ReplaceOPC (E, OP65_STA);
1064                 }
1065                 break;
1066
1067             case OP65_STY:
1068                 /* If we store into a known zero page location, and this
1069                  * location does already contain the value to be stored,
1070                  * remove the store.
1071                  */
1072                 if (RegValIsKnown (In->RegY)          && /* Value of Y is known */
1073                     E->AM == AM65_ZP                  && /* Store into zp */
1074                     In->RegY == ZPRegVal (E->Chg, In)) { /* Value identical */
1075
1076                     Delete = 1;
1077
1078                 /* If the value in the Y register is known and the same as
1079                  * that in the A register, replace the store by a STA. The
1080                  * optimizer will then remove the load instruction for Y
1081                  * later. If replacement by A is not possible try a
1082                  * replacement by X, but check for invalid addressing modes
1083                  * in this case.
1084                  */
1085                 } else if (RegValIsKnown (In->RegY)) {
1086                     if (In->RegY == In->RegA) {
1087                         CE_ReplaceOPC (E, OP65_STA);
1088                     } else if (In->RegY == In->RegX   &&
1089                                E->AM != AM65_ABSX     &&
1090                                E->AM != AM65_ZPX) {
1091                         CE_ReplaceOPC (E, OP65_STX);
1092                     }
1093                 }
1094                 break;
1095
1096             case OP65_STZ:
1097                 /* If we store into a known zero page location, and this
1098                  * location does already contain the value to be stored,
1099                  * remove the store.
1100                  */
1101                 if ((CPUIsets[CPU] & CPU_ISET_65SC02) != 0 && E->AM == AM65_ZP) {
1102                     if (ZPRegVal (E->Chg, In) == 0) {
1103                         Delete = 1;
1104                     }
1105                 }
1106                 break;
1107
1108             case OP65_TAX:
1109                 if (RegValIsKnown (In->RegA)          &&
1110                     In->RegA == In->RegX              &&
1111                     (N = CS_GetNextEntry (S, I)) != 0 &&
1112                     !CE_UseLoadFlags (N)) {
1113                     /* Value is identical and not followed by a branch */
1114                     Delete = 1;
1115                 }
1116                 break;
1117
1118             case OP65_TAY:
1119                 if (RegValIsKnown (In->RegA)            &&
1120                     In->RegA == In->RegY                &&
1121                     (N = CS_GetNextEntry (S, I)) != 0   &&
1122                     !CE_UseLoadFlags (N)) {
1123                     /* Value is identical and not followed by a branch */
1124                     Delete = 1;
1125                 }
1126                 break;
1127
1128             case OP65_TXA:
1129                 if (RegValIsKnown (In->RegX)            &&
1130                     In->RegX == In->RegA                &&
1131                     (N = CS_GetNextEntry (S, I)) != 0   &&
1132                     !CE_UseLoadFlags (N)) {
1133                     /* Value is identical and not followed by a branch */
1134                     Delete = 1;
1135                 }
1136                 break;
1137
1138             case OP65_TYA:
1139                 if (RegValIsKnown (In->RegY)            &&
1140                     In->RegY == In->RegA                &&
1141                     (N = CS_GetNextEntry (S, I)) != 0   &&
1142                     !CE_UseLoadFlags (N)) {
1143                     /* Value is identical and not followed by a branch */
1144                     Delete = 1;
1145                 }
1146                 break;
1147
1148             default:
1149                 break;
1150
1151         }
1152
1153         /* Delete the entry if requested */
1154         if (Delete) {
1155
1156             /* Register value is not used, remove the load */
1157             CS_DelEntry (S, I);
1158
1159             /* Remember, we had changes */
1160             ++Changes;
1161
1162         } else {
1163
1164             /* Next entry */
1165             ++I;
1166
1167         }
1168
1169     }
1170
1171     /* Free register info */
1172     CS_FreeRegInfo (S);
1173
1174     /* Return the number of changes made */
1175     return Changes;
1176 }
1177
1178
1179
1180 unsigned OptStoreLoad (CodeSeg* S)
1181 /* Remove a store followed by a load from the same location. */
1182 {
1183     unsigned Changes = 0;
1184
1185     /* Walk over the entries */
1186     unsigned I = 0;
1187     while (I < CS_GetEntryCount (S)) {
1188
1189         CodeEntry* N;
1190         CodeEntry* X;
1191
1192         /* Get next entry */
1193         CodeEntry* E = CS_GetEntry (S, I);
1194
1195         /* Check if it is a store instruction followed by a load from the
1196          * same address which is itself not followed by a conditional branch.
1197          */
1198         if ((E->Info & OF_STORE) != 0                       &&
1199             (N = CS_GetNextEntry (S, I)) != 0               &&
1200             !CE_HasLabel (N)                                &&
1201             E->AM == N->AM                                  &&
1202             ((E->OPC == OP65_STA && N->OPC == OP65_LDA) ||
1203              (E->OPC == OP65_STX && N->OPC == OP65_LDX) ||
1204              (E->OPC == OP65_STY && N->OPC == OP65_LDY))    &&
1205             strcmp (E->Arg, N->Arg) == 0                    &&
1206             (X = CS_GetNextEntry (S, I+1)) != 0             &&
1207             !CE_UseLoadFlags (X)) {
1208
1209             /* Register has already the correct value, remove the load */
1210             CS_DelEntry (S, I+1);
1211
1212             /* Remember, we had changes */
1213             ++Changes;
1214
1215         }
1216
1217         /* Next entry */
1218         ++I;
1219
1220     }
1221
1222     /* Return the number of changes made */
1223     return Changes;
1224 }
1225
1226
1227
1228 unsigned OptTransfers1 (CodeSeg* S)
1229 /* Remove transfers from one register to another and back */
1230 {
1231     unsigned Changes = 0;
1232
1233     /* Walk over the entries */
1234     unsigned I = 0;
1235     while (I < CS_GetEntryCount (S)) {
1236
1237         CodeEntry* N;
1238         CodeEntry* X;
1239         CodeEntry* P;
1240
1241         /* Get next entry */
1242         CodeEntry* E = CS_GetEntry (S, I);
1243
1244         /* Check if we have two transfer instructions */
1245         if ((E->Info & OF_XFR) != 0                 &&
1246             (N = CS_GetNextEntry (S, I)) != 0       &&
1247             !CE_HasLabel (N)                        &&
1248             (N->Info & OF_XFR) != 0) {
1249
1250             /* Check if it's a transfer and back */
1251             if ((E->OPC == OP65_TAX && N->OPC == OP65_TXA && !RegXUsed (S, I+2)) ||
1252                 (E->OPC == OP65_TAY && N->OPC == OP65_TYA && !RegYUsed (S, I+2)) ||
1253                 (E->OPC == OP65_TXA && N->OPC == OP65_TAX && !RegAUsed (S, I+2)) ||
1254                 (E->OPC == OP65_TYA && N->OPC == OP65_TAY && !RegAUsed (S, I+2))) {
1255
1256                 /* If the next insn is a conditional branch, check if the insn
1257                  * preceeding the first xfr will set the flags right, otherwise we
1258                  * may not remove the sequence.
1259                  */
1260                 if ((X = CS_GetNextEntry (S, I+1)) == 0) {
1261                     goto NextEntry;
1262                 }
1263                 if (CE_UseLoadFlags (X)) {
1264                     if (I == 0) {
1265                         /* No preceeding entry */
1266                         goto NextEntry;
1267                     }
1268                     P = CS_GetEntry (S, I-1);
1269                     if ((P->Info & OF_SETF) == 0) {
1270                         /* Does not set the flags */
1271                         goto NextEntry;
1272                     }
1273                 }
1274
1275                 /* Remove both transfers */
1276                 CS_DelEntry (S, I+1);
1277                 CS_DelEntry (S, I);
1278
1279                 /* Remember, we had changes */
1280                 ++Changes;
1281             }
1282         }
1283
1284 NextEntry:
1285         /* Next entry */
1286         ++I;
1287
1288     }
1289
1290     /* Return the number of changes made */
1291     return Changes;
1292 }
1293
1294
1295
1296 unsigned OptTransfers2 (CodeSeg* S)
1297 /* Replace loads followed by a register transfer by a load with the second
1298  * register if possible.
1299  */
1300 {
1301     unsigned Changes = 0;
1302
1303     /* Walk over the entries */
1304     unsigned I = 0;
1305     while (I < CS_GetEntryCount (S)) {
1306
1307         CodeEntry* N;
1308
1309         /* Get next entry */
1310         CodeEntry* E = CS_GetEntry (S, I);
1311
1312         /* Check if we have a load followed by a transfer where the loaded
1313          * register is not used later.
1314          */
1315         if ((E->Info & OF_LOAD) != 0                &&
1316             (N = CS_GetNextEntry (S, I)) != 0       &&
1317             !CE_HasLabel (N)                        &&
1318             (N->Info & OF_XFR) != 0                 &&
1319             GetRegInfo (S, I+2, E->Chg) != E->Chg) {
1320
1321             CodeEntry* X = 0;
1322
1323             if (E->OPC == OP65_LDA && N->OPC == OP65_TAX) {
1324                 /* LDA/TAX - check for the right addressing modes */
1325                 if (E->AM == AM65_IMM ||
1326                     E->AM == AM65_ZP  ||
1327                     E->AM == AM65_ABS ||
1328                     E->AM == AM65_ABSY) {
1329                     /* Replace */
1330                     X = NewCodeEntry (OP65_LDX, E->AM, E->Arg, 0, N->LI);
1331                 }
1332             } else if (E->OPC == OP65_LDA && N->OPC == OP65_TAY) {
1333                 /* LDA/TAY - check for the right addressing modes */
1334                 if (E->AM == AM65_IMM ||
1335                     E->AM == AM65_ZP  ||
1336                     E->AM == AM65_ZPX ||
1337                     E->AM == AM65_ABS ||
1338                     E->AM == AM65_ABSX) {
1339                     /* Replace */
1340                     X = NewCodeEntry (OP65_LDY, E->AM, E->Arg, 0, N->LI);
1341                 }
1342             } else if (E->OPC == OP65_LDY && N->OPC == OP65_TYA) {
1343                 /* LDY/TYA. LDA supports all addressing modes LDY does */
1344                 X = NewCodeEntry (OP65_LDA, E->AM, E->Arg, 0, N->LI);
1345             } else if (E->OPC == OP65_LDX && N->OPC == OP65_TXA) {
1346                 /* LDX/TXA. LDA doesn't support zp,y, so we must map it to
1347                  * abs,y instead.
1348                  */
1349                 am_t AM = (E->AM == AM65_ZPY)? AM65_ABSY : E->AM;
1350                 X = NewCodeEntry (OP65_LDA, AM, E->Arg, 0, N->LI);
1351             }
1352
1353             /* If we have a load entry, add it and remove the old stuff */
1354             if (X) {
1355                 CS_InsertEntry (S, X, I+2);
1356                 CS_DelEntries (S, I, 2);
1357                 ++Changes;
1358                 --I;    /* Correct for one entry less */
1359             }
1360         }
1361
1362         /* Next entry */
1363         ++I;
1364     }
1365
1366     /* Return the number of changes made */
1367     return Changes;
1368 }
1369
1370
1371
1372 unsigned OptTransfers3 (CodeSeg* S)
1373 /* Replace a register transfer followed by a store of the second register by a
1374  * store of the first register if this is possible.
1375  */
1376 {
1377     unsigned Changes      = 0;
1378     unsigned UsedRegs     = REG_NONE;   /* Track used registers */
1379     unsigned Xfer         = 0;          /* Index of transfer insn */
1380     unsigned Store        = 0;          /* Index of store insn */
1381     CodeEntry* XferEntry  = 0;          /* Pointer to xfer insn */
1382     CodeEntry* StoreEntry = 0;          /* Pointer to store insn */
1383
1384     enum {
1385         Initialize,
1386         Search,
1387         FoundXfer,
1388         FoundStore
1389     } State = Initialize;
1390
1391     /* Walk over the entries. Look for a xfer instruction that is followed by
1392      * a store later, where the value of the register is not used later.
1393      */
1394     unsigned I = 0;
1395     while (I < CS_GetEntryCount (S)) {
1396
1397         /* Get next entry */
1398         CodeEntry* E = CS_GetEntry (S, I);
1399
1400         switch (State) {
1401
1402             case Initialize:
1403                 /* Clear the list of used registers */
1404                 UsedRegs = REG_NONE;
1405                 /* FALLTHROUGH */
1406
1407             case Search:
1408                 if (E->Info & OF_XFR) {
1409                     /* Found start of sequence */
1410                     Xfer = I;
1411                     XferEntry = E;
1412                     State = FoundXfer;
1413                 }
1414                 break;
1415
1416             case FoundXfer:
1417                 /* If we find a conditional jump, abort the sequence, since
1418                  * handling them makes things really complicated.
1419                  */
1420                 if (E->Info & OF_CBRA) {
1421
1422                     /* Switch back to searching */
1423                     I = Xfer;
1424                     State = Initialize;
1425
1426                 /* Does this insn use the target register of the transfer? */
1427                 } else if ((E->Use & XferEntry->Chg) != 0) {
1428
1429                     /* It it's a store instruction, and the block is a basic
1430                      * block, proceed. Otherwise restart
1431                      */
1432                     if ((E->Info & OF_STORE) != 0       &&
1433                         CS_IsBasicBlock (S, Xfer, I)) {
1434                         Store = I;
1435                         StoreEntry = E;
1436                         State = FoundStore;
1437                     } else {
1438                         I = Xfer;
1439                         State = Initialize;
1440                     }
1441
1442                 /* Does this insn change the target register of the transfer? */
1443                 } else if (E->Chg & XferEntry->Chg) {
1444
1445                     /* We *may* add code here to remove the transfer, but I'm
1446                      * currently not sure about the consequences, so I won't
1447                      * do that and bail out instead.
1448                      */
1449                     I = Xfer;
1450                     State = Initialize;
1451
1452                 /* Does this insn have a label? */
1453                 } else if (CE_HasLabel (E)) {
1454
1455                     /* Too complex to handle - bail out */
1456                     I = Xfer;
1457                     State = Initialize;
1458
1459                 } else {
1460                     /* Track used registers */
1461                     UsedRegs |= E->Use;
1462                 }
1463                 break;
1464
1465             case FoundStore:
1466                 /* We are at the instruction behind the store. If the register
1467                  * isn't used later, and we have an address mode match, we can
1468                  * replace the transfer by a store and remove the store here.
1469                  */
1470                 if ((GetRegInfo (S, I, XferEntry->Chg) & XferEntry->Chg) == 0   &&
1471                     (StoreEntry->AM == AM65_ABS         ||
1472                      StoreEntry->AM == AM65_ZP)                                 &&
1473                     (StoreEntry->AM != AM65_ZP ||
1474                      (StoreEntry->Chg & UsedRegs) == 0)                         &&
1475                     !MemAccess (S, Xfer+1, Store-1, StoreEntry->Arg)) {
1476
1477                     /* Generate the replacement store insn */
1478                     CodeEntry* X = 0;
1479                     switch (XferEntry->OPC) {
1480
1481                         case OP65_TXA:
1482                             X = NewCodeEntry (OP65_STX,
1483                                               StoreEntry->AM,
1484                                               StoreEntry->Arg,
1485                                               0,
1486                                               StoreEntry->LI);
1487                             break;
1488
1489                         case OP65_TAX:
1490                             X = NewCodeEntry (OP65_STA,
1491                                               StoreEntry->AM,
1492                                               StoreEntry->Arg,
1493                                               0,
1494                                               StoreEntry->LI);
1495                             break;
1496
1497                         case OP65_TYA:
1498                             X = NewCodeEntry (OP65_STY,
1499                                               StoreEntry->AM,
1500                                               StoreEntry->Arg,
1501                                               0,
1502                                               StoreEntry->LI);
1503                             break;
1504
1505                         case OP65_TAY:
1506                             X = NewCodeEntry (OP65_STA,
1507                                               StoreEntry->AM,
1508                                               StoreEntry->Arg,
1509                                               0,
1510                                               StoreEntry->LI);
1511                             break;
1512
1513                         default:
1514                             break;
1515                     }
1516
1517                     /* If we have a replacement store, change the code */
1518                     if (X) {
1519                         /* Insert after the xfer insn */
1520                         CS_InsertEntry (S, X, Xfer+1);
1521
1522                         /* Remove the xfer instead */
1523                         CS_DelEntry (S, Xfer);
1524
1525                         /* Remove the final store */
1526                         CS_DelEntry (S, Store);
1527
1528                         /* Correct I so we continue with the next insn */
1529                         I -= 2;
1530
1531                         /* Remember we had changes */
1532                         ++Changes;
1533                     } else {
1534                         /* Restart after last xfer insn */
1535                         I = Xfer;
1536                     }
1537                 } else {
1538                     /* Restart after last xfer insn */
1539                     I = Xfer;
1540                 }
1541                 State = Initialize;
1542                 break;
1543
1544         }
1545
1546         /* Next entry */
1547         ++I;
1548     }
1549
1550     /* Return the number of changes made */
1551     return Changes;
1552 }
1553
1554
1555
1556 unsigned OptTransfers4 (CodeSeg* S)
1557 /* Replace a load of a register followed by a transfer insn of the same register
1558  * by a load of the second register if possible.
1559  */
1560 {
1561     unsigned Changes      = 0;
1562     unsigned Load         = 0;  /* Index of load insn */
1563     unsigned Xfer         = 0;  /* Index of transfer insn */
1564     CodeEntry* LoadEntry  = 0;  /* Pointer to load insn */
1565     CodeEntry* XferEntry  = 0;  /* Pointer to xfer insn */
1566
1567     enum {
1568         Search,
1569         FoundLoad,
1570         FoundXfer
1571     } State = Search;
1572
1573     /* Walk over the entries. Look for a load instruction that is followed by
1574      * a load later.
1575      */
1576     unsigned I = 0;
1577     while (I < CS_GetEntryCount (S)) {
1578
1579         /* Get next entry */
1580         CodeEntry* E = CS_GetEntry (S, I);
1581
1582         switch (State) {
1583
1584             case Search:
1585                 if (E->Info & OF_LOAD) {
1586                     /* Found start of sequence */
1587                     Load = I;
1588                     LoadEntry = E;
1589                     State = FoundLoad;
1590                 }
1591                 break;
1592
1593             case FoundLoad:
1594                 /* If we find a conditional jump, abort the sequence, since
1595                  * handling them makes things really complicated.
1596                  */
1597                 if (E->Info & OF_CBRA) {
1598
1599                     /* Switch back to searching */
1600                     I = Load;
1601                     State = Search;
1602
1603                 /* Does this insn use the target register of the load? */
1604                 } else if ((E->Use & LoadEntry->Chg) != 0) {
1605
1606                     /* It it's a xfer instruction, and the block is a basic
1607                      * block, proceed. Otherwise restart
1608                      */
1609                     if ((E->Info & OF_XFR) != 0       &&
1610                         CS_IsBasicBlock (S, Load, I)) {
1611                         Xfer = I;
1612                         XferEntry = E;
1613                         State = FoundXfer;
1614                     } else {
1615                         I = Load;
1616                         State = Search;
1617                     }
1618
1619                 /* Does this insn change the target register of the load? */
1620                 } else if (E->Chg & LoadEntry->Chg) {
1621
1622                     /* We *may* add code here to remove the load, but I'm
1623                      * currently not sure about the consequences, so I won't
1624                      * do that and bail out instead.
1625                      */
1626                     I = Load;
1627                     State = Search;
1628                 }
1629                 break;
1630
1631             case FoundXfer:
1632                 /* We are at the instruction behind the xfer. If the register
1633                  * isn't used later, and we have an address mode match, we can
1634                  * replace the transfer by a load and remove the initial load.
1635                  */
1636                 if ((GetRegInfo (S, I, LoadEntry->Chg) & LoadEntry->Chg) == 0   &&
1637                     (LoadEntry->AM == AM65_ABS          ||
1638                      LoadEntry->AM == AM65_ZP           ||
1639                      LoadEntry->AM == AM65_IMM)                                 &&
1640                     !MemAccess (S, Load+1, Xfer-1, LoadEntry->Arg)) {
1641
1642                     /* Generate the replacement load insn */
1643                     CodeEntry* X = 0;
1644                     switch (XferEntry->OPC) {
1645
1646                         case OP65_TXA:
1647                         case OP65_TYA:
1648                             X = NewCodeEntry (OP65_LDA,
1649                                               LoadEntry->AM,
1650                                               LoadEntry->Arg,
1651                                               0,
1652                                               LoadEntry->LI);
1653                             break;
1654
1655                         case OP65_TAX:
1656                             X = NewCodeEntry (OP65_LDX,
1657                                               LoadEntry->AM,
1658                                               LoadEntry->Arg,
1659                                               0,
1660                                               LoadEntry->LI);
1661                             break;
1662
1663                         case OP65_TAY:
1664                             X = NewCodeEntry (OP65_LDY,
1665                                               LoadEntry->AM,
1666                                               LoadEntry->Arg,
1667                                               0,
1668                                               LoadEntry->LI);
1669                             break;
1670
1671                         default:
1672                             break;
1673                     }
1674
1675                     /* If we have a replacement load, change the code */
1676                     if (X) {
1677                         /* Insert after the xfer insn */
1678                         CS_InsertEntry (S, X, Xfer+1);
1679
1680                         /* Remove the xfer instead */
1681                         CS_DelEntry (S, Xfer);
1682
1683                         /* Remove the initial load */
1684                         CS_DelEntry (S, Load);
1685
1686                         /* Correct I so we continue with the next insn */
1687                         I -= 2;
1688
1689                         /* Remember we had changes */
1690                         ++Changes;
1691                     } else {
1692                         /* Restart after last xfer insn */
1693                         I = Xfer;
1694                     }
1695                 } else {
1696                     /* Restart after last xfer insn */
1697                     I = Xfer;
1698                 }
1699                 State = Search;
1700                 break;
1701
1702         }
1703
1704         /* Next entry */
1705         ++I;
1706     }
1707
1708     /* Return the number of changes made */
1709     return Changes;
1710 }
1711
1712
1713
1714 unsigned OptPushPop (CodeSeg* S)
1715 /* Remove a PHA/PLA sequence were A is not used later */
1716 {
1717     unsigned Changes = 0;
1718     unsigned Push    = 0;       /* Index of push insn */
1719     unsigned Pop     = 0;       /* Index of pop insn */
1720     enum {
1721         Searching,
1722         FoundPush,
1723         FoundPop
1724     } State = Searching;
1725
1726     /* Walk over the entries. Look for a push instruction that is followed by
1727      * a pop later, where the pop is not followed by an conditional branch,
1728      * and where the value of the A register is not used later on.
1729      * Look out for the following problems:
1730      *
1731      *  - There may be another PHA/PLA inside the sequence: Restart it.
1732      *  - If the PLA has a label, all jumps to this label must be inside
1733      *    the sequence, otherwise we cannot remove the PHA/PLA.
1734      */
1735     unsigned I = 0;
1736     while (I < CS_GetEntryCount (S)) {
1737
1738         CodeEntry* X;
1739
1740         /* Get next entry */
1741         CodeEntry* E = CS_GetEntry (S, I);
1742
1743         switch (State) {
1744
1745             case Searching:
1746                 if (E->OPC == OP65_PHA) {
1747                     /* Found start of sequence */
1748                     Push  = I;
1749                     State = FoundPush;
1750                 }
1751                 break;
1752
1753             case FoundPush:
1754                 if (E->OPC == OP65_PHA) {
1755                     /* Inner push/pop, restart */
1756                     Push = I;
1757                 } else if (E->OPC == OP65_PLA) {
1758                     /* Found a matching pop */
1759                     Pop = I;
1760                     /* Check that the block between Push and Pop is a basic
1761                      * block (one entry, one exit). Otherwise ignore it.
1762                      */
1763                     if (CS_IsBasicBlock (S, Push, Pop)) {
1764                         State = FoundPop;
1765                     } else {
1766                         /* Go into searching mode again */
1767                         State = Searching;
1768                     }
1769                 }
1770                 break;
1771
1772             case FoundPop:
1773                 /* We're at the instruction after the PLA.
1774                  * Check for the following conditions:
1775                  *   - If this instruction is a store of A, and A is not used
1776                  *     later, we may replace the PHA by the store and remove
1777                  *     pla if several other conditions are met.
1778                  *   - If this instruction is not a conditional branch, and A
1779                  *     is unused later, we may remove PHA and PLA.
1780                  */
1781                 if (E->OPC == OP65_STA                  &&
1782                     !RegAUsed (S, I+1)                  &&
1783                     !MemAccess (S, Push+1, Pop-1, E->Arg)) {
1784
1785                     /* Insert a STA after the PHA */
1786                     X = NewCodeEntry (E->OPC, E->AM, E->Arg, E->JumpTo, E->LI);
1787                     CS_InsertEntry (S, X, Push+1);
1788
1789                     /* Remove the PHA instead */
1790                     CS_DelEntry (S, Push);
1791
1792                     /* Remove the PLA/STA sequence */
1793                     CS_DelEntries (S, Pop, 2);
1794
1795                     /* Correct I so we continue with the next insn */
1796                     I -= 2;
1797
1798                     /* Remember we had changes */
1799                     ++Changes;
1800
1801                 } else if ((E->Info & OF_CBRA) == 0     &&
1802                            !RegAUsed (S, I)) {
1803
1804                     /* We can remove the PHA and PLA instructions */
1805                     CS_DelEntry (S, Pop);
1806                     CS_DelEntry (S, Push);
1807
1808                     /* Correct I so we continue with the next insn */
1809                     I -= 2;
1810
1811                     /* Remember we had changes */
1812                     ++Changes;
1813
1814                 }
1815                 /* Go into search mode again */
1816                 State = Searching;
1817                 break;
1818
1819         }
1820
1821         /* Next entry */
1822         ++I;
1823     }
1824
1825     /* Return the number of changes made */
1826     return Changes;
1827 }
1828
1829
1830
1831 unsigned OptPrecalc (CodeSeg* S)
1832 /* Replace immediate operations with the accu where the current contents are
1833  * known by a load of the final value.
1834  */
1835 {
1836     unsigned Changes = 0;
1837     unsigned I;
1838
1839     /* Generate register info for this step */
1840     CS_GenRegInfo (S);
1841
1842     /* Walk over the entries */
1843     I = 0;
1844     while (I < CS_GetEntryCount (S)) {
1845
1846         /* Get next entry */
1847         CodeEntry* E = CS_GetEntry (S, I);
1848
1849         /* Get pointers to the input and output registers of the insn */
1850         const RegContents* Out = &E->RI->Out;
1851         const RegContents* In  = &E->RI->In;
1852
1853         /* Argument for LDn and flag */
1854         const char* Arg = 0;
1855         opc_t OPC = OP65_LDA;
1856
1857         /* Handle the different instructions */
1858         switch (E->OPC) {
1859
1860             case OP65_LDA:
1861                 if (E->AM != AM65_IMM && RegValIsKnown (Out->RegA)) {
1862                     /* Result of load is known */
1863                     Arg = MakeHexArg (Out->RegA);
1864                 }
1865                 break;
1866
1867             case OP65_LDX:
1868                 if (E->AM != AM65_IMM && RegValIsKnown (Out->RegX)) {
1869                     /* Result of load is known but register is X */
1870                     Arg = MakeHexArg (Out->RegX);
1871                     OPC = OP65_LDX;
1872                 }
1873                 break;
1874
1875             case OP65_LDY:
1876                 if (E->AM != AM65_IMM && RegValIsKnown (Out->RegY)) {
1877                     /* Result of load is known but register is Y */
1878                     Arg = MakeHexArg (Out->RegY);
1879                     OPC = OP65_LDY;
1880                 }
1881                 break;
1882
1883             case OP65_ASL:
1884             case OP65_EOR:
1885             case OP65_LSR:
1886                 if (RegValIsKnown (Out->RegA)) {
1887                     /* Accu op zp with known contents */
1888                     Arg = MakeHexArg (Out->RegA);
1889                 }
1890                 break;
1891
1892             case OP65_ADC:
1893             case OP65_SBC:
1894                 /* If this is an operation with an immediate operand of zero,
1895                  * and the register is zero, the operation won't give us any
1896                  * results we don't already have (including the flags), so
1897                  * remove it. Something like this is generated as a result of
1898                  * a compare where parts of the values are known to be zero.
1899                  */
1900                 if (In->RegA == 0 && CE_IsKnownImm (E, 0x00)) {
1901                     /* 0-0 or 0+0 -> remove */
1902                     CS_DelEntry (S, I);
1903                     ++Changes;
1904                 } else if (RegValIsKnown (Out->RegA)) {
1905                     /* Accu op zp with known contents */
1906                     Arg = MakeHexArg (Out->RegA);
1907                 }
1908                 break;
1909
1910             case OP65_AND:
1911                 if (CE_IsKnownImm (E, 0xFF)) {
1912                     /* AND with 0xFF, remove */
1913                     CS_DelEntry (S, I);
1914                     ++Changes;
1915                 } else if (CE_IsKnownImm (E, 0x00)) {
1916                     /* AND with 0x00, replace by lda #$00 */
1917                     Arg = MakeHexArg (0x00);
1918                 } else if (RegValIsKnown (Out->RegA)) {
1919                     /* Accu AND zp with known contents */
1920                     Arg = MakeHexArg (Out->RegA);
1921                 } else if (In->RegA == 0xFF) {
1922                     /* AND but A contains 0xFF - replace by lda */
1923                     CE_ReplaceOPC (E, OP65_LDA);
1924                     ++Changes;
1925                 }
1926                 break;
1927
1928             case OP65_ORA:
1929                 if (CE_IsKnownImm (E, 0x00)) {
1930                     /* ORA with zero, remove */
1931                     CS_DelEntry (S, I);
1932                     ++Changes;
1933                 } else if (CE_IsKnownImm (E, 0xFF)) {
1934                     /* ORA with 0xFF, replace by lda #$ff */
1935                     Arg = MakeHexArg (0xFF);
1936                 } else if (RegValIsKnown (Out->RegA)) {
1937                     /* Accu AND zp with known contents */
1938                     Arg = MakeHexArg (Out->RegA);
1939                 } else if (In->RegA == 0) {
1940                     /* ORA but A contains 0x00 - replace by lda */
1941                     CE_ReplaceOPC (E, OP65_LDA);
1942                     ++Changes;
1943                 }
1944                 break;
1945
1946             default:
1947                 break;
1948
1949         }
1950
1951         /* Check if we have to replace the insn by LDA */
1952         if (Arg) {
1953             CodeEntry* X = NewCodeEntry (OPC, AM65_IMM, Arg, 0, E->LI);
1954             CS_InsertEntry (S, X, I+1);
1955             CS_DelEntry (S, I);
1956             ++Changes;
1957         }
1958
1959         /* Next entry */
1960         ++I;
1961     }
1962
1963     /* Free register info */
1964     CS_FreeRegInfo (S);
1965
1966     /* Return the number of changes made */
1967     return Changes;
1968 }
1969
1970
1971
1972 /*****************************************************************************/
1973 /*                           Optimize branch types                           */
1974 /*****************************************************************************/
1975
1976
1977
1978 unsigned OptBranchDist (CodeSeg* S)
1979 /* Change branches for the distance needed. */
1980 {
1981     unsigned Changes = 0;
1982
1983     /* Walk over the entries */
1984     unsigned I = 0;
1985     while (I < CS_GetEntryCount (S)) {
1986
1987         /* Get next entry */
1988         CodeEntry* E = CS_GetEntry (S, I);
1989
1990         /* Check if it's a conditional branch to a local label. */
1991         if (E->Info & OF_CBRA) {
1992
1993             /* Is this a branch to a local symbol? */
1994             if (E->JumpTo != 0) {
1995
1996                 /* Check if the branch distance is short */
1997                 int IsShort = IsShortDist (GetBranchDist (S, I, E->JumpTo->Owner));
1998
1999                 /* Make the branch short/long according to distance */
2000                 if ((E->Info & OF_LBRA) == 0 && !IsShort) {
2001                     /* Short branch but long distance */
2002                     CE_ReplaceOPC (E, MakeLongBranch (E->OPC));
2003                     ++Changes;
2004                 } else if ((E->Info & OF_LBRA) != 0 && IsShort) {
2005                     /* Long branch but short distance */
2006                     CE_ReplaceOPC (E, MakeShortBranch (E->OPC));
2007                     ++Changes;
2008                 }
2009
2010             } else if ((E->Info & OF_LBRA) == 0) {
2011
2012                 /* Short branch to external symbol - make it long */
2013                 CE_ReplaceOPC (E, MakeLongBranch (E->OPC));
2014                 ++Changes;
2015
2016             }
2017
2018         } else if ((CPUIsets[CPU] & CPU_ISET_65SC02) != 0 &&
2019                    (E->Info & OF_UBRA) != 0               &&
2020                    E->JumpTo != 0                         &&
2021                    IsShortDist (GetBranchDist (S, I, E->JumpTo->Owner))) {
2022
2023             /* The jump is short and may be replaced by a BRA on the 65C02 CPU */
2024             CE_ReplaceOPC (E, OP65_BRA);
2025             ++Changes;
2026         }
2027
2028         /* Next entry */
2029         ++I;
2030
2031     }
2032
2033     /* Return the number of changes made */
2034     return Changes;
2035 }
2036
2037
2038