]> git.sur5r.net Git - cc65/blob - src/cc65/coptstop.c
Fixed a bug
[cc65] / src / cc65 / coptstop.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 coptstop.c                                */
4 /*                                                                           */
5 /*           Optimize operations that take operands via the stack            */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2001-2002 Ullrich von Bassewitz                                       */
10 /*               Wacholderweg 14                                             */
11 /*               D-70597 Stuttgart                                           */
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 #include <stdlib.h>
37 #include <ctype.h>
38
39 /* cc65 */
40 #include "codeent.h"
41 #include "codeinfo.h"
42 #include "coptstop.h"
43
44
45
46 /*****************************************************************************/
47 /*                                   Data                                    */
48 /*****************************************************************************/
49
50
51
52 /* Structure that holds the needed data */
53 typedef struct StackOpData StackOpData;
54 struct StackOpData {
55     CodeSeg*    Code;                   /* Pointer to code segment */
56     unsigned    Flags;                  /* Flags to remember things */
57     unsigned    PushIndex;              /* Index of call to pushax in codeseg */
58     unsigned    OpIndex;                /* Index of actual operation */
59     CodeEntry*  PrevEntry;              /* Entry before the call to pushax */
60     CodeEntry*  PushEntry;              /* Pointer to entry with call to pushax */
61     CodeEntry*  OpEntry;                /* Pointer to entry with op */
62     CodeEntry*  NextEntry;              /* Entry after the op */
63     const char* ZPLo;                   /* Lo byte of zero page loc to use */
64     const char* ZPHi;                   /* Hi byte of zero page loc to use */
65     unsigned    IP;                     /* Insertion point used by some routines */
66 };
67
68 /* Flags returned by DirectOp */
69 #define OP_DIRECT       0x01            /* Direct op may be used */
70 #define OP_RELOAD_Y     0x02            /* Must reload index register Y */
71
72
73
74 /*****************************************************************************/
75 /*                                  Helpers                                  */
76 /*****************************************************************************/
77
78
79
80 static unsigned AdjustStackOffset (CodeSeg* S, unsigned Start, unsigned Stop,
81                                    unsigned Offs)
82 /* Adjust the offset for all stack accesses in the range Start to Stop, both
83  * inclusive. The function returns the number of instructions that have been
84  * inserted.
85  */
86 {
87     /* Number of inserted instructions */
88     unsigned Inserted = 0;
89
90     /* Walk over all entries */
91     unsigned I = Start;
92     while (I <= Stop) {
93
94         CodeEntry* E = CS_GetEntry (S, I);
95
96         int NeedCorrection = 0;
97         if ((E->Use & REG_SP) != 0) {
98
99             /* Check for some things that should not happen */
100             CHECK (E->AM == AM65_ZP_INDY || E->RI->In.RegY >= (short) Offs);
101             CHECK (strcmp (E->Arg, "sp") == 0);
102
103             /* We need to correct this one */
104             NeedCorrection = 1;
105
106         } else if (CE_IsCallTo (E, "ldaxysp")) {
107
108             /* We need to correct this one */
109             NeedCorrection = 1;
110
111         }
112
113         if (NeedCorrection) {
114
115             CodeEntry* P;
116
117             /* Get the code entry before this one. If it's a LDY, adjust the
118              * value.
119              */
120             P = CS_GetPrevEntry (S, I);
121             if (P && P->OPC == OP65_LDY && CE_KnownImm (P)) {
122
123                 /* The Y load is just before the stack access, adjust it */
124                 CE_SetNumArg (P, P->Num - Offs);
125
126             } else {
127
128                 /* Insert a new load instruction before the stack access */
129                 const char* Arg = MakeHexArg (E->RI->In.RegY - Offs);
130                 CodeEntry* X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, E->LI);
131                 CS_InsertEntry (S, X, I);
132
133                 /* One more inserted entries */
134                 ++Inserted;
135                 ++Stop;
136
137                 /* Be sure to skip the stack access for the next round */
138                 ++I;
139
140             }
141
142         }
143
144         /* Next entry */
145         ++I;
146     }
147
148     /* Return the number of inserted entries */
149     return Inserted;
150 }
151
152
153
154 static void InsertEntry (StackOpData* D, CodeEntry* E, unsigned Index)
155 /* Insert a new entry. Depending on Index, D->PushIndex and D->OpIndex will
156  * be adjusted by this function.
157  */
158 {
159     /* Insert the entry into the code segment */
160     CS_InsertEntry (D->Code, E, Index);
161
162     /* Adjust the indices if necessary */
163     if (D->PushEntry && Index <= D->PushIndex) {
164         ++D->PushIndex;
165     }
166     if (D->OpEntry && Index <= D->OpIndex) {
167         ++D->OpIndex;
168     }
169 }
170
171
172
173 static void DelEntry (StackOpData* D, unsigned Index)
174 /* Delete an entry. Depending on Index, D->PushIndex and D->OpIndex will be
175  * adjusted by this function, and PushEntry/OpEntry may get invalidated.
176  */
177 {
178     /* Delete the entry from the code segment */
179     CS_DelEntry (D->Code, Index);
180
181     /* Adjust the indices if necessary */
182     if (Index < D->PushIndex) {
183         --D->PushIndex;
184     } else if (Index == D->PushIndex) {
185         D->PushEntry = 0;
186     }
187     if (Index < D->OpIndex) {
188         --D->OpIndex;
189     } else if (Index == D->OpIndex) {
190         D->OpEntry = 0;
191     }
192 }
193
194
195
196 static void CheckDirectOp (StackOpData* D)
197 /* Check if the given entry is a lda instruction with an addressing mode
198  * that allows us to replace it by another operation (like ora). If so, we may
199  * use this location for the or and must not save the value in the zero
200  * page location.
201  */
202 {
203     /* We need the entry before the push */
204     CodeEntry* E;
205     CHECK ((E = D->PrevEntry) != 0);
206
207     if (E->OPC == OP65_LDA) {
208         if (E->AM == AM65_IMM || E->AM == AM65_ZP || E->AM == AM65_ABS) {
209             /* These insns are all ok and replaceable */
210             D->Flags |= OP_DIRECT;
211         } else if (E->AM == AM65_ZP_INDY && RegValIsKnown (E->RI->In.RegY) &&
212                    strcmp (E->Arg, "sp") == 0) {
213             /* A load from the stack with known offset is also ok, but in this
214              * case we must reload the index register later. Please note that
215              * a load indirect via other zero page locations is not ok, since
216              * these locations may change between the push and the actual
217              * operation.
218              */
219             D->Flags |= (OP_DIRECT | OP_RELOAD_Y);
220         }
221     }
222 }
223
224
225
226 static void ReplacePushByStore (StackOpData* D)
227 /* Replace the call to the push subroutine by a store into the zero page
228  * location (actually, the push is not replaced, because we need it for
229  * later, but the name is still ok since the push will get removed at the
230  * end of each routine).
231  */
232 {
233     CodeEntry* X;
234
235     /* Store the value into the zeropage instead of pushing it */
236     X = NewCodeEntry (OP65_STX, AM65_ZP, D->ZPHi, 0, D->PushEntry->LI);
237     InsertEntry (D, X, D->PushIndex+1);
238     if ((D->Flags & OP_DIRECT) == 0) {
239         X = NewCodeEntry (OP65_STA, AM65_ZP, D->ZPLo, 0, D->PushEntry->LI);
240         InsertEntry (D, X, D->PushIndex+1);
241     }
242 }
243
244
245
246 static void AddOpLow (StackOpData* D, opc_t OPC)
247 /* Add an op for the low byte of an operator. This function honours the
248  * OP_DIRECT and OP_RELOAD_Y flags and generates the necessary instructions.
249  * All code is inserted at the current insertion point.
250  */
251 {
252     CodeEntry* X;
253
254     if ((D->Flags & OP_DIRECT) != 0) {
255         /* Op with a variable location. If the location is on the stack, we
256          * need to reload the Y register.
257          */
258         if ((D->Flags & OP_RELOAD_Y) != 0) {
259             const char* Arg = MakeHexArg (D->PrevEntry->RI->In.RegY);
260             X = NewCodeEntry (OP65_LDY, AM65_IMM, Arg, 0, D->OpEntry->LI);
261             InsertEntry (D, X, D->IP++);
262         }
263         X = NewCodeEntry (OPC, D->PrevEntry->AM, D->PrevEntry->Arg, 0, D->OpEntry->LI);
264     } else {
265         /* Op with temp storage */
266         X = NewCodeEntry (OPC, AM65_ZP, D->ZPLo, 0, D->OpEntry->LI);
267     }
268     InsertEntry (D, X, D->IP++);
269 }
270
271
272
273 static void AddOpHigh (StackOpData* D, opc_t OPC)
274 /* Add an op for the high byte of an operator. Special cases (constant values
275  * or similar have to be checked separately, the function covers only the
276  * generic case. Code is inserted at the insertion point.
277  */
278 {
279     CodeEntry* X;
280
281     /* High byte is unknown */
282     X = NewCodeEntry (OP65_STA, AM65_ZP, D->ZPLo, 0, D->OpEntry->LI);
283     InsertEntry (D, X, D->IP++);
284     X = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, D->OpEntry->LI);
285     InsertEntry (D, X, D->IP++);
286     X = NewCodeEntry (OPC, AM65_ZP, D->ZPHi, 0, D->OpEntry->LI);
287     InsertEntry (D, X, D->IP++);
288     X = NewCodeEntry (OP65_TAX, AM65_IMP, 0, 0, D->OpEntry->LI);
289     InsertEntry (D, X, D->IP++);
290     X = NewCodeEntry (OP65_LDA, AM65_ZP, D->ZPLo, 0, D->OpEntry->LI);
291     InsertEntry (D, X, D->IP++);
292 }
293
294
295
296 static void RemovePushAndOp (StackOpData* D)
297 /* Remove the call to pushax and the call to the operator subroutine */
298 {
299     DelEntry (D, D->OpIndex);
300     DelEntry (D, D->PushIndex);
301 }
302
303
304
305 static const char* IsRegVar (const StackOpData* D)
306 /* If the value pushed is that of a register variable, return the name of the
307  * entry in the register bank. Otherwise return NULL.
308  */
309 {
310     CodeEntry* P;
311
312     if (D->PushIndex >= 2                                &&
313         (P = D->PrevEntry) != 0                          &&
314         P->OPC == OP65_LDX                               &&
315         P->AM == AM65_ZP                                 &&
316         strncmp (P->Arg, "regbank+", 7) == 0             &&
317         isdigit (P->Arg[8])                              &&
318         (P = CS_GetEntry (D->Code, D->PushIndex-2)) != 0 &&
319         P->OPC == OP65_LDA                               &&
320         P->AM == AM65_ZP                                 &&
321         strncmp (P->Arg, "regbank+", 7) == 0             &&
322         isdigit (P->Arg[8])) {
323         /* Ok, it loads the register variable */
324         return P->Arg;
325     } else {
326         return 0;
327     }
328 }
329
330
331
332 /*****************************************************************************/
333 /*                       Actual optimization functions                       */
334 /*****************************************************************************/
335
336
337
338 static unsigned Opt_staspidx (StackOpData* D)
339 /* Optimize the staspidx sequence if possible */
340 {
341     CodeEntry* X;
342     const char* ZPLo;
343
344     /* Check if we're using a register variable */
345     if ((ZPLo = IsRegVar (D)) == 0) {
346
347         /* Store the value into the zeropage instead of pushing it */
348         ReplacePushByStore (D);
349
350         /* Use the given zero page loc */
351         ZPLo = D->ZPLo;
352     }
353
354     /* Replace the store subroutine call by a direct op */
355     X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, ZPLo, 0, D->OpEntry->LI);
356     InsertEntry (D, X, D->OpIndex+1);
357
358     /* Remove the push and the call to the staspidx function */
359     RemovePushAndOp (D);
360
361     /* We changed the sequence */
362     return 1;
363 }
364
365
366
367 static unsigned Opt_staxspidx (StackOpData* D)
368 /* Optimize the staxspidx sequence if possible */
369 {
370     CodeEntry* X;
371     const char* ZPLo;
372
373     /* Check if we're using a register variable */
374     if ((ZPLo = IsRegVar (D)) == 0) {
375
376         /* Store the value into the zeropage instead of pushing it */
377         ReplacePushByStore (D);
378
379         /* Use the given zero page loc */
380         ZPLo = D->ZPLo;
381     }
382
383     /* Inline the store */
384     X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, ZPLo, 0, D->OpEntry->LI);
385     InsertEntry (D, X, D->OpIndex+1);
386     X = NewCodeEntry (OP65_INY, AM65_IMP, 0, 0, D->OpEntry->LI);
387     InsertEntry (D, X, D->OpIndex+2);
388     if (RegValIsKnown (D->OpEntry->RI->In.RegX)) {
389         /* Value of X is known */
390         const char* Arg = MakeHexArg (D->OpEntry->RI->In.RegX);
391         X = NewCodeEntry (OP65_LDA, AM65_IMM, Arg, 0, D->OpEntry->LI);
392     } else {
393         /* Value unknown */
394         X = NewCodeEntry (OP65_TXA, AM65_IMP, 0, 0, D->OpEntry->LI);
395     }
396     InsertEntry (D, X, D->OpIndex+3);
397     X = NewCodeEntry (OP65_STA, AM65_ZP_INDY, ZPLo, 0, D->OpEntry->LI);
398     InsertEntry (D, X, D->OpIndex+4);
399
400     /* Remove the push and the call to the staspidx function */
401     RemovePushAndOp (D);
402
403     /* We changed the sequence */
404     return 1;
405 }
406
407
408
409 static unsigned Opt_tosaddax (StackOpData* D)
410 /* Optimize the tosaddax sequence if possible */
411 {
412     CodeEntry*  X;
413
414
415     /* We need the entry behind the add */
416     CHECK (D->NextEntry != 0);
417
418     /* Check the entry before the push. If it's a lda instruction with an
419      * addressing mode that allows us to replace it, we may use this
420      * location for the op and must not save the value in the zero page
421      * location.
422      */
423     CheckDirectOp (D);
424
425     /* Store the value into the zeropage instead of pushing it */
426     ReplacePushByStore (D);
427
428     /* Inline the add */
429     D->IP = D->OpIndex+1;
430     X = NewCodeEntry (OP65_CLC, AM65_IMP, 0, 0, D->OpEntry->LI);
431     InsertEntry (D, X, D->IP++);
432
433     /* Low byte */
434     AddOpLow (D, OP65_ADC);
435
436     /* High byte */
437     if (D->PushEntry->RI->In.RegX == 0) {
438         /* The high byte is the value in X plus the carry */
439         CodeLabel* L = CS_GenLabel (D->Code, D->NextEntry);
440         X = NewCodeEntry (OP65_BCC, AM65_BRA, L->Name, L, D->OpEntry->LI);
441         InsertEntry (D, X, D->IP++);
442         X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, D->OpEntry->LI);
443         InsertEntry (D, X, D->IP++);
444     } else if (D->OpEntry->RI->In.RegX == 0) {
445         /* The high byte is that of the first operand plus carry */
446         CodeLabel* L;
447         if (RegValIsKnown (D->PushEntry->RI->In.RegX)) {
448             /* Value of first op high byte is known */
449             const char* Arg = MakeHexArg (D->PushEntry->RI->In.RegX);
450             X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI);
451         } else {
452             /* Value of first op high byte is unknown */
453             X = NewCodeEntry (OP65_LDX, AM65_ZP, D->ZPHi, 0, D->OpEntry->LI);
454         }
455         InsertEntry (D, X, D->IP++);
456         L = CS_GenLabel (D->Code, D->NextEntry);
457         X = NewCodeEntry (OP65_BCC, AM65_BRA, L->Name, L, D->OpEntry->LI);
458         InsertEntry (D, X, D->IP++);
459         X = NewCodeEntry (OP65_INX, AM65_IMP, 0, 0, D->OpEntry->LI);
460         InsertEntry (D, X, D->IP++);
461     } else {
462         /* High byte is unknown */
463         AddOpHigh (D, OP65_ADC);
464     }
465
466     /* Remove the push and the call to the tosaddax function */
467     RemovePushAndOp (D);
468
469     /* We changed the sequence */
470     return 1;
471 }
472
473
474
475 static unsigned Opt_tosandax (StackOpData* D)
476 /* Optimize the tosandax sequence if possible */
477 {
478     CodeEntry*  X;
479
480     /* Check the entry before the push. If it's a lda instruction with an
481      * addressing mode that allows us to replace it, we may use this
482      * location for the op and must not save the value in the zero page
483      * location.
484      */
485     CheckDirectOp (D);
486
487     /* Store the value into the zeropage instead of pushing it */
488     ReplacePushByStore (D);
489
490     /* Inline the and, low byte */
491     D->IP = D->OpIndex + 1;
492     AddOpLow (D, OP65_AND);
493
494     /* High byte */
495     if (D->PushEntry->RI->In.RegX == 0 || D->OpEntry->RI->In.RegX == 0) {
496         /* The high byte is zero */
497         X = NewCodeEntry (OP65_LDX, AM65_IMM, "$00", 0, D->OpEntry->LI);
498         InsertEntry (D, X, D->IP++);
499     } else {
500         /* High byte is unknown */
501         AddOpHigh (D, OP65_AND);
502     }
503
504     /* Remove the push and the call to the tosandax function */
505     RemovePushAndOp (D);
506
507     /* We changed the sequence */
508     return 1;
509 }
510
511
512
513 static unsigned Opt_tosorax (StackOpData* D)
514 /* Optimize the tosorax sequence if possible */
515 {
516     CodeEntry*  X;
517
518     /* Check the entry before the push. If it's a lda instruction with an
519      * addressing mode that allows us to replace it, we may use this
520      * location for the op and must not save the value in the zero page
521      * location.
522      */
523     CheckDirectOp (D);
524
525     /* Store the value into the zeropage instead of pushing it */
526     ReplacePushByStore (D);
527
528     /* Inline the or, low byte */
529     D->IP = D->OpIndex + 1;
530     AddOpLow (D, OP65_ORA);
531
532     /* High byte */
533     if (RegValIsKnown (D->PushEntry->RI->In.RegX) &&
534         RegValIsKnown (D->OpEntry->RI->In.RegX)) {
535         /* Both values known, precalculate the result */
536         const char* Arg = MakeHexArg (D->PushEntry->RI->In.RegX | D->OpEntry->RI->In.RegX);
537         X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI);
538         InsertEntry (D, X, D->IP++);
539     } else if (D->PushEntry->RI->In.RegX != 0) {
540         /* High byte is unknown */
541         AddOpHigh (D, OP65_ORA);
542     }
543
544     /* Remove the push and the call to the tosorax function */
545     RemovePushAndOp (D);
546
547     /* We changed the sequence */
548     return 1;
549 }
550
551
552
553 static unsigned Opt_tosxorax (StackOpData* D)
554 /* Optimize the tosxorax sequence if possible */
555 {
556     CodeEntry*  X;
557
558     /* Check the entry before the push. If it's a lda instruction with an
559      * addressing mode that allows us to replace it, we may use this
560      * location for the op and must not save the value in the zero page
561      * location.
562      */
563     CheckDirectOp (D);
564
565     /* Store the value into the zeropage instead of pushing it */
566     ReplacePushByStore (D);
567
568     /* Inline the xor, low byte */
569     D->IP = D->OpIndex + 1;
570     AddOpLow (D, OP65_EOR);
571
572     /* High byte */
573     if (RegValIsKnown (D->PushEntry->RI->In.RegX) &&
574         RegValIsKnown (D->OpEntry->RI->In.RegX)) {
575         /* Both values known, precalculate the result */
576         const char* Arg = MakeHexArg (D->PushEntry->RI->In.RegX ^ D->OpEntry->RI->In.RegX);
577         X = NewCodeEntry (OP65_LDX, AM65_IMM, Arg, 0, D->OpEntry->LI);
578         InsertEntry (D, X, D->IP++);
579     } else if (D->PushEntry->RI->In.RegX != 0) {
580         /* High byte is unknown */
581         AddOpHigh (D, OP65_EOR);
582     }
583
584     /* Remove the push and the call to the tosandax function */
585     RemovePushAndOp (D);
586
587     /* We changed the sequence */
588     return 1;
589 }
590
591
592
593 /*****************************************************************************/
594 /*                                   Code                                    */
595 /*****************************************************************************/
596
597
598
599 /* Flags for the functions */
600 typedef enum {
601     STOP_NONE,              /* Nothing special */
602     STOP_A_UNUSED           /* Call only if a unused later */
603 } STOP_FLAGS;
604
605
606 typedef unsigned (*OptFunc) (StackOpData* D);
607 typedef struct OptFuncDesc OptFuncDesc;
608 struct OptFuncDesc {
609     const char*     Name;   /* Name of the replaced runtime function */
610     OptFunc         Func;   /* Function pointer */
611     STOP_FLAGS      Flags;  /* Flags */
612 };
613
614 static const OptFuncDesc FuncTable[] = {
615     { "staspidx",   Opt_staspidx,  STOP_NONE },
616     { "staxspidx",  Opt_staxspidx, STOP_A_UNUSED },
617     { "tosaddax",   Opt_tosaddax,  STOP_NONE },
618     { "tosandax",   Opt_tosandax,  STOP_NONE },
619     { "tosorax",    Opt_tosorax,   STOP_NONE },
620     { "tosxorax",   Opt_tosxorax,  STOP_NONE },
621 };
622 #define FUNC_COUNT (sizeof(FuncTable) / sizeof(FuncTable[0]))
623
624
625
626 static int CmpFunc (const void* Key, const void* Func)
627 /* Compare function for bsearch */
628 {
629     return strcmp (Key, ((const OptFuncDesc*) Func)->Name);
630 }
631
632
633
634 static const OptFuncDesc* FindFunc (const char* Name)
635 /* Find the function with the given name. Return a pointer to the table entry
636  * or NULL if the function was not found.
637  */
638 {
639     return bsearch (Name, FuncTable, FUNC_COUNT, sizeof(OptFuncDesc), CmpFunc);
640 }
641
642
643
644 static int CmpHarmless (const void* Key, const void* Entry)
645 /* Compare function for bsearch */
646 {
647     return strcmp (Key, *(const char**)Entry);
648 }
649
650
651
652 static int HarmlessCall (const char* Name)
653 /* Check if this is a call to a harmless subroutine that will not interrupt
654  * the pushax/op sequence when encountered.
655  */
656 {
657     static const char* Tab[] = {
658         "ldaxidx",
659         "ldaxysp",
660         "negax",
661     };
662
663     void* R = bsearch (Name,
664                        Tab,
665                        sizeof (Tab) / sizeof (Tab[0]),
666                        sizeof (Tab[0]),
667                        CmpHarmless);
668     return (R != 0);
669 }
670
671
672
673 /*****************************************************************************/
674 /*                                   Code                                    */
675 /*****************************************************************************/
676
677
678
679 unsigned OptStackOps (CodeSeg* S)
680 /* Optimize operations that take operands via the stack */
681 {
682     unsigned    Changes = 0;    /* Number of changes in one run */
683     int         InSeq = 0;      /* Inside a sequence */
684     unsigned    Push = 0;       /* Index of pushax */
685     unsigned    UsedRegs = 0;   /* Zeropage registers used in sequence */
686     unsigned    I;
687
688
689     /* Generate register info */
690     CS_GenRegInfo (S);
691
692     /* Look for a call to pushax followed by a call to some other function
693      * that takes it's first argument on the stack, and the second argument
694      * in the primary register.
695      * It depends on the code between the two if we can handle/transform the
696      * sequence, so check this code for the following list of things:
697      *
698      *  - the range must be a basic block (one entry, one exit)
699      *  - there may not be accesses to local variables with unknown
700      *    offsets (because we have to adjust these offsets).
701      *  - no subroutine calls
702      *  - no jump labels
703      *
704      * Since we need a zero page register later, do also check the
705      * intermediate code for zero page use.
706      */
707     I = 0;
708     while (I < CS_GetEntryCount (S)) {
709
710         /* Get the next entry */
711         CodeEntry* E = CS_GetEntry (S, I);
712
713         /* Handling depends if we're inside a sequence or not */
714         if (InSeq) {
715
716             /* If we are using the stack, and we don't have "indirect Y"
717              * addressing mode, or the value of Y is unknown, or less than
718              * two, we cannot cope with this piece of code. Having an unknown
719              * value of Y means that we cannot correct the stack offset, while
720              * having an offset less than two means that the code works with
721              * the value on stack which is to be removed.
722              */
723             if ((E->Use & REG_SP) != 0 &&
724                 (E->AM != AM65_ZP_INDY || RegValIsUnknown (E->RI->In.RegY) ||
725                  E->RI->In.RegY < 2)) {
726
727                 /* All this stuff is not allowed in a sequence */
728                 InSeq = 0;
729
730             } else if (E->OPC == OP65_JSR) {
731
732                 /* Subroutine call: Check if this is one of our functions */
733                 const OptFuncDesc* F = FindFunc (E->Arg);
734                 if (F) {
735
736                     StackOpData Data;
737                     int PreCondOk = 1;
738
739                     /* Check the flags */
740                     if (F->Flags & STOP_A_UNUSED) {
741                         /* a must be unused later */
742                         if (RegAUsed (S, I+1)) {
743                             /* Cannot optimize */
744                             PreCondOk = 0;
745                         }
746                     }
747
748                     /* Determine the zero page locations to use */
749                     if (PreCondOk) {
750                         UsedRegs |= GetRegInfo (S, I+1, REG_SREG | REG_PTR1 | REG_PTR2);
751                         if ((UsedRegs & REG_SREG) == REG_NONE) {
752                             /* SREG is available */
753                             Data.ZPLo = "sreg";
754                             Data.ZPHi = "sreg+1";
755                         } else if ((UsedRegs & REG_PTR1) == REG_NONE) {
756                             Data.ZPLo = "ptr1";
757                             Data.ZPHi = "ptr1+1";
758                         } else if ((UsedRegs & REG_PTR2) == REG_NONE) {
759                             Data.ZPLo = "ptr2";
760                             Data.ZPHi = "ptr2+1";
761                         } else {
762                             /* No registers available */
763                             PreCondOk = 0;
764                         }
765                     }
766
767                     /* Determine if we have a basic block */
768                     if (PreCondOk) {
769                         PreCondOk = CS_IsBasicBlock (S, Push, I);
770                     }
771
772                     /* If preconditions are ok, call the optimizer function */
773                     if (PreCondOk) {
774
775                         /* Adjust stack offsets */
776                         Data.OpIndex = I + AdjustStackOffset (S, Push, I, 2);
777
778                         /* Prepare the remainder of the data structure */
779                         Data.Code      = S;
780                         Data.Flags     = 0;
781                         Data.PushIndex = Push;
782                         Data.PrevEntry = CS_GetPrevEntry (S, Data.PushIndex);
783                         Data.PushEntry = CS_GetEntry (S, Data.PushIndex);
784                         Data.OpEntry   = E;
785                         Data.NextEntry = CS_GetNextEntry (S, Data.OpIndex);
786
787                         /* Call the optimizer function */
788                         Changes += F->Func (&Data);
789
790                         /* Regenerate register info */
791                         CS_GenRegInfo (S);
792                     }
793
794                     /* End of sequence */
795                     InSeq = 0;
796
797                 } else if (strcmp (E->Arg, "pushax") == 0) {
798                     /* Restart the sequence */
799                     Push     = I;
800                     UsedRegs = REG_NONE;
801                 } else if (HarmlessCall (E->Arg)) {
802                     /* Track zeropage register usage */
803                     UsedRegs |= (E->Use | E->Chg);
804                 } else {
805                     /* A call to an unkown subroutine ends the sequence */
806                     InSeq = 0;
807                 }
808
809             } else {
810                 /* Other stuff: Track zeropage register usage */
811                 UsedRegs |= (E->Use | E->Chg);
812             }
813
814         } else if (CE_IsCallTo (E, "pushax")) {
815
816             /* This starts a sequence */
817             Push     = I;
818             UsedRegs = REG_NONE;
819             InSeq    = 1;
820
821         }
822
823         /* Next entry */
824         ++I;
825
826     }
827
828     /* Free the register info */
829     CS_FreeRegInfo (S);
830
831     /* Return the number of changes made */
832     return Changes;
833 }
834
835
836