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