]> 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                Expr[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     Expr[0] = '\0';
164     switch (*L) {
165
166         case '\0':
167             /* Implicit */
168             AM = AM_IMP;
169             break;
170
171         case '#':
172             /* Immidiate */
173             StrCopy (Expr, sizeof (Expr), L+1);
174             AM = AM_IMM;
175             break;
176
177         case '(':
178             /* Indirect */
179             L = ReadToken (L+1, ",)", Expr, sizeof (Expr));
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, ",", Expr, sizeof (Expr));
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.
274      */
275     Label = 0;
276     if ((OPC->Info & CI_MASK_BRA) == CI_BRA) {
277
278         unsigned Hash;
279
280         /* ### Check for local labels here */
281         CHECK (AM == AM_ABS);
282         AM = AM_BRA;
283         Hash = HashStr (Expr) % CS_LABEL_HASH_SIZE;
284         Label = FindCodeLabel (S, Expr, Hash);
285         if (Label == 0) {
286             /* Generate a new label */
287             Label = NewCodeSegLabel (S, Expr, Hash);
288         }
289     }
290
291     /* We do now have the addressing mode in AM. Allocate a new CodeEntry
292      * structure and initialize it.
293      */
294     E = NewCodeEntry (OPC, AM, Label);
295     if (Expr[0] != '\0') {
296         /* We have an additional expression */
297         E->Arg.Expr = xstrdup (Expr);
298     }
299
300     /* Return the new code entry */
301     return E;
302 }
303
304
305
306 /*****************************************************************************/
307 /*                                   Code                                    */
308 /*****************************************************************************/
309
310
311
312 CodeSeg* NewCodeSeg (const char* Name)
313 /* Create a new code segment, initialize and return it */
314 {
315     unsigned I;
316
317     /* Allocate memory */
318     CodeSeg* S = xmalloc (sizeof (CodeSeg));
319
320     /* Initialize the fields */
321     S->Next = 0;
322     S->Name = xstrdup (Name);
323     InitCollection (&S->Entries);
324     InitCollection (&S->Labels);
325     for (I = 0; I < sizeof(S->LabelHash) / sizeof(S->LabelHash[0]); ++I) {
326         S->LabelHash[I] = 0;
327     }
328
329     /* Return the new struct */
330     return S;
331 }
332
333
334
335 void FreeCodeSeg (CodeSeg* S)
336 /* Free a code segment including all code entries */
337 {
338     unsigned I, Count;
339
340     /* Free the name */
341     xfree (S->Name);
342
343     /* Free the entries */
344     Count = CollCount (&S->Entries);
345     for (I = 0; I < Count; ++I) {
346         FreeCodeEntry (CollAt (&S->Entries, I));
347     }
348
349     /* Free the collections */
350     DoneCollection (&S->Entries);
351     DoneCollection (&S->Labels);
352
353     /* Free all labels */
354     for (I = 0; I < sizeof(S->LabelHash) / sizeof(S->LabelHash[0]); ++I) {
355         CodeLabel* L = S->LabelHash[I];
356         while (L) {
357             CodeLabel* Tmp = L;
358             L = L->Next;
359             FreeCodeLabel (Tmp);
360         }
361     }
362
363     /* Free the struct */
364     xfree (S);
365 }
366
367
368
369 void PushCodeSeg (CodeSeg* S)
370 /* Push the given code segment onto the stack */
371 {
372     S->Next = CS;
373     CS      = S;
374 }
375
376
377
378 CodeSeg* PopCodeSeg (void)
379 /* Remove the current code segment from the stack and return it */
380 {
381     /* Remember the current code segment */
382     CodeSeg* S = CS;
383
384     /* Cannot pop on empty stack */
385     PRECONDITION (S != 0);
386
387     /* Pop */
388     CS = S->Next;
389
390     /* Return the popped code segment */
391     return S;
392 }
393
394
395
396 void AddCodeSegLine (CodeSeg* S, const char* Format, ...)
397 /* Add a line to the given code segment */
398 {
399     const char* L;
400     CodeEntry*  E;
401     char        Token[64];
402
403     /* Format the line */
404     va_list ap;
405     char Buf [256];
406     va_start (ap, Format);
407     xvsprintf (Buf, sizeof (Buf), Format, ap);
408     va_end (ap);
409
410     /* Skip whitespace */
411     L = SkipSpace (Buf);
412
413     /* Check which type of instruction we have */
414     E = 0;      /* Assume no insn created */
415     switch (*L) {
416
417         case '\0':
418             /* Empty line, just ignore it */
419             break;
420
421         case ';':
422             /* Comment or hint, ignore it for now */
423             break;
424
425         case '.':
426             /* Control instruction */
427             ReadToken (L, " \t", Token, sizeof (Token));
428             Error ("ASM code error: Pseudo instruction `%s' not supported", Token);
429             break;
430
431         default:
432             E = ParseInsn (S, L);
433             break;
434     }
435
436     /* If we have a code entry, transfer the labels and insert it */
437     if (E) {
438
439         /* Transfer the labels if we have any */
440         unsigned I;
441         unsigned LabelCount = CollCount (&S->Labels);
442         for (I = 0; I < LabelCount; ++I) {
443             /* Get the label */
444             CodeLabel* L = CollAt (&S->Labels, I);
445             /* Mark it as defined */
446             L->Flags |= LF_DEF;
447             /* Move it to the code entry */
448             CollAppend (&E->Labels, L);
449         }
450
451         /* Delete the transfered labels */
452         CollDeleteAll (&S->Labels);
453
454         /* Add the entry to the list of code entries in this segment */
455         CollAppend (&S->Entries, E);
456
457     }
458 }
459
460
461
462 CodeLabel* AddCodeLabel (CodeSeg* S, const char* Name)
463 /* Add a code label for the next instruction to follow */
464 {
465     /* Calculate the hash from the name */
466     unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
467
468     /* Try to find the code label if it does already exist */
469     CodeLabel* L = FindCodeLabel (S, Name, Hash);
470
471     /* Did we find it? */
472     if (L) {
473         /* We found it - be sure it does not already have an owner */
474         CHECK (L->Owner == 0);
475     } else {
476         /* Not found - create a new one */
477         L = NewCodeSegLabel (S, Name, Hash);
478     }
479
480     /* We do now have a valid label. Remember it for later */
481     CollAppend (&S->Labels, L);
482
483     /* Return the label */
484     return L;
485 }
486
487
488
489 void AddExtCodeLabel (CodeSeg* S, const char* Name)
490 /* Add an external code label for the next instruction to follow */
491 {
492     /* Add the code label */
493     CodeLabel* L = AddCodeLabel (S, Name);
494
495     /* Mark it as external label */
496     L->Flags |= LF_EXT;
497 }
498
499
500
501 void AddLocCodeLabel (CodeSeg* S, const char* Name)
502 /* Add a local code label for the next instruction to follow */
503 {
504     /* Add the code label */
505     AddCodeLabel (S, Name);
506 }
507
508
509
510 void AddCodeSegHint (CodeSeg* S, unsigned Hint)
511 /* Add a hint for the preceeding instruction */
512 {
513     CodeEntry* E;
514
515     /* Get the number of entries in this segment */
516     unsigned EntryCount = CollCount (&S->Entries);
517
518     /* Must have at least one entry */
519     CHECK (EntryCount > 0);
520
521     /* Get the last entry */
522     E = CollAt (&S->Entries, EntryCount-1);
523
524     /* Add the hint */
525     E->Hints |= Hint;
526 }
527
528
529
530 void DelCodeSegAfter (CodeSeg* S, unsigned Last)
531 /* Delete all entries including the given one */
532 {
533     /* Get the number of entries in this segment */
534     unsigned Count = CollCount (&S->Entries);
535
536     /* Remove all entries after the given one */
537     while (Last < Count) {
538
539         /* Get the next entry */
540         CodeEntry* E = CollAt (&S->Entries, Count-1);
541
542         /* We have to transfer all labels to the code segment label pool */
543         unsigned LabelCount = CollCount (&E->Labels);
544         while (LabelCount--) {
545             CodeLabel* L = CollAt (&E->Labels, LabelCount);
546             L->Flags &= ~LF_DEF;
547             CollAppend (&S->Labels, L);
548         }
549         CollDeleteAll (&E->Labels);
550
551         /* Remove the code entry */
552         FreeCodeEntry (CollAt (&S->Entries, Count-1));
553         CollDelete (&S->Entries, Count-1);
554         --Count;
555     }
556 }
557
558
559
560 void OutputCodeSeg (FILE* F, const CodeSeg* S)
561 /* Output the code segment data to a file */
562 {
563     unsigned I;
564
565     /* Get the number of entries in this segment */
566     unsigned Count = CollCount (&S->Entries);
567
568     /* Output the segment directive */
569     fprintf (F, ".segment\t\"%s\"\n", S->Name);
570
571     /* Output all entries */
572     for (I = 0; I < Count; ++I) {
573         OutputCodeEntry (F, CollConstAt (&S->Entries, I));
574     }
575 }
576
577
578
579 CodeLabel* FindCodeLabel (CodeSeg* S, const char* Name, unsigned Hash)
580 /* Find the label with the given name. Return the label or NULL if not found */
581 {
582     /* Get the first hash chain entry */
583     CodeLabel* L = S->LabelHash[Hash];
584
585     /* Search the list */
586     while (L) {
587         if (strcmp (Name, L->Name) == 0) {
588             /* Found */
589             break;
590         }
591         L = L->Next;
592     }
593     return L;
594 }
595
596
597
598 void MergeCodeLabels (CodeSeg* S)
599 /* Merge code labels. That means: For each instruction, remove all labels but
600  * one and adjust the code entries accordingly.
601  */
602 {
603     unsigned I;
604
605     /* Walk over all code entries */
606     unsigned EntryCount = CollCount (&S->Entries);
607     for (I = 0; I < EntryCount; ++I) {
608
609         CodeLabel* RefLab;
610         unsigned   J;
611
612         /* Get a pointer to the next entry */
613         CodeEntry* E = CollAt (&S->Entries, I);
614
615         /* If this entry has zero labels, continue with the next one */
616         unsigned LabelCount = CollCount (&E->Labels);
617         if (LabelCount == 0) {
618             continue;
619         }
620
621         /* We have at least one label. Use the first one as reference label.
622          * We don't have a notification for global labels for now, and using
623          * the first one will also keep the global function labels, since these
624          * are inserted at position 0.
625          */
626         RefLab = CollAt (&E->Labels, 0);
627
628         /* Walk through the remaining labels and change references to these
629          * labels to a reference to the one and only label. Delete the labels
630          * that are no longer used. To increase performance, walk backwards
631          * through the list.
632          */
633         for (J = LabelCount-1; J >= 1; --J) {
634
635             unsigned K;
636
637             /* Get the next label */
638             CodeLabel* L = CollAt (&E->Labels, J);
639
640             /* Walk through all instructions referencing this label */
641             unsigned RefCount = CollCount (&L->JumpFrom);
642             for (K = 0; K < RefCount; ++K) {
643
644                 /* Get the next instrcuction that references this label */
645                 CodeEntry* E = CollAt (&L->JumpFrom, K);
646
647                 /* Change the reference */
648                 CHECK (E->JumpTo == L);
649                 E->JumpTo = RefLab;
650                 CollAppend (&RefLab->JumpFrom, E);
651
652             }
653
654             /* If the label is not an external label, we may remove the
655              * label completely.
656              */
657 #if 0
658             if ((L->Flags & LF_EXT) == 0) {
659                 FreeCodeLabel (L);
660                 CollDelete (&E->Labels, J);
661             }
662 #endif
663         }
664
665         /* The reference label is the only remaining label. If it is not an
666          * external label, check if there are any references to this label,
667          * and delete it if this is not the case.
668          */
669 #if 0
670         if ((RefLab->Flags & LF_EXT) == 0 && CollCount (&RefLab->JumpFrom) == 0) {
671             /* Delete the label */
672             FreeCodeLabel (RefLab);
673             /* Remove it from the list */
674             CollDelete (&E->Labels, 0);
675         }
676 #endif
677     }
678 }
679
680
681
682 unsigned GetCodeSegEntries (const CodeSeg* S)
683 /* Return the number of entries for the given code segment */
684 {
685     return CollCount (&S->Entries);
686 }
687
688
689
690