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 /*****************************************************************************/
55 /*****************************************************************************/
56 /* Functions for parsing instructions */
57 /*****************************************************************************/
61 static CodeLabel* NewCodeSegLabel (CodeSeg* S, const char* Name, unsigned Hash)
62 /* Create a new label and insert it into the label hash table */
64 /* Not found - create a new one */
65 CodeLabel* L = NewCodeLabel (Name, Hash);
67 /* Enter the label into the hash table */
68 L->Next = S->LabelHash[L->Hash];
69 S->LabelHash[L->Hash] = L;
71 /* Return the new label */
77 static const char* SkipSpace (const char* S)
78 /* Skip white space and return an updated pointer */
80 while (IsSpace (*S)) {
88 static const char* ReadToken (const char* L, const char* Term,
89 char* Buf, unsigned BufSize)
90 /* Read the next token into Buf, return the updated line pointer. The
91 * token is terminated by one of the characters given in term.
94 /* Read/copy the token */
96 unsigned ParenCount = 0;
97 while (*L && (ParenCount > 0 || strchr (Term, *L) == 0)) {
103 } else if (*L == '(') {
109 /* Terminate the buffer contents */
112 /* Return the updated line pointer */
118 static CodeEntry* ParseInsn (CodeSeg* S, const char* L)
119 /* Parse an instruction nnd generate a code entry from it. If the line contains
120 * errors, output an error message and return NULL.
121 * For simplicity, we don't accept the broad range of input a "real" assembler
122 * does. The instruction and the argument are expected to be separated by
123 * white space, for example.
128 am_t AM = 0; /* Initialize to keep gcc silent */
135 L = ReadToken (L, " \t", Mnemo, sizeof (Mnemo));
137 /* Try to find the opcode description for the mnemonic */
138 OPC = FindOpcode (Mnemo);
140 /* If we didn't find the opcode, print an error and bail out */
142 Error ("ASM code error: %s is not a valid mnemonic", Mnemo);
146 /* Skip separator white space */
149 /* Get the addressing mode */
160 StrCopy (Arg, sizeof (Arg), L+1);
166 L = ReadToken (L+1, ",)", Arg, sizeof (Arg));
168 /* Check for errors */
170 Error ("ASM code error: syntax error");
174 /* Check the different indirect modes */
176 /* Expect zp x indirect */
178 if (toupper (*L) != 'X') {
179 Error ("ASM code error: `X' expected");
184 Error ("ASM code error: `)' expected");
189 Error ("ASM code error: syntax error");
193 } else if (*L == ')') {
194 /* zp indirect or zp indirect, y */
198 if (toupper (*L) != 'Y') {
199 Error ("ASM code error: `Y' expected");
204 Error ("ASM code error: syntax error");
208 } else if (*L == '\0') {
211 Error ("ASM code error: syntax error");
227 /* Absolute, maybe indexed */
228 L = ReadToken (L, ",", Arg, sizeof (Arg));
230 /* Assume absolute */
232 } else if (*L == ',') {
236 Error ("ASM code error: syntax error");
243 } else if (Reg == 'Y') {
246 Error ("ASM code error: syntax error");
250 Error ("ASM code error: syntax error");
259 /* If the instruction is a branch, check for the label and generate it
260 * if it does not exist. Ignore anything but local labels here.
263 if ((OPC->Info & CI_MASK_BRA) == CI_BRA && Arg[0] == 'L') {
267 /* Addressing mode must be alsobute or something is really wrong */
268 CHECK (AM == AM_ABS);
270 /* Addressing mode is a branch/jump */
273 /* Generate the hash over the label, then search for the label */
274 Hash = HashStr (Arg) % CS_LABEL_HASH_SIZE;
275 Label = FindCodeLabel (S, Arg, Hash);
277 /* If we don't have the label, it's a forward ref - create it */
279 /* Generate a new label */
280 Label = NewCodeSegLabel (S, Arg, Hash);
284 /* We do now have the addressing mode in AM. Allocate a new CodeEntry
285 * structure and initialize it.
287 E = NewCodeEntry (OPC, AM, Arg, Label);
289 /* Return the new code entry */
295 /*****************************************************************************/
297 /*****************************************************************************/
301 CodeSeg* NewCodeSeg (const char* SegName, SymEntry* Func)
302 /* Create a new code segment, initialize and return it */
306 /* Allocate memory */
307 CodeSeg* S = xmalloc (sizeof (CodeSeg));
309 /* Initialize the fields */
310 S->SegName = xstrdup (SegName);
312 InitCollection (&S->Entries);
313 InitCollection (&S->Labels);
314 for (I = 0; I < sizeof(S->LabelHash) / sizeof(S->LabelHash[0]); ++I) {
318 /* Return the new struct */
324 void FreeCodeSeg (CodeSeg* S)
325 /* Free a code segment including all code entries */
327 Internal ("Not implemented");
332 void AddCodeEntry (CodeSeg* S, const char* Format, va_list ap)
333 /* Add a line to the given code segment */
339 /* Format the line */
341 xvsprintf (Buf, sizeof (Buf), Format, ap);
343 /* Skip whitespace */
346 /* Check which type of instruction we have */
347 E = 0; /* Assume no insn created */
351 /* Empty line, just ignore it */
355 /* Comment or hint, ignore it for now */
359 /* Control instruction */
360 ReadToken (L, " \t", Token, sizeof (Token));
361 Error ("ASM code error: Pseudo instruction `%s' not supported", Token);
365 E = ParseInsn (S, L);
369 /* If we have a code entry, transfer the labels and insert it */
372 /* Transfer the labels if we have any */
374 unsigned LabelCount = CollCount (&S->Labels);
375 for (I = 0; I < LabelCount; ++I) {
377 CodeLabel* L = CollAt (&S->Labels, I);
378 /* Mark it as defined */
380 /* Move it to the code entry */
381 CollAppend (&E->Labels, L);
382 /* Tell the label about it's owner */
386 /* Delete the transfered labels */
387 CollDeleteAll (&S->Labels);
389 /* Add the entry to the list of code entries in this segment */
390 CollAppend (&S->Entries, E);
397 void DelCodeEntry (CodeSeg* S, unsigned Index)
398 /* Delete an entry from the code segment. This includes deleting any associated
399 * labels, removing references to labels and even removing the referenced labels
400 * if the reference count drops to zero.
403 /* Get the code entry for the given index */
404 CodeEntry* E = CollAt (&S->Entries, Index);
406 /* Remove any labels associated with this entry */
408 while ((Count = CollCount (&E->Labels)) > 0) {
409 DelCodeLabel (S, CollAt (&E->Labels, Count-1));
412 /* If this insn references a label, remove the reference. And, if the
413 * the reference count for this label drops to zero, remove this label.
417 /* Remove the reference */
418 if (RemoveLabelRef (E->JumpTo, E) == 0) {
419 /* No references remaining, remove the label */
420 DelCodeLabel (S, E->JumpTo);
423 /* Reset the label pointer to avoid problems later */
427 /* Delete the pointer to the insn */
428 CollDelete (&S->Entries, Index);
430 /* Delete the instruction itself */
436 void AddCodeLabel (CodeSeg* S, const char* Name)
437 /* Add a code label for the next instruction to follow */
439 /* Calculate the hash from the name */
440 unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
442 /* Try to find the code label if it does already exist */
443 CodeLabel* L = FindCodeLabel (S, Name, Hash);
445 /* Did we find it? */
447 /* We found it - be sure it does not already have an owner */
448 CHECK (L->Owner == 0);
450 /* Not found - create a new one */
451 L = NewCodeSegLabel (S, Name, Hash);
454 /* We do now have a valid label. Remember it for later */
455 CollAppend (&S->Labels, L);
460 void DelCodeLabel (CodeSeg* S, CodeLabel* L)
461 /* Remove references from this label and delete it. */
465 /* Get the first entry in the hash chain */
466 CodeLabel* List = S->LabelHash[L->Hash];
468 /* First, remove the label from the hash chain */
470 /* First entry in hash chain */
471 S->LabelHash[L->Hash] = L->Next;
473 /* Must search through the chain */
474 while (List->Next != L) {
475 /* If we've reached the end of the chain, something is *really* wrong */
476 CHECK (List->Next != 0);
480 /* The next entry is the one, we have been searching for */
481 List->Next = L->Next;
484 /* Remove references from insns jumping to this label */
485 Count = CollCount (&L->JumpFrom);
486 for (I = 0; I < Count; ++I) {
487 /* Get the insn referencing this label */
488 CodeEntry* E = CollAt (&L->JumpFrom, I);
489 /* Remove the reference */
492 CollDeleteAll (&L->JumpFrom);
494 /* Remove the reference to the owning instruction */
495 CollDeleteItem (&L->Owner->Labels, L);
497 /* All references removed, delete the label itself */
503 void AddCodeSegHint (CodeSeg* S, unsigned Hint)
504 /* Add a hint for the preceeding instruction */
508 /* Get the number of entries in this segment */
509 unsigned EntryCount = CollCount (&S->Entries);
511 /* Must have at least one entry */
512 CHECK (EntryCount > 0);
514 /* Get the last entry */
515 E = CollAt (&S->Entries, EntryCount-1);
523 void DelCodeSegAfter (CodeSeg* S, unsigned Last)
524 /* Delete all entries including the given one */
526 /* Get the number of entries in this segment */
527 unsigned Count = CollCount (&S->Entries);
529 /* Remove all entries after the given one */
530 while (Last < Count) {
532 /* Get the next entry */
533 CodeEntry* E = CollAt (&S->Entries, Count-1);
535 /* We have to transfer all labels to the code segment label pool */
536 unsigned LabelCount = CollCount (&E->Labels);
537 while (LabelCount--) {
538 CodeLabel* L = CollAt (&E->Labels, LabelCount);
540 CollAppend (&S->Labels, L);
542 CollDeleteAll (&E->Labels);
544 /* Remove the code entry */
545 FreeCodeEntry (CollAt (&S->Entries, Count-1));
546 CollDelete (&S->Entries, Count-1);
553 void OutputCodeSeg (const CodeSeg* S, FILE* F)
554 /* Output the code segment data to a file */
558 /* Get the number of entries in this segment */
559 unsigned Count = CollCount (&S->Entries);
561 /* If the code segment is empty, bail out here */
566 /* Output the segment directive */
567 fprintf (F, ".segment\t\"%s\"\n\n", S->SegName);
569 /* If this is a segment for a function, enter a function */
571 fprintf (F, ".proc\t_%s\n\n", S->Func->Name);
574 /* Output all entries */
575 for (I = 0; I < Count; ++I) {
576 OutputCodeEntry (CollConstAt (&S->Entries, I), F);
579 /* If this is a segment for a function, leave the function */
581 fprintf (F, "\n.endproc\n\n");
587 CodeLabel* FindCodeLabel (CodeSeg* S, const char* Name, unsigned Hash)
588 /* Find the label with the given name. Return the label or NULL if not found */
590 /* Get the first hash chain entry */
591 CodeLabel* L = S->LabelHash[Hash];
593 /* Search the list */
595 if (strcmp (Name, L->Name) == 0) {
606 void MergeCodeLabels (CodeSeg* S)
607 /* Merge code labels. That means: For each instruction, remove all labels but
608 * one and adjust the code entries accordingly.
613 /* Walk over all code entries */
614 unsigned EntryCount = CollCount (&S->Entries);
615 for (I = 0; I < EntryCount; ++I) {
620 /* Get a pointer to the next entry */
621 CodeEntry* E = CollAt (&S->Entries, I);
623 /* If this entry has zero labels, continue with the next one */
624 unsigned LabelCount = CollCount (&E->Labels);
625 if (LabelCount == 0) {
629 /* We have at least one label. Use the first one as reference label. */
630 RefLab = CollAt (&E->Labels, 0);
632 /* Walk through the remaining labels and change references to these
633 * labels to a reference to the one and only label. Delete the labels
634 * that are no longer used. To increase performance, walk backwards
637 for (J = LabelCount-1; J >= 1; --J) {
641 /* Get the next label */
642 CodeLabel* L = CollAt (&E->Labels, J);
644 /* Walk through all instructions referencing this label */
645 unsigned RefCount = CollCount (&L->JumpFrom);
646 for (K = 0; K < RefCount; ++K) {
648 /* Get the next instruction that references this label */
649 CodeEntry* E = CollAt (&L->JumpFrom, K);
651 /* Change the reference */
652 CHECK (E->JumpTo == L);
653 AddLabelRef (RefLab, E);
657 /* There are no more instructions jumping to this label now */
658 CollDeleteAll (&L->JumpFrom);
660 /* Remove the label completely. */
664 /* The reference label is the only remaining label. Check if there
665 * are any references to this label, and delete it if this is not
668 if (CollCount (&RefLab->JumpFrom) == 0) {
669 /* Delete the label */
670 DelCodeLabel (S, RefLab);
677 unsigned GetCodeSegEntries (const CodeSeg* S)
678 /* Return the number of entries for the given code segment */
680 return CollCount (&S->Entries);