]> git.sur5r.net Git - cc65/blob - src/cc65/codeseg.c
More renaming
[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_MoveLabelsToPool (CodeSeg* S, CodeEntry* E)
66 /* Move the labels of the code entry E to the label pool of the code segment */
67 {
68     unsigned LabelCount = CE_GetLabelCount (E);
69     while (LabelCount--) {
70         CodeLabel* L = CE_GetLabel (E, LabelCount);
71         L->Owner = 0;
72         CollAppend (&S->Labels, L);
73     }
74     CollDeleteAll (&E->Labels);
75 }
76
77
78
79 static CodeLabel* CS_FindLabel (CodeSeg* S, const char* Name, unsigned Hash)
80 /* Find the label with the given name. Return the label or NULL if not found */
81 {
82     /* Get the first hash chain entry */
83     CodeLabel* L = S->LabelHash[Hash];
84
85     /* Search the list */
86     while (L) {
87         if (strcmp (Name, L->Name) == 0) {
88             /* Found */
89             break;
90         }
91         L = L->Next;
92     }
93     return L;
94 }
95
96
97
98 static CodeLabel* CS_NewCodeLabel (CodeSeg* S, const char* Name, unsigned Hash)
99 /* Create a new label and insert it into the label hash table */
100 {
101     /* Create a new label */
102     CodeLabel* L = NewCodeLabel (Name, Hash);
103
104     /* Enter the label into the hash table */
105     L->Next = S->LabelHash[L->Hash];
106     S->LabelHash[L->Hash] = L;
107
108     /* Return the new label */
109     return L;
110 }
111
112
113
114 static void CS_RemoveLabelFromHash (CodeSeg* S, CodeLabel* L)
115 /* Remove the given code label from the hash list */
116 {
117     /* Get the first entry in the hash chain */
118     CodeLabel* List = S->LabelHash[L->Hash];
119     CHECK (List != 0);
120
121     /* First, remove the label from the hash chain */
122     if (List == L) {
123         /* First entry in hash chain */
124         S->LabelHash[L->Hash] = L->Next;
125     } else {
126         /* Must search through the chain */
127         while (List->Next != L) {
128             /* If we've reached the end of the chain, something is *really* wrong */
129             CHECK (List->Next != 0);
130             /* Next entry */
131             List = List->Next;
132         }
133         /* The next entry is the one, we have been searching for */
134         List->Next = L->Next;
135     }
136 }
137
138
139
140 /*****************************************************************************/
141 /*                    Functions for parsing instructions                     */
142 /*****************************************************************************/
143
144
145
146 static const char* SkipSpace (const char* S)
147 /* Skip white space and return an updated pointer */
148 {
149     while (IsSpace (*S)) {
150         ++S;
151     }
152     return S;
153 }
154
155
156
157 static const char* ReadToken (const char* L, const char* Term,
158                               char* Buf, unsigned BufSize)
159 /* Read the next token into Buf, return the updated line pointer. The
160  * token is terminated by one of the characters given in term.
161  */
162 {
163     /* Read/copy the token */
164     unsigned I = 0;
165     unsigned ParenCount = 0;
166     while (*L && (ParenCount > 0 || strchr (Term, *L) == 0)) {
167         if (I < BufSize-1) {
168             Buf[I++] = *L;
169         }
170         if (*L == ')') {
171             --ParenCount;
172         } else if (*L == '(') {
173             ++ParenCount;
174         }
175         ++L;
176     }
177
178     /* Terminate the buffer contents */
179     Buf[I] = '\0';
180
181     /* Return the updated line pointer */
182     return L;
183 }
184
185
186
187 static CodeEntry* ParseInsn (CodeSeg* S, LineInfo* LI, const char* L)
188 /* Parse an instruction nnd generate a code entry from it. If the line contains
189  * errors, output an error message and return NULL.
190  * For simplicity, we don't accept the broad range of input a "real" assembler
191  * does. The instruction and the argument are expected to be separated by
192  * white space, for example.
193  */
194 {
195     char                Mnemo[16];
196     const OPCDesc*      OPC;
197     am_t                AM = 0;         /* Initialize to keep gcc silent */
198     char                Arg[64];
199     char                Reg;
200     CodeEntry*          E;
201     CodeLabel*          Label;
202
203     /* Mnemonic */
204     L = ReadToken (L, " \t", Mnemo, sizeof (Mnemo));
205
206     /* Try to find the opcode description for the mnemonic */
207     OPC = FindOP65 (Mnemo);
208
209     /* If we didn't find the opcode, print an error and bail out */
210     if (OPC == 0) {
211         Error ("ASM code error: %s is not a valid mnemonic", Mnemo);
212         return 0;
213     }
214
215     /* Skip separator white space */
216     L = SkipSpace (L);
217
218     /* Get the addressing mode */
219     Arg[0] = '\0';
220     switch (*L) {
221
222         case '\0':
223             /* Implicit */
224             AM = AM65_IMP;
225             break;
226
227         case '#':
228             /* Immidiate */
229             StrCopy (Arg, sizeof (Arg), L+1);
230             AM = AM65_IMM;
231             break;
232
233         case '(':
234             /* Indirect */
235             L = ReadToken (L+1, ",)", Arg, sizeof (Arg));
236
237             /* Check for errors */
238             if (*L == '\0') {
239                 Error ("ASM code error: syntax error");
240                 return 0;
241             }
242
243             /* Check the different indirect modes */
244             if (*L == ',') {
245                 /* Expect zp x indirect */
246                 L = SkipSpace (L+1);
247                 if (toupper (*L) != 'X') {
248                     Error ("ASM code error: `X' expected");
249                     return 0;
250                 }
251                 L = SkipSpace (L+1);
252                 if (*L != ')') {
253                     Error ("ASM code error: `)' expected");
254                     return 0;
255                 }
256                 L = SkipSpace (L+1);
257                 if (*L != '\0') {
258                     Error ("ASM code error: syntax error");
259                     return 0;
260                 }
261                 AM = AM65_ZPX_IND;
262             } else if (*L == ')') {
263                 /* zp indirect or zp indirect, y */
264                 L = SkipSpace (L+1);
265                 if (*L == ',') {
266                     L = SkipSpace (L+1);
267                     if (toupper (*L) != 'Y') {
268                         Error ("ASM code error: `Y' expected");
269                         return 0;
270                     }
271                     L = SkipSpace (L+1);
272                     if (*L != '\0') {
273                         Error ("ASM code error: syntax error");
274                         return 0;
275                     }
276                     AM = AM65_ZP_INDY;
277                 } else if (*L == '\0') {
278                     AM = AM65_ZP_IND;
279                 } else {
280                     Error ("ASM code error: syntax error");
281                     return 0;
282                 }
283             }
284             break;
285
286         case 'a':
287         case 'A':
288             /* Accumulator? */
289             if (L[1] == '\0') {
290                 AM = AM65_ACC;
291                 break;
292             }
293             /* FALLTHROUGH */
294
295         default:
296             /* Absolute, maybe indexed */
297             L = ReadToken (L, ",", Arg, sizeof (Arg));
298             if (*L == '\0') {
299                 /* Absolute, zeropage or branch */
300                 if ((OPC->Info & OF_BRA) != 0) {
301                     /* Branch */
302                     AM = AM65_BRA;
303                 } else if (IsZPName (Arg)) {
304                     AM = AM65_ZP;
305                 } else {
306                     AM = AM65_ABS;
307                 }
308             } else if (*L == ',') {
309                 /* Indexed */
310                 L = SkipSpace (L+1);
311                 if (*L == '\0') {
312                     Error ("ASM code error: syntax error");
313                     return 0;
314                 } else {
315                     Reg = toupper (*L);
316                     L = SkipSpace (L+1);
317                     if (Reg == 'X') {
318                         if (IsZPName (Arg)) {
319                             AM = AM65_ZPX;
320                         } else {
321                             AM = AM65_ABSX;
322                         }
323                     } else if (Reg == 'Y') {
324                         AM = AM65_ABSY;
325                     } else {
326                         Error ("ASM code error: syntax error");
327                         return 0;
328                     }
329                     if (*L != '\0') {
330                         Error ("ASM code error: syntax error");
331                         return 0;
332                     }
333                 }
334             }
335             break;
336
337     }
338
339     /* If the instruction is a branch, check for the label and generate it
340      * if it does not exist. Ignore anything but local labels here.
341      */
342     Label = 0;
343     if (AM == AM65_BRA && Arg[0] == 'L') {
344
345         /* Generate the hash over the label, then search for the label */
346         unsigned Hash = HashStr (Arg) % CS_LABEL_HASH_SIZE;
347         Label = CS_FindLabel (S, Arg, Hash);
348
349         /* If we don't have the label, it's a forward ref - create it */
350         if (Label == 0) {
351             /* Generate a new label */
352             Label = CS_NewCodeLabel (S, Arg, Hash);
353         }
354     }
355
356     /* We do now have the addressing mode in AM. Allocate a new CodeEntry
357      * structure and initialize it.
358      */
359     E = NewCodeEntry (OPC->OPC, AM, Arg, Label, LI);
360
361     /* Return the new code entry */
362     return E;
363 }
364
365
366
367 /*****************************************************************************/
368 /*                                   Code                                    */
369 /*****************************************************************************/
370
371
372
373 CodeSeg* NewCodeSeg (const char* SegName, SymEntry* Func)
374 /* Create a new code segment, initialize and return it */
375 {
376     unsigned I;
377
378     /* Allocate memory */
379     CodeSeg* S = xmalloc (sizeof (CodeSeg));
380
381     /* Initialize the fields */
382     S->SegName  = xstrdup (SegName);
383     S->Func     = Func;
384     InitCollection (&S->Entries);
385     InitCollection (&S->Labels);
386     for (I = 0; I < sizeof(S->LabelHash) / sizeof(S->LabelHash[0]); ++I) {
387         S->LabelHash[I] = 0;
388     }
389
390     /* If we have a function given, get the return type of the function.
391      * Assume ANY return type besides void will use the A and X registers.
392      */
393     if (S->Func && !IsTypeVoid (GetFuncReturn (Func->Type))) {
394         S->ExitRegs = REG_AX;
395     } else {
396         S->ExitRegs = REG_NONE;
397     }
398
399     /* Return the new struct */
400     return S;
401 }
402
403
404
405 void CS_AddEntry (CodeSeg* S, struct CodeEntry* E, LineInfo* LI)
406 /* Add an entry to the given code segment */
407 {
408     /* Transfer the labels if we have any */
409     unsigned I;
410     unsigned LabelCount = CollCount (&S->Labels);
411     for (I = 0; I < LabelCount; ++I) {
412
413         /* Get the label */
414         CodeLabel* L = CollAt (&S->Labels, I);
415
416         /* Attach it to the entry */
417         CE_AttachLabel (E, L);
418     }
419
420     /* Delete the transfered labels */
421     CollDeleteAll (&S->Labels);
422
423     /* Add the entry to the list of code entries in this segment */
424     CollAppend (&S->Entries, E);
425 }
426
427
428
429 void CS_AddLine (CodeSeg* S, LineInfo* LI, const char* Format, va_list ap)
430 /* Add a line to the given code segment */
431 {
432     const char* L;
433     CodeEntry*  E;
434     char        Token[64];
435
436     /* Format the line */
437     char Buf [256];
438     xvsprintf (Buf, sizeof (Buf), Format, ap);
439
440     /* Skip whitespace */
441     L = SkipSpace (Buf);
442
443     /* Check which type of instruction we have */
444     E = 0;      /* Assume no insn created */
445     switch (*L) {
446
447         case '\0':
448             /* Empty line, just ignore it */
449             break;
450
451         case ';':
452             /* Comment or hint, ignore it for now */
453             break;
454
455         case '.':
456             /* Control instruction */
457             ReadToken (L, " \t", Token, sizeof (Token));
458             Error ("ASM code error: Pseudo instruction `%s' not supported", Token);
459             break;
460
461         default:
462             E = ParseInsn (S, LI, L);
463             break;
464     }
465
466     /* If we have a code entry, transfer the labels and insert it */
467     if (E) {
468         CS_AddEntry (S, E, LI);
469     }
470 }
471
472
473
474 void CS_InsertEntry (CodeSeg* S, struct CodeEntry* E, unsigned Index)
475 /* Insert the code entry at the index given. Following code entries will be
476  * moved to slots with higher indices.
477  */
478 {
479     /* Insert the entry into the collection */
480     CollInsert (&S->Entries, E, Index);
481 }
482
483
484
485 void CS_DelEntry (CodeSeg* S, unsigned Index)
486 /* Delete an entry from the code segment. This includes moving any associated
487  * labels, removing references to labels and even removing the referenced labels
488  * if the reference count drops to zero.
489  */
490 {
491     /* Get the code entry for the given index */
492     CodeEntry* E = CS_GetEntry (S, Index);
493
494     /* If the entry has a labels, we have to move this label to the next insn.
495      * If there is no next insn, move the label into the code segement label
496      * pool. The operation is further complicated by the fact that the next
497      * insn may already have a label. In that case change all reference to
498      * this label and delete the label instead of moving it.
499      */
500     unsigned Count = CE_GetLabelCount (E);
501     if (Count > 0) {
502
503         /* The instruction has labels attached. Check if there is a next
504          * instruction.
505          */
506         if (Index == CS_GetEntryCount (S)-1) {
507
508             /* No next instruction, move to the codeseg label pool */
509             CS_MoveLabelsToPool (S, E);
510
511         } else {
512
513             /* There is a next insn, get it */
514             CodeEntry* N = CS_GetEntry (S, Index+1);
515
516             /* Move labels to the next entry */
517             CS_MoveLabels (S, E, N);
518
519         }
520     }
521
522     /* If this insn references a label, remove the reference. And, if the
523      * the reference count for this label drops to zero, remove this label.
524      */
525     if (E->JumpTo) {
526         /* Remove the reference */
527         CS_RemoveLabelRef (S, E);
528     }
529
530     /* Delete the pointer to the insn */
531     CollDelete (&S->Entries, Index);
532
533     /* Delete the instruction itself */
534     FreeCodeEntry (E);
535 }
536
537
538
539 void CS_DelEntries (CodeSeg* S, unsigned Start, unsigned Count)
540 /* Delete a range of code entries. This includes removing references to labels,
541  * labels attached to the entries and so on.
542  */
543 {
544     /* Start deleting the entries from the rear, because this involves less
545      * memory moving.
546      */
547     while (Count--) {
548         CS_DelEntry (S, Start + Count);
549     }
550 }
551
552
553
554 void CS_MoveEntry (CodeSeg* S, unsigned OldPos, unsigned NewPos)
555 /* Move an entry from one position to another. OldPos is the current position
556  * of the entry, NewPos is the new position of the entry.
557  */
558 {
559     /* Get the code entry and remove it from the collection */
560     CodeEntry* E = CS_GetEntry (S, OldPos);
561     CollDelete (&S->Entries, OldPos);
562
563     /* Correct NewPos if needed */
564     if (NewPos >= OldPos) {
565         /* Position has changed with removal */
566         --NewPos;
567     }
568
569     /* Now insert it at the new position */
570     CollInsert (&S->Entries, E, NewPos);
571 }
572
573
574
575 struct CodeEntry* CS_GetNextEntry (CodeSeg* S, unsigned Index)
576 /* Get the code entry following the one with the index Index. If there is no
577  * following code entry, return NULL.
578  */
579 {
580     if (Index >= CollCount (&S->Entries)-1) {
581         /* This is the last entry */
582         return 0;
583     } else {
584         /* Code entries left */
585         return CollAtUnchecked (&S->Entries, Index+1);
586     }
587 }
588
589
590
591 int CS_GetEntries (CodeSeg* S, struct CodeEntry** List,
592                    unsigned Start, unsigned Count)
593 /* Get Count code entries into List starting at index start. Return true if
594  * we got the lines, return false if not enough lines were available.
595  */
596 {
597     /* Check if enough entries are available */
598     if (Start + Count > CollCount (&S->Entries)) {
599         return 0;
600     }
601
602     /* Copy the entries */
603     while (Count--) {
604         *List++ = CollAtUnchecked (&S->Entries, Start++);
605     }
606
607     /* We have the entries */
608     return 1;
609 }
610
611
612
613 unsigned CS_GetEntryIndex (CodeSeg* S, struct CodeEntry* E)
614 /* Return the index of a code entry */
615 {
616     int Index = CollIndex (&S->Entries, E);
617     CHECK (Index >= 0);
618     return Index;
619 }
620
621
622
623 CodeLabel* CS_AddLabel (CodeSeg* S, const char* Name)
624 /* Add a code label for the next instruction to follow */
625 {
626     /* Calculate the hash from the name */
627     unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
628
629     /* Try to find the code label if it does already exist */
630     CodeLabel* L = CS_FindLabel (S, Name, Hash);
631
632     /* Did we find it? */
633     if (L) {
634         /* We found it - be sure it does not already have an owner */
635         CHECK (L->Owner == 0);
636     } else {
637         /* Not found - create a new one */
638         L = CS_NewCodeLabel (S, Name, Hash);
639     }
640
641     /* Safety. This call is quite costly, but safety is better */
642     if (CollIndex (&S->Labels, L) >= 0) {
643         Internal ("AddCodeLabel: Label `%s' already defined", Name);
644     }
645
646     /* We do now have a valid label. Remember it for later */
647     CollAppend (&S->Labels, L);
648
649     /* Return the label */
650     return L;
651 }
652
653
654
655 CodeLabel* CS_GenLabel (CodeSeg* S, struct CodeEntry* E)
656 /* If the code entry E does already have a label, return it. Otherwise
657  * create a new label, attach it to E and return it.
658  */
659 {
660     CodeLabel* L;
661
662     if (CE_HasLabel (E)) {
663
664         /* Get the label from this entry */
665         L = CE_GetLabel (E, 0);
666
667     } else {
668
669         /* Get a new name */
670         const char* Name = LocalLabelName (GetLocalLabel ());
671
672         /* Generate the hash over the name */
673         unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
674
675         /* Create a new label */
676         L = CS_NewCodeLabel (S, Name, Hash);
677
678         /* Attach this label to the code entry */
679         CE_AttachLabel (E, L);
680
681     }
682
683     /* Return the label */
684     return L;
685 }
686
687
688
689 void CS_DelLabel (CodeSeg* S, CodeLabel* L)
690 /* Remove references from this label and delete it. */
691 {
692     unsigned Count, I;
693
694     /* First, remove the label from the hash chain */
695     CS_RemoveLabelFromHash (S, L);
696
697     /* Remove references from insns jumping to this label */
698     Count = CollCount (&L->JumpFrom);
699     for (I = 0; I < Count; ++I) {
700         /* Get the insn referencing this label */
701         CodeEntry* E = CollAt (&L->JumpFrom, I);
702         /* Remove the reference */
703         E->JumpTo = 0;
704     }
705     CollDeleteAll (&L->JumpFrom);
706
707     /* Remove the reference to the owning instruction if it has one. The
708      * function may be called for a label without an owner when deleting
709      * unfinished parts of the code. This is unfortunate since it allows
710      * errors to slip through.
711      */
712     if (L->Owner) {
713         CollDeleteItem (&L->Owner->Labels, L);
714     }
715
716     /* All references removed, delete the label itself */
717     FreeCodeLabel (L);
718 }
719
720
721
722 void CS_MergeLabels (CodeSeg* S)
723 /* Merge code labels. That means: For each instruction, remove all labels but
724  * one and adjust references accordingly.
725  */
726 {
727     unsigned I;
728
729     /* Walk over all code entries */
730     for (I = 0; I < CS_GetEntryCount (S); ++I) {
731
732         CodeLabel* RefLab;
733         unsigned   J;
734
735         /* Get a pointer to the next entry */
736         CodeEntry* E = CS_GetEntry (S, I);
737
738         /* If this entry has zero labels, continue with the next one */
739         unsigned LabelCount = CE_GetLabelCount (E);
740         if (LabelCount == 0) {
741             continue;
742         }
743
744         /* We have at least one label. Use the first one as reference label. */
745         RefLab = CE_GetLabel (E, 0);
746
747         /* Walk through the remaining labels and change references to these
748          * labels to a reference to the one and only label. Delete the labels
749          * that are no longer used. To increase performance, walk backwards
750          * through the list.
751          */
752         for (J = LabelCount-1; J >= 1; --J) {
753
754             /* Get the next label */
755             CodeLabel* L = CE_GetLabel (E, J);
756
757             /* Move all references from this label to the reference label */
758             CL_MoveRefs (L, RefLab);
759
760             /* Remove the label completely. */
761             CS_DelLabel (S, L);
762         }
763
764         /* The reference label is the only remaining label. Check if there
765          * are any references to this label, and delete it if this is not
766          * the case.
767          */
768         if (CollCount (&RefLab->JumpFrom) == 0) {
769             /* Delete the label */
770             CS_DelLabel (S, RefLab);
771         }
772     }
773 }
774
775
776
777 void CS_MoveLabels (CodeSeg* S, struct CodeEntry* Old, struct CodeEntry* New)
778 /* Move all labels from Old to New. The routine will move the labels itself
779  * if New does not have any labels, and move references if there is at least
780  * a label for new. If references are moved, the old label is deleted
781  * afterwards.
782  */
783 {
784     /* Get the number of labels to move */
785     unsigned OldLabelCount = CE_GetLabelCount (Old);
786
787     /* Does the new entry have itself a label? */
788     if (CE_HasLabel (New)) {
789
790         /* The new entry does already have a label - move references */
791         CodeLabel* NewLabel = CE_GetLabel (New, 0);
792         while (OldLabelCount--) {
793
794             /* Get the next label */
795             CodeLabel* OldLabel = CE_GetLabel (Old, OldLabelCount);
796
797             /* Move references */
798             CL_MoveRefs (OldLabel, NewLabel);
799
800             /* Delete the label */
801             CS_DelLabel (S, OldLabel);
802
803         }
804
805     } else {
806
807         /* The new entry does not have a label, just move them */
808         while (OldLabelCount--) {
809
810             /* Move the label to the new entry */
811             CE_MoveLabel (CE_GetLabel (Old, OldLabelCount), New);
812
813         }
814
815     }
816 }
817
818
819
820 void CS_RemoveLabelRef (CodeSeg* S, struct CodeEntry* E)
821 /* Remove the reference between E and the label it jumps to. The reference
822  * will be removed on both sides and E->JumpTo will be 0 after that. If
823  * the reference was the only one for the label, the label will get
824  * deleted.
825  */
826 {
827     /* Get a pointer to the label and make sure it exists */
828     CodeLabel* L = E->JumpTo;
829     CHECK (L != 0);
830
831     /* Delete the entry from the label */
832     CollDeleteItem (&L->JumpFrom, E);
833
834     /* The entry jumps no longer to L */
835     E->JumpTo = 0;
836
837     /* If there are no more references, delete the label */
838     if (CollCount (&L->JumpFrom) == 0) {
839         CS_DelLabel (S, L);
840     }
841 }
842
843
844
845 void CS_MoveLabelRef (CodeSeg* S, struct CodeEntry* E, CodeLabel* L)
846 /* Change the reference of E to L instead of the current one. If this
847  * was the only reference to the old label, the old label will get
848  * deleted.
849  */
850 {
851     /* Get the old label */
852     CodeLabel* OldLabel = E->JumpTo;
853
854     /* Be sure that code entry references a label */
855     PRECONDITION (OldLabel != 0);
856
857     /* Remove the reference to our label */
858     CS_RemoveLabelRef (S, E);
859
860     /* Use the new label */
861     CL_AddRef (L, E);
862 }
863
864
865
866 void CS_DelCodeAfter (CodeSeg* S, unsigned Last)
867 /* Delete all entries including the given one */
868 {
869     /* Get the number of entries in this segment */
870     unsigned Count = CS_GetEntryCount (S);
871
872     /* First pass: Delete all references to labels. If the reference count
873      * for a label drops to zero, delete it.
874      */
875     unsigned C = Count;
876     while (Last < C--) {
877
878         /* Get the next entry */
879         CodeEntry* E = CS_GetEntry (S, C);
880
881         /* Check if this entry has a label reference */
882         if (E->JumpTo) {
883             /* If the label is a label in the label pool and this is the last
884              * reference to the label, remove the label from the pool.
885              */
886             CodeLabel* L = E->JumpTo;
887             int Index = CollIndex (&S->Labels, L);
888             if (Index >= 0 && CollCount (&L->JumpFrom) == 1) {
889                 /* Delete it from the pool */
890                 CollDelete (&S->Labels, Index);
891             }
892
893             /* Remove the reference to the label */
894             CS_RemoveLabelRef (S, E);
895         }
896
897     }
898
899     /* Second pass: Delete the instructions. If a label attached to an
900      * instruction still has references, it must be references from outside
901      * the deleted area. Don't delete the label in this case, just make it
902      * ownerless and move it to the label pool.
903      */
904     C = Count;
905     while (Last < C--) {
906
907         /* Get the next entry */
908         CodeEntry* E = CS_GetEntry (S, C);
909
910         /* Check if this entry has a label attached */
911         if (CE_HasLabel (E)) {
912             /* Move the labels to the pool and clear the owner pointer */
913             CS_MoveLabelsToPool (S, E);
914         }
915
916         /* Delete the pointer to the entry */
917         CollDelete (&S->Entries, C);
918
919         /* Delete the entry itself */
920         FreeCodeEntry (E);
921     }
922 }
923
924
925
926 void CS_Output (const CodeSeg* S, FILE* F)
927 /* Output the code segment data to a file */
928 {
929     unsigned I;
930     const LineInfo* LI;
931
932     /* Get the number of entries in this segment */
933     unsigned Count = CS_GetEntryCount (S);
934
935     /* If the code segment is empty, bail out here */
936     if (Count == 0) {
937         return;
938     }
939
940     /* Output the segment directive */
941     fprintf (F, ".segment\t\"%s\"\n\n", S->SegName);
942
943     /* If this is a segment for a function, enter a function */
944     if (S->Func) {
945         fprintf (F, ".proc\t_%s\n\n", S->Func->Name);
946     }
947
948     /* Output all entries, prepended by the line information if it has changed */
949     LI = 0;
950     for (I = 0; I < Count; ++I) {
951         /* Get the next entry */
952         const CodeEntry* E = CollConstAt (&S->Entries, I);
953         /* Check if the line info has changed. If so, output the source line
954          * if the option is enabled and output debug line info if the debug
955          * option is enabled.
956          */
957         if (E->LI != LI) {
958             /* Line info has changed, remember the new line info */
959             LI = E->LI;
960
961             /* Add the source line as a comment */
962             if (AddSource) {
963                 fprintf (F, ";\n; %s\n;\n", LI->Line);
964             }
965
966             /* Add line debug info */
967             if (DebugInfo) {
968                 fprintf (F, "\t.dbg\tline, \"%s\", %u\n",
969                          GetInputName (LI), GetInputLine (LI));
970             }
971         }
972         /* Output the code */
973         CE_Output (E, F);
974     }
975
976     /* If debug info is enabled, terminate the last line number information */
977     if (DebugInfo) {
978         fprintf (F, "\t.dbg\tline\n");
979     }
980
981     /* If this is a segment for a function, leave the function */
982     if (S->Func) {
983         fprintf (F, "\n.endproc\n\n");
984     }
985 }
986
987
988
989