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