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