]> git.sur5r.net Git - cc65/blob - src/cc65/main.c
New --register-space option
[cc65] / src / cc65 / main.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                  main.c                                   */
4 /*                                                                           */
5 /*                             cc65 main program                             */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2000-2002 Ullrich von Bassewitz                                       */
10 /*               Wacholderweg 14                                             */
11 /*               D-70597 Stuttgart                                           */
12 /* EMail:        uz@cc65.org                                                 */
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 <stdio.h>
37 #include <string.h>
38 #include <stdlib.h>
39 #include <errno.h>
40
41 /* common */
42 #include "abend.h"
43 #include "chartype.h"
44 #include "cmdline.h"
45 #include "fname.h"
46 #include "print.h"
47 #include "target.h"
48 #include "tgttrans.h"
49 #include "version.h"
50 #include "xmalloc.h"
51
52 /* cc65 */
53 #include "asmcode.h"
54 #include "compile.h"
55 #include "codeopt.h"
56 #include "cpu.h"
57 #include "error.h"
58 #include "global.h"
59 #include "incpath.h"
60 #include "input.h"
61 #include "macrotab.h"
62 #include "scanner.h"
63 #include "segments.h"
64
65
66
67 /*****************************************************************************/
68 /*                                   Code                                    */
69 /*****************************************************************************/
70
71
72
73 static void Usage (void)
74 {
75     fprintf (stderr,
76              "Usage: %s [options] file\n"
77              "Short options:\n"
78              "  -A\t\t\tStrict ANSI mode\n"
79              "  -Cl\t\t\tMake local variables static\n"
80              "  -Dsym[=defn]\t\tDefine a symbol\n"
81              "  -I dir\t\tSet an include directory search path\n"
82              "  -O\t\t\tOptimize code\n"
83              "  -Oi\t\t\tOptimize code, inline more code\n"
84              "  -Or\t\t\tEnable register variables\n"
85              "  -Os\t\t\tInline some known functions\n"
86              "  -T\t\t\tInclude source as comment\n"
87              "  -V\t\t\tPrint the compiler version number\n"
88              "  -W\t\t\tSuppress warnings\n"
89              "  -d\t\t\tDebug mode\n"
90              "  -g\t\t\tAdd debug info to object file\n"
91              "  -h\t\t\tHelp (this text)\n"
92              "  -j\t\t\tDefault characters are signed\n"
93              "  -o name\t\tName the output file\n"
94              "  -r\t\t\tEnable register variables\n"
95              "  -t sys\t\tSet the target system\n"
96              "  -v\t\t\tIncrease verbosity\n"
97              "\n"
98              "Long options:\n"
99              "  --add-source\t\tInclude source as comment\n"
100              "  --ansi\t\tStrict ANSI mode\n"
101              "  --bss-name seg\tSet the name of the BSS segment\n"
102              "  --check-stack\t\tGenerate stack overflow checks\n"
103              "  --code-name seg\tSet the name of the CODE segment\n"
104              "  --codesize x\t\tAccept larger code by factor x\n"
105              "  --cpu type\t\tSet cpu type\n"
106              "  --create-dep\t\tCreate a make dependency file\n"
107              "  --data-name seg\tSet the name of the DATA segment\n"
108              "  --debug\t\tDebug mode\n"
109              "  --debug-info\t\tAdd debug info to object file\n"
110              "  --debug-opt name\tDebug optimization steps\n"
111              "  --disable-opt name\tDisable an optimization step\n"
112              "  --enable-opt name\tEnable an optimization step\n"
113              "  --help\t\tHelp (this text)\n"
114              "  --include-dir dir\tSet an include directory search path\n"
115              "  --list-opt-steps\tList all optimizer steps and exit\n"
116              "  --register-space b\tSet space available for register variables\n"
117              "  --register-vars\tEnable register variables\n"
118              "  --rodata-name seg\tSet the name of the RODATA segment\n"
119              "  --signed-chars\tDefault characters are signed\n"
120              "  --static-locals\tMake local variables static\n"
121              "  --target sys\t\tSet the target system\n"
122              "  --verbose\t\tIncrease verbosity\n"
123              "  --version\t\tPrint the compiler version number\n",
124              ProgName);
125 }
126
127
128
129 static void cbmsys (const char* sys)
130 /* Define a CBM system */
131 {
132     DefineNumericMacro ("__CBM__", 1);
133     DefineNumericMacro (sys, 1);
134 }
135
136
137
138 static void SetSys (const char* Sys)
139 /* Define a target system */
140 {
141     switch (Target = FindTarget (Sys)) {
142
143         case TGT_NONE:
144             break;
145
146         case TGT_MODULE:
147             AbEnd ("Cannot use `module' as a target for the compiler");
148             break;
149
150         case TGT_ATARI:
151             DefineNumericMacro ("__ATARI__", 1);
152             break;
153
154         case TGT_C16:
155             cbmsys ("__C16__");
156             break;
157
158         case TGT_C64:
159             cbmsys ("__C64__");
160             break;
161
162         case TGT_VIC20:
163             cbmsys ("__VIC20__");
164             break;
165
166         case TGT_C128:
167             cbmsys ("__C128__");
168             break;
169
170         case TGT_ACE:
171             cbmsys ("__ACE__");
172             break;
173
174         case TGT_PLUS4:
175             cbmsys ("__PLUS4__");
176             break;
177
178         case TGT_CBM510:
179             cbmsys ("__CBM510__");
180             break;
181
182         case TGT_CBM610:
183             cbmsys ("__CBM610__");
184             break;
185
186         case TGT_PET:
187             cbmsys ("__PET__");
188             break;
189
190         case TGT_BBC:
191             DefineNumericMacro ("__BBC__", 1);
192             break;
193
194         case TGT_APPLE2:
195             DefineNumericMacro ("__APPLE2__", 1);
196             break;
197
198         case TGT_GEOS:
199             /* Do not handle as a CBM system */
200             DefineNumericMacro ("__GEOS__", 1);
201             break;
202
203         case TGT_LUNIX:
204             DefineNumericMacro ("__LUNIX__", 1);
205             break;
206
207         case TGT_ATMOS:
208             DefineNumericMacro ("__ATMOS__", 1);
209             break;
210
211         default:
212             AbEnd ("Unknown target system type");
213     }
214
215     /* Initialize the translation tables for the target system */
216     TgtTranslateInit ();
217 }
218
219
220
221 static void DoCreateDep (const char* OutputName)
222 /* Create the dependency file */
223 {
224     /* Make the dependency file name from the output file name */
225     char* DepName = MakeFilename (OutputName, ".u");
226
227     /* Open the file */
228     FILE* F = fopen (DepName, "w");
229     if (F == 0) {
230         Fatal ("Cannot open dependency file `%s': %s", DepName, strerror (errno));
231     }
232
233     /* Write the dependencies to the file */
234     WriteDependencies (F, OutputName);
235
236     /* Close the file, check for errors */
237     if (fclose (F) != 0) {
238         remove (DepName);
239         Fatal ("Cannot write to dependeny file (disk full?)");
240     }
241
242     /* Free the name */
243     xfree (DepName);
244 }
245
246
247
248 static void DefineSym (const char* Def)
249 /* Define a symbol on the command line */
250 {
251     const char* P = Def;
252
253     /* The symbol must start with a character or underline */
254     if (Def [0] != '_' && !IsAlpha (Def [0])) {
255         InvDef (Def);
256     }
257
258     /* Check the symbol name */
259     while (IsAlNum (*P) || *P == '_') {
260         ++P;
261     }
262
263     /* Do we have a value given? */
264     if (*P != '=') {
265         if (*P != '\0') {
266             InvDef (Def);
267         }
268         /* No value given. Define the macro with the value 1 */
269         DefineNumericMacro (Def, 1);
270     } else {
271         /* We have a value, P points to the '=' character. Since the argument
272          * is const, create a copy and replace the '=' in the copy by a zero
273          * terminator.
274          */
275         char* Q;
276         unsigned Len = strlen (Def)+1;
277         char* S = (char*) xmalloc (Len);
278         memcpy (S, Def, Len);
279         Q = S + (P - Def);
280         *Q++ = '\0';
281
282         /* Define this as a macro */
283         DefineTextMacro (S, Q);
284
285         /* Release the allocated memory */
286         xfree (S);
287     }
288 }
289
290
291
292 static void CheckSegName (const char* Seg)
293 /* Abort if the given name is not a valid segment name */
294 {
295     /* Print an error and abort if the name is not ok */
296     if (!ValidSegName (Seg)) {
297         AbEnd ("Segment name `%s' is invalid", Seg);
298     }
299 }
300
301
302
303 static void OptAddSource (const char* Opt attribute ((unused)),
304                           const char* Arg attribute ((unused)))
305 /* Add source lines as comments in generated assembler file */
306 {
307     AddSource = 1;
308 }
309
310
311
312 static void OptAnsi (const char* Opt attribute ((unused)),
313                      const char* Arg attribute ((unused)))
314 /* Compile in strict ANSI mode */
315 {
316     ANSI = 1;
317 }
318
319
320
321 static void OptBssName (const char* Opt attribute ((unused)), const char* Arg)
322 /* Handle the --bss-name option */
323 {
324     /* Check for a valid name */
325     CheckSegName (Arg);
326
327     /* Set the name */
328     NewSegName (SEG_BSS, Arg);
329 }
330
331
332
333 static void OptCheckStack (const char* Opt attribute ((unused)),
334                            const char* Arg attribute ((unused)))
335 /* Handle the --check-stack option */
336 {
337     CheckStack = 1;
338 }
339
340
341
342 static void OptCodeName (const char* Opt attribute ((unused)), const char* Arg)
343 /* Handle the --code-name option */
344 {
345     /* Check for a valid name */
346     CheckSegName (Arg);
347
348     /* Set the name */
349     NewSegName (SEG_CODE, Arg);
350 }
351
352
353
354 static void OptCodeSize (const char* Opt, const char* Arg)
355 /* Handle the --codesize option */
356 {
357     /* Numeric argument expected */
358     if (sscanf (Arg, "%u", &CodeSizeFactor) != 1 ||
359         CodeSizeFactor < 100 ||
360         CodeSizeFactor > 1000) {
361         AbEnd ("Argument for %s is invalid", Opt);
362     }
363 }
364
365
366
367 static void OptCreateDep (const char* Opt attribute ((unused)),
368                           const char* Arg attribute ((unused)))
369 /* Handle the --create-dep option */
370 {
371     CreateDep = 1;
372 }
373
374
375
376 static void OptCPU (const char* Opt, const char* Arg)
377 /* Handle the --cpu option */
378 {
379     if (strcmp (Arg, "6502") == 0) {
380         CPU = CPU_6502;
381     } else if (strcmp (Arg, "65C02") == 0) {
382         CPU = CPU_65C02;
383     } else {
384         AbEnd ("Invalid argument for %s: `%s'", Opt, Arg);
385     }
386 }
387
388
389
390 static void OptDataName (const char* Opt attribute ((unused)), const char* Arg)
391 /* Handle the --data-name option */
392 {
393     /* Check for a valid name */
394     CheckSegName (Arg);
395
396     /* Set the name */
397     NewSegName (SEG_DATA, Arg);
398 }
399
400
401
402 static void OptDebug (const char* Opt attribute ((unused)),
403                       const char* Arg attribute ((unused)))
404 /* Compiler debug mode */
405 {
406     Debug = 1;
407 }
408
409
410
411 static void OptDebugInfo (const char* Opt attribute ((unused)),
412                           const char* Arg attribute ((unused)))
413 /* Add debug info to the object file */
414 {
415     DebugInfo = 1;
416 }
417
418
419
420 static void OptDebugOpt (const char* Opt attribute ((unused)), const char* Arg)
421 /* Debug optimization steps */
422 {
423     char Buf [128];
424     char* Line;
425
426     /* Open the file */
427     FILE* F = fopen (Arg, "r");
428     if (F == 0) {
429         AbEnd ("Cannot open `%s': %s", Arg, strerror (errno));
430     }
431
432     /* Read line by line, ignore empty lines and switch optimization
433      * steps on/off.
434      */
435     while (fgets (Buf, sizeof (Buf), F) != 0) {
436
437         /* Remove trailing control chars. This will also remove the
438          * trailing newline.
439          */
440         unsigned Len = strlen (Buf);
441         while (Len > 0 && IsControl (Buf[Len-1])) {
442             --Len;
443         }
444         Buf[Len] = '\0';
445
446         /* Get a pointer to the buffer and remove leading white space */
447         Line = Buf;
448         while (IsBlank (*Line)) {
449             ++Line;
450         }
451
452         /* Check the first character and enable/disable the step or
453          * ignore the line
454          */
455         switch (*Line) {
456
457             case '\0':
458             case '#':
459             case ';':
460                 /* Empty or comment line */
461                 continue;
462
463             case '-':
464                 DisableOpt (Line+1);
465                 break;
466
467             case '+':
468                 ++Line;
469                 /* FALLTHROUGH */
470
471             default:
472                 EnableOpt (Line);
473                 break;
474
475         }
476
477     }
478
479     /* Close the file, no error check here since we were just reading and
480      * this is only a debug function.
481      */
482     (void) fclose (F);
483 }
484
485
486
487 static void OptDisableOpt (const char* Opt attribute ((unused)), const char* Arg)
488 /* Disable an optimization step */
489 {
490     DisableOpt (Arg);
491 }
492
493
494
495 static void OptEnableOpt (const char* Opt attribute ((unused)), const char* Arg)
496 /* Enable an optimization step */
497 {
498     EnableOpt (Arg);
499 }
500
501
502
503 static void OptHelp (const char* Opt attribute ((unused)),
504                      const char* Arg attribute ((unused)))
505 /* Print usage information and exit */
506 {
507     Usage ();
508     exit (EXIT_SUCCESS);
509 }
510
511
512
513 static void OptIncludeDir (const char* Opt attribute ((unused)), const char* Arg)
514 /* Add an include search path */
515 {
516     AddIncludePath (Arg, INC_SYS | INC_USER);
517 }
518
519
520
521 static void OptListOptSteps (const char* Opt attribute ((unused)),
522                              const char* Arg attribute ((unused)))
523 /* List all optimizer steps */
524 {
525     /* List the optimizer steps */
526     ListOptSteps (stdout);
527
528     /* Terminate */
529     exit (EXIT_SUCCESS);
530 }
531
532
533
534 static void OptRegisterSpace (const char* Opt, const char* Arg)
535 /* Handle the --register-space option */
536 {
537     /* Numeric argument expected */
538     if (sscanf (Arg, "%u", &RegisterSpace) != 1 || RegisterSpace > 256) {
539         AbEnd ("Argument for option %s is invalid", Opt);
540     }
541 }
542
543
544
545 static void OptRegisterVars (const char* Opt attribute ((unused)),
546                              const char* Arg attribute ((unused)))
547 /* Handle the --register-vars option */
548 {
549     EnableRegVars = 1;
550 }
551
552
553
554 static void OptRodataName (const char* Opt attribute ((unused)), const char* Arg)
555 /* Handle the --rodata-name option */
556 {
557     /* Check for a valid name */
558     CheckSegName (Arg);
559
560     /* Set the name */
561     NewSegName (SEG_RODATA, Arg);
562 }
563
564
565
566 static void OptSignedChars (const char* Opt attribute ((unused)),
567                             const char* Arg attribute ((unused)))
568 /* Make default characters signed */
569 {
570     SignedChars = 1;
571 }
572
573
574
575 static void OptStaticLocals (const char* Opt attribute ((unused)),
576                              const char* Arg attribute ((unused)))
577 /* Place local variables in static storage */
578 {
579     StaticLocals = 1;
580 }
581
582
583
584 static void OptTarget (const char* Opt attribute ((unused)), const char* Arg)
585 /* Set the target system */
586 {
587     SetSys (Arg);
588 }
589
590
591
592 static void OptVerbose (const char* Opt attribute ((unused)),
593                         const char* Arg attribute ((unused)))
594 /* Increase verbosity */
595 {
596     ++Verbosity;
597 }
598
599
600
601 static void OptVersion (const char* Opt attribute ((unused)),
602                         const char* Arg attribute ((unused)))
603 /* Print the assembler version */
604 {
605     fprintf (stderr,
606              "cc65 V%u.%u.%u\n",
607              VER_MAJOR, VER_MINOR, VER_PATCH);
608 }
609
610
611
612 int main (int argc, char* argv[])
613 {
614     /* Program long options */
615     static const LongOpt OptTab[] = {
616         { "--add-source",       0,      OptAddSource            },
617         { "--ansi",             0,      OptAnsi                 },
618         { "--bss-name",         1,      OptBssName              },
619         { "--check-stack",      0,      OptCheckStack           },
620         { "--code-name",        1,      OptCodeName             },
621         { "--codesize",         1,      OptCodeSize             },
622         { "--cpu",              1,      OptCPU                  },
623         { "--create-dep",       0,      OptCreateDep            },
624         { "--data-name",        1,      OptDataName             },
625         { "--debug",            0,      OptDebug                },
626         { "--debug-info",       0,      OptDebugInfo            },
627         { "--debug-opt",        1,      OptDebugOpt             },
628         { "--disable-opt",      1,      OptDisableOpt           },
629         { "--enable-opt",       1,      OptEnableOpt,           },
630         { "--help",             0,      OptHelp                 },
631         { "--include-dir",      1,      OptIncludeDir           },
632         { "--list-opt-steps",   0,      OptListOptSteps         },
633         { "--register-space",   1,      OptRegisterSpace        },
634         { "--register-vars",    0,      OptRegisterVars         },
635         { "--rodata-name",      1,      OptRodataName           },
636         { "--signed-chars",     0,      OptSignedChars          },
637         { "--static-locals",    0,      OptStaticLocals         },
638         { "--target",           1,      OptTarget               },
639         { "--verbose",          0,      OptVerbose              },
640         { "--version",          0,      OptVersion              },
641     };
642
643     unsigned I;
644
645     /* Initialize the output file name */
646     const char* OutputFile = 0;
647     const char* InputFile  = 0;
648
649     /* Initialize the cmdline module */
650     InitCmdLine (&argc, &argv, "cc65");
651
652     /* Initialize the default segment names */
653     InitSegNames ();
654
655     /* Parse the command line */
656     I = 1;
657     while (I < ArgCount) {
658
659         const char* P;
660
661         /* Get the argument */
662         const char* Arg = ArgVec[I];
663
664         /* Check for an option */
665         if (Arg [0] == '-') {
666
667             switch (Arg [1]) {
668
669                 case '-':
670                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
671                     break;
672
673                 case 'd':
674                     OptDebug (Arg, 0);
675                     break;
676
677                 case 'h':
678                 case '?':
679                     OptHelp (Arg, 0);
680                     break;
681
682                 case 'g':
683                     OptDebugInfo (Arg, 0);
684                     break;
685
686                 case 'j':
687                     OptSignedChars (Arg, 0);
688                     break;
689
690                 case 'o':
691                     OutputFile = GetArg (&I, 2);
692                     break;
693
694                 case 'r':
695                     OptRegisterVars (Arg, 0);
696                     break;
697
698                 case 't':
699                     OptTarget (Arg, GetArg (&I, 2));
700                     break;
701
702                 case 'u':
703                     OptCreateDep (Arg, 0);
704                     break;
705
706                 case 'v':
707                     OptVerbose (Arg, 0);
708                     break;
709
710                 case 'A':
711                     OptAnsi (Arg, 0);
712                     break;
713
714                 case 'C':
715                     P = Arg + 2;
716                     while (*P) {
717                         switch (*P++) {
718                             case 'l':
719                                 OptStaticLocals (Arg, 0);
720                                 break;
721                             default:
722                                 UnknownOption (Arg);
723                                 break;
724                         }
725                     }
726                     break;
727
728                 case 'D':
729                     DefineSym (GetArg (&I, 2));
730                     break;
731
732                 case 'I':
733                     OptIncludeDir (Arg, GetArg (&I, 2));
734                     break;
735
736                 case 'O':
737                     Optimize = 1;
738                     P = Arg + 2;
739                     while (*P) {
740                         switch (*P++) {
741                             case 'f':
742                                 sscanf (P, "%lx", (long*) &OptDisable);
743                                 break;
744                             case 'i':
745                                 FavourSize = 0;
746                                 CodeSizeFactor = 200;
747                                 break;
748                             case 'r':
749                                 EnableRegVars = 1;
750                                 break;
751                             case 's':
752                                 InlineStdFuncs = 1;
753                                 break;
754                         }
755                     }
756                     break;
757
758                 case 'T':
759                     OptAddSource (Arg, 0);
760                     break;
761
762                 case 'V':
763                     OptVersion (Arg, 0);
764                     break;
765
766                 case 'W':
767                     NoWarn = 1;
768                     break;
769
770                 default:
771                     UnknownOption (Arg);
772                     break;
773             }
774         } else {
775             if (InputFile) {
776                 fprintf (stderr, "additional file specs ignored\n");
777             } else {
778                 InputFile = Arg;
779             }
780         }
781
782         /* Next argument */
783         ++I;
784     }
785
786     /* Did we have a file spec on the command line? */
787     if (InputFile == 0) {
788         AbEnd ("No input files");
789     }
790
791     /* Create the output file name if it was not explicitly given */
792     if (OutputFile == 0) {
793         OutputFile = MakeFilename (InputFile, ".s");
794     }
795
796     /* Go! */
797     Compile (InputFile);
798
799     /* Create the output file if we didn't had any errors */
800     if (ErrorCount == 0 || Debug) {
801
802         FILE* F;
803
804 #if 0
805         /* Optimize the output if requested */
806         if (Optimize) {
807             OptDoOpt ();
808         }
809 #endif
810
811         /* Open the file */
812         F = fopen (OutputFile, "w");
813         if (F == 0) {
814             Fatal ("Cannot open output file `%s': %s", OutputFile, strerror (errno));
815         }
816
817         /* Write the output to the file */
818         WriteOutput (F);
819
820         /* Close the file, check for errors */
821         if (fclose (F) != 0) {
822             remove (OutputFile);
823             Fatal ("Cannot write to output file (disk full?)");
824         }
825
826         /* Create dependencies if requested */
827         if (CreateDep) {
828             DoCreateDep (OutputFile);
829         }
830
831     }
832
833     /* Return an apropriate exit code */
834     return (ErrorCount > 0)? EXIT_FAILURE : EXIT_SUCCESS;
835 }
836
837
838