* src/pic16/glue.c (pic16_initPointer): avoid assertion, emit better
[fw/sdcc] / src / pic16 / glue.c
index 124f5a05d61f783a9ccbcf50ee7bd939ff360844..158aa8a5eb842663a1c7e847caa277d8c9c8dd6c 100644 (file)
 #include "gen.h"
 #include "device.h"
 #include "main.h"
-#include <string.h>
-
+#include "dbuf_string.h"
 #include <string.h>
 
 
-#ifdef WORDS_BIGENDIAN
-  #define _ENDIAN(x)  (3-x)
-#else
-  #define _ENDIAN(x)  (x)
-#endif
-
-#define BYTE_IN_LONG(x,b) ((x>>(8*_ENDIAN(b)))&0xff)
-
 extern symbol *interrupts[256];
 void pic16_printIval (symbol * sym, sym_link * type, initList * ilist, char ptype, void *p);
 extern int noAlloc;
@@ -52,9 +43,7 @@ extern unsigned maxInterrupts;
 extern int maxRegBank;
 extern symbol *mainf;
 extern char *VersionString;
-extern FILE *codeOutFile;
-extern set *tmpfileSet;
-extern set *tmpfileNameSet;
+extern struct dbuf_s *codeOutBuf;
 extern char *iComments1;
 extern char *iComments2;
 
@@ -62,6 +51,7 @@ extern int initsfpnt;
 extern unsigned long pFile_isize;
 
 extern unsigned long pic16_countInstructions();
+set *pic16_localFunctions = NULL;
 set *rel_idataSymSet=NULL;
 set *fix_idataSymSet=NULL;
 
@@ -71,7 +61,6 @@ extern DEFSETFUNC (rmTmpFiles);
 extern void pic16_AnalyzeBanking (void);
 extern void pic16_OptimizeJumps ();
 extern void pic16_OptimizeBanksel ();
-extern void copyFile (FILE * dest, FILE * src);
 extern void pic16_InlinepCode(void);
 extern void pic16_writeUsedRegs(FILE *);
 
@@ -86,7 +75,7 @@ extern void pic16_pCodeConstString(char *name, char *value);
 /*-----------------------------------------------------------------*/
 /* aopLiteral - string from a literal value                        */
 /*-----------------------------------------------------------------*/
