]> git.sur5r.net Git - cc65/blob - src/cc65/codeseg.c
ba759988b2cd54447980b468a00e3987e6a2591f
[cc65] / src / cc65 / codeseg.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 codeseg.c                                 */
4 /*                                                                           */
5 /*                          Code segment structure                           */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2001-2011, 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 #include <string.h>
37 #include <ctype.h>
38
39 /* common */
40 #include "chartype.h"
41 #include "check.h"
42 #include "debugflag.h"
43 #include "global.h"
44 #include "hashfunc.h"
45 #include "strbuf.h"
46 #include "strutil.h"
47 #include "xmalloc.h"
48
49 /* cc65 */
50 #include "asmlabel.h"
51 #include "codeent.h"
52 #include "codeinfo.h"
53 #include "codeseg.h"
54 #include "datatype.h"
55 #include "error.h"
56 #include "global.h"
57 #include "ident.h"
58 #include "output.h"
59 #include "symentry.h"
60
61
62
63 /*****************************************************************************/
64 /*                             Helper functions                              */
65 /*****************************************************************************/
66
67
68
69 static void CS_PrintFunctionHeader (const CodeSeg* S)
70 /* Print a comment with the function signature to the output file */
71 {
72     /* Get the associated function */
73     const SymEntry* Func = S->Func;
74
75     /* If this is a global code segment, do nothing */
76     if (Func) {
77         WriteOutput ("; ---------------------------------------------------------------\n"
78                      "; ");
79         PrintFuncSig (OutputFile, Func->Name, Func->Type);
80         WriteOutput ("\n"
81                      "; ---------------------------------------------------------------\n"
82                      "\n");
83     }
84 }
85
86
87
88 static void CS_MoveLabelsToEntry (CodeSeg* S, CodeEntry* E)
89 /* Move all labels from the label pool to the given entry and remove them
90 ** from the pool.
91 */
92 {
93     /* Transfer the labels if we have any */
94     unsigned I;
95     unsigned LabelCount = CollCount (&S->Labels);
96     for (I = 0; I < LabelCount; ++I) {
97
98         /* Get the label */
99         CodeLabel* L = CollAt (&S->Labels, I);
100
101         /* Attach it to the entry */
102         CE_AttachLabel (E, L);
103     }
104
105     /* Delete the transfered labels */
106     CollDeleteAll (&S->Labels);
107 }
108
109
110
111 static void CS_MoveLabelsToPool (CodeSeg* S, CodeEntry* E)
112 /* Move the labels of the code entry E to the label pool of the code segment */
113 {
114     unsigned LabelCount = CE_GetLabelCount (E);
115     while (LabelCount--) {
116         CodeLabel* L = CE_GetLabel (E, LabelCount);
117         L->Owner = 0;
118         CollAppend (&S->Labels, L);
119     }
120     CollDeleteAll (&E->Labels);
121 }
122
123
124
125 static CodeLabel* CS_FindLabel (CodeSeg* S, const char* Name, unsigned Hash)
126 /* Find the label with the given name. Return the label or NULL if not found */
127 {
128     /* Get the first hash chain entry */
129     CodeLabel* L = S->LabelHash[Hash];
130
131     /* Search the list */
132     while (L) {
133         if (strcmp (Name, L->Name) == 0) {
134             /* Found */
135             break;
136         }
137         L = L->Next;
138     }
139     return L;
140 }
141
142
143
144 static CodeLabel* CS_NewCodeLabel (CodeSeg* S, const char* Name, unsigned Hash)
145 /* Create a new label and insert it into the label hash table */
146 {
147     /* Create a new label */
148     CodeLabel* L = NewCodeLabel (Name, Hash);
149
150     /* Enter the label into the hash table */
151     L->Next = S->LabelHash[L->Hash];
152     S->LabelHash[L->Hash] = L;
153
154     /* Return the new label */
155     return L;
156 }
157
158
159
160 static void CS_RemoveLabelFromHash (CodeSeg* S, CodeLabel* L)
161 /* Remove the given code label from the hash list */
162 {
163     /* Get the first entry in the hash chain */
164     CodeLabel* List = S->LabelHash[L->Hash];
165     CHECK (List != 0);
166
167     /* First, remove the label from the hash chain */
168     if (List == L) {
169         /* First entry in hash chain */
170         S->LabelHash[L->Hash] = L->Next;
171     } else {
172         /* Must search through the chain */
173         while (List->Next != L) {
174             /* If we've reached the end of the chain, something is *really* wrong */
175             CHECK (List->Next != 0);
176             /* Next entry */
177             List = List->Next;
178         }
179         /* The next entry is the one, we have been searching for */
180         List->Next = L->Next;
181     }
182 }
183
184
185
186 /*****************************************************************************/
187 /*                    Functions for parsing instructions                     */
188 /*****************************************************************************/
189
190
191
192 static const char* SkipSpace (const char* S)
193 /* Skip white space and return an updated pointer */
194 {
195     while (IsSpace (*S)) {
196         ++S;
197     }
198     return S;
199 }
200
201
202
203 static const char* ReadToken (const char* L, const char* Term,
204                               char* Buf, unsigned BufSize)
205 /* Read the next token into Buf, return the updated line pointer. The
206 ** token is terminated by one of the characters given in term.
207 */
208 {
209     /* Read/copy the token */
210     unsigned I = 0;
211     unsigned ParenCount = 0;
212     while (*L && (ParenCount > 0 || strchr (Term, *L) == 0)) {
213         if (I < BufSize-1) {
214             Buf[I] = *L;
215         } else if (I == BufSize-1) {
216             /* Cannot store this character, this is an input error (maybe
217             ** identifier too long or similar).
218             */
219             Error ("ASM code error: syntax error");
220         }
221         ++I;
222         if (*L == ')') {
223             --ParenCount;
224         } else if (*L == '(') {
225             ++ParenCount;
226         }
227         ++L;
228     }
229
230     /* Terminate the buffer contents */
231     Buf[I] = '\0';
232
233     /* Return the updated line pointer */
234     return L;
235 }
236
237
238
239 static CodeEntry* ParseInsn (CodeSeg* S, LineInfo* LI, const char* L)
240 /* Parse an instruction nnd generate a code entry from it. If the line contains
241 ** errors, output an error message and return NULL.
242 ** For simplicity, we don't accept the broad range of input a "real" assembler
243 ** does. The instruction and the argument are expected to be separated by
244 ** white space, for example.
245 */
246 {
247     char                Mnemo[IDENTSIZE+10];
248     const OPCDesc*      OPC;
249     am_t                AM = 0;         /* Initialize to keep gcc silent */
250     char                Arg[IDENTSIZE+10];
251     char                Reg;
252     CodeEntry*          E;
253     CodeLabel*          Label;
254
255     /* Read the first token and skip white space after it */
256     L = SkipSpace (ReadToken (L, " \t:", Mnemo, sizeof (Mnemo)));
257
258     /* Check if we have a label */
259     if (*L == ':') {
260
261         /* Skip the colon and following white space */
262         L = SkipSpace (L+1);
263
264         /* Add the label */
265         CS_AddLabel (S, Mnemo);
266
267         /* If we have reached end of line, bail out, otherwise a mnemonic
268         ** may follow.
269         */
270         if (*L == '\0') {
271             return 0;
272         }
273
274         L = SkipSpace (ReadToken (L, " \t", Mnemo, sizeof (Mnemo)));
275     }
276
277     /* Try to find the opcode description for the mnemonic */
278     OPC = FindOP65 (Mnemo);
279
280     /* If we didn't find the opcode, print an error and bail out */
281     if (OPC == 0) {
282         Error ("ASM code error: %s is not a valid mnemonic", Mnemo);
283         return 0;
284     }
285
286     /* Get the addressing mode */
287     Arg[0] = '\0';
288     switch (*L) {
289
290         case '\0':
291             /* Implicit or accu */
292             if (OPC->Info & OF_NOIMP) {
293                 AM = AM65_ACC;
294             } else {
295                 AM = AM65_IMP;
296             }
297             break;
298
299         case '#':
300             /* Immidiate */
301             StrCopy (Arg, sizeof (Arg), L+1);
302             AM = AM65_IMM;
303             break;
304
305         case '(':
306             /* Indirect */
307             L = ReadToken (L+1, ",)", Arg, sizeof (Arg));
308
309             /* Check for errors */
310             if (*L == '\0') {
311                 Error ("ASM code error: syntax error");
312                 return 0;
313             }
314
315             /* Check the different indirect modes */
316             if (*L == ',') {
317                 /* Expect zp x indirect */
318                 L = SkipSpace (L+1);
319                 if (toupper (*L) != 'X') {
320                     Error ("ASM code error: 'X' expected");
321                     return 0;
322                 }
323                 L = SkipSpace (L+1);
324                 if (*L != ')') {
325                     Error ("ASM code error: ')' expected");
326                     return 0;
327                 }
328                 L = SkipSpace (L+1);
329                 if (*L != '\0') {
330                     Error ("ASM code error: syntax error");
331                     return 0;
332                 }
333                 AM = AM65_ZPX_IND;
334             } else if (*L == ')') {
335                 /* zp indirect or zp indirect, y */
336                 L = SkipSpace (L+1);
337                 if (*L == ',') {
338                     L = SkipSpace (L+1);
339                     if (toupper (*L) != 'Y') {
340                         Error ("ASM code error: 'Y' expected");
341                         return 0;
342                     }
343                     L = SkipSpace (L+1);
344                     if (*L != '\0') {
345                         Error ("ASM code error: syntax error");
346                         return 0;
347                     }
348                     AM = AM65_ZP_INDY;
349                 } else if (*L == '\0') {
350                     AM = AM65_ZP_IND;
351                 } else {
352                     Error ("ASM code error: syntax error");
353                     return 0;
354                 }
355             }
356             break;
357
358         case 'a':
359         case 'A':
360             /* Accumulator? */
361             if (L[1] == '\0') {
362                 AM = AM65_ACC;
363                 break;
364             }
365             /* FALLTHROUGH */
366
367         default:
368             /* Absolute, maybe indexed */
369             L = ReadToken (L, ",", Arg, sizeof (Arg));
370             if (*L == '\0') {
371                 /* Absolute, zeropage or branch */
372                 if ((OPC->Info & OF_BRA) != 0) {
373                     /* Branch */
374                     AM = AM65_BRA;
375                 } else if (GetZPInfo(Arg) != 0) {
376                     AM = AM65_ZP;
377                 } else {
378                     /* Check for subroutine call to local label */
379                     if ((OPC->Info & OF_CALL) && IsLocalLabelName (Arg)) {
380                         Error ("ASM code error: "
381                                "Cannot use local label '%s' in subroutine call",
382                                Arg);
383                     }
384                     AM = AM65_ABS;
385                 }
386             } else if (*L == ',') {
387                 /* Indexed */
388                 L = SkipSpace (L+1);
389                 if (*L == '\0') {
390                     Error ("ASM code error: syntax error");
391                     return 0;
392                 } else {
393                     Reg = toupper (*L);
394                     L = SkipSpace (L+1);
395                     if (Reg == 'X') {
396                         if (GetZPInfo(Arg) != 0) {
397                             AM = AM65_ZPX;
398                         } else {
399                             AM = AM65_ABSX;
400                         }
401                     } else if (Reg == 'Y') {
402                         AM = AM65_ABSY;
403                     } else {
404                         Error ("ASM code error: syntax error");
405                         return 0;
406                     }
407                     if (*L != '\0') {
408                         Error ("ASM code error: syntax error");
409                         return 0;
410                     }
411                 }
412             }
413             break;
414
415     }
416
417     /* If the instruction is a branch, check for the label and generate it
418     ** if it does not exist. This may lead to unused labels (if the label
419     ** is actually an external one) which are removed by the CS_MergeLabels
420     ** function later.
421     */
422     Label = 0;
423     if (AM == AM65_BRA) {
424
425         /* Generate the hash over the label, then search for the label */
426         unsigned Hash = HashStr (Arg) % CS_LABEL_HASH_SIZE;
427         Label = CS_FindLabel (S, Arg, Hash);
428
429         /* If we don't have the label, it's a forward ref - create it */
430         if (Label == 0) {
431             /* Generate a new label */
432             Label = CS_NewCodeLabel (S, Arg, Hash);
433         }
434     }
435
436     /* We do now have the addressing mode in AM. Allocate a new CodeEntry
437     ** structure and initialize it.
438     */
439     E = NewCodeEntry (OPC->OPC, AM, Arg, Label, LI);
440
441     /* Return the new code entry */
442     return E;
443 }
444
445
446
447 /*****************************************************************************/
448 /*                                   Code                                    */
449 /*****************************************************************************/
450
451
452
453 CodeSeg* NewCodeSeg (const char* SegName, SymEntry* Func)
454 /* Create a new code segment, initialize and return it */
455 {
456     unsigned I;
457     const Type* RetType;
458
459     /* Allocate memory */
460     CodeSeg* S = xmalloc (sizeof (CodeSeg));
461
462     /* Initialize the fields */
463     S->SegName  = xstrdup (SegName);
464     S->Func     = Func;
465     InitCollection (&S->Entries);
466     InitCollection (&S->Labels);
467     for (I = 0; I < sizeof(S->LabelHash) / sizeof(S->LabelHash[0]); ++I) {
468         S->LabelHash[I] = 0;
469     }
470
471     /* If we have a function given, get the return type of the function.
472     ** Assume ANY return type besides void will use the A and X registers.
473     */
474     if (S->Func && !IsTypeVoid ((RetType = GetFuncReturn (Func->Type)))) {
475         if (SizeOf (RetType) == SizeOf (type_long)) {
476             S->ExitRegs = REG_EAX;
477         } else {
478             S->ExitRegs = REG_AX;
479         }
480     } else {
481         S->ExitRegs = REG_NONE;
482     }
483
484     /* Copy the global optimization settings */
485     S->Optimize       = (unsigned char) IS_Get (&Optimize);
486     S->CodeSizeFactor = (unsigned) IS_Get (&CodeSizeFactor);
487
488     /* Return the new struct */
489     return S;
490 }
491
492
493
494 void CS_AddEntry (CodeSeg* S, struct CodeEntry* E)
495 /* Add an entry to the given code segment */
496 {
497     /* Transfer the labels if we have any */
498     CS_MoveLabelsToEntry (S, E);
499
500     /* Add the entry to the list of code entries in this segment */
501     CollAppend (&S->Entries, E);
502 }
503
504
505
506 void CS_AddVLine (CodeSeg* S, LineInfo* LI, const char* Format, va_list ap)
507 /* Add a line to the given code segment */
508 {
509     const char* L;
510     CodeEntry*  E;
511     char        Token[IDENTSIZE+10];
512
513     /* Format the line */
514     StrBuf Buf = STATIC_STRBUF_INITIALIZER;
515     SB_VPrintf (&Buf, Format, ap);
516
517     /* Skip whitespace */
518     L = SkipSpace (SB_GetConstBuf (&Buf));
519
520     /* Check which type of instruction we have */
521     E = 0;      /* Assume no insn created */
522     switch (*L) {
523
524         case '\0':
525             /* Empty line, just ignore it */
526             break;
527
528         case ';':
529             /* Comment or hint, ignore it for now */
530             break;
531
532         case '.':
533             /* Control instruction */
534             ReadToken (L, " \t", Token, sizeof (Token));
535             Error ("ASM code error: Pseudo instruction '%s' not supported", Token);
536             break;
537
538         default:
539             E = ParseInsn (S, LI, L);
540             break;
541     }
542
543     /* If we have a code entry, transfer the labels and insert it */
544     if (E) {
545         CS_AddEntry (S, E);
546     }
547
548     /* Cleanup the string buffer */
549     SB_Done (&Buf);
550 }
551
552
553
554 void CS_AddLine (CodeSeg* S, LineInfo* LI, const char* Format, ...)
555 /* Add a line to the given code segment */
556 {
557     va_list ap;
558     va_start (ap, Format);
559     CS_AddVLine (S, LI, Format, ap);
560     va_end (ap);
561 }
562
563
564
565 void CS_InsertEntry (CodeSeg* S, struct CodeEntry* E, unsigned Index)
566 /* Insert the code entry at the index given. Following code entries will be
567 ** moved to slots with higher indices.
568 */
569 {
570     /* Insert the entry into the collection */
571     CollInsert (&S->Entries, E, Index);
572 }
573
574
575
576 void CS_DelEntry (CodeSeg* S, unsigned Index)
577 /* Delete an entry from the code segment. This includes moving any associated
578 ** labels, removing references to labels and even removing the referenced labels
579 ** if the reference count drops to zero.
580 ** Note: Labels are moved forward if possible, that is, they are moved to the
581 ** next insn (not the preceeding one).
582 */
583 {
584     /* Get the code entry for the given index */
585     CodeEntry* E = CS_GetEntry (S, Index);
586
587     /* If the entry has a labels, we have to move this label to the next insn.
588     ** If there is no next insn, move the label into the code segement label
589     ** pool. The operation is further complicated by the fact that the next
590     ** insn may already have a label. In that case change all reference to
591     ** this label and delete the label instead of moving it.
592     */
593     unsigned Count = CE_GetLabelCount (E);
594     if (Count > 0) {
595
596         /* The instruction has labels attached. Check if there is a next
597         ** instruction.
598         */
599         if (Index == CS_GetEntryCount (S)-1) {
600
601             /* No next instruction, move to the codeseg label pool */
602             CS_MoveLabelsToPool (S, E);
603
604         } else {
605
606             /* There is a next insn, get it */
607             CodeEntry* N = CS_GetEntry (S, Index+1);
608
609             /* Move labels to the next entry */
610             CS_MoveLabels (S, E, N);
611
612         }
613     }
614
615     /* If this insn references a label, remove the reference. And, if the
616     ** the reference count for this label drops to zero, remove this label.
617     */
618     if (E->JumpTo) {
619         /* Remove the reference */
620         CS_RemoveLabelRef (S, E);
621     }
622
623     /* Delete the pointer to the insn */
624     CollDelete (&S->Entries, Index);
625
626     /* Delete the instruction itself */
627     FreeCodeEntry (E);
628 }
629
630
631
632 void CS_DelEntries (CodeSeg* S, unsigned Start, unsigned Count)
633 /* Delete a range of code entries. This includes removing references to labels,
634 ** labels attached to the entries and so on.
635 */
636 {
637     /* Start deleting the entries from the rear, because this involves less
638     ** memory moving.
639     */
640     while (Count--) {
641         CS_DelEntry (S, Start + Count);
642     }
643 }
644
645
646
647 void CS_MoveEntries (CodeSeg* S, unsigned Start, unsigned Count, unsigned NewPos)
648 /* Move a range of entries from one position to another. Start is the index
649 ** of the first entry to move, Count is the number of entries and NewPos is
650 ** the index of the target entry. The entry with the index Start will later
651 ** have the index NewPos. All entries with indices NewPos and above are
652 ** moved to higher indices. If the code block is moved to the end of the
653 ** current code, and if pending labels exist, these labels will get attached
654 ** to the first instruction of the moved block (the first one after the
655 ** current code end)
656 */
657 {
658     /* Transparently handle an empty range */
659     if (Count == 0) {
660         return;
661     }
662
663     /* If NewPos is at the end of the code segment, move any labels from the
664     ** label pool to the first instruction of the moved range.
665     */
666     if (NewPos == CS_GetEntryCount (S)) {
667         CS_MoveLabelsToEntry (S, CS_GetEntry (S, Start));
668     }
669
670     /* Move the code block to the destination */
671     CollMoveMultiple (&S->Entries, Start, Count, NewPos);
672 }
673
674
675
676 struct CodeEntry* CS_GetPrevEntry (CodeSeg* S, unsigned Index)
677 /* Get the code entry preceeding the one with the index Index. If there is no
678 ** preceeding code entry, return NULL.
679 */
680 {
681     if (Index == 0) {
682         /* This is the first entry */
683         return 0;
684     } else {
685         /* Previous entry available */
686         return CollAtUnchecked (&S->Entries, Index-1);
687     }
688 }
689
690
691
692 struct CodeEntry* CS_GetNextEntry (CodeSeg* S, unsigned Index)
693 /* Get the code entry following the one with the index Index. If there is no
694 ** following code entry, return NULL.
695 */
696 {
697     if (Index >= CollCount (&S->Entries)-1) {
698         /* This is the last entry */
699         return 0;
700     } else {
701         /* Code entries left */
702         return CollAtUnchecked (&S->Entries, Index+1);
703     }
704 }
705
706
707
708 int CS_GetEntries (CodeSeg* S, struct CodeEntry** List,
709                    unsigned Start, unsigned Count)
710 /* Get Count code entries into List starting at index start. Return true if
711 ** we got the lines, return false if not enough lines were available.
712 */
713 {
714     /* Check if enough entries are available */
715     if (Start + Count > CollCount (&S->Entries)) {
716         return 0;
717     }
718
719     /* Copy the entries */
720     while (Count--) {
721         *List++ = CollAtUnchecked (&S->Entries, Start++);
722     }
723
724     /* We have the entries */
725     return 1;
726 }
727
728
729
730 unsigned CS_GetEntryIndex (CodeSeg* S, struct CodeEntry* E)
731 /* Return the index of a code entry */
732 {
733     int Index = CollIndex (&S->Entries, E);
734     CHECK (Index >= 0);
735     return Index;
736 }
737
738
739
740 int CS_RangeHasLabel (CodeSeg* S, unsigned Start, unsigned Count)
741 /* Return true if any of the code entries in the given range has a label
742 ** attached. If the code segment does not span the given range, check the
743 ** possible span instead.
744 */
745 {
746     unsigned EntryCount = CS_GetEntryCount(S);
747
748     /* Adjust count. We expect at least Start to be valid. */
749     CHECK (Start < EntryCount);
750     if (Start + Count > EntryCount) {
751         Count = EntryCount - Start;
752     }
753
754     /* Check each entry. Since we have validated the index above, we may
755     ** use the unchecked access function in the loop which is faster.
756     */
757     while (Count--) {
758         const CodeEntry* E = CollAtUnchecked (&S->Entries, Start++);
759         if (CE_HasLabel (E)) {
760             return 1;
761         }
762     }
763
764     /* No label in the complete range */
765     return 0;
766 }
767
768
769
770 CodeLabel* CS_AddLabel (CodeSeg* S, const char* Name)
771 /* Add a code label for the next instruction to follow */
772 {
773     /* Calculate the hash from the name */
774     unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
775
776     /* Try to find the code label if it does already exist */
777     CodeLabel* L = CS_FindLabel (S, Name, Hash);
778
779     /* Did we find it? */
780     if (L) {
781         /* We found it - be sure it does not already have an owner */
782         if (L->Owner) {
783             Error ("ASM label '%s' is already defined", Name);
784             return L;
785         }
786     } else {
787         /* Not found - create a new one */
788         L = CS_NewCodeLabel (S, Name, Hash);
789     }
790
791     /* Safety. This call is quite costly, but safety is better */
792     if (CollIndex (&S->Labels, L) >= 0) {
793         Error ("ASM label '%s' is already defined", Name);
794         return L;
795     }
796
797     /* We do now have a valid label. Remember it for later */
798     CollAppend (&S->Labels, L);
799
800     /* Return the label */
801     return L;
802 }
803
804
805
806 CodeLabel* CS_GenLabel (CodeSeg* S, struct CodeEntry* E)
807 /* If the code entry E does already have a label, return it. Otherwise
808 ** create a new label, attach it to E and return it.
809 */
810 {
811     CodeLabel* L;
812
813     if (CE_HasLabel (E)) {
814
815         /* Get the label from this entry */
816         L = CE_GetLabel (E, 0);
817
818     } else {
819
820         /* Get a new name */
821         const char* Name = LocalLabelName (GetLocalLabel ());
822
823         /* Generate the hash over the name */
824         unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
825
826         /* Create a new label */
827         L = CS_NewCodeLabel (S, Name, Hash);
828
829         /* Attach this label to the code entry */
830         CE_AttachLabel (E, L);
831
832     }
833
834     /* Return the label */
835     return L;
836 }
837
838
839
840 void CS_DelLabel (CodeSeg* S, CodeLabel* L)
841 /* Remove references from this label and delete it. */
842 {
843     unsigned Count, I;
844
845     /* First, remove the label from the hash chain */
846     CS_RemoveLabelFromHash (S, L);
847
848     /* Remove references from insns jumping to this label */
849     Count = CollCount (&L->JumpFrom);
850     for (I = 0; I < Count; ++I) {
851         /* Get the insn referencing this label */
852         CodeEntry* E = CollAt (&L->JumpFrom, I);
853         /* Remove the reference */
854         CE_ClearJumpTo (E);
855     }
856     CollDeleteAll (&L->JumpFrom);
857
858     /* Remove the reference to the owning instruction if it has one. The
859     ** function may be called for a label without an owner when deleting
860     ** unfinished parts of the code. This is unfortunate since it allows
861     ** errors to slip through.
862     */
863     if (L->Owner) {
864         CollDeleteItem (&L->Owner->Labels, L);
865     }
866
867     /* All references removed, delete the label itself */
868     FreeCodeLabel (L);
869 }
870
871
872
873 void CS_MergeLabels (CodeSeg* S)
874 /* Merge code labels. That means: For each instruction, remove all labels but
875 ** one and adjust references accordingly.
876 */
877 {
878     unsigned I;
879     unsigned J;
880
881     /* First, remove all labels from the label symbol table that don't have an
882     ** owner (this means that they are actually external labels but we didn't
883     ** know that previously since they may have also been forward references).
884     */
885     for (I = 0; I < CS_LABEL_HASH_SIZE; ++I) {
886
887         /* Get the first label in this hash chain */
888         CodeLabel** L = &S->LabelHash[I];
889         while (*L) {
890             if ((*L)->Owner == 0) {
891
892                 /* The label does not have an owner, remove it from the chain */
893                 CodeLabel* X = *L;
894                 *L = X->Next;
895
896                 /* Cleanup any entries jumping to this label */
897                 for (J = 0; J < CL_GetRefCount (X); ++J) {
898                     /* Get the entry referencing this label */
899                     CodeEntry* E = CL_GetRef (X, J);
900                     /* And remove the reference. Do NOT call CE_ClearJumpTo
901                     ** here, because this will also clear the label name,
902                     ** which is not what we want.
903                     */
904                     E->JumpTo = 0;
905                 }
906
907                 /* Print some debugging output */
908                 if (Debug) {
909                     printf ("Removing unused global label '%s'", X->Name);
910                 }
911
912                 /* And free the label */
913                 FreeCodeLabel (X);
914             } else {
915                 /* Label is owned, point to next code label pointer */
916                 L = &((*L)->Next);
917             }
918         }
919     }
920
921     /* Walk over all code entries */
922     for (I = 0; I < CS_GetEntryCount (S); ++I) {
923
924         CodeLabel* RefLab;
925         unsigned   J;
926
927         /* Get a pointer to the next entry */
928         CodeEntry* E = CS_GetEntry (S, I);
929
930         /* If this entry has zero labels, continue with the next one */
931         unsigned LabelCount = CE_GetLabelCount (E);
932         if (LabelCount == 0) {
933             continue;
934         }
935
936         /* We have at least one label. Use the first one as reference label. */
937         RefLab = CE_GetLabel (E, 0);
938
939         /* Walk through the remaining labels and change references to these
940         ** labels to a reference to the one and only label. Delete the labels
941         ** that are no longer used. To increase performance, walk backwards
942         ** through the list.
943         */
944         for (J = LabelCount-1; J >= 1; --J) {
945
946             /* Get the next label */
947             CodeLabel* L = CE_GetLabel (E, J);
948
949             /* Move all references from this label to the reference label */
950             CL_MoveRefs (L, RefLab);
951
952             /* Remove the label completely. */
953             CS_DelLabel (S, L);
954         }
955
956         /* The reference label is the only remaining label. Check if there
957         ** are any references to this label, and delete it if this is not
958         ** the case.
959         */
960         if (CollCount (&RefLab->JumpFrom) == 0) {
961             /* Delete the label */
962             CS_DelLabel (S, RefLab);
963         }
964     }
965 }
966
967
968
969 void CS_MoveLabels (CodeSeg* S, struct CodeEntry* Old, struct CodeEntry* New)
970 /* Move all labels from Old to New. The routine will move the labels itself
971 ** if New does not have any labels, and move references if there is at least
972 ** a label for new. If references are moved, the old label is deleted
973 ** afterwards.
974 */
975 {
976     /* Get the number of labels to move */
977     unsigned OldLabelCount = CE_GetLabelCount (Old);
978
979     /* Does the new entry have itself a label? */
980     if (CE_HasLabel (New)) {
981
982         /* The new entry does already have a label - move references */
983         CodeLabel* NewLabel = CE_GetLabel (New, 0);
984         while (OldLabelCount--) {
985
986             /* Get the next label */
987             CodeLabel* OldLabel = CE_GetLabel (Old, OldLabelCount);
988
989             /* Move references */
990             CL_MoveRefs (OldLabel, NewLabel);
991
992             /* Delete the label */
993             CS_DelLabel (S, OldLabel);
994
995         }
996
997     } else {
998
999         /* The new entry does not have a label, just move them */
1000         while (OldLabelCount--) {
1001
1002             /* Move the label to the new entry */
1003             CE_MoveLabel (CE_GetLabel (Old, OldLabelCount), New);
1004
1005         }
1006
1007     }
1008 }
1009
1010
1011
1012 void CS_RemoveLabelRef (CodeSeg* S, struct CodeEntry* E)
1013 /* Remove the reference between E and the label it jumps to. The reference
1014 ** will be removed on both sides and E->JumpTo will be 0 after that. If
1015 ** the reference was the only one for the label, the label will get
1016 ** deleted.
1017 */
1018 {
1019     /* Get a pointer to the label and make sure it exists */
1020     CodeLabel* L = E->JumpTo;
1021     CHECK (L != 0);
1022
1023     /* Delete the entry from the label */
1024     CollDeleteItem (&L->JumpFrom, E);
1025
1026     /* The entry jumps no longer to L */
1027     CE_ClearJumpTo (E);
1028
1029     /* If there are no more references, delete the label */
1030     if (CollCount (&L->JumpFrom) == 0) {
1031         CS_DelLabel (S, L);
1032     }
1033 }
1034
1035
1036
1037 void CS_MoveLabelRef (CodeSeg* S, struct CodeEntry* E, CodeLabel* L)
1038 /* Change the reference of E to L instead of the current one. If this
1039 ** was the only reference to the old label, the old label will get
1040 ** deleted.
1041 */
1042 {
1043     /* Get the old label */
1044     CodeLabel* OldLabel = E->JumpTo;
1045
1046     /* Be sure that code entry references a label */
1047     PRECONDITION (OldLabel != 0);
1048
1049     /* Remove the reference to our label */
1050     CS_RemoveLabelRef (S, E);
1051
1052     /* Use the new label */
1053     CL_AddRef (L, E);
1054 }
1055
1056
1057
1058 void CS_DelCodeRange (CodeSeg* S, unsigned First, unsigned Last)
1059 /* Delete all entries between first and last, both inclusive. The function
1060 ** can only handle basic blocks (First is the only entry, Last the only exit)
1061 ** and no open labels. It will call FAIL if any of these preconditions are
1062 ** violated.
1063 */
1064 {
1065     unsigned   I;
1066     CodeEntry* FirstEntry;
1067
1068     /* Do some sanity checks */
1069     CHECK (First <= Last && Last < CS_GetEntryCount (S));
1070
1071     /* If Last is actually the last insn, call CS_DelCodeAfter instead, which
1072     ** is more flexible in this case.
1073     */
1074     if (Last == CS_GetEntryCount (S) - 1) {
1075         CS_DelCodeAfter (S, First);
1076         return;
1077     }
1078
1079     /* Get the first entry and check if it has any labels. If it has, move
1080     ** them to the insn following Last. If Last is the last insn of the code
1081     ** segment, make them ownerless and move them to the label pool.
1082     */
1083     FirstEntry = CS_GetEntry (S, First);
1084     if (CE_HasLabel (FirstEntry)) {
1085         /* Get the entry following last */
1086         CodeEntry* FollowingEntry = CS_GetNextEntry (S, Last);
1087         if (FollowingEntry) {
1088             /* There is an entry after Last - move the labels */
1089             CS_MoveLabels (S, FirstEntry, FollowingEntry);
1090         } else {
1091             /* Move the labels to the pool and clear the owner pointer */
1092             CS_MoveLabelsToPool (S, FirstEntry);
1093         }
1094     }
1095
1096     /* First pass: Delete all references to labels. If the reference count
1097     ** for a label drops to zero, delete it.
1098     */
1099     for (I = Last; I >= First; --I) {
1100
1101         /* Get the next entry */
1102         CodeEntry* E = CS_GetEntry (S, I);
1103
1104         /* Check if this entry has a label reference */
1105         if (E->JumpTo) {
1106
1107             /* If the label is a label in the label pool, this is an error */
1108             CodeLabel* L = E->JumpTo;
1109             CHECK (CollIndex (&S->Labels, L) < 0);
1110
1111             /* Remove the reference to the label */
1112             CS_RemoveLabelRef (S, E);
1113         }
1114     }
1115
1116     /* Second pass: Delete the instructions. If a label attached to an
1117     ** instruction still has references, it must be references from outside
1118     ** the deleted area, which is an error.
1119     */
1120     for (I = Last; I >= First; --I) {
1121
1122         /* Get the next entry */
1123         CodeEntry* E = CS_GetEntry (S, I);
1124
1125         /* Check if this entry has a label attached */
1126         CHECK (!CE_HasLabel (E));
1127
1128         /* Delete the pointer to the entry */
1129         CollDelete (&S->Entries, I);
1130
1131         /* Delete the entry itself */
1132         FreeCodeEntry (E);
1133     }
1134 }
1135
1136
1137
1138 void CS_DelCodeAfter (CodeSeg* S, unsigned Last)
1139 /* Delete all entries including the given one */
1140 {
1141     /* Get the number of entries in this segment */
1142     unsigned Count = CS_GetEntryCount (S);
1143
1144     /* First pass: Delete all references to labels. If the reference count
1145     ** for a label drops to zero, delete it.
1146     */
1147     unsigned C = Count;
1148     while (Last < C--) {
1149
1150         /* Get the next entry */
1151         CodeEntry* E = CS_GetEntry (S, C);
1152
1153         /* Check if this entry has a label reference */
1154         if (E->JumpTo) {
1155             /* If the label is a label in the label pool and this is the last
1156             ** reference to the label, remove the label from the pool.
1157             */
1158             CodeLabel* L = E->JumpTo;
1159             int Index = CollIndex (&S->Labels, L);
1160             if (Index >= 0 && CollCount (&L->JumpFrom) == 1) {
1161                 /* Delete it from the pool */
1162                 CollDelete (&S->Labels, Index);
1163             }
1164
1165             /* Remove the reference to the label */
1166             CS_RemoveLabelRef (S, E);
1167         }
1168
1169     }
1170
1171     /* Second pass: Delete the instructions. If a label attached to an
1172     ** instruction still has references, it must be references from outside
1173     ** the deleted area. Don't delete the label in this case, just make it
1174     ** ownerless and move it to the label pool.
1175     */
1176     C = Count;
1177     while (Last < C--) {
1178
1179         /* Get the next entry */
1180         CodeEntry* E = CS_GetEntry (S, C);
1181
1182         /* Check if this entry has a label attached */
1183         if (CE_HasLabel (E)) {
1184             /* Move the labels to the pool and clear the owner pointer */
1185             CS_MoveLabelsToPool (S, E);
1186         }
1187
1188         /* Delete the pointer to the entry */
1189         CollDelete (&S->Entries, C);
1190
1191         /* Delete the entry itself */
1192         FreeCodeEntry (E);
1193     }
1194 }
1195
1196
1197
1198 void CS_ResetMarks (CodeSeg* S, unsigned First, unsigned Last)
1199 /* Remove all user marks from the entries in the given range */
1200 {
1201     while (First <= Last) {
1202         CE_ResetMark (CS_GetEntry (S, First++));
1203     }
1204 }
1205
1206
1207
1208 int CS_IsBasicBlock (CodeSeg* S, unsigned First, unsigned Last)
1209 /* Check if the given code segment range is a basic block. That is, check if
1210 ** First is the only entrance and Last is the only exit. This means that no
1211 ** jump/branch inside the block may jump to an insn below First or after(!)
1212 ** Last, and that no insn may jump into this block from the outside.
1213 */
1214 {
1215     unsigned I;
1216
1217     /* Don't accept invalid ranges */
1218     CHECK (First <= Last);
1219
1220     /* First pass: Walk over the range and remove all marks from the entries */
1221     CS_ResetMarks (S, First, Last);
1222
1223     /* Second pass: Walk over the range checking all labels. Note: There may be
1224     ** label on the first insn which is ok.
1225     */
1226     I = First + 1;
1227     while (I <= Last) {
1228
1229         /* Get the next entry */
1230         CodeEntry* E = CS_GetEntry (S, I);
1231
1232         /* Check if this entry has one or more labels, if so, check which
1233         ** entries jump to this label.
1234         */
1235         unsigned LabelCount = CE_GetLabelCount (E);
1236         unsigned LabelIndex;
1237         for (LabelIndex = 0; LabelIndex < LabelCount; ++LabelIndex) {
1238
1239             /* Get this label */
1240             CodeLabel* L = CE_GetLabel (E, LabelIndex);
1241
1242             /* Walk over all entries that jump to this label. Check for each
1243             ** of the entries if it is out of the range.
1244             */
1245             unsigned RefCount = CL_GetRefCount (L);
1246             unsigned RefIndex;
1247             for (RefIndex = 0; RefIndex < RefCount; ++RefIndex) {
1248
1249                 /* Get the code entry that jumps here */
1250                 CodeEntry* Ref = CL_GetRef (L, RefIndex);
1251
1252                 /* Walk over out complete range and check if we find the
1253                 ** refering entry. This is cheaper than using CS_GetEntryIndex,
1254                 ** because CS_GetEntryIndex will search the complete code
1255                 ** segment and not just our range.
1256                 */
1257                 unsigned J;
1258                 for (J = First; J <= Last; ++J) {
1259                     if (Ref == CS_GetEntry (S, J)) {
1260                         break;
1261                     }
1262                 }
1263                 if (J > Last) {
1264                     /* We did not find the entry. This means that the jump to
1265                     ** out code segment entry E came from outside the range,
1266                     ** which in turn means that the given range is not a basic
1267                     ** block.
1268                     */
1269                     CS_ResetMarks (S, First, Last);
1270                     return 0;
1271                 }
1272
1273                 /* If we come here, we found the entry. Mark it, so we know
1274                 ** that the branch to the label is in range.
1275                 */
1276                 CE_SetMark (Ref);
1277             }
1278         }
1279
1280         /* Next entry */
1281         ++I;
1282     }
1283
1284     /* Third pass: Walk again over the range and check all branches. If we
1285     ** find a branch that is not marked, its target is not inside the range
1286     ** (since we checked all the labels in the range before).
1287     */
1288     I = First;
1289     while (I <= Last) {
1290
1291         /* Get the next entry */
1292         CodeEntry* E = CS_GetEntry (S, I);
1293
1294         /* Check if this is a branch and if so, if it has a mark */
1295         if (E->Info & (OF_UBRA | OF_CBRA)) {
1296             if (!CE_HasMark (E)) {
1297                 /* No mark means not a basic block. Before bailing out, be sure
1298                 ** to remove the marks from the remaining entries.
1299                 */
1300                 CS_ResetMarks (S, I+1, Last);
1301                 return 0;
1302             }
1303
1304             /* Remove the mark */
1305             CE_ResetMark (E);
1306         }
1307
1308         /* Next entry */
1309         ++I;
1310     }
1311
1312     /* Done - this is a basic block */
1313     return 1;
1314 }
1315
1316
1317
1318 void CS_OutputPrologue (const CodeSeg* S)
1319 /* If the given code segment is a code segment for a function, output the
1320 ** assembler prologue into the file. That is: Output a comment header, switch
1321 ** to the correct segment and enter the local function scope. If the code
1322 ** segment is global, do nothing.
1323 */
1324 {
1325     /* Get the function associated with the code segment */
1326     SymEntry* Func = S->Func;
1327
1328     /* If the code segment is associated with a function, print a function
1329     ** header and enter a local scope. Be sure to switch to the correct
1330     ** segment before outputing the function label.
1331     */
1332     if (Func) {
1333         /* Get the function descriptor */
1334         CS_PrintFunctionHeader (S);
1335         WriteOutput (".segment\t\"%s\"\n\n.proc\t_%s", S->SegName, Func->Name);
1336         if (IsQualNear (Func->Type)) {
1337             WriteOutput (": near");
1338         } else if (IsQualFar (Func->Type)) {
1339             WriteOutput (": far");
1340         }
1341         WriteOutput ("\n\n");
1342     }
1343
1344 }
1345
1346
1347
1348 void CS_OutputEpilogue (const CodeSeg* S)
1349 /* If the given code segment is a code segment for a function, output the
1350 ** assembler epilogue into the file. That is: Close the local function scope.
1351 */
1352 {
1353     if (S->Func) {
1354         WriteOutput ("\n.endproc\n\n");
1355     }
1356 }
1357
1358
1359
1360 void CS_Output (CodeSeg* S)
1361 /* Output the code segment data to the output file */
1362 {
1363     unsigned I;
1364     const LineInfo* LI;
1365
1366     /* Get the number of entries in this segment */
1367     unsigned Count = CS_GetEntryCount (S);
1368
1369     /* If the code segment is empty, bail out here */
1370     if (Count == 0) {
1371         return;
1372     }
1373
1374     /* Generate register info */
1375     CS_GenRegInfo (S);
1376
1377     /* Output the segment directive */
1378     WriteOutput (".segment\t\"%s\"\n\n", S->SegName);
1379
1380     /* Output all entries, prepended by the line information if it has changed */
1381     LI = 0;
1382     for (I = 0; I < Count; ++I) {
1383         /* Get the next entry */
1384         const CodeEntry* E = CollConstAt (&S->Entries, I);
1385         /* Check if the line info has changed. If so, output the source line
1386         ** if the option is enabled and output debug line info if the debug
1387         ** option is enabled.
1388         */
1389         if (E->LI != LI) {
1390             /* Line info has changed, remember the new line info */
1391             LI = E->LI;
1392
1393             /* Add the source line as a comment. Beware: When line continuation
1394             ** was used, the line may contain newlines.
1395             */
1396             if (AddSource) {
1397                 const char* L = LI->Line;
1398                 WriteOutput (";\n; ");
1399                 while (*L) {
1400                     const char* N = strchr (L, '\n');
1401                     if (N) {
1402                         /* We have a newline, just write the first part */
1403                         WriteOutput ("%.*s\n; ", (int) (N - L), L);
1404                         L = N+1;
1405                     } else {
1406                         /* No Newline, write as is */
1407                         WriteOutput ("%s\n", L);
1408                         break;
1409                     }
1410                 }
1411                 WriteOutput (";\n");
1412             }
1413
1414             /* Add line debug info */
1415             if (DebugInfo) {
1416                 WriteOutput ("\t.dbg\tline, \"%s\", %u\n",
1417                              GetInputName (LI), GetInputLine (LI));
1418             }
1419         }
1420         /* Output the code */
1421         CE_Output (E);
1422     }
1423
1424     /* If debug info is enabled, terminate the last line number information */
1425     if (DebugInfo) {
1426         WriteOutput ("\t.dbg\tline\n");
1427     }
1428
1429     /* Free register info */
1430     CS_FreeRegInfo (S);
1431 }
1432
1433
1434
1435 void CS_FreeRegInfo (CodeSeg* S)
1436 /* Free register infos for all instructions */
1437 {
1438     unsigned I;
1439     for (I = 0; I < CS_GetEntryCount (S); ++I) {
1440         CE_FreeRegInfo (CS_GetEntry(S, I));
1441     }
1442 }
1443
1444
1445
1446 void CS_GenRegInfo (CodeSeg* S)
1447 /* Generate register infos for all instructions */
1448 {
1449     unsigned I;
1450     RegContents Regs;           /* Initial register contents */
1451     RegContents* CurrentRegs;   /* Current register contents */
1452     int WasJump;                /* True if last insn was a jump */
1453     int Done;                   /* All runs done flag */
1454
1455     /* Be sure to delete all register infos */
1456     CS_FreeRegInfo (S);
1457
1458     /* We may need two runs to get back references right */
1459     do {
1460
1461         /* Assume we're done after this run */
1462         Done = 1;
1463
1464         /* On entry, the register contents are unknown */
1465         RC_Invalidate (&Regs);
1466         CurrentRegs = &Regs;
1467
1468         /* Walk over all insns and note just the changes from one insn to the
1469         ** next one.
1470         */
1471         WasJump = 0;
1472         for (I = 0; I < CS_GetEntryCount (S); ++I) {
1473
1474             CodeEntry* P;
1475
1476             /* Get the next instruction */
1477             CodeEntry* E = CollAtUnchecked (&S->Entries, I);
1478
1479             /* If the instruction has a label, we need some special handling */
1480             unsigned LabelCount = CE_GetLabelCount (E);
1481             if (LabelCount > 0) {
1482
1483                 /* Loop over all entry points that jump here. If these entry
1484                 ** points already have register info, check if all values are
1485                 ** known and identical. If all values are identical, and the
1486                 ** preceeding instruction was not an unconditional branch, check
1487                 ** if the register value on exit of the preceeding instruction
1488                 ** is also identical. If all these values are identical, the
1489                 ** value of a register is known, otherwise it is unknown.
1490                 */
1491                 CodeLabel* Label = CE_GetLabel (E, 0);
1492                 unsigned Entry;
1493                 if (WasJump) {
1494                     /* Preceeding insn was an unconditional branch */
1495                     CodeEntry* J = CL_GetRef(Label, 0);
1496                     if (J->RI) {
1497                         Regs = J->RI->Out2;
1498                     } else {
1499                         RC_Invalidate (&Regs);
1500                     }
1501                     Entry = 1;
1502                 } else {
1503                     Regs = *CurrentRegs;
1504                     Entry = 0;
1505                 }
1506
1507                 while (Entry < CL_GetRefCount (Label)) {
1508                     /* Get this entry */
1509                     CodeEntry* J = CL_GetRef (Label, Entry);
1510                     if (J->RI == 0) {
1511                         /* No register info for this entry. This means that the
1512                         ** instruction that jumps here is at higher addresses and
1513                         ** the jump is a backward jump. We need a second run to
1514                         ** get the register info right in this case. Until then,
1515                         ** assume unknown register contents.
1516                         */
1517                         Done = 0;
1518                         RC_Invalidate (&Regs);
1519                         break;
1520                     }
1521                     if (J->RI->Out2.RegA != Regs.RegA) {
1522                         Regs.RegA = UNKNOWN_REGVAL;
1523                     }
1524                     if (J->RI->Out2.RegX != Regs.RegX) {
1525                         Regs.RegX = UNKNOWN_REGVAL;
1526                     }
1527                     if (J->RI->Out2.RegY != Regs.RegY) {
1528                         Regs.RegY = UNKNOWN_REGVAL;
1529                     }
1530                     if (J->RI->Out2.SRegLo != Regs.SRegLo) {
1531                         Regs.SRegLo = UNKNOWN_REGVAL;
1532                     }
1533                     if (J->RI->Out2.SRegHi != Regs.SRegHi) {
1534                         Regs.SRegHi = UNKNOWN_REGVAL;
1535                     }
1536                     if (J->RI->Out2.Tmp1 != Regs.Tmp1) {
1537                         Regs.Tmp1 = UNKNOWN_REGVAL;
1538                     }
1539                     ++Entry;
1540                 }
1541
1542                 /* Use this register info */
1543                 CurrentRegs = &Regs;
1544
1545             }
1546
1547             /* Generate register info for this instruction */
1548             CE_GenRegInfo (E, CurrentRegs);
1549
1550             /* Remember for the next insn if this insn was an uncondition branch */
1551             WasJump = (E->Info & OF_UBRA) != 0;
1552
1553             /* Output registers for this insn are input for the next */
1554             CurrentRegs = &E->RI->Out;
1555
1556             /* If this insn is a branch on zero flag, we may have more info on
1557             ** register contents for one of both flow directions, but only if
1558             ** there is a previous instruction.
1559             */
1560             if ((E->Info & OF_ZBRA) != 0 && (P = CS_GetPrevEntry (S, I)) != 0) {
1561
1562                 /* Get the branch condition */
1563                 bc_t BC = GetBranchCond (E->OPC);
1564
1565                 /* Check the previous instruction */
1566                 switch (P->OPC) {
1567
1568                     case OP65_ADC:
1569                     case OP65_AND:
1570                     case OP65_DEA:
1571                     case OP65_EOR:
1572                     case OP65_INA:
1573                     case OP65_LDA:
1574                     case OP65_ORA:
1575                     case OP65_PLA:
1576                     case OP65_SBC:
1577                         /* A is zero in one execution flow direction */
1578                         if (BC == BC_EQ) {
1579                             E->RI->Out2.RegA = 0;
1580                         } else {
1581                             E->RI->Out.RegA = 0;
1582                         }
1583                         break;
1584
1585                     case OP65_CMP:
1586                         /* If this is an immidiate compare, the A register has
1587                         ** the value of the compare later.
1588                         */
1589                         if (CE_IsConstImm (P)) {
1590                             if (BC == BC_EQ) {
1591                                 E->RI->Out2.RegA = (unsigned char)P->Num;
1592                             } else {
1593                                 E->RI->Out.RegA = (unsigned char)P->Num;
1594                             }
1595                         }
1596                         break;
1597
1598                     case OP65_CPX:
1599                         /* If this is an immidiate compare, the X register has
1600                         ** the value of the compare later.
1601                         */
1602                         if (CE_IsConstImm (P)) {
1603                             if (BC == BC_EQ) {
1604                                 E->RI->Out2.RegX = (unsigned char)P->Num;
1605                             } else {
1606                                 E->RI->Out.RegX = (unsigned char)P->Num;
1607                             }
1608                         }
1609                         break;
1610
1611                     case OP65_CPY:
1612                         /* If this is an immidiate compare, the Y register has
1613                         ** the value of the compare later.
1614                         */
1615                         if (CE_IsConstImm (P)) {
1616                             if (BC == BC_EQ) {
1617                                 E->RI->Out2.RegY = (unsigned char)P->Num;
1618                             } else {
1619                                 E->RI->Out.RegY = (unsigned char)P->Num;
1620                             }
1621                         }
1622                         break;
1623
1624                     case OP65_DEX:
1625                     case OP65_INX:
1626                     case OP65_LDX:
1627                     case OP65_PLX:
1628                         /* X is zero in one execution flow direction */
1629                         if (BC == BC_EQ) {
1630                             E->RI->Out2.RegX = 0;
1631                         } else {
1632                             E->RI->Out.RegX = 0;
1633                         }
1634                         break;
1635
1636                     case OP65_DEY:
1637                     case OP65_INY:
1638                     case OP65_LDY:
1639                     case OP65_PLY:
1640                         /* X is zero in one execution flow direction */
1641                         if (BC == BC_EQ) {
1642                             E->RI->Out2.RegY = 0;
1643                         } else {
1644                             E->RI->Out.RegY = 0;
1645                         }
1646                         break;
1647
1648                     case OP65_TAX:
1649                     case OP65_TXA:
1650                         /* If the branch is a beq, both A and X are zero at the
1651                         ** branch target, otherwise they are zero at the next
1652                         ** insn.
1653                         */
1654                         if (BC == BC_EQ) {
1655                             E->RI->Out2.RegA = E->RI->Out2.RegX = 0;
1656                         } else {
1657                             E->RI->Out.RegA = E->RI->Out.RegX = 0;
1658                         }
1659                         break;
1660
1661                     case OP65_TAY:
1662                     case OP65_TYA:
1663                         /* If the branch is a beq, both A and Y are zero at the
1664                         ** branch target, otherwise they are zero at the next
1665                         ** insn.
1666                         */
1667                         if (BC == BC_EQ) {
1668                             E->RI->Out2.RegA = E->RI->Out2.RegY = 0;
1669                         } else {
1670                             E->RI->Out.RegA = E->RI->Out.RegY = 0;
1671                         }
1672                         break;
1673
1674                     default:
1675                         break;
1676
1677                 }
1678             }
1679         }
1680     } while (!Done);
1681
1682 }