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