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