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