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