]> git.sur5r.net Git - cc65/blob - src/cc65/coptind.c
eee07f879fced780f3c765c3c9e90819bc853dd0
[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 OptCondBranches (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 /*****************************************************************************/
803 /*                      Remove unused loads and stores                       */
804 /*****************************************************************************/
805
806
807
808 unsigned OptUnusedLoads (CodeSeg* S)
809 /* Remove loads of registers where the value loaded is not used later. */
810 {
811     unsigned Changes = 0;
812
813     /* Walk over the entries */
814     unsigned 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 register load or transfer insn */
823         if ((E->Info & (OF_LOAD | OF_XFR | OF_REG_INCDEC)) != 0         &&
824             (N = CS_GetNextEntry (S, I)) != 0                           &&
825             !CE_UseLoadFlags (N)) {
826
827             /* Check which sort of load or transfer it is */
828             unsigned R;
829             switch (E->OPC) {
830                 case OP65_DEA:
831                 case OP65_INA:
832                 case OP65_LDA:
833                 case OP65_TXA:
834                 case OP65_TYA:  R = REG_A;      break;
835                 case OP65_DEX:
836                 case OP65_INX:
837                 case OP65_LDX:
838                 case OP65_TAX:  R = REG_X;      break;
839                 case OP65_DEY:
840                 case OP65_INY:
841                 case OP65_LDY:
842                 case OP65_TAY:  R = REG_Y;      break;
843                 default:        goto NextEntry;         /* OOPS */
844             }
845
846             /* Get register usage and check if the register value is used later */
847             if ((GetRegInfo (S, I+1, R) & R) == 0) {
848
849                 /* Register value is not used, remove the load */
850                 CS_DelEntry (S, I);
851
852                 /* Remember, we had changes. Account the deleted entry in I. */
853                 ++Changes;
854                 --I;
855
856             }
857         }
858
859 NextEntry:
860         /* Next entry */
861         ++I;
862
863     }
864
865     /* Return the number of changes made */
866     return Changes;
867 }
868
869
870
871 unsigned OptUnusedStores (CodeSeg* S)
872 /* Remove stores into zero page registers that aren't used later */
873 {
874     unsigned Changes = 0;
875
876     /* Walk over the entries */
877     unsigned I = 0;
878     while (I < CS_GetEntryCount (S)) {
879
880         /* Get next entry */
881         CodeEntry* E = CS_GetEntry (S, I);
882
883         /* Check if it's a register load or transfer insn */
884         if ((E->Info & OF_STORE) != 0    &&
885             E->AM == AM65_ZP             &&
886             (E->Chg & REG_ZP) != 0) {
887
888             /* Check for the zero page location. We know that there cannot be
889              * more than one zero page location involved in the store.
890              */
891             unsigned R = E->Chg & REG_ZP;
892
893             /* Get register usage and check if the register value is used later */
894             if ((GetRegInfo (S, I+1, R) & R) == 0) {
895
896                 /* Register value is not used, remove the load */
897                 CS_DelEntry (S, I);
898
899                 /* Remember, we had changes */
900                 ++Changes;
901
902                 /* Continue with next insn */
903                 continue;
904             }
905         }
906
907         /* Next entry */
908         ++I;
909
910     }
911
912     /* Return the number of changes made */
913     return Changes;
914 }
915
916
917
918 unsigned OptDupLoads (CodeSeg* S)
919 /* Remove loads of registers where the value loaded is already in the register. */
920 {
921     unsigned Changes = 0;
922     unsigned I;
923
924     /* Generate register info for this step */
925     CS_GenRegInfo (S);
926
927     /* Walk over the entries */
928     I = 0;
929     while (I < CS_GetEntryCount (S)) {
930
931         CodeEntry* N;
932
933         /* Get next entry */
934         CodeEntry* E = CS_GetEntry (S, I);
935
936         /* Assume we won't delete the entry */
937         int Delete = 0;
938
939         /* Get a pointer to the input registers of the insn */
940         const RegContents* In  = &E->RI->In;
941
942         /* Handle the different instructions */
943         switch (E->OPC) {
944
945             case OP65_LDA:
946                 if (RegValIsKnown (In->RegA)          && /* Value of A is known */
947                     CE_IsKnownImm (E, In->RegA)       && /* Value to be loaded is known */
948                     (N = CS_GetNextEntry (S, I)) != 0 && /* There is a next entry */
949                     !CE_UseLoadFlags (N)) {              /* Which does not use the flags */
950                     Delete = 1;
951                 }
952                 break;
953
954             case OP65_LDX:
955                 if (RegValIsKnown (In->RegX)          && /* Value of X is known */
956                     CE_IsKnownImm (E, In->RegX)       && /* Value to be loaded is known */
957                     (N = CS_GetNextEntry (S, I)) != 0 && /* There is a next entry */
958                     !CE_UseLoadFlags (N)) {              /* Which does not use the flags */
959                     Delete = 1;
960                 }
961                 break;
962
963             case OP65_LDY:
964                 if (RegValIsKnown (In->RegY)          && /* Value of Y is known */
965                     CE_IsKnownImm (E, In->RegY)       && /* Value to be loaded is known */
966                     (N = CS_GetNextEntry (S, I)) != 0 && /* There is a next entry */
967                     !CE_UseLoadFlags (N)) {              /* Which does not use the flags */
968                     Delete = 1;
969                 }
970                 break;
971
972             case OP65_STA:
973                 /* If we store into a known zero page location, and this
974                  * location does already contain the value to be stored,
975                  * remove the store.
976                  */
977                 if (RegValIsKnown (In->RegA)          && /* Value of A is known */
978                     E->AM == AM65_ZP                  && /* Store into zp */
979                     In->RegA == ZPRegVal (E->Chg, In)) { /* Value identical */
980
981                     Delete = 1;
982                 }
983                 break;
984
985             case OP65_STX:
986                 /* If we store into a known zero page location, and this
987                  * location does already contain the value to be stored,
988                  * remove the store.
989                  */
990                 if (RegValIsKnown (In->RegX)          && /* Value of A is known */
991                     E->AM == AM65_ZP                  && /* Store into zp */
992                     In->RegX == ZPRegVal (E->Chg, In)) { /* Value identical */
993
994                     Delete = 1;
995
996                 /* If the value in the X register is known and the same as
997                  * that in the A register, replace the store by a STA. The
998                  * optimizer will then remove the load instruction for X
999                  * later. STX does support the zeropage,y addressing mode,
1000                  * so be sure to check for that.
1001                  */
1002                 } else if (RegValIsKnown (In->RegX)   &&
1003                            In->RegX == In->RegA       &&
1004                            E->AM != AM65_ABSY         &&
1005                            E->AM != AM65_ZPY) {
1006                     /* Use the A register instead */
1007                     CE_ReplaceOPC (E, OP65_STA);
1008                 }
1009                 break;
1010
1011             case OP65_STY:
1012                 /* If we store into a known zero page location, and this
1013                  * location does already contain the value to be stored,
1014                  * remove the store.
1015                  */
1016                 if (RegValIsKnown (In->RegY)          && /* Value of Y is known */
1017                     E->AM == AM65_ZP                  && /* Store into zp */
1018                     In->RegY == ZPRegVal (E->Chg, In)) { /* Value identical */
1019
1020                     Delete = 1;
1021
1022                 /* If the value in the Y register is known and the same as
1023                  * that in the A register, replace the store by a STA. The
1024                  * optimizer will then remove the load instruction for Y
1025                  * later. If replacement by A is not possible try a
1026                  * replacement by X, but check for invalid addressing modes
1027                  * in this case.
1028                  */
1029                 } else if (RegValIsKnown (In->RegY)) {
1030                     if (In->RegY == In->RegA) {
1031                         CE_ReplaceOPC (E, OP65_STA);
1032                     } else if (In->RegY == In->RegX   &&
1033                                E->AM != AM65_ABSX     &&
1034                                E->AM != AM65_ZPX) {
1035                         CE_ReplaceOPC (E, OP65_STX);
1036                     }
1037                 }
1038                 break;
1039
1040             case OP65_STZ:
1041                 /* If we store into a known zero page location, and this
1042                  * location does already contain the value to be stored,
1043                  * remove the store.
1044                  */
1045                 if ((CPUIsets[CPU] & CPU_ISET_65SC02) != 0 && E->AM == AM65_ZP) {
1046                     if (ZPRegVal (E->Chg, In) == 0) {
1047                         Delete = 1;
1048                     }
1049                 }
1050                 break;
1051
1052             case OP65_TAX:
1053                 if (RegValIsKnown (In->RegA)          &&
1054                     In->RegA == In->RegX              &&
1055                     (N = CS_GetNextEntry (S, I)) != 0 &&
1056                     !CE_UseLoadFlags (N)) {
1057                     /* Value is identical and not followed by a branch */
1058                     Delete = 1;
1059                 }
1060                 break;
1061
1062             case OP65_TAY:
1063                 if (RegValIsKnown (In->RegA)            &&
1064                     In->RegA == In->RegY                &&
1065                     (N = CS_GetNextEntry (S, I)) != 0   &&
1066                     !CE_UseLoadFlags (N)) {
1067                     /* Value is identical and not followed by a branch */
1068                     Delete = 1;
1069                 }
1070                 break;
1071
1072             case OP65_TXA:
1073                 if (RegValIsKnown (In->RegX)            &&
1074                     In->RegX == In->RegA                &&
1075                     (N = CS_GetNextEntry (S, I)) != 0   &&
1076                     !CE_UseLoadFlags (N)) {
1077                     /* Value is identical and not followed by a branch */
1078                     Delete = 1;
1079                 }
1080                 break;
1081
1082             case OP65_TYA:
1083                 if (RegValIsKnown (In->RegY)            &&
1084                     In->RegY == In->RegA                &&
1085                     (N = CS_GetNextEntry (S, I)) != 0   &&
1086                     !CE_UseLoadFlags (N)) {
1087                     /* Value is identical and not followed by a branch */
1088                     Delete = 1;
1089                 }
1090                 break;
1091
1092             default:
1093                 break;
1094
1095         }
1096
1097         /* Delete the entry if requested */
1098         if (Delete) {
1099
1100             /* Register value is not used, remove the load */
1101             CS_DelEntry (S, I);
1102
1103             /* Remember, we had changes */
1104             ++Changes;
1105
1106         } else {
1107
1108             /* Next entry */
1109             ++I;
1110
1111         }
1112
1113     }
1114
1115     /* Free register info */
1116     CS_FreeRegInfo (S);
1117
1118     /* Return the number of changes made */
1119     return Changes;
1120 }
1121
1122
1123
1124 unsigned OptStoreLoad (CodeSeg* S)
1125 /* Remove a store followed by a load from the same location. */
1126 {
1127     unsigned Changes = 0;
1128
1129     /* Walk over the entries */
1130     unsigned I = 0;
1131     while (I < CS_GetEntryCount (S)) {
1132
1133         CodeEntry* N;
1134         CodeEntry* X;
1135
1136         /* Get next entry */
1137         CodeEntry* E = CS_GetEntry (S, I);
1138
1139         /* Check if it is a store instruction followed by a load from the
1140          * same address which is itself not followed by a conditional branch.
1141          */
1142         if ((E->Info & OF_STORE) != 0                       &&
1143             (N = CS_GetNextEntry (S, I)) != 0               &&
1144             !CE_HasLabel (N)                                &&
1145             E->AM == N->AM                                  &&
1146             ((E->OPC == OP65_STA && N->OPC == OP65_LDA) ||
1147              (E->OPC == OP65_STX && N->OPC == OP65_LDX) ||
1148              (E->OPC == OP65_STY && N->OPC == OP65_LDY))    &&
1149             strcmp (E->Arg, N->Arg) == 0                    &&
1150             (X = CS_GetNextEntry (S, I+1)) != 0             &&
1151             !CE_UseLoadFlags (X)) {
1152
1153             /* Register has already the correct value, remove the load */
1154             CS_DelEntry (S, I+1);
1155
1156             /* Remember, we had changes */
1157             ++Changes;
1158
1159         }
1160
1161         /* Next entry */
1162         ++I;
1163
1164     }
1165
1166     /* Return the number of changes made */
1167     return Changes;
1168 }
1169
1170
1171
1172 unsigned OptTransfers1 (CodeSeg* S)
1173 /* Remove transfers from one register to another and back */
1174 {
1175     unsigned Changes = 0;
1176
1177     /* Walk over the entries */
1178     unsigned I = 0;
1179     while (I < CS_GetEntryCount (S)) {
1180
1181         CodeEntry* N;
1182         CodeEntry* X;
1183         CodeEntry* P;
1184
1185         /* Get next entry */
1186         CodeEntry* E = CS_GetEntry (S, I);
1187
1188         /* Check if we have two transfer instructions */
1189         if ((E->Info & OF_XFR) != 0                 &&
1190             (N = CS_GetNextEntry (S, I)) != 0       &&
1191             !CE_HasLabel (N)                        &&
1192             (N->Info & OF_XFR) != 0) {
1193
1194             /* Check if it's a transfer and back */
1195             if ((E->OPC == OP65_TAX && N->OPC == OP65_TXA && !RegXUsed (S, I+2)) ||
1196                 (E->OPC == OP65_TAY && N->OPC == OP65_TYA && !RegYUsed (S, I+2)) ||
1197                 (E->OPC == OP65_TXA && N->OPC == OP65_TAX && !RegAUsed (S, I+2)) ||
1198                 (E->OPC == OP65_TYA && N->OPC == OP65_TAY && !RegAUsed (S, I+2))) {
1199
1200                 /* If the next insn is a conditional branch, check if the insn
1201                  * preceeding the first xfr will set the flags right, otherwise we
1202                  * may not remove the sequence.
1203                  */
1204                 if ((X = CS_GetNextEntry (S, I+1)) == 0) {
1205                     goto NextEntry;
1206                 }
1207                 if (CE_UseLoadFlags (X)) {
1208                     if (I == 0) {
1209                         /* No preceeding entry */
1210                         goto NextEntry;
1211                     }
1212                     P = CS_GetEntry (S, I-1);
1213                     if ((P->Info & OF_SETF) == 0) {
1214                         /* Does not set the flags */
1215                         goto NextEntry;
1216                     }
1217                 }
1218
1219                 /* Remove both transfers */
1220                 CS_DelEntry (S, I+1);
1221                 CS_DelEntry (S, I);
1222
1223                 /* Remember, we had changes */
1224                 ++Changes;
1225             }
1226         }
1227
1228 NextEntry:
1229         /* Next entry */
1230         ++I;
1231
1232     }
1233
1234     /* Return the number of changes made */
1235     return Changes;
1236 }
1237
1238
1239
1240 unsigned OptTransfers2 (CodeSeg* S)
1241 /* Replace loads followed by a register transfer by a load with the second
1242  * register if possible.
1243  */
1244 {
1245     unsigned Changes = 0;
1246
1247     /* Walk over the entries */
1248     unsigned I = 0;
1249     while (I < CS_GetEntryCount (S)) {
1250
1251         CodeEntry* N;
1252
1253         /* Get next entry */
1254         CodeEntry* E = CS_GetEntry (S, I);
1255
1256         /* Check if we have a load followed by a transfer where the loaded
1257          * register is not used later.
1258          */
1259         if ((E->Info & OF_LOAD) != 0                &&
1260             (N = CS_GetNextEntry (S, I)) != 0       &&
1261             !CE_HasLabel (N)                        &&
1262             (N->Info & OF_XFR) != 0                 &&
1263             GetRegInfo (S, I+2, E->Chg) != E->Chg) {
1264
1265             CodeEntry* X = 0;
1266
1267             if (E->OPC == OP65_LDA && N->OPC == OP65_TAX) {
1268                 /* LDA/TAX - check for the right addressing modes */
1269                 if (E->AM == AM65_IMM ||
1270                     E->AM == AM65_ZP  ||
1271                     E->AM == AM65_ABS ||
1272                     E->AM == AM65_ABSY) {
1273                     /* Replace */
1274                     X = NewCodeEntry (OP65_LDX, E->AM, E->Arg, 0, N->LI);
1275                 }
1276             } else if (E->OPC == OP65_LDA && N->OPC == OP65_TAY) {
1277                 /* LDA/TAY - check for the right addressing modes */
1278                 if (E->AM == AM65_IMM ||
1279                     E->AM == AM65_ZP  ||
1280                     E->AM == AM65_ZPX ||
1281                     E->AM == AM65_ABS ||
1282                     E->AM == AM65_ABSX) {
1283                     /* Replace */
1284                     X = NewCodeEntry (OP65_LDY, E->AM, E->Arg, 0, N->LI);
1285                 }
1286             } else if (E->OPC == OP65_LDY && N->OPC == OP65_TYA) {
1287                 /* LDY/TYA. LDA supports all addressing modes LDY does */
1288                 X = NewCodeEntry (OP65_LDA, E->AM, E->Arg, 0, N->LI);
1289             } else if (E->OPC == OP65_LDX && N->OPC == OP65_TXA) {
1290                 /* LDX/TXA. LDA doesn't support zp,y, so we must map it to
1291                  * abs,y instead.
1292                  */
1293                 am_t AM = (E->AM == AM65_ZPY)? AM65_ABSY : E->AM;
1294                 X = NewCodeEntry (OP65_LDA, AM, E->Arg, 0, N->LI);
1295             }
1296
1297             /* If we have a load entry, add it and remove the old stuff */
1298             if (X) {
1299                 CS_InsertEntry (S, X, I+2);
1300                 CS_DelEntries (S, I, 2);
1301                 ++Changes;
1302                 --I;    /* Correct for one entry less */
1303             }
1304         }
1305
1306         /* Next entry */
1307         ++I;
1308     }
1309
1310     /* Return the number of changes made */
1311     return Changes;
1312 }
1313
1314
1315
1316 unsigned OptTransfers3 (CodeSeg* S)
1317 /* Replace a register transfer followed by a store of the second register by a
1318  * store of the first register if this is possible.
1319  */
1320 {
1321     unsigned Changes      = 0;
1322     unsigned Xfer         = 0;  /* Index of transfer insn */
1323     unsigned Store        = 0;  /* Index of store insn */
1324     CodeEntry* XferEntry  = 0;  /* Pointer to xfer insn */
1325     CodeEntry* StoreEntry = 0;  /* Pointer to store insn */
1326
1327     enum {
1328         Searching,
1329         FoundXfer,
1330         FoundStore
1331     } State = Searching;
1332
1333     /* Walk over the entries. Look for a xfer instruction that is followed by
1334      * a store later, where the value of the register is not used later.
1335      */
1336     unsigned I = 0;
1337     while (I < CS_GetEntryCount (S)) {
1338
1339         /* Get next entry */
1340         CodeEntry* E = CS_GetEntry (S, I);
1341
1342         switch (State) {
1343
1344             case Searching:
1345                 if (E->Info & OF_XFR) {
1346                     /* Found start of sequence */
1347                     Xfer = I;
1348                     XferEntry = E;
1349                     State = FoundXfer;
1350                 }
1351                 break;
1352
1353             case FoundXfer:
1354                 /* If we find a conditional jump, abort the sequence, since
1355                  * handling them makes things really complicated.
1356                  */
1357                 if (E->Info & OF_CBRA) {
1358
1359                     /* Switch back to searching */
1360                     I = Xfer;
1361                     State = Searching;
1362
1363                 /* Does this insn use the target register of the transfer? */
1364                 } else if ((E->Use & XferEntry->Chg) != 0) {
1365
1366                     /* It it's a store instruction, and the block is a basic
1367                      * block, proceed. Otherwise restart
1368                      */
1369                     if ((E->Info & OF_STORE) != 0       &&
1370                         CS_IsBasicBlock (S, Xfer, I)) {
1371                         Store = I;
1372                         StoreEntry = E;
1373                         State = FoundStore;
1374                     } else {
1375                         I = Xfer;
1376                         State = Searching;
1377                     }
1378
1379                 /* Does this insn change the target register of the transfer? */
1380                 } else if (E->Chg & XferEntry->Chg) {
1381
1382                     /* We *may* add code here to remove the transfer, but I'm
1383                      * currently not sure about the consequences, so I won't
1384                      * do that and bail out instead.
1385                      */
1386                     I = Xfer;
1387                     State = Searching;
1388
1389                 /* Does this insn have a label? */
1390                 } else if (CE_HasLabel (E)) {
1391
1392                     /* Too complex to handle - bail out */
1393                     I = Xfer;
1394                     State = Searching;
1395
1396                 }
1397                 break;
1398
1399             case FoundStore:
1400                 /* We are at the instruction behind the store. If the register
1401                  * isn't used later, and we have an address mode match, we can
1402                  * replace the transfer by a store and remove the store here.
1403                  */
1404                 if ((GetRegInfo (S, I, XferEntry->Chg) & XferEntry->Chg) == 0   &&
1405                     (StoreEntry->AM == AM65_ABS || StoreEntry->AM == AM65_ZP)   &&
1406                     !MemAccess (S, Xfer+1, Store-1, StoreEntry->Arg)) {
1407
1408                     /* Generate the replacement store insn */
1409                     CodeEntry* X = 0;
1410                     switch (XferEntry->OPC) {
1411
1412                         case OP65_TXA:
1413                             X = NewCodeEntry (OP65_STX,
1414                                               StoreEntry->AM,
1415                                               StoreEntry->Arg,
1416                                               0,
1417                                               StoreEntry->LI);
1418                             break;
1419
1420                         case OP65_TAX:
1421                             X = NewCodeEntry (OP65_STA,
1422                                               StoreEntry->AM,
1423                                               StoreEntry->Arg,
1424                                               0,
1425                                               StoreEntry->LI);
1426                             break;
1427
1428                         case OP65_TYA:
1429                             X = NewCodeEntry (OP65_STY,
1430                                               StoreEntry->AM,
1431                                               StoreEntry->Arg,
1432                                               0,
1433                                               StoreEntry->LI);
1434                             break;
1435
1436                         case OP65_TAY:
1437                             X = NewCodeEntry (OP65_STA,
1438                                               StoreEntry->AM,
1439                                               StoreEntry->Arg,
1440                                               0,
1441                                               StoreEntry->LI);
1442                             break;
1443
1444                         default:
1445                             break;
1446                     }
1447
1448                     /* If we have a replacement store, change the code */
1449                     if (X) {
1450                         /* Insert after the xfer insn */
1451                         CS_InsertEntry (S, X, Xfer+1);
1452
1453                         /* Remove the xfer instead */
1454                         CS_DelEntry (S, Xfer);
1455
1456                         /* Remove the final store */
1457                         CS_DelEntry (S, Store);
1458
1459                         /* Correct I so we continue with the next insn */
1460                         I -= 2;
1461
1462                         /* Remember we had changes */
1463                         ++Changes;
1464                     } else {
1465                         /* Restart after last xfer insn */
1466                         I = Xfer;
1467                     }
1468                 } else {
1469                     /* Restart after last xfer insn */
1470                     I = Xfer;
1471                 }
1472                 State = Searching;
1473                 break;
1474
1475         }
1476
1477         /* Next entry */
1478         ++I;
1479     }
1480
1481     /* Return the number of changes made */
1482     return Changes;
1483 }
1484
1485
1486
1487 unsigned OptTransfers4 (CodeSeg* S)
1488 /* Replace a load of a register followed by a transfer insn of the same register
1489  * by a load of the second register if possible.
1490  */
1491 {
1492     unsigned Changes      = 0;
1493     unsigned Load         = 0;  /* Index of load insn */
1494     unsigned Xfer         = 0;  /* Index of transfer insn */
1495     CodeEntry* LoadEntry  = 0;  /* Pointer to load insn */
1496     CodeEntry* XferEntry  = 0;  /* Pointer to xfer insn */
1497
1498     enum {
1499         Searching,
1500         FoundLoad,
1501         FoundXfer
1502     } State = Searching;
1503
1504     /* Walk over the entries. Look for a load instruction that is followed by
1505      * a load later.
1506      */
1507     unsigned I = 0;
1508     while (I < CS_GetEntryCount (S)) {
1509
1510         /* Get next entry */
1511         CodeEntry* E = CS_GetEntry (S, I);
1512
1513         switch (State) {
1514
1515             case Searching:
1516                 if (E->Info & OF_LOAD) {
1517                     /* Found start of sequence */
1518                     Load = I;
1519                     LoadEntry = E;
1520                     State = FoundLoad;
1521                 }
1522                 break;
1523
1524             case FoundLoad:
1525                 /* If we find a conditional jump, abort the sequence, since
1526                  * handling them makes things really complicated.
1527                  */
1528                 if (E->Info & OF_CBRA) {
1529
1530                     /* Switch back to searching */
1531                     I = Load;
1532                     State = Searching;
1533
1534                 /* Does this insn use the target register of the load? */
1535                 } else if ((E->Use & LoadEntry->Chg) != 0) {
1536
1537                     /* It it's a xfer instruction, and the block is a basic
1538                      * block, proceed. Otherwise restart
1539                      */
1540                     if ((E->Info & OF_XFR) != 0       &&
1541                         CS_IsBasicBlock (S, Load, I)) {
1542                         Xfer = I;
1543                         XferEntry = E;
1544                         State = FoundXfer;
1545                     } else {
1546                         I = Load;
1547                         State = Searching;
1548                     }
1549
1550                 /* Does this insn change the target register of the load? */
1551                 } else if (E->Chg & LoadEntry->Chg) {
1552
1553                     /* We *may* add code here to remove the load, but I'm
1554                      * currently not sure about the consequences, so I won't
1555                      * do that and bail out instead.
1556                      */
1557                     I = Load;
1558                     State = Searching;
1559                 }
1560                 break;
1561
1562             case FoundXfer:
1563                 /* We are at the instruction behind the xfer. If the register
1564                  * isn't used later, and we have an address mode match, we can
1565                  * replace the transfer by a load and remove the initial load.
1566                  */
1567                 if ((GetRegInfo (S, I, LoadEntry->Chg) & LoadEntry->Chg) == 0   &&
1568                     (LoadEntry->AM == AM65_ABS          ||
1569                      LoadEntry->AM == AM65_ZP           ||
1570                      LoadEntry->AM == AM65_IMM)                                 &&
1571                     !MemAccess (S, Load+1, Xfer-1, LoadEntry->Arg)) {
1572
1573                     /* Generate the replacement load insn */
1574                     CodeEntry* X = 0;
1575                     switch (XferEntry->OPC) {
1576
1577                         case OP65_TXA:
1578                         case OP65_TYA:
1579                             X = NewCodeEntry (OP65_LDA,
1580                                               LoadEntry->AM,
1581                                               LoadEntry->Arg,
1582                                               0,
1583                                               LoadEntry->LI);
1584                             break;
1585
1586                         case OP65_TAX:
1587                             X = NewCodeEntry (OP65_LDX,
1588                                               LoadEntry->AM,
1589                                               LoadEntry->Arg,
1590                                               0,
1591                                               LoadEntry->LI);
1592                             break;
1593
1594                         case OP65_TAY:
1595                             X = NewCodeEntry (OP65_LDY,
1596                                               LoadEntry->AM,
1597                                               LoadEntry->Arg,
1598                                               0,
1599                                               LoadEntry->LI);
1600                             break;
1601
1602                         default:
1603                             break;
1604                     }
1605
1606                     /* If we have a replacement load, change the code */
1607                     if (X) {
1608                         /* Insert after the xfer insn */
1609                         CS_InsertEntry (S, X, Xfer+1);
1610
1611                         /* Remove the xfer instead */
1612                         CS_DelEntry (S, Xfer);
1613
1614                         /* Remove the initial load */
1615                         CS_DelEntry (S, Load);
1616
1617                         /* Correct I so we continue with the next insn */
1618                         I -= 2;
1619
1620                         /* Remember we had changes */
1621                         ++Changes;
1622                     } else {
1623                         /* Restart after last xfer insn */
1624                         I = Xfer;
1625                     }
1626                 } else {
1627                     /* Restart after last xfer insn */
1628                     I = Xfer;
1629                 }
1630                 State = Searching;
1631                 break;
1632
1633         }
1634
1635         /* Next entry */
1636         ++I;
1637     }
1638
1639     /* Return the number of changes made */
1640     return Changes;
1641 }
1642
1643
1644
1645 unsigned OptPushPop (CodeSeg* S)
1646 /* Remove a PHA/PLA sequence were A is not used later */
1647 {
1648     unsigned Changes = 0;
1649     unsigned Push    = 0;       /* Index of push insn */
1650     unsigned Pop     = 0;       /* Index of pop insn */
1651     enum {
1652         Searching,
1653         FoundPush,
1654         FoundPop
1655     } State = Searching;
1656
1657     /* Walk over the entries. Look for a push instruction that is followed by
1658      * a pop later, where the pop is not followed by an conditional branch,
1659      * and where the value of the A register is not used later on.
1660      * Look out for the following problems:
1661      *
1662      *  - There may be another PHA/PLA inside the sequence: Restart it.
1663      *  - If the PLA has a label, all jumps to this label must be inside
1664      *    the sequence, otherwise we cannot remove the PHA/PLA.
1665      */
1666     unsigned I = 0;
1667     while (I < CS_GetEntryCount (S)) {
1668
1669         CodeEntry* X;
1670
1671         /* Get next entry */
1672         CodeEntry* E = CS_GetEntry (S, I);
1673
1674         switch (State) {
1675
1676             case Searching:
1677                 if (E->OPC == OP65_PHA) {
1678                     /* Found start of sequence */
1679                     Push  = I;
1680                     State = FoundPush;
1681                 }
1682                 break;
1683
1684             case FoundPush:
1685                 if (E->OPC == OP65_PHA) {
1686                     /* Inner push/pop, restart */
1687                     Push = I;
1688                 } else if (E->OPC == OP65_PLA) {
1689                     /* Found a matching pop */
1690                     Pop = I;
1691                     /* Check that the block between Push and Pop is a basic
1692                      * block (one entry, one exit). Otherwise ignore it.
1693                      */
1694                     if (CS_IsBasicBlock (S, Push, Pop)) {
1695                         State = FoundPop;
1696                     } else {
1697                         /* Go into searching mode again */
1698                         State = Searching;
1699                     }
1700                 }
1701                 break;
1702
1703             case FoundPop:
1704                 /* We're at the instruction after the PLA.
1705                  * Check for the following conditions:
1706                  *   - If this instruction is a store of A, and A is not used
1707                  *     later, we may replace the PHA by the store and remove
1708                  *     pla if several other conditions are met.
1709                  *   - If this instruction is not a conditional branch, and A
1710                  *     is unused later, we may remove PHA and PLA.
1711                  */
1712                 if (E->OPC == OP65_STA                  &&
1713                     !RegAUsed (S, I+1)                  &&
1714                     !MemAccess (S, Push+1, Pop-1, E->Arg)) {
1715
1716                     /* Insert a STA after the PHA */
1717                     X = NewCodeEntry (E->OPC, E->AM, E->Arg, E->JumpTo, E->LI);
1718                     CS_InsertEntry (S, X, Push+1);
1719
1720                     /* Remove the PHA instead */
1721                     CS_DelEntry (S, Push);
1722
1723                     /* Remove the PLA/STA sequence */
1724                     CS_DelEntries (S, Pop, 2);
1725
1726                     /* Correct I so we continue with the next insn */
1727                     I -= 2;
1728
1729                     /* Remember we had changes */
1730                     ++Changes;
1731
1732                 } else if ((E->Info & OF_CBRA) == 0     &&
1733                            !RegAUsed (S, I)) {
1734
1735                     /* We can remove the PHA and PLA instructions */
1736                     CS_DelEntry (S, Pop);
1737                     CS_DelEntry (S, Push);
1738
1739                     /* Correct I so we continue with the next insn */
1740                     I -= 2;
1741
1742                     /* Remember we had changes */
1743                     ++Changes;
1744
1745                 }
1746                 /* Go into search mode again */
1747                 State = Searching;
1748                 break;
1749
1750         }
1751
1752         /* Next entry */
1753         ++I;
1754     }
1755
1756     /* Return the number of changes made */
1757     return Changes;
1758 }
1759
1760
1761
1762 unsigned OptPrecalc (CodeSeg* S)
1763 /* Replace immediate operations with the accu where the current contents are
1764  * known by a load of the final value.
1765  */
1766 {
1767     unsigned Changes = 0;
1768     unsigned I;
1769
1770     /* Generate register info for this step */
1771     CS_GenRegInfo (S);
1772
1773     /* Walk over the entries */
1774     I = 0;
1775     while (I < CS_GetEntryCount (S)) {
1776
1777         /* Get next entry */
1778         CodeEntry* E = CS_GetEntry (S, I);
1779
1780         /* Get a pointer to the output registers of the insn */
1781         const RegContents* Out = &E->RI->Out;
1782
1783         /* Argument for LDn and flag */
1784         const char* Arg = 0;
1785         opc_t OPC = OP65_LDA;
1786
1787         /* Handle the different instructions */
1788         switch (E->OPC) {
1789
1790             case OP65_LDA:
1791                 if (E->AM != AM65_IMM && RegValIsKnown (Out->RegA)) {
1792                     /* Result of load is known */
1793                     Arg = MakeHexArg (Out->RegA);
1794                 }
1795                 break;
1796
1797             case OP65_LDX:
1798                 if (E->AM != AM65_IMM && RegValIsKnown (Out->RegX)) {
1799                     /* Result of load is known but register is X */
1800                     Arg = MakeHexArg (Out->RegX);
1801                     OPC = OP65_LDX;
1802                 }
1803                 break;
1804
1805             case OP65_LDY:
1806                 if (E->AM != AM65_IMM && RegValIsKnown (Out->RegY)) {
1807                     /* Result of load is known but register is Y */
1808                     Arg = MakeHexArg (Out->RegY);
1809                     OPC = OP65_LDY;
1810                 }
1811                 break;
1812
1813             case OP65_ADC:
1814             case OP65_ASL:
1815             case OP65_EOR:
1816             case OP65_LSR:
1817             case OP65_SBC:
1818                 if (RegValIsKnown (Out->RegA)) {
1819                     /* Accu op zp with known contents */
1820                     Arg = MakeHexArg (Out->RegA);
1821                 }
1822                 break;
1823
1824             case OP65_AND:
1825                 if (CE_IsKnownImm (E, 0xFF)) {
1826                     /* AND with 0xFF, remove */
1827                     CS_DelEntry (S, I);
1828                     ++Changes;
1829                 } else if (RegValIsKnown (Out->RegA)) {
1830                     /* Accu AND zp with known contents */
1831                     Arg = MakeHexArg (Out->RegA);
1832                 }
1833                 break;
1834
1835             case OP65_ORA:
1836                 if (CE_IsKnownImm (E, 0x00)) {
1837                     /* ORA with zero, remove */
1838                     CS_DelEntry (S, I);
1839                     ++Changes;
1840                 } else if (RegValIsKnown (Out->RegA)) {
1841                     /* Accu AND zp with known contents */
1842                     Arg = MakeHexArg (Out->RegA);
1843                 }
1844                 break;
1845
1846             default:
1847                 break;
1848
1849         }
1850
1851         /* Check if we have to replace the insn by LDA */
1852         if (Arg) {
1853             CodeEntry* X = NewCodeEntry (OPC, AM65_IMM, Arg, 0, E->LI);
1854             CS_InsertEntry (S, X, I+1);
1855             CS_DelEntry (S, I);
1856             ++Changes;
1857         }
1858
1859         /* Next entry */
1860         ++I;
1861     }
1862
1863     /* Free register info */
1864     CS_FreeRegInfo (S);
1865
1866     /* Return the number of changes made */
1867     return Changes;
1868 }
1869
1870
1871
1872 /*****************************************************************************/
1873 /*                           Optimize branch types                           */
1874 /*****************************************************************************/
1875
1876
1877
1878 unsigned OptBranchDist (CodeSeg* S)
1879 /* Change branches for the distance needed. */
1880 {
1881     unsigned Changes = 0;
1882
1883     /* Walk over the entries */
1884     unsigned I = 0;
1885     while (I < CS_GetEntryCount (S)) {
1886
1887         /* Get next entry */
1888         CodeEntry* E = CS_GetEntry (S, I);
1889
1890         /* Check if it's a conditional branch to a local label. */
1891         if (E->Info & OF_CBRA) {
1892
1893             /* Is this a branch to a local symbol? */
1894             if (E->JumpTo != 0) {
1895
1896                 /* Check if the branch distance is short */
1897                 int IsShort = IsShortDist (GetBranchDist (S, I, E->JumpTo->Owner));
1898
1899                 /* Make the branch short/long according to distance */
1900                 if ((E->Info & OF_LBRA) == 0 && !IsShort) {
1901                     /* Short branch but long distance */
1902                     CE_ReplaceOPC (E, MakeLongBranch (E->OPC));
1903                     ++Changes;
1904                 } else if ((E->Info & OF_LBRA) != 0 && IsShort) {
1905                     /* Long branch but short distance */
1906                     CE_ReplaceOPC (E, MakeShortBranch (E->OPC));
1907                     ++Changes;
1908                 }
1909
1910             } else if ((E->Info & OF_LBRA) == 0) {
1911
1912                 /* Short branch to external symbol - make it long */
1913                 CE_ReplaceOPC (E, MakeLongBranch (E->OPC));
1914                 ++Changes;
1915
1916             }
1917
1918         } else if ((CPUIsets[CPU] & CPU_ISET_65SC02) != 0 &&
1919                    (E->Info & OF_UBRA) != 0               &&
1920                    E->JumpTo != 0                         &&
1921                    IsShortDist (GetBranchDist (S, I, E->JumpTo->Owner))) {
1922
1923             /* The jump is short and may be replaced by a BRA on the 65C02 CPU */
1924             CE_ReplaceOPC (E, OP65_BRA);
1925             ++Changes;
1926         }
1927
1928         /* Next entry */
1929         ++I;
1930
1931     }
1932
1933     /* Return the number of changes made */
1934     return Changes;
1935 }
1936
1937
1938