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