1 /*****************************************************************************/
5 /* Code segment structure */
9 /* (C) 2001 Ullrich von Bassewitz */
11 /* D-70597 Stuttgart */
12 /* EMail: uz@cc65.org */
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. */
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: */
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 */
32 /*****************************************************************************/
56 /*****************************************************************************/
57 /* Helper functions */
58 /*****************************************************************************/
62 static void MoveLabelsToPool (CodeSeg* S, CodeEntry* E)
63 /* Move the labels of the code entry E to the label pool of the code segment */
65 unsigned LabelCount = GetCodeLabelCount (E);
66 while (LabelCount--) {
67 CodeLabel* L = GetCodeLabel (E, LabelCount);
70 CollAppend (&S->Labels, L);
72 CollDeleteAll (&E->Labels);
77 static CodeLabel* FindCodeLabel (CodeSeg* S, const char* Name, unsigned Hash)
78 /* Find the label with the given name. Return the label or NULL if not found */
80 /* Get the first hash chain entry */
81 CodeLabel* L = S->LabelHash[Hash];
85 if (strcmp (Name, L->Name) == 0) {
96 static CodeLabel* NewCodeSegLabel (CodeSeg* S, const char* Name, unsigned Hash)
97 /* Create a new label and insert it into the label hash table */
99 /* Not found - create a new one */
100 CodeLabel* L = NewCodeLabel (Name, Hash);
102 /* Enter the label into the hash table */
103 L->Next = S->LabelHash[L->Hash];
104 S->LabelHash[L->Hash] = L;
106 /* Return the new label */
112 static void RemoveLabelFromHash (CodeSeg* S, CodeLabel* L)
113 /* Remove the given code label from the hash list */
115 /* Get the first entry in the hash chain */
116 CodeLabel* List = S->LabelHash[L->Hash];
119 /* First, remove the label from the hash chain */
121 /* First entry in hash chain */
122 S->LabelHash[L->Hash] = L->Next;
124 /* Must search through the chain */
125 while (List->Next != L) {
126 /* If we've reached the end of the chain, something is *really* wrong */
127 CHECK (List->Next != 0);
131 /* The next entry is the one, we have been searching for */
132 List->Next = L->Next;
138 /*****************************************************************************/
139 /* Functions for parsing instructions */
140 /*****************************************************************************/
144 static const char* SkipSpace (const char* S)
145 /* Skip white space and return an updated pointer */
147 while (IsSpace (*S)) {
155 static const char* ReadToken (const char* L, const char* Term,
156 char* Buf, unsigned BufSize)
157 /* Read the next token into Buf, return the updated line pointer. The
158 * token is terminated by one of the characters given in term.
161 /* Read/copy the token */
163 unsigned ParenCount = 0;
164 while (*L && (ParenCount > 0 || strchr (Term, *L) == 0)) {
170 } else if (*L == '(') {
176 /* Terminate the buffer contents */
179 /* Return the updated line pointer */
185 static CodeEntry* ParseInsn (CodeSeg* S, const char* L)
186 /* Parse an instruction nnd generate a code entry from it. If the line contains
187 * errors, output an error message and return NULL.
188 * For simplicity, we don't accept the broad range of input a "real" assembler
189 * does. The instruction and the argument are expected to be separated by
190 * white space, for example.
195 am_t AM = 0; /* Initialize to keep gcc silent */
202 L = ReadToken (L, " \t", Mnemo, sizeof (Mnemo));
204 /* Try to find the opcode description for the mnemonic */
205 OPC = FindOpcode (Mnemo);
207 /* If we didn't find the opcode, print an error and bail out */
209 Error ("ASM code error: %s is not a valid mnemonic", Mnemo);
213 /* Skip separator white space */
216 /* Get the addressing mode */
227 StrCopy (Arg, sizeof (Arg), L+1);
233 L = ReadToken (L+1, ",)", Arg, sizeof (Arg));
235 /* Check for errors */
237 Error ("ASM code error: syntax error");
241 /* Check the different indirect modes */
243 /* Expect zp x indirect */
245 if (toupper (*L) != 'X') {
246 Error ("ASM code error: `X' expected");
251 Error ("ASM code error: `)' expected");
256 Error ("ASM code error: syntax error");
260 } else if (*L == ')') {
261 /* zp indirect or zp indirect, y */
265 if (toupper (*L) != 'Y') {
266 Error ("ASM code error: `Y' expected");
271 Error ("ASM code error: syntax error");
275 } else if (*L == '\0') {
278 Error ("ASM code error: syntax error");
294 /* Absolute, maybe indexed */
295 L = ReadToken (L, ",", Arg, sizeof (Arg));
297 /* Assume absolute */
299 } else if (*L == ',') {
303 Error ("ASM code error: syntax error");
310 } else if (Reg == 'Y') {
313 Error ("ASM code error: syntax error");
317 Error ("ASM code error: syntax error");
326 /* If the instruction is a branch, check for the label and generate it
327 * if it does not exist. Ignore anything but local labels here.
330 if ((OPC->Info & OF_BRA) != 0 && Arg[0] == 'L') {
334 /* Addressing mode must be alsobute or something is really wrong */
335 CHECK (AM == AM_ABS);
337 /* Addressing mode is a branch/jump */
340 /* Generate the hash over the label, then search for the label */
341 Hash = HashStr (Arg) % CS_LABEL_HASH_SIZE;
342 Label = FindCodeLabel (S, Arg, Hash);
344 /* If we don't have the label, it's a forward ref - create it */
346 /* Generate a new label */
347 Label = NewCodeSegLabel (S, Arg, Hash);
351 /* We do now have the addressing mode in AM. Allocate a new CodeEntry
352 * structure and initialize it.
354 E = NewCodeEntry (OPC, AM, Arg, Label);
356 /* Return the new code entry */
362 /*****************************************************************************/
364 /*****************************************************************************/
368 CodeSeg* NewCodeSeg (const char* SegName, SymEntry* Func)
369 /* Create a new code segment, initialize and return it */
373 /* Allocate memory */
374 CodeSeg* S = xmalloc (sizeof (CodeSeg));
376 /* Initialize the fields */
377 S->SegName = xstrdup (SegName);
379 InitCollection (&S->Entries);
380 InitCollection (&S->Labels);
381 for (I = 0; I < sizeof(S->LabelHash) / sizeof(S->LabelHash[0]); ++I) {
385 /* Return the new struct */
391 void AddCodeEntry (CodeSeg* S, const char* Format, va_list ap)
392 /* Add a line to the given code segment */
398 /* Format the line */
400 xvsprintf (Buf, sizeof (Buf), Format, ap);
402 /* Skip whitespace */
405 /* Check which type of instruction we have */
406 E = 0; /* Assume no insn created */
410 /* Empty line, just ignore it */
414 /* Comment or hint, ignore it for now */
418 /* Control instruction */
419 ReadToken (L, " \t", Token, sizeof (Token));
420 Error ("ASM code error: Pseudo instruction `%s' not supported", Token);
424 E = ParseInsn (S, L);
428 /* If we have a code entry, transfer the labels and insert it */
431 /* Transfer the labels if we have any */
433 unsigned LabelCount = CollCount (&S->Labels);
434 for (I = 0; I < LabelCount; ++I) {
437 CodeLabel* L = CollAt (&S->Labels, I);
439 /* Attach it to the entry */
440 AttachCodeLabel (E, L);
443 /* Delete the transfered labels */
444 CollDeleteAll (&S->Labels);
446 /* Add the entry to the list of code entries in this segment */
447 CollAppend (&S->Entries, E);
454 void DelCodeEntry (CodeSeg* S, unsigned Index)
455 /* Delete an entry from the code segment. This includes moving any associated
456 * labels, removing references to labels and even removing the referenced labels
457 * if the reference count drops to zero.
460 /* Get the code entry for the given index */
461 CodeEntry* E = GetCodeEntry (S, Index);
463 /* If the entry has a labels, we have to move this label to the next insn.
464 * If there is no next insn, move the label into the code segement label
465 * pool. The operation is further complicated by the fact that the next
466 * insn may already have a label. In that case change all reference to
467 * this label and delete the label instead of moving it.
469 unsigned Count = GetCodeLabelCount (E);
472 /* The instruction has labels attached. Check if there is a next
475 if (Index == GetCodeEntryCount (S)-1) {
477 /* No next instruction, move to the codeseg label pool */
478 MoveLabelsToPool (S, E);
482 /* There is a next insn, get it */
483 CodeEntry* N = GetCodeEntry (S, Index+1);
485 /* Move labels to the next entry */
486 MoveCodeLabels (S, E, N);
491 /* If this insn references a label, remove the reference. And, if the
492 * the reference count for this label drops to zero, remove this label.
495 /* Remove the reference */
496 RemoveCodeLabelRef (S, E);
499 /* Delete the pointer to the insn */
500 CollDelete (&S->Entries, Index);
502 /* Delete the instruction itself */
508 struct CodeEntry* GetCodeEntry (CodeSeg* S, unsigned Index)
509 /* Get an entry from the given code segment */
511 return CollAt (&S->Entries, Index);
516 unsigned GetCodeEntryIndex (CodeSeg* S, struct CodeEntry* E)
517 /* Return the index of a code entry */
519 int Index = CollIndex (&S->Entries, E);
526 void AddCodeLabel (CodeSeg* S, const char* Name)
527 /* Add a code label for the next instruction to follow */
529 /* Calculate the hash from the name */
530 unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
532 /* Try to find the code label if it does already exist */
533 CodeLabel* L = FindCodeLabel (S, Name, Hash);
535 /* Did we find it? */
537 /* We found it - be sure it does not already have an owner */
538 CHECK (L->Owner == 0);
540 /* Not found - create a new one */
541 L = NewCodeSegLabel (S, Name, Hash);
544 /* Safety. This call is quite costly, but safety is better */
545 if (CollIndex (&S->Labels, L) >= 0) {
546 Internal ("AddCodeLabel: Label `%s' already defined", Name);
549 /* We do now have a valid label. Remember it for later */
550 CollAppend (&S->Labels, L);
555 CodeLabel* GenCodeLabel (CodeSeg* S, struct CodeEntry* E)
556 /* If the code entry E does already have a label, return it. Otherwise
557 * create a new label, attach it to E and return it.
562 if (CodeEntryHasLabel (E)) {
564 /* Get the label from this entry */
565 L = GetCodeLabel (E, 0);
570 const char* Name = LocalLabelName (GetLocalLabel ());
572 /* Generate the hash over the name */
573 unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
575 /* Create a new label */
576 L = NewCodeSegLabel (S, Name, Hash);
578 /* Attach this label to the code entry */
579 AttachCodeLabel (E, L);
583 /* Return the label */
589 void DelCodeLabel (CodeSeg* S, CodeLabel* L)
590 /* Remove references from this label and delete it. */
594 /* First, remove the label from the hash chain */
595 RemoveLabelFromHash (S, L);
597 /* Remove references from insns jumping to this label */
598 Count = CollCount (&L->JumpFrom);
599 for (I = 0; I < Count; ++I) {
600 /* Get the insn referencing this label */
601 CodeEntry* E = CollAt (&L->JumpFrom, I);
602 /* Remove the reference */
605 CollDeleteAll (&L->JumpFrom);
607 /* Remove the reference to the owning instruction if it has one. The
608 * function may be called for a label without an owner when deleting
609 * unfinished parts of the code. This is unfortunate since it allows
610 * errors to slip through.
613 CollDeleteItem (&L->Owner->Labels, L);
616 /* All references removed, delete the label itself */
622 void MergeCodeLabels (CodeSeg* S)
623 /* Merge code labels. That means: For each instruction, remove all labels but
624 * one and adjust references accordingly.
629 /* Walk over all code entries */
630 unsigned EntryCount = GetCodeEntryCount (S);
631 for (I = 0; I < EntryCount; ++I) {
636 /* Get a pointer to the next entry */
637 CodeEntry* E = GetCodeEntry (S, I);
639 /* If this entry has zero labels, continue with the next one */
640 unsigned LabelCount = GetCodeLabelCount (E);
641 if (LabelCount == 0) {
645 /* We have at least one label. Use the first one as reference label. */
646 RefLab = GetCodeLabel (E, 0);
648 /* Walk through the remaining labels and change references to these
649 * labels to a reference to the one and only label. Delete the labels
650 * that are no longer used. To increase performance, walk backwards
653 for (J = LabelCount-1; J >= 1; --J) {
655 /* Get the next label */
656 CodeLabel* L = GetCodeLabel (E, J);
658 /* Move all references from this label to the reference label */
659 MoveLabelRefs (L, RefLab);
661 /* Remove the label completely. */
665 /* The reference label is the only remaining label. Check if there
666 * are any references to this label, and delete it if this is not
669 if (CollCount (&RefLab->JumpFrom) == 0) {
670 /* Delete the label */
671 DelCodeLabel (S, RefLab);
678 void MoveCodeLabels (CodeSeg* S, struct CodeEntry* Old, struct CodeEntry* New)
679 /* Move all labels from Old to New. The routine will move the labels itself
680 * if New does not have any labels, and move references if there is at least
681 * a label for new. If references are moved, the old label is deleted
685 /* Get the number of labels to move */
686 unsigned OldLabelCount = GetCodeLabelCount (Old);
688 /* Does the new entry have itself a label? */
689 if (CodeEntryHasLabel (New)) {
691 /* The new entry does already have a label - move references */
692 CodeLabel* NewLabel = GetCodeLabel (New, 0);
693 while (OldLabelCount--) {
695 /* Get the next label */
696 CodeLabel* OldLabel = GetCodeLabel (Old, OldLabelCount);
698 /* Move references */
699 MoveLabelRefs (OldLabel, NewLabel);
701 /* Delete the label */
702 DelCodeLabel (S, OldLabel);
708 /* The new entry does not have a label, just move them */
709 while (OldLabelCount--) {
711 /* Move the label to the new entry */
712 MoveCodeLabel (GetCodeLabel (Old, OldLabelCount), New);
721 void RemoveCodeLabelRef (CodeSeg* S, struct CodeEntry* E)
722 /* Remove the reference between E and the label it jumps to. The reference
723 * will be removed on both sides and E->JumpTo will be 0 after that. If
724 * the reference was the only one for the label, the label will get
728 /* Get a pointer to the label and make sure it exists */
729 CodeLabel* L = E->JumpTo;
732 /* Delete the entry from the label */
733 CollDeleteItem (&L->JumpFrom, E);
735 /* The entry jumps no longer to L */
738 /* If there are no more references, delete the label */
739 if (CollCount (&L->JumpFrom) == 0) {
746 void MoveCodeLabelRef (CodeSeg* S, struct CodeEntry* E, CodeLabel* L)
747 /* Change the reference of E to L instead of the current one. If this
748 * was the only reference to the old label, the old label will get
752 /* Get the old label */
753 CodeLabel* OldLabel = E->JumpTo;
755 /* Be sure that code entry references a label */
756 PRECONDITION (OldLabel != 0);
758 /* Remove the reference to our label */
759 RemoveCodeLabelRef (S, E);
761 /* Use the new label */
767 void AddCodeSegHint (CodeSeg* S, unsigned Hint)
768 /* Add a hint for the preceeding instruction */
772 /* Get the number of entries in this segment */
773 unsigned EntryCount = GetCodeEntryCount (S);
775 /* Must have at least one entry */
776 CHECK (EntryCount > 0);
778 /* Get the last entry */
779 E = GetCodeEntry (S, EntryCount-1);
787 void DelCodeSegAfter (CodeSeg* S, unsigned Last)
788 /* Delete all entries including the given one */
790 /* Get the number of entries in this segment */
791 unsigned Count = GetCodeEntryCount (S);
793 /* Check if we have to delete anything */
796 /* Remove all entries after the given one */
797 while (Last < Count--) {
799 /* Get the next entry */
800 CodeEntry* E = GetCodeEntry (S, Count);
802 /* If the code entry has labels, delete them */
803 while (CodeEntryHasLabel (E)) {
806 CodeLabel* L = GetCodeLabel (E, 0);
813 /* Delete the entry itself */
814 DelCodeEntry (S, Count);
821 void OutputCodeSeg (const CodeSeg* S, FILE* F)
822 /* Output the code segment data to a file */
826 /* Get the number of entries in this segment */
827 unsigned Count = GetCodeEntryCount (S);
829 /* If the code segment is empty, bail out here */
834 /* Output the segment directive */
835 fprintf (F, ".segment\t\"%s\"\n\n", S->SegName);
837 /* If this is a segment for a function, enter a function */
839 fprintf (F, ".proc\t_%s\n\n", S->Func->Name);
842 /* Output all entries */
843 for (I = 0; I < Count; ++I) {
844 OutputCodeEntry (CollConstAt (&S->Entries, I), F);
847 /* If this is a segment for a function, leave the function */
849 fprintf (F, "\n.endproc\n\n");
855 unsigned GetCodeEntryCount (const CodeSeg* S)
856 /* Return the number of entries for the given code segment */
858 return CollCount (&S->Entries);