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