* .version: bumped version number to 2.4.8
[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 "gen.h"
35
36
37 static char _defaultRules[] =
38 {
39 #include "peeph.rul"
40 };
41
42 /* list of key words used by pic16 */
43 static char *_pic16_keywords[] =
44 {
45   "at",
46 //  "bit",
47   "code",
48   "critical",
49   "register",
50   "data",
51   "far",
52 //  "idata",
53   "interrupt",
54   "near",
55   "pdata",
56   "reentrant",
57   "sfr",
58 //  "sbit",
59   "using",
60 //  "xdata",
61   "_data",
62   "_code",
63   "_generic",
64   "_near",
65 //  "_xdata",
66   "_pdata",
67 //  "_idata",
68   "_naked",
69   NULL
70 };
71
72
73 pic16_sectioninfo_t pic16_sectioninfo;
74
75
76 extern char *pic16_processor_base_name(void);
77
78 void  pic16_pCodeInitRegisters(void);
79
80 void pic16_assignRegisters (eBBlock ** ebbs, int count);
81
82 static int regParmFlg = 0;      /* determine if we can register a parameter */
83
84 pic16_options_t pic16_options;
85
86 extern set *includeDirsSet;
87 extern set *dataDirsSet;
88 extern set *libFilesSet;
89
90 /* Also defined in gen.h, but the #include is commented out */
91 /* for an unknowned reason. - EEP */
92 void pic16_emitDebuggerSymbol (char *);
93  
94 extern regs* newReg(short type, short pc_type, int rIdx, char *name, int size, int alias, operand *refop);
95 extern void pic16_emitConfigRegs(FILE *of);
96 extern void pic16_emitIDRegs(FILE *of);
97
98
99
100 static void
101 _pic16_init (void)
102 {
103   asm_addTree (&asm_asxxxx_mapping);
104   pic16_pCodeInitRegisters();
105   maxInterrupts = 2;
106 }
107
108 static void
109 _pic16_reset_regparm (void)
110 {
111   regParmFlg = 0;
112 }
113
114 static int
115 _pic16_regparm (sym_link * l)
116 {
117   /* force all parameters via SEND/RECEIVE */
118   if(0 /*pic16_options.ip_stack*/) {
119     /* for this processor it is simple
120      * can pass only the first parameter in a register */
121     if(regParmFlg)return 0;
122       regParmFlg++;
123       return 1; //regParmFlg;
124   } else {
125     /* otherwise pass all arguments in registers via SEND/RECEIVE */
126     regParmFlg++;// = 1;
127     return regParmFlg;
128   }
129 }
130
131
132 int initsfpnt=0;                /* set to 1 if source provides a pragma for stack
133                                  * so glue() later emits code to initialize stack/frame pointers */
134 set *absSymSet;
135
136 set *sectNames=NULL;                    /* list of section listed in pragma directives */
137 set *sectSyms=NULL;                     /* list of symbols set in a specific section */
138 set *wparamList=NULL;
139
140 struct {
141   unsigned ignore: 1;
142   unsigned want_libc: 1;
143   unsigned want_libm: 1;
144   unsigned want_libio: 1;
145   unsigned want_libdebug: 1;
146 } libflags = { 0, 0, 0, 0, 0 };
147   
148
149 static int
150 _process_pragma(const char *sz)
151 {
152   static const char *WHITE = " \t\n";
153   static const char *WHITECOMMA = " \t\n,";
154   
155   char  *ptr = strtok((char *)sz, WHITE);
156
157         /* #pragma maxram [maxram] */
158         if (startsWith (ptr, "maxram")) {
159           char *maxRAM = strtok((char *)NULL, WHITE);
160
161                 if (maxRAM != (char *)NULL) {
162                   int maxRAMaddress;
163                   value *maxRAMVal;
164
165                         maxRAMVal = constVal(maxRAM);
166                         maxRAMaddress = (int)floatFromVal(maxRAMVal);
167                         pic16_setMaxRAM(maxRAMaddress);
168                 }
169
170           return 0;
171         }
172         
173         /* #pragma stack [stack-position] [stack-len] */
174         if(startsWith(ptr, "stack")) {
175           char *stackPosS = strtok((char *)NULL, WHITE);
176           char *stackLenS = strtok((char *)NULL, WHITE);
177           value *stackPosVal;
178           value *stackLenVal;
179           regs *reg;
180           symbol *sym;
181
182                 stackPosVal = constVal( stackPosS );
183                 stackPos = (unsigned int)floatFromVal( stackPosVal );
184
185                 
186                 if(stackLenS) {
187                         stackLenVal = constVal( stackLenS );
188                         stackLen = (unsigned int)floatFromVal( stackLenVal );
189                 }
190
191                 if(stackLen < 1) {
192                         stackLen = 64;
193                         fprintf(stderr, "%s:%d: warning: setting stack to default size %d (0x%04x)\n",
194                                       filename, lineno-1, stackLen, stackLen);
195                         
196 //                      fprintf(stderr, "%s:%d setting stack to default size %d\n", __FILE__, __LINE__, stackLen);
197                 }
198
199 //              fprintf(stderr, "Initializing stack pointer at 0x%x len 0x%x\n", stackPos, stackLen);
200                                 
201                 reg=newReg(REG_SFR, PO_SFR_REGISTER, stackPos, "_stack", stackLen-1, 0, NULL);
202                 addSet(&pic16_fix_udata, reg);
203                 
204                 reg = newReg(REG_SFR, PO_SFR_REGISTER, stackPos + stackLen-1, "_stack_end", 1, 0, NULL);
205                 addSet(&pic16_fix_udata, reg);
206
207                 sym = newSymbol("stack", 0);
208                 sprintf(sym->rname, "_%s", sym->name);
209                 addSet(&publics, sym);
210
211                 sym = newSymbol("stack_end", 0);
212                 sprintf(sym->rname, "_%s", sym->name);
213                 addSet(&publics, sym);
214                 
215                 initsfpnt = 1;          // force glue() to initialize stack/frame pointers */
216
217           return 0;
218         }
219         
220         /* #pragma code [symbol] [location] */
221         if(startsWith(ptr, "code")) {
222           char *symname = strtok((char *)NULL, WHITE);
223           char *location = strtok((char *)NULL, WHITE);
224           absSym *absS;
225           value *addr;
226
227                 absS = Safe_calloc(1, sizeof(absSym));
228                 sprintf(absS->name, "_%s", symname);
229                 
230                 addr = constVal( location );
231                 absS->address = (unsigned int)floatFromVal( addr );
232
233                 if((absS->address % 2) != 0) {
234                   absS->address--;
235                   fprintf(stderr, "%s:%d: warning: code memory locations should be word aligned, will locate to 0x%06x instead\n",
236                                       filename, lineno-1, absS->address);
237                 }
238
239                 addSet(&absSymSet, absS);
240 //              fprintf(stderr, "%s:%d symbol %s will be placed in location 0x%06x in code memory\n",
241 //                      __FILE__, __LINE__, symname, absS->address);
242
243           return 0;
244         }
245
246         /* #pragma udata [section-name] [symbol] */
247         if(startsWith(ptr, "udata")) {
248           char *sectname = strtok((char *)NULL, WHITE);
249           char *symname = strtok((char *)NULL, WHITE);
250           symbol *nsym;
251           sectSym *ssym;
252           sectName *snam;
253           int found=0;
254           
255                 while(symname) {
256                         ssym = Safe_calloc(1, sizeof(sectSyms));
257                         ssym->name = Safe_calloc(1, strlen(symname)+2);
258                         sprintf(ssym->name, "_%s", symname);
259                         ssym->reg = NULL;
260
261                         addSet(&sectSyms, ssym);
262
263                         nsym = newSymbol(symname, 0);
264                         strcpy(nsym->rname, ssym->name);
265 #if 0
266                         checkAddSym(&publics, nsym);
267 #endif
268
269                         found = 0;
270                         for(snam=setFirstItem(sectNames);snam;snam=setNextItem(sectNames)) {
271                                 if(!strcmp(sectname, snam->name)){ found=1; break; }
272                         }
273                         
274                         if(!found) {
275                                 snam = Safe_calloc(1, sizeof(sectNames));
276                                 snam->name = Safe_strdup( sectname );
277                                 snam->regsSet = NULL;
278                                 
279                                 addSet(&sectNames, snam);
280                         }
281                         
282                         ssym->section = snam;
283                                 
284 #if 0
285                         fprintf(stderr, "%s:%d placing symbol %s at section %s (%p)\n", __FILE__, __LINE__,
286                                 ssym->name, snam->name, snam);
287 #endif
288
289                         symname = strtok((char *)NULL, WHITE);
290                 }
291
292           return 0;
293         }
294         
295         /* #pragma wparam function1[, function2[,...]] */
296         if(startsWith(ptr, "wparam")) {
297           char *fname = strtok((char *)NULL, WHITECOMMA);
298           
299             while(fname) {
300               addSet(&wparamList, Safe_strdup(fname));
301               
302 //              debugf("passing with WREG to %s\n", fname);
303               fname = strtok((char *)NULL, WHITECOMMA);
304             }
305             
306           return 0;
307         }
308         
309         /* #pragma library library_module */
310         if(startsWith(ptr, "library")) {
311           char *lmodule = strtok((char *)NULL, WHITE);
312         
313             if(lmodule) {
314               /* lmodule can be:
315                * c      link the C library
316                * math   link the math library
317                * io     link the IO library
318                * debug  link the debug libary
319                * anything else, will link as-is */
320               if(!strcmp(lmodule, "c"))libflags.want_libc = 1;
321               else if(!strcmp(lmodule, "math"))libflags.want_libm = 1;
322               else if(!strcmp(lmodule, "io"))libflags.want_libio = 1;
323               else if(!strcmp(lmodule, "debug"))libflags.want_libdebug = 1;
324               else if(!strcmp(lmodule, "ignore"))libflags.ignore = 1;
325               else {
326                 if(!libflags.ignore) {
327                   fprintf(stderr, "link library %s\n", lmodule);
328                   addSetHead(&libFilesSet, lmodule);
329                 }
330               }
331             }
332             
333             return 0;
334         }
335                 
336               
337         
338   return 1;
339 }
340
341 #define REP_UDATA       "--preplace-udata-with="
342
343 #define STACK_MODEL     "--pstack-model="
344 #define OPT_BANKSEL     "--obanksel="
345
346 #define ALT_ASM         "--asm="
347 #define ALT_LINK        "--link="
348
349 #define IVT_LOC         "--ivt-loc"
350 #define NO_DEFLIBS      "--nodefaultlibs"
351 #define MPLAB_COMPAT    "--mplab-comp"
352
353 #define NL_OPT          "--nl="
354 #define USE_CRT         "--use-crt="
355
356 #define OFMSG_LRSUPPORT "--flr-support"
357
358 #define OPTIMIZE_GOTO   "--optimize-goto"
359
360 char *alt_asm=NULL;
361 char *alt_link=NULL;
362
363 int pic16_mplab_comp=0;
364 extern int pic16_debug_verbose;
365 extern int pic16_ralloc_debug;
366 extern int pic16_pcode_verbose;
367
368 int pic16_fstack=0;
369 int pic16_enable_peeps=0;
370 int pic16_nl=0;                 /* 0 for LF, 1 for CRLF */
371
372 OPTION pic16_optionsTable[]= {
373         { 0,    NO_DEFLIBS,             &pic16_options.nodefaultlibs,   "do not link default libraries when linking"},
374         { 0,    "--pno-banksel",        &pic16_options.no_banksel,      "do not generate BANKSEL assembler directives"},
375         { 0,    OPT_BANKSEL,            NULL,                           "set banksel optimization level (default=0 no)"},
376 //      { 0,    "--pomit-config-words", &pic16_options.omit_configw,    "omit the generation of configuration words"},
377 //      { 0,    "--pomit-ivt",          &pic16_options.omit_ivt,        "omit the generation of the Interrupt Vector Table"},
378 //      { 0,    "--pleave-reset-vector",&pic16_options.leave_reset,     "when omitting IVT leave RESET vector"},
379         { 0,    STACK_MODEL,            NULL,                           "use stack model 'small' (default) or 'large'"},
380
381         { 0,    "--debug-xtra",         &pic16_debug_verbose,   "show more debug info in assembly output"},
382         { 0,    "--debug-ralloc",       &pic16_ralloc_debug,    "dump register allocator debug file *.d"},
383         { 0,    "--pcode-verbose",      &pic16_pcode_verbose,   "dump pcode related info"},
384                 
385         { 0,    REP_UDATA,      NULL,   "Place udata variables at another section: udata_acs, udata_ovr, udata_shr"},
386
387         { 0,    ALT_ASM,        NULL,   "Use alternative assembler"},
388         { 0,    ALT_LINK,       NULL,   "Use alternative linker"},
389
390         { 0,    "--denable-peeps",      &pic16_enable_peeps,    "explicit enable of peepholes"},
391         { 0,    IVT_LOC,        NULL,   "<nnnn> interrupt vector table location"},
392         { 0,    "--calltree",           &pic16_options.dumpcalltree,    "dump call tree in .calltree file"},
393         { 0,    MPLAB_COMPAT,           &pic16_mplab_comp,      "enable compatibility mode for MPLAB utilities (MPASM/MPLINK)"},
394         { 0,    "--fstack",             &pic16_fstack,          "enable stack optimizations"},
395         { 0,    NL_OPT,         NULL,                           "new line, \"lf\" or \"crlf\""},
396         { 0,    USE_CRT,        NULL,   "use <crt-o> run-time initialization module"},
397         { 0,    "--no-crt",     &pic16_options.no_crt,  "do not link any default run-time initialization module"},
398         { 0,    "--gstack",     &pic16_options.gstack,  "trace stack pointer push/pop to overflow"},
399 //      { 0,    OFMSG_LRSUPPORT,        NULL,           "use support functions for local register store/restore"},
400         { 0,    OPTIMIZE_GOTO,  NULL,                   "try to use (conditional) BRA instead of GOTO"},
401         { 0,    NULL,           NULL,   NULL}
402         };
403
404
405 #define ISOPT(str)      !strncmp(argv[ *i ], str, strlen(str) )
406
407 extern char *getStringArg(const char *,  char **, int *, int);
408 extern int getIntArg(const char *, char **, int *, int);
409
410 static bool
411 _pic16_parseOptions (int *pargc, char **argv, int *i)
412 {
413   int j=0;
414   char *stkmodel;
415   
416   /* TODO: allow port-specific command line options to specify
417    * segment names here.
418    */
419   
420     /* check for arguments that have associated an integer variable */
421     while(pic16_optionsTable[j].pparameter) {
422       if(ISOPT( pic16_optionsTable[j].longOpt )) {
423         (*pic16_optionsTable[j].pparameter)++;
424         return TRUE;
425       }
426       j++;
427     }
428
429     if(ISOPT(STACK_MODEL)) {
430       stkmodel = getStringArg(STACK_MODEL, argv, i, *pargc);
431       if(!STRCASECMP(stkmodel, "small"))pic16_options.stack_model = 0;
432       else if(!STRCASECMP(stkmodel, "large"))pic16_options.stack_model = 1;
433       else {
434         fprintf(stderr, "Unknown stack model: %s", stkmodel);
435         exit(-1);
436       }
437       return TRUE;
438     }
439
440     if(ISOPT(OPT_BANKSEL)) {
441       pic16_options.opt_banksel = getIntArg(OPT_BANKSEL, argv, i, *pargc);
442       return TRUE;
443     }
444
445     if(ISOPT(REP_UDATA)) {
446       pic16_sectioninfo.at_udata = Safe_strdup(getStringArg(REP_UDATA, argv, i, *pargc));
447       return TRUE;
448     }
449         
450     if(ISOPT(ALT_ASM)) {
451       alt_asm = Safe_strdup(getStringArg(ALT_ASM, argv, i, *pargc));
452       return TRUE;
453     }
454         
455     if(ISOPT(ALT_LINK)) {
456       alt_link = Safe_strdup(getStringArg(ALT_LINK, argv, i, *pargc));
457       return TRUE;
458     }
459
460     if(ISOPT(IVT_LOC)) {
461       pic16_options.ivt_loc = getIntArg(IVT_LOC, argv, i, *pargc);
462       return TRUE;
463     }
464         
465     if(ISOPT(NL_OPT)) {
466       char *tmp;
467             
468         tmp = Safe_strdup( getStringArg(NL_OPT, argv, i, *pargc) );
469         if(!STRCASECMP(tmp, "lf"))pic16_nl = 0;
470         else if(!STRCASECMP(tmp, "crlf"))pic16_nl = 1;
471         else {
472           fprintf(stderr, "invalid termination character id\n");
473           exit(-1);
474         }
475         return TRUE;
476     }
477
478     if(ISOPT(USE_CRT)) {
479       pic16_options.no_crt = 0;
480       pic16_options.crt_name = Safe_strdup( getStringArg(USE_CRT, argv, i, *pargc) );
481
482       return TRUE;
483     }
484
485 #if 0
486     if(ISOPT(OFMSG_LRSUPPORT)) {
487       pic16_options.opt_flags |= OF_LR_SUPPORT;
488       return TRUE;
489     }
490 #endif
491
492 #if 1
493     if (ISOPT(OPTIMIZE_GOTO)) {
494       pic16_options.opt_flags |= OF_OPTIMIZE_GOTO;
495       return TRUE;
496     }
497 #endif
498
499   return FALSE;
500 }
501
502 extern set *userIncDirsSet;
503
504 static void _pic16_initPaths(void)
505 {
506   char pic16incDir[512];
507   char pic16libDir[512];
508   set *pic16incDirsSet=NULL;
509   set *pic16libDirsSet=NULL;
510   char devlib[512];
511
512     setMainValue("mcu", pic16->name[2] );
513     addSet(&preArgvSet, Safe_strdup("-D{mcu}"));
514
515     sprintf(pic16incDir, "%s%cpic16", INCLUDE_DIR_SUFFIX, DIR_SEPARATOR_CHAR);
516     sprintf(pic16libDir, "%s%cpic16", LIB_DIR_SUFFIX, DIR_SEPARATOR_CHAR);
517
518
519     if(!options.nostdinc) {
520       /* setup pic16 include directory */
521       pic16incDirsSet = appendStrSet(dataDirsSet, NULL, pic16incDir);
522       includeDirsSet = pic16incDirsSet;
523 //      mergeSets(&includeDirsSet, pic16incDirsSet);
524     }
525     /* pic16 port should not search to the SDCC standard include directories,
526      * so add here the deleted include dirs that user has issued in command line */
527     mergeSets(&pic16incDirsSet, userIncDirsSet);
528
529     if(!options.nostdlib) {
530       /* setup pic16 library directory */
531       pic16libDirsSet = appendStrSet(dataDirsSet, NULL, pic16libDir);
532       libDirsSet = pic16libDirsSet;
533 //      mergeSets(&libDirsSet, pic16libDirsSet);
534     }
535
536     if(!pic16_options.nodefaultlibs) {
537       /* now add the library for the device */
538       sprintf(devlib, "%s.lib", pic16->name[2]);
539       addSet(&libFilesSet, Safe_strdup(devlib));
540
541       /* add the internal SDCC library */
542       addSet(&libFilesSet, Safe_strdup( "libsdcc.lib" ));
543     }
544 }
545
546 extern set *linkOptionsSet;
547 char *msprintf(hTab *pvals, const char *pformat, ...);
548 int my_system(const char *cmd);
549
550 /* custom function to link objects */
551 static void _pic16_linkEdit(void)
552 {
553   hTab *linkValues=NULL;
554   char lfrm[256];
555   char *lcmd;
556   char temp[128];
557   set *tSet=NULL;
558   int ret;
559   
560         /*
561          * link command format:
562          * {linker} {incdirs} {lflags} -o {outfile} {spec_ofiles} {ofiles} {libs}
563          *
564          */
565          
566         sprintf(lfrm, "{linker} {incdirs} {lflags} -o {outfile} {user_ofile} {spec_ofiles} {ofiles} {libs}");
567                  
568         shash_add(&linkValues, "linker", "gplink");
569
570         mergeSets(&tSet, libDirsSet);
571         mergeSets(&tSet, libPathsSet);
572         
573         shash_add(&linkValues, "incdirs", joinStrSet( appendStrSet(tSet, "-I\"", "\"")));
574         shash_add(&linkValues, "lflags", joinStrSet(linkOptionsSet));
575   
576         shash_add(&linkValues, "outfile", dstFileName);
577
578         if(fullSrcFileName) {
579                 sprintf(temp, "%s.o", dstFileName);
580 //              addSetHead(&relFilesSet, Safe_strdup(temp));
581                 shash_add(&linkValues, "user_ofile", temp);
582         }
583
584         if(!pic16_options.no_crt)
585           shash_add(&linkValues, "spec_ofiles", pic16_options.crt_name);
586
587         shash_add(&linkValues, "ofiles", joinStrSet(relFilesSet));
588
589         if(!libflags.ignore) {
590           if(libflags.want_libc)
591             addSet(&libFilesSet, Safe_strdup("libc18f.lib"));
592         
593           if(libflags.want_libm)
594             addSet(&libFilesSet, Safe_strdup("libm18f.lib"));
595         
596           if(libflags.want_libio) {
597             sprintf(temp, "libio%s.lib", pic16->name[1]);       /* build libio18f452.lib name */
598             addSet(&libFilesSet, Safe_strdup(temp));
599           }
600         
601           if(libflags.want_libdebug)
602             addSet(&libFilesSet, Safe_strdup("libdebug.lib"));
603         }
604
605         shash_add(&linkValues, "libs", joinStrSet(libFilesSet));
606         
607         lcmd = msprintf(linkValues, lfrm);
608          
609         ret = my_system( lcmd );
610          
611         Safe_free( lcmd );
612          
613         if(ret)
614                 exit(1);
615 }
616
617
618 /* forward declarations */
619 extern const char *pic16_linkCmd[];
620 extern const char *pic16_asmCmd[];
621 extern set *asmOptionsSet;
622
623 static void
624 _pic16_finaliseOptions (void)
625 {
626     port->mem.default_local_map = data;
627     port->mem.default_globl_map = data;
628
629     /* peepholes are disabled for the time being */
630     options.nopeep = 1;
631
632     /* explicit enable peepholes for testing */
633     if(pic16_enable_peeps)
634       options.nopeep = 0;
635
636     options.all_callee_saves = 1;               // always callee saves
637
638 #if 0
639     options.float_rent = 1;
640     options.intlong_rent = 1;
641 #endif
642         
643
644     if(alt_asm && strlen(alt_asm))
645       pic16_asmCmd[0] = alt_asm;
646         
647     if(alt_link && strlen(alt_link))
648       pic16_linkCmd[0] = alt_link;
649         
650     if(!pic16_options.no_crt) {
651       pic16_options.omit_ivt = 1;
652       pic16_options.leave_reset = 0;
653     }
654     
655     if(options.model == MODEL_SMALL)
656       addSet(&asmOptionsSet, Safe_strdup("-DSDCC_MODEL_SMALL"));
657     else
658     if(options.model == MODEL_LARGE)
659       addSet(&asmOptionsSet, Safe_strdup("-DSDCC_MODEL_LARGE"));
660     
661     if(STACK_MODEL_LARGE) {
662       addSet(&preArgvSet, Safe_strdup("-DSTACK_MODEL_LARGE"));
663       addSet(&asmOptionsSet, Safe_strdup("-DSTACK_MODEL_LARGE"));
664     } else {
665       addSet(&preArgvSet, Safe_strdup("-DSTACK_MODEL_SMALL"));
666       addSet(&asmOptionsSet, Safe_strdup("-DSTACK_MODEL_SMALL"));
667     }
668 }
669
670
671 #if 0
672   if (options.model == MODEL_LARGE)
673     {
674       port->mem.default_local_map = xdata;
675       port->mem.default_globl_map = xdata;
676     }
677   else
678     {
679       port->mem.default_local_map = data;
680       port->mem.default_globl_map = data;
681     }
682
683   if (options.stack10bit)
684     {
685       if (options.model != MODEL_FLAT24)
686         {
687           fprintf (stderr,
688                    "*** warning: 10 bit stack mode is only supported in flat24 model.\n");
689           fprintf (stderr, "\t10 bit stack mode disabled.\n");
690           options.stack10bit = 0;
691         }
692       else
693         {
694           /* Fixup the memory map for the stack; it is now in
695            * far space and requires a FPOINTER to access it.
696            */
697           istack->fmap = 1;
698           istack->ptrType = FPOINTER;
699         }
700     }
701 #endif
702
703
704 static void
705 _pic16_setDefaultOptions (void)
706 {
707   options.stackAuto = 0;                /* implicit declaration */
708   /* port is not capable yet to allocate separate registers 
709    * dedicated for passing certain parameters */
710   
711   /* initialize to defaults section locations, names and addresses */
712   pic16_sectioninfo.at_udata    = "udata";
713
714   /* set pic16 port options to defaults */
715   pic16_options.no_banksel = 0;
716   pic16_options.opt_banksel = 0;
717   pic16_options.omit_configw = 0;
718   pic16_options.omit_ivt = 0;
719   pic16_options.leave_reset = 0;
720   pic16_options.stack_model = 0;                        /* 0 for 'small', 1 for 'large' */
721   pic16_options.ivt_loc = 0x000000;
722   pic16_options.nodefaultlibs = 0;
723   pic16_options.dumpcalltree = 0;
724   pic16_options.crt_name = "crt0i.o";           /* the default crt to link */
725   pic16_options.no_crt = 0;                     /* use crt by default */
726   pic16_options.ip_stack = 1;           /* set to 1 to enable ipop/ipush for stack */
727   pic16_options.gstack = 0;
728   pic16_options.debgen = 0;
729 }
730
731 static const char *
732 _pic16_getRegName (struct regs *reg)
733 {
734   if (reg)
735     return reg->name;
736   return "err";
737 }
738
739
740 #if 1
741 static  char *_pic16_mangleFunctionName(char *sz)
742 {
743 //      fprintf(stderr, "mangled function name: %s\n", sz);
744
745   return sz;
746 }
747 #endif
748
749
750 static void
751 _pic16_genAssemblerPreamble (FILE * of)
752 {
753   char *name = pic16_processor_base_name();
754
755         if(!name) {
756                 name = "p18f452";
757                 fprintf(stderr,"WARNING: No Pic has been selected, defaulting to %s\n",name);
758         }
759
760         fprintf (of, "\tlist\tp=%s\n",&name[1]);
761
762         if(!pic16_options.omit_configw) {
763                 pic16_emitConfigRegs(of);
764                 fprintf(of, "\n");
765                 pic16_emitIDRegs(of);
766         }
767         
768   fprintf (of, "\tradix dec\n");
769 }
770
771 /* Generate interrupt vector table. */
772 static int
773 _pic16_genIVT (FILE * of, symbol ** interrupts, int maxInterrupts)
774 {
775 #if 1
776         /* PIC18F family has only two interrupts, the high and the low
777          * priority interrupts, which reside at 0x0008 and 0x0018 respectively - VR */
778
779         if((!pic16_options.omit_ivt) || (pic16_options.omit_ivt && pic16_options.leave_reset)) {
780                 fprintf(of, "; RESET vector\n");
781                 fprintf(of, "\tgoto\t__sdcc_gsinit_startup\n");
782         }
783         
784         if(!pic16_options.omit_ivt) {
785                 fprintf(of, "\tres 4\n");
786
787
788                 fprintf(of, "; High priority interrupt vector 0x0008\n");
789                 if(interrupts[1]) {
790                         fprintf(of, "\tgoto\t%s\n", interrupts[1]->rname);
791                         fprintf(of, "\tres\t12\n"); 
792                 } else {
793                         fprintf(of, "\tretfie\n");
794                         fprintf(of, "\tres\t14\n");
795                 }
796
797                 fprintf(of, "; Low priority interrupt vector 0x0018\n");
798                 if(interrupts[2]) {
799                         fprintf(of, "\tgoto\t%s\n", interrupts[2]->rname);
800                 } else {
801                         fprintf(of, "\tretfie\n");
802                 }
803         }
804 #endif
805   return TRUE;
806 }
807
808 /* return True if the port can handle the type,
809  * False to convert it to function call */
810 static bool _hasNativeMulFor (iCode *ic, sym_link *left, sym_link *right)
811 {
812 //      fprintf(stderr,"checking for native mult for %c (size: %d)\n", ic->op, getSize(OP_SYMBOL(IC_RESULT(ic))->type));
813
814 #if 1
815         /* multiplication is fixed */
816         /* support mul for char/int/long */
817         if((ic->op == '*')
818           && (getSize(OP_SYMBOL(IC_LEFT(ic))->type ) < 2))return TRUE;
819 #endif
820
821 #if 0
822         /* support div for char/int/long */
823         if((getSize(OP_SYMBOL(IC_LEFT(ic))->type ) < 0)
824                 && (ic->op == '/'))return TRUE;
825 #endif
826         
827   return FALSE;
828 }
829
830
831 #if 0
832 /* Do CSE estimation */
833 static bool cseCostEstimation (iCode *ic, iCode *pdic)
834 {
835 //    operand *result = IC_RESULT(ic);
836 //    sym_link *result_type = operandType(result);
837
838
839         /* VR -- this is an adhoc. Put here after conversation
840          * with Erik Epetrich */
841
842         if(ic->op == '<'
843                 || ic->op == '>'
844                 || ic->op == EQ_OP) {
845
846                 fprintf(stderr, "%d %s\n", __LINE__, __FUNCTION__);
847           return 0;
848         }
849
850 #if 0
851     /* if it is a pointer then return ok for now */
852     if (IC_RESULT(ic) && IS_PTR(result_type)) return 1;
853
854     /* if bitwise | add & subtract then no since mcs51 is pretty good at it
855        so we will cse only if they are local (i.e. both ic & pdic belong to
856        the same basic block */
857     if (IS_BITWISE_OP(ic) || ic->op == '+' || ic->op == '-') {
858         /* then if they are the same Basic block then ok */
859         if (ic->eBBlockNum == pdic->eBBlockNum) return 1;
860         else return 0;
861     }
862 #endif
863
864     /* for others it is cheaper to do the cse */
865     return 1;
866 }
867 #endif
868
869
870 /* Indicate which extended bit operations this port supports */
871 static bool
872 hasExtBitOp (int op, int size)
873 {
874   if (op == RRC
875       || op == RLC
876       /* || op == GETHBIT */ /* GETHBIT doesn't look complete for PIC */
877      )
878     return TRUE;
879   else
880     return FALSE;
881 }
882
883 /* Indicate the expense of an access to an output storage class */
884 static int
885 oclsExpense (struct memmap *oclass)
886 {
887   /* The IN_FARSPACE test is compatible with historical behaviour, */
888   /* but I don't think it is applicable to PIC. If so, please feel */
889   /* free to remove this test -- EEP */
890   if (IN_FARSPACE(oclass))
891     return 1;
892     
893   return 0;
894 }
895
896 /** $1 is the input object file (PIC16 specific)        // >>always the basename<<.
897     $2 is always the output file.
898     $3 -L path and -l libraries
899     $l is the list of extra options that should be there somewhere...
900     MUST be terminated with a NULL.
901 */
902 const char *pic16_linkCmd[] =
903 {
904   "gplink", "$l", "-o \"$2\"", "\"$1\"","$3", NULL
905 };
906
907
908
909 /** $1 is always the basename.
910     $2 is always the output file.
911     $3 varies (nothing currently)
912     $l is the list of extra options that should be there somewhere...
913     MUST be terminated with a NULL.
914 */
915 const char *pic16_asmCmd[] =
916 {
917   "gpasm", "$l", "$3", "-c", "\"$1.asm\"", "-o \"$2\"", NULL
918
919 };
920
921 /* Globals */
922 PORT pic16_port =
923 {
924   TARGET_ID_PIC16,
925   "pic16",
926   "MCU PIC16",                  /* Target name */
927   "p18f452",                    /* Processor */
928   {
929     pic16glue,
930     TRUE,                       /* Emit glue around main */
931     MODEL_SMALL | MODEL_LARGE | MODEL_FLAT24,
932     MODEL_SMALL
933   },
934   {
935     pic16_asmCmd,               /* assembler command and arguments */
936     NULL,                       /* alternate macro based form */
937     "-g",                       /* arguments for debug mode */
938     NULL,                       /* arguments for normal mode */
939     0,                          /* print externs as global */
940     ".asm",                     /* assembler file extension */
941     NULL                        /* no do_assemble function */
942   },
943   {
944     NULL,                       //    pic16_linkCmd,            /* linker command and arguments */
945     NULL,                       /* alternate macro based form */
946     _pic16_linkEdit,            //NULL,                 /* no do_link function */
947     ".o",                       /* extension for object files */
948     0                           /* no need for linker file */
949   },
950   {
951     _defaultRules
952   },
953   {
954         /* Sizes */
955     1,          /* char */
956     2,          /* short */
957     2,          /* int */
958     4,          /* long */
959     2,          /* ptr */
960     3,          /* fptr, far pointers (see Microchip) */
961     3,          /* gptr */
962     1,          /* bit */
963     4,          /* float */
964     4           /* max */
965   },
966   {
967     "XSEG    (XDATA)",          // xstack
968     "STACK   (DATA)",           // istack
969     "CSEG    (CODE)",           // code
970     "DSEG    (DATA)",           // data
971     "ISEG    (DATA)",           // idata
972     "PSEG    (DATA)",           // pdata
973     "XSEG    (XDATA)",          // xdata
974     "BSEG    (BIT)",            // bit
975     "RSEG    (DATA)",           // reg
976     "GSINIT  (CODE)",           // static
977     "OSEG    (OVR,DATA)",       // overlay
978     "GSFINAL (CODE)",           // post static
979     "HOME    (CODE)",   // home
980     NULL,                       // xidata
981     NULL,                       // xinit
982     NULL,                       // default location for auto vars
983     NULL,                       // default location for global vars
984     1                           // code is read only 1=yes
985   },
986   {
987     NULL,               /* genExtraAreaDeclaration */
988     NULL                /* genExatrAreaLinkOptions */
989   },
990   {
991         /* stack related information */
992     -1,                 /* -1 stack grows downwards, +1 upwards */
993     1,                  /* extra overhead when calling between banks */
994     4,                  /* extra overhead when the function is an ISR */
995     1,                  /* extra overhead for a function call */
996     1,                  /* re-entrant space */
997     0                   /* 'banked' call overhead, mild overlap with bank_overhead */
998   },
999     /* pic16 has an 8 bit mul */
1000   {
1001      0, -1
1002   },
1003   {
1004     pic16_emitDebuggerSymbol
1005   },
1006   {
1007     255/3,      /* maxCount */
1008     3,          /* sizeofElement */
1009     /* The rest of these costs are bogus. They approximate */
1010     /* the behavior of src/SDCCicode.c 1.207 and earlier.  */
1011     {4,4,4},    /* sizeofMatchJump[] */
1012     {0,0,0},    /* sizeofRangeCompare[] */
1013     0,          /* sizeofSubtract */
1014     3,          /* sizeofDispatch */
1015   },
1016   "_",
1017   _pic16_init,
1018   _pic16_parseOptions,
1019   pic16_optionsTable,
1020   _pic16_initPaths,
1021   _pic16_finaliseOptions,
1022   _pic16_setDefaultOptions,
1023   pic16_assignRegisters,
1024   _pic16_getRegName,
1025   _pic16_keywords,
1026   _pic16_genAssemblerPreamble,
1027   NULL,                         /* no genAssemblerEnd */
1028   _pic16_genIVT,
1029   NULL, // _pic16_genXINIT
1030   NULL,                         /* genInitStartup */
1031   _pic16_reset_regparm,
1032   _pic16_regparm,
1033   _process_pragma,                              /* process a pragma */
1034   _pic16_mangleFunctionName,                            /* mangles function name */
1035   _hasNativeMulFor,
1036   hasExtBitOp,                  /* hasExtBitOp */
1037   oclsExpense,                  /* oclsExpense */
1038   FALSE,                        
1039   TRUE,                         /* little endian */
1040   0,                            /* leave lt */
1041   0,                            /* leave gt */
1042   1,                            /* transform <= to ! > */
1043   1,                            /* transform >= to ! < */
1044   1,                            /* transform != to !(a == b) */
1045   0,                            /* leave == */
1046   FALSE,                        /* No array initializer support. */
1047   0,    //cseCostEstimation,            /* !!!no CSE cost estimation yet */
1048   NULL,                         /* no builtin functions */
1049   GPOINTER,                     /* treat unqualified pointers as "generic" pointers */
1050   1,                            /* reset labelKey to 1 */
1051   1,                            /* globals & local static allowed */
1052   PORT_MAGIC
1053 };