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