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