* src/SDCCsymt.c: fixed (hopeful properly) bug
[fw/sdcc] / src / SDCCsymt.c
1 /*-------------------------------------------------------------------------
2   SDCCsymt.c - Code file for Symbols table related structures and MACRO's.
3         Written By -  Sandeep Dutta . sandeep.dutta@usa.net (1998)
4
5    This program is free software; you can redistribute it and/or modify it
6    under the terms of the GNU General Public License as published by the
7    Free Software Foundation; either version 2, or (at your option) any
8    later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18
19    In other words, you are welcome to use, share and improve this program.
20    You are forbidden to forbid anyone else to use, share and improve
21    what you give them.   Help stamp out software-hoarding!
22 -------------------------------------------------------------------------*/
23
24 #include "common.h"
25 #include "newalloc.h"
26 #include "dbuf_string.h"
27
28 #include "SDCCsymt.h"
29
30 value *aggregateToPointer (value *val);
31 void printTypeChainRaw (sym_link * start, FILE * of);
32
33 void printFromToType(sym_link *from, sym_link *to) {
34   fprintf (stderr, "from type '");
35   printTypeChain (from, stderr);
36   fprintf (stderr, "'\nto type '");
37   printTypeChain (to, stderr);
38   fprintf (stderr, "'\n");
39 }
40
41 /* noun strings */
42 char *nounName(sym_link *sl) {
43   switch (SPEC_NOUN(sl))
44     {
45     case V_INT: {
46       if (SPEC_LONG(sl)) return "long";
47       if (SPEC_SHORT(sl)) return "short";
48       return "int";
49     }
50     case V_FLOAT: return "float";
51     case V_FIXED16X16: return "fixed16x16";
52     case V_CHAR: return "char";
53     case V_VOID: return "void";
54     case V_STRUCT: return "struct";
55     case V_LABEL: return "label";
56     case V_BITFIELD: return "bitfield";
57     case V_BIT: return "bit";
58     case V_SBIT: return "sbit";
59     case V_DOUBLE: return "double";
60     }
61   return "unknown";
62 };
63
64 bucket *SymbolTab[256];         /* the symbol    table  */
65 bucket *StructTab[256];         /* the structure table  */
66 bucket *TypedefTab[256];        /* the typedef   table  */
67 bucket *LabelTab[256];          /* the Label     table  */
68 bucket *enumTab[256];           /* enumerated    table  */
69
70 /*------------------------------------------------------------------*/
71 /* initSymt () - initialises symbol table related stuff             */
72 /*------------------------------------------------------------------*/
73 void
74 initSymt ()
75 {
76   int i = 0;
77
78   for (i = 0; i < 256; i++)
79     SymbolTab[i] = StructTab[i] = (void *) NULL;
80
81
82 }
83 /*-----------------------------------------------------------------*/
84 /* newBucket - allocates & returns a new bucket        */
85 /*-----------------------------------------------------------------*/
86 bucket *
87 newBucket ()
88 {
89   bucket *bp;
90
91   bp = Safe_alloc ( sizeof (bucket));
92
93   return bp;
94 }
95
96 /*-----------------------------------------------------------------*/
97 /* hashKey - computes the hashkey given a symbol name              */
98 /*-----------------------------------------------------------------*/
99 int
100 hashKey (const char *s)
101 {
102   unsigned long key = 0;
103
104   while (*s)
105     key += *s++;
106   return key % 256;
107 }
108
109 /*-----------------------------------------------------------------*/
110 /* addSym - adds a symbol to the hash Table                        */
111 /*-----------------------------------------------------------------*/
112 void
113 addSym (bucket ** stab,
114         void *sym,
115         char *sname,
116         int level,
117         int block,
118         int checkType)
119 {
120   int i;                        /* index into the hash Table */
121   bucket *bp;                   /* temp bucket    *         */
122
123   if (checkType) {
124     symbol *csym = (symbol *)sym;
125
126     if (getenv("DEBUG_SANITY")) {
127       fprintf (stderr, "addSym: %s ", sname);
128     }
129     /* make sure the type is complete and sane */
130     checkTypeSanity(csym->etype, csym->name);
131   }
132
133   /* prevent overflow of the (r)name buffers */
134   if (strlen(sname)>SDCC_SYMNAME_MAX) {
135     werror (W_SYMBOL_NAME_TOO_LONG, SDCC_SYMNAME_MAX);
136     sname[SDCC_SYMNAME_MAX]='\0';
137   }
138
139   /* the symbols are always added at the head of the list  */
140   i = hashKey (sname);
141   /* get a free entry */
142   bp = Safe_alloc ( sizeof (bucket));
143
144   bp->sym = sym;                /* update the symbol pointer  */
145   bp->level = level;            /* update the nest level      */
146   bp->block = block;
147   strncpyz (bp->name, sname, sizeof(bp->name)); /* copy the name into place */
148
149   /* if this is the first entry */
150   if (stab[i] == NULL)
151     {
152       bp->prev = bp->next = (void *) NULL;      /* point to nothing */
153       stab[i] = bp;
154     }
155   /* not first entry then add @ head of list */
156   else
157     {
158       bp->prev = NULL;
159       stab[i]->prev = bp;
160       bp->next = stab[i];
161       stab[i] = bp;
162     }
163 }
164
165 /*-----------------------------------------------------------------*/
166 /* deleteSym - deletes a symbol from the hash Table  entry     */
167 /*-----------------------------------------------------------------*/
168 void
169 deleteSym (bucket ** stab, void *sym, char *sname)
170 {
171   int i = 0;
172   bucket *bp;
173
174   i = hashKey (sname);
175
176   bp = stab[i];
177   /* find the symbol */
178   while (bp)
179     {
180       if (bp->sym == sym)       /* found it then break out */
181         break;                  /* of the loop       */
182       bp = bp->next;
183     }
184
185   if (!bp)                      /* did not find it */
186     return;
187   /* if this is the first one in the chain */
188   if (!bp->prev)
189     {
190       stab[i] = bp->next;
191       if (stab[i])              /* if chain ! empty */
192         stab[i]->prev = (void *) NULL;
193     }
194   /* middle || end of chain */
195   else
196     {
197       if (bp->next)             /* if not end of chain */
198         bp->next->prev = bp->prev;
199
200       bp->prev->next = bp->next;
201     }
202
203 }
204
205 /*-----------------------------------------------------------------*/
206 /* findSym - finds a symbol in a table           */
207 /*-----------------------------------------------------------------*/
208 void *
209 findSym (bucket ** stab, void *sym, const char *sname)
210 {
211   bucket *bp;
212
213   bp = stab[hashKey (sname)];
214   while (bp)
215     {
216       if (bp->sym == sym || strcmp (bp->name, sname) == 0)
217         break;
218       bp = bp->next;
219     }
220
221   return (bp ? bp->sym : (void *) NULL);
222 }
223
224 /*-----------------------------------------------------------------*/
225 /* findSymWithLevel - finds a symbol with a name & level           */
226 /*-----------------------------------------------------------------*/
227 void *
228 findSymWithLevel (bucket ** stab, symbol * sym)
229 {
230   bucket *bp;
231
232   bp = stab[hashKey (sym->name)];
233
234   /**
235    **  do the search from the head of the list since the
236    **  elements are added at the head it is ensured that
237    ** we will find the deeper definitions before we find
238    ** the global ones. we need to check for symbols with
239    ** level <= to the level given, if levels match then block
240    ** numbers need to match as well
241    **/
242   while (bp)
243     {
244       if (strcmp (bp->name, sym->name) == 0 && bp->level <= sym->level)
245         {
246           /* if this is parameter then nothing else need to be checked */
247           if (((symbol *) (bp->sym))->_isparm)
248             return (bp->sym);
249           /* if levels match then block numbers should also match */
250           if (bp->level && bp->level == sym->level && bp->block == sym->block)
251             return (bp->sym);
252           /* if levels don't match then we are okay */
253           if (bp->level && bp->level != sym->level && bp->block <= sym->block)
254             return (bp->sym);
255           /* if this is a global variable then we are ok too */
256           if (bp->level == 0)
257             return (bp->sym);
258         }
259
260       bp = bp->next;
261     }
262
263   return (void *) NULL;
264 }
265
266 /*-----------------------------------------------------------------*/
267 /* findSymWithBlock - finds a symbol with name in with a block     */
268 /*-----------------------------------------------------------------*/
269 void *
270 findSymWithBlock (bucket ** stab, symbol * sym, int block)
271 {
272   bucket *bp;
273
274   bp = stab[hashKey (sym->name)];
275   while (bp)
276     {
277       if (strcmp (bp->name, sym->name) == 0 &&
278           bp->block <= block)
279         break;
280       bp = bp->next;
281     }
282
283   return (bp ? bp->sym : (void *) NULL);
284 }
285
286 /*------------------------------------------------------------------*/
287 /* newSymbol () - returns a new pointer to a symbol                 */
288 /*------------------------------------------------------------------*/
289 symbol *
290 newSymbol (char *name, int scope)
291 {
292   symbol *sym;
293
294   sym = Safe_alloc ( sizeof (symbol));
295
296   strncpyz (sym->name, name, sizeof(sym->name)); /* copy the name */
297   sym->level = scope;           /* set the level */
298   sym->block = currBlockno;
299   sym->lineDef = lexLineno;    /* set the line number */
300   sym->fileDef = lexFilename;
301   return sym;
302 }
303
304 /*------------------------------------------------------------------*/
305 /* newLink - creates a new link (declarator,specifier)              */
306 /*------------------------------------------------------------------*/
307 sym_link *
308 newLink (SYM_LINK_CLASS select)
309 {
310   sym_link *p;
311
312   p = Safe_alloc ( sizeof (sym_link));
313   p->class=select;
314
315   return p;
316 }
317
318 /*------------------------------------------------------------------*/
319 /* newStruct - creats a new structdef from the free list            */
320 /*------------------------------------------------------------------*/
321 structdef *
322 newStruct (char *tag)
323 {
324   structdef *s;
325
326   s = Safe_alloc ( sizeof (structdef));
327
328   strncpyz (s->tag, tag, sizeof(s->tag));               /* copy the tag */
329   return s;
330 }
331
332 /*------------------------------------------------------------------*/
333 /* sclsFromPtr - Return the storage class a pointer points into.    */
334 /*               S_FIXED is returned for generic pointers or other  */
335 /*               unexpected cases                                   */
336 /*------------------------------------------------------------------*/
337 STORAGE_CLASS
338 sclsFromPtr(sym_link *ptr)
339 {
340   switch (DCL_TYPE (ptr))
341     {
342     case POINTER:
343       return S_DATA;
344     case GPOINTER:
345       return S_FIXED;
346     case FPOINTER:
347       return S_XDATA;
348     case CPOINTER:
349       return S_CODE;
350     case IPOINTER:
351       return S_IDATA;
352     case PPOINTER:
353       return S_PDATA;
354     case EEPPOINTER:
355       return S_EEPROM;
356     case FUNCTION:
357       return S_CODE;
358     default:
359       return S_FIXED;
360     }
361 }
362
363 /*------------------------------------------------------------------*/
364 /* pointerTypes - do the computation for the pointer types          */
365 /*------------------------------------------------------------------*/
366 void
367 pointerTypes (sym_link * ptr, sym_link * type)
368 {
369   if (IS_SPEC (ptr))
370     return;
371
372   /* find the first pointer type */
373   while (ptr && !IS_PTR (ptr))
374     ptr = ptr->next;
375
376   /* could not find it */
377   if (!ptr || IS_SPEC (ptr))
378     return;
379
380   if (IS_PTR(ptr) && DCL_TYPE(ptr)!=UPOINTER) {
381     pointerTypes (ptr->next, type);
382     return;
383   }
384
385   /* change the pointer type depending on the
386      storage class of the type */
387   if (IS_SPEC (type))
388     {
389       switch (SPEC_SCLS (type))
390         {
391         case S_XDATA:
392           DCL_TYPE (ptr) = FPOINTER;
393           break;
394         case S_IDATA:
395           DCL_TYPE (ptr) = IPOINTER;
396           break;
397         case S_PDATA:
398           DCL_TYPE (ptr) = PPOINTER;
399           break;
400         case S_DATA:
401           DCL_TYPE (ptr) = POINTER;
402           break;
403         case S_CODE:
404           DCL_TYPE (ptr) = CPOINTER;
405           break;
406         case S_EEPROM:
407           DCL_TYPE (ptr) = EEPPOINTER;
408           break;
409         default:
410           DCL_TYPE (ptr) = port->unqualified_pointer;
411           break;
412         }
413       /* the storage class of type ends here */
414       SPEC_SCLS (type) = 0;
415     }
416
417   /* now change all the remaining unknown pointers
418      to generic pointers */
419   while (ptr)
420     {
421       if (!IS_SPEC (ptr) && DCL_TYPE (ptr) == UPOINTER)
422         DCL_TYPE (ptr) = port->unqualified_pointer;
423       ptr = ptr->next;
424     }
425
426   /* same for the type although it is highly unlikely that
427      type will have a pointer */
428   while (type)
429     {
430       if (!IS_SPEC (type) && DCL_TYPE (type) == UPOINTER)
431         DCL_TYPE (type) = port->unqualified_pointer;
432       type = type->next;
433     }
434 }
435
436 /*------------------------------------------------------------------*/
437 /* addDecl - adds a declarator @ the end of a chain                 */
438 /*------------------------------------------------------------------*/
439 void
440 addDecl (symbol * sym, int type, sym_link * p)
441 {
442   static sym_link *empty = NULL;
443   sym_link *head;
444   sym_link *tail;
445   sym_link *t;
446
447   if (getenv("SDCC_DEBUG_FUNCTION_POINTERS"))
448     fprintf (stderr, "SDCCsymt.c:addDecl(%s,%d,%p)\n", sym->name, type, p);
449
450   if (empty == NULL)
451     empty = newLink(SPECIFIER);
452
453   /* if we are passed a link then set head & tail */
454   if (p)
455     {
456       tail = head = p;
457       while (tail->next)
458         tail = tail->next;
459     }
460   else
461     {
462       head = tail = newLink (DECLARATOR);
463       DCL_TYPE (head) = type;
464     }
465
466   /* if this is the first entry   */
467   if (!sym->type)
468     {
469       sym->type = head;
470       sym->etype = tail;
471     }
472   else if (IS_SPEC (sym->etype) && IS_SPEC (head) && head == tail)
473     {
474       sym->etype = mergeSpec (sym->etype, head, sym->name);
475     }
476   else if (IS_SPEC (sym->etype) && !IS_SPEC (head) && head == tail)
477     {
478       t = sym->type;
479       while (t->next != sym->etype)
480         t = t->next;
481       t->next = head;
482       tail->next = sym->etype;
483     }
484   else if (IS_FUNC (sym->type) && IS_SPEC (sym->type->next) &&
485            !memcmp(sym->type->next, empty, sizeof(sym_link)))
486     {
487       sym->type->next = head;
488       sym->etype = tail;
489     }
490   else
491     {
492       sym->etype->next = head;
493       sym->etype = tail;
494     }
495
496   /* if the type is an unknown pointer and has
497      a tspec then take the storage class const & volatile
498      attribute from the tspec & make it those of this
499      symbol */
500   if (p &&
501       !IS_SPEC (p) &&
502       //DCL_TYPE (p) == UPOINTER &&
503       DCL_TSPEC (p))
504     {
505       if (!IS_SPEC (sym->etype))
506         {
507           sym->etype = sym->etype->next = newLink (SPECIFIER);
508         }
509       SPEC_SCLS (sym->etype) = SPEC_SCLS (DCL_TSPEC (p));
510       DCL_TSPEC (p) = NULL;
511     }
512
513   // if there is a function in this type chain
514   if (p && funcInChain(sym->type)) {
515     processFuncArgs (sym);
516   }
517
518   return;
519 }
520
521 /*------------------------------------------------------------------
522   checkTypeSanity: prevent the user from doing e.g.:
523   unsigned float uf;
524   ------------------------------------------------------------------*/
525 void checkTypeSanity(sym_link *etype, char *name) {
526   char *noun;
527
528   if (!etype) {
529     if (getenv("DEBUG_SANITY")) {
530       fprintf (stderr, "sanity check skipped for %s (etype==0)\n", name);
531     }
532     return;
533   }
534
535   if (!IS_SPEC(etype)) {
536     if (getenv("DEBUG_SANITY")) {
537       fprintf (stderr, "sanity check skipped for %s (!IS_SPEC)\n", name);
538     }
539     return;
540   }
541
542   noun=nounName(etype);
543
544   if (getenv("DEBUG_SANITY")) {
545     fprintf (stderr, "checking sanity for %s %p\n", name, etype);
546   }
547
548   if ((SPEC_NOUN(etype)==V_CHAR ||
549        SPEC_NOUN(etype)==V_FLOAT ||
550        SPEC_NOUN(etype)==V_FIXED16X16 ||
551        SPEC_NOUN(etype)==V_DOUBLE ||
552        SPEC_NOUN(etype)==V_VOID) &&
553       (SPEC_SHORT(etype) || SPEC_LONG(etype))) {
554     // long or short for char float double or void
555     werror (E_LONG_OR_SHORT_INVALID, noun, name);
556   }
557   if ((SPEC_NOUN(etype)==V_FLOAT ||
558        SPEC_NOUN(etype)==V_FIXED16X16 ||
559        SPEC_NOUN(etype)==V_DOUBLE ||
560        SPEC_NOUN(etype)==V_VOID) &&
561       (etype->select.s.b_signed || SPEC_USIGN(etype))) {
562     // signed or unsigned for float double or void
563     werror (E_SIGNED_OR_UNSIGNED_INVALID, noun, name);
564   }
565
566   // special case for "short"
567   if (SPEC_SHORT(etype)) {
568     SPEC_NOUN(etype) = options.shortis8bits ? V_CHAR : V_INT;
569     SPEC_SHORT(etype) = 0;
570   }
571
572   /* if no noun e.g.
573      "const a;" or "data b;" or "signed s" or "long l"
574      assume an int */
575   if (!SPEC_NOUN(etype)) {
576     SPEC_NOUN(etype)=V_INT;
577   }
578
579   /* ISO/IEC 9899 J.3.9 implementation defined behaviour: */
580   /* a "plain" int bitfield is unsigned */
581   if (SPEC_NOUN(etype)==V_BIT ||
582       SPEC_NOUN(etype)==V_SBIT) {
583     if (!etype->select.s.b_signed)
584       SPEC_USIGN(etype) = 1;
585   }
586
587   if (etype->select.s.b_signed && SPEC_USIGN(etype)) {
588     // signed AND unsigned
589     werror (E_SIGNED_AND_UNSIGNED_INVALID, noun, name);
590   }
591   if (SPEC_SHORT(etype) && SPEC_LONG(etype)) {
592     // short AND long
593     werror (E_LONG_AND_SHORT_INVALID, noun, name);
594   }
595
596 }
597
598 /*------------------------------------------------------------------*/
599 /* mergeSpec - merges two specifiers and returns the new one        */
600 /*------------------------------------------------------------------*/
601 sym_link *
602 mergeSpec (sym_link * dest, sym_link * src, char *name)
603 {
604   if (!IS_SPEC(dest) || !IS_SPEC(src)) {
605 #if 0
606     werror (E_INTERNAL_ERROR, __FILE__, __LINE__, "cannot merge declarator");
607     exit (1);
608 #else
609     werror (E_SYNTAX_ERROR, yytext);
610     // the show must go on
611     return newIntLink();
612 #endif
613   }
614
615   if (SPEC_NOUN(src)) {
616     if (!SPEC_NOUN(dest)) {
617       SPEC_NOUN(dest)=SPEC_NOUN(src);
618     } else {
619       /* we shouldn't redeclare the type */
620       if (getenv("DEBUG_SANITY")) {
621         fprintf (stderr, "mergeSpec: ");
622       }
623       werror(E_TWO_OR_MORE_DATA_TYPES, name);
624     }
625   }
626
627   if (SPEC_SCLS(src)) {
628     /* if destination has no storage class */
629     if (!SPEC_SCLS (dest) || SPEC_SCLS(dest)==S_REGISTER) {
630       SPEC_SCLS (dest) = SPEC_SCLS (src);
631     } else {
632       if (getenv("DEBUG_SANITY")) {
633         fprintf (stderr, "mergeSpec: ");
634       }
635       werror(E_TWO_OR_MORE_STORAGE_CLASSES, name);
636     }
637   }
638
639   /* copy all the specifications  */
640
641   // we really should do:
642 #if 0
643   if (SPEC_what(src)) {
644     if (SPEC_what(dest)) {
645       werror(W_DUPLICATE_SPEC, "what");
646     }
647     SPEC_what(dst)|=SPEC_what(src);
648   }
649 #endif
650   // but there are more important thing right now
651
652   SPEC_LONG (dest) |= SPEC_LONG (src);
653   SPEC_SHORT(dest) |= SPEC_SHORT(src);
654   SPEC_USIGN (dest) |= SPEC_USIGN (src);
655   dest->select.s.b_signed|=src->select.s.b_signed;
656   SPEC_STAT (dest) |= SPEC_STAT (src);
657   SPEC_EXTR (dest) |= SPEC_EXTR (src);
658   SPEC_INLINE (dest) |= SPEC_INLINE (src);
659   SPEC_CONST(dest) |= SPEC_CONST (src);
660   SPEC_ABSA (dest) |= SPEC_ABSA (src);
661   SPEC_VOLATILE (dest) |= SPEC_VOLATILE (src);
662   SPEC_RESTRICT (dest) |= SPEC_RESTRICT (src);
663   SPEC_ADDR (dest) |= SPEC_ADDR (src);
664   SPEC_OCLS (dest) = SPEC_OCLS (src);
665   SPEC_BLEN (dest) |= SPEC_BLEN (src);
666   SPEC_BSTR (dest) |= SPEC_BSTR (src);
667   SPEC_TYPEDEF (dest) |= SPEC_TYPEDEF (src);
668   SPEC_ENUM (dest) |= SPEC_ENUM (src);
669   if (SPEC_ARGREG(src) && !SPEC_ARGREG(dest))
670       SPEC_ARGREG(dest) = SPEC_ARGREG(src);
671
672   if (IS_STRUCT (dest) && SPEC_STRUCT (dest) == NULL)
673     SPEC_STRUCT (dest) = SPEC_STRUCT (src);
674
675   /* these are the only function attributes that will be set
676      in a specifier while parsing */
677   FUNC_NONBANKED(dest) |= FUNC_NONBANKED(src);
678   FUNC_BANKED(dest) |= FUNC_BANKED(src);
679   FUNC_ISCRITICAL(dest) |= FUNC_ISCRITICAL(src);
680   FUNC_ISREENT(dest) |= FUNC_ISREENT(src);
681   FUNC_ISNAKED(dest) |= FUNC_ISNAKED(src);
682   FUNC_ISISR(dest) |= FUNC_ISISR(src);
683   FUNC_ISJAVANATIVE(dest) |= FUNC_ISJAVANATIVE(src);
684   FUNC_ISBUILTIN(dest) |= FUNC_ISBUILTIN(src);
685   FUNC_ISOVERLAY(dest) |= FUNC_ISOVERLAY(src);
686   FUNC_INTNO(dest) |= FUNC_INTNO(src);
687   FUNC_REGBANK(dest) |= FUNC_REGBANK(src);
688   FUNC_ISINLINE (dest) |= FUNC_ISINLINE (src);
689
690   return dest;
691 }
692
693 /*------------------------------------------------------------------*/
694 /* genSymName - generates and returns a name used for anonymous vars */
695 /*------------------------------------------------------------------*/
696 char *
697 genSymName (int level)
698 {
699   static int gCount = 0;
700   static char gname[SDCC_NAME_MAX + 1];
701
702   SNPRINTF (gname, sizeof(gname), "__%04d%04d", level, gCount++);
703   return gname;
704 }
705
706 /*------------------------------------------------------------------*/
707 /* getSpec - returns the specifier part from a declaration chain    */
708 /*------------------------------------------------------------------*/
709 sym_link *
710 getSpec (sym_link * p)
711 {
712   sym_link *loop;
713
714   loop = p;
715   while (p && !(IS_SPEC (p)))
716     p = p->next;
717
718   return p;
719 }
720
721 /*------------------------------------------------------------------*/
722 /* newCharLink() - creates an char type                             */
723 /*------------------------------------------------------------------*/
724 sym_link *
725 newCharLink ()
726 {
727   sym_link *p;
728
729   p = newLink (SPECIFIER);
730   SPEC_NOUN (p) = V_CHAR;
731
732   return p;
733 }
734
735 /*------------------------------------------------------------------*/
736 /* newFloatLink - a new Float type                                  */
737 /*------------------------------------------------------------------*/
738 sym_link *
739 newFloatLink ()
740 {
741   sym_link *p;
742
743   p = newLink (SPECIFIER);
744   SPEC_NOUN (p) = V_FLOAT;
745
746   return p;
747 }
748
749 /*------------------------------------------------------------------*/
750 /* newFixed16x16Link - a new Float type                                  */
751 /*------------------------------------------------------------------*/
752 sym_link *
753 newFixed16x16Link ()
754 {
755   sym_link *p;
756
757   p = newLink (SPECIFIER);
758   SPEC_NOUN (p) = V_FIXED16X16;
759
760   return p;
761 }
762
763 /*------------------------------------------------------------------*/
764 /* newLongLink() - new long type                                    */
765 /*------------------------------------------------------------------*/
766 sym_link *
767 newLongLink ()
768 {
769   sym_link *p;
770
771   p = newLink (SPECIFIER);
772   SPEC_NOUN (p) = V_INT;
773   SPEC_LONG (p) = 1;
774
775   return p;
776 }
777
778 /*------------------------------------------------------------------*/
779 /* newIntLink() - creates an int type                               */
780 /*------------------------------------------------------------------*/
781 sym_link *
782 newIntLink ()
783 {
784   sym_link *p;
785
786   p = newLink (SPECIFIER);
787   SPEC_NOUN (p) = V_INT;
788
789   return p;
790 }
791
792 /*------------------------------------------------------------------*/
793 /* newBoolLink() - creates an bool type                             */
794 /*------------------------------------------------------------------*/
795 sym_link *
796 newBoolLink ()
797 {
798   sym_link *p;
799
800   p = newLink (SPECIFIER);
801   SPEC_NOUN (p) = V_BIT;
802
803   return p;
804 }
805
806 /*------------------------------------------------------------------*/
807 /* getSize - returns size of a type chain in bytes                  */
808 /*------------------------------------------------------------------*/
809 unsigned int
810 getSize (sym_link * p)
811 {
812   /* if nothing return 0 */
813   if (!p)
814     return 0;
815   if (IS_SPEC (p))
816     {                           /* if this is the specifier then */
817       switch (SPEC_NOUN (p))
818         {                       /* depending on the specifier type */
819         case V_INT:
820           return (IS_LONG (p) ? LONGSIZE : INTSIZE);
821         case V_FLOAT:
822           return FLOATSIZE;
823         case V_FIXED16X16:
824           return (4);
825         case V_CHAR:
826           return CHARSIZE;
827         case V_VOID:
828           return 0;
829         case V_STRUCT:
830           return SPEC_STRUCT (p)->size;
831         case V_LABEL:
832           return 0;
833         case V_SBIT:
834         case V_BIT:
835           return BITSIZE;
836         case V_BITFIELD:
837           return ((SPEC_BLEN (p) / 8) + (SPEC_BLEN (p) % 8 ? 1 : 0));
838         default:
839           return 0;
840         }
841     }
842
843   /* this is a declarator */
844   switch (DCL_TYPE (p))
845     {
846     case ARRAY:
847       if (DCL_ELEM(p)) {
848         return DCL_ELEM (p) * getSize (p->next);
849       } else {
850           //    werror (E_INTERNAL_ERROR, __FILE__, __LINE__,
851           //    "can not tell the size of an array[]");
852         return 0;
853       }
854     case IPOINTER:
855     case PPOINTER:
856     case POINTER:
857       return (PTRSIZE);
858     case EEPPOINTER:
859     case FPOINTER:
860     case CPOINTER:
861     case FUNCTION:
862       return (IFFUNC_BANKED (p) ? GPTRSIZE : FPTRSIZE);
863     case GPOINTER:
864       return (GPTRSIZE);
865
866     default:
867       return 0;
868     }
869 }
870
871 /*------------------------------------------------------------------*/
872 /* checkStructFlexArray - check tree behind a struct                */
873 /*------------------------------------------------------------------*/
874 static bool
875 checkStructFlexArray (symbol *sym, sym_link *p)
876 {
877   /* if nothing return FALSE */
878   if (!p)
879     return FALSE;
880
881   if (IS_SPEC (p))
882     {
883       /* (nested) struct with flexible array member? */
884       if (IS_STRUCT (p) && SPEC_STRUCT (p)->b_flexArrayMember)
885         {
886           werror (W_INVALID_FLEXARRAY);
887           return FALSE;
888         }
889       return FALSE;
890     }
891
892   /* this is a declarator */
893   if (IS_ARRAY (p))
894     {
895       /* flexible array member? */
896       if (!DCL_ELEM(p))
897         {
898           if (!options.std_c99)
899             werror (W_C89_NO_FLEXARRAY);
900           return TRUE;
901         }
902       /* walk tree */
903       return checkStructFlexArray (sym, p->next);
904     }
905   return FALSE;
906 }
907
908 /*------------------------------------------------------------------*/
909 /* bitsForType - returns # of bits required to store this type      */
910 /*------------------------------------------------------------------*/
911 unsigned int
912 bitsForType (sym_link * p)
913 {
914   /* if nothing return 0 */
915   if (!p)
916     return 0;
917
918   if (IS_SPEC (p))
919     {                           /* if this is the specifier then */
920
921       switch (SPEC_NOUN (p))
922         {                       /* depending on the specifier type */
923         case V_INT:
924           return (IS_LONG (p) ? LONGSIZE * 8 : INTSIZE * 8);
925         case V_FLOAT:
926           return FLOATSIZE * 8;
927         case V_FIXED16X16:
928           return (32);
929         case V_CHAR:
930           return CHARSIZE * 8;
931         case V_VOID:
932           return 0;
933         case V_STRUCT:
934           return SPEC_STRUCT (p)->size * 8;
935         case V_LABEL:
936           return 0;
937         case V_SBIT:
938         case V_BIT:
939           return 1;
940         case V_BITFIELD:
941           return SPEC_BLEN (p);
942         default:
943           return 0;
944         }
945     }
946
947   /* this is a specifier  */
948   switch (DCL_TYPE (p))
949     {
950     case ARRAY:
951       return DCL_ELEM (p) * getSize (p->next) * 8;
952     case IPOINTER:
953     case PPOINTER:
954     case POINTER:
955       return (PTRSIZE * 8);
956     case EEPPOINTER:
957     case FPOINTER:
958     case CPOINTER:
959     case FUNCTION:
960       return (FPTRSIZE * 8);
961     case GPOINTER:
962       return (GPTRSIZE * 8);
963
964     default:
965       return 0;
966     }
967 }
968
969 /*------------------------------------------------------------------*/
970 /* copySymbolChain - copies a symbol chain                          */
971 /*------------------------------------------------------------------*/
972 symbol *
973 copySymbolChain (symbol * src)
974 {
975   symbol *dest;
976
977   if (!src)
978     return NULL;
979
980   dest = copySymbol (src);
981   dest->next = copySymbolChain (src->next);
982   return dest;
983 }
984
985 /*------------------------------------------------------------------*/
986 /* copySymbol - makes a copy of a symbol                            */
987 /*------------------------------------------------------------------*/
988 symbol *
989 copySymbol (symbol * src)
990 {
991   symbol *dest;
992
993   if (!src)
994     return NULL;
995
996   dest = newSymbol (src->name, src->level);
997   memcpy (dest, src, sizeof (symbol));
998   dest->level = src->level;
999   dest->block = src->block;
1000   dest->ival = copyIlist (src->ival);
1001   dest->type = copyLinkChain (src->type);
1002   dest->etype = getSpec (dest->type);
1003   dest->next = NULL;
1004   dest->key = src->key;
1005   dest->allocreq = src->allocreq;
1006   return dest;
1007 }
1008
1009 /*------------------------------------------------------------------*/
1010 /* reverseSyms - reverses the links for a symbol chain      */
1011 /*------------------------------------------------------------------*/
1012 symbol *
1013 reverseSyms (symbol * sym)
1014 {
1015   symbol *prev, *curr, *next;
1016
1017   if (!sym)
1018     return NULL;
1019
1020   prev = sym;
1021   curr = sym->next;
1022
1023   while (curr)
1024     {
1025       next = curr->next;
1026       curr->next = prev;
1027       prev = curr;
1028       curr = next;
1029     }
1030   sym->next = (void *) NULL;
1031   return prev;
1032 }
1033
1034 /*------------------------------------------------------------------*/
1035 /* reverseLink - reverses the links for a type chain        */
1036 /*------------------------------------------------------------------*/
1037 sym_link *
1038 reverseLink (sym_link * type)
1039 {
1040   sym_link *prev, *curr, *next;
1041
1042   if (!type)
1043     return NULL;
1044
1045   prev = type;
1046   curr = type->next;
1047
1048   while (curr)
1049     {
1050       next = curr->next;
1051       curr->next = prev;
1052       prev = curr;
1053       curr = next;
1054     }
1055   type->next = (void *) NULL;
1056   return prev;
1057 }
1058
1059 /*------------------------------------------------------------------*/
1060 /* addSymChain - adds a symbol chain to the symboltable             */
1061 /*------------------------------------------------------------------*/
1062 void
1063 addSymChain (symbol ** symHead)
1064 {
1065   symbol *sym = *symHead;
1066   symbol *csym = NULL;
1067   symbol **symPtrPtr;
1068   int error = 0;
1069
1070   for (; sym != NULL; sym = sym->next)
1071     {
1072       changePointer(sym->type);
1073       checkTypeSanity(sym->etype, sym->name);
1074
1075       if (!sym->level && !(IS_SPEC(sym->etype) && IS_TYPEDEF(sym->etype)))
1076         checkDecl (sym, 0);
1077       else
1078         {
1079           /* if this is an array without any dimension
1080              then update the dimension from the initial value */
1081           if (IS_ARRAY (sym->type) && !DCL_ELEM (sym->type))
1082             DCL_ELEM (sym->type) = getNelements (sym->type, sym->ival);
1083         }
1084
1085       /* if already exists in the symbol table on the same level */
1086       if ((csym = findSymWithLevel (SymbolTab, sym)) &&
1087           csym->level == sym->level)
1088         {
1089           /* if not formal parameter and not in file scope
1090              then show symbol redefined error
1091              else check if symbols have conpatible types */
1092           if (!sym->_isparm && sym->level > 0)
1093             error = 1;
1094           else
1095             {
1096               /* If the previous definition was for an array with incomplete
1097                  type, and the new definition has completed the type, update
1098                  the original type to match */
1099               if (IS_DECL(csym->type) && DCL_TYPE(csym->type)==ARRAY
1100                   && IS_DECL(sym->type) && DCL_TYPE(sym->type)==ARRAY)
1101                 {
1102                   if (!DCL_ELEM(csym->type) && DCL_ELEM(sym->type))
1103                     DCL_ELEM(csym->type) = DCL_ELEM(sym->type);
1104                 }
1105
1106               #if 0
1107               /* If only one of the definitions used the "at" keyword, copy */
1108               /* the address to the other. */
1109               if (IS_SPEC(csym->etype) && SPEC_ABSA(csym->etype)
1110                   && IS_SPEC(sym->etype) && !SPEC_ABSA(sym->etype))
1111                 {
1112                   SPEC_ABSA (sym->etype) = 1;
1113                   SPEC_ADDR (sym->etype) = SPEC_ADDR (csym->etype);
1114                 }
1115               if (IS_SPEC(csym->etype) && !SPEC_ABSA(csym->etype)
1116                   && IS_SPEC(sym->etype) && SPEC_ABSA(sym->etype))
1117                 {
1118                   SPEC_ABSA (csym->etype) = 1;
1119                   SPEC_ADDR (csym->etype) = SPEC_ADDR (sym->etype);
1120                 }
1121               #endif
1122
1123               error = 0;
1124               if (csym->ival && sym->ival)
1125                 error = 1;
1126               if (compareTypeExact (csym->type, sym->type, sym->level) != 1)
1127                 error = 1;
1128             }
1129
1130           if (error)
1131             {
1132               /* one definition extern ? */
1133               if (IS_EXTERN (csym->etype) || IS_EXTERN (sym->etype))
1134                 werror (E_EXTERN_MISMATCH, sym->name);
1135               else
1136                 werror (E_DUPLICATE, sym->name);
1137               werrorfl (csym->fileDef, csym->lineDef, E_PREVIOUS_DEF);
1138               #if 0
1139               fprintf (stderr, "from type '");
1140               printTypeChain (csym->type, stderr);
1141               if (IS_SPEC (csym->etype) && SPEC_ABSA (csym->etype))
1142                 fprintf(stderr, " at 0x%x", SPEC_ADDR (csym->etype));
1143               fprintf (stderr, "'\nto type '");
1144               printTypeChain (sym->type, stderr);
1145               if (IS_SPEC (sym->etype) && SPEC_ABSA (sym->etype))
1146                 fprintf(stderr, " at 0x%x", SPEC_ADDR (sym->etype));
1147               fprintf (stderr, "'\n");
1148               #endif
1149               continue;
1150             }
1151
1152           if (csym->ival && !sym->ival)
1153             sym->ival = csym->ival;
1154
1155           if (!csym->cdef && !sym->cdef && IS_EXTERN (sym->etype))
1156             {
1157               /* if none of symbols is a compiler defined function
1158                  and at least one is not extern
1159                  then set the new symbol to non extern */
1160               SPEC_EXTR(sym->etype) = SPEC_EXTR(csym->etype);
1161             }
1162
1163           /* delete current entry */
1164           deleteSym (SymbolTab, csym, csym->name);
1165           deleteFromSeg(csym);
1166
1167           symPtrPtr = symHead;
1168           while (*symPtrPtr && *symPtrPtr != csym)
1169             symPtrPtr = &(*symPtrPtr)->next;
1170           if (*symPtrPtr == csym)
1171             *symPtrPtr = csym->next;
1172         }
1173
1174       /* add new entry */
1175       addSym (SymbolTab, sym, sym->name, sym->level, sym->block, 1);
1176     }
1177 }
1178
1179
1180 /*------------------------------------------------------------------*/
1181 /* funcInChain - DCL Type 'FUNCTION' found in type chain            */
1182 /*------------------------------------------------------------------*/
1183 int
1184 funcInChain (sym_link * lnk)
1185 {
1186   while (lnk)
1187     {
1188       if (IS_FUNC (lnk))
1189         return 1;
1190       lnk = lnk->next;
1191     }
1192   return 0;
1193 }
1194
1195 /*------------------------------------------------------------------*/
1196 /* structElemType - returns the type info of a struct member        */
1197 /*------------------------------------------------------------------*/
1198 sym_link *
1199 structElemType (sym_link * stype, value * id)
1200 {
1201   symbol *fields = (SPEC_STRUCT (stype) ? SPEC_STRUCT (stype)->fields : NULL);
1202   sym_link *type, *etype;
1203   sym_link *petype = getSpec (stype);
1204
1205   if (fields && id) {
1206
1207     /* look for the id */
1208     while (fields)
1209       {
1210         if (strcmp (fields->rname, id->name) == 0)
1211           {
1212             type = copyLinkChain (fields->type);
1213             etype = getSpec (type);
1214             SPEC_SCLS (etype) = (SPEC_SCLS (petype) == S_REGISTER ?
1215                                  SPEC_SCLS (etype) : SPEC_SCLS (petype));
1216             if (IS_SPEC (type))
1217               SPEC_CONST (type) |= SPEC_CONST (stype);
1218             else
1219               DCL_PTR_CONST (type) |= SPEC_CONST (stype);
1220             return type;
1221           }
1222         fields = fields->next;
1223       }
1224   }
1225
1226   werror (E_NOT_MEMBER, id->name);
1227
1228   // the show must go on
1229   return newIntLink();
1230 }
1231
1232 /*------------------------------------------------------------------*/
1233 /* getStructElement - returns element of a tructure definition      */
1234 /*------------------------------------------------------------------*/
1235 symbol *
1236 getStructElement (structdef * sdef, symbol * sym)
1237 {
1238   symbol *field;
1239
1240   for (field = sdef->fields; field; field = field->next)
1241     if (strcmp (field->name, sym->name) == 0)
1242       return field;
1243
1244   werror (E_NOT_MEMBER, sym->name);
1245
1246   return sdef->fields;
1247 }
1248
1249 /*------------------------------------------------------------------*/
1250 /* compStructSize - computes the size of a structure                */
1251 /*------------------------------------------------------------------*/
1252 int
1253 compStructSize (int su, structdef * sdef)
1254 {
1255   int sum = 0, usum = 0;
1256   int bitOffset = 0;
1257   symbol *loop;
1258
1259   /* for the identifiers  */
1260   loop = sdef->fields;
1261   while (loop) {
1262
1263     /* create the internal name for this variable */
1264     SNPRINTF (loop->rname, sizeof(loop->rname), "_%s", loop->name);
1265     if (su == UNION) {
1266         sum = 0;
1267         bitOffset = 0;
1268     }
1269     SPEC_VOLATILE (loop->etype) |= (su == UNION ? 1 : 0);
1270
1271     /* if this is a bit field  */
1272     if (loop->bitVar) {
1273
1274       /* change it to a unsigned bit */
1275       SPEC_NOUN (loop->etype) = V_BITFIELD;
1276       /* ISO/IEC 9899 J.3.9 implementation defined behaviour: */
1277       /* a "plain" int bitfield is unsigned */
1278       if (!loop->etype->select.s.b_signed)
1279         SPEC_USIGN(loop->etype) = 1;
1280
1281       SPEC_BLEN (loop->etype) = loop->bitVar;
1282
1283       if (loop->bitVar == BITVAR_PAD) {
1284         /* A zero length bitfield forces padding */
1285         SPEC_BSTR (loop->etype) = bitOffset;
1286         SPEC_BLEN (loop->etype) = 0;
1287         bitOffset = 8;
1288         loop->offset = sum;
1289       }
1290       else {
1291         if (bitOffset == 8) {
1292           bitOffset = 0;
1293           sum++;
1294         }
1295         /* check if this fit into the remaining   */
1296         /* bits of this byte else align it to the */
1297         /* next byte boundary                     */
1298         if (loop->bitVar <= (8 - bitOffset)) {
1299           /* fits into current byte */
1300           loop->offset = sum;
1301           SPEC_BSTR (loop->etype) = bitOffset;
1302           bitOffset += loop->bitVar;
1303         }
1304         else if (!bitOffset) {
1305           /* does not fit, but is already byte aligned */
1306           loop->offset = sum;
1307           SPEC_BSTR (loop->etype) = bitOffset;
1308           bitOffset += loop->bitVar;
1309         }
1310         else {
1311           if( TARGET_IS_PIC16 && getenv("PIC16_PACKED_BITFIELDS") ) {
1312             /* if PIC16 && enviroment variable is set, then
1313              * tightly pack bitfields, this means that when a
1314              * bitfield goes beyond byte alignment, do not
1315              * automatically start allocatint from next byte,
1316              * but also use the available bits first */
1317             fprintf(stderr, ": packing bitfields in structures\n");
1318             SPEC_BSTR (loop->etype) = bitOffset;
1319             bitOffset += loop->bitVar;
1320             loop->offset = (su == UNION ? sum = 0 : sum);
1321           } else {
1322             /* does not fit; need to realign first */
1323             sum++;
1324             loop->offset = (su == UNION ? sum = 0 : sum);
1325             bitOffset = 0;
1326             SPEC_BSTR (loop->etype) = bitOffset;
1327             bitOffset += loop->bitVar;
1328           }
1329         }
1330         while (bitOffset>8) {
1331           bitOffset -= 8;
1332           sum++;
1333         }
1334       }
1335     }
1336     else {
1337       /* This is a non-bit field. Make sure we are */
1338       /* byte aligned first */
1339       if (bitOffset) {
1340         sum++;
1341         loop->offset = (su == UNION ? sum = 0 : sum);
1342         bitOffset = 0;
1343       }
1344       loop->offset = sum;
1345       checkDecl (loop, 1);
1346       sum += getSize (loop->type);
1347
1348       /* search for "flexibel array members" */
1349       /* and do some syntax checks */
1350       if (   su == STRUCT
1351           && checkStructFlexArray (loop, loop->type))
1352         {
1353           /* found a "flexible array member" */
1354           sdef->b_flexArrayMember = TRUE;
1355           /* is another struct-member following? */
1356           if (loop->next)
1357             werror (E_FLEXARRAY_NOTATEND);
1358           /* is it the first struct-member? */
1359           else if (loop == sdef->fields)
1360             werror (E_FLEXARRAY_INEMPTYSTRCT);
1361         }
1362     }
1363
1364     loop = loop->next;
1365
1366     /* if union then size = sizeof largest field */
1367     if (su == UNION) {
1368       /* For UNION, round up after each field */
1369       sum += ((bitOffset+7)/8);
1370       usum = max (usum, sum);
1371     }
1372
1373   }
1374
1375   /* For STRUCT, round up after all fields processed */
1376   if (su != UNION)
1377     sum += ((bitOffset+7)/8);
1378
1379   return (su == UNION ? usum : sum);
1380 }
1381
1382 /*-------------------------------------------------------------------*/
1383 /* promoteAnonStructs - promote anonymous struct/union's fields into */
1384 /*                      an enclosing struct/union                    */
1385 /*-------------------------------------------------------------------*/
1386 void
1387 promoteAnonStructs (int su, structdef * sdef)
1388 {
1389   symbol *field;
1390   symbol *subfield;
1391   symbol **tofield;
1392   symbol *nextfield;
1393   symbol *dupfield;
1394   int base;
1395
1396   tofield = &sdef->fields;
1397   field = sdef->fields;
1398   while (field)
1399     {
1400       nextfield = field->next;
1401       if (!*field->name && IS_STRUCT (field->type))
1402         {
1403           /* Found an anonymous struct/union. Replace it */
1404           /* with the fields it contains and adjust all  */
1405           /* the offsets */
1406
1407           base = field->offset;
1408           subfield = copySymbolChain (SPEC_STRUCT (field->type)->fields);
1409           if (!subfield)
1410             continue;           /* just in case it's empty */
1411
1412           *tofield = subfield;
1413           for (;;)
1414             {
1415               /* check for field name conflicts resulting from promotion */
1416               dupfield = sdef->fields;
1417               while (dupfield && dupfield != subfield)
1418                 {
1419                   if (*subfield->name && !strcmp (dupfield->name, subfield->name))
1420                     {
1421                       werrorfl (subfield->fileDef, subfield->lineDef,
1422                                 E_DUPLICATE_MEMBER,
1423                                 su==STRUCT ? "struct" : "union",
1424                                 subfield->name);
1425                       werrorfl (dupfield->fileDef, dupfield->lineDef,
1426                                 E_PREVIOUS_DEF);
1427                     }
1428                   dupfield = dupfield->next;
1429                 }
1430
1431               subfield->offset += base;
1432               if (subfield->next)
1433                 subfield = subfield->next;
1434               else
1435                 break;
1436             }
1437           subfield->next = nextfield;
1438           tofield = &subfield->next;
1439         }
1440       else
1441         tofield = &field->next;
1442       field = nextfield;
1443     }
1444 }
1445
1446
1447 /*------------------------------------------------------------------*/
1448 /* checkSClass - check the storage class specification              */
1449 /*------------------------------------------------------------------*/
1450 static void
1451 checkSClass (symbol * sym, int isProto)
1452 {
1453   sym_link *t;
1454
1455   if (getenv("DEBUG_SANITY")) {
1456     fprintf (stderr, "checkSClass: %s \n", sym->name);
1457   }
1458
1459   /* type is literal can happen for enums change to auto */
1460   if (SPEC_SCLS (sym->etype) == S_LITERAL && !SPEC_ENUM (sym->etype))
1461     SPEC_SCLS (sym->etype) = S_AUTO;
1462
1463   /* if sfr or sbit then must also be volatile */
1464   if (SPEC_SCLS (sym->etype) == S_SBIT ||
1465       SPEC_SCLS (sym->etype) == S_SFR)
1466     {
1467       SPEC_VOLATILE (sym->etype) = 1;
1468     }
1469
1470   /* make sure restrict is only used with pointers */
1471   if (SPEC_RESTRICT (sym->etype))
1472     {
1473       werrorfl (sym->fileDef, sym->lineDef, E_BAD_RESTRICT);
1474       SPEC_RESTRICT (sym->etype) = 0;
1475     }
1476   t = sym->type;
1477   while (t)
1478     {
1479       if (IS_DECL (t) && DCL_PTR_RESTRICT (t) && !IS_PTR (t))
1480         {
1481           werrorfl (sym->fileDef, sym->lineDef, E_BAD_RESTRICT);
1482           DCL_PTR_RESTRICT (t) = 0;
1483           break;
1484         }
1485       t = t->next;
1486     }
1487
1488   /* if absolute address given then it mark it as
1489      volatile -- except in the PIC port */
1490
1491 #if !OPT_DISABLE_PIC || !OPT_DISABLE_PIC16
1492   /* The PIC port uses a different peep hole optimizer based on "pCode" */
1493   if (!TARGET_IS_PIC && !TARGET_IS_PIC16)
1494 #endif
1495
1496     if (IS_ABSOLUTE (sym->etype))
1497       SPEC_VOLATILE (sym->etype) = 1;
1498
1499   if (TARGET_IS_MCS51 &&
1500       IS_ABSOLUTE (sym->etype) &&
1501       SPEC_SCLS (sym->etype) == S_SFR)
1502     {
1503       int n, size;
1504       unsigned addr;
1505
1506       if (SPEC_NOUN (sym->etype) == V_CHAR)
1507         size = 8;
1508       else if (SPEC_LONG (sym->etype) == 0)
1509         size = 16;
1510       else
1511         size = 32;
1512
1513       addr = SPEC_ADDR (sym->etype);
1514       for (n=0; n<size; n+=8)
1515         if (((addr >> n) & 0xFF) < 0x80)
1516           werror (W_SFR_ABSRANGE, sym->name);
1517     }
1518
1519   /* If code memory is read only, then pointers to code memory */
1520   /* implicitly point to constants -- make this explicit       */
1521   t = sym->type;
1522   while (t && t->next) {
1523     if (IS_CODEPTR(t) && port->mem.code_ro) {
1524       if (IS_SPEC(t->next)) {
1525         SPEC_CONST (t->next) = 1;
1526       } else {
1527         DCL_PTR_CONST (t->next) = 1;
1528       }
1529     }
1530     t = t->next;
1531   }
1532
1533   /* global variables declared const put into code */
1534   /* if no other storage class specified */
1535   if (sym->level == 0 &&
1536       SPEC_SCLS(sym->etype) == S_FIXED &&
1537       !IS_FUNC(sym->type)) {
1538     /* find the first non-array link */
1539     t = sym->type;
1540     while (IS_ARRAY(t))
1541       t = t->next;
1542     if (IS_CONSTANT (t)) {
1543       SPEC_SCLS (sym->etype) = S_CODE;
1544     }
1545   }
1546
1547   /* global variable in code space is a constant */
1548   if (sym->level == 0 &&
1549       SPEC_SCLS (sym->etype) == S_CODE &&
1550       port->mem.code_ro) {
1551     /* find the first non-array link */
1552     t = sym->type;
1553     while (IS_ARRAY(t))
1554       t = t->next;
1555     if (IS_SPEC(t)) {
1556       SPEC_CONST (t) = 1;
1557     } else {
1558       DCL_PTR_CONST (t) = 1;
1559     }
1560   }
1561
1562   /* if bit variable then no storage class can be */
1563   /* specified since bit is already a storage */
1564   if (IS_BITVAR (sym->etype) &&
1565       (SPEC_SCLS (sym->etype) != S_FIXED &&
1566        SPEC_SCLS (sym->etype) != S_SBIT &&
1567        SPEC_SCLS (sym->etype) != S_BIT)
1568     )
1569     {
1570       werror (E_BITVAR_STORAGE, sym->name);
1571       SPEC_SCLS (sym->etype) = S_FIXED;
1572     }
1573
1574   /* extern variables cannot be initialized */
1575   if (IS_EXTERN (sym->etype) && sym->ival)
1576     {
1577       werror (E_EXTERN_INIT, sym->name);
1578       sym->ival = NULL;
1579     }
1580
1581   /* if this is an automatic symbol */
1582   if (sym->level && (options.stackAuto || reentrant)) {
1583     if (SPEC_SCLS (sym->etype) != S_BIT) {
1584       if ((SPEC_SCLS (sym->etype) == S_AUTO ||
1585            SPEC_SCLS (sym->etype) == S_FIXED ||
1586            SPEC_SCLS (sym->etype) == S_REGISTER ||
1587            SPEC_SCLS (sym->etype) == S_STACK ||
1588            SPEC_SCLS (sym->etype) == S_XSTACK)) {
1589         SPEC_SCLS (sym->etype) = S_AUTO;
1590       } else {
1591         /* storage class may only be specified for statics */
1592         if (!IS_STATIC(sym->etype)) {
1593           werror (E_AUTO_ASSUMED, sym->name);
1594         }
1595       }
1596     }
1597   }
1598
1599   /* automatic symbols cannot be given   */
1600   /* an absolute address ignore it      */
1601   if (sym->level && !IS_STATIC(sym->etype) &&
1602       SPEC_ABSA (sym->etype) &&
1603       (options.stackAuto || reentrant))
1604     {
1605       werror (E_AUTO_ABSA, sym->name);
1606       SPEC_ABSA (sym->etype) = 0;
1607     }
1608
1609   /* arrays & pointers cannot be defined for bits   */
1610   /* SBITS or SFRs or BIT                           */
1611   if ((IS_ARRAY (sym->type) || IS_PTR (sym->type)) &&
1612       !IS_FUNCPTR (sym->type) &&
1613       (SPEC_NOUN (sym->etype) == V_BIT ||
1614        SPEC_NOUN (sym->etype) == V_SBIT ||
1615        SPEC_NOUN (sym->etype) == V_BITFIELD ||
1616        SPEC_SCLS (sym->etype) == S_SFR))
1617     werror (E_BIT_ARRAY, sym->name);
1618
1619   /* if this is a bit|sbit then set length & start  */
1620   if (SPEC_NOUN (sym->etype) == V_BIT ||
1621       SPEC_NOUN (sym->etype) == V_SBIT)
1622     {
1623       SPEC_BLEN (sym->etype) = 1;
1624       SPEC_BSTR (sym->etype) = 0;
1625     }
1626
1627   if (!isProto) {
1628     /* variables declared in CODE space must have */
1629     /* initializers if not an extern */
1630     if (SPEC_SCLS (sym->etype) == S_CODE &&
1631         sym->ival == NULL &&
1632         !sym->_isparm &&
1633         //!sym->level &&
1634         port->mem.code_ro &&
1635         !IS_EXTERN (sym->etype) &&
1636         !SPEC_ABSA (sym->etype) &&
1637         !funcInChain (sym->type))
1638       werror (E_CODE_NO_INIT, sym->name);
1639   }
1640
1641   /* if parameter or local variable then change */
1642   /* the storage class to reflect where the var will go */
1643   if (sym->level && SPEC_SCLS (sym->etype) == S_FIXED
1644    && !IS_STATIC(sym->etype)
1645       )
1646     {
1647       if (options.stackAuto || (currFunc && IFFUNC_ISREENT (currFunc->type)))
1648         {
1649           SPEC_SCLS (sym->etype) = (options.useXstack ?
1650                                     S_XSTACK : S_STACK);
1651         }
1652       else
1653         {
1654           /* hack-o-matic! I see no reason why the useXstack option should ever
1655            * control this allocation, but the code was originally that way, and
1656            * changing it for non-390 ports breaks the compiler badly.
1657            */
1658           bool useXdata = (TARGET_IS_DS390 || TARGET_IS_DS400) ?
1659                 1 : options.useXstack;
1660           SPEC_SCLS (sym->etype) = (useXdata ?
1661                                     S_XDATA : S_FIXED);
1662         }
1663     }
1664 }
1665
1666 /*------------------------------------------------------------------*/
1667 /* changePointer - change pointer to functions                      */
1668 /*------------------------------------------------------------------*/
1669 void
1670 changePointer (sym_link * p)
1671 {
1672
1673   /* go thru the chain of declarations   */
1674   /* if we find a pointer to a function  */
1675   /* change it to a ptr to code area     */
1676   /* unless the function is banked.      */
1677   for (; p; p = p->next)
1678     {
1679       if (!IS_SPEC (p) && DCL_TYPE (p) == UPOINTER)
1680         DCL_TYPE (p) = port->unqualified_pointer;
1681       if (IS_PTR (p) && IS_FUNC (p->next))
1682         if (!IFFUNC_BANKED(p->next))
1683         DCL_TYPE (p) = CPOINTER;
1684     }
1685 }
1686
1687 /*------------------------------------------------------------------*/
1688 /* checkDecl - does semantic validation of a declaration                   */
1689 /*------------------------------------------------------------------*/
1690 int
1691 checkDecl (symbol * sym, int isProto)
1692 {
1693
1694   checkSClass (sym, isProto);           /* check the storage class      */
1695   changePointer (sym->type);          /* change pointers if required */
1696
1697   /* if this is an array without any dimension
1698      then update the dimension from the initial value */
1699   if (IS_ARRAY (sym->type) && !DCL_ELEM (sym->type))
1700     DCL_ELEM (sym->type) = getNelements (sym->type, sym->ival);
1701
1702   return 0;
1703 }
1704
1705 /*------------------------------------------------------------------*/
1706 /* copyLinkChain - makes a copy of the link chain & rets ptr 2 head */
1707 /*------------------------------------------------------------------*/
1708 sym_link *
1709 copyLinkChain (sym_link * p)
1710 {
1711   sym_link *head, *curr, *loop;
1712
1713   /* note: v_struct and v_struct->fields are not copied! */
1714   curr = p;
1715   head = loop = (curr ? newLink (p->class) : (void *) NULL);
1716   while (curr)
1717     {
1718       memcpy (loop, curr, sizeof (sym_link));   /* copy it */
1719       loop->next = (curr->next ? newLink (curr->next->class) : (void *) NULL);
1720       loop = loop->next;
1721       curr = curr->next;
1722     }
1723
1724   return head;
1725 }
1726
1727 /*------------------------------------------------------------------*/
1728 /* cleanUpBlock - cleansup the symbol table specified for all the   */
1729 /*                symbols in the given block                        */
1730 /*------------------------------------------------------------------*/
1731 void
1732 cleanUpBlock (bucket ** table, int block)
1733 {
1734   int i;
1735   bucket *chain;
1736
1737   /* go thru the entire  table  */
1738   for (i = 0; i < 256; i++)
1739     {
1740       for (chain = table[i]; chain; chain = chain->next)
1741         {
1742           if (chain->block >= block)
1743             {
1744               deleteSym (table, chain->sym, chain->name);
1745             }
1746         }
1747     }
1748 }
1749
1750 /*------------------------------------------------------------------*/
1751 /* cleanUpLevel - cleansup the symbol table specified for all the   */
1752 /*                symbols in the given level                        */
1753 /*------------------------------------------------------------------*/
1754 void
1755 cleanUpLevel (bucket ** table, int level)
1756 {
1757   int i;
1758   bucket *chain;
1759
1760   /* go thru the entire  table  */
1761   for (i = 0; i < 256; i++)
1762     {
1763       for (chain = table[i]; chain; chain = chain->next)
1764         {
1765           if (chain->level >= level)
1766             {
1767               deleteSym (table, chain->sym, chain->name);
1768             }
1769         }
1770     }
1771 }
1772
1773 /*------------------------------------------------------------------*/
1774 /* computeTypeOr - computes the resultant type from two types       */
1775 /*------------------------------------------------------------------*/
1776 static sym_link *
1777 computeTypeOr (sym_link * etype1, sym_link * etype2, sym_link * reType)
1778 {
1779   /* sanity check */
1780   assert (   (IS_CHAR (etype1) || IS_BIT (etype1))
1781           && (IS_CHAR (etype2) || IS_BIT (etype2)));
1782
1783   if (SPEC_USIGN (etype1) == SPEC_USIGN (etype2))
1784     {
1785       SPEC_USIGN (reType) = SPEC_USIGN (etype1);
1786       return reType;
1787     }
1788
1789   if (SPEC_USIGN (etype1))
1790     {
1791       if (   IS_LITERAL (etype2)
1792           && floatFromVal (valFromType (etype2)) >= 0)
1793         SPEC_USIGN (reType) = 1;
1794       else
1795         {
1796           /* promote to int */
1797           SPEC_USIGN (reType) = 0;
1798           SPEC_NOUN (reType) = V_INT;
1799         }
1800     }
1801   else /* etype1 signed */
1802     {
1803       if (   IS_LITERAL (etype2)
1804           && floatFromVal (valFromType (etype2)) <= 127)
1805         SPEC_USIGN (reType) = 0;
1806       else
1807         {
1808           /* promote to int */
1809           SPEC_USIGN (reType) = 0;
1810           SPEC_NOUN (reType) = V_INT;
1811         }
1812     }
1813
1814   if (SPEC_USIGN (etype2))
1815     {
1816       if (   IS_LITERAL (etype1)
1817           && floatFromVal (valFromType (etype1)) >= 0)
1818         SPEC_USIGN (reType) = 1;
1819       else
1820         {
1821           /* promote to int */
1822           SPEC_USIGN (reType) = 0;
1823           SPEC_NOUN (reType) = V_INT;
1824         }
1825     }
1826   else /* etype2 signed */
1827     {
1828       if (   IS_LITERAL (etype1)
1829           && floatFromVal (valFromType (etype1)) <= 127)
1830         SPEC_USIGN (reType) = 0;
1831       else
1832         {
1833           /* promote to int */
1834           SPEC_USIGN (reType) = 0;
1835           SPEC_NOUN (reType) = V_INT;
1836         }
1837     }
1838   return reType;
1839 }
1840
1841 /*------------------------------------------------------------------*/
1842 /* computeType - computes the resultant type from two types         */
1843 /*------------------------------------------------------------------*/
1844 sym_link *
1845 computeType (sym_link * type1, sym_link * type2,
1846              RESULT_TYPE resultType, int op)
1847 {
1848   sym_link *rType;
1849   sym_link *reType;
1850   sym_link *etype1 = getSpec (type1);
1851   sym_link *etype2;
1852
1853   etype2 = type2 ? getSpec (type2) : type1;
1854
1855   /* if one of them is a float then result is a float */
1856   /* here we assume that the types passed are okay */
1857   /* and can be cast to one another                */
1858   /* which ever is greater in size */
1859   if (IS_FLOAT (etype1) || IS_FLOAT (etype2))
1860     rType = newFloatLink ();
1861   /* if both are fixed16x16 then result is float */
1862   else if (IS_FIXED16X16(etype1) && IS_FIXED16X16(etype2))
1863     rType = newFixed16x16Link();
1864   else if (IS_FIXED16X16(etype1) && IS_FLOAT (etype2))
1865     rType = newFloatLink ();
1866   else if (IS_FLOAT (etype1) && IS_FIXED16X16 (etype2) )
1867     rType = newFloatLink ();
1868
1869   /* if both are bitvars choose the larger one */
1870   else if (IS_BITVAR (etype1) && IS_BITVAR (etype2))
1871     rType = SPEC_BLEN (etype1) >= SPEC_BLEN (etype2) ?
1872             copyLinkChain (type1) : copyLinkChain (type1);
1873
1874   /* if only one of them is a bit variable then the other one prevails */
1875   else if (IS_BITVAR (etype1) && !IS_BITVAR (etype2))
1876     {
1877       rType = copyLinkChain (type2);
1878       /* bitfield can have up to 16 bits */
1879       if (getSize (etype1) > 1)
1880         SPEC_NOUN (getSpec (rType)) = V_INT;
1881     }
1882   else if (IS_BITVAR (etype2) && !IS_BITVAR (etype1))
1883     {
1884       rType = copyLinkChain (type1);
1885       /* bitfield can have up to 16 bits */
1886       if (getSize (etype2) > 1)
1887         SPEC_NOUN (getSpec (rType)) = V_INT;
1888     }
1889   /* if one of them is a pointer or array then that
1890      prevails */
1891   else if (IS_PTR (type1) || IS_ARRAY (type1))
1892     rType = copyLinkChain (type1);
1893   else if (IS_PTR (type2) || IS_ARRAY (type2))
1894     rType = copyLinkChain (type2);
1895   else if (getSize (type1) > getSize (type2))
1896     rType = copyLinkChain (type1);
1897   else
1898     rType = copyLinkChain (type2);
1899
1900   reType = getSpec (rType);
1901
1902   /* avoid conflicting types */
1903   reType->select.s.b_signed = 0;
1904
1905   /* if result is a literal then make not so */
1906   if (IS_LITERAL (reType))
1907     SPEC_SCLS (reType) = S_REGISTER;
1908
1909   switch (resultType)
1910     {
1911       case RESULT_TYPE_IFX:
1912         if (TARGET_IS_HC08)
1913           break;
1914         //fallthrough
1915       case RESULT_TYPE_BIT:
1916         if (op == ':')
1917           {
1918             SPEC_NOUN (reType) = V_BIT;
1919             return rType;
1920           }
1921         break;
1922       case RESULT_TYPE_CHAR:
1923         if (IS_BITVAR (reType))
1924           {
1925             SPEC_NOUN (reType) = V_CHAR;
1926             SPEC_SCLS (reType) = 0;
1927             SPEC_USIGN (reType) = 0;
1928             return rType;
1929           }
1930         break;
1931       case RESULT_TYPE_INT:
1932       case RESULT_TYPE_NONE:
1933       case RESULT_TYPE_OTHER:
1934         if (IS_BIT (reType))
1935           {
1936             SPEC_NOUN (reType) = V_CHAR;
1937             SPEC_SCLS (reType) = 0;
1938             SPEC_USIGN (reType) = 0;
1939             return rType;
1940           }
1941         else if (IS_BITFIELD (reType))
1942           {
1943             /* could be smarter, but it depends on the op */
1944             /* this is for the worst case: a multiplication of 4 * 4 bit */
1945             SPEC_NOUN (reType) = SPEC_BLEN (reType) <= 4 ? V_CHAR : V_INT;
1946             SPEC_SCLS (reType) = 0;
1947             SPEC_USIGN (reType) = 0;
1948             return rType;
1949           }
1950         else if (IS_CHAR (reType))
1951           {
1952             /* promotion of some special cases */
1953             switch (op)
1954               {
1955                 case '|':
1956                 case '^':
1957                   return computeTypeOr (etype1, etype2, reType);
1958                 case '&':
1959                   if (SPEC_USIGN (etype1) != SPEC_USIGN (etype2))
1960                     {
1961                       SPEC_USIGN (reType) = 1;
1962                       return rType;
1963                     }
1964                   break;
1965                 case '*':
1966                   SPEC_NOUN (reType) = V_INT;
1967                   SPEC_USIGN (reType) = 0;
1968                   return rType;
1969                 case '/':
1970                   /* if both are unsigned char then no promotion required */
1971                   if (!(SPEC_USIGN (etype1) && SPEC_USIGN (etype2)))
1972                     {
1973                       SPEC_NOUN (reType) = V_INT;
1974                       SPEC_USIGN (reType) = 0;
1975                       return rType;
1976                     }
1977                   break;
1978                 default:
1979                   break;
1980               }
1981           }
1982         break;
1983       default:
1984         break;
1985     }
1986
1987   /* SDCC's sign promotion:
1988      - if one or both operands are unsigned, the resultant type will be unsigned
1989        (except char, see below)
1990      - if an operand is promoted to a larger type (char -> int, int -> long),
1991        the larger type will be signed
1992
1993      SDCC tries hard to avoid promotion to int and does 8 bit calculation as
1994      much as possible. We're leaving ISO IEC 9899 here and have to extrapolate
1995      the standard. The standard demands, that the result has to be the same
1996      "as if" the promotion would have been performed:
1997
1998      - if the result of an operation with two char's is promoted to a
1999        larger type, the result will be signed.
2000
2001      More sophisticated are these:
2002      - if the result of an operation with two char's is a char again,
2003        the result will only then be unsigned, if both operands are
2004        unsigned. In all other cases the result will be signed.
2005
2006        This seems to be contradictionary to the first two rules, but it makes
2007        real sense (all types are char's):
2008
2009         A signed char can be negative; this must be preserved in the result
2010                 -1 * 100 = -100;
2011
2012         Only if both operands are unsigned it's safe to make the result
2013         unsigned; this helps to avoid overflow:
2014                 2 * 100 =  200;
2015
2016      - ToDo: document '|', '^' and '&'
2017
2018      Homework: - why is (200 * 200 < 0) true?
2019                - why is { char l = 200, r = 200; (r * l > 0) } true?
2020   */
2021
2022   if (!IS_FLOAT (reType)
2023       && (   (SPEC_USIGN (etype1)
2024               /* if this operand is promoted to a larger type,
2025                  then it will be promoted to a signed type */
2026               && !(bitsForType (etype1) < bitsForType (reType))
2027               /* char require special handling */
2028               && !IS_CHAR (etype1))
2029           || /* same for 2nd operand */
2030              (SPEC_USIGN (etype2)
2031               && !(bitsForType (etype2) < bitsForType (reType))
2032               && !IS_CHAR (etype2))
2033           || /* if both are 'unsigned char' and not promoted
2034                 let the result be unsigned too */
2035              (   SPEC_USIGN (etype1)
2036               && SPEC_USIGN (etype2)
2037               && IS_CHAR (etype1)
2038               && IS_CHAR (etype2)
2039               && IS_CHAR (reType))))
2040     SPEC_USIGN (reType) = 1;
2041   else
2042     SPEC_USIGN (reType) = 0;
2043
2044   return rType;
2045 }
2046
2047 /*--------------------------------------------------------------------*/
2048 /* compareType - will do type check return 1 if match, -1 if castable */
2049 /*--------------------------------------------------------------------*/
2050 int
2051 compareType (sym_link * dest, sym_link * src)
2052 {
2053   if (!dest && !src)
2054     return 1;
2055
2056   if (dest && !src)
2057     return 0;
2058
2059   if (src && !dest)
2060     return 0;
2061
2062   /* if dest is a declarator then */
2063   if (IS_DECL (dest))
2064     {
2065       if (IS_DECL (src))
2066         {
2067           /* banked function pointer */
2068           if (IS_GENPTR (dest) && IS_GENPTR (src))
2069             {
2070               if (IS_FUNC (src->next) && IS_VOID(dest->next))
2071                 return -1;
2072               if (IS_FUNC (dest->next) && IS_VOID(src->next))
2073                 return -1;
2074               return compareType (dest->next, src->next);
2075             }
2076
2077           if (DCL_TYPE (src) == DCL_TYPE (dest))
2078             {
2079               if (IS_FUNC(src))
2080                 {
2081                   //checkFunction(src,dest);
2082                 }
2083               return compareType (dest->next, src->next);
2084             }
2085           if (IS_PTR (dest) && IS_GENPTR (src) && IS_VOID(src->next))
2086             {
2087               return -1;
2088             }
2089           if (IS_PTR (src) &&
2090               (IS_GENPTR (dest) ||
2091                ((DCL_TYPE(src) == POINTER) && (DCL_TYPE(dest) == IPOINTER))
2092              ))
2093             return -1;
2094           if (IS_PTR (dest) && IS_ARRAY (src))
2095             {
2096               value *val=aggregateToPointer (valFromType(src));
2097               int res=compareType (dest, val->type);
2098               Safe_free(val->type);
2099               Safe_free(val);
2100               return res;
2101             }
2102           if (IS_PTR (dest) && IS_FUNC (dest->next) && IS_FUNC (src))
2103             return compareType (dest->next, src);
2104           return 0;
2105         }
2106       else if (IS_PTR (dest) && IS_INTEGRAL (src))
2107         return -1;
2108       else
2109         return 0;
2110     }
2111
2112   /* if one is a specifier and the other is not */
2113   if ((IS_SPEC (src) && !IS_SPEC (dest)) ||
2114       (IS_SPEC (dest) && !IS_SPEC (src)))
2115     return 0;
2116
2117   /* if one of them is a void then ok */
2118   if (SPEC_NOUN (dest) == V_VOID &&
2119       SPEC_NOUN (src) != V_VOID)
2120     return -1;
2121
2122   if (SPEC_NOUN (dest) != V_VOID &&
2123       SPEC_NOUN (src) == V_VOID)
2124     return -1;
2125
2126   /* if they are both bitfields then if the lengths
2127      and starts don't match */
2128   if (IS_BITFIELD (dest) && IS_BITFIELD (src) &&
2129       (SPEC_BLEN (dest) != SPEC_BLEN (src) ||
2130        SPEC_BSTR (dest) != SPEC_BSTR (src)))
2131     return -1;
2132
2133   /* it is a specifier */
2134   if (SPEC_NOUN (dest) != SPEC_NOUN (src))
2135     {
2136       if (SPEC_USIGN (dest) == SPEC_USIGN (src) &&
2137           IS_INTEGRAL (dest) && IS_INTEGRAL (src) &&
2138           /* I would prefer
2139           bitsForType (dest) == bitsForType (src))
2140              instead of the next two lines, but the regression tests fail with
2141              them; I guess it's a problem with replaceCheaperOp  */
2142           getSize (dest) == getSize (src) &&
2143           (IS_BIT (dest) == IS_BIT (src)))
2144         return 1;
2145       else if (IS_ARITHMETIC (dest) && IS_ARITHMETIC (src))
2146         return -1;
2147       else
2148         return 0;
2149     }
2150   else if (IS_STRUCT (dest))
2151     {
2152       if (SPEC_STRUCT (dest) != SPEC_STRUCT (src))
2153         return 0;
2154       else
2155         return 1;
2156     }
2157   if (SPEC_LONG (dest) != SPEC_LONG (src))
2158     return -1;
2159
2160   if (SPEC_USIGN (dest) != SPEC_USIGN (src))
2161     return -1;
2162
2163   return 1;
2164 }
2165
2166 /*--------------------------------------------------------------------*/
2167 /* compareTypeExact - will do type check return 1 if match exactly    */
2168 /*--------------------------------------------------------------------*/
2169 int
2170 compareTypeExact (sym_link * dest, sym_link * src, int level)
2171 {
2172   STORAGE_CLASS srcScls, destScls;
2173
2174   if (!dest && !src)
2175     return 1;
2176
2177   if (dest && !src)
2178     return 0;
2179
2180   if (src && !dest)
2181     return 0;
2182
2183   /* if dest is a declarator then */
2184   if (IS_DECL (dest))
2185     {
2186       if (IS_DECL (src))
2187         {
2188           if (DCL_TYPE (src) == DCL_TYPE (dest)) {
2189             if ((DCL_TYPE (src) == ARRAY) && (DCL_ELEM (src) != DCL_ELEM (dest)))
2190               return 0;
2191             if (DCL_PTR_CONST (src) != DCL_PTR_CONST (dest))
2192               return 0;
2193             if (DCL_PTR_VOLATILE (src) != DCL_PTR_VOLATILE (dest))
2194               return 0;
2195             if (IS_FUNC(src))
2196               {
2197                 value *exargs, *acargs, *checkValue;
2198
2199                 /* verify function return type */
2200                 if (!compareTypeExact (dest->next, src->next, -1))
2201                   return 0;
2202                 if (FUNC_ISISR (dest) != FUNC_ISISR (src))
2203                   return 0;
2204                 if (FUNC_REGBANK (dest) != FUNC_REGBANK (src))
2205                   return 0;
2206                 if (IFFUNC_ISNAKED (dest) != IFFUNC_ISNAKED (src))
2207                   return 0;
2208                 #if 0
2209                 if (IFFUNC_ISREENT (dest) != IFFUNC_ISREENT (src) && argCnt>1)
2210                   return 0;
2211                 #endif
2212
2213                 /* compare expected args with actual args */
2214                 exargs = FUNC_ARGS(dest);
2215                 acargs = FUNC_ARGS(src);
2216
2217                 /* for all the expected args do */
2218                 for (; exargs && acargs; exargs = exargs->next, acargs = acargs->next)
2219                   {
2220                     //checkTypeSanity(acargs->etype, acargs->name);
2221
2222                     if (IS_AGGREGATE (acargs->type))
2223                       {
2224                         checkValue = copyValue (acargs);
2225                         aggregateToPointer (checkValue);
2226                       }
2227                     else
2228                       checkValue = acargs;
2229
2230                     #if 0
2231                     if (!compareTypeExact (exargs->type, checkValue->type, -1))
2232                       return 0;
2233                     #endif
2234                   }
2235
2236                   /* if one them ended we have a problem */
2237                   if ((exargs && !acargs && !IS_VOID (exargs->type)) ||
2238                       (!exargs && acargs && !IS_VOID (acargs->type)))
2239                     return 0;
2240                   return 1;
2241               }
2242             return compareTypeExact (dest->next, src->next, level);
2243           }
2244           return 0;
2245         }
2246       return 0;
2247     }
2248
2249   /* if one is a specifier and the other is not */
2250   if ((IS_SPEC (src) && !IS_SPEC (dest)) ||
2251       (IS_SPEC (dest) && !IS_SPEC (src)))
2252     return 0;
2253
2254   /* if one of them is a void then ok */
2255   if (SPEC_NOUN (dest) != SPEC_NOUN (src))
2256     return 0;
2257
2258   /* if they are both bitfields then if the lengths
2259      and starts don't match */
2260   if (IS_BITFIELD (dest) && IS_BITFIELD (src) &&
2261       (SPEC_BLEN (dest) != SPEC_BLEN (src) ||
2262        SPEC_BSTR (dest) != SPEC_BSTR (src)))
2263     return 0;
2264
2265   if (IS_INTEGRAL (dest))
2266     {
2267       /* signedness must match */
2268       if (SPEC_USIGN (dest) != SPEC_USIGN (src))
2269         return 0;
2270       /* size must match */
2271       if (SPEC_LONG (dest) != SPEC_LONG (src))
2272         return 0;
2273       if (SPEC_SHORT (dest) != SPEC_SHORT (src))
2274         return 0;
2275     }
2276
2277   if (IS_STRUCT (dest))
2278     {
2279       if (SPEC_STRUCT (dest) != SPEC_STRUCT (src))
2280         return 0;
2281     }
2282
2283   if (SPEC_CONST (dest) != SPEC_CONST (src))
2284     return 0;
2285   if (SPEC_VOLATILE (dest) != SPEC_VOLATILE (src))
2286     return 0;
2287   if (SPEC_STAT (dest) != SPEC_STAT (src))
2288     return 0;
2289   if (SPEC_ABSA (dest) != SPEC_ABSA (src))
2290     return 0;
2291   if (SPEC_ABSA (dest) && SPEC_ADDR (dest) != SPEC_ADDR (src))
2292     return 0;
2293
2294   destScls = SPEC_SCLS (dest);
2295   srcScls = SPEC_SCLS (src);
2296
2297   /* Compensate for const to const code change in checkSClass() */
2298   if (!level & port->mem.code_ro && SPEC_CONST (dest))
2299     {
2300       if (srcScls == S_CODE && destScls == S_FIXED)
2301         destScls = S_CODE;
2302       if (destScls == S_CODE && srcScls == S_FIXED)
2303         srcScls = S_CODE;
2304     }
2305
2306   /* compensate for allocGlobal() */
2307   if ((srcScls == S_FIXED || srcScls == S_AUTO)
2308       && port->mem.default_globl_map == xdata
2309       && !level)
2310     srcScls = S_XDATA;
2311
2312   if (level>0 && !SPEC_STAT (dest))
2313     {
2314       /* Compensate for hack-o-matic in checkSClass() */
2315       if (options.stackAuto || (currFunc && IFFUNC_ISREENT (currFunc->type)))
2316         {
2317           if (destScls == S_FIXED)
2318             destScls = (options.useXstack ? S_XSTACK : S_STACK);
2319           if (srcScls == S_FIXED)
2320             srcScls = (options.useXstack ? S_XSTACK : S_STACK);
2321         }
2322       else if (TARGET_IS_DS390 || TARGET_IS_DS400 || options.useXstack)
2323         {
2324           if (destScls == S_FIXED)
2325             destScls = S_XDATA;
2326           if (srcScls == S_FIXED)
2327             srcScls = S_XDATA;
2328         }
2329     }
2330
2331   if (srcScls != destScls)
2332     {
2333       #if 0
2334       printf ("level = %d\n", level);
2335       printf ("SPEC_SCLS (src) = %d, SPEC_SCLS (dest) = %d\n",
2336                 SPEC_SCLS (src), SPEC_SCLS (dest));
2337       printf ("srcScls = %d, destScls = %d\n",srcScls, destScls);
2338       #endif
2339       return 0;
2340     }
2341
2342   return 1;
2343 }
2344
2345 /*------------------------------------------------------------------*/
2346 /* inCalleeSaveList - return 1 if found in callee save list          */
2347 /*------------------------------------------------------------------*/
2348 static int
2349 calleeCmp(void *p1, void *p2)
2350 {
2351   return (strcmp((char *)p1, (char *)(p2)) == 0);
2352 }
2353
2354 bool
2355 inCalleeSaveList(char *s)
2356 {
2357   if (options.all_callee_saves)
2358     return 1;
2359   return isinSetWith(options.calleeSavesSet, s, calleeCmp);
2360 }
2361
2362 /*-----------------------------------------------------------------*/
2363 /* aggregateToPointer:     change an aggregate type function       */
2364 /*                         argument to a pointer to that type.     */
2365 /*-----------------------------------------------------------------*/
2366 value *
2367 aggregateToPointer (value * val)
2368 {
2369   if (IS_AGGREGATE (val->type))
2370     {
2371       /* if this is a structure */
2372       /* then we need to add a new link */
2373       if (IS_STRUCT (val->type))
2374         {
2375           /* first lets add DECLARATOR type */
2376           sym_link *p = val->type;
2377
2378           werror (W_STRUCT_AS_ARG, val->name);
2379           val->type = newLink (DECLARATOR);
2380           val->type->next = p;
2381         }
2382
2383       /* change to a pointer depending on the */
2384       /* storage class specified        */
2385       switch (SPEC_SCLS (val->etype))
2386         {
2387         case S_IDATA:
2388           DCL_TYPE (val->type) = IPOINTER;
2389           break;
2390         case S_PDATA:
2391           DCL_TYPE (val->type) = PPOINTER;
2392           break;
2393         case S_FIXED:
2394           if (SPEC_OCLS(val->etype)) {
2395             DCL_TYPE(val->type)=PTR_TYPE(SPEC_OCLS(val->etype));
2396           } else {
2397             // this happens for (external) function parameters
2398             DCL_TYPE (val->type) = port->unqualified_pointer;
2399           }
2400           break;
2401         case S_AUTO:
2402         case S_DATA:
2403         case S_REGISTER:
2404           DCL_TYPE (val->type) = POINTER;
2405           break;
2406         case S_CODE:
2407           DCL_TYPE (val->type) = CPOINTER;
2408           break;
2409         case S_XDATA:
2410           DCL_TYPE (val->type) = FPOINTER;
2411           break;
2412         case S_EEPROM:
2413           DCL_TYPE (val->type) = EEPPOINTER;
2414           break;
2415         default:
2416           DCL_TYPE (val->type) = port->unqualified_pointer;
2417         }
2418
2419       /* is there is a symbol associated then */
2420       /* change the type of the symbol as well */
2421       if (val->sym)
2422         {
2423           val->sym->type = copyLinkChain (val->type);
2424           val->sym->etype = getSpec (val->sym->type);
2425         }
2426     }
2427   return val;
2428 }
2429 /*------------------------------------------------------------------*/
2430 /* checkFunction - does all kinds of check on a function            */
2431 /*------------------------------------------------------------------*/
2432 int
2433 checkFunction (symbol * sym, symbol *csym)
2434 {
2435   value *exargs, *acargs;
2436   value *checkValue;
2437   int argCnt = 0;
2438
2439   if (getenv("DEBUG_SANITY")) {
2440     fprintf (stderr, "checkFunction: %s ", sym->name);
2441   }
2442
2443   if (!IS_DECL(sym->type) || DCL_TYPE(sym->type)!=FUNCTION)
2444     {
2445       werror(E_SYNTAX_ERROR, sym->name);
2446       return 0;
2447     }
2448
2449   /* move inline specifier from return type to function attributes */
2450   if (IS_INLINE (sym->etype))
2451     {
2452       SPEC_INLINE (sym->etype) = 0;
2453       FUNC_ISINLINE (sym->type) = 1;
2454     }
2455
2456   /* make sure the type is complete and sane */
2457   checkTypeSanity(((symbol *)sym)->etype, ((symbol *)sym)->name);
2458
2459   /* if not type then some kind of error */
2460   if (!sym->type)
2461     return 0;
2462
2463   /* if the function has no type then make it return int */
2464   if (!sym->type->next)
2465     sym->type->next = sym->etype = newIntLink ();
2466
2467   /* function cannot return aggregate */
2468   if (IS_AGGREGATE (sym->type->next))
2469     {
2470       werror (E_FUNC_AGGR, sym->name);
2471       return 0;
2472     }
2473
2474   /* check if this function is defined as calleeSaves
2475      then mark it as such */
2476   FUNC_CALLEESAVES(sym->type) = inCalleeSaveList (sym->name);
2477
2478   /* if interrupt service routine  */
2479   /* then it cannot have arguments */
2480   if (IFFUNC_ARGS(sym->type) && FUNC_ISISR (sym->type))
2481     {
2482       if (!IS_VOID(FUNC_ARGS(sym->type)->type)) {
2483         werror (E_INT_ARGS, sym->name);
2484         FUNC_ARGS(sym->type)=NULL;
2485       }
2486     }
2487
2488   if (IFFUNC_ISSHADOWREGS(sym->type) && !FUNC_ISISR (sym->type))
2489     {
2490       werror (E_SHADOWREGS_NO_ISR, sym->name);
2491     }
2492
2493   for (argCnt=1, acargs = FUNC_ARGS(sym->type);
2494        acargs;
2495        acargs=acargs->next, argCnt++) {
2496     if (!acargs->sym) {
2497       // this can happen for reentrant functions
2498       werror(E_PARAM_NAME_OMITTED, sym->name, argCnt);
2499       // the show must go on: synthesize a name and symbol
2500       SNPRINTF (acargs->name, sizeof(acargs->name), "_%s_PARM_%d", sym->name, argCnt);
2501       acargs->sym = newSymbol (acargs->name, 1);
2502       SPEC_OCLS (acargs->etype) = istack;
2503       acargs->sym->type = copyLinkChain (acargs->type);
2504       acargs->sym->etype = getSpec (acargs->sym->type);
2505       acargs->sym->_isparm = 1;
2506       strncpyz (acargs->sym->rname, acargs->name, sizeof(acargs->sym->rname));
2507     } else if (strcmp(acargs->sym->name, acargs->sym->rname)==0) {
2508       // synthesized name
2509       werror(E_PARAM_NAME_OMITTED, sym->name, argCnt);
2510     }
2511   }
2512   argCnt--;
2513
2514   /*JCF: Mark the register bank as used*/
2515   RegBankUsed[FUNC_REGBANK (sym->type)] = 1;
2516
2517   if (!csym && !(csym = findSym (SymbolTab, sym, sym->name)))
2518     return 1;                   /* not defined nothing more to check  */
2519
2520   /* check if body already present */
2521   if (csym && IFFUNC_HASBODY(csym->type))
2522     {
2523       werror (E_FUNC_BODY, sym->name);
2524       return 0;
2525     }
2526
2527   /* check the return value type   */
2528   if (compareType (csym->type, sym->type) <= 0)
2529     {
2530       werror (E_PREV_DEF_CONFLICT, csym->name, "type");
2531       printFromToType(csym->type, sym->type);
2532       return 0;
2533     }
2534
2535   if (FUNC_ISISR (csym->type) != FUNC_ISISR (sym->type))
2536     {
2537       werror (E_PREV_DEF_CONFLICT, csym->name, "interrupt");
2538     }
2539
2540   /* I don't think this is necessary for interrupts. An isr is a  */
2541   /* root in the calling tree.                                    */
2542   if ((FUNC_REGBANK (csym->type) != FUNC_REGBANK (sym->type)) &&
2543       (!FUNC_ISISR (sym->type)))
2544     {
2545       werror (E_PREV_DEF_CONFLICT, csym->name, "using");
2546     }
2547
2548   if (IFFUNC_ISNAKED (csym->type) != IFFUNC_ISNAKED (sym->type))
2549     {
2550       werror (E_PREV_DEF_CONFLICT, csym->name, "_naked");
2551     }
2552
2553   /* Really, reentrant should match regardless of argCnt, but     */
2554   /* this breaks some existing code (the fp lib functions). If    */
2555   /* the first argument is always passed the same way, this       */
2556   /* lax checking is ok (but may not be true for in future ports) */
2557   if (IFFUNC_ISREENT (csym->type) != IFFUNC_ISREENT (sym->type)
2558       && argCnt>1)
2559     {
2560       //printf("argCnt = %d\n",argCnt);
2561       werror (E_PREV_DEF_CONFLICT, csym->name, "reentrant");
2562     }
2563
2564   if (IFFUNC_ISWPARAM (csym->type) != IFFUNC_ISWPARAM (sym->type))
2565     {
2566       werror (E_PREV_DEF_CONFLICT, csym->name, "wparam");
2567     }
2568
2569   if (IFFUNC_ISSHADOWREGS (csym->type) != IFFUNC_ISSHADOWREGS (sym->type))
2570     {
2571       werror (E_PREV_DEF_CONFLICT, csym->name, "shadowregs");
2572     }
2573
2574
2575   /* compare expected args with actual args */
2576   exargs = FUNC_ARGS(csym->type);
2577   acargs = FUNC_ARGS(sym->type);
2578
2579   /* for all the expected args do */
2580   for (argCnt = 1;
2581        exargs && acargs;
2582        exargs = exargs->next, acargs = acargs->next, argCnt++)
2583     {
2584       if (getenv("DEBUG_SANITY")) {
2585         fprintf (stderr, "checkFunction: %s ", exargs->name);
2586       }
2587       /* make sure the type is complete and sane */
2588       checkTypeSanity(exargs->etype, exargs->name);
2589
2590       /* If the actual argument is an array, any prototype
2591        * will have modified it to a pointer. Duplicate that
2592        * change here.
2593        */
2594       if (IS_AGGREGATE (acargs->type))
2595         {
2596           checkValue = copyValue (acargs);
2597           aggregateToPointer (checkValue);
2598         }
2599       else
2600         {
2601           checkValue = acargs;
2602         }
2603
2604       if (compareType (exargs->type, checkValue->type) <= 0)
2605         {
2606           werror (E_ARG_TYPE, argCnt);
2607           printFromToType(exargs->type, checkValue->type);
2608           return 0;
2609         }
2610     }
2611
2612   /* if one them ended we have a problem */
2613   if ((exargs && !acargs && !IS_VOID (exargs->type)) ||
2614       (!exargs && acargs && !IS_VOID (acargs->type)))
2615     werror (E_ARG_COUNT);
2616
2617   /* replace with this defition */
2618   sym->cdef = csym->cdef;
2619   deleteSym (SymbolTab, csym, csym->name);
2620   deleteFromSeg(csym);
2621   addSym (SymbolTab, sym, sym->name, sym->level, sym->block, 1);
2622   if (IS_EXTERN (csym->etype) && !
2623       IS_EXTERN (sym->etype))
2624     {
2625       addSet (&publics, sym);
2626     }
2627   return 1;
2628 }
2629
2630 /*------------------------------------------------------------------*/
2631 /* cdbStructBlock - calls struct printing for a blcks               */
2632 /*------------------------------------------------------------------*/
2633 void cdbStructBlock (int block)
2634 {
2635   int i;
2636   bucket **table = StructTab;
2637   bucket *chain;
2638
2639   /* go thru the entire  table  */
2640   for (i = 0; i < 256; i++)
2641     {
2642       for (chain = table[i]; chain; chain = chain->next)
2643         {
2644           if (chain->block >= block)
2645             {
2646               if(debugFile)
2647                 debugFile->writeType((structdef *)chain->sym, chain->block, 0, NULL);
2648             }
2649         }
2650     }
2651 }
2652
2653 /*-----------------------------------------------------------------*/
2654 /* processFuncPtrArgs - does some processing with args of func ptrs*/
2655 /*-----------------------------------------------------------------*/
2656 void
2657 processFuncPtrArgs (sym_link * funcType)
2658 {
2659   value *val = FUNC_ARGS(funcType);
2660
2661   /* if it is void then remove parameters */
2662   if (val && IS_VOID (val->type))
2663     {
2664       FUNC_ARGS(funcType) = NULL;
2665       return;
2666     }
2667 }
2668
2669 /*-----------------------------------------------------------------*/
2670 /* processFuncArgs - does some processing with function args       */
2671 /*-----------------------------------------------------------------*/
2672 void
2673 processFuncArgs (symbol * func)
2674 {
2675   value *val;
2676   int pNum = 1;
2677   sym_link *funcType=func->type;
2678
2679   if (getenv("SDCC_DEBUG_FUNCTION_POINTERS"))
2680     fprintf (stderr, "SDCCsymt.c:processFuncArgs(%s)\n", func->name);
2681
2682   /* find the function declaration within the type */
2683   while (funcType && !IS_FUNC(funcType))
2684     funcType=funcType->next;
2685
2686   /* if this function has variable argument list */
2687   /* then make the function a reentrant one    */
2688   if (IFFUNC_HASVARARGS(funcType) || (options.stackAuto && !func->cdef))
2689     FUNC_ISREENT(funcType)=1;
2690
2691   /* check if this function is defined as calleeSaves
2692      then mark it as such */
2693   FUNC_CALLEESAVES(funcType) = inCalleeSaveList (func->name);
2694
2695   /* loop thru all the arguments   */
2696   val = FUNC_ARGS(funcType);
2697
2698   /* if it is void then remove parameters */
2699   if (val && IS_VOID (val->type))
2700     {
2701       FUNC_ARGS(funcType) = NULL;
2702       return;
2703     }
2704
2705   /* reset regparm for the port */
2706   (*port->reset_regparms) ();
2707
2708   /* if any of the arguments is an aggregate */
2709   /* change it to pointer to the same type */
2710   while (val)
2711     {
2712       int argreg = 0;
2713       char buffer[SDCC_NAME_MAX+1];
2714
2715       SNPRINTF (buffer, sizeof(buffer), "%s parameter %d", func->name, pNum);
2716       checkTypeSanity (val->etype, buffer);
2717
2718       /* mark it as a register parameter if
2719          the function does not have VA_ARG
2720          and as port dictates */
2721       if (!IFFUNC_HASVARARGS(funcType) &&
2722           (argreg = (*port->reg_parm) (val->type, FUNC_ISREENT(funcType))))
2723         {
2724           SPEC_REGPARM (val->etype) = 1;
2725           SPEC_ARGREG(val->etype) = argreg;
2726         } else if (IFFUNC_ISREENT(funcType)) {
2727             FUNC_HASSTACKPARM(funcType) = 1;
2728         }
2729
2730       if (IS_AGGREGATE (val->type))
2731         {
2732           aggregateToPointer (val);
2733         }
2734
2735       val = val->next;
2736       pNum++;
2737     }
2738
2739   /* if this is an internal generated function call */
2740   if (func->cdef) {
2741     /* ignore --stack-auto for this one, we don't know how it is compiled */
2742     /* simply trust on --int-long-reent or --float-reent */
2743     if (IFFUNC_ISREENT(funcType)) {
2744       return;
2745     }
2746   } else {
2747     /* if this function is reentrant or */
2748     /* automatics r 2b stacked then nothing */
2749     if (IFFUNC_ISREENT (funcType) || options.stackAuto)
2750       return;
2751   }
2752
2753   val = FUNC_ARGS(funcType);
2754   pNum = 1;
2755   while (val)
2756     {
2757
2758       /* if a symbolname is not given  */
2759       /* synthesize a variable name */
2760       if (!val->sym)
2761         {
2762           SNPRINTF (val->name, sizeof(val->name),
2763                     "_%s_PARM_%d", func->name, pNum++);
2764           val->sym = newSymbol (val->name, 1);
2765           if (SPEC_SCLS(val->etype) == S_BIT)
2766             SPEC_OCLS (val->etype) = bit;
2767           else
2768             SPEC_OCLS (val->etype) = port->mem.default_local_map;
2769           val->sym->type = copyLinkChain (val->type);
2770           val->sym->etype = getSpec (val->sym->type);
2771           val->sym->_isparm = 1;
2772           strncpyz (val->sym->rname, val->name, sizeof(val->sym->rname));
2773           #if 0
2774           /* ?? static functions shouldn't imply static parameters - EEP */
2775           if (IS_SPEC(func->etype)) {
2776             SPEC_STAT (val->etype) = SPEC_STAT (val->sym->etype) =
2777               SPEC_STAT (func->etype);
2778           }
2779           #endif
2780           addSymChain (&val->sym);
2781
2782         }
2783       else                      /* symbol name given create synth name */
2784         {
2785
2786           SNPRINTF (val->name, sizeof(val->name), "_%s_PARM_%d", func->name, pNum++);
2787           strncpyz (val->sym->rname, val->name, sizeof(val->sym->rname));
2788           val->sym->_isparm = 1;
2789           if (SPEC_SCLS(val->etype) == S_BIT)
2790             SPEC_OCLS (val->etype) = SPEC_OCLS (val->sym->etype) = bit;
2791           else
2792             SPEC_OCLS (val->etype) = SPEC_OCLS (val->sym->etype) =
2793               port->mem.default_local_map;
2794
2795           #if 0
2796           /* ?? static functions shouldn't imply static parameters - EEP */
2797           if (IS_SPEC(func->etype)) {
2798             SPEC_STAT (val->etype) = SPEC_STAT (val->sym->etype) =
2799               SPEC_STAT (func->etype);
2800           }
2801           #endif
2802         }
2803       if (SPEC_OCLS (val->sym->etype) == pdata)
2804         val->sym->iaccess = 1;
2805       if (!isinSet(operKeyReset, val->sym)) {
2806         addSet (&operKeyReset, val->sym);
2807         applyToSet (operKeyReset, resetParmKey);
2808       }
2809       val = val->next;
2810     }
2811 }
2812
2813 /*-----------------------------------------------------------------*/
2814 /* isSymbolEqual - compares two symbols return 1 if they match     */
2815 /*-----------------------------------------------------------------*/
2816 int
2817 isSymbolEqual (symbol * dest, symbol * src)
2818 {
2819   /* if pointers match then equal */
2820   if (dest == src)
2821     return 1;
2822
2823   /* if one of them is null then don't match */
2824   if (!dest || !src)
2825     return 0;
2826
2827   /* if both of them have rname match on rname */
2828   if (dest->rname[0] && src->rname[0])
2829     return (!strcmp (dest->rname, src->rname));
2830
2831   /* otherwise match on name */
2832   return (!strcmp (dest->name, src->name));
2833 }
2834
2835 void PT(sym_link *type)
2836 {
2837         printTypeChain(type,0);
2838 }
2839 /*-----------------------------------------------------------------*/
2840 /* printTypeChain - prints the type chain in human readable form   */
2841 /*-----------------------------------------------------------------*/
2842 void
2843 printTypeChain (sym_link * start, FILE * of)
2844 {
2845   struct dbuf_s dbuf;
2846   int nlr = 0;
2847
2848   if (!of)
2849     {
2850       of = stdout;
2851       nlr = 1;
2852     }
2853
2854   dbuf_init (&dbuf, 1024);
2855   dbuf_printTypeChain (start, &dbuf);
2856   dbuf_write_and_destroy (&dbuf, of);
2857
2858   if (nlr)
2859     putc ('\n', of);
2860 }
2861
2862 void
2863 dbuf_printTypeChain (sym_link * start, struct dbuf_s *dbuf)
2864 {
2865   value *args;
2866   sym_link * type, * search;
2867   STORAGE_CLASS scls;
2868
2869   if (start==NULL) {
2870     dbuf_append_str (dbuf, "void");
2871     return;
2872   }
2873
2874   /* Print the chain as it is written in the source: */
2875   /* start with the last entry.                      */
2876   /* However, the storage class at the end of the    */
2877   /* chain reall applies to the first in the chain!  */
2878
2879   for (type = start; type && type->next; type = type->next)
2880     ;
2881   if (IS_SPEC (type))
2882     scls=SPEC_SCLS(type);
2883   else
2884     scls=0;
2885   while (type)
2886     {
2887       if (type==start) {
2888         switch (scls)
2889           {
2890           case S_DATA: dbuf_append_str (dbuf, "data-"); break;
2891           case S_XDATA: dbuf_append_str (dbuf, "xdata-"); break;
2892           case S_SFR: dbuf_append_str (dbuf, "sfr-"); break;
2893           case S_SBIT: dbuf_append_str (dbuf, "sbit-"); break;
2894           case S_CODE: dbuf_append_str (dbuf, "code-"); break;
2895           case S_IDATA: dbuf_append_str (dbuf, "idata-"); break;
2896           case S_PDATA: dbuf_append_str (dbuf, "pdata-"); break;
2897           case S_LITERAL: dbuf_append_str (dbuf, "literal-"); break;
2898           case S_STACK: dbuf_append_str (dbuf, "stack-"); break;
2899           case S_XSTACK: dbuf_append_str (dbuf, "xstack-"); break;
2900           case S_BIT: dbuf_append_str (dbuf, "bit-"); break;
2901           case S_EEPROM: dbuf_append_str (dbuf, "eeprom-"); break;
2902           default: break;
2903           }
2904       }
2905
2906       if (IS_DECL (type))
2907         {
2908           if (!IS_FUNC(type)) {
2909             if (DCL_PTR_VOLATILE (type)) {
2910               dbuf_append_str (dbuf, "volatile-");
2911             }
2912             if (DCL_PTR_CONST (type)) {
2913               dbuf_append_str (dbuf, "const-");
2914             }
2915             if (DCL_PTR_RESTRICT (type)) {
2916               dbuf_append_str (dbuf, "restrict-");
2917             }
2918           }
2919           switch (DCL_TYPE (type))
2920             {
2921             case FUNCTION:
2922               dbuf_printf (dbuf, "function %s %s",
2923                        (IFFUNC_ISBUILTIN(type) ? "__builtin__" : " "),
2924                        (IFFUNC_ISJAVANATIVE(type) ? "_JavaNative" : " "));
2925               dbuf_append_str (dbuf, "( ");
2926               for (args = FUNC_ARGS(type);
2927                    args;
2928                    args=args->next) {
2929                 dbuf_printTypeChain(args->type, dbuf);
2930                 if (args->next)
2931                   dbuf_append_str (dbuf, ", ");
2932               }
2933               dbuf_append_str (dbuf, ") ");
2934               break;
2935             case GPOINTER:
2936               dbuf_append_str (dbuf, "generic* ");
2937               break;
2938             case CPOINTER:
2939               dbuf_append_str (dbuf, "code* ");
2940               break;
2941             case FPOINTER:
2942               dbuf_append_str (dbuf, "xdata* ");
2943               break;
2944             case EEPPOINTER:
2945               dbuf_append_str (dbuf, "eeprom* ");
2946               break;
2947             case POINTER:
2948               dbuf_append_str (dbuf, "near* ");
2949               break;
2950             case IPOINTER:
2951               dbuf_append_str (dbuf, "idata* ");
2952               break;
2953             case PPOINTER:
2954               dbuf_append_str (dbuf, "pdata* ");
2955               break;
2956             case UPOINTER:
2957               dbuf_append_str (dbuf, "unknown* ");
2958               break;
2959             case ARRAY:
2960               if (DCL_ELEM(type)) {
2961                 dbuf_printf (dbuf, "[%d] ", DCL_ELEM(type));
2962               } else {
2963                 dbuf_append_str (dbuf, "[] ");
2964               }
2965               break;
2966             }
2967         }
2968       else
2969         {
2970           if (SPEC_VOLATILE (type))
2971             dbuf_append_str (dbuf, "volatile-");
2972           if (SPEC_CONST (type))
2973             dbuf_append_str (dbuf, "const-");
2974           if (SPEC_USIGN (type))
2975             dbuf_append_str (dbuf, "unsigned-");
2976           switch (SPEC_NOUN (type))
2977             {
2978             case V_INT:
2979               if (IS_LONG (type))
2980                 dbuf_append_str (dbuf, "long-");
2981               dbuf_append_str (dbuf, "int");
2982               break;
2983
2984             case V_CHAR:
2985               dbuf_append_str (dbuf, "char");
2986               break;
2987
2988             case V_VOID:
2989               dbuf_append_str (dbuf, "void");
2990               break;
2991
2992             case V_FLOAT:
2993               dbuf_append_str (dbuf, "float");
2994               break;
2995
2996             case V_FIXED16X16:
2997               dbuf_append_str (dbuf, "fixed16x16");
2998               break;
2999
3000             case V_STRUCT:
3001               dbuf_printf (dbuf, "struct %s", SPEC_STRUCT (type)->tag);
3002               break;
3003
3004             case V_SBIT:
3005               dbuf_append_str (dbuf, "sbit");
3006               break;
3007
3008             case V_BIT:
3009               dbuf_append_str (dbuf, "bit");
3010               break;
3011
3012             case V_BITFIELD:
3013               dbuf_printf (dbuf, "bitfield {%d,%d}", SPEC_BSTR (type), SPEC_BLEN (type));
3014               break;
3015
3016             case V_DOUBLE:
3017               dbuf_append_str (dbuf, "double");
3018               break;
3019
3020             default:
3021               dbuf_append_str (dbuf, "unknown type");
3022               break;
3023             }
3024         }
3025       /* search entry in list before "type" */
3026       for (search = start; search && search->next != type;)
3027         search = search->next;
3028       type = search;
3029       if (type)
3030           dbuf_append_char(dbuf, ' ');
3031     }
3032 }
3033
3034 /*--------------------------------------------------------------------*/
3035 /* printTypeChainRaw - prints the type chain in human readable form   */
3036 /*                     in the raw data structure ordering             */
3037 /*--------------------------------------------------------------------*/
3038 void
3039 printTypeChainRaw (sym_link * start, FILE * of)
3040 {
3041   int nlr = 0;
3042   value *args;
3043   sym_link * type;
3044
3045   if (!of)
3046     {
3047       of = stdout;
3048       nlr = 1;
3049     }
3050
3051   if (start==NULL) {
3052     fprintf (of, "void");
3053     return;
3054   }
3055
3056   type = start;
3057
3058   while (type)
3059     {
3060       if (IS_DECL (type))
3061         {
3062           if (!IS_FUNC(type)) {
3063             if (DCL_PTR_VOLATILE (type)) {
3064               fprintf (of, "volatile-");
3065             }
3066             if (DCL_PTR_CONST (type)) {
3067               fprintf (of, "const-");
3068             }
3069             if (DCL_PTR_RESTRICT (type)) {
3070               fprintf (of, "restrict-");
3071             }
3072           }
3073           switch (DCL_TYPE (type))
3074             {
3075             case FUNCTION:
3076               if (IFFUNC_ISINLINE(type)) {
3077                 fprintf (of, "inline-");
3078               }
3079               fprintf (of, "function %s %s",
3080                        (IFFUNC_ISBUILTIN(type) ? "__builtin__" : " "),
3081                        (IFFUNC_ISJAVANATIVE(type) ? "_JavaNative" : " "));
3082               fprintf (of, "( ");
3083               for (args = FUNC_ARGS(type);
3084                    args;
3085                    args=args->next) {
3086                 printTypeChain(args->type, of);
3087                 if (args->next)
3088                   fprintf(of, ", ");
3089               }
3090               fprintf (of, ") ");
3091               break;
3092             case GPOINTER:
3093               fprintf (of, "generic* ");
3094               break;
3095             case CPOINTER:
3096               fprintf (of, "code* ");
3097               break;
3098             case FPOINTER:
3099               fprintf (of, "xdata* ");
3100               break;
3101             case EEPPOINTER:
3102               fprintf (of, "eeprom* ");
3103               break;
3104             case POINTER:
3105               fprintf (of, "near* ");
3106               break;
3107             case IPOINTER:
3108               fprintf (of, "idata* ");
3109               break;
3110             case PPOINTER:
3111               fprintf (of, "pdata* ");
3112               break;
3113             case UPOINTER:
3114               fprintf (of, "unknown* ");
3115               break;
3116             case ARRAY:
3117               if (DCL_ELEM(type)) {
3118                 fprintf (of, "[%d] ", DCL_ELEM(type));
3119               } else {
3120                 fprintf (of, "[] ");
3121               }
3122               break;
3123             }
3124           if (DCL_TSPEC(type))
3125             {
3126               fprintf (of, "{");
3127               printTypeChainRaw(DCL_TSPEC(type), of);
3128               fprintf (of, "}");
3129             }
3130         }
3131       else if (IS_SPEC (type))
3132         {
3133         switch (SPEC_SCLS (type))
3134           {
3135           case S_DATA: fprintf (of, "data-"); break;
3136           case S_XDATA: fprintf (of, "xdata-"); break;
3137           case S_SFR: fprintf (of, "sfr-"); break;
3138           case S_SBIT: fprintf (of, "sbit-"); break;
3139           case S_CODE: fprintf (of, "code-"); break;
3140           case S_IDATA: fprintf (of, "idata-"); break;
3141           case S_PDATA: fprintf (of, "pdata-"); break;
3142           case S_LITERAL: fprintf (of, "literal-"); break;
3143           case S_STACK: fprintf (of, "stack-"); break;
3144           case S_XSTACK: fprintf (of, "xstack-"); break;
3145           case S_BIT: fprintf (of, "bit-"); break;
3146           case S_EEPROM: fprintf (of, "eeprom-"); break;
3147           default: break;
3148           }
3149           if (SPEC_VOLATILE (type))
3150             fprintf (of, "volatile-");
3151           if (SPEC_CONST (type))
3152             fprintf (of, "const-");
3153           if (SPEC_USIGN (type))
3154             fprintf (of, "unsigned-");
3155           switch (SPEC_NOUN (type))
3156             {
3157             case V_INT:
3158               if (IS_LONG (type))
3159                 fprintf (of, "long-");
3160               fprintf (of, "int");
3161               break;
3162
3163             case V_CHAR:
3164               fprintf (of, "char");
3165               break;
3166
3167             case V_VOID:
3168               fprintf (of, "void");
3169               break;
3170
3171             case V_FLOAT:
3172               fprintf (of, "float");
3173               break;
3174
3175             case V_FIXED16X16:
3176               fprintf (of, "fixed16x16");
3177               break;
3178
3179             case V_STRUCT:
3180               fprintf (of, "struct %s", SPEC_STRUCT (type)->tag);
3181               break;
3182
3183             case V_SBIT:
3184               fprintf (of, "sbit");
3185               break;
3186
3187             case V_BIT:
3188               fprintf (of, "bit");
3189               break;
3190
3191             case V_BITFIELD:
3192               fprintf (of, "bitfield {%d,%d}", SPEC_BSTR (type), SPEC_BLEN (type));
3193               break;
3194
3195             case V_DOUBLE:
3196               fprintf (of, "double");
3197               break;
3198
3199             default:
3200               fprintf (of, "unknown type");
3201               break;
3202             }
3203         }
3204       else
3205         fprintf (of, "NOT_SPEC_OR_DECL");
3206       type = type->next;
3207       if (type)
3208         fputc (' ', of);
3209     }
3210   if (nlr)
3211     fprintf (of, "\n");
3212 }
3213
3214
3215 /*-----------------------------------------------------------------*/
3216 /* powof2 - returns power of two for the number if number is pow 2 */
3217 /*-----------------------------------------------------------------*/
3218 int
3219 powof2 (TYPE_TARGET_ULONG num)
3220 {
3221   int nshifts = 0;
3222   int n1s = 0;
3223
3224   while (num)
3225     {
3226       if (num & 1)
3227         n1s++;
3228       num >>= 1;
3229       nshifts++;
3230     }
3231
3232   if (n1s > 1 || nshifts == 0)
3233     return -1;
3234   return nshifts - 1;
3235 }
3236
3237 symbol *__fsadd;
3238 symbol *__fssub;
3239 symbol *__fsmul;
3240 symbol *__fsdiv;
3241 symbol *__fseq;
3242 symbol *__fsneq;
3243 symbol *__fslt;
3244 symbol *__fslteq;
3245 symbol *__fsgt;
3246 symbol *__fsgteq;
3247
3248 symbol *__fps16x16_add;
3249 symbol *__fps16x16_sub;
3250 symbol *__fps16x16_mul;
3251 symbol *__fps16x16_div;
3252 symbol *__fps16x16_eq;
3253 symbol *__fps16x16_neq;
3254 symbol *__fps16x16_lt;
3255 symbol *__fps16x16_lteq;
3256 symbol *__fps16x16_gt;
3257 symbol *__fps16x16_gteq;
3258
3259 /* Dims: mul/div/mod, BYTE/WORD/DWORD, SIGNED/UNSIGNED */
3260 symbol *__muldiv[3][3][2];
3261 /* Dims: BYTE/WORD/DWORD SIGNED/UNSIGNED */
3262 sym_link *__multypes[3][2];
3263 /* Dims: to/from float, BYTE/WORD/DWORD, SIGNED/USIGNED */
3264 symbol *__conv[2][3][2];
3265 /* Dims: to/from fixed16x16, BYTE/WORD/DWORD/FLOAT, SIGNED/USIGNED */
3266 symbol *__fp16x16conv[2][4][2];
3267 /* Dims: shift left/shift right, BYTE/WORD/DWORD, SIGNED/UNSIGNED */
3268 symbol *__rlrr[2][3][2];
3269
3270 sym_link *floatType;
3271 sym_link *fixed16x16Type;
3272
3273 static char *
3274 _mangleFunctionName(char *in)
3275 {
3276   if (port->getMangledFunctionName)
3277     {
3278       return port->getMangledFunctionName(in);
3279     }
3280   else
3281     {
3282       return in;
3283     }
3284 }
3285
3286 /*-----------------------------------------------------------------*/
3287 /* typeFromStr - create a typechain from an encoded string         */
3288 /* basic types -        'c' - char                                 */
3289 /*                      's' - short                                */
3290 /*                      'i' - int                                  */
3291 /*                      'l' - long                                 */
3292 /*                      'f' - float                                */
3293 /*                      'q' - fixed16x16                           */
3294 /*                      'v' - void                                 */
3295 /*                      '*' - pointer - default (GPOINTER)         */
3296 /* modifiers -          'u' - unsigned                             */
3297 /* pointer modifiers -  'g' - generic                              */
3298 /*                      'x' - xdata                                */
3299 /*                      'p' - code                                 */
3300 /*                      'd' - data                                 */
3301 /*                      'F' - function                             */
3302 /* examples : "ig*" - generic int *                                */
3303 /*            "cx*" - char xdata *                                 */
3304 /*            "ui" -  unsigned int                                 */
3305 /*-----------------------------------------------------------------*/
3306 sym_link *typeFromStr (char *s)
3307 {
3308     sym_link *r = newLink(DECLARATOR);
3309     int usign = 0;
3310
3311     do {
3312         sym_link *nr;
3313         switch (*s) {
3314         case 'u' :
3315             usign = 1;
3316             s++;
3317             continue ;
3318             break ;
3319         case 'c':
3320             r->class = SPECIFIER;
3321             SPEC_NOUN(r) = V_CHAR;
3322             break;
3323         case 's':
3324         case 'i':
3325             r->class = SPECIFIER;
3326             SPEC_NOUN(r) = V_INT;
3327             break;
3328         case 'l':
3329             r->class = SPECIFIER;
3330             SPEC_NOUN(r) = V_INT;
3331             SPEC_LONG(r) = 1;
3332             break;
3333         case 'f':
3334             r->class = SPECIFIER;
3335             SPEC_NOUN(r) = V_FLOAT;
3336             break;
3337         case 'q':
3338             r->class = SPECIFIER;
3339             SPEC_NOUN(r) = V_FIXED16X16;
3340             break;
3341         case 'v':
3342             r->class = SPECIFIER;
3343             SPEC_NOUN(r) = V_VOID;
3344             break;
3345         case '*':
3346             DCL_TYPE(r) = port->unqualified_pointer;
3347             break;
3348         case 'g':
3349         case 'x':
3350         case 'p':
3351         case 'd':
3352         case 'F':
3353             assert(*(s+1)=='*');
3354             nr = newLink(DECLARATOR);
3355             nr->next = r;
3356             r = nr;
3357             switch (*s) {
3358             case 'g':
3359                 DCL_TYPE(r) = GPOINTER;
3360                 break;
3361             case 'x':
3362                 DCL_TYPE(r) = FPOINTER;
3363                 break;
3364             case 'p':
3365                 DCL_TYPE(r) = CPOINTER;
3366                 break;
3367             case 'd':
3368                 DCL_TYPE(r) = POINTER;
3369                 break;
3370             case 'F':
3371                 DCL_TYPE(r) = FUNCTION;
3372                 nr = newLink(DECLARATOR);
3373                 nr->next = r;
3374                 r = nr;
3375                 DCL_TYPE(r) = CPOINTER;
3376                 break;
3377             }
3378             s++;
3379             break;
3380         default:
3381             werror(E_INTERNAL_ERROR, __FILE__, __LINE__,
3382                    "typeFromStr: unknown type");
3383             break;
3384         }
3385         if (IS_SPEC(r) && usign) {
3386             SPEC_USIGN(r) = 1;
3387             usign = 0;
3388         }
3389         s++;
3390     } while (*s);
3391     return r;
3392 }
3393
3394 /*-----------------------------------------------------------------*/
3395 /* initCSupport - create functions for C support routines          */
3396 /*-----------------------------------------------------------------*/
3397 void
3398 initCSupport ()
3399 {
3400   const char *smuldivmod[] =
3401   {
3402     "mul", "div", "mod"
3403   };
3404   const char *sbwd[] =
3405   {
3406     "char", "int", "long", "fixed16x16",
3407   };
3408   const char *fp16x16sbwd[] =
3409   {
3410     "char", "int", "long", "float",
3411   };
3412   const char *ssu[] =
3413   {
3414     "s", "u"
3415   };
3416   const char *srlrr[] =
3417   {
3418     "rl", "rr"
3419   };
3420
3421   int bwd, su, muldivmod, tofrom, rlrr;
3422
3423   if (getenv("SDCC_NO_C_SUPPORT")) {
3424     /* for debugging only */
3425     return;
3426   }
3427
3428   floatType = newFloatLink ();
3429   fixed16x16Type = newFixed16x16Link ();
3430
3431   for (bwd = 0; bwd < 3; bwd++)
3432     {
3433       sym_link *l = NULL;
3434       switch (bwd)
3435         {
3436         case 0:
3437           l = newCharLink ();
3438           break;
3439         case 1:
3440           l = newIntLink ();
3441           break;
3442         case 2:
3443           l = newLongLink ();
3444           break;
3445         default:
3446           assert (0);
3447         }
3448       __multypes[bwd][0] = l;
3449       __multypes[bwd][1] = copyLinkChain (l);
3450       SPEC_USIGN (__multypes[bwd][1]) = 1;
3451     }
3452
3453   __fsadd = funcOfType ("__fsadd", floatType, floatType, 2, options.float_rent);
3454   __fssub = funcOfType ("__fssub", floatType, floatType, 2, options.float_rent);
3455   __fsmul = funcOfType ("__fsmul", floatType, floatType, 2, options.float_rent);
3456   __fsdiv = funcOfType ("__fsdiv", floatType, floatType, 2, options.float_rent);
3457   __fseq = funcOfType ("__fseq", CHARTYPE, floatType, 2, options.float_rent);
3458   __fsneq = funcOfType ("__fsneq", CHARTYPE, floatType, 2, options.float_rent);
3459   __fslt = funcOfType ("__fslt", CHARTYPE, floatType, 2, options.float_rent);
3460   __fslteq = funcOfType ("__fslteq", CHARTYPE, floatType, 2, options.float_rent);
3461   __fsgt = funcOfType ("__fsgt", CHARTYPE, floatType, 2, options.float_rent);
3462   __fsgteq = funcOfType ("__fsgteq", CHARTYPE, floatType, 2, options.float_rent);
3463
3464   __fps16x16_add = funcOfType ("__fps16x16_add", fixed16x16Type, fixed16x16Type, 2, options.float_rent);
3465   __fps16x16_sub = funcOfType ("__fps16x16_sub", fixed16x16Type, fixed16x16Type, 2, options.float_rent);
3466   __fps16x16_mul = funcOfType ("__fps16x16_mul", fixed16x16Type, fixed16x16Type, 2, options.float_rent);
3467   __fps16x16_div = funcOfType ("__fps16x16_div", fixed16x16Type, fixed16x16Type, 2, options.float_rent);
3468   __fps16x16_eq = funcOfType ("__fps16x16_eq", CHARTYPE, fixed16x16Type, 2, options.float_rent);
3469   __fps16x16_neq = funcOfType ("__fps16x16_neq", CHARTYPE, fixed16x16Type, 2, options.float_rent);
3470   __fps16x16_lt = funcOfType ("__fps16x16_lt", CHARTYPE, fixed16x16Type, 2, options.float_rent);
3471   __fps16x16_lteq = funcOfType ("__fps16x16_lteq", CHARTYPE, fixed16x16Type, 2, options.float_rent);
3472   __fps16x16_gt = funcOfType ("__fps16x16_gt", CHARTYPE, fixed16x16Type, 2, options.float_rent);
3473   __fps16x16_gteq = funcOfType ("__fps16x16_gteq", CHARTYPE, fixed16x16Type, 2, options.float_rent);
3474
3475
3476   for (tofrom = 0; tofrom < 2; tofrom++)
3477     {
3478       for (bwd = 0; bwd < 3; bwd++)
3479         {
3480           for (su = 0; su < 2; su++)
3481             {
3482               if (tofrom)
3483                 {
3484                   SNPRINTF (buffer, sizeof(buffer), "__fs2%s%s", ssu[su], sbwd[bwd]);
3485                   __conv[tofrom][bwd][su] = funcOfType (buffer, __multypes[bwd][su], floatType, 1, options.float_rent);
3486                 }
3487               else
3488                 {
3489                   SNPRINTF (buffer, sizeof(buffer), "__%s%s2fs", ssu[su], sbwd[bwd]);
3490                   __conv[tofrom][bwd][su] = funcOfType (buffer, floatType, __multypes[bwd][su], 1, options.float_rent);
3491                 }
3492             }
3493         }
3494     }
3495
3496   for (tofrom = 0; tofrom < 2; tofrom++)
3497     {
3498       for (bwd = 0; bwd < 4; bwd++)
3499         {
3500           for (su = 0; su < 2; su++)
3501             {
3502               if (tofrom)
3503                 {
3504                   SNPRINTF (buffer, sizeof(buffer), "__fps16x162%s%s", ssu[su], fp16x16sbwd[bwd]);
3505                   if(bwd == 3) {
3506                     __fp16x16conv[tofrom][bwd][su] = funcOfType (buffer, floatType, fixed16x16Type, 1, options.float_rent);
3507                   } else
3508                     __fp16x16conv[tofrom][bwd][su] = funcOfType (buffer, __multypes[bwd][su], fixed16x16Type, 1, options.float_rent);
3509                 }
3510               else
3511                 {
3512                   SNPRINTF (buffer, sizeof(buffer), "__%s%s2fps16x16", ssu[su], fp16x16sbwd[bwd]);
3513                   if(bwd == 3) {
3514                     __fp16x16conv[tofrom][bwd][su] = funcOfType (buffer, fixed16x16Type, floatType, 1, options.float_rent);
3515                   } else
3516                     __fp16x16conv[tofrom][bwd][su] = funcOfType (buffer, fixed16x16Type, __multypes[bwd][su], 1, options.float_rent);
3517                 }
3518             }
3519         }
3520     }
3521
3522 /*
3523   for (muldivmod = 0; muldivmod < 3; muldivmod++)
3524     {
3525       for (bwd = 0; bwd < 3; bwd++)
3526         {
3527           for (su = 0; su < 2; su++)
3528             {
3529               SNPRINTF (buffer, sizeof(buffer),
3530                         "_%s%s%s",
3531                        smuldivmod[muldivmod],
3532                        ssu[su],
3533                        sbwd[bwd]);
3534               __muldiv[muldivmod][bwd][su] = funcOfType (_mangleFunctionName(buffer), __multypes[bwd][su], __multypes[bwd][su], 2, options.intlong_rent);
3535               FUNC_NONBANKED (__muldiv[muldivmod][bwd][su]->type) = 1;
3536             }
3537         }
3538     }
3539
3540   muluint() and mulsint() resp. mululong() and mulslong() return the same result.
3541   Therefore they've been merged into mulint() and mullong().
3542 */
3543
3544   for (bwd = 0; bwd < 3; bwd++)
3545     {
3546       for (su = 0; su < 2; su++)
3547         {
3548           for (muldivmod = 1; muldivmod < 3; muldivmod++)
3549             {
3550               /* div and mod : s8_t x s8_t -> s8_t should be s8_t x s8_t -> s16_t, see below */
3551               if (!TARGET_IS_PIC16 || muldivmod != 1 || bwd != 0 || su != 0)
3552               {
3553                 SNPRINTF (buffer, sizeof(buffer),
3554                     "_%s%s%s",
3555                     smuldivmod[muldivmod],
3556                     ssu[su],
3557                     sbwd[bwd]);
3558                 __muldiv[muldivmod][bwd][su] = funcOfType (
3559                     _mangleFunctionName(buffer),
3560                     __multypes[bwd][su],
3561                     __multypes[bwd][su],
3562                     2,
3563                     options.intlong_rent);
3564                 FUNC_NONBANKED (__muldiv[muldivmod][bwd][su]->type) = 1;
3565               }
3566             }
3567         }
3568     }
3569
3570   if (TARGET_IS_PIC16)
3571   {
3572     /* PIC16 port wants __divschar/__modschar to return an int, so that both
3573      * 100 / -4 = -25 and -128 / -1 = 128 can be handled correctly
3574      * (first one would have to be sign extended, second one must not be).
3575      * Similarly, modschar should be handled, but the iCode introduces cast
3576      * here and forces '% : s8 x s8 -> s8' ... */
3577     su = 0; bwd = 0;
3578     for (muldivmod = 1; muldivmod < 2; muldivmod++) {
3579       SNPRINTF (buffer, sizeof(buffer),
3580           "_%s%s%s",
3581           smuldivmod[muldivmod],
3582           ssu[su],
3583           sbwd[bwd]);
3584       __muldiv[muldivmod][bwd][su] = funcOfType (
3585           _mangleFunctionName(buffer),
3586           __multypes[1][su],
3587           __multypes[bwd][su],
3588           2,
3589           options.intlong_rent);
3590       FUNC_NONBANKED (__muldiv[muldivmod][bwd][su]->type) = 1;
3591     }
3592   }
3593
3594   /* mul only */
3595   muldivmod = 0;
3596   /* byte */
3597   bwd = 0;
3598   for (su = 0; su < 2; su++)
3599     {
3600       /* muluchar and mulschar are still separate functions, because e.g. the z80
3601          port is sign/zero-extending to int before calling mulint() */
3602       SNPRINTF (buffer, sizeof(buffer),
3603                 "_%s%s%s",
3604                 smuldivmod[muldivmod],
3605                 ssu[su],
3606                 sbwd[bwd]);
3607       __muldiv[muldivmod][bwd][su] = funcOfType (_mangleFunctionName(buffer), __multypes[bwd][su], __multypes[bwd][su], 2, options.intlong_rent);
3608       FUNC_NONBANKED (__muldiv[muldivmod][bwd][su]->type) = 1;
3609     }
3610   /* signed only */
3611   su = 0;
3612   /* word and doubleword */
3613   for (bwd = 1; bwd < 3; bwd++)
3614     {
3615       /* mul, int/long */
3616       SNPRINTF (buffer, sizeof(buffer),
3617                 "_%s%s",
3618                 smuldivmod[muldivmod],
3619                 sbwd[bwd]);
3620       __muldiv[muldivmod][bwd][0] = funcOfType (_mangleFunctionName(buffer), __multypes[bwd][su], __multypes[bwd][su], 2, options.intlong_rent);
3621       FUNC_NONBANKED (__muldiv[muldivmod][bwd][0]->type) = 1;
3622       /* signed = unsigned */
3623       __muldiv[muldivmod][bwd][1] = __muldiv[muldivmod][bwd][0];
3624     }
3625
3626   for (rlrr = 0; rlrr < 2; rlrr++)
3627     {
3628       for (bwd = 0; bwd < 3; bwd++)
3629         {
3630           for (su = 0; su < 2; su++)
3631             {
3632               SNPRINTF (buffer, sizeof(buffer),
3633                         "_%s%s%s",
3634                        srlrr[rlrr],
3635                        ssu[su],
3636                        sbwd[bwd]);
3637               __rlrr[rlrr][bwd][su] = funcOfType (_mangleFunctionName(buffer), __multypes[bwd][su], __multypes[0][0], 2, options.intlong_rent);
3638               FUNC_NONBANKED (__rlrr[rlrr][bwd][su]->type) = 1;
3639             }
3640         }
3641     }
3642 }
3643
3644 /*-----------------------------------------------------------------*/
3645 /* initBuiltIns - create prototypes for builtin functions          */
3646 /*-----------------------------------------------------------------*/
3647 void initBuiltIns()
3648 {
3649     int i;
3650     symbol *sym;
3651
3652     if (!port->builtintable) return ;
3653
3654     for (i = 0 ; port->builtintable[i].name ; i++) {
3655         sym = funcOfTypeVarg(port->builtintable[i].name,port->builtintable[i].rtype,
3656                              port->builtintable[i].nParms,port->builtintable[i].parm_types);
3657         FUNC_ISBUILTIN(sym->type) = 1;
3658         FUNC_ISREENT(sym->type) = 0;    /* can never be reentrant */
3659     }
3660 }
3661
3662 sym_link *validateLink(sym_link         *l,
3663                         const char      *macro,
3664                         const char      *args,
3665                         const char      select,
3666                         const char      *file,
3667                         unsigned        line)
3668 {
3669   if (l && l->class==select)
3670     {
3671         return l;
3672     }
3673     fprintf(stderr,
3674             "Internal error: validateLink failed in %s(%s) @ %s:%u:"
3675             " expected %s, got %s\n",
3676             macro, args, file, line,
3677             DECLSPEC2TXT(select), l ? DECLSPEC2TXT(l->class) : "null-link");
3678     exit(EXIT_FAILURE);
3679     return l; // never reached, makes compiler happy.
3680 }
3681
3682 /*--------------------------------------------------------------------*/
3683 /* newEnumType - create an integer type compatible with enumerations  */
3684 /*--------------------------------------------------------------------*/
3685 sym_link *
3686 newEnumType (symbol *enumlist)
3687 {
3688   int min, max, v;
3689   symbol *sym;
3690   sym_link *type;
3691
3692   if (!enumlist)
3693     {
3694       type = newLink (SPECIFIER);
3695       SPEC_NOUN (type) = V_INT;
3696       return type;
3697     }
3698
3699   /* Determine the range of the enumerated values */
3700   sym = enumlist;
3701   min = max = (int) ulFromVal (valFromType (sym->type));
3702   for (sym = sym->next; sym; sym = sym->next)
3703     {
3704       v = (int) ulFromVal (valFromType (sym->type));
3705       if (v<min)
3706         min = v;
3707       if (v>max)
3708         max = v;
3709     }
3710
3711   /* Determine the smallest integer type that is compatible with this range */
3712   type = newLink (SPECIFIER);
3713   if (min>=0 && max<=255)
3714     {
3715       SPEC_NOUN (type) = V_CHAR;
3716       SPEC_USIGN (type) = 1;
3717     }
3718   else if (min>=-128 && max<=127)
3719     {
3720       SPEC_NOUN (type) = V_CHAR;
3721     }
3722   else if (min>=0 && max<=65535)
3723     {
3724       SPEC_NOUN (type) = V_INT;
3725       SPEC_USIGN (type) = 1;
3726     }
3727   else if (min>=-32768 && max<=32767)
3728     {
3729       SPEC_NOUN (type) = V_INT;
3730     }
3731   else
3732     {
3733       SPEC_NOUN (type) = V_INT;
3734       SPEC_LONG (type) = 1;
3735       if (min>=0)
3736         SPEC_USIGN (type) = 1;
3737     }
3738
3739   return type;
3740 }