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