* src/pic16/main.c (_pic16_linkEdit): prepend -L paths to linker
[fw/sdcc] / src / pic16 / main.c
1 /*-------------------------------------------------------------------------
2
3   main.c - pic16 specific general functions.
4
5    Written by - Scott Dattalo scott@dattalo.com
6    Ported to PIC16 by - Martin Dubuc m.debuc@rogers.com
7
8    Note that mlh prepended _pic16_ on the static functions.  Makes
9    it easier to set a breakpoint using the debugger.
10
11
12    This program is free software; you can redistribute it and/or modify it
13    under the terms of the GNU General Public License as published by the
14    Free Software Foundation; either version 2, or (at your option) any
15    later version.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20    GNU General Public License for more details.
21
22    You should have received a copy of the GNU General Public License
23    along with this program; if not, write to the Free Software
24    Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25 -------------------------------------------------------------------------*/
26
27 #include "common.h"
28 #include "main.h"
29 #include "ralloc.h"
30 #include "device.h"
31 #include "SDCCutil.h"
32 #include "glue.h"
33 #include "pcode.h"
34 #include "SDCCargs.h"
35 #include "dbuf_string.h"
36
37
38 static char _defaultRules[] =
39 {
40 #include "peeph.rul"
41 };
42
43 /* list of key words used by pic16 */
44 static char *_pic16_keywords[] =
45 {
46   "at",
47   "code",
48   "critical",
49   "register",
50   "data",
51   "far",
52   "interrupt",
53   "near",
54   //"pdata",
55   "reentrant",
56   "sfr",
57   "sfr16",
58   "using",
59   "_data",
60   "_code",
61   "_generic",
62   "_near",
63   //"_pdata",
64   "_naked",
65   "shadowregs",
66   "wparam",
67   "prodlp",
68   "prodhp",
69   "fsr0lp",
70   "fixed16x16",
71
72 //  "bit",
73 //  "idata",
74 //  "sbit",
75 //  "xdata",
76 //  "_xdata",
77 //  "_idata",
78   NULL
79 };
80
81
82 pic16_sectioninfo_t pic16_sectioninfo;
83
84 extern char *pic16_processor_base_name(void);
85
86 void  pic16_pCodeInitRegisters(void);
87
88 void pic16_assignRegisters (ebbIndex *);
89
90 static int regParmFlg = 0;  /* determine if we can register a parameter */
91
92 pic16_options_t pic16_options;
93
94 extern set *includeDirsSet;
95 extern set *dataDirsSet;
96 extern set *libFilesSet;
97
98 /* Also defined in gen.h, but the #include is commented out */
99 /* for an unknowned reason. - EEP */
100 void pic16_emitDebuggerSymbol (char *);
101
102 extern void pic16_emitConfigRegs(FILE *of);
103 extern void pic16_emitIDRegs(FILE *of);
104
105
106
107 static void
108 _pic16_init (void)
109 {
110   asm_addTree (&asm_asxxxx_mapping);
111   pic16_pCodeInitRegisters();
112   maxInterrupts = 2;
113 }
114
115 static void
116 _pic16_reset_regparm (void)
117 {
118   regParmFlg = 0;
119 }
120
121 static int
122 _pic16_regparm (sym_link * l, bool reentrant)
123 {
124   /* force all parameters via SEND/RECEIVE */
125   if(0 /*pic16_options.ip_stack*/) {
126     /* for this processor it is simple
127      * can pass only the first parameter in a register */
128     if(regParmFlg)return 0;
129       regParmFlg++;
130       return 1; //regParmFlg;
131   } else {
132     /* otherwise pass all arguments in registers via SEND/RECEIVE */
133     regParmFlg++;// = 1;
134     return regParmFlg;
135   }
136 }
137
138
139 int initsfpnt=0;        /* set to 1 if source provides a pragma for stack
140                  * so glue() later emits code to initialize stack/frame pointers */
141 set *absSymSet;
142
143 set *sectNames=NULL;            /* list of section listed in pragma directives */
144 set *sectSyms=NULL;         /* list of symbols set in a specific section */
145 set *wparamList=NULL;
146
147 #if 0
148 /* This is an experimental code for #pragma inline
149    and is temporarily disabled for 2.5.0 release */
150 set *asmInlineMap=NULL;
151 #endif  /* 0 */
152
153 struct {
154   unsigned ignore: 1;
155   unsigned want_libc: 1;
156   unsigned want_libm: 1;
157   unsigned want_libio: 1;
158   unsigned want_libdebug: 1;
159 } libflags = { 0, 0, 0, 0, 0 };
160
161
162 enum {
163   P_STACK = 1,
164   P_CODE,
165   P_UDATA,
166   P_LIBRARY
167 };
168
169 static int
170 do_pragma(int id, const char *name, const char *cp)
171 {
172   struct pragma_token_s token;
173   int err = 0;
174   int processed = 1;
175
176   init_pragma_token(&token);
177
178   switch (id)
179     {
180     /* #pragma stack [stack-position] [stack-len] */
181     case  P_STACK:
182       {
183         unsigned int stackPos, stackLen;
184         regs *reg;
185         symbol *sym;
186
187         cp = get_pragma_token(cp, &token);
188         if (TOKEN_INT != token.type)
189           {
190             err = 1;
191             break;
192           }
193         stackPos = token.val.int_val;
194
195         cp = get_pragma_token(cp, &token);
196         if (TOKEN_INT != token.type)
197           {
198             err = 1;
199             break;
200           }
201         stackLen = token.val.int_val;
202
203         cp = get_pragma_token(cp, &token);
204         if (TOKEN_EOL != token.type)
205           {
206             err = 1;
207             break;
208           }
209
210         if (stackLen < 1) {
211           stackLen = 64;
212           fprintf(stderr, "%s:%d: warning: setting stack to default size %d (0x%04x)\n",
213                   filename, lineno, stackLen, stackLen);
214         }
215
216         /* check sanity of stack */
217         if ((stackPos >> 8) != ((stackPos + stackLen - 1) >> 8)) {
218           fprintf (stderr, "%s:%u: warning: stack [0x%03X,0x%03X] crosses memory bank boundaries (not fully tested)\n",
219                   filename, lineno, stackPos, stackPos + stackLen - 1);
220         }
221
222         if (pic16) {
223           if (stackPos < pic16->acsSplitOfs) {
224             fprintf (stderr, "%s:%u: warning: stack [0x%03X, 0x%03X] intersects with the access bank [0x000,0x%03x] -- this is highly discouraged!\n",
225                   filename, lineno, stackPos, stackPos + stackLen - 1, pic16->acsSplitOfs);
226           }
227
228           if (stackPos+stackLen > 0xF00 + pic16->acsSplitOfs) {
229             fprintf (stderr, "%s:%u: warning: stack [0x%03X,0x%03X] intersects with special function registers [0x%03X,0xFFF]-- this is highly discouraged!\n",
230                    filename, lineno, stackPos, stackPos + stackLen - 1, 0xF00 + pic16->acsSplitOfs);
231           }
232
233           if (stackPos+stackLen > pic16->RAMsize) {
234             fprintf (stderr, "%s:%u: error: stack [0x%03X,0x%03X] is placed outside available memory [0x000,0x%03X]!\n",
235                   filename, lineno, stackPos, stackPos + stackLen - 1, pic16->RAMsize-1);
236             err = 1;
237             break;
238           }
239         }
240
241         reg = newReg(REG_SFR, PO_SFR_REGISTER, stackPos, "_stack", stackLen-1, 0, NULL);
242         addSet(&pic16_fix_udata, reg);
243
244         reg = newReg(REG_SFR, PO_SFR_REGISTER, stackPos + stackLen-1, "_stack_end", 1, 0, NULL);
245         addSet(&pic16_fix_udata, reg);
246
247         sym = newSymbol("stack", 0);
248         sprintf(sym->rname, "_%s", sym->name);
249         addSet(&publics, sym);
250
251         sym = newSymbol("stack_end", 0);
252         sprintf(sym->rname, "_%s", sym->name);
253         addSet(&publics, sym);
254
255         initsfpnt = 1;    // force glue() to initialize stack/frame pointers */
256       }
257       break;
258
259     /* #pragma code [symbol] [location] */
260     case P_CODE:
261       {
262         absSym *absS;
263
264         cp = get_pragma_token(cp, &token);
265         if (TOKEN_STR != token.type)
266           goto code_err;
267
268         absS = Safe_calloc(1, sizeof(absSym));
269         sprintf(absS->name, "_%s", get_pragma_string(&token));
270
271         cp = get_pragma_token(cp, &token);
272         if (TOKEN_INT != token.type)
273           {
274           code_err:
275             //fprintf (stderr, "%s:%d: #pragma code [symbol] [location] -- symbol or location missing\n", filename, lineno);
276             err = 1;
277             break;
278           }
279         absS->address = token.val.int_val;
280
281         cp = get_pragma_token(cp, &token);
282         if (TOKEN_EOL != token.type)
283           {
284             err = 1;
285             break;
286           }
287
288         if ((absS->address % 2) != 0) {
289           absS->address--;
290           fprintf(stderr, "%s:%d: warning: code memory locations should be word aligned, will locate to 0x%06x instead\n",
291                   filename, lineno, absS->address);
292         }
293
294         addSet(&absSymSet, absS);
295 //      fprintf(stderr, "%s:%d symbol %s will be placed in location 0x%06x in code memory\n",
296 //        __FILE__, __LINE__, symname, absS->address);
297       }
298       break;
299
300     /* #pragma udata [section-name] [symbol] */
301     case P_UDATA:
302       {
303         char *sectname;
304         const char *symname;
305         symbol *nsym;
306         sectSym *ssym;
307         sectName *snam;
308         int found = 0;
309
310         cp = get_pragma_token(cp, &token);
311         if (TOKEN_STR == token.type)
312           sectname = Safe_strdup(get_pragma_string(&token));
313         else
314           {
315             err = 1;
316             break;
317           }
318
319         cp = get_pragma_token(cp, &token);
320         if (TOKEN_STR == token.type)
321           symname = get_pragma_string(&token);
322         else
323           {
324             //fprintf (stderr, "%s:%d: #pragma udata [section-name] [symbol] -- section-name or symbol missing!\n", filename, lineno);
325             err = 1;
326             symname = NULL;
327           }
328
329         while (symname)
330           {
331             ssym = Safe_calloc(1, sizeof(sectSym));
332             ssym->name = Safe_calloc(1, strlen(symname) + 2);
333             sprintf(ssym->name, "%s%s", port->fun_prefix, symname);
334             ssym->reg = NULL;
335
336             addSet(&sectSyms, ssym);
337
338             nsym = newSymbol((char *)symname, 0);
339             strcpy(nsym->rname, ssym->name);
340
341 #if 0
342             checkAddSym(&publics, nsym);
343 #endif
344
345             found = 0;
346             for (snam = setFirstItem(sectNames);snam;snam=setNextItem(sectNames))
347               {
348                 if (!strcmp(sectname, snam->name))
349                   {
350                     found=1;
351                     break;
352                   }
353               }
354
355             if(!found)
356               {
357                 snam = Safe_calloc(1, sizeof(sectName));
358                 snam->name = Safe_strdup(sectname);
359                 snam->regsSet = NULL;
360
361                 addSet(&sectNames, snam);
362               }
363
364             ssym->section = snam;
365
366 #if 0
367             fprintf(stderr, "%s:%d placing symbol %s at section %s (%p)\n", __FILE__, __LINE__,
368                ssym->name, snam->name, snam);
369 #endif
370
371             cp = get_pragma_token(cp, &token);
372             if (TOKEN_STR == token.type)
373               symname = get_pragma_string(&token);
374             else if (TOKEN_EOL == token.type)
375               symname = NULL;
376             else
377               {
378                 err = 1;
379                 symname = NULL;
380               }
381           }
382
383           Safe_free(sectname);
384       }
385       break;
386
387     /* #pragma library library_module */
388     case P_LIBRARY:
389       {
390         const char *lmodule;
391
392         cp = get_pragma_token(cp, &token);
393         if (TOKEN_EOL != token.type)
394           {
395             lmodule = get_pragma_string(&token);
396
397             /* lmodule can be:
398              * c    link the C library
399              * math link the math library
400              * io   link the IO library
401              * debug    link the debug libary
402              * anything else, will link as-is */
403
404             if(!strcmp(lmodule, "c"))
405               libflags.want_libc = 1;
406             else if(!strcmp(lmodule, "math"))
407               libflags.want_libm = 1;
408             else if(!strcmp(lmodule, "io"))
409               libflags.want_libio = 1;
410             else if(!strcmp(lmodule, "debug"))
411               libflags.want_libdebug = 1;
412             else if(!strcmp(lmodule, "ignore"))
413               libflags.ignore = 1;
414             else
415               {
416                 if(!libflags.ignore)
417                   {
418                     fprintf(stderr, "link library %s\n", lmodule);
419                     addSetHead(&libFilesSet, (char *)lmodule);
420                   }
421               }
422           }
423         else
424           {
425             err = 1;
426             break;
427           }
428
429         cp = get_pragma_token(cp, &token);
430         if (TOKEN_EOL != token.type)
431           {
432             err = 1;
433             break;
434           }
435       }
436       break;
437
438 #if 0
439   /* This is an experimental code for #pragma inline
440      and is temporarily disabled for 2.5.0 release */
441     case P_INLINE:
442       {
443         char *tmp = strtok((char *)NULL, WHITECOMMA);
444
445         while(tmp) {
446           addSet(&asmInlineMap, Safe_strdup( tmp ));
447           tmp = strtok((char *)NULL, WHITECOMMA);
448         }
449
450         {
451           char *s;
452
453           for(s = setFirstItem(asmInlineMap); s ; s = setNextItem(asmInlineMap)) {
454             debugf("inline asm: `%s'\n", s);
455           }
456         }
457       }
458       break;
459 #endif  /* 0 */
460
461     default:
462       processed = 0;
463       break;
464   }
465
466   get_pragma_token(cp, &token);
467
468   if (1 == err)
469     werror(W_BAD_PRAGMA_ARGUMENTS, name);
470
471   free_pragma_token(&token);
472   return processed;
473 }
474
475 static struct pragma_s pragma_tbl[] = {
476   { "stack",   P_STACK,   0, do_pragma },
477   { "code",    P_CODE,    0, do_pragma },
478   { "udata",   P_UDATA,   0, do_pragma },
479   { "library", P_LIBRARY, 0, do_pragma },
480 /*{ "inline",  P_INLINE,  0, do_pragma }, */
481   { NULL,      0,         0, NULL },
482   };
483
484 static int
485 _process_pragma(const char *s)
486 {
487   return process_pragma_tbl(pragma_tbl, s);
488 }
489
490 #define REP_UDATA         "--preplace-udata-with="
491
492 #define STACK_MODEL       "--pstack-model="
493 #define OPT_BANKSEL       "--obanksel="
494
495 #define ALT_ASM           "--asm="
496 #define ALT_LINK          "--link="
497
498 #define IVT_LOC           "--ivt-loc="
499 #define NO_DEFLIBS        "--nodefaultlibs"
500 #define MPLAB_COMPAT      "--mplab-comp"
501
502 #define USE_CRT           "--use-crt="
503
504 #define OFMSG_LRSUPPORT   "--flr-support"
505
506 #define NO_OPTIMIZE_GOTO  "--no-optimize-goto"
507 #define OPTIMIZE_CMP      "--optimize-cmp"
508 #define OPTIMIZE_DF       "--optimize-df"
509
510 char *alt_asm = NULL;
511 char *alt_link = NULL;
512
513 int pic16_mplab_comp = 0;
514 extern int pic16_debug_verbose;
515 extern int pic16_ralloc_debug;
516 extern int pic16_pcode_verbose;
517
518 int pic16_enable_peeps = 0;
519
520 OPTION pic16_optionsTable[]= {
521     /* code generation options */
522     { 0, STACK_MODEL,        NULL, "use stack model 'small' (default) or 'large'"},
523 #if XINST
524     { 'y', "--extended",     &pic16_options.xinst, "enable Extended Instruction Set/Literal Offset Addressing mode"},
525 #endif
526     { 0, "--pno-banksel",    &pic16_options.no_banksel, "do not generate BANKSEL assembler directives"},
527
528     /* optimization options */
529     { 0, OPT_BANKSEL,       &pic16_options.opt_banksel, "set banksel optimization level (default=0 no)", CLAT_INTEGER },
530     { 0, "--denable-peeps", &pic16_enable_peeps, "explicit enable of peepholes"},
531     { 0, NO_OPTIMIZE_GOTO,  NULL, "do NOT use (conditional) BRA instead of GOTO"},
532     { 0, OPTIMIZE_CMP,      NULL, "try to optimize some compares"},
533     { 0, OPTIMIZE_DF,       NULL, "thoroughly analyze data flow (memory and time intensive!)"},
534
535     /* assembling options */
536     { 0, ALT_ASM,           &alt_asm, "Use alternative assembler", CLAT_STRING},
537     { 0, MPLAB_COMPAT,      &pic16_mplab_comp, "enable compatibility mode for MPLAB utilities (MPASM/MPLINK)"},
538
539     /* linking options */
540     { 0, ALT_LINK,          &alt_link, "Use alternative linker", CLAT_STRING },
541     { 0, REP_UDATA,         &pic16_sectioninfo.at_udata, "Place udata variables at another section: udata_acs, udata_ovr, udata_shr", CLAT_STRING },
542     { 0, IVT_LOC,           NULL, "Set address of interrupt vector table."},
543     { 0, NO_DEFLIBS,        &pic16_options.nodefaultlibs,   "do not link default libraries when linking"},
544     { 0, USE_CRT,           NULL, "use <crt-o> run-time initialization module"},
545     { 0, "--no-crt",        &pic16_options.no_crt, "do not link any default run-time initialization module"},
546
547     /* debugging options */
548     { 0, "--debug-xtra",    &pic16_debug_verbose, "show more debug info in assembly output"},
549     { 0, "--debug-ralloc",  &pic16_ralloc_debug, "dump register allocator debug file *.d"},
550     { 0, "--pcode-verbose", &pic16_pcode_verbose, "dump pcode related info"},
551     { 0, "--calltree",      &pic16_options.dumpcalltree, "dump call tree in .calltree file"},
552     { 0, "--gstack",        &pic16_options.gstack, "trace stack pointer push/pop to overflow"},
553     { 0, NULL,              NULL, NULL}
554 };
555
556
557 #define ISOPT(str)  !strncmp(argv[ *i ], str, strlen(str) )
558
559 static bool
560 _pic16_parseOptions (int *pargc, char **argv, int *i)
561 {
562   int j=0;
563   char *stkmodel;
564
565   /* TODO: allow port-specific command line options to specify
566    * segment names here.
567    */
568
569     /* check for arguments that have associated an integer variable */
570     while(pic16_optionsTable[j].pparameter) {
571       if(ISOPT( pic16_optionsTable[j].longOpt )) {
572         (*(int *)pic16_optionsTable[j].pparameter)++;
573         return TRUE;
574       }
575       j++;
576     }
577
578     if(ISOPT(STACK_MODEL)) {
579       stkmodel = getStringArg(STACK_MODEL, argv, i, *pargc);
580       if(!STRCASECMP(stkmodel, "small"))pic16_options.stack_model = 0;
581       else if(!STRCASECMP(stkmodel, "large"))pic16_options.stack_model = 1;
582       else {
583         fprintf(stderr, "Unknown stack model: %s", stkmodel);
584         exit(EXIT_FAILURE);
585       }
586       return TRUE;
587     }
588
589     if(ISOPT(IVT_LOC)) {
590       pic16_options.ivt_loc = getIntArg(IVT_LOC, argv, i, *pargc);
591       fprintf(stderr, "%s:%d setting interrupt vector addresses 0x%x\n", __FILE__, __LINE__, pic16_options.ivt_loc);
592       return TRUE;
593     }
594
595     if(ISOPT(USE_CRT)) {
596       pic16_options.no_crt = 0;
597       pic16_options.crt_name = Safe_strdup( getStringArg(USE_CRT, argv, i, *pargc) );
598
599       return TRUE;
600     }
601
602 #if 0
603     if(ISOPT(OFMSG_LRSUPPORT)) {
604       pic16_options.opt_flags |= OF_LR_SUPPORT;
605       return TRUE;
606     }
607 #endif
608
609     if (ISOPT(NO_OPTIMIZE_GOTO)) {
610       pic16_options.opt_flags |= OF_NO_OPTIMIZE_GOTO;
611       return TRUE;
612     }
613
614     if(ISOPT(OPTIMIZE_CMP)) {
615       pic16_options.opt_flags |= OF_OPTIMIZE_CMP;
616       return TRUE;
617     }
618
619     if (ISOPT(OPTIMIZE_DF)) {
620       pic16_options.opt_flags |= OF_OPTIMIZE_DF;
621       return TRUE;
622     }
623
624
625   return FALSE;
626 }
627
628 extern void pic16_init_pic(const char *name);
629
630 static void _pic16_initPaths(void)
631 {
632     set *pic16libDirsSet=NULL;
633
634     if (!options.nostdlib) {
635         struct dbuf_s pic16libDir;
636
637         dbuf_init(&pic16libDir, 128);
638         dbuf_makePath(&pic16libDir, LIB_DIR_SUFFIX, "pic16");
639         pic16libDirsSet = appendStrSet(dataDirsSet, NULL, dbuf_c_str(&pic16libDir));
640         dbuf_destroy(&pic16libDir);
641         mergeSets(&pic16libDirsSet, libDirsSet);
642         libDirsSet = pic16libDirsSet;
643     }
644
645     /* now that we have the paths set up... */
646     pic16_init_pic(port->processor);
647 }
648
649 extern set *linkOptionsSet;
650 char *msprintf(hTab *pvals, const char *pformat, ...);
651 int my_system(const char *cmd);
652
653 /* forward declarations */
654 extern const char *pic16_linkCmd[];
655 extern const char *pic16_asmCmd[];
656 extern set *asmOptionsSet;
657
658 /* custom function to link objects */
659 static void _pic16_linkEdit(void)
660 {
661   hTab *linkValues=NULL;
662   char lfrm[1024];
663   char *lcmd;
664   char temp[1024];
665   set *tSet=NULL;
666   int ret;
667
668     /*
669      * link command format:
670      * {linker} {incdirs} {lflags} -o {outfile} {spec_ofiles} {ofiles} {libs}
671      *
672      */
673     sprintf(lfrm, "{linker} {incdirs} {lflags} -w -r -o {outfile} {user_ofile} {ofiles} {spec_ofiles} {libs}");
674
675     shash_add(&linkValues, "linker", pic16_linkCmd[0]);
676
677     mergeSets(&tSet, libPathsSet);
678     mergeSets(&tSet, libDirsSet);
679
680     shash_add(&linkValues, "incdirs", joinStrSet( appendStrSet(tSet, "-I\"", "\"")));
681     shash_add(&linkValues, "lflags", joinStrSet(linkOptionsSet));
682
683     shash_add(&linkValues, "outfile", fullDstFileName ? fullDstFileName : dstFileName);
684
685     if(fullSrcFileName) {
686         sprintf(temp, "%s.o", fullDstFileName ? fullDstFileName : dstFileName);
687 //      addSetHead(&relFilesSet, Safe_strdup(temp));
688                 shash_add(&linkValues, "user_ofile", temp);
689     }
690
691     if(!pic16_options.no_crt)
692           shash_add(&linkValues, "spec_ofiles", pic16_options.crt_name);
693
694     shash_add(&linkValues, "ofiles", joinStrSet(relFilesSet));
695
696     if(!libflags.ignore) {
697       if(libflags.want_libc)
698         addSet(&libFilesSet, Safe_strdup("libc18f.lib"));
699
700           if(libflags.want_libm)
701             addSet(&libFilesSet, Safe_strdup("libm18f.lib"));
702
703           if(libflags.want_libio) {
704             sprintf(temp, "libio%s.lib", pic16->name[1]);   /* build libio18f452.lib name */
705             addSet(&libFilesSet, Safe_strdup(temp));
706           }
707
708           if(libflags.want_libdebug)
709             addSet(&libFilesSet, Safe_strdup("libdebug.lib"));
710         }
711
712     shash_add(&linkValues, "libs", joinStrSet(libFilesSet));
713
714     lcmd = msprintf(linkValues, lfrm);
715
716     ret = my_system( lcmd );
717
718     Safe_free( lcmd );
719
720     if(ret)
721         exit(1);
722 }
723
724
725 static void
726 _pic16_finaliseOptions (void)
727 {
728   port->mem.default_local_map = data;
729   port->mem.default_globl_map = data;
730
731   /* peepholes are disabled for the time being */
732   options.nopeep = 1;
733
734   /* explicit enable peepholes for testing */
735   if (pic16_enable_peeps)
736     options.nopeep = 0;
737
738   options.all_callee_saves = 1;       // always callee saves
739
740 #if 0
741   options.float_rent = 1;
742   options.intlong_rent = 1;
743 #endif
744
745   setMainValue("mcu", pic16->name[2] );
746   addSet(&preArgvSet, Safe_strdup("-D{mcu}"));
747
748   setMainValue("mcu1", pic16->name[1] );
749   addSet(&preArgvSet, Safe_strdup("-D__{mcu1}"));
750
751   if (!pic16_options.nodefaultlibs)
752     {
753       char devlib[512];
754
755       /* now add the library for the device */
756       sprintf(devlib, "libdev%s.lib", pic16->name[1]);   /* e.g., libdev18f452.lib */
757       addSet(&libFilesSet, Safe_strdup(devlib));
758
759       /* add the internal SDCC library */
760       addSet(&libFilesSet, Safe_strdup( "libsdcc.lib" ));
761     }
762
763   if (alt_asm && alt_asm[0] != '\0')
764     {
765       pic16_asmCmd[0] = alt_asm;
766     }
767
768   if (alt_link && alt_link[0] != '\0')
769     {
770       pic16_linkCmd[0] = alt_link;
771     }
772
773   if (!pic16_options.no_crt)
774     {
775       pic16_options.omit_ivt = 1;
776       pic16_options.leave_reset = 0;
777     }
778
779   if (options.model == MODEL_SMALL)
780     {
781       addSet(&asmOptionsSet, Safe_strdup("-DSDCC_MODEL_SMALL"));
782     }
783   else if (options.model == MODEL_LARGE)
784     {
785       char buf[128];
786
787       addSet(&asmOptionsSet, Safe_strdup("-DSDCC_MODEL_LARGE"));
788
789       sprintf(buf, "-D%s -D__%s", pic16->name[2], pic16->name[1]);
790       *(strrchr(buf, 'f')) = 'F';
791       addSet(&asmOptionsSet, Safe_strdup(buf));
792     }
793
794   if (STACK_MODEL_LARGE)
795     {
796       addSet(&preArgvSet, Safe_strdup("-DSTACK_MODEL_LARGE"));
797       addSet(&asmOptionsSet, Safe_strdup("-DSTACK_MODEL_LARGE"));
798     }
799   else
800     {
801       addSet(&preArgvSet, Safe_strdup("-DSTACK_MODEL_SMALL"));
802       addSet(&asmOptionsSet, Safe_strdup("-DSTACK_MODEL_SMALL"));
803     }
804 }
805
806
807 static void
808 _pic16_setDefaultOptions (void)
809 {
810   options.stackAuto = 0;        /* implicit declaration */
811   /* port is not capable yet to allocate separate registers
812    * dedicated for passing certain parameters */
813
814   /* initialize to defaults section locations, names and addresses */
815   pic16_sectioninfo.at_udata    = "udata";
816
817   /* set pic16 port options to defaults */
818   pic16_options.no_banksel = 0;
819   pic16_options.opt_banksel = 0;
820   pic16_options.omit_configw = 0;
821   pic16_options.omit_ivt = 0;
822   pic16_options.leave_reset = 0;
823   pic16_options.stack_model = 0;            /* 0 for 'small', 1 for 'large' */
824   pic16_options.ivt_loc = 0x000000;
825   pic16_options.nodefaultlibs = 0;
826   pic16_options.dumpcalltree = 0;
827   pic16_options.crt_name = "crt0i.o";       /* the default crt to link */
828   pic16_options.no_crt = 0;         /* use crt by default */
829   pic16_options.ip_stack = 1;       /* set to 1 to enable ipop/ipush for stack */
830   pic16_options.gstack = 0;
831   pic16_options.debgen = 0;
832 }
833
834 static const char *
835 _pic16_getRegName (struct regs *reg)
836 {
837   if (reg)
838     return reg->name;
839   return "err";
840 }
841
842
843 #if 1
844 static  char *_pic16_mangleFunctionName(char *sz)
845 {
846 //  fprintf(stderr, "mangled function name: %s\n", sz);
847
848   return sz;
849 }
850 #endif
851
852
853 static void
854 _pic16_genAssemblerPreamble (FILE * of)
855 {
856   char *name = pic16_processor_base_name();
857
858     if(!name) {
859         name = "p18f452";
860         fprintf(stderr,"WARNING: No Pic has been selected, defaulting to %s\n",name);
861     }
862
863     fprintf (of, "\tlist\tp=%s\n",&name[1]);
864     if (pic16_mplab_comp) {
865       // provide ACCESS macro used during SFR accesses
866       fprintf (of, "\tinclude <p%s.inc>\n", &name[1]);
867     }
868
869     if(!pic16_options.omit_configw) {
870         pic16_emitConfigRegs(of);
871         fprintf(of, "\n");
872         pic16_emitIDRegs(of);
873     }
874
875   fprintf (of, "\tradix dec\n");
876 }
877
878 /* Generate interrupt vector table. */
879 static int
880 _pic16_genIVT (struct dbuf_s * oBuf, symbol ** interrupts, int maxInterrupts)
881 {
882 #if 1
883     /* PIC18F family has only two interrupts, the high and the low
884      * priority interrupts, which reside at 0x0008 and 0x0018 respectively - VR */
885
886     if((!pic16_options.omit_ivt) || (pic16_options.omit_ivt && pic16_options.leave_reset)) {
887         dbuf_printf(oBuf, "; RESET vector\n");
888         dbuf_printf(oBuf, "\tgoto\t__sdcc_gsinit_startup\n");
889     }
890
891     if(!pic16_options.omit_ivt) {
892         dbuf_printf(oBuf, "\tres 4\n");
893
894
895         dbuf_printf(oBuf, "; High priority interrupt vector 0x0008\n");
896         if(interrupts[1]) {
897             dbuf_printf(oBuf, "\tgoto\t%s\n", interrupts[1]->rname);
898             dbuf_printf(oBuf, "\tres\t12\n");
899         } else {
900             dbuf_printf(oBuf, "\tretfie\n");
901             dbuf_printf(oBuf, "\tres\t14\n");
902         }
903
904         dbuf_printf(oBuf, "; Low priority interrupt vector 0x0018\n");
905         if(interrupts[2]) {
906             dbuf_printf(oBuf, "\tgoto\t%s\n", interrupts[2]->rname);
907         } else {
908             dbuf_printf(oBuf, "\tretfie\n");
909         }
910     }
911 #endif
912   return TRUE;
913 }
914
915 /* return True if the port can handle the type,
916  * False to convert it to function call */
917 static bool _hasNativeMulFor (iCode *ic, sym_link *left, sym_link *right)
918 {
919   //fprintf(stderr,"checking for native mult for %c (size: %d)\n", ic->op, getSize(OP_SYMBOL(IC_RESULT(ic))->type));
920   int symL, symR, symRes, sizeL = 0, sizeR = 0, sizeRes = 0;
921
922   /* left/right are symbols? */
923   symL = IS_SYMOP(IC_LEFT(ic));
924   symR = IS_SYMOP(IC_RIGHT(ic));
925   symRes = IS_SYMOP(IC_RESULT(ic));
926
927   /* --> then determine their sizes */
928   sizeL = symL ? getSize(OP_SYM_TYPE(IC_LEFT(ic))) : 4;
929   sizeR = symR ? getSize(OP_SYM_TYPE(IC_RIGHT(ic))) : 4;
930   sizeRes = symRes ? getSize(OP_SYM_TYPE(IC_RESULT(ic))) : 4;
931
932   /* Checks to enable native multiplication.
933    * PICs do not offer native division at all...
934    *
935    * Ideas:
936    * (  i) if result is just one byte, use native MUL
937    *       (regardless of the operands)
938    * ( ii) if left and right are unsigned 8-bit operands,
939    *       use native MUL
940    * (iii) if left or right is a literal in the range of [-128..256)
941    *       and the other is an unsigned byte, use native MUL
942    */
943   if (ic->op == '*')
944   {
945     /* use native mult for `*: <?> x <?> --> {u8_t, s8_t}' */
946     if (sizeRes == 1) { return TRUE; }
947
948     /* use native mult for `u8_t x u8_t --> { u16_t, s16_t }' */
949     if (sizeL == 1 && symL /*&& SPEC_USIGN(OP_SYM_TYPE(IC_LEFT(ic)))*/) {
950       sizeL = 1;
951     } else {
952       //printf( "%s: left too large (%u) / signed (%u)\n", __FUNCTION__, sizeL, symL && !SPEC_USIGN(OP_SYM_TYPE(IC_LEFT(ic))));
953       sizeL = 4;
954     }
955     if (sizeR == 1 && symR /*&& SPEC_USIGN(OP_SYM_TYPE(IC_RIGHT(ic)))*/) {
956       sizeR = 1;
957     } else {
958       //printf( "%s: right too large (%u) / signed (%u)\n", __FUNCTION__, sizeR, symR && !SPEC_USIGN(OP_SYM_TYPE(IC_RIGHT(ic))));
959       sizeR = 4;
960     }
961
962     /* also allow literals [-128..256) for left/right operands */
963     if (IS_VALOP(IC_LEFT(ic)))
964     {
965       long l = (long) ulFromVal ( OP_VALUE( IC_LEFT(ic) ) );
966       sizeL = 4;
967       //printf( "%s: val(left) = %ld\n", __FUNCTION__, l );
968       if (l >= -128 && l < 256)
969       {
970     sizeL = 1;
971       } else {
972     //printf( "%s: left value %ld outside [-128..256)\n", __FUNCTION__, l );
973       }
974     }
975     if (IS_VALOP( IC_RIGHT(ic) ))
976     {
977       long l = (long) ulFromVal ( OP_VALUE( IC_RIGHT(ic) ) );
978       sizeR = 4;
979       //printf( "%s: val(right) = %ld\n", __FUNCTION__, l );
980       if (l >= -128 && l < 256)
981       {
982     sizeR = 1;
983       } else {
984     //printf( "%s: right value %ld outside [-128..256)\n", __FUNCTION__, l );
985       }
986     }
987
988     /* use native mult iff left and right are (unsigned) 8-bit operands */
989     if (sizeL == 1 && sizeR == 1) { return TRUE; }
990   }
991
992   if (ic->op == '/' || ic->op == '%')
993   {
994     /* We must catch /: {u8_t,s8_t} x {u8_t,s8_t} --> {u8_t,s8_t},
995      * because SDCC will call 'divuchar' even for u8_t / s8_t.
996      * Example: 128 / -2 becomes 128 / 254 = 0 != -64... */
997     if (sizeL == 1 && sizeR == 1) return TRUE;
998
999     /* What about literals? */
1000     if (IS_VALOP( IC_LEFT(ic) ))
1001     {
1002       long l = (long) ulFromVal ( OP_VALUE( IC_LEFT(ic) ) );
1003       sizeL = 4;
1004       //printf( "%s: val(left) = %ld\n", __FUNCTION__, l );
1005       if (l >= -128 && l < 256)
1006       {
1007     sizeL = 1;
1008       } else {
1009     //printf( "%s: left value %ld outside [-128..256)\n", __FUNCTION__, l );
1010       }
1011     }
1012     if (IS_VALOP( IC_RIGHT(ic) ))
1013     {
1014       long l = (long) ulFromVal ( OP_VALUE( IC_RIGHT(ic) ) );
1015       sizeR = 4;
1016       //printf( "%s: val(right) = %ld\n", __FUNCTION__, l );
1017       if (l >= -128 && l < 256)
1018       {
1019     sizeR = 1;
1020       } else {
1021     //printf( "%s: right value %ld outside [-128..256)\n", __FUNCTION__, l );
1022       }
1023     }
1024     if (sizeL == 1 && sizeR == 1) { return TRUE; }
1025   }
1026
1027   return FALSE;
1028 }
1029
1030
1031 #if 0
1032 /* Do CSE estimation */
1033 static bool cseCostEstimation (iCode *ic, iCode *pdic)
1034 {
1035 //    operand *result = IC_RESULT(ic);
1036 //    sym_link *result_type = operandType(result);
1037
1038
1039     /* VR -- this is an adhoc. Put here after conversation
1040      * with Erik Epetrich */
1041
1042     if(ic->op == '<'
1043         || ic->op == '>'
1044         || ic->op == EQ_OP) {
1045
1046         fprintf(stderr, "%d %s\n", __LINE__, __FUNCTION__);
1047       return 0;
1048     }
1049
1050 #if 0
1051     /* if it is a pointer then return ok for now */
1052     if (IC_RESULT(ic) && IS_PTR(result_type)) return 1;
1053
1054     /* if bitwise | add & subtract then no since mcs51 is pretty good at it
1055        so we will cse only if they are local (i.e. both ic & pdic belong to
1056        the same basic block */
1057     if (IS_BITWISE_OP(ic) || ic->op == '+' || ic->op == '-') {
1058         /* then if they are the same Basic block then ok */
1059         if (ic->eBBlockNum == pdic->eBBlockNum) return 1;
1060         else return 0;
1061     }
1062 #endif
1063
1064     /* for others it is cheaper to do the cse */
1065     return 1;
1066 }
1067 #endif
1068
1069
1070 /* Indicate which extended bit operations this port supports */
1071 static bool
1072 hasExtBitOp (int op, int size)
1073 {
1074   if (op == RRC
1075       || op == RLC
1076       /* || op == GETHBIT */ /* GETHBIT doesn't look complete for PIC */
1077      )
1078     return TRUE;
1079   else
1080     return FALSE;
1081 }
1082
1083 /* Indicate the expense of an access to an output storage class */
1084 static int
1085 oclsExpense (struct memmap *oclass)
1086 {
1087   /* The IN_FARSPACE test is compatible with historical behaviour, */
1088   /* but I don't think it is applicable to PIC. If so, please feel */
1089   /* free to remove this test -- EEP */
1090   if (IN_FARSPACE(oclass))
1091     return 1;
1092
1093   return 0;
1094 }
1095
1096 /** $1 is the input object file (PIC16 specific)    // >>always the basename<<.
1097     $2 is always the output file.
1098     $3 -L path and -l libraries
1099     $l is the list of extra options that should be there somewhere...
1100     MUST be terminated with a NULL.
1101 */
1102 const char *pic16_linkCmd[] =
1103 {
1104   "gplink", "$l", "-w", "-r", "-o \"$2\"", "\"$1\"","$3", NULL
1105 };
1106
1107
1108
1109 /** $1 is always the basename.
1110     $2 is always the output file.
1111     $3 varies (nothing currently)
1112     $l is the list of extra options that should be there somewhere...
1113     MUST be terminated with a NULL.
1114 */
1115 const char *pic16_asmCmd[] =
1116 {
1117   "gpasm", "$l", "$3", "-c", "\"$1.asm\"", "-o \"$2\"", NULL
1118
1119 };
1120
1121 /* Globals */
1122 PORT pic16_port =
1123 {
1124   TARGET_ID_PIC16,
1125   "pic16",
1126   "MCU PIC16",      /* Target name */
1127   "p18f452",        /* Processor */
1128   {
1129     pic16glue,
1130     TRUE,           /* Emit glue around main */
1131     MODEL_SMALL | MODEL_LARGE | MODEL_FLAT24,
1132     MODEL_SMALL
1133   },
1134   {
1135     pic16_asmCmd,   /* assembler command and arguments */
1136     NULL,           /* alternate macro based form */
1137     "-g",           /* arguments for debug mode */
1138     NULL,           /* arguments for normal mode */
1139     0,              /* print externs as global */
1140     ".asm",         /* assembler file extension */
1141     NULL            /* no do_assemble function */
1142   },
1143   {
1144     NULL,           //    pic16_linkCmd,        /* linker command and arguments */
1145     NULL,           /* alternate macro based form */
1146     _pic16_linkEdit,        //NULL,         /* no do_link function */
1147     ".o",           /* extension for object files */
1148     0               /* no need for linker file */
1149   },
1150   {
1151     _defaultRules
1152   },
1153   {
1154     /* Sizes */
1155     1,      /* char */
1156     2,      /* short */
1157     2,      /* int */
1158     4,      /* long */
1159     2,      /* ptr */
1160     3,      /* fptr, far pointers (see Microchip) */
1161     3,      /* gptr */
1162     1,      /* bit */
1163     4,      /* float */
1164     4       /* max */
1165   },
1166
1167     /* generic pointer tags */
1168   {
1169     0x00,   /* far */
1170     0x80,   /* near */
1171     0x00,   /* xstack */
1172     0x00    /* code */
1173   },
1174
1175   {
1176     "XSEG    (XDATA)",      // xstack
1177     "STACK   (DATA)",       // istack
1178     "CSEG    (CODE)",       // code
1179     "DSEG    (DATA)",       // data
1180     "ISEG    (DATA)",       // idata
1181     "PSEG    (DATA)",       // pdata
1182     "XSEG    (XDATA)",      // xdata
1183     "BSEG    (BIT)",        // bit
1184     "RSEG    (DATA)",       // reg
1185     "GSINIT  (CODE)",       // static
1186     "OSEG    (OVR,DATA)",   // overlay
1187     "GSFINAL (CODE)",       // post static
1188     "HOME    (CODE)",       // home
1189     NULL,                   // xidata
1190     NULL,                   // xinit
1191     "CONST   (CODE)",       // const_name - const data (code or not)
1192     "CABS    (ABS,CODE)",   // cabs_name - const absolute data (code or not)
1193     "XABS    (ABS,XDATA)",  // xabs_name - absolute xdata
1194     "IABS    (ABS,DATA)",   // iabs_name - absolute data
1195     NULL,                   // default location for auto vars
1196     NULL,                   // default location for global vars
1197     1                       // code is read only 1=yes
1198   },
1199   {
1200     NULL,       /* genExtraAreaDeclaration */
1201     NULL        /* genExatrAreaLinkOptions */
1202   },
1203   {
1204     /* stack related information */
1205     -1,         /* -1 stack grows downwards, +1 upwards */
1206     1,          /* extra overhead when calling between banks */
1207     4,          /* extra overhead when the function is an ISR */
1208     1,          /* extra overhead for a function call */
1209     1,          /* re-entrant space */
1210     0           /* 'banked' call overhead, mild overlap with bank_overhead */
1211   },
1212     /* pic16 has an 8 bit mul */
1213   {
1214      0, -1
1215   },
1216   {
1217     pic16_emitDebuggerSymbol
1218   },
1219   {
1220     255/3,      /* maxCount */
1221     3,          /* sizeofElement */
1222     /* The rest of these costs are bogus. They approximate */
1223     /* the behavior of src/SDCCicode.c 1.207 and earlier.  */
1224     {4,4,4},    /* sizeofMatchJump[] */
1225     {0,0,0},    /* sizeofRangeCompare[] */
1226     0,          /* sizeofSubtract */
1227     3,          /* sizeofDispatch */
1228   },
1229   "_",
1230   _pic16_init,
1231   _pic16_parseOptions,
1232   pic16_optionsTable,
1233   _pic16_initPaths,
1234   _pic16_finaliseOptions,
1235   _pic16_setDefaultOptions,
1236   pic16_assignRegisters,
1237   _pic16_getRegName,
1238   _pic16_keywords,
1239   _pic16_genAssemblerPreamble,
1240   NULL,             /* no genAssemblerEnd */
1241   _pic16_genIVT,
1242   NULL, // _pic16_genXINIT
1243   NULL,             /* genInitStartup */
1244   _pic16_reset_regparm,
1245   _pic16_regparm,
1246   _process_pragma,  /* process a pragma */
1247   _pic16_mangleFunctionName, /* mangles function name */
1248   _hasNativeMulFor,
1249   hasExtBitOp,      /* hasExtBitOp */
1250   oclsExpense,      /* oclsExpense */
1251   FALSE,
1252   TRUE,             /* little endian */
1253   0,                /* leave lt */
1254   0,                /* leave gt */
1255   1,                /* transform <= to ! > */
1256   1,                /* transform >= to ! < */
1257   1,                /* transform != to !(a == b) */
1258   0,                /* leave == */
1259   FALSE,            /* No array initializer support. */
1260   0,    //cseCostEstimation,            /* !!!no CSE cost estimation yet */
1261   NULL,             /* no builtin functions */
1262   GPOINTER,         /* treat unqualified pointers as "generic" pointers */
1263   1,                /* reset labelKey to 1 */
1264   1,                /* globals & local static allowed */
1265   PORT_MAGIC
1266 };