]> 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 LabelCount = CollCount (&S->Labels);
394         unsigned I;
395         for (I = 0; I < LabelCount; ++I) {
396             CollAppend (&E->Labels, CollAt (&S->Labels, I));
397         }
398         CollDeleteAll (&S->Labels);
399
400         /* Add the entry to the list of code entries in this segment */
401         CollAppend (&S->Entries, E);
402
403     }
404 }
405
406
407
408 void AddCodeSegLabel (CodeSeg* S, const char* Name)
409 /* Add a label for the next instruction to follow */
410 {
411     /* Calculate the hash from the name */
412     unsigned Hash = HashStr (Name) % CS_LABEL_HASH_SIZE;
413
414     /* Try to find the code label if it does already exist */
415     CodeLabel* L = FindCodeLabel (S, Name, Hash);
416
417     /* Did we find it? */
418     if (L) {
419         /* We found it - be sure it does not already have an owner */
420         CHECK (L->Owner == 0);
421     } else {
422         /* Not found - create a new one */
423         L = NewCodeSegLabel (S, Name, Hash);
424     }
425
426     /* We do now have a valid label. Remember it for later */
427     CollAppend (&S->Labels, L);
428 }
429
430
431
432 void AddCodeSegHint (CodeSeg* S, unsigned Hint)
433 /* Add a hint for the preceeding instruction */
434 {
435     CodeEntry* E;
436
437     /* Get the number of entries in this segment */
438     unsigned EntryCount = CollCount (&S->Entries);
439
440     /* Must have at least one entry */
441     CHECK (EntryCount > 0);
442
443     /* Get the last entry */
444     E = CollAt (&S->Entries, EntryCount-1);
445
446     /* Add the hint */
447     E->Hints |= Hint;
448 }
449
450
451
452 void DelCodeSegAfter (CodeSeg* S, unsigned Last)
453 /* Delete all entries after the given one */
454 {
455     unsigned I;
456
457     /* Get the number of entries in this segment */
458     unsigned Count = CollCount (&S->Entries);
459
460     /* ### We need some more cleanup here wrt labels */
461
462     /* Remove all entries after the given one */
463     for (I = Count-1; I > Last; --I) {
464         FreeCodeEntry (CollAt (&S->Entries, I));
465         CollDelete (&S->Entries, I);
466     }
467
468     /* Delete all waiting labels */
469     CollDeleteAll (&S->Labels);
470 }
471
472
473
474 void OutputCodeSeg (FILE* F, const CodeSeg* S)
475 /* Output the code segment data to a file */
476 {
477     unsigned I;
478
479     /* Get the number of entries in this segment */
480     unsigned Count = CollCount (&S->Entries);
481
482     /* Output the segment directive */
483     fprintf (F, ".segment\t\"%s\"\n", S->Name);
484
485     /* Output all entries */
486     for (I = 0; I < Count; ++I) {
487         OutputCodeEntry (F, CollConstAt (&S->Entries, I));
488     }
489 }
490
491
492
493 CodeLabel* FindCodeLabel (CodeSeg* S, const char* Name, unsigned Hash)
494 /* Find the label with the given name. Return the label or NULL if not found */
495 {
496     /* Get the first hash chain entry */
497     CodeLabel* L = S->LabelHash[Hash];
498
499     /* Search the list */
500     while (L) {
501         if (strcmp (Name, L->Name) == 0) {
502             /* Found */
503             break;
504         }
505         L = L->Next;
506     }
507     return L;
508 }
509
510
511
512 void MergeCodeLabels (CodeSeg* S)
513 /* Merge code labels. That means: For each instruction, remove all labels but
514  * one and adjust the code entries accordingly.
515  */
516 {
517     unsigned I;
518
519     /* Walk over all code entries */
520     unsigned EntryCount = CollCount (&S->Entries);
521     for (I = 0; I < EntryCount; ++I) {
522
523         CodeLabel* RefLab;
524         unsigned   J;
525
526         /* Get a pointer to the next entry */
527         CodeEntry* E = CollAt (&S->Entries, I);
528
529         /* If this entry has zero labels, continue with the next one */
530         unsigned LabelCount = CollCount (&E->Labels);
531         if (LabelCount == 0) {
532             continue;
533         }
534
535         /* We have at least one label. Use the first one as reference label.
536          * We don't have a notification for global labels for now, and using
537          * the first one will also keep the global function labels, since these
538          * are inserted at position 0.
539          */
540         RefLab = CollAt (&E->Labels, 0);
541
542         /* Walk through the remaining labels and change references to these
543          * labels to a reference to the one and only label. Delete the labels
544          * that are no longer used. To increase performance, walk backwards
545          * through the list.
546          */
547         for (J = LabelCount-1; J >= 1; --J) {
548
549             unsigned K;
550
551             /* Get the next label */
552             CodeLabel* L = CollAt (&E->Labels, J);
553
554             /* Walk through all instructions referencing this label */
555             unsigned RefCount = CollCount (&L->JumpFrom);
556             for (K = 0; K < RefCount; ++K) {
557
558                 /* Get the next instrcuction that references this label */
559                 CodeEntry* E = CollAt (&L->JumpFrom, K);
560
561                 /* Change the reference */
562                 CHECK (E->JumpTo == L);
563                 E->JumpTo = RefLab;
564                 CollAppend (&RefLab->JumpFrom, E);
565
566             }
567
568             /* Delete the label */
569             FreeCodeLabel (L);
570
571             /* Remove it from the list */
572             CollDelete (&E->Labels, J);
573
574         }
575
576         /* The reference label is the only remaining label. Check if there
577          * are any references to this label, and delete it if this is not
578          * the case.
579          */
580         if (CollCount (&RefLab->JumpFrom) == 0) {
581             /* Delete the label */
582             FreeCodeLabel (RefLab);
583             /* Remove it from the list */
584             CollDelete (&E->Labels, 0);
585         }
586     }
587 }
588
589
590
591 unsigned GetCodeSegEntries (const CodeSeg* S)
592 /* Return the number of entries for the given code segment */
593 {
594     return CollCount (&S->Entries);
595 }
596
597
598
599