]> git.sur5r.net Git - cc65/blob - src/cc65/codeseg.c
Working
[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 "hashstr.h"
43 #include "strutil.h"
44 #include "xmalloc.h"
45 #include "xsprintf.h"
46
47 /* cc65 */
48 #include "asmlabel.h"
49 #include "codeent.h"
50 #include "codeinfo.h"
51 #include "datatype.h"
52 #include "error.h"
53 #include "symentry.h"
54 #include "codeseg.h"
55
56
57
58 /*****************************************************************************/
59 /*                             Helper functions                              */
60 /*****************************************************************************/
61
62
63
64 static void MoveLabelsToPool (CodeSeg* S, CodeEntry* E)
65 /* Move the labels of the code entry E to the label pool of the code segment */
66 {
67     unsigned LabelCount = GetCodeLabelCount (E);
68     while (LabelCount--) {
69         CodeLabel* L = GetCodeLabel (E, LabelCount);
70         L->Flags &= ~LF_DEF;
71         L->Owner = 0;
72         CollAppend (&S->Labels, L);
73     }
74     CollDeleteAll (&E->Labels);
75 }
76
77
78
79 static CodeLabel* FindCodeLabel (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* NewCodeSegLabel (CodeSeg* S, const char* Name, unsigned Hash)
99 /* Create a new label and insert it into the label hash table */
100 {
101     /* Not found - create a new one */
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 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, 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 = FindOpcode (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 = AM_IMP;
225             break;
226
227         case '#':
228             /* Immidiate */
229             StrCopy (Arg, sizeof (Arg), L+1);
230             AM = AM_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 = AM_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 = AM_ZP_INDY;
277                 } else if (*L == '\0') {
278                     AM = AM_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 = AM_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                 /* Assume absolute */
300                 AM = AM_ABS;
301             } else if (*L == ',') {
302                 /* Indexed */
303                 L = SkipSpace (L+1);
304                 if (*L == '\0') {
305                     Error ("ASM code error: syntax error");
306                     return 0;
307                 } else {
308                     Reg = toupper (*L);
309                     L = SkipSpace (L+1);
310                     if (Reg == 'X') {
311                         AM = AM_ABSX;
312                     } else if (Reg == 'Y') {
313                         AM = AM_ABSY;
314                     } else {
315                         Error ("ASM code error: syntax error");
316                         return 0;
317                     }
318                     if (*L != '\0') {
319                         Error ("ASM code error: syntax error");
320                         return 0;
321                     }
322                 }
323             }
324             break;
325
326     }
327
328     /* If the instruction is a branch, check for the label and generate it
329      * if it does not exist. Ignore anything but local labels here.
330      */
331     Label = 0;
332     if ((OPC->Info & OF_BRA) != 0 && Arg[0] == 'L') {
333
334         unsigned Hash;
335
336         /* Addressing mode must be alsobute or something is really wrong */
337         CHECK (AM == AM_ABS);
338
339         /* Addressing mode is a branch/jump */
340         AM = AM_BRA;
341
342         /* Generate the hash over the label, then search for the label */
343         Hash = HashStr (Arg) % CS_LABEL_HASH_SIZE;
344         Label = FindCodeLabel (S, Arg, Hash);
345
346         /* If we don't have the label, it's a forward ref - create it */
347         if (Label == 0) {
348             /* Generate a new label */
349             Label = NewCodeSegLabel (S, Arg, Hash);
350         }
351     }
352
353     /* We do now have the addressing mode in AM. Allocate a new CodeEntry
354      * structure and initialize it.
355      */
356     E = NewCodeEntry (OPC->OPC, AM, Arg, Label);
357
358     /* Return the new code entry */
359     return E;
360 }
361
362
363
364 /*****************************************************************************/
365 /*                                   Code                                    */
366 /*****************************************************************************/
367
368
369
370 CodeSeg* NewCodeSeg (const char* SegName, SymEntry* Func)
371 /* Create a new code segment, initialize and return it */
372 {
373     unsigned I;
374
375     /* Allocate memory */
376     CodeSeg* S = xmalloc (sizeof (CodeSeg));
377
378     /* Initialize the fields */
379     S->SegName  = xstrdup (SegName);
380     S->Func     = Func;
381     InitCollection (&S->Entries);
382     InitCollection (&S->Labels);
383     for (I = 0; I < sizeof(S->LabelHash) / sizeof(S->LabelHash[0]); ++I) {
384         S->LabelHash[I] = 0;
385     }
386
387     /* If we have a function given, get the return type of the function.
388      * Assume ANY return type besides void will use the A and X registers.
389      */
390     if (S->Func && !IsTypeVoid (GetFuncReturn (Func->Type))) {
391         S->ExitRegs = REG_AX;
392     } else {
393         S->ExitRegs = REG_NONE;
394     }
395
396     /* Return the new struct */
397     return S;
398 }
399
400
401
402 void AddCodeEntry (CodeSeg* S, const char* Format, va_list ap)
403 /* Add a line to the given code segment */
404 {
405     const char* L;
406     CodeEntry*  E;
407     char        Token[64];
408
409     /* Format the line */
410     char Buf [256];
411     xvsprintf (Buf, sizeof (Buf), Format, ap);
412
413     /* Skip whitespace */
414     L = SkipSpace (Buf);
415
416     /* Check which type of instruction we have */
417     E = 0;      /* Assume no insn created */
418     switch (*L) {
419
420         case '\0':
421             /* Empty line, just ignore it */
422             break;
423
424         case ';':
425             /* Comment or hint, ignore it for now */
426             break;
427
428         case '.':
429             /* Control instruction */
430             ReadToken (L, " \t", Token, sizeof (Token));
431             Error ("ASM code error: Pseudo instruction `%s' not supported", Token);
432             break;
433
434         default:
435             E = ParseInsn (S, L);
436             break;
437     }
438
439     /* If we have a code entry, transfer the labels and insert it */
440     if (E) {
441
442         /* Transfer the labels if we have any */
443         unsigned I;
444         unsigned LabelCount = CollCount (&S->Labels);
445         for (I = 0; I < LabelCount; ++I) {
446
447             /* Get the label */
448             CodeLabel* L = CollAt (&S->Labels, I);
449
450             /* Attach it to the entry */
451             AttachCodeLabel (E, L);
452         }
453
454         /* Delete the transfered labels */
455         CollDeleteAll (&S->Labels);
456
457         /* Add the entry to the list of code entries in this segment */
458         CollAppend (&S->Entries, E);
459
460     }
461 }
462
463
464
465 void InsertCodeEntry (CodeSeg* S, struct CodeEntry* E, unsigned Index)
466 /* Insert the code entry at the index given. Following code entries will be
467  * moved to slots with higher indices.
468  */
469 {
470     /* Insert the entry into the collection */
471     CollInsert (&S->Entries, E, Index);
472 }
473
474
475
476 void DelCodeEntry (CodeSeg* S, unsigned Index)
477 /* Delete an entry from the code segment. This includes moving any associated
478  * labels, removing references to labels and even removing the referenced labels
479  * if the reference count drops to zero.
480  */
481 {
482     /* Get the code entry for the given index */
483     CodeEntry* E = GetCodeEntry (S, Index);
484
485     /* If the entry has a labels, we have to move this label to the next insn.
486      * If there is no next insn, move the label into the code segement label
487      * pool. The operation is further complicated by the fact that the next
488      * insn may already have a label. In that case change all reference to
489      * this label and delete the label instead of moving it.
490      */
491     unsigned Count = GetCodeLabelCount (E);
492     if (Count > 0) {
493
494         /* The instruction has labels attached. Check if there is a next
495          * instruction.
496          */
497         if (Index == GetCodeEntryCount (S)-1) {
498
499             /* No next instruction, move to the codeseg label pool */
500             MoveLabelsToPool (S, E);
501
502         } else {
503
504             /* There is a next insn, get it */
505             CodeEntry* N = GetCodeEntry (S, Index+1);
506
507             /* Move labels to the next entry */
508             MoveCodeLabels (S, E, N);
509
510         }
511     }
512
513     /* If this insn references a label, remove the reference. And, if the
514      * the reference count for this label drops to zero, remove this label.
515      */
516     if (E->JumpTo) {
517         /* Remove the reference */
518         RemoveCodeLabelRef (S, E);
519     }
520
521     /* Delete the pointer to the insn */
522     CollDelete (&S->Entries, Index);
523
524     /* Delete the instruction itself */
525     FreeCodeEntry (E);
526 }
527
528
529
530 void DelCodeEntries (CodeSeg* S, unsigned Start, unsigned Count)
531 /* Delete a range of code entries. This includes removing references to labels,
532  * labels attached to the entries and so on.
533  */
534 {
535     /* Start deleting the entries from the rear, because this involves less
536      * memory moving.
537      */
538     while (Count--) {
539         DelCodeEntry (S, Start + Count);
540     }
541 }
542
543
544
545 struct CodeEntry* RetrieveCodeEntry (CodeSeg* S, unsigned Index)
546 /* Retrieve a code entry. This means, the code entry is removed from the
547  * entry collection, but not deleted and returned instead. The entry may
548  * then be inserted again at another position.
549  */
550 {
551     /* Get the code entry, remove it from the collection and return it */
552     CodeEntry* E = GetCodeEntry (S, Index);
553     CollDelete (&S->Entries, Index);
554     return E;
555 }
556
557
558
559 struct CodeEntry* GetNextCodeEntry (CodeSeg* S, unsigned Index)
560 /* Get the code entry following the one with the index Index. If there is no
561  * following code entry, return NULL.
562  */
563 {
564     if (Index >= CollCount (&S->Entries)-1) {
565         /* This is the last entry */
566         return 0;
567     } else {
568         /* Code entries left */
569         return CollAtUnchecked (&S->Entries, Index+1);
570     }
571 }
572
573
574
575 int GetCodeEntries (CodeSeg* S, struct CodeEntry** List,
576                     unsigned Start, unsigned Count)
577 /* Get Count code entries into List starting at index start. Return true if
578  * we got the lines, return false if not enough lines were available.
579  */
580 {
581     /* Check if enough entries are available */
582     if (Start + Count > CollCount (&S->Entries)) {
583         return 0;
584     }
585
586     /* Copy the entries */
587     while (Count--) {
588         *List++ = CollAtUnchecked (&S->Entries, Start++);
589     }
590
591     /* We have the entries */
592     return 1;
593 }
594
595
596
597 unsigned GetCodeEntryIndex (CodeSeg* S, struct CodeEntry* E)
598 /* Return the index of a code entry */
599 {
600     int Index = CollIndex (&S->Entries, E);
601     CHECK (Index >= 0);
602     return Index;
603 }
604
605
606
607 void AddCodeLabel (CodeSeg* S, const char* Name)
608 /* Add a code label for the next instruction to follow */
609 {
610     /* Calculate the hash from the name */
611     unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
612
613     /* Try to find the code label if it does already exist */
614     CodeLabel* L = FindCodeLabel (S, Name, Hash);
615
616     /* Did we find it? */
617     if (L) {
618         /* We found it - be sure it does not already have an owner */
619         CHECK (L->Owner == 0);
620     } else {
621         /* Not found - create a new one */
622         L = NewCodeSegLabel (S, Name, Hash);
623     }
624
625     /* Safety. This call is quite costly, but safety is better */
626     if (CollIndex (&S->Labels, L) >= 0) {
627         Internal ("AddCodeLabel: Label `%s' already defined", Name);
628     }
629
630     /* We do now have a valid label. Remember it for later */
631     CollAppend (&S->Labels, L);
632 }
633
634
635
636 CodeLabel* GenCodeLabel (CodeSeg* S, struct CodeEntry* E)
637 /* If the code entry E does already have a label, return it. Otherwise
638  * create a new label, attach it to E and return it.
639  */
640 {
641     CodeLabel* L;
642
643     if (CodeEntryHasLabel (E)) {
644
645         /* Get the label from this entry */
646         L = GetCodeLabel (E, 0);
647
648     } else {
649
650         /* Get a new name */
651         const char* Name = LocalLabelName (GetLocalLabel ());
652
653         /* Generate the hash over the name */
654         unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
655
656         /* Create a new label */
657         L = NewCodeSegLabel (S, Name, Hash);
658
659         /* Attach this label to the code entry */
660         AttachCodeLabel (E, L);
661
662     }
663
664     /* Return the label */
665     return L;
666 }
667
668
669
670 void DelCodeLabel (CodeSeg* S, CodeLabel* L)
671 /* Remove references from this label and delete it. */
672 {
673     unsigned Count, I;
674
675     /* First, remove the label from the hash chain */
676     RemoveLabelFromHash (S, L);
677
678     /* Remove references from insns jumping to this label */
679     Count = CollCount (&L->JumpFrom);
680     for (I = 0; I < Count; ++I) {
681         /* Get the insn referencing this label */
682         CodeEntry* E = CollAt (&L->JumpFrom, I);
683         /* Remove the reference */
684         E->JumpTo = 0;
685     }
686     CollDeleteAll (&L->JumpFrom);
687
688     /* Remove the reference to the owning instruction if it has one. The
689      * function may be called for a label without an owner when deleting
690      * unfinished parts of the code. This is unfortunate since it allows
691      * errors to slip through.
692      */
693     if (L->Owner) {
694         CollDeleteItem (&L->Owner->Labels, L);
695     }
696
697     /* All references removed, delete the label itself */
698     FreeCodeLabel (L);
699 }
700
701
702
703 void MergeCodeLabels (CodeSeg* S)
704 /* Merge code labels. That means: For each instruction, remove all labels but
705  * one and adjust references accordingly.
706  */
707 {
708     unsigned I;
709
710     /* Walk over all code entries */
711     unsigned EntryCount = GetCodeEntryCount (S);
712     for (I = 0; I < EntryCount; ++I) {
713
714         CodeLabel* RefLab;
715         unsigned   J;
716
717         /* Get a pointer to the next entry */
718         CodeEntry* E = GetCodeEntry (S, I);
719
720         /* If this entry has zero labels, continue with the next one */
721         unsigned LabelCount = GetCodeLabelCount (E);
722         if (LabelCount == 0) {
723             continue;
724         }
725
726         /* We have at least one label. Use the first one as reference label. */
727         RefLab = GetCodeLabel (E, 0);
728
729         /* Walk through the remaining labels and change references to these
730          * labels to a reference to the one and only label. Delete the labels
731          * that are no longer used. To increase performance, walk backwards
732          * through the list.
733          */
734         for (J = LabelCount-1; J >= 1; --J) {
735
736             /* Get the next label */
737             CodeLabel* L = GetCodeLabel (E, J);
738
739             /* Move all references from this label to the reference label */
740             MoveLabelRefs (L, RefLab);
741
742             /* Remove the label completely. */
743             DelCodeLabel (S, L);
744         }
745
746         /* The reference label is the only remaining label. Check if there
747          * are any references to this label, and delete it if this is not
748          * the case.
749          */
750         if (CollCount (&RefLab->JumpFrom) == 0) {
751             /* Delete the label */
752             DelCodeLabel (S, RefLab);
753         }
754     }
755 }
756
757
758
759 void MoveCodeLabels (CodeSeg* S, struct CodeEntry* Old, struct CodeEntry* New)
760 /* Move all labels from Old to New. The routine will move the labels itself
761  * if New does not have any labels, and move references if there is at least
762  * a label for new. If references are moved, the old label is deleted
763  * afterwards.
764  */
765 {
766     /* Get the number of labels to move */
767     unsigned OldLabelCount = GetCodeLabelCount (Old);
768
769     /* Does the new entry have itself a label? */
770     if (CodeEntryHasLabel (New)) {
771
772         /* The new entry does already have a label - move references */
773         CodeLabel* NewLabel = GetCodeLabel (New, 0);
774         while (OldLabelCount--) {
775
776             /* Get the next label */
777             CodeLabel* OldLabel = GetCodeLabel (Old, OldLabelCount);
778
779             /* Move references */
780             MoveLabelRefs (OldLabel, NewLabel);
781
782             /* Delete the label */
783             DelCodeLabel (S, OldLabel);
784
785         }
786
787     } else {
788
789         /* The new entry does not have a label, just move them */
790         while (OldLabelCount--) {
791
792             /* Move the label to the new entry */
793             MoveCodeLabel (GetCodeLabel (Old, OldLabelCount), New);
794
795         }
796
797     }
798 }
799
800
801
802 void RemoveCodeLabelRef (CodeSeg* S, struct CodeEntry* E)
803 /* Remove the reference between E and the label it jumps to. The reference
804  * will be removed on both sides and E->JumpTo will be 0 after that. If
805  * the reference was the only one for the label, the label will get
806  * deleted.
807  */
808 {
809     /* Get a pointer to the label and make sure it exists */
810     CodeLabel* L = E->JumpTo;
811     CHECK (L != 0);
812
813     /* Delete the entry from the label */
814     CollDeleteItem (&L->JumpFrom, E);
815
816     /* The entry jumps no longer to L */
817     E->JumpTo = 0;
818
819     /* If there are no more references, delete the label */
820     if (CollCount (&L->JumpFrom) == 0) {
821         DelCodeLabel (S, L);
822     }
823 }
824
825
826
827 void MoveCodeLabelRef (CodeSeg* S, struct CodeEntry* E, CodeLabel* L)
828 /* Change the reference of E to L instead of the current one. If this
829  * was the only reference to the old label, the old label will get
830  * deleted.
831  */
832 {
833     /* Get the old label */
834     CodeLabel* OldLabel = E->JumpTo;
835
836     /* Be sure that code entry references a label */
837     PRECONDITION (OldLabel != 0);
838
839     /* Remove the reference to our label */
840     RemoveCodeLabelRef (S, E);
841
842     /* Use the new label */
843     AddLabelRef (L, E);
844 }
845
846
847
848 void AddCodeSegHint (CodeSeg* S, unsigned Hint)
849 /* Add a hint for the preceeding instruction */
850 {
851     CodeEntry* E;
852
853     /* Get the number of entries in this segment */
854     unsigned EntryCount = GetCodeEntryCount (S);
855
856     /* Must have at least one entry */
857     CHECK (EntryCount > 0);
858
859     /* Get the last entry */
860     E = GetCodeEntry (S, EntryCount-1);
861
862     /* Add the hint */
863     E->Hints |= Hint;
864 }
865
866
867
868 void DelCodeSegAfter (CodeSeg* S, unsigned Last)
869 /* Delete all entries including the given one */
870 {
871     /* Get the number of entries in this segment */
872     unsigned Count = GetCodeEntryCount (S);
873
874     /* First pass: Delete all references to labels. If the reference count
875      * for a label drops to zero, delete it.
876      */
877     unsigned C = Count;
878     while (Last < C--) {
879
880         /* Get the next entry */
881         CodeEntry* E = GetCodeEntry (S, C);
882
883         /* Check if this entry has a label reference */
884         if (E->JumpTo) {
885             /* Remove the reference to the label */
886             RemoveCodeLabelRef (S, E);
887         }
888
889     }
890
891     /* Second pass: Delete the instructions. If a label attached to an
892      * instruction still has references, it must be references from outside
893      * the deleted area. Don't delete the label in this case, just make it
894      * ownerless and move it to the label pool.
895      */
896     C = Count;
897     while (Last < C--) {
898
899         /* Get the next entry */
900         CodeEntry* E = GetCodeEntry (S, C);
901
902         /* Check if this entry has a label attached */
903         if (CodeEntryHasLabel (E)) {
904             /* Move the labels to the pool and clear the owner pointer */
905             MoveLabelsToPool (S, E);
906         }
907
908         /* Delete the pointer to the entry */
909         CollDelete (&S->Entries, C);
910
911         /* Delete the entry itself */
912         FreeCodeEntry (E);
913     }
914 }
915
916
917
918 void OutputCodeSeg (const CodeSeg* S, FILE* F)
919 /* Output the code segment data to a file */
920 {
921     unsigned I;
922
923     /* Get the number of entries in this segment */
924     unsigned Count = GetCodeEntryCount (S);
925
926     /* If the code segment is empty, bail out here */
927     if (Count == 0) {
928         return;
929     }
930
931     /* Output the segment directive */
932     fprintf (F, ".segment\t\"%s\"\n\n", S->SegName);
933
934     /* If this is a segment for a function, enter a function */
935     if (S->Func) {
936         fprintf (F, ".proc\t_%s\n\n", S->Func->Name);
937     }
938
939     /* Output all entries */
940     for (I = 0; I < Count; ++I) {
941
942         unsigned char Use;
943
944         OutputCodeEntry (CollConstAt (&S->Entries, I), F);
945
946         /* Print usage info */
947         Use = GetRegInfo ((CodeSeg*) S, I+1);
948         fprintf (F,
949                  "  Use: %c%c%c\n",
950                  (Use & REG_A)? 'A' : '_',
951                  (Use & REG_X)? 'X' : '_',
952                  (Use & REG_Y)? 'Y' : '_');
953     }
954
955     /* If this is a segment for a function, leave the function */
956     if (S->Func) {
957         fprintf (F, "\n.endproc\n\n");
958     }
959 }
960
961
962
963
964
965
966