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