]> git.sur5r.net Git - cc65/blob - src/cc65/codeseg.c
Working on the new backend
[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@musoftware.de                                             */
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 "error.h"
49
50 /* b6502 */
51 #include "codeent.h"
52 #include "codeinfo.h"
53 #include "codeseg.h"
54
55
56
57 /*****************************************************************************/
58 /*                                   Data                                    */
59 /*****************************************************************************/
60
61
62
63 /* Pointer to current code segment */
64 CodeSeg* CS = 0;
65
66
67
68 /*****************************************************************************/
69 /*                    Functions for parsing instructions                     */
70 /*****************************************************************************/
71
72
73
74 static CodeLabel* NewCodeSegLabel (CodeSeg* S, const char* Name, unsigned Hash)
75 /* Create a new label and insert it into the label hash table */
76 {
77     /* Not found - create a new one */
78     CodeLabel* L = NewCodeLabel (Name, Hash);
79
80     /* Enter the label into the hash table */
81     L->Next = S->LabelHash[L->Hash];
82     S->LabelHash[L->Hash] = L;
83
84     /* Return the new label */
85     return L;
86 }
87
88
89
90 static const char* SkipSpace (const char* S)
91 /* Skip white space and return an updated pointer */
92 {
93     while (IsSpace (*S)) {
94         ++S;
95     }
96     return S;
97 }
98
99
100
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.
105  */
106 {
107     /* Read/copy the token */
108     unsigned I = 0;
109     unsigned ParenCount = 0;
110     while (*L && (ParenCount > 0 || strchr (Term, *L) == 0)) {
111         if (I < BufSize-1) {
112             Buf[I++] = *L;
113         }
114         if (*L == ')') {
115             --ParenCount;
116         } else if (*L == '(') {
117             ++ParenCount;
118         }
119         ++L;
120     }
121
122     /* Terminate the buffer contents */
123     Buf[I] = '\0';
124
125     /* Return the updated line pointer */
126     return L;
127 }
128
129
130
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.
137  */
138 {
139     char                Mnemo[16];
140     const OPCDesc*      OPC;
141     am_t                AM = 0;         /* Initialize to keep gcc silent */
142     char                Arg[64];
143     char                Reg;
144     CodeEntry*          E;
145     CodeLabel*          Label;
146
147     /* Mnemonic */
148     L = ReadToken (L, " \t", Mnemo, sizeof (Mnemo));
149
150     /* Try to find the opcode description for the mnemonic */
151     OPC = FindOpcode (Mnemo);
152
153     /* If we didn't find the opcode, print an error and bail out */
154     if (OPC == 0) {
155         Error ("ASM code error: %s is not a valid mnemonic", Mnemo);
156         return 0;
157     }
158
159     /* Skip separator white space */
160     L = SkipSpace (L);
161
162     /* Get the addressing mode */
163     Arg[0] = '\0';
164     switch (*L) {
165
166         case '\0':
167             /* Implicit */
168             AM = AM_IMP;
169             break;
170
171         case '#':
172             /* Immidiate */
173             StrCopy (Arg, sizeof (Arg), L+1);
174             AM = AM_IMM;
175             break;
176
177         case '(':
178             /* Indirect */
179             L = ReadToken (L+1, ",)", Arg, sizeof (Arg));
180
181             /* Check for errors */
182             if (*L == '\0') {
183                 Error ("ASM code error: syntax error");
184                 return 0;
185             }
186
187             /* Check the different indirect modes */
188             if (*L == ',') {
189                 /* Expect zp x indirect */
190                 L = SkipSpace (L+1);
191                 if (toupper (*L) != 'X') {
192                     Error ("ASM code error: `X' expected");
193                     return 0;
194                 }
195                 L = SkipSpace (L+1);
196                 if (*L != ')') {
197                     Error ("ASM code error: `)' expected");
198                     return 0;
199                 }
200                 L = SkipSpace (L+1);
201                 if (*L != '\0') {
202                     Error ("ASM code error: syntax error");
203                     return 0;
204                 }
205                 AM = AM_ZPX_IND;
206             } else if (*L == ')') {
207                 /* zp indirect or zp indirect, y */
208                 L = SkipSpace (L+1);
209                 if (*L == ',') {
210                     L = SkipSpace (L+1);
211                     if (toupper (*L) != 'Y') {
212                         Error ("ASM code error: `Y' expected");
213                         return 0;
214                     }
215                     L = SkipSpace (L+1);
216                     if (*L != '\0') {
217                         Error ("ASM code error: syntax error");
218                         return 0;
219                     }
220                     AM = AM_ZP_INDY;
221                 } else if (*L == '\0') {
222                     AM = AM_ZP_IND;
223                 } else {
224                     Error ("ASM code error: syntax error");
225                     return 0;
226                 }
227             }
228             break;
229
230         case 'a':
231         case 'A':
232             /* Accumulator? */
233             if (L[1] == '\0') {
234                 AM = AM_ACC;
235                 break;
236             }
237             /* FALLTHROUGH */
238
239         default:
240             /* Absolute, maybe indexed */
241             L = ReadToken (L, ",", Arg, sizeof (Arg));
242             if (*L == '\0') {
243                 /* Assume absolute */
244                 AM = AM_ABS;
245             } else if (*L == ',') {
246                 /* Indexed */
247                 L = SkipSpace (L+1);
248                 if (*L == '\0') {
249                     Error ("ASM code error: syntax error");
250                     return 0;
251                 } else {
252                     Reg = toupper (*L);
253                     L = SkipSpace (L+1);
254                     if (Reg == 'X') {
255                         AM = AM_ABSX;
256                     } else if (Reg == 'Y') {
257                         AM = AM_ABSY;
258                     } else {
259                         Error ("ASM code error: syntax error");
260                         return 0;
261                     }
262                     if (*L != '\0') {
263                         Error ("ASM code error: syntax error");
264                         return 0;
265                     }
266                 }
267             }
268             break;
269
270     }
271
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.
274      */
275     Label = 0;
276     if ((OPC->Info & CI_MASK_BRA) == CI_BRA && Arg[0] == 'L') {
277
278         unsigned Hash;
279
280         /* Addressing mode must be alsobute or something is really wrong */
281         CHECK (AM == AM_ABS);
282
283         /* Addressing mode is a branch/jump */
284         AM = AM_BRA;
285
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);
289
290         /* If we don't have the label, it's a forward ref - create it */
291         if (Label == 0) {
292             /* Generate a new label */
293             Label = NewCodeSegLabel (S, Arg, Hash);
294         }
295     }
296
297     /* We do now have the addressing mode in AM. Allocate a new CodeEntry
298      * structure and initialize it.
299      */
300     E = NewCodeEntry (OPC, AM, Arg, Label);
301
302     /* Return the new code entry */
303     return E;
304 }
305
306
307
308 /*****************************************************************************/
309 /*                                   Code                                    */
310 /*****************************************************************************/
311
312
313
314 CodeSeg* NewCodeSeg (const char* SegName, const char* FuncName)
315 /* Create a new code segment, initialize and return it */
316 {
317     unsigned I;
318
319     /* Allocate memory */
320     CodeSeg* S = xmalloc (sizeof (CodeSeg));
321
322     /* Initialize the fields */
323     S->Next     = 0;
324     S->SegName  = xstrdup (SegName);
325     S->FuncName = xstrdup (FuncName);
326     InitCollection (&S->Entries);
327     InitCollection (&S->Labels);
328     for (I = 0; I < sizeof(S->LabelHash) / sizeof(S->LabelHash[0]); ++I) {
329         S->LabelHash[I] = 0;
330     }
331
332     /* Return the new struct */
333     return S;
334 }
335
336
337
338 void FreeCodeSeg (CodeSeg* S)
339 /* Free a code segment including all code entries */
340 {
341     FAIL ("Not implemented");
342 }
343
344
345
346 void PushCodeSeg (CodeSeg* S)
347 /* Push the given code segment onto the stack */
348 {
349     S->Next = CS;
350     CS      = S;
351 }
352
353
354
355 CodeSeg* PopCodeSeg (void)
356 /* Remove the current code segment from the stack and return it */
357 {
358     /* Remember the current code segment */
359     CodeSeg* S = CS;
360
361     /* Cannot pop on empty stack */
362     PRECONDITION (S != 0);
363
364     /* Pop */
365     CS = S->Next;
366
367     /* Return the popped code segment */
368     return S;
369 }
370
371
372
373 void AddCodeSegLine (CodeSeg* S, const char* Format, ...)
374 /* Add a line to the given code segment */
375 {
376     const char* L;
377     CodeEntry*  E;
378     char        Token[64];
379
380     /* Format the line */
381     va_list ap;
382     char Buf [256];
383     va_start (ap, Format);
384     xvsprintf (Buf, sizeof (Buf), Format, ap);
385     va_end (ap);
386
387     /* Skip whitespace */
388     L = SkipSpace (Buf);
389
390     /* Check which type of instruction we have */
391     E = 0;      /* Assume no insn created */
392     switch (*L) {
393
394         case '\0':
395             /* Empty line, just ignore it */
396             break;
397
398         case ';':
399             /* Comment or hint, ignore it for now */
400             break;
401
402         case '.':
403             /* Control instruction */
404             ReadToken (L, " \t", Token, sizeof (Token));
405             Error ("ASM code error: Pseudo instruction `%s' not supported", Token);
406             break;
407
408         default:
409             E = ParseInsn (S, L);
410             break;
411     }
412
413     /* If we have a code entry, transfer the labels and insert it */
414     if (E) {
415
416         /* Transfer the labels if we have any */
417         unsigned I;
418         unsigned LabelCount = CollCount (&S->Labels);
419         for (I = 0; I < LabelCount; ++I) {
420             /* Get the label */
421             CodeLabel* L = CollAt (&S->Labels, I);
422             /* Mark it as defined */
423             L->Flags |= LF_DEF;
424             /* Move it to the code entry */
425             CollAppend (&E->Labels, L);
426             /* Tell the label about it's owner */
427             L->Owner = E;
428         }
429
430         /* Delete the transfered labels */
431         CollDeleteAll (&S->Labels);
432
433         /* Add the entry to the list of code entries in this segment */
434         CollAppend (&S->Entries, E);
435
436     }
437 }
438
439
440
441 void DelCodeSegLine (CodeSeg* S, unsigned Index)
442 /* Delete an entry from the code segment. This includes deleting any associated
443  * labels, removing references to labels and even removing the referenced labels
444  * if the reference count drops to zero.
445  */
446 {
447     /* Get the code entry for the given index */
448     CodeEntry* E = CollAt (&S->Entries, Index);
449
450     /* Remove any labels associated with this entry */
451     unsigned Count;
452     while ((Count = CollCount (&E->Labels)) > 0) {
453         DelCodeLabel (S, CollAt (&E->Labels, Count-1));
454     }
455
456     /* If this insn references a label, remove the reference. And, if the
457      * the reference count for this label drops to zero, remove this label.
458      */
459     if (E->JumpTo) {
460
461         /* Remove the reference */
462         if (RemoveLabelRef (E->JumpTo, E) == 0) {
463             /* No references remaining, remove the label */
464             DelCodeLabel (S, E->JumpTo);
465         }
466
467         /* Reset the label pointer to avoid problems later */
468         E->JumpTo = 0;
469     }
470
471     /* Delete the pointer to the insn */
472     CollDelete (&S->Entries, Index);
473
474     /* Delete the instruction itself */
475     FreeCodeEntry (E);
476 }
477
478
479
480 void AddCodeLabel (CodeSeg* S, const char* Name)
481 /* Add a code label for the next instruction to follow */
482 {
483     /* Calculate the hash from the name */
484     unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
485
486     /* Try to find the code label if it does already exist */
487     CodeLabel* L = FindCodeLabel (S, Name, Hash);
488
489     /* Did we find it? */
490     if (L) {
491         /* We found it - be sure it does not already have an owner */
492         CHECK (L->Owner == 0);
493     } else {
494         /* Not found - create a new one */
495         L = NewCodeSegLabel (S, Name, Hash);
496     }
497
498     /* We do now have a valid label. Remember it for later */
499     CollAppend (&S->Labels, L);
500 }
501
502
503
504 void DelCodeLabel (CodeSeg* S, CodeLabel* L)
505 /* Remove references from this label and delete it. */
506 {
507     unsigned Count, I;
508
509     /* Get the first entry in the hash chain */
510     CodeLabel* List = S->LabelHash[L->Hash];
511
512     /* First, remove the label from the hash chain */
513     if (List == L) {
514         /* First entry in hash chain */
515         S->LabelHash[L->Hash] = L->Next;
516     } else {
517         /* Must search through the chain */
518         while (List->Next != L) {
519             /* If we've reached the end of the chain, something is *really* wrong */
520             CHECK (List->Next != 0);
521             /* Next entry */
522             List = List->Next;
523         }
524         /* The next entry is the one, we have been searching for */
525         List->Next = L->Next;
526     }
527
528     /* Remove references from insns jumping to this label */
529     Count = CollCount (&L->JumpFrom);
530     for (I = 0; I < Count; ++I) {
531         /* Get the insn referencing this label */
532         CodeEntry* E = CollAt (&L->JumpFrom, I);
533         /* Remove the reference */
534         E->JumpTo = 0;
535     }
536     CollDeleteAll (&L->JumpFrom);
537
538     /* Remove the reference to the owning instruction */
539     CollDeleteItem (&L->Owner->Labels, L);
540
541     /* All references removed, delete the label itself */
542     FreeCodeLabel (L);
543 }
544
545
546
547 void AddCodeSegHint (CodeSeg* S, unsigned Hint)
548 /* Add a hint for the preceeding instruction */
549 {
550     CodeEntry* E;
551
552     /* Get the number of entries in this segment */
553     unsigned EntryCount = CollCount (&S->Entries);
554
555     /* Must have at least one entry */
556     CHECK (EntryCount > 0);
557
558     /* Get the last entry */
559     E = CollAt (&S->Entries, EntryCount-1);
560
561     /* Add the hint */
562     E->Hints |= Hint;
563 }
564
565
566
567 void DelCodeSegAfter (CodeSeg* S, unsigned Last)
568 /* Delete all entries including the given one */
569 {
570     /* Get the number of entries in this segment */
571     unsigned Count = CollCount (&S->Entries);
572
573     /* Remove all entries after the given one */
574     while (Last < Count) {
575
576         /* Get the next entry */
577         CodeEntry* E = CollAt (&S->Entries, Count-1);
578
579         /* We have to transfer all labels to the code segment label pool */
580         unsigned LabelCount = CollCount (&E->Labels);
581         while (LabelCount--) {
582             CodeLabel* L = CollAt (&E->Labels, LabelCount);
583             L->Flags &= ~LF_DEF;
584             CollAppend (&S->Labels, L);
585         }
586         CollDeleteAll (&E->Labels);
587
588         /* Remove the code entry */
589         FreeCodeEntry (CollAt (&S->Entries, Count-1));
590         CollDelete (&S->Entries, Count-1);
591         --Count;
592     }
593 }
594
595
596
597 void OutputCodeSeg (FILE* F, const CodeSeg* S)
598 /* Output the code segment data to a file */
599 {
600     unsigned I;
601
602     /* Get the number of entries in this segment */
603     unsigned Count = CollCount (&S->Entries);
604
605     fprintf (F, "; Labels: ");
606     for (I = 0; I < CS_LABEL_HASH_SIZE; ++I) {
607         const CodeLabel* L = S->LabelHash[I];
608         while (L) {
609             fprintf (F, "%s ", L->Name);
610             L = L->Next;
611         }
612     }
613     fprintf (F, "\n");
614
615     /* Output the segment directive */
616     fprintf (F, ".segment\t\"%s\"\n\n", S->SegName);
617
618     /* If this is a segment for a function, enter a function */
619     if (S->FuncName[0] != '\0') {
620         fprintf (F, ".proc\t_%s\n\n", S->FuncName);
621     }
622
623     /* Output all entries */
624     for (I = 0; I < Count; ++I) {
625         OutputCodeEntry (F, CollConstAt (&S->Entries, I));
626     }
627
628     /* If this is a segment for a function, leave the function */
629     if (S->FuncName[0] != '\0') {
630         fprintf (F, "\n.endproc\n\n");
631     }
632 }
633
634
635
636 CodeLabel* FindCodeLabel (CodeSeg* S, const char* Name, unsigned Hash)
637 /* Find the label with the given name. Return the label or NULL if not found */
638 {
639     /* Get the first hash chain entry */
640     CodeLabel* L = S->LabelHash[Hash];
641
642     /* Search the list */
643     while (L) {
644         if (strcmp (Name, L->Name) == 0) {
645             /* Found */
646             break;
647         }
648         L = L->Next;
649     }
650     return L;
651 }
652
653
654
655 void MergeCodeLabels (CodeSeg* S)
656 /* Merge code labels. That means: For each instruction, remove all labels but
657  * one and adjust the code entries accordingly.
658  */
659 {
660     unsigned I;
661
662     /* Walk over all code entries */
663     unsigned EntryCount = CollCount (&S->Entries);
664     for (I = 0; I < EntryCount; ++I) {
665
666         CodeLabel* RefLab;
667         unsigned   J;
668
669         /* Get a pointer to the next entry */
670         CodeEntry* E = CollAt (&S->Entries, I);
671
672         /* If this entry has zero labels, continue with the next one */
673         unsigned LabelCount = CollCount (&E->Labels);
674         if (LabelCount == 0) {
675             continue;
676         }
677
678         /* We have at least one label. Use the first one as reference label. */
679         RefLab = CollAt (&E->Labels, 0);
680
681         /* Walk through the remaining labels and change references to these
682          * labels to a reference to the one and only label. Delete the labels
683          * that are no longer used. To increase performance, walk backwards
684          * through the list.
685          */
686         for (J = LabelCount-1; J >= 1; --J) {
687
688             unsigned K;
689
690             /* Get the next label */
691             CodeLabel* L = CollAt (&E->Labels, J);
692
693             /* Walk through all instructions referencing this label */
694             unsigned RefCount = CollCount (&L->JumpFrom);
695             for (K = 0; K < RefCount; ++K) {
696
697                 /* Get the next instruction that references this label */
698                 CodeEntry* E = CollAt (&L->JumpFrom, K);
699
700                 /* Change the reference */
701                 CHECK (E->JumpTo == L);
702                 AddLabelRef (RefLab, E);
703
704             }
705
706             /* There are no more instructions jumping to this label now */
707             CollDeleteAll (&L->JumpFrom);
708
709             /* Remove the label completely. */
710             DelCodeLabel (S, L);
711         }
712
713         /* The reference label is the only remaining label. Check if there
714          * are any references to this label, and delete it if this is not
715          * the case.
716          */
717         if (CollCount (&RefLab->JumpFrom) == 0) {
718             /* Delete the label */
719             DelCodeLabel (S, RefLab);
720         }
721     }
722 }
723
724
725
726 unsigned GetCodeSegEntries (const CodeSeg* S)
727 /* Return the number of entries for the given code segment */
728 {
729     return CollCount (&S->Entries);
730 }
731
732
733
734