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