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