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