-int pic16aopLiteral (value *val, int offset)
+unsigned int pic16aopLiteral (value *val, int offset)
 {
   union {
     float f;
@@ -95,12 +84,18 @@ int pic16aopLiteral (value *val, int offset)
 
   /* if it is a float then it gets tricky */
   /* otherwise it is fairly simple */
-  if (!IS_FLOAT(val->type)) {
+  if (!(IS_FLOAT(val->type) || IS_FIXED(val->type))) {
     unsigned long v = (unsigned long) floatFromVal(val);
 
     return ( (v >> (offset * 8)) & 0xff);
   }
 
+  if(IS_FIXED16X16(val->type)) {
+    unsigned long v = (unsigned long)fixed16x16FromDouble( floatFromVal( val ) );
+    
+    return ( (v >> (offset * 8)) & 0xff);
+  }
+
   /* it is type float */
   fl.f = (float) floatFromVal(val);
 #ifdef WORDS_BIGENDIAN
@@ -128,7 +123,7 @@ pic16emitRegularMap (memmap * map, bool addPublics, bool arFlag)
 //     fprintf(stderr, "%s:%d map name= %s\n", __FUNCTION__, __LINE__, map->sname);
        
        if(addPublics)
-               fprintf (map->oFile, ";\t.area\t%s\n", map->sname);
+               dbuf_printf (&map->oBuf, ";\t.area\t%s\n", map->sname);
                /* print the area name */
 
        for (sym = setFirstItem (map->syms); sym; sym = setNextItem (map->syms)) {
@@ -225,7 +220,7 @@ pic16emitRegularMap (memmap * map, bool addPublics, bool arFlag)
 //                             fprintf (stderr,"; %s == 0x%04x\t\treqv= %p nRegs= %d\n",
 //                                     sym->name, SPEC_ADDR (sym->etype), sym->reqv, sym->regType);
 
-                       fprintf (map->oFile, "%s\tEQU\t0x%04x\n",
+                       dbuf_printf (&map->oBuf, "%s\tEQU\t0x%04x\n",
                                sym->rname,
                                SPEC_ADDR (sym->etype));
 
@@ -313,13 +308,13 @@ pic16emitRegularMap (memmap * map, bool addPublics, bool arFlag)
                        if (IS_BITVAR (sym->etype)) {
                                bitvars++;
                        } else {
-                               fprintf (map->oFile, "\t%s\n", sym->rname);
+                               dbuf_printf (map->oBuf, "\t%s\n", sym->rname);
                                if ((size = (unsigned int) getSize (sym->type) & 0xffff) > 1) {
                                        for (i = 1; i < size; i++)
-                                               fprintf (map->oFile, "\t%s_%d\n", sym->rname, i);
+                                               dbuf_printf (map->oBuf, "\t%s_%d\n", sym->rname, i);
                                }
                        }
-                       fprintf (map->oFile, "\t.ds\t0x%04x\n", (unsigned int)getSize (sym->type) & 0xffff);
+                       dbuf_printf (map->oBuf, "\t.ds\t0x%04x\n", (unsigned int)getSize (sym->type) & 0xffff);
 #endif
                }
        
@@ -367,7 +362,7 @@ pic16emitRegularMap (memmap * map, bool addPublics, bool arFlag)
 
                        if(ival) {
                                setAstLineno(ival, sym->lineDef);
-                               codeOutFile = statsg->oFile;
+                               codeOutBuf = &statsg->oBuf;
                                GcurMemmap = statsg;
                                eBBlockFromiCode (iCodeFromAst (ival));
                                sym->ival = NULL;
@@ -396,7 +391,7 @@ value *pic16_initPointer (initList * ilist, sym_link *toType)
     goto wrong;
   
   /* try it the old way first */
-  if ((val = constExprValue (expr, FALSE)))
+  if (expr->etype && (val = constExprValue (expr, FALSE)))
     return val;
   
   /* ( ptr + constant ) */
@@ -427,8 +422,8 @@ value *pic16_initPointer (initList * ilist, sym_link *toType)
      a variable or address of an array element */
   if (IS_AST_OP (expr) && expr->opval.op == '&') {
     /* address of symbol */
-    if (IS_AST_SYM_VALUE (expr->left)) {
-      val = copyValue (AST_VALUE (expr->left));
+    if (IS_AST_SYM_VALUE (expr->left) && expr->left->etype) {
+      val = AST_VALUE (expr->left);
       val->type = newLink (DECLARATOR);
       if(SPEC_SCLS (expr->left->etype) == S_CODE) {
         DCL_TYPE (val->type) = CPOINTER;
@@ -538,7 +533,7 @@ void _pic16_printPointerType (const char *name, char ptype, void *p)
 void pic16_printPointerType (const char *name, char ptype, void *p)
 {
   _pic16_printPointerType (name, ptype, p);
-  pic16_flushDB(ptype, p);
+  //pic16_flushDB(ptype, p); /* breaks char* const arr[] = {&c, &c, &c}; */
 }
 
 /*-----------------------------------------------------------------*/
@@ -554,6 +549,7 @@ void pic16_printGPointerType (const char *iname, const unsigned int itype,
     switch( itype ) {
       case FPOINTER:
       case CPOINTER:
+      case GPOINTER:
       case FUNCTION:
         {
           sprintf(buf, "UPPER(%s)", iname);
@@ -569,7 +565,7 @@ void pic16_printGPointerType (const char *iname, const unsigned int itype,
         assert( 0 );
     }
 
-    pic16_flushDB(ptype, p);
+    //pic16_flushDB(ptype, p); /* might break char* const arr[] = {...}; */
 }
 
 
@@ -637,7 +633,7 @@ static int
 pic16_printIvalChar (symbol *sym, sym_link * type, initList * ilist, char *s, char ptype, void *p)
 {
   value *val;
-  int remain, len;
+  int remain, len, ilen;
 
   if(!p)
     return 0;
@@ -648,10 +644,14 @@ pic16_printIvalChar (symbol *sym, sym_link * type, initList * ilist, char *s, ch
 
   if(!s) {
     val = list2val (ilist);
+
     /* if the value is a character string  */
     if(IS_ARRAY (val->type) && IS_CHAR (val->etype)) {
+      /* length of initializer string (might contain \0, so do not use strlen) */
+      ilen = DCL_ELEM(val->type);
+
       if(!DCL_ELEM (type))
-        DCL_ELEM (type) = strlen (SPEC_CVAL (val->etype).v_char) + 1;
+        DCL_ELEM (type) = ilen;
 
       /* len is 0 if declartion equals initializer,
        * >0 if declaration greater than initializer
@@ -660,23 +660,20 @@ pic16_printIvalChar (symbol *sym, sym_link * type, initList * ilist, char *s, ch
        * if <0 then emit only the length of declaration elements
        * and warn user
        */
-      len = DCL_ELEM (type) - (strlen (SPEC_CVAL (val->etype).v_char)+1);
+      len = DCL_ELEM (type) - ilen;
 
-//      fprintf(stderr, "%s:%d len = %i DCL_ELEM(type) = %i SPEC_CVAL-len = %i\n", __FILE__, __LINE__,
-//        len, DCL_ELEM(type), strlen(SPEC_CVAL(val->etype).v_char));
+//      fprintf(stderr, "%s:%d ilen = %i len = %i DCL_ELEM(type) = %i SPEC_CVAL-len = %i\n", __FILE__, __LINE__,
+//        ilen, len, DCL_ELEM(type), strlen(SPEC_CVAL(val->etype).v_char));
 
-      remain=0;
       if(len >= 0) {
-        for(remain=0; remain<strlen(SPEC_CVAL(val->etype).v_char)+1; remain++)
+        /* emit initializer */
+        for(remain=0; remain<ilen; remain++)
           pic16_emitDB(SPEC_CVAL(val->etype).v_char[ remain ], ptype, p);
 
-        if(len>0) {
-          len -= remain;
+         /* fill array with 0x00 */
           while(len--) {
             pic16_emitDB(0x00, ptype, p);
           }
-        }
-
       } else {
         werror (W_EXCESS_INITIALIZERS, "array of chars", sym->name, sym->lineDef);
 
@@ -801,6 +798,7 @@ void pic16_printIvalBitFields(symbol **sym, initList **ilist, char ptype, void *
     i <<= SPEC_BSTR (lsym->etype);
     ival |= i;
     if (! ( lsym->next &&
+          (lilist && lilist->next) &&
           (IS_BITFIELD(lsym->next->type)) &&
           (SPEC_BSTR(lsym->next->etype)))) break;
     lsym = lsym->next;
@@ -809,19 +807,19 @@ void pic16_printIvalBitFields(symbol **sym, initList **ilist, char ptype, void *
   switch (size) {
   case 1:
        pic16_emitDB(BYTE_IN_LONG(ival, 0), ptype, p);
-        break;
+       break;
 
   case 2:
        pic16_emitDB(BYTE_IN_LONG(ival, 0), ptype, p);
        pic16_emitDB(BYTE_IN_LONG(ival, 1), ptype, p);
-        break;
+    break;
 
   case 4: /* EEP: why is this db and not dw? */
        pic16_emitDB(BYTE_IN_LONG(ival, 0), ptype, p);
        pic16_emitDB(BYTE_IN_LONG(ival, 1), ptype, p);
        pic16_emitDB(BYTE_IN_LONG(ival, 2), ptype, p);
        pic16_emitDB(BYTE_IN_LONG(ival, 3), ptype, p);
-        break;
+    break;
   default:
        /* VR - only 1,2,4 size long can be handled???? Why? */
        fprintf(stderr, "%s:%d: unhandled case. Contact author.\n", __FILE__, __LINE__);
@@ -857,7 +855,7 @@ void pic16_printIvalStruct (symbol * sym, sym_link * type,
     iloop = ilist->init.deep;
   }
 
-  for (; sflds; sflds = sflds->next, iloop = (iloop ? iloop->next : NULL)) {
+  for (; (sflds && iloop); sflds = sflds->next, iloop = (iloop ? iloop->next : NULL)) {
 //    fprintf(stderr, "%s:%d sflds: %p\tiloop = %p\n", __FILE__, __LINE__, sflds, iloop);
     if (IS_BITFIELD(sflds->type)) {
       pic16_printIvalBitFields(&sflds, &iloop, ptype, p);
@@ -871,6 +869,55 @@ void pic16_printIvalStruct (symbol * sym, sym_link * type,
   return;
 }
 
+/*-----------------------------------------------------------------*/
+/* printIvalUnion - generates initial value for unions             */
+/*-----------------------------------------------------------------*/
+void pic16_printIvalUnion (symbol * sym, sym_link * type,
+                 initList * ilist, char ptype, void *p)
+{
+  //symbol *sflds;
+  initList *iloop = NULL;
+  int i, size;
+
+
+#if DEBUG_PRINTIVAL
+  fprintf(stderr, "%s\n",__FUNCTION__);
+#endif
+
+  iloop = ilist;
+  i = 0;
+  while (iloop)
+  {
+    i++;
+    iloop = iloop->next;
+  } // while
+
+  size = -1;
+  if (type) size = SPEC_STRUCT(type)->size;
+
+  if (i == 1 && size >= 0 && size <= sizeof(long))
+  {
+    unsigned long val = (unsigned long)floatFromVal(list2val(ilist));
+    while (size--)
+    {
+      pic16_emitDB(val, ptype, p);
+      val >>= 8;
+    } // while
+    return;
+  } // if
+
+  fprintf( stderr, "INCOMPLETE SUPPORT FOR INITIALIZED union---FALLING BACK TO struct\n" );
+  fprintf( stderr, "This is a bug. Please file a bug-report with your source attached.\n" );
+  pic16_printIvalStruct( sym, type, ilist, ptype, p );
+}
+
+static int
+pic16_isUnion( symbol *sym, sym_link *type )
+{
+  if (type && SPEC_STRUCT(type)->type == UNION) return 1;
+  return 0;
+}
+
 /*--------------------------------------------------------------------------*/
 /* pic16_printIvalCharPtr - generates initial values for character pointers */
 /*--------------------------------------------------------------------------*/
@@ -1119,8 +1166,14 @@ void pic16_printIval (symbol * sym, sym_link * type, initList * ilist, char ptyp
   /* if structure then */
   if (IS_STRUCT (type))
     {
-//      fprintf(stderr,"%s struct\n",__FUNCTION__);
-      pic16_printIvalStruct (sym, type, ilist, ptype, p);
+      if (pic16_isUnion(sym, type))
+        {
+          //fprintf(stderr,"%s union\n",__FUNCTION__);
+          pic16_printIvalUnion (sym, type, ilist, ptype, p);
+       } else {
+          //fprintf(stderr,"%s struct\n",__FUNCTION__);
+          pic16_printIvalStruct (sym, type, ilist, ptype, p);
+        }
       return;
     }
 
@@ -1243,7 +1296,7 @@ CODESPACE: %d\tCONST: %d\tPTRCONST: %d\tSPEC_CONST: %d\n", __FUNCTION__,
         }
 
        /* if it is "extern" then do nothing */
-       if (IS_EXTERN (sym->etype) && !SPEC_ABSA(sym->etype)) {
+       if (IS_EXTERN (sym->etype)/* && !SPEC_ABSA(sym->etype)*/) {
                checkAddSym(&externs, sym);
          continue;
        }
@@ -1292,7 +1345,7 @@ CODESPACE: %d\tCONST: %d\tPTRCONST: %d\tSPEC_CONST: %d\n", __FUNCTION__,
              
              pic16_addpCode2pBlock(pb,pcf);
              pic16_addpCode2pBlock(pb,pic16_newpCodeLabel(sym->rname,-1));
-//           fprintf(stderr, "%s:%d [1] generating init for label: %s\n", __FILE__, __LINE__, sym->rname);
+             //fprintf(stderr, "%s:%d [1] generating init for label: %s\n", __FILE__, __LINE__, sym->rname);
              pic16_printIval(sym, sym->type, sym->ival, 'p', (void *)pb);
               pic16_flushDB('p', (void *)pb);
 
@@ -1305,7 +1358,7 @@ CODESPACE: %d\tCONST: %d\tPTRCONST: %d\tSPEC_CONST: %d\n", __FUNCTION__,
              /* symbol has absolute address but no initial value */
              
              /* allocate space */
-             fprintf (code->oFile, "%s:\n", sym->rname);
+             dbuf_printf (&code->oBuf, "%s:\n", sym->rname);
 
              /* special case for character strings */
              if (IS_ARRAY (sym->type) && IS_CHAR (sym->type->next) &&
@@ -1315,6 +1368,7 @@ CODESPACE: %d\tCONST: %d\tPTRCONST: %d\tSPEC_CONST: %d\n", __FUNCTION__,
 
                pic16_pCodeConstString(sym->rname , SPEC_CVAL (sym->etype).v_char);
              } else {
+               fprintf (stderr, "%s:%u(%s): do not know how to intialize symbol %s\n", __FILE__, __LINE__, __FUNCTION__, sym->rname);
                assert(0);
              }
            }
@@ -1329,7 +1383,7 @@ CODESPACE: %d\tCONST: %d\tPTRCONST: %d\tSPEC_CONST: %d\n", __FUNCTION__,
              pBlock *pb;
 
              /* symbol doesn't have absolute address but has initial value */
-             fprintf (code->oFile, "%s:\n", sym->rname);
+             dbuf_printf (&code->oBuf, "%s:\n", sym->rname);
              noAlloc++;
              resolveIvalSym (sym->ival, sym->type);
 
@@ -1342,10 +1396,9 @@ CODESPACE: %d\tCONST: %d\tPTRCONST: %d\tSPEC_CONST: %d\n", __FUNCTION__,
                
                didcode++;
              }
-                            
-//           fprintf(stderr, "%s:%d [2] generating init for label: %s\n", __FILE__, __LINE__, sym->rname);
 
              pic16_addpCode2pBlock(pb,pic16_newpCodeLabel(sym->rname,-1));
+             //fprintf(stderr, "%s:%d [2] generating init for label: %s\n", __FILE__, __LINE__, sym->rname);
              pic16_printIval(sym, sym->type, sym->ival, 'p', (void *)pb);
               pic16_flushDB('p', (void *)pb);
              noAlloc--;
@@ -1354,7 +1407,7 @@ CODESPACE: %d\tCONST: %d\tPTRCONST: %d\tSPEC_CONST: %d\n", __FUNCTION__,
              /* symbol doesn't have absolute address and no initial value */
              /* allocate space */
 //           fprintf(stderr, "%s:%d [3] generating init for label: %s\n", __FILE__, __LINE__, sym->rname);
-             fprintf (code->oFile, "%s:\n", sym->rname);
+             dbuf_printf (&code->oBuf, "%s:\n", sym->rname);
              /* special case for character strings */
              if (IS_ARRAY (sym->type) && IS_CHAR (sym->type->next) &&
                  SPEC_CVAL (sym->etype).v_char) {
@@ -1379,7 +1432,7 @@ void pic16_emitConfigRegs(FILE *of)
 {
   int i;
 
-       for(i=0;i<pic16->cwInfo.confAddrEnd-pic16->cwInfo.confAddrStart;i++)
+       for(i=0;i<=(pic16->cwInfo.confAddrEnd-pic16->cwInfo.confAddrStart);i++)
                if(pic16->cwInfo.crInfo[i].emit)        //mask != -1)
                        fprintf (of, "\t__config 0x%x, 0x%hhx\n",
                                pic16->cwInfo.confAddrStart+i,
@@ -1390,7 +1443,7 @@ void pic16_emitIDRegs(FILE *of)
 {
   int i;
 
-       for(i=0;i<pic16->idInfo.idAddrEnd-pic16->idInfo.idAddrStart;i++)
+       for(i=0;i<=(pic16->idInfo.idAddrEnd-pic16->idInfo.idAddrStart);i++)
                if(pic16->idInfo.irInfo[i].emit)
                        fprintf (of, "\t__idlocs 0x%06x, 0x%hhx\n",
                                pic16->idInfo.idAddrStart+i,
@@ -1411,13 +1464,14 @@ pic16emitMaps ()
   pic16emitRegularMap (sfrbit, FALSE, FALSE);
   pic16emitRegularMap (code, TRUE, FALSE);
   pic16emitStaticSeg (statsg);
+  pic16emitStaticSeg (c_abs);
 }
 
 /*-----------------------------------------------------------------*/
 /* createInterruptVect - creates the interrupt vector              */
 /*-----------------------------------------------------------------*/
 static void
-pic16createInterruptVect (FILE * vFile)
+pic16createInterruptVect (struct dbuf_s * vBuf)
 {
        /* if the main is only a prototype ie. no body then do nothing */
 #if 0
@@ -1430,8 +1484,8 @@ pic16createInterruptVect (FILE * vFile)
 #endif
 #if 0
        if((!pic16_options.omit_ivt) || (pic16_options.omit_ivt && pic16_options.leave_reset)) {
-               fprintf (vFile, ";\t.area\t%s\n", CODE_NAME);
-               fprintf(vFile, ".intvecs\tcode\t0x%06x\n", pic16_options.ivt_loc);
+               dbuf_printf (vBuf, ";\t.area\t%s\n", CODE_NAME);
+               dbuf_printf (vBuf, ".intvecs\tcode\t0x%06x\n", pic16_options.ivt_loc);
 
                /* this is an overkill since WE are the port,
                 * and we know if we have a genIVT function! */
@@ -1452,16 +1506,54 @@ pic16initialComments (FILE * afile)
 {
        initialComments (afile);
        fprintf (afile, "; PIC16 port for the Microchip 16-bit core micros\n");
+       if(xinst)
+         fprintf (afile, "; * Extended Instruction Set\n");
+         
        if(pic16_mplab_comp)
-               fprintf(afile, "; MPLAB/MPASM/MPASMWIN/MPLINK compatibility mode enabled\n");
+               fprintf(afile, "; MPLAB/MPASM/MPASMWIN/MPLINK compatibility mode enabled\n");
        fprintf (afile, iComments2);
 
        if(options.debug) {
-               fprintf (afile, "\n\t.ident \"SDCC version %s #%s [pic16 port]\"\n",
-                               SDCC_VERSION_STR, getBuildNumber() );
+               fprintf (afile, "\n\t.ident \"SDCC version %s #%s [pic16 port]%s\"\n",
+                               SDCC_VERSION_STR, getBuildNumber(), (!xinst?"":" {extended}") );
        }
 }
 
+int
+pic16_stringInSet(const char *str, set **world, int autoAdd)
+{
+  char *s;
+
+  if (!str) return 1;
+  assert(world);
+
+  for (s = setFirstItem(*world); s; s = setNextItem(*world))
+  {
+    /* found in set */
+    if (0 == strcmp(s, str)) return 1;
+  }
+
+  /* not found */
+  if (autoAdd) addSet(world, Safe_strdup(str));
+  return 0;
+}
+
+static int
+pic16_emitSymbolIfNew(FILE *file, const char *fmt, const char *sym, int checkLocals)
+{
+  static set *emitted = NULL;
+
+  if (!pic16_stringInSet(sym, &emitted, 1)) {
+    /* sym was not in emittedSymbols */
+    if (!checkLocals || !pic16_stringInSet(sym, &pic16_localFunctions, 0)) {
+      /* sym is not a locally defined function---avoid bug #1443651 */
+      fprintf( file, fmt, sym );
+      return 0;
+    }
+  }
+  return 1;
+}
+
 /*-----------------------------------------------------------------*/
 /* printPublics - generates global declarations for publics        */
 /*-----------------------------------------------------------------*/
@@ -1477,7 +1569,7 @@ pic16printPublics (FILE *afile)
        for(sym = setFirstItem (publics); sym; sym = setNextItem (publics))
          /* sanity check */
          if(!IS_STATIC(sym->etype))
-               fprintf(afile, "\tglobal %s\n", sym->rname);
+               pic16_emitSymbolIfNew(afile, "\tglobal %s\n", sym->rname, 0);
 }
 
 /*-----------------------------------------------------------------*/
@@ -1497,22 +1589,22 @@ pic16_printExterns(FILE *afile)
        fprintf(afile, "%s", iComments2);
        
        for(sym = setFirstItem(externs); sym; sym = setNextItem(externs))
-               fprintf(afile, "\textern %s\n", sym->rname);
+               pic16_emitSymbolIfNew(afile, "\textern %s\n", sym->rname, 1);
 
        for(sym = setFirstItem(pic16_builtin_functions); sym; sym = setNextItem(pic16_builtin_functions))
-               fprintf(afile, "\textern _%s\n", sym->name);
+               pic16_emitSymbolIfNew(afile, "\textern _%s\n", sym->name, 1);
 }
 
 /*-----------------------------------------------------------------*/
 /* emitOverlay - will emit code for the overlay stuff              */
 /*-----------------------------------------------------------------*/
 static void
-pic16emitOverlay (FILE * afile)
+pic16emitOverlay (struct dbuf_s *aBuf)
 {
   set *ovrset;
 
   if (!elementsInSet (ovrSetSets))
-    fprintf (afile, ";\t.area\t%s\n", port->mem.overlay_name);
+    dbuf_printf (aBuf, ";\t.area\t%s\n", port->mem.overlay_name);
 
   /* for each of the sets in the overlay segment do */
   for (ovrset = setFirstItem (ovrSetSets); ovrset;
@@ -1527,9 +1619,9 @@ pic16emitOverlay (FILE * afile)
             otherwise the assembler will append each of these
             declarations into one chunk and will not overlay
             sad but true */
-         fprintf (afile, ";\t.area _DUMMY\n");
+         dbuf_printf (aBuf, ";\t.area _DUMMY\n");
          /* output the area informtion */
-         fprintf (afile, ";\t.area\t%s\n", port->mem.overlay_name);    /* MOF */
+         dbuf_printf (aBuf, ";\t.area\t%s\n", port->mem.overlay_name); /* MOF */
        }
 
       for (sym = setFirstItem (ovrset); sym;
@@ -1569,20 +1661,20 @@ pic16emitOverlay (FILE * afile)
            {
 
              if (options.debug || sym->level == 0)
-               fprintf (afile, " == 0x%04x\n", SPEC_ADDR (sym->etype));
+               dbuf_printf (aBuf, " == 0x%04x\n", SPEC_ADDR (sym->etype));
 
-             fprintf (afile, "%s\t=\t0x%04x\n",
+             dbuf_printf (aBuf, "%s\t=\t0x%04x\n",
                       sym->rname,
                       SPEC_ADDR (sym->etype));
            }
          else
            {
              if (options.debug || sym->level == 0)
-               fprintf (afile, "==.\n");
+               dbuf_printf (aBuf, "==.\n");
 
              /* allocate space */
-             fprintf (afile, "%s:\n", sym->rname);
-             fprintf (afile, "\t.ds\t0x%04x\n", (unsigned int) getSize (sym->type) & 0xffff);
+             dbuf_printf (aBuf, "%s:\n", sym->rname);
+             dbuf_printf (aBuf, "\t.ds\t0x%04x\n", (unsigned int) getSize (sym->type) & 0xffff);
            }
 
        }
@@ -1591,17 +1683,20 @@ pic16emitOverlay (FILE * afile)
 
 void emitStatistics(FILE *asmFile)
 {
-  unsigned long isize, udsize;
+  unsigned long isize, udsize, ramsize;
   statistics.isize = pic16_countInstructions();
   isize = (statistics.isize >= 0) ? statistics.isize : 0;
   udsize = (statistics.udsize >= 0) ? statistics.udsize : 0;
+  ramsize = pic16 ? pic16->RAMsize : 0x200;
+  ramsize -= 256; /* ignore access bank and SFRs */
+  if (ramsize == 0) ramsize = 64; /* prevent division by zero (below) */
        
   fprintf (asmFile, "\n\n; Statistics:\n");
-  fprintf (asmFile, "; code size:\t%5ld (0x%04lx) bytes (%3.2f%%)\n;           \t%5ld (0x%04lx) words\n",
-    isize, isize, (isize*100.0)/(128 << 10),
+  fprintf (asmFile, "; code size:\t%5ld (0x%04lx) bytes (%5.2f%%)\n;           \t%5ld (0x%04lx) words\n",
+    isize, isize, (isize*100.0)/(128UL << 10),
     isize>>1, isize>>1);
-  fprintf (asmFile, "; udata size:\t%5ld (0x%04lx) bytes (%3.2f%%)\n",
-    udsize, udsize, (udsize*100.0) / ((pic16 ? pic16->RAMsize : 0x200) -256));
+  fprintf (asmFile, "; udata size:\t%5ld (0x%04lx) bytes (%5.2f%%)\n",
+    udsize, udsize, (udsize*100.0) / (1.0 * ramsize));
   fprintf (asmFile, "; access size:\t%5ld (0x%04lx) bytes\n",
     statistics.intsize, statistics.intsize);
 
@@ -1616,16 +1711,18 @@ void emitStatistics(FILE *asmFile)
 void
 pic16glue ()
 {
-  FILE *vFile;
   FILE *asmFile;
-  FILE *ovrFile = tempfile();
+  struct dbuf_s ovrBuf;
+  struct dbuf_s vBuf;
+
+    dbuf_init(&ovrBuf, 4096);
+    dbuf_init(&vBuf, 4096);
 
     mainf = newSymbol ("main", 0);
     mainf->block = 0;
 
     mainf = findSymWithLevel(SymbolTab, mainf);
 
-    addSetHead(&tmpfileSet,ovrFile);
     pic16_pCodeInitRegisters();
 
     if(pic16_options.no_crt && mainf && IFFUNC_HASBODY(mainf->type)) {
@@ -1666,20 +1763,17 @@ pic16glue ()
 
     /* print the global struct definitions */
 
-    vFile = tempfile();
     /* PENDING: this isnt the best place but it will do */
     if (port->general.glue_up_main) {
       /* create the interrupt vector table */
-      pic16createInterruptVect (vFile);
+      pic16createInterruptVect (&vBuf);
     }
 
-    addSetHead(&tmpfileSet,vFile);
-    
     /* emit code for the all the variables declared */
     pic16emitMaps ();
 
     /* do the overlay segments */
-    pic16emitOverlay(ovrFile);
+    pic16emitOverlay(&ovrBuf);
     pic16_AnalyzepCode('*');
 
 #if 1
@@ -1746,12 +1840,12 @@ pic16glue ()
       pic16_OptimizeJumps();
     }
 
-    /* print the extern variables to this module */
-    pic16_printExterns(asmFile);
-       
     /* print the global variables in this module */
     pic16printPublics (asmFile);
 
+    /* print the extern variables to this module */
+    pic16_printExterns(asmFile);
+       
     pic16_writeUsedRegs(asmFile);
 
 #if 0
@@ -1772,7 +1866,7 @@ pic16glue ()
     fprintf (asmFile, "%s", iComments2);
     fprintf (asmFile, "; external ram data\n");
     fprintf (asmFile, "%s", iComments2);
-    copyFile (asmFile, xdata->oFile);
+    dbuf_write_and_destroy (&xdata->oBuf, asmFile);
 #endif
 
 #if 0
@@ -1780,7 +1874,7 @@ pic16glue ()
     fprintf (asmFile, "%s", iComments2);
     fprintf (asmFile, "; bit data\n");
     fprintf (asmFile, "%s", iComments2);
-    copyFile (asmFile, bit->oFile);
+    dbuf_write_and_destroy (&bit->oBuf, asmFile);
 #endif
 
     /* copy the interrupt vector table */
@@ -1788,7 +1882,7 @@ pic16glue ()
       fprintf (asmFile, "\n%s", iComments2);
       fprintf (asmFile, "; interrupt vector \n");
       fprintf (asmFile, "%s", iComments2);
-      copyFile (asmFile, vFile);
+      dbuf_write_and_destroy (&vBuf, asmFile);
     }
     
     /* copy global & static initialisations */
@@ -1808,7 +1902,7 @@ pic16glue ()
       }
     }
 
-//    copyFile (stderr, code->oFile);
+//    dbuf_write_and_destroy (&code->oBuf, stderr);
 
     fprintf(asmFile, "; I code from now on!\n");
     pic16_copypCode(asmFile, 'I');
@@ -1842,6 +1936,4 @@ pic16glue ()
 
     fprintf (asmFile,"\tend\n");
     fclose (asmFile);
-    
-    rm_tmpfiles();
 }