1 /*****************************************************************************/
5 /* Code segment structure */
9 /* (C) 2001 Ullrich von Bassewitz */
11 /* D-70597 Stuttgart */
12 /* EMail: uz@musoftware.de */
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 /*****************************************************************************/
57 /*****************************************************************************/
59 /*****************************************************************************/
63 /* Pointer to current code segment */
68 /*****************************************************************************/
69 /* Functions for parsing instructions */
70 /*****************************************************************************/
74 static CodeLabel* NewCodeSegLabel (CodeSeg* S, const char* Name, unsigned Hash)
75 /* Create a new label and insert it into the label hash table */
77 /* Not found - create a new one */
78 CodeLabel* L = NewCodeLabel (Name, Hash);
80 /* Enter the label into the hash table */
81 L->Next = S->LabelHash[L->Hash];
82 S->LabelHash[L->Hash] = L;
84 /* Return the new label */
90 static const char* SkipSpace (const char* S)
91 /* Skip white space and return an updated pointer */
93 while (IsSpace (*S)) {
101 static const char* ReadToken (const char* L, const char* Term,
102 char* Buf, unsigned BufSize)
103 /* Read the next token into Buf, return the updated line pointer. The
104 * token is terminated by one of the characters given in term.
107 /* Read/copy the token */
109 unsigned ParenCount = 0;
110 while (*L && (ParenCount > 0 || strchr (Term, *L) == 0)) {
116 } else if (*L == '(') {
122 /* Terminate the buffer contents */
125 /* Return the updated line pointer */
131 static CodeEntry* ParseInsn (CodeSeg* S, const char* L)
132 /* Parse an instruction nnd generate a code entry from it. If the line contains
133 * errors, output an error message and return NULL.
134 * For simplicity, we don't accept the broad range of input a "real" assembler
135 * does. The instruction and the argument are expected to be separated by
136 * white space, for example.
141 am_t AM = 0; /* Initialize to keep gcc silent */
148 L = ReadToken (L, " \t", Mnemo, sizeof (Mnemo));
150 /* Try to find the opcode description for the mnemonic */
151 OPC = FindOpcode (Mnemo);
153 /* If we didn't find the opcode, print an error and bail out */
155 Error ("ASM code error: %s is not a valid mnemonic", Mnemo);
159 /* Skip separator white space */
162 /* Get the addressing mode */
173 StrCopy (Arg, sizeof (Arg), L+1);
179 L = ReadToken (L+1, ",)", Arg, sizeof (Arg));
181 /* Check for errors */
183 Error ("ASM code error: syntax error");
187 /* Check the different indirect modes */
189 /* Expect zp x indirect */
191 if (toupper (*L) != 'X') {
192 Error ("ASM code error: `X' expected");
197 Error ("ASM code error: `)' expected");
202 Error ("ASM code error: syntax error");
206 } else if (*L == ')') {
207 /* zp indirect or zp indirect, y */
211 if (toupper (*L) != 'Y') {
212 Error ("ASM code error: `Y' expected");
217 Error ("ASM code error: syntax error");
221 } else if (*L == '\0') {
224 Error ("ASM code error: syntax error");
240 /* Absolute, maybe indexed */
241 L = ReadToken (L, ",", Arg, sizeof (Arg));
243 /* Assume absolute */
245 } else if (*L == ',') {
249 Error ("ASM code error: syntax error");
256 } else if (Reg == 'Y') {
259 Error ("ASM code error: syntax error");
263 Error ("ASM code error: syntax error");
272 /* If the instruction is a branch, check for the label and generate it
273 * if it does not exist. Ignore anything but local labels here.
276 if ((OPC->Info & CI_MASK_BRA) == CI_BRA && Arg[0] == 'L') {
280 /* Addressing mode must be alsobute or something is really wrong */
281 CHECK (AM == AM_ABS);
283 /* Addressing mode is a branch/jump */
286 /* Generate the hash over the label, then search for the label */
287 Hash = HashStr (Arg) % CS_LABEL_HASH_SIZE;
288 Label = FindCodeLabel (S, Arg, Hash);
290 /* If we don't have the label, it's a forward ref - create it */
292 /* Generate a new label */
293 Label = NewCodeSegLabel (S, Arg, Hash);
297 /* We do now have the addressing mode in AM. Allocate a new CodeEntry
298 * structure and initialize it.
300 E = NewCodeEntry (OPC, AM, Label);
301 if (Arg[0] != '\0') {
302 /* We have an additional expression */
303 E->Arg = xstrdup (Arg);
306 /* Return the new code entry */
312 /*****************************************************************************/
314 /*****************************************************************************/
318 CodeSeg* NewCodeSeg (const char* SegName, const char* FuncName)
319 /* Create a new code segment, initialize and return it */
323 /* Allocate memory */
324 CodeSeg* S = xmalloc (sizeof (CodeSeg));
326 /* Initialize the fields */
328 S->SegName = xstrdup (SegName);
329 S->FuncName = xstrdup (FuncName);
330 InitCollection (&S->Entries);
331 InitCollection (&S->Labels);
332 for (I = 0; I < sizeof(S->LabelHash) / sizeof(S->LabelHash[0]); ++I) {
336 /* Return the new struct */
342 void FreeCodeSeg (CodeSeg* S)
343 /* Free a code segment including all code entries */
345 FAIL ("Not implemented");
350 void PushCodeSeg (CodeSeg* S)
351 /* Push the given code segment onto the stack */
359 CodeSeg* PopCodeSeg (void)
360 /* Remove the current code segment from the stack and return it */
362 /* Remember the current code segment */
365 /* Cannot pop on empty stack */
366 PRECONDITION (S != 0);
371 /* Return the popped code segment */
377 void AddCodeSegLine (CodeSeg* S, const char* Format, ...)
378 /* Add a line to the given code segment */
384 /* Format the line */
387 va_start (ap, Format);
388 xvsprintf (Buf, sizeof (Buf), Format, ap);
391 /* Skip whitespace */
394 /* Check which type of instruction we have */
395 E = 0; /* Assume no insn created */
399 /* Empty line, just ignore it */
403 /* Comment or hint, ignore it for now */
407 /* Control instruction */
408 ReadToken (L, " \t", Token, sizeof (Token));
409 Error ("ASM code error: Pseudo instruction `%s' not supported", Token);
413 E = ParseInsn (S, L);
417 /* If we have a code entry, transfer the labels and insert it */
420 /* Transfer the labels if we have any */
422 unsigned LabelCount = CollCount (&S->Labels);
423 for (I = 0; I < LabelCount; ++I) {
425 CodeLabel* L = CollAt (&S->Labels, I);
426 /* Mark it as defined */
428 /* Move it to the code entry */
429 CollAppend (&E->Labels, L);
430 /* Tell the label about it's owner */
434 /* Delete the transfered labels */
435 CollDeleteAll (&S->Labels);
437 /* Add the entry to the list of code entries in this segment */
438 CollAppend (&S->Entries, E);
445 void DelCodeSegLine (CodeSeg* S, unsigned Index)
446 /* Delete an entry from the code segment. This includes deleting any associated
447 * labels, removing references to labels and even removing the referenced labels
448 * if the reference count drops to zero.
451 /* Get the code entry for the given index */
452 CodeEntry* E = CollAt (&S->Entries, Index);
454 /* Remove any labels associated with this entry */
456 while ((Count = CollCount (&E->Labels)) > 0) {
457 DelCodeLabel (S, CollAt (&E->Labels, Count-1));
460 /* If this insn references a label, remove the reference. And, if the
461 * the reference count for this label drops to zero, remove this label.
465 /* Remove the reference */
466 if (RemoveLabelRef (E->JumpTo, E) == 0) {
467 /* No references remaining, remove the label */
468 DelCodeLabel (S, E->JumpTo);
471 /* Reset the label pointer to avoid problems later */
475 /* Delete the pointer to the insn */
476 CollDelete (&S->Entries, Index);
478 /* Delete the instruction itself */
484 void AddCodeLabel (CodeSeg* S, const char* Name)
485 /* Add a code label for the next instruction to follow */
487 /* Calculate the hash from the name */
488 unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
490 /* Try to find the code label if it does already exist */
491 CodeLabel* L = FindCodeLabel (S, Name, Hash);
493 /* Did we find it? */
495 /* We found it - be sure it does not already have an owner */
496 CHECK (L->Owner == 0);
498 /* Not found - create a new one */
499 L = NewCodeSegLabel (S, Name, Hash);
502 /* We do now have a valid label. Remember it for later */
503 CollAppend (&S->Labels, L);
508 void DelCodeLabel (CodeSeg* S, CodeLabel* L)
509 /* Remove references from this label and delete it. */
513 /* Get the first entry in the hash chain */
514 CodeLabel* List = S->LabelHash[L->Hash];
516 /* First, remove the label from the hash chain */
518 /* First entry in hash chain */
519 S->LabelHash[L->Hash] = L->Next;
521 /* Must search through the chain */
522 while (List->Next != L) {
523 /* If we've reached the end of the chain, something is *really* wrong */
524 CHECK (List->Next != 0);
528 /* The next entry is the one, we have been searching for */
529 List->Next = L->Next;
532 /* Remove references from insns jumping to this label */
533 Count = CollCount (&L->JumpFrom);
534 for (I = 0; I < Count; ++I) {
535 /* Get the insn referencing this label */
536 CodeEntry* E = CollAt (&L->JumpFrom, I);
537 /* Remove the reference */
540 CollDeleteAll (&L->JumpFrom);
542 /* Remove the reference to the owning instruction */
543 CollDeleteItem (&L->Owner->Labels, L);
545 /* All references removed, delete the label itself */
551 void AddCodeSegHint (CodeSeg* S, unsigned Hint)
552 /* Add a hint for the preceeding instruction */
556 /* Get the number of entries in this segment */
557 unsigned EntryCount = CollCount (&S->Entries);
559 /* Must have at least one entry */
560 CHECK (EntryCount > 0);
562 /* Get the last entry */
563 E = CollAt (&S->Entries, EntryCount-1);
571 void DelCodeSegAfter (CodeSeg* S, unsigned Last)
572 /* Delete all entries including the given one */
574 /* Get the number of entries in this segment */
575 unsigned Count = CollCount (&S->Entries);
577 /* Remove all entries after the given one */
578 while (Last < Count) {
580 /* Get the next entry */
581 CodeEntry* E = CollAt (&S->Entries, Count-1);
583 /* We have to transfer all labels to the code segment label pool */
584 unsigned LabelCount = CollCount (&E->Labels);
585 while (LabelCount--) {
586 CodeLabel* L = CollAt (&E->Labels, LabelCount);
588 CollAppend (&S->Labels, L);
590 CollDeleteAll (&E->Labels);
592 /* Remove the code entry */
593 FreeCodeEntry (CollAt (&S->Entries, Count-1));
594 CollDelete (&S->Entries, Count-1);
601 void OutputCodeSeg (FILE* F, const CodeSeg* S)
602 /* Output the code segment data to a file */
606 /* Get the number of entries in this segment */
607 unsigned Count = CollCount (&S->Entries);
609 fprintf (F, "; Labels: ");
610 for (I = 0; I < CS_LABEL_HASH_SIZE; ++I) {
611 const CodeLabel* L = S->LabelHash[I];
613 fprintf (F, "%s ", L->Name);
619 /* Output the segment directive */
620 fprintf (F, ".segment\t\"%s\"\n\n", S->SegName);
622 /* If this is a segment for a function, enter a function */
623 if (S->FuncName[0] != '\0') {
624 fprintf (F, ".proc\t_%s\n\n", S->FuncName);
627 /* Output all entries */
628 for (I = 0; I < Count; ++I) {
629 OutputCodeEntry (F, CollConstAt (&S->Entries, I));
632 /* If this is a segment for a function, leave the function */
633 if (S->FuncName[0] != '\0') {
634 fprintf (F, "\n.endproc\n\n");
640 CodeLabel* FindCodeLabel (CodeSeg* S, const char* Name, unsigned Hash)
641 /* Find the label with the given name. Return the label or NULL if not found */
643 /* Get the first hash chain entry */
644 CodeLabel* L = S->LabelHash[Hash];
646 /* Search the list */
648 if (strcmp (Name, L->Name) == 0) {
659 void MergeCodeLabels (CodeSeg* S)
660 /* Merge code labels. That means: For each instruction, remove all labels but
661 * one and adjust the code entries accordingly.
666 /* Walk over all code entries */
667 unsigned EntryCount = CollCount (&S->Entries);
668 for (I = 0; I < EntryCount; ++I) {
673 /* Get a pointer to the next entry */
674 CodeEntry* E = CollAt (&S->Entries, I);
676 /* If this entry has zero labels, continue with the next one */
677 unsigned LabelCount = CollCount (&E->Labels);
678 if (LabelCount == 0) {
682 /* We have at least one label. Use the first one as reference label. */
683 RefLab = CollAt (&E->Labels, 0);
685 /* Walk through the remaining labels and change references to these
686 * labels to a reference to the one and only label. Delete the labels
687 * that are no longer used. To increase performance, walk backwards
690 for (J = LabelCount-1; J >= 1; --J) {
694 /* Get the next label */
695 CodeLabel* L = CollAt (&E->Labels, J);
697 /* Walk through all instructions referencing this label */
698 unsigned RefCount = CollCount (&L->JumpFrom);
699 for (K = 0; K < RefCount; ++K) {
701 /* Get the next instruction that references this label */
702 CodeEntry* E = CollAt (&L->JumpFrom, K);
704 /* Change the reference */
705 CHECK (E->JumpTo == L);
706 AddLabelRef (RefLab, E);
710 /* There are no more instructions jumping to this label now */
711 CollDeleteAll (&L->JumpFrom);
713 /* Remove the label completely. */
717 /* The reference label is the only remaining label. Check if there
718 * are any references to this label, and delete it if this is not
721 if (CollCount (&RefLab->JumpFrom) == 0) {
722 /* Delete the label */
723 DelCodeLabel (S, RefLab);
730 unsigned GetCodeSegEntries (const CodeSeg* S)
731 /* Return the number of entries for the given code segment */
733 return CollCount (&S->Entries);