d73acaa0cd4286f85f442266ddc76aafefc68d8a
[fw/sdcc] / src / z80 / ralloc.c
1 /** @name Z80 Register allocation functions.
2     @author Michael Hope
3
4     Note: much of this is ripped straight from Sandeep's mcs51 code.
5
6     This code maps the virtual symbols and code onto the real
7     hardware.  It allocates based on usage and how long the varible
8     lives into registers or temporary memory on the stack.
9
10     On the Z80 hl and ix and a are reserved for the code generator,
11     leaving bc and de for allocation.  iy is unusable due to currently
12     as it's only adressable as a pair.  The extra register pressure
13     from reserving hl is made up for by how much easier the sub
14     operations become.  You could swap hl for iy if the undocumented
15     iyl/iyh instructions are available.
16
17     The stack frame is the common ix-bp style.  Basically:
18
19     ix+4+n:     param 1 
20     ix+4:       param 0 
21     ix+2:       return address 
22     ix+0:       calling functions ix 
23     ix-n:       local varibles 
24     ...  
25     sp:         end of local varibles
26
27     There is currently no support for bit spaces or banked functions.
28     
29     This program is free software; you can redistribute it and/or
30     modify it under the terms of the GNU General Public License as
31     published by the Free Software Foundation; either version 2, or (at
32     your option) any later version.  This program is distributed in the
33     hope that it will be useful, but WITHOUT ANY WARRANTY; without even
34     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
35     PURPOSE.  See the GNU General Public License for more details.
36     
37     You should have received a copy of the GNU General Public License
38     along with this program; if not, write to the Free Software
39     Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307,
40     USA.  In other words, you are welcome to use, share and improve
41     this program.  You are forbidden to forbid anyone else to use,
42     share and improve what you give them.  Help stamp out
43     software-hoarding!  
44 */
45
46 #include "z80.h"
47 #include "SDCCicode.h"
48
49 /* Flags to turn off optimisations.
50  */
51 enum
52   {
53     DISABLE_PACK_ACC = 0,
54     DISABLE_PACK_ASSIGN = 0,
55     DISABLE_PACK_ONE_USE = 0,
56     DISABLE_PACK_HL = 0,
57     DISABLE_PACK_IY = 0
58   };
59
60 /* Flags to turn on debugging code.
61  */
62 enum
63   {
64     D_ALLOC = 0,
65     D_ALLOC2 = 0,
66     D_ACCUSE2 = 0,
67     D_ACCUSE2_VERBOSE = 0,
68     D_HLUSE = 0,
69     D_HLUSE2 = 0,
70     D_HLUSE2_VERBOSE = 0,
71     D_FILL_GAPS = 0,
72     D_PACK_IY = 0,
73     D_PACK_HLUSE3 = 0
74   };
75
76 #if 1
77 #define D(_a, _s)       if (_a)  { printf _s; fflush(stdout); }
78 #else
79 #define D(_a, _s)
80 #endif
81
82 #define DISABLE_PACKREGSFORSUPPORT      1
83 #define DISABLE_PACKREGSFORACCUSE       1
84
85 extern void genZ80Code (iCode *);
86
87 /** Local static variables */
88 static struct
89 {
90   bitVect *spiltSet;
91   set *stackSpil;
92   bitVect *regAssigned;
93   bitVect *totRegAssigned;    /* final set of LRs that got into registers */
94   short blockSpil;
95   int slocNum;
96   /* registers used in a function */
97   bitVect *funcrUsed;
98   int stackExtend;
99   int dataExtend;
100   int nRegs;
101 } _G;
102
103 static regs _gbz80_regs[] =
104 {
105   {REG_GPR, C_IDX, "c", 1},
106   {REG_GPR, B_IDX, "b", 1},
107   {REG_CND, CND_IDX, "c", 1}
108 };
109
110 static regs _z80_regs[] =
111 {
112   {REG_GPR, C_IDX, "c", 1},
113   {REG_GPR, B_IDX, "b", 1},
114   {REG_GPR, E_IDX, "e", 1},
115   {REG_GPR, D_IDX, "d", 1},
116   {REG_CND, CND_IDX, "c", 1}
117 };
118
119 regs *regsZ80;
120
121 /** Number of usable registers (all but C) */
122 #define Z80_MAX_REGS ((sizeof(_z80_regs)/sizeof(_z80_regs[0]))-1)
123 #define GBZ80_MAX_REGS ((sizeof(_gbz80_regs)/sizeof(_gbz80_regs[0]))-1)
124
125 static void spillThis (symbol *);
126 static void freeAllRegs ();
127
128 /** Allocates register of given type.
129     'type' is not used on the z80 version.  It was used to select
130     between pointer and general purpose registers on the mcs51 version.
131
132     @return             Pointer to the newly allocated register.
133  */
134 static regs *
135 allocReg (short type)
136 {
137   int i;
138
139   for (i = 0; i < _G.nRegs; i++)
140     {
141       /* For now we allocate from any free */
142       if (regsZ80[i].isFree)
143         {
144           regsZ80[i].isFree = 0;
145           if (currFunc)
146             {
147               currFunc->regsUsed = bitVectSetBit (currFunc->regsUsed, i);
148             }
149           D (D_ALLOC, ("allocReg: alloced %p\n", &regsZ80[i]));
150           return &regsZ80[i];
151         }
152     }
153   D (D_ALLOC, ("allocReg: No free.\n"));
154   return NULL;
155 }
156
157 /** Returns pointer to register wit index number
158  */
159 regs *
160 regWithIdx (int idx)
161 {
162   int i;
163
164   for (i = 0; i < _G.nRegs; i++)
165     {
166       if (regsZ80[i].rIdx == idx)
167         {
168           return &regsZ80[i];
169         }
170     }
171
172   wassertl (0, "regWithIdx not found");
173   exit (1);
174 }
175
176 /** Frees a register.
177  */
178 static void 
179 freeReg (regs * reg)
180 {
181   wassert (!reg->isFree);
182   reg->isFree = 1;
183   D (D_ALLOC, ("freeReg: freed %p\n", reg));
184 }
185
186
187 /** Returns number of free registers.
188  */
189 static int 
190 nFreeRegs (int type)
191 {
192   int i;
193   int nfr = 0;
194
195   for (i = 0; i < _G.nRegs; i++)
196     {
197       /* For now only one reg type */
198       if (regsZ80[i].isFree)
199         {
200           nfr++;
201         }
202     }
203   return nfr;
204 }
205
206 /** Free registers with type.
207  */
208 static int 
209 nfreeRegsType (int type)
210 {
211   int nfr;
212   if (type == REG_PTR)
213     {
214       if ((nfr = nFreeRegs (type)) == 0)
215         {
216           return nFreeRegs (REG_GPR);
217         }
218     }
219
220   return nFreeRegs (type);
221 }
222
223 /*-----------------------------------------------------------------*/
224 /* useReg - marks a register  as used                              */
225 /*-----------------------------------------------------------------*/
226 static void
227 useReg (regs * reg)
228 {
229   reg->isFree = 0;
230 }
231
232 #if 0
233 /*-----------------------------------------------------------------*/
234 /* allDefsOutOfRange - all definitions are out of a range          */
235 /*-----------------------------------------------------------------*/
236 static bool 
237 allDefsOutOfRange (bitVect * defs, int fseq, int toseq)
238 {
239   int i;
240
241   if (!defs)
242     return TRUE;
243
244   for (i = 0; i < defs->size; i++)
245     {
246       iCode *ic;
247
248       if (bitVectBitValue (defs, i) &&
249           (ic = hTabItemWithKey (iCodehTab, i)) &&
250           (ic->seq >= fseq && ic->seq <= toseq))
251
252         return FALSE;
253
254     }
255
256   return TRUE;
257 }
258 #endif
259
260 /*-----------------------------------------------------------------*/
261 /* computeSpillable - given a point find the spillable live ranges */
262 /*-----------------------------------------------------------------*/
263 static bitVect *
264 computeSpillable (iCode * ic)
265 {
266   bitVect *spillable;
267
268   /* spillable live ranges are those that are live at this 
269      point . the following categories need to be subtracted
270      from this set. 
271      a) - those that are already spilt
272      b) - if being used by this one
273      c) - defined by this one */
274
275   spillable = bitVectCopy (ic->rlive);
276   spillable =
277     bitVectCplAnd (spillable, _G.spiltSet);     /* those already spilt */
278   spillable =
279     bitVectCplAnd (spillable, ic->uses);        /* used in this one */
280   bitVectUnSetBit (spillable, ic->defKey);
281   spillable = bitVectIntersect (spillable, _G.regAssigned);
282
283   return spillable;
284 }
285
286 /*-----------------------------------------------------------------*/
287 /* noSpilLoc - return true if a variable has no spil location      */
288 /*-----------------------------------------------------------------*/
289 static int 
290 noSpilLoc (symbol * sym, eBBlock * ebp, iCode * ic)
291 {
292   return (sym->usl.spillLoc ? 0 : 1);
293 }
294
295 /*-----------------------------------------------------------------*/
296 /* hasSpilLoc - will return 1 if the symbol has spil location      */
297 /*-----------------------------------------------------------------*/
298 static int 
299 hasSpilLoc (symbol * sym, eBBlock * ebp, iCode * ic)
300 {
301   return (sym->usl.spillLoc ? 1 : 0);
302 }
303
304 /** Will return 1 if the remat flag is set.
305     A symbol is rematerialisable if it doesnt need to be allocated
306     into registers at creation as it can be re-created at any time -
307     i.e. it's constant in some way.
308 */
309 static int 
310 rematable (symbol * sym, eBBlock * ebp, iCode * ic)
311 {
312   return sym->remat;
313 }
314
315 /*-----------------------------------------------------------------*/
316 /* allLRs - return true for all                                    */
317 /*-----------------------------------------------------------------*/
318 static int 
319 allLRs (symbol * sym, eBBlock * ebp, iCode * ic)
320 {
321   return 1;
322 }
323
324 /** liveRangesWith - applies function to a given set of live range 
325  */
326 static set *
327 liveRangesWith (bitVect * lrs, int (func) (symbol *, eBBlock *, iCode *),
328                 eBBlock * ebp, iCode * ic)
329 {
330   set *rset = NULL;
331   int i;
332
333   if (!lrs || !lrs->size)
334     return NULL;
335
336   for (i = 1; i < lrs->size; i++)
337     {
338       symbol *sym;
339       if (!bitVectBitValue (lrs, i))
340         continue;
341
342       /* if we don't find it in the live range 
343          hash table we are in serious trouble */
344       if (!(sym = hTabItemWithKey (liveRanges, i)))
345         {
346           wassertl (0, "liveRangesWith could not find liveRange");
347           exit (1);
348         }
349
350       if (func (sym, ebp, ic) && bitVectBitValue (_G.regAssigned, sym->key))
351         {
352           addSetHead (&rset, sym);
353         }
354     }
355
356   return rset;
357 }
358
359
360 /** leastUsedLR - given a set determines which is the least used 
361  */
362 static symbol *
363 leastUsedLR (set * sset)
364 {
365   symbol *sym = NULL, *lsym = NULL;
366
367   sym = lsym = setFirstItem (sset);
368
369   if (!lsym)
370     return NULL;
371
372   for (; lsym; lsym = setNextItem (sset))
373     {
374
375       /* if usage is the same then prefer
376          the spill the smaller of the two */
377       if (lsym->used == sym->used)
378         if (getSize (lsym->type) < getSize (sym->type))
379           sym = lsym;
380
381       /* if less usage */
382       if (lsym->used < sym->used)
383         sym = lsym;
384
385     }
386
387   setToNull ((void **) &sset);
388   sym->blockSpil = 0;
389   return sym;
390 }
391
392 /** noOverLap - will iterate through the list looking for over lap
393  */
394 static int 
395 noOverLap (set * itmpStack, symbol * fsym)
396 {
397   symbol *sym;
398
399   for (sym = setFirstItem (itmpStack); sym;
400        sym = setNextItem (itmpStack))
401     {
402       if (bitVectBitValue(sym->clashes,fsym->key)) 
403         return 0;
404 #if 0
405             // if sym starts before (or on) our end point
406             // and ends after (or on) our start point, 
407             // it is an overlap.
408             if (sym->liveFrom <= fsym->liveTo &&
409                 sym->liveTo   >= fsym->liveFrom)
410             {
411                 return 0;
412             }
413 #endif
414     }
415   return 1;
416 }
417
418 /*-----------------------------------------------------------------*/
419 /* isFree - will return 1 if the a free spil location is found     */
420 /*-----------------------------------------------------------------*/
421 DEFSETFUNC (isFree)
422 {
423   symbol *sym = item;
424   V_ARG (symbol **, sloc);
425   V_ARG (symbol *, fsym);
426
427   /* if already found */
428   if (*sloc)
429     return 0;
430
431   /* if it is free && and the itmp assigned to
432      this does not have any overlapping live ranges
433      with the one currently being assigned and
434      the size can be accomodated  */
435   if (sym->isFree &&
436       noOverLap (sym->usl.itmpStack, fsym) &&
437       getSize (sym->type) >= getSize (fsym->type))
438     {
439       *sloc = sym;
440       return 1;
441     }
442
443   return 0;
444 }
445
446 /*-----------------------------------------------------------------*/
447 /* createStackSpil - create a location on the stack to spil        */
448 /*-----------------------------------------------------------------*/
449 static symbol *
450 createStackSpil (symbol * sym)
451 {
452   symbol *sloc = NULL;
453
454   D (D_ALLOC, ("createStackSpil: for sym %p\n", sym));
455
456   /* first go try and find a free one that is already 
457      existing on the stack */
458   if (applyToSet (_G.stackSpil, isFree, &sloc, sym))
459     {
460       /* found a free one : just update & return */
461       sym->usl.spillLoc = sloc;
462       sym->stackSpil = 1;
463       sloc->isFree = 0;
464       addSetHead (&sloc->usl.itmpStack, sym);
465       D (D_ALLOC, ("createStackSpil: found existing\n"));
466       return sym;
467     }
468
469   /* could not then have to create one , this is the hard part
470      we need to allocate this on the stack : this is really a
471      hack!! but cannot think of anything better at this time */
472
473   sprintf (buffer, "sloc%d", _G.slocNum++);
474   sloc = newiTemp (buffer);
475
476   /* set the type to the spilling symbol */
477   sloc->type = copyLinkChain (sym->type);
478   sloc->etype = getSpec (sloc->type);
479   SPEC_SCLS (sloc->etype) = S_AUTO;
480   SPEC_EXTR (sloc->etype) = 0;
481   SPEC_STAT (sloc->etype) = 0;
482   SPEC_VOLATILE(sloc->etype) = 0;
483
484   allocLocal (sloc);
485
486   sloc->isref = 1;              /* to prevent compiler warning */
487
488   /* if it is on the stack then update the stack */
489   if (IN_STACK (sloc->etype))
490     {
491       currFunc->stack += getSize (sloc->type);
492       _G.stackExtend += getSize (sloc->type);
493     }
494   else
495     {
496       _G.dataExtend += getSize (sloc->type);
497     }
498
499   /* add it to the stackSpil set */
500   addSetHead (&_G.stackSpil, sloc);
501   sym->usl.spillLoc = sloc;
502   sym->stackSpil = 1;
503
504   /* add it to the set of itempStack set 
505      of the spill location */
506   addSetHead (&sloc->usl.itmpStack, sym);
507
508   D (D_ALLOC, ("createStackSpil: created new\n"));
509   return sym;
510 }
511
512 /*-----------------------------------------------------------------*/
513 /* spillThis - spils a specific operand                            */
514 /*-----------------------------------------------------------------*/
515 static void 
516 spillThis (symbol * sym)
517 {
518   int i;
519
520   D (D_ALLOC, ("spillThis: spilling %p\n", sym));
521
522   /* if this is rematerializable or has a spillLocation
523      we are okay, else we need to create a spillLocation
524      for it */
525   if (!(sym->remat || sym->usl.spillLoc))
526     {
527       createStackSpil (sym);
528     }
529
530   /* mark it has spilt & put it in the spilt set */
531   sym->isspilt = sym->spillA = 1;
532   _G.spiltSet = bitVectSetBit (_G.spiltSet, sym->key);
533
534   bitVectUnSetBit (_G.regAssigned, sym->key);
535   bitVectUnSetBit (_G.totRegAssigned, sym->key);
536
537   for (i = 0; i < sym->nRegs; i++)
538     {
539       if (sym->regs[i])
540         {
541           freeReg (sym->regs[i]);
542           sym->regs[i] = NULL;
543         }
544     }
545
546   if (sym->usl.spillLoc && !sym->remat)
547     {
548       sym->usl.spillLoc->allocreq++;
549     }
550   return;
551 }
552
553 #if DISABLED
554 /*-----------------------------------------------------------------*/
555 /* allDefsOutOfRange - all definitions are out of a range          */
556 /*-----------------------------------------------------------------*/
557 static bool
558 allDefsOutOfRange (bitVect * defs, int fseq, int toseq)
559 {
560   int i;
561
562   if (!defs)
563     return TRUE;
564
565   for (i = 0; i < defs->size; i++)
566     {
567       iCode *ic;
568
569       if (bitVectBitValue (defs, i) &&
570           (ic = hTabItemWithKey (iCodehTab, i)) &&
571           (ic->seq >= fseq && ic->seq <= toseq))
572
573         return FALSE;
574
575     }
576
577   return TRUE;
578 }
579
580 /*-----------------------------------------------------------------*/
581 /* hasSpilLocnoUptr - will return 1 if the symbol has spil location */
582 /*                    but is not used as a pointer                 */
583 /*-----------------------------------------------------------------*/
584 static int
585 hasSpilLocnoUptr (symbol * sym, eBBlock * ebp, iCode * ic)
586 {
587   return ((sym->usl.spillLoc && !sym->uptr) ? 1 : 0);
588 }
589
590 /*-----------------------------------------------------------------*/
591 /* notUsedInBlock - not used in this block                         */
592 /*-----------------------------------------------------------------*/
593 static int
594 notUsedInBlock (symbol * sym, eBBlock * ebp, iCode * ic)
595 {
596   return (!bitVectBitsInCommon (sym->defs, ebp->usesDefs) &&
597           allDefsOutOfRange (sym->defs, ebp->fSeq, ebp->lSeq));
598 /*     return (!bitVectBitsInCommon(sym->defs,ebp->usesDefs)); */
599 }
600
601 /*-----------------------------------------------------------------*/
602 /* notUsedInRemaining - not used or defined in remain of the block */
603 /*-----------------------------------------------------------------*/
604 static int
605 notUsedInRemaining (symbol * sym, eBBlock * ebp, iCode * ic)
606 {
607   return ((usedInRemaining (operandFromSymbol (sym), ic) ? 0 : 1) &&
608           allDefsOutOfRange (sym->defs, ebp->fSeq, ebp->lSeq));
609 }
610 #endif
611
612 /** Select a iTemp to spil : rather a simple procedure.
613  */
614 symbol *
615 selectSpil (iCode * ic, eBBlock * ebp, symbol * forSym)
616 {
617   bitVect *lrcs = NULL;
618   set *selectS;
619   symbol *sym;
620
621   D (D_ALLOC, ("selectSpil: finding spill for ic %p\n", ic));
622   /* get the spillable live ranges */
623   lrcs = computeSpillable (ic);
624
625   /* get all live ranges that are rematerizable */
626   if ((selectS = liveRangesWith (lrcs, rematable, ebp, ic)))
627     {
628       D (D_ALLOC, ("selectSpil: using remat.\n"));
629       /* return the least used of these */
630       return leastUsedLR (selectS);
631     }
632
633 #if 0
634   /* get live ranges with spillLocations in direct space */
635   if ((selectS = liveRangesWith (lrcs, directSpilLoc, ebp, ic)))
636     {
637       sym = leastUsedLR (selectS);
638       strcpy (sym->rname, (sym->usl.spillLoc->rname[0] ?
639                            sym->usl.spillLoc->rname :
640                            sym->usl.spillLoc->name));
641       sym->spildir = 1;
642       /* mark it as allocation required */
643       sym->usl.spillLoc->allocreq++;
644       return sym;
645     }
646
647   /* if the symbol is local to the block then */
648   if (forSym->liveTo < ebp->lSeq)
649     {
650
651       /* check if there are any live ranges allocated
652          to registers that are not used in this block */
653       if (!_G.blockSpil && (selectS = liveRangesWith (lrcs, notUsedInBlock, ebp, ic)))
654         {
655           sym = leastUsedLR (selectS);
656           /* if this is not rematerializable */
657           if (!sym->remat)
658             {
659               _G.blockSpil++;
660               wassertl (0, "Attempted to do an unsupported block spill");
661               sym->blockSpil = 1;
662             }
663           return sym;
664         }
665
666       /* check if there are any live ranges that not
667          used in the remainder of the block */
668       if (!_G.blockSpil && (selectS = liveRangesWith (lrcs, notUsedInRemaining, ebp, ic)))
669         {
670           sym = leastUsedLR (selectS);
671           if (sym != forSym)
672             {
673               if (!sym->remat)
674                 {
675                   wassertl (0, "Attempted to do an unsupported remain spill");
676                   sym->remainSpil = 1;
677                   _G.blockSpil++;
678                 }
679               return sym;
680             }
681         }
682     }
683   /* find live ranges with spillocation && not used as pointers */
684   if ((selectS = liveRangesWith (lrcs, hasSpilLocnoUptr, ebp, ic)))
685     {
686
687       sym = leastUsedLR (selectS);
688       /* mark this as allocation required */
689       sym->usl.spillLoc->allocreq++;
690       return sym;
691     }
692 #endif
693
694   /* find live ranges with spillocation */
695   if ((selectS = liveRangesWith (lrcs, hasSpilLoc, ebp, ic)))
696     {
697       D (D_ALLOC, ("selectSpil: using with spill.\n"));
698       sym = leastUsedLR (selectS);
699       sym->usl.spillLoc->allocreq++;
700       return sym;
701     }
702
703   /* couldn't find then we need to create a spil
704      location on the stack , for which one? the least
705      used ofcourse */
706   if ((selectS = liveRangesWith (lrcs, noSpilLoc, ebp, ic)))
707     {
708       D (D_ALLOC, ("selectSpil: creating new spill.\n"));
709       /* return a created spil location */
710       sym = createStackSpil (leastUsedLR (selectS));
711       sym->usl.spillLoc->allocreq++;
712       return sym;
713     }
714
715   /* this is an extreme situation we will spill
716      this one : happens very rarely but it does happen */
717   D (D_ALLOC, ("selectSpil: using spillThis.\n"));
718   spillThis (forSym);
719   return forSym;
720
721 }
722
723 /** Spil some variable & mark registers as free.
724     A spill occurs when an iTemp wont fit into the available registers.
725  */
726 bool 
727 spilSomething (iCode * ic, eBBlock * ebp, symbol * forSym)
728 {
729   symbol *ssym;
730   int i;
731
732   D (D_ALLOC, ("spilSomething: spilling on ic %p\n", ic));
733
734   /* get something we can spil */
735   ssym = selectSpil (ic, ebp, forSym);
736
737   /* mark it as spilt */
738   ssym->isspilt = ssym->spillA = 1;
739   _G.spiltSet = bitVectSetBit (_G.spiltSet, ssym->key);
740
741   /* mark it as not register assigned &
742      take it away from the set */
743   bitVectUnSetBit (_G.regAssigned, ssym->key);
744   bitVectUnSetBit (_G.totRegAssigned, ssym->key);
745
746   /* mark the registers as free */
747   for (i = 0; i < ssym->nRegs; i++)
748     if (ssym->regs[i])
749       freeReg (ssym->regs[i]);
750
751   wassertl (ssym->blockSpil == 0, "Encountered a sym with a block spill");
752   wassertl (ssym->remainSpil == 0, "Encountered a sym with a remain spill");
753 #if 0
754   /* if spilt on stack then free up r0 & r1 
755      if they could have been assigned to as gprs */
756   if (!ptrRegReq && isSpiltOnStack (ssym))
757     {
758       ptrRegReq++;
759       spillLRWithPtrReg (ssym);
760     }
761
762   /* if this was a block level spil then insert push & pop 
763      at the start & end of block respectively */
764   if (ssym->blockSpil)
765     {
766       iCode *nic = newiCode (IPUSH, operandFromSymbol (ssym), NULL);
767       /* add push to the start of the block */
768       addiCodeToeBBlock (ebp, nic, (ebp->sch->op == LABEL ?
769                                     ebp->sch->next : ebp->sch));
770       nic = newiCode (IPOP, operandFromSymbol (ssym), NULL);
771       /* add pop to the end of the block */
772       addiCodeToeBBlock (ebp, nic, NULL);
773     }
774
775   /* if spilt because not used in the remainder of the
776      block then add a push before this instruction and
777      a pop at the end of the block */
778   if (ssym->remainSpil)
779     {
780
781       iCode *nic = newiCode (IPUSH, operandFromSymbol (ssym), NULL);
782       /* add push just before this instruction */
783       addiCodeToeBBlock (ebp, nic, ic);
784
785       nic = newiCode (IPOP, operandFromSymbol (ssym), NULL);
786       /* add pop to the end of the block */
787       addiCodeToeBBlock (ebp, nic, NULL);
788     }
789 #endif
790
791   D (D_ALLOC, ("spilSomething: done.\n"));
792
793   if (ssym == forSym)
794     return FALSE;
795   else
796     return TRUE;
797 }
798
799 /** Will try for GPR if not spil.
800  */
801 regs *
802 getRegGpr (iCode * ic, eBBlock * ebp, symbol * sym)
803 {
804   regs *reg;
805
806   D (D_ALLOC, ("getRegGpr: on ic %p\n", ic));
807 tryAgain:
808   /* try for gpr type */
809   if ((reg = allocReg (REG_GPR)))
810     {
811       D (D_ALLOC, ("getRegGpr: got a reg.\n"));
812       return reg;
813     }
814
815   /* we have to spil */
816   if (!spilSomething (ic, ebp, sym))
817     {
818       D (D_ALLOC, ("getRegGpr: have to spill.\n"));
819       return NULL;
820     }
821
822   /* this looks like an infinite loop but 
823      in really selectSpil will abort  */
824   goto tryAgain;
825 }
826
827 static regs *getRegGprNoSpil()
828 {
829   regs *reg;
830
831   /* try for gpr type */
832   if ((reg = allocReg (REG_GPR)))
833     {
834       D (D_ALLOC, ("getRegGprNoSpil: got a reg.\n"));
835       return reg;
836     }
837   assert(0);
838 }
839
840 /** Symbol has a given register.
841  */
842 static bool 
843 symHasReg (symbol * sym, regs * reg)
844 {
845   int i;
846
847   for (i = 0; i < sym->nRegs; i++)
848     if (sym->regs[i] == reg)
849       return TRUE;
850
851   return FALSE;
852 }
853
854 /** Check the live to and if they have registers & are not spilt then
855     free up the registers 
856 */
857 static void 
858 deassignLRs (iCode * ic, eBBlock * ebp)
859 {
860   symbol *sym;
861   int k;
862   symbol *result;
863
864   for (sym = hTabFirstItem (liveRanges, &k); sym;
865        sym = hTabNextItem (liveRanges, &k))
866     {
867
868       symbol *psym = NULL;
869       /* if it does not end here */
870       if (sym->liveTo > ic->seq)
871         continue;
872
873       /* if it was spilt on stack then we can 
874          mark the stack spil location as free */
875       if (sym->isspilt)
876         {
877           if (sym->stackSpil)
878             {
879               sym->usl.spillLoc->isFree = 1;
880               sym->stackSpil = 0;
881             }
882           continue;
883         }
884
885       if (!bitVectBitValue (_G.regAssigned, sym->key))
886         continue;
887
888       /* special case check if this is an IFX &
889          the privious one was a pop and the 
890          previous one was not spilt then keep track
891          of the symbol */
892       if (ic->op == IFX && ic->prev &&
893           ic->prev->op == IPOP &&
894           !ic->prev->parmPush &&
895           !OP_SYMBOL (IC_LEFT (ic->prev))->isspilt)
896         psym = OP_SYMBOL (IC_LEFT (ic->prev));
897
898       D (D_ALLOC, ("deassignLRs: in loop on sym %p nregs %u\n", sym, sym->nRegs));
899
900       if (sym->nRegs)
901         {
902           int i = 0;
903
904           bitVectUnSetBit (_G.regAssigned, sym->key);
905
906           /* if the result of this one needs registers
907              and does not have it then assign it right
908              away */
909           if (IC_RESULT (ic) &&
910               !(SKIP_IC2 (ic) ||        /* not a special icode */
911                 ic->op == JUMPTABLE ||
912                 ic->op == IFX ||
913                 ic->op == IPUSH ||
914                 ic->op == IPOP ||
915                 ic->op == RETURN) &&
916               (result = OP_SYMBOL (IC_RESULT (ic))) &&  /* has a result */
917               result->liveTo > ic->seq &&       /* and will live beyond this */
918               result->liveTo <= ebp->lSeq &&    /* does not go beyond this block */
919               result->regType == sym->regType &&        /* same register types */
920               result->nRegs &&  /* which needs registers */
921               !result->isspilt &&       /* and does not already have them */
922               !result->remat &&
923               !bitVectBitValue (_G.regAssigned, result->key) &&
924           /* the number of free regs + number of regs in this LR
925              can accomodate the what result Needs */
926               ((nfreeRegsType (result->regType) +
927                 sym->nRegs) >= result->nRegs)
928             )
929             {
930               for (i = 0; i < result->nRegs; i++)
931                 {
932                   if (i < sym->nRegs)
933                     result->regs[i] = sym->regs[i];
934                   else
935                     result->regs[i] = getRegGpr (ic, ebp, result);
936
937                   /* if the allocation falied which means
938                      this was spilt then break */
939                   if (!result->regs[i])
940                     {
941                       wassert (0);
942                       assert (0);
943                       break;
944                     }
945                 }
946
947               _G.regAssigned = bitVectSetBit (_G.regAssigned, result->key);
948               _G.totRegAssigned = bitVectSetBit (_G.totRegAssigned, result->key);
949             }
950
951           /* free the remaining */
952           for (; i < sym->nRegs; i++)
953             {
954               if (psym)
955                 {
956                   if (!symHasReg (psym, sym->regs[i]))
957                     freeReg (sym->regs[i]);
958                 }
959               else
960                 freeReg (sym->regs[i]);
961               //              sym->regs[i] = NULL;
962             }
963         }
964     }
965 }
966
967
968 /** Reassign this to registers.
969  */
970 static void 
971 reassignLR (operand * op)
972 {
973   symbol *sym = OP_SYMBOL (op);
974   int i;
975
976   D (D_ALLOC, ("reassingLR: on sym %p\n", sym));
977
978   /* not spilt any more */
979   sym->isspilt = sym->spillA = sym->blockSpil = sym->remainSpil = 0;
980   bitVectUnSetBit (_G.spiltSet, sym->key);
981
982   _G.regAssigned = bitVectSetBit (_G.regAssigned, sym->key);
983   _G.totRegAssigned = bitVectSetBit (_G.totRegAssigned, sym->key);
984
985   _G.blockSpil--;
986
987   for (i = 0; i < sym->nRegs; i++)
988     sym->regs[i]->isFree = 0;
989 }
990
991 /** Determines if allocating will cause a spill.
992  */
993 static int 
994 willCauseSpill (int nr, int rt)
995 {
996   /* first check if there are any avlb registers
997      of te type required */
998   if (nFreeRegs (0) >= nr)
999     return 0;
1000
1001   /* it will cause a spil */
1002   return 1;
1003 }
1004
1005 /** The allocator can allocate same registers to result and operand,
1006     if this happens make sure they are in the same position as the operand
1007     otherwise chaos results.
1008 */
1009 static int
1010 positionRegs (symbol * result, symbol * opsym)
1011 {
1012   int count = min (result->nRegs, opsym->nRegs);
1013   int i, j = 0, shared = 0;
1014   int change = 0;
1015
1016   D (D_ALLOC, ("positionRegs: on result %p opsum %p line %u\n", result, opsym, lineno));
1017
1018   /* if the result has been spilt then cannot share */
1019   if (opsym->isspilt)
1020     return 0;
1021 again:
1022   shared = 0;
1023   /* first make sure that they actually share */
1024   for (i = 0; i < count; i++)
1025     {
1026       for (j = 0; j < count; j++)
1027         {
1028           if (result->regs[i] == opsym->regs[j] && i != j)
1029             {
1030               shared = 1;
1031               goto xchgPositions;
1032             }
1033         }
1034     }
1035 xchgPositions:
1036   if (shared)
1037     {
1038       regs *tmp = result->regs[i];
1039       result->regs[i] = result->regs[j];
1040       result->regs[j] = tmp;
1041       change ++;
1042       goto again;
1043     }
1044   return change ;
1045 }
1046
1047 /** Try to allocate a pair of registers to the symbol.
1048  */
1049 bool 
1050 tryAllocatingRegPair (symbol * sym)
1051 {
1052   int i;
1053   wassert (sym->nRegs == 2);
1054   for (i = 0; i < _G.nRegs; i += 2)
1055     {
1056       if ((regsZ80[i].isFree) && (regsZ80[i + 1].isFree))
1057         {
1058           regsZ80[i].isFree = 0;
1059           sym->regs[0] = &regsZ80[i];
1060           regsZ80[i + 1].isFree = 0;
1061           sym->regs[1] = &regsZ80[i + 1];
1062           sym->regType = REG_PAIR;
1063
1064           if (currFunc)
1065             {
1066               currFunc->regsUsed =
1067                 bitVectSetBit (currFunc->regsUsed, i);
1068               currFunc->regsUsed =
1069                 bitVectSetBit (currFunc->regsUsed, i + 1);
1070             }
1071           D (D_ALLOC, ("tryAllocRegPair: succeded for sym %p\n", sym));
1072           return TRUE;
1073         }
1074     }
1075   D (D_ALLOC, ("tryAllocRegPair: failed on sym %p\n", sym));
1076   return FALSE;
1077 }
1078
1079 /** Serially allocate registers to the variables.
1080     This is the main register allocation function.  It is called after
1081     packing.
1082  */
1083 static void 
1084 serialRegAssign (eBBlock ** ebbs, int count)
1085 {
1086   int i;
1087
1088   /* for all blocks */
1089   for (i = 0; i < count; i++)
1090     {
1091
1092       iCode *ic;
1093
1094       if (ebbs[i]->noPath &&
1095           (ebbs[i]->entryLabel != entryLabel &&
1096            ebbs[i]->entryLabel != returnLabel))
1097         continue;
1098
1099       /* of all instructions do */
1100       for (ic = ebbs[i]->sch; ic; ic = ic->next)
1101         {
1102
1103           /* if this is an ipop that means some live
1104              range will have to be assigned again */
1105           if (ic->op == IPOP)
1106             {
1107               wassert (0);
1108               reassignLR (IC_LEFT (ic));
1109             }
1110
1111           /* if result is present && is a true symbol */
1112           if (IC_RESULT (ic) && ic->op != IFX &&
1113               IS_TRUE_SYMOP (IC_RESULT (ic)))
1114             OP_SYMBOL (IC_RESULT (ic))->allocreq++;
1115
1116           /* take away registers from live
1117              ranges that end at this instruction */
1118           deassignLRs (ic, ebbs[i]);
1119
1120           /* some don't need registers */
1121           /* MLH: removed RESULT and POINTER_SET condition */
1122           if (SKIP_IC2 (ic) ||
1123               ic->op == JUMPTABLE ||
1124               ic->op == IFX ||
1125               ic->op == IPUSH ||
1126               ic->op == IPOP)
1127             continue;
1128
1129           /* now we need to allocate registers only for the result */
1130           if (IC_RESULT (ic))
1131             {
1132               symbol *sym = OP_SYMBOL (IC_RESULT (ic));
1133               bitVect *spillable;
1134               int willCS;
1135               int j;
1136
1137               D (D_ALLOC, ("serialRegAssign: in loop on result %p\n", sym));
1138
1139               /* if it does not need or is spilt 
1140                  or is already assigned to registers
1141                  or will not live beyond this instructions */
1142               if (!sym->nRegs ||
1143                   sym->isspilt ||
1144                   bitVectBitValue (_G.regAssigned, sym->key) ||
1145                   sym->liveTo <= ic->seq)
1146                 {
1147                   D (D_ALLOC, ("serialRegAssign: wont live long enough.\n"));
1148                   continue;
1149                 }
1150
1151               /* if some liverange has been spilt at the block level
1152                  and this one live beyond this block then spil this
1153                  to be safe */
1154               if (_G.blockSpil && sym->liveTo > ebbs[i]->lSeq)
1155                 {
1156                   D (D_ALLOC, ("serialRegAssign: \"spilling to be safe.\"\n"));
1157                   spillThis (sym);
1158                   continue;
1159                 }
1160               /* if trying to allocate this will cause
1161                  a spill and there is nothing to spill 
1162                  or this one is rematerializable then
1163                  spill this one */
1164               willCS = willCauseSpill (sym->nRegs, sym->regType);
1165               spillable = computeSpillable (ic);
1166               if (sym->remat ||
1167                   (willCS && bitVectIsZero (spillable)))
1168                 {
1169
1170                   D (D_ALLOC, ("serialRegAssign: \"remat spill\"\n"));
1171                   spillThis (sym);
1172                   continue;
1173
1174                 }
1175
1176               /* if it has a spillocation & is used less than
1177                  all other live ranges then spill this */
1178               if (willCS) {
1179                       if (sym->usl.spillLoc) {
1180                               symbol *leastUsed = leastUsedLR (liveRangesWith (spillable,
1181                                                                                allLRs, ebbs[i], ic));
1182                               if (leastUsed && leastUsed->used > sym->used) {
1183                                       spillThis (sym);
1184                                       continue;
1185                               }
1186                       } else {
1187                               /* if none of the liveRanges have a spillLocation then better
1188                                  to spill this one than anything else already assigned to registers */
1189                               if (liveRangesWith(spillable,noSpilLoc,ebbs[i],ic)) {
1190                                   /* if this is local to this block then we might find a block spil */
1191                                   if (!(sym->liveFrom >= ebbs[i]->fSeq && sym->liveTo <= ebbs[i]->lSeq)) {
1192                                       spillThis (sym);
1193                                       continue;
1194                                   }
1195                               }
1196                       }
1197               }
1198
1199               /* else we assign registers to it */
1200               _G.regAssigned = bitVectSetBit (_G.regAssigned, sym->key);
1201               _G.totRegAssigned = bitVectSetBit (_G.totRegAssigned, sym->key);
1202
1203               /* Special case:  Try to fit into a reg pair if
1204                  available */
1205               D (D_ALLOC, ("serialRegAssign: actually allocing regs!\n"));
1206               if ((sym->nRegs == 2) && tryAllocatingRegPair (sym))
1207                 {
1208                 }
1209               else
1210                 {
1211                   for (j = 0; j < sym->nRegs; j++)
1212                     {
1213                       sym->regs[j] = getRegGpr (ic, ebbs[i], sym);
1214
1215                       /* if the allocation falied which means
1216                          this was spilt then break */
1217                       if (!sym->regs[j])
1218                         {
1219                           D (D_ALLOC, ("Couldnt alloc (spill)\n"))
1220                             break;
1221                         }
1222                     }
1223                 }
1224               /* if it shares registers with operands make sure
1225                  that they are in the same position */
1226               if (IC_LEFT (ic) && IS_SYMOP (IC_LEFT (ic)) &&
1227                   OP_SYMBOL (IC_LEFT (ic))->nRegs && ic->op != '=')
1228                 positionRegs (OP_SYMBOL (IC_RESULT (ic)),
1229                               OP_SYMBOL (IC_LEFT (ic)));
1230               /* do the same for the right operand */
1231               if (IC_RIGHT (ic) && IS_SYMOP (IC_RIGHT (ic)) &&
1232                   OP_SYMBOL (IC_RIGHT (ic))->nRegs)
1233                 positionRegs (OP_SYMBOL (IC_RESULT (ic)),
1234                               OP_SYMBOL (IC_RIGHT (ic)));
1235
1236             }
1237         }
1238     }
1239 }
1240
1241 /*-----------------------------------------------------------------*/
1242 /* fillGaps - Try to fill in the Gaps left by Pass1                */
1243 /*-----------------------------------------------------------------*/
1244 static void fillGaps()
1245 {
1246     symbol *sym =NULL;
1247     int key =0;    
1248     
1249     if (getenv("DISABLE_FILL_GAPS")) return;
1250     
1251     /* look for livernages that was spilt by the allocator */
1252     for (sym = hTabFirstItem(liveRanges,&key) ; sym ; 
1253          sym = hTabNextItem(liveRanges,&key)) {
1254
1255         int i;
1256         int pdone = 0;
1257
1258         if (!sym->spillA || !sym->clashes || sym->remat) continue ;
1259
1260         /* find the liveRanges this one clashes with, that are
1261            still assigned to registers & mark the registers as used*/
1262         for ( i = 0 ; i < sym->clashes->size ; i ++) {
1263             int k;
1264             symbol *clr;
1265
1266             if (bitVectBitValue(sym->clashes,i) == 0 ||    /* those that clash with this */
1267                 bitVectBitValue(_G.totRegAssigned,i) == 0) /* and are still assigned to registers */
1268                 continue ;
1269
1270             assert (clr = hTabItemWithKey(liveRanges,i));
1271          
1272             /* mark these registers as used */
1273             for (k = 0 ; k < clr->nRegs ; k++ ) 
1274                 useReg(clr->regs[k]);
1275         }
1276
1277         if (willCauseSpill(sym->nRegs,sym->regType)) {
1278             /* NOPE :( clear all registers & and continue */
1279             freeAllRegs();
1280             continue ;
1281         }
1282
1283         /* THERE IS HOPE !!!! */
1284         for (i=0; i < sym->nRegs ; i++ ) {
1285                 sym->regs[i] = getRegGprNoSpil ();                
1286         }
1287
1288         /* for all its definitions check if the registers
1289            allocated needs positioning NOTE: we can position
1290            only ONCE if more than One positioning required 
1291            then give up */
1292         sym->isspilt = 0;
1293         for (i = 0 ; i < sym->defs->size ; i++ ) {
1294             if (bitVectBitValue(sym->defs,i)) {
1295                 iCode *ic;
1296                 if (!(ic = hTabItemWithKey(iCodehTab,i))) continue ;
1297                 if (SKIP_IC(ic)) continue;
1298                 assert(isSymbolEqual(sym,OP_SYMBOL(IC_RESULT(ic)))); /* just making sure */
1299                 /* if left is assigned to registers */
1300                 if (IS_SYMOP(IC_LEFT(ic)) && 
1301                     bitVectBitValue(_G.totRegAssigned,OP_SYMBOL(IC_LEFT(ic))->key)) {
1302                     pdone += positionRegs(sym,OP_SYMBOL(IC_LEFT(ic)));
1303                 }
1304                 if (IS_SYMOP(IC_RIGHT(ic)) && 
1305                     bitVectBitValue(_G.totRegAssigned,OP_SYMBOL(IC_RIGHT(ic))->key)) {
1306                     pdone += positionRegs(sym,OP_SYMBOL(IC_RIGHT(ic)));
1307                 }
1308                 if (pdone > 1) break;
1309             }
1310         }
1311         for (i = 0 ; i < sym->uses->size ; i++ ) {
1312             if (bitVectBitValue(sym->uses,i)) {
1313                 iCode *ic;
1314                 if (!(ic = hTabItemWithKey(iCodehTab,i))) continue ;
1315                 if (SKIP_IC(ic)) continue;
1316                 if (!IS_ASSIGN_ICODE(ic)) continue ;
1317
1318                 /* if result is assigned to registers */
1319                 if (IS_SYMOP(IC_RESULT(ic)) && 
1320                     bitVectBitValue(_G.totRegAssigned,OP_SYMBOL(IC_RESULT(ic))->key)) {
1321                     pdone += positionRegs(sym,OP_SYMBOL(IC_RESULT(ic)));
1322                 }
1323                 if (pdone > 1) break;
1324             }
1325         }
1326         /* had to position more than once GIVE UP */
1327         if (pdone > 1) {
1328             /* UNDO all the changes we made to try this */
1329             sym->isspilt = 1;
1330             for (i=0; i < sym->nRegs ; i++ ) {
1331                 sym->regs[i] = NULL;
1332             }
1333             freeAllRegs();
1334             D(D_FILL_GAPS,("Fill Gap gave up due to positioning for %s in function %s\n",sym->name, currFunc ? currFunc->name : "UNKNOWN"));
1335             continue ;      
1336         }
1337         D(D_FILL_GAPS,("FILLED GAP for %s in function %s\n",sym->name, currFunc ? currFunc->name : "UNKNOWN"));
1338         _G.totRegAssigned = bitVectSetBit(_G.totRegAssigned,sym->key);
1339         sym->isspilt = sym->spillA = 0 ;
1340         sym->usl.spillLoc->allocreq--;
1341         freeAllRegs();
1342     }
1343 }
1344
1345 /*-----------------------------------------------------------------*/
1346 /* rUmaskForOp :- returns register mask for an operand             */
1347 /*-----------------------------------------------------------------*/
1348 bitVect *
1349 rUmaskForOp (operand * op)
1350 {
1351   bitVect *rumask;
1352   symbol *sym;
1353   int j;
1354
1355   /* only temporaries are assigned registers */
1356   if (!IS_ITEMP (op))
1357     return NULL;
1358
1359   sym = OP_SYMBOL (op);
1360
1361   /* if spilt or no registers assigned to it
1362      then nothing */
1363   if (sym->isspilt || !sym->nRegs)
1364     return NULL;
1365
1366   rumask = newBitVect (_G.nRegs);
1367
1368   for (j = 0; j < sym->nRegs; j++)
1369     {
1370       rumask = bitVectSetBit (rumask, sym->regs[j]->rIdx);
1371     }
1372
1373   return rumask;
1374 }
1375
1376 bitVect *
1377 z80_rUmaskForOp (operand * op)
1378 {
1379   return rUmaskForOp (op);
1380 }
1381
1382 /** Returns bit vector of registers used in iCode.
1383  */
1384 bitVect *
1385 regsUsedIniCode (iCode * ic)
1386 {
1387   bitVect *rmask = newBitVect (_G.nRegs);
1388
1389   /* do the special cases first */
1390   if (ic->op == IFX)
1391     {
1392       rmask = bitVectUnion (rmask,
1393                             rUmaskForOp (IC_COND (ic)));
1394       goto ret;
1395     }
1396
1397   /* for the jumptable */
1398   if (ic->op == JUMPTABLE)
1399     {
1400       rmask = bitVectUnion (rmask,
1401                             rUmaskForOp (IC_JTCOND (ic)));
1402
1403       goto ret;
1404     }
1405
1406   /* of all other cases */
1407   if (IC_LEFT (ic))
1408     rmask = bitVectUnion (rmask,
1409                           rUmaskForOp (IC_LEFT (ic)));
1410
1411
1412   if (IC_RIGHT (ic))
1413     rmask = bitVectUnion (rmask,
1414                           rUmaskForOp (IC_RIGHT (ic)));
1415
1416   if (IC_RESULT (ic))
1417     rmask = bitVectUnion (rmask,
1418                           rUmaskForOp (IC_RESULT (ic)));
1419
1420 ret:
1421   return rmask;
1422 }
1423
1424 /** For each instruction will determine the regsUsed.
1425  */
1426 static void 
1427 createRegMask (eBBlock ** ebbs, int count)
1428 {
1429   int i;
1430
1431   /* for all blocks */
1432   for (i = 0; i < count; i++)
1433     {
1434       iCode *ic;
1435
1436       if (ebbs[i]->noPath &&
1437           (ebbs[i]->entryLabel != entryLabel &&
1438            ebbs[i]->entryLabel != returnLabel))
1439         continue;
1440
1441       /* for all instructions */
1442       for (ic = ebbs[i]->sch; ic; ic = ic->next)
1443         {
1444
1445           int j;
1446
1447           if (SKIP_IC2 (ic) || !ic->rlive)
1448             continue;
1449
1450           /* first mark the registers used in this
1451              instruction */
1452           ic->rUsed = regsUsedIniCode (ic);
1453           _G.funcrUsed = bitVectUnion (_G.funcrUsed, ic->rUsed);
1454
1455           /* now create the register mask for those 
1456              registers that are in use : this is a
1457              super set of ic->rUsed */
1458           ic->rMask = newBitVect (_G.nRegs + 1);
1459
1460           /* for all live Ranges alive at this point */
1461           for (j = 1; j < ic->rlive->size; j++)
1462             {
1463               symbol *sym;
1464               int k;
1465
1466               /* if not alive then continue */
1467               if (!bitVectBitValue (ic->rlive, j))
1468                 continue;
1469
1470               /* find the live range we are interested in */
1471               if (!(sym = hTabItemWithKey (liveRanges, j)))
1472                 {
1473                   werror (E_INTERNAL_ERROR, __FILE__, __LINE__,
1474                           "createRegMask cannot find live range");
1475                   exit (0);
1476                 }
1477
1478               /* if no register assigned to it */
1479               if (!sym->nRegs || sym->isspilt)
1480                 continue;
1481
1482               /* for all the registers allocated to it */
1483               for (k = 0; k < sym->nRegs; k++)
1484                 if (sym->regs[k])
1485                   ic->rMask =
1486                     bitVectSetBit (ic->rMask, sym->regs[k]->rIdx);
1487             }
1488         }
1489     }
1490 }
1491
1492 /** Returns the rematerialized string for a remat var.
1493  */
1494 char *
1495 rematStr (symbol * sym)
1496 {
1497   char *s = buffer;
1498   iCode *ic = sym->rematiCode;
1499
1500   while (1)
1501     {
1502
1503       /* if plus or minus print the right hand side */
1504       if (ic->op == '+' || ic->op == '-')
1505         {
1506           sprintf (s, "0x%04x %c ", (int) operandLitValue (IC_RIGHT (ic)),
1507                    ic->op);
1508           s += strlen (s);
1509           ic = OP_SYMBOL (IC_LEFT (ic))->rematiCode;
1510           continue;
1511         }
1512       /* we reached the end */
1513       sprintf (s, "%s", OP_SYMBOL (IC_LEFT (ic))->rname);
1514       break;
1515     }
1516
1517   return buffer;
1518 }
1519
1520 /*-----------------------------------------------------------------*/
1521 /* regTypeNum - computes the type & number of registers required   */
1522 /*-----------------------------------------------------------------*/
1523 static void 
1524 regTypeNum (void)
1525 {
1526   symbol *sym;
1527   int k;
1528
1529   /* for each live range do */
1530   for (sym = hTabFirstItem (liveRanges, &k); sym;
1531        sym = hTabNextItem (liveRanges, &k))
1532     {
1533
1534       /* if used zero times then no registers needed */
1535       if ((sym->liveTo - sym->liveFrom) == 0)
1536         continue;
1537
1538       D (D_ALLOC, ("regTypeNum: loop on sym %p\n", sym));
1539
1540       /* if the live range is a temporary */
1541       if (sym->isitmp)
1542         {
1543
1544           /* if the type is marked as a conditional */
1545           if (sym->regType == REG_CND)
1546             continue;
1547
1548           /* if used in return only then we don't 
1549              need registers */
1550           if (sym->ruonly || sym->accuse)
1551             {
1552               if (IS_AGGREGATE (sym->type) || sym->isptr)
1553                 sym->type = aggrToPtr (sym->type, FALSE);
1554               continue;
1555             }
1556
1557           /* if not then we require registers */
1558           D (D_ALLOC, ("regTypeNum: isagg %u nRegs %u type %p\n", IS_AGGREGATE (sym->type) || sym->isptr, sym->nRegs, sym->type));
1559           sym->nRegs = ((IS_AGGREGATE (sym->type) || sym->isptr) ?
1560                         getSize (sym->type = aggrToPtr (sym->type, FALSE)) :
1561                         getSize (sym->type));
1562           D (D_ALLOC, ("regTypeNum: setting nRegs of %s (%p) to %u\n", sym->name, sym, sym->nRegs));
1563
1564           D (D_ALLOC, ("regTypeNum: setup to assign regs sym %p\n", sym));
1565
1566           if (sym->nRegs > 4)
1567             {
1568               fprintf (stderr, "allocated more than 4 or 0 registers for type ");
1569               printTypeChain (sym->type, stderr);
1570               fprintf (stderr, "\n");
1571             }
1572
1573           /* determine the type of register required */
1574           /* Always general purpose */
1575           sym->regType = REG_GPR;
1576
1577         }
1578       else
1579         {
1580           /* for the first run we don't provide */
1581           /* registers for true symbols we will */
1582           /* see how things go                  */
1583           D (D_ALLOC, ("regTypeNum: #2 setting num of %p to 0\n", sym));
1584           sym->nRegs = 0;
1585         }
1586     }
1587
1588 }
1589
1590 /** Mark all registers as free.
1591  */
1592 static void 
1593 freeAllRegs ()
1594 {
1595   int i;
1596
1597   D (D_ALLOC, ("freeAllRegs: running.\n"));
1598
1599   for (i = 0; i < _G.nRegs; i++)
1600     regsZ80[i].isFree = 1;
1601 }
1602
1603 /*-----------------------------------------------------------------*/
1604 /* deallocStackSpil - this will set the stack pointer back         */
1605 /*-----------------------------------------------------------------*/
1606 DEFSETFUNC (deallocStackSpil)
1607 {
1608   symbol *sym = item;
1609
1610   deallocLocal (sym);
1611   return 0;
1612 }
1613
1614 /** Register reduction for assignment.
1615  */
1616 static int 
1617 packRegsForAssign (iCode * ic, eBBlock * ebp)
1618 {
1619   iCode *dic, *sic;
1620
1621   D (D_ALLOC, ("packRegsForAssign: running on ic %p\n", ic));
1622
1623   if (!IS_ITEMP (IC_RIGHT (ic)) ||
1624       OP_SYMBOL (IC_RIGHT (ic))->isind ||
1625       OP_LIVETO (IC_RIGHT (ic)) > ic->seq)
1626     {
1627       return 0;
1628     }
1629
1630   /* find the definition of iTempNN scanning backwards if we find a 
1631      a use of the true symbol in before we find the definition then 
1632      we cannot */
1633   for (dic = ic->prev; dic; dic = dic->prev)
1634     {
1635       /* PENDING: Don't pack across function calls. */
1636       if (dic->op == CALL || dic->op == PCALL)
1637         {
1638           dic = NULL;
1639           break;
1640         }
1641
1642       if (SKIP_IC2 (dic))
1643         continue;
1644
1645       if (IS_SYMOP (IC_RESULT (dic)) &&
1646           IC_RESULT (dic)->key == IC_RIGHT (ic)->key)
1647         {
1648           break;
1649         }
1650
1651       if (IS_SYMOP (IC_RIGHT (dic)) &&
1652           (IC_RIGHT (dic)->key == IC_RESULT (ic)->key ||
1653            IC_RIGHT (dic)->key == IC_RIGHT (ic)->key))
1654         {
1655           dic = NULL;
1656           break;
1657         }
1658
1659       if (IS_SYMOP (IC_LEFT (dic)) &&
1660           (IC_LEFT (dic)->key == IC_RESULT (ic)->key ||
1661            IC_LEFT (dic)->key == IC_RIGHT (ic)->key))
1662         {
1663           dic = NULL;
1664           break;
1665         }
1666     }
1667
1668   if (!dic)
1669     return 0;                   /* did not find */
1670
1671   /* if the result is on stack or iaccess then it must be
1672      the same atleast one of the operands */
1673   if (OP_SYMBOL (IC_RESULT (ic))->onStack ||
1674       OP_SYMBOL (IC_RESULT (ic))->iaccess)
1675     {
1676       /* the operation has only one symbol
1677          operator then we can pack */
1678       if ((IC_LEFT (dic) && !IS_SYMOP (IC_LEFT (dic))) ||
1679           (IC_RIGHT (dic) && !IS_SYMOP (IC_RIGHT (dic))))
1680         goto pack;
1681
1682       if (!((IC_LEFT (dic) &&
1683              IC_RESULT (ic)->key == IC_LEFT (dic)->key) ||
1684             (IC_RIGHT (dic) &&
1685              IC_RESULT (ic)->key == IC_RIGHT (dic)->key)))
1686         return 0;
1687     }
1688 pack:
1689   /* found the definition */
1690   /* replace the result with the result of */
1691   /* this assignment and remove this assignment */
1692   bitVectUnSetBit(OP_SYMBOL(IC_RESULT(dic))->defs,dic->key);
1693   IC_RESULT (dic) = IC_RESULT (ic);
1694
1695   if (IS_ITEMP (IC_RESULT (dic)) && OP_SYMBOL (IC_RESULT (dic))->liveFrom > dic->seq)
1696     {
1697       OP_SYMBOL (IC_RESULT (dic))->liveFrom = dic->seq;
1698     }
1699   /* delete from liverange table also 
1700      delete from all the points inbetween and the new
1701      one */
1702   for (sic = dic; sic != ic; sic = sic->next)
1703     {
1704       bitVectUnSetBit (sic->rlive, IC_RESULT (ic)->key);
1705       if (IS_ITEMP (IC_RESULT (dic)))
1706         bitVectSetBit (sic->rlive, IC_RESULT (dic)->key);
1707     }
1708
1709   remiCodeFromeBBlock (ebp, ic);
1710   // PENDING: Check vs mcs51
1711   bitVectUnSetBit(OP_SYMBOL(IC_RESULT(ic))->defs,ic->key);
1712   hTabDeleteItem (&iCodehTab, ic->key, ic, DELETE_ITEM, NULL);
1713   OP_DEFS (IC_RESULT (dic)) = bitVectSetBit (OP_DEFS (IC_RESULT (dic)), dic->key);
1714   return 1;
1715 }
1716
1717 /** Scanning backwards looks for first assig found.
1718  */
1719 iCode *
1720 findAssignToSym (operand * op, iCode * ic)
1721 {
1722   iCode *dic;
1723
1724   for (dic = ic->prev; dic; dic = dic->prev)
1725     {
1726
1727       /* if definition by assignment */
1728       if (dic->op == '=' &&
1729           !POINTER_SET (dic) &&
1730           IC_RESULT (dic)->key == op->key)
1731         /*      &&  IS_TRUE_SYMOP(IC_RIGHT(dic)) */
1732         {
1733
1734           /* we are interested only if defined in far space */
1735           /* or in stack space in case of + & - */
1736
1737           /* if assigned to a non-symbol then return
1738              true */
1739           if (!IS_SYMOP (IC_RIGHT (dic)))
1740             break;
1741
1742           /* if the symbol is in far space then
1743              we should not */
1744           if (isOperandInFarSpace (IC_RIGHT (dic)))
1745             return NULL;
1746
1747           /* for + & - operations make sure that
1748              if it is on the stack it is the same
1749              as one of the three operands */
1750           if ((ic->op == '+' || ic->op == '-') &&
1751               OP_SYMBOL (IC_RIGHT (dic))->onStack)
1752             {
1753
1754               if (IC_RESULT (ic)->key != IC_RIGHT (dic)->key &&
1755                   IC_LEFT (ic)->key != IC_RIGHT (dic)->key &&
1756                   IC_RIGHT (ic)->key != IC_RIGHT (dic)->key)
1757                 return NULL;
1758             }
1759
1760           break;
1761
1762         }
1763
1764       /* if we find an usage then we cannot delete it */
1765       if (IC_LEFT (dic) && IC_LEFT (dic)->key == op->key)
1766         return NULL;
1767
1768       if (IC_RIGHT (dic) && IC_RIGHT (dic)->key == op->key)
1769         return NULL;
1770
1771       if (POINTER_SET (dic) && IC_RESULT (dic)->key == op->key)
1772         return NULL;
1773     }
1774
1775   /* now make sure that the right side of dic
1776      is not defined between ic & dic */
1777   if (dic)
1778     {
1779       iCode *sic = dic->next;
1780
1781       for (; sic != ic; sic = sic->next)
1782         if (IC_RESULT (sic) &&
1783             IC_RESULT (sic)->key == IC_RIGHT (dic)->key)
1784           return NULL;
1785     }
1786
1787   return dic;
1788
1789
1790 }
1791
1792 #if !DISABLE_PACKREGSFORSUPPORT
1793 // PENDING
1794
1795 /*-----------------------------------------------------------------*/
1796 /* packRegsForSupport :- reduce some registers for support calls   */
1797 /*-----------------------------------------------------------------*/
1798 static int 
1799 packRegsForSupport (iCode * ic, eBBlock * ebp)
1800 {
1801   int change = 0;
1802   /* for the left & right operand :- look to see if the
1803      left was assigned a true symbol in far space in that
1804      case replace them */
1805   D (D_ALLOC, ("packRegsForSupport: running on ic %p\n", ic));
1806
1807   if (IS_ITEMP (IC_LEFT (ic)) &&
1808       OP_SYMBOL (IC_LEFT (ic))->liveTo <= ic->seq)
1809     {
1810       iCode *dic = findAssignToSym (IC_LEFT (ic), ic);
1811       iCode *sic;
1812
1813       if (!dic)
1814         goto right;
1815
1816       /* found it we need to remove it from the
1817          block */
1818       for (sic = dic; sic != ic; sic = sic->next)
1819         bitVectUnSetBit (sic->rlive, IC_LEFT (ic)->key);
1820
1821       IC_LEFT (ic)->operand.symOperand =
1822         IC_RIGHT (dic)->operand.symOperand;
1823       IC_LEFT (ic)->key = IC_RIGHT (dic)->operand.symOperand->key;
1824       remiCodeFromeBBlock (ebp, dic);
1825       bitVectUnSetBit(OP_SYMBOL(IC_RESULT(dic))->defs,dic->key);
1826       hTabDeleteItem (&iCodehTab, dic->key, dic, DELETE_ITEM, NULL);
1827       // PENDING: Check vs mcs51
1828       change++;
1829     }
1830
1831   /* do the same for the right operand */
1832 right:
1833   if (!change &&
1834       IS_ITEMP (IC_RIGHT (ic)) &&
1835       OP_SYMBOL (IC_RIGHT (ic))->liveTo <= ic->seq)
1836     {
1837       iCode *dic = findAssignToSym (IC_RIGHT (ic), ic);
1838       iCode *sic;
1839
1840       if (!dic)
1841         return change;
1842
1843       /* found it we need to remove it from the block */
1844       for (sic = dic; sic != ic; sic = sic->next)
1845         bitVectUnSetBit (sic->rlive, IC_RIGHT (ic)->key);
1846
1847       IC_RIGHT (ic)->operand.symOperand =
1848         IC_RIGHT (dic)->operand.symOperand;
1849       IC_RIGHT (ic)->key = IC_RIGHT (dic)->operand.symOperand->key;
1850
1851       remiCodeFromeBBlock (ebp, dic);
1852       bitVectUnSetBit(OP_SYMBOL(IC_RESULT(dic))->defs,dic->key);
1853       hTabDeleteItem (&iCodehTab, dic->key, dic, DELETE_ITEM, NULL);
1854       // PENDING: vs mcs51
1855       change++;
1856     }
1857
1858   return change;
1859 }
1860 #endif
1861
1862 #define IS_OP_RUONLY(x) (x && IS_SYMOP(x) && OP_SYMBOL(x)->ruonly)
1863
1864 /** Will reduce some registers for single use.
1865  */
1866 static iCode *
1867 packRegsForOneuse (iCode * ic, operand * op, eBBlock * ebp)
1868 {
1869   bitVect *uses;
1870   iCode *dic, *sic;
1871
1872   // PENDING: Disable
1873   D (D_ALLOC, ("packRegsForOneUse: running on ic %p\n", ic));
1874
1875   /* if returning a literal then do nothing */
1876   if (!IS_SYMOP (op))
1877     return NULL;
1878
1879   /* only upto 2 bytes since we cannot predict
1880      the usage of b, & acc */
1881   if (getSize (operandType (op)) > 2)
1882     return NULL;
1883
1884   if (ic->op != RETURN &&
1885       ic->op != SEND)
1886     return NULL;
1887
1888   /* this routine will mark the a symbol as used in one 
1889      instruction use only && if the defintion is local 
1890      (ie. within the basic block) && has only one definition &&
1891      that definiion is either a return value from a 
1892      function or does not contain any variables in
1893      far space */
1894   uses = bitVectCopy (OP_USES (op));
1895   bitVectUnSetBit (uses, ic->key);      /* take away this iCode */
1896   if (!bitVectIsZero (uses))    /* has other uses */
1897     return NULL;
1898
1899   /* if it has only one defintion */
1900   if (bitVectnBitsOn (OP_DEFS (op)) > 1)
1901     return NULL;                /* has more than one definition */
1902
1903   /* get the that definition */
1904   if (!(dic =
1905         hTabItemWithKey (iCodehTab,
1906                          bitVectFirstBit (OP_DEFS (op)))))
1907     return NULL;
1908
1909   /* found the definition now check if it is local */
1910   if (dic->seq < ebp->fSeq ||
1911       dic->seq > ebp->lSeq)
1912     return NULL;                /* non-local */
1913
1914   /* now check if it is the return from a function call */
1915   if (dic->op == CALL || dic->op == PCALL)
1916     {
1917       if (ic->op != SEND && ic->op != RETURN &&
1918           !POINTER_SET(ic) && !POINTER_GET(ic))
1919         {
1920           OP_SYMBOL (op)->ruonly = 1;
1921           return dic;
1922         }
1923       dic = dic->next;
1924     }
1925
1926   /* otherwise check that the definition does
1927      not contain any symbols in far space */
1928   if (isOperandInFarSpace (IC_LEFT (dic)) ||
1929       isOperandInFarSpace (IC_RIGHT (dic)) ||
1930       IS_OP_RUONLY (IC_LEFT (ic)) ||
1931       IS_OP_RUONLY (IC_RIGHT (ic)))
1932     {
1933       return NULL;
1934     }
1935
1936   /* if pointer set then make sure the pointer is one byte */
1937   if (POINTER_SET (dic))
1938     return NULL;
1939
1940   if (POINTER_GET (dic))
1941     return NULL;
1942
1943   sic = dic;
1944
1945   /* also make sure the intervenening instructions
1946      don't have any thing in far space */
1947   for (dic = dic->next; dic && dic != ic; dic = dic->next)
1948     {
1949       /* if there is an intervening function call then no */
1950       if (dic->op == CALL || dic->op == PCALL)
1951         return NULL;
1952       /* if pointer set then make sure the pointer
1953          is one byte */
1954       if (POINTER_SET (dic))
1955         return NULL;
1956
1957       if (POINTER_GET (dic))
1958         return NULL;
1959
1960       /* if address of & the result is remat the okay */
1961       if (dic->op == ADDRESS_OF &&
1962           OP_SYMBOL (IC_RESULT (dic))->remat)
1963         continue;
1964
1965       /* if left or right or result is in far space */
1966       if (isOperandInFarSpace (IC_LEFT (dic)) ||
1967           isOperandInFarSpace (IC_RIGHT (dic)) ||
1968           isOperandInFarSpace (IC_RESULT (dic)) ||
1969           IS_OP_RUONLY (IC_LEFT (dic)) ||
1970           IS_OP_RUONLY (IC_RIGHT (dic)) ||
1971           IS_OP_RUONLY (IC_RESULT (dic)))
1972         {
1973           return NULL;
1974         }
1975     }
1976
1977   OP_SYMBOL (op)->ruonly = 1;
1978   return sic;
1979 }
1980
1981 /*-----------------------------------------------------------------*/
1982 /* isBitwiseOptimizable - requirements of JEAN LOUIS VERN          */
1983 /*-----------------------------------------------------------------*/
1984 static bool 
1985 isBitwiseOptimizable (iCode * ic)
1986 {
1987   sym_link *rtype = getSpec (operandType (IC_RIGHT (ic)));
1988
1989   /* bitwise operations are considered optimizable
1990      under the following conditions (Jean-Louis VERN) 
1991
1992      x & lit
1993      bit & bit
1994      bit & x
1995      bit ^ bit
1996      bit ^ x
1997      x   ^ lit
1998      x   | lit
1999      bit | bit
2000      bit | x
2001    */
2002   if (IS_LITERAL (rtype))
2003     return TRUE;
2004   return FALSE;
2005 }
2006
2007 /** Optimisations:
2008     Certian assignments involving pointers can be temporarly stored
2009     in HL.  Esp.
2010 genAssign
2011     ld  iy,#_Blah
2012     ld  bc,(iy)
2013 genAssign (ptr)
2014     ld  hl,bc
2015     ld  iy,#_Blah2
2016     ld  (iy),(hl)
2017 */
2018
2019 #if !DISABLE_PACKREGSFORACCUSE
2020 // PENDING
2021
2022 /** Pack registers for acc use.
2023     When the result of this operation is small and short lived it may
2024     be able to be stored in the accumelator.
2025  */
2026 static void 
2027 packRegsForAccUse (iCode * ic)
2028 {
2029   iCode *uic;
2030
2031   /* if this is an aggregate, e.g. a one byte char array */
2032   if (IS_AGGREGATE(operandType(IC_RESULT(ic)))) {
2033     return;
2034   }
2035
2036   /* if + or - then it has to be one byte result */
2037   if ((ic->op == '+' || ic->op == '-')
2038       && getSize (operandType (IC_RESULT (ic))) > 1)
2039     return;
2040
2041   /* if shift operation make sure right side is not a literal */
2042   if (ic->op == RIGHT_OP &&
2043       (isOperandLiteral (IC_RIGHT (ic)) ||
2044        getSize (operandType (IC_RESULT (ic))) > 1))
2045     return;
2046
2047   if (ic->op == LEFT_OP &&
2048       (isOperandLiteral (IC_RIGHT (ic)) ||
2049        getSize (operandType (IC_RESULT (ic))) > 1))
2050     return;
2051
2052   /* has only one definition */
2053   if (bitVectnBitsOn (OP_DEFS (IC_RESULT (ic))) > 1)
2054     return;
2055
2056   /* has only one use */
2057   if (bitVectnBitsOn (OP_USES (IC_RESULT (ic))) > 1)
2058     return;
2059
2060   /* and the usage immediately follows this iCode */
2061   if (!(uic = hTabItemWithKey (iCodehTab,
2062                                bitVectFirstBit (OP_USES (IC_RESULT (ic))))))
2063     return;
2064
2065   if (ic->next != uic)
2066     return;
2067
2068   /* if it is a conditional branch then we definitely can */
2069   if (uic->op == IFX)
2070     goto accuse;
2071
2072   if (uic->op == JUMPTABLE)
2073     return;
2074
2075 #if 0
2076   /* if the usage is not is an assignment or an 
2077      arithmetic / bitwise / shift operation then not */
2078   if (POINTER_SET (uic) &&
2079       getSize (aggrToPtr (operandType (IC_RESULT (uic)), FALSE)) > 1)
2080     return;
2081 #endif
2082
2083   if (uic->op != '=' &&
2084       !IS_ARITHMETIC_OP (uic) &&
2085       !IS_BITWISE_OP (uic) &&
2086       uic->op != LEFT_OP &&
2087       uic->op != RIGHT_OP)
2088     return;
2089
2090   /* if used in ^ operation then make sure right is not a 
2091      literl */
2092   if (uic->op == '^' && isOperandLiteral (IC_RIGHT (uic)))
2093     return;
2094
2095   /* if shift operation make sure right side is not a literal */
2096   if (uic->op == RIGHT_OP &&
2097       (isOperandLiteral (IC_RIGHT (uic)) ||
2098        getSize (operandType (IC_RESULT (uic))) > 1))
2099     return;
2100
2101   if (uic->op == LEFT_OP &&
2102       (isOperandLiteral (IC_RIGHT (uic)) ||
2103        getSize (operandType (IC_RESULT (uic))) > 1))
2104     return;
2105
2106 #if 0
2107   /* make sure that the result of this icode is not on the
2108      stack, since acc is used to compute stack offset */
2109   if (IS_TRUE_SYMOP (IC_RESULT (uic)) &&
2110       OP_SYMBOL (IC_RESULT (uic))->onStack)
2111     return;
2112 #endif
2113
2114 #if 0
2115   /* if either one of them in far space then we cannot */
2116   if ((IS_TRUE_SYMOP (IC_LEFT (uic)) &&
2117        isOperandInFarSpace (IC_LEFT (uic))) ||
2118       (IS_TRUE_SYMOP (IC_RIGHT (uic)) &&
2119        isOperandInFarSpace (IC_RIGHT (uic))))
2120     return;
2121 #endif
2122
2123   /* if the usage has only one operand then we can */
2124   if (IC_LEFT (uic) == NULL ||
2125       IC_RIGHT (uic) == NULL)
2126     goto accuse;
2127
2128   /* make sure this is on the left side if not
2129      a '+' since '+' is commutative */
2130   if (ic->op != '+' &&
2131       IC_LEFT (uic)->key != IC_RESULT (ic)->key)
2132     return;
2133
2134   // See mcs51 ralloc for reasoning
2135 #if 0
2136   /* if one of them is a literal then we can */
2137   if ((IC_LEFT (uic) && IS_OP_LITERAL (IC_LEFT (uic))) ||
2138       (IC_RIGHT (uic) && IS_OP_LITERAL (IC_RIGHT (uic))))
2139     {
2140       goto accuse;
2141       return;
2142     }
2143 #endif
2144
2145 /** This is confusing :)  Guess for now */
2146   if (IC_LEFT (uic)->key == IC_RESULT (ic)->key &&
2147       (IS_ITEMP (IC_RIGHT (uic)) ||
2148        (IS_TRUE_SYMOP (IC_RIGHT (uic)))))
2149     goto accuse;
2150
2151   if (IC_RIGHT (uic)->key == IC_RESULT (ic)->key &&
2152       (IS_ITEMP (IC_LEFT (uic)) ||
2153        (IS_TRUE_SYMOP (IC_LEFT (uic)))))
2154     goto accuse;
2155   return;
2156 accuse:
2157   OP_SYMBOL (IC_RESULT (ic))->accuse = ACCUSE_A;
2158 }
2159 #endif
2160
2161 static void 
2162 packRegsForHLUse (iCode * ic)
2163 {
2164   iCode *uic;
2165
2166   /* PENDING: Could do IFX */
2167   if (ic->op == IFX)
2168     {
2169       return;
2170     }
2171
2172   /* has only one definition */
2173   if (bitVectnBitsOn (OP_DEFS (IC_RESULT (ic))) > 1)
2174     {
2175       D (D_HLUSE, ("  + Dropping as has more than one def\n"));
2176       return;
2177     }
2178
2179   /* has only one use */
2180   if (bitVectnBitsOn (OP_USES (IC_RESULT (ic))) > 1)
2181     {
2182       D (D_HLUSE, ("  + Dropping as has more than one use\n"));
2183       return;
2184     }
2185
2186   /* and the usage immediately follows this iCode */
2187   if (!(uic = hTabItemWithKey (iCodehTab,
2188                                bitVectFirstBit (OP_USES (IC_RESULT (ic))))))
2189     {
2190       D (D_HLUSE, ("  + Dropping as usage isn't in this block\n"));
2191       return;
2192     }
2193
2194   if (ic->next != uic)
2195     {
2196       D (D_HLUSE, ("  + Dropping as usage doesn't follow this\n"));
2197       return;
2198     }
2199
2200   if (uic->op ==IFX)
2201     {
2202       return;
2203     }
2204
2205   if (getSize (operandType (IC_RESULT (ic))) != 2 ||
2206       (IC_LEFT(uic) && getSize (operandType (IC_LEFT (uic))) != 2) ||
2207       (IC_RIGHT(uic) && getSize (operandType (IC_RIGHT (uic))) != 2))
2208     {
2209       D (D_HLUSE, ("  + Dropping as the result size is not 2\n"));
2210       return;
2211     }
2212
2213   if (IS_Z80)
2214     {
2215       if (ic->op == CAST && uic->op == IPUSH)
2216         goto hluse;
2217       if (ic->op == ADDRESS_OF && uic->op == IPUSH)
2218         goto hluse;
2219       if (ic->op == ADDRESS_OF && POINTER_GET (uic) && IS_ITEMP( IC_RESULT (uic)))
2220         goto hluse;
2221       if (ic->op == CALL && ic->parmBytes == 0 && (uic->op == '-' || uic->op == '+'))
2222         goto hluse;
2223     }
2224   else if (IS_GB)
2225     {
2226       /* Case of assign a constant to offset in a static array. */
2227       if (ic->op == '+' && IS_VALOP (IC_RIGHT (ic)))
2228         {
2229           if (uic->op == '=' && POINTER_SET (uic))
2230             {
2231               goto hluse;
2232             }
2233           else if (uic->op == IPUSH && getSize (operandType (IC_LEFT (uic))) == 2)
2234             {
2235               goto hluse;
2236             }
2237         }
2238     }
2239
2240   D (D_HLUSE, ("  + Dropping as it's a bad op\n"));
2241   return;
2242 hluse:
2243   OP_SYMBOL (IC_RESULT (ic))->accuse = ACCUSE_SCRATCH;
2244 }
2245
2246 static iCode *
2247 packRegsForHLUse3 (iCode * lic, operand * op, eBBlock * ebp)
2248 {
2249   int i, key;
2250   symbol *sym;
2251   iCode *ic, *dic;
2252   bool isFirst = TRUE;
2253
2254   D (D_PACK_HLUSE3, ("Checking HL on %p lic key %u first def %u line %u:\n", OP_SYMBOL(op), lic->key, bitVectFirstBit(OP_DEFS(op)), lic->lineno));
2255   if (D_PACK_HLUSE3)
2256     piCode(lic, NULL);
2257
2258   if ( OP_SYMBOL(op)->accuse)
2259     {
2260       return NULL;
2261     }
2262
2263   if (OP_SYMBOL(op)->remat)
2264     {
2265       return NULL; 
2266     }
2267
2268   /* Only defined once */
2269   if (bitVectnBitsOn (OP_DEFS (op)) > 1)
2270     return NULL;
2271
2272   if (getSize (operandType (op)) > 2)
2273     return NULL;
2274
2275   /* And this is the definition */
2276   if (bitVectFirstBit (OP_DEFS (op)) != lic->key)
2277     return NULL;
2278
2279   /* first check if any overlapping liverange has already been
2280      assigned to DPTR */
2281   if (OP_SYMBOL(op)->clashes) 
2282     {
2283       for (i = 0 ; i < OP_SYMBOL(op)->clashes->size ; i++ ) 
2284         {
2285           if (bitVectBitValue(OP_SYMBOL(op)->clashes,i)) 
2286             {
2287               sym = hTabItemWithKey(liveRanges,i);
2288               if (sym->accuse == ACCUSE_SCRATCH)
2289                 {
2290                   return NULL;
2291                 }
2292             }
2293         }
2294     }
2295
2296   /* Nothing else that clashes with this is using the scratch
2297      register.  Scan through all of the intermediate instructions and
2298      see if any of them could nuke HL.
2299   */
2300   dic = ic = hTabFirstItemWK(iCodeSeqhTab,OP_SYMBOL(op)->liveFrom);
2301
2302   for (; ic && ic->seq <= OP_SYMBOL(op)->liveTo;
2303        ic = hTabNextItem(iCodeSeqhTab, &key)) 
2304     {
2305       if (D_PACK_HLUSE3)
2306         piCode(ic, NULL);
2307       D (D_PACK_HLUSE3, ("(On %p: op: %u next: %p)\n", ic, ic->op, ic->next));
2308
2309       if (isFirst)
2310         {
2311           isFirst = FALSE;
2312           if (ic->op == ADDRESS_OF)
2313             continue;
2314           if (POINTER_GET (ic))
2315             continue;
2316           if (ic->op == '=' && !POINTER_SET(ic))
2317             continue;
2318         }
2319
2320       if (IC_RESULT(ic) && IS_SYMOP(IC_RESULT(ic))
2321           && isOperandInDirSpace (IC_RESULT (ic)))
2322         return NULL;
2323
2324       if (IC_LEFT(ic) && IS_SYMOP(IC_LEFT(ic))
2325           && isOperandInDirSpace (IC_LEFT (ic)))
2326         return NULL;
2327
2328       if (IC_RIGHT(ic) && IS_SYMOP(IC_RIGHT(ic))
2329           && isOperandInDirSpace (IC_RIGHT (ic)))
2330         return NULL;
2331
2332       /* Handle the non left/right/result ones first */
2333       if (ic->op == IFX)
2334         continue;
2335       if (ic->op == JUMPTABLE)
2336         return NULL;
2337
2338       if (SKIP_IC2(ic))
2339         continue;
2340
2341       if (ic->op == CAST)
2342         continue;
2343
2344       if (ic->op == IPUSH && isOperandEqual (op, IC_LEFT (ic)))
2345         continue;
2346
2347       if (ic->op == SEND && isOperandEqual (op, IC_LEFT (ic)))
2348         continue;
2349
2350       if (ic->op == CALL && isOperandEqual (op, IC_RESULT (ic)))
2351         continue;
2352
2353       if (ic->op == LEFT_OP && isOperandLiteral (IC_RIGHT (ic)))
2354         continue;
2355
2356       if ((ic->op == '=' && !POINTER_SET(ic)) ||
2357           ic->op == UNARYMINUS ||
2358           ic->op == '+' ||
2359           ic->op == '-' ||
2360           ic->op == '>' ||
2361           ic->op == '<' ||
2362           ic->op == EQ_OP ||
2363           0)
2364         continue;
2365
2366       if (ic->op == '*' && isOperandEqual (op, IC_LEFT (ic)))
2367         continue;
2368
2369       if (POINTER_SET (ic) && isOperandEqual (op, IC_RESULT (ic)))
2370         continue;
2371
2372       if (POINTER_GET (ic) && isOperandEqual (op, IC_LEFT (ic)))
2373         continue;
2374
2375       if (IS_VALOP (IC_RIGHT (ic)) &&
2376           (ic->op == EQ_OP ||
2377            0))
2378         {
2379           continue;
2380         }
2381
2382       /* By default give up */
2383       return NULL;
2384     }
2385
2386   D (D_PACK_HLUSE3, ("Succeeded!\n"))
2387
2388   OP_SYMBOL (op)->accuse = ACCUSE_SCRATCH;
2389   return dic;
2390 }
2391
2392 static iCode *
2393 packRegsForIYUse (iCode * lic, operand * op, eBBlock * ebp)
2394 {
2395   int i, key;
2396   symbol *sym;
2397   iCode *ic, *dic;
2398   bitVect *uses;
2399
2400   D (D_PACK_IY, ("Checking IY on %p lic key %u first def %u line %u:\n", OP_SYMBOL(op), lic->key, bitVectFirstBit(OP_DEFS(op)), lic->lineno));
2401   if (D_PACK_IY)
2402     piCode(lic, NULL);
2403
2404   if ( OP_SYMBOL(op)->accuse)
2405     {
2406       return NULL;
2407     }
2408
2409   if (OP_SYMBOL(op)->remat)
2410     {
2411       return NULL; 
2412     }
2413
2414   /* Only defined once */
2415   if (bitVectnBitsOn (OP_DEFS (op)) > 1)
2416     return NULL;
2417
2418   /* And this is the definition */
2419   if (bitVectFirstBit (OP_DEFS (op)) != lic->key)
2420     return NULL;
2421
2422   /* first check if any overlapping liverange has already been
2423      assigned to DPTR */
2424   if (OP_SYMBOL(op)->clashes) 
2425     {
2426       for (i = 0 ; i < OP_SYMBOL(op)->clashes->size ; i++ ) 
2427         {
2428           if (bitVectBitValue(OP_SYMBOL(op)->clashes,i)) 
2429             {
2430               sym = hTabItemWithKey(liveRanges,i);
2431               if (sym->accuse == ACCUSE_IY)
2432                 {
2433                   return NULL;
2434                 }
2435             }
2436         }
2437     }
2438
2439   /* Only a few instructions can load into IY */
2440   if (lic->op != '=')
2441     {
2442       return NULL;
2443     }
2444
2445   /* Nothing else that clashes with this is using the scratch
2446      register.  Scan through all of the intermediate instructions and
2447      see if any of them could nuke HL.
2448   */
2449   dic = ic = hTabFirstItemWK(iCodeSeqhTab,OP_SYMBOL(op)->liveFrom);
2450   uses = OP_USES(op);
2451
2452   for (; ic && ic->seq <= OP_SYMBOL(op)->liveTo;
2453        ic = hTabNextItem(iCodeSeqhTab,&key)) 
2454     {
2455       if (D_PACK_IY)
2456         piCode(ic, NULL);
2457
2458       if (ic->op == PCALL || 
2459           ic->op == CALL ||
2460           ic->op == JUMPTABLE
2461           )
2462         return NULL;
2463
2464       if (SKIP_IC2(ic))
2465         continue;
2466
2467       /* Be pessamistic. */
2468       if (ic->op == IFX)
2469         return NULL;
2470
2471       D (D_PACK_IY, ("  op: %u uses %u result: %d left: %d right: %d\n", ic->op, bitVectBitValue(uses, ic->key),
2472                      IC_RESULT(ic) && IS_SYMOP(IC_RESULT(ic)) ? isOperandInDirSpace(IC_RESULT(ic)) : -1,
2473                      IC_LEFT(ic) && IS_SYMOP(IC_LEFT(ic)) ? isOperandInDirSpace(IC_LEFT(ic)) : -1,
2474                      IC_RIGHT(ic) && IS_SYMOP(IC_RIGHT(ic)) ? isOperandInDirSpace(IC_RIGHT(ic)) : -1
2475                      ));
2476
2477       if (IC_RESULT(ic) && IS_SYMOP(IC_RESULT(ic)) && 
2478           isOperandInDirSpace(IC_RESULT(ic)))
2479         return NULL;
2480       
2481       if (IC_RIGHT(ic) && IS_SYMOP(IC_RIGHT(ic)) && 
2482           isOperandInDirSpace(IC_RIGHT(ic)))
2483         return NULL;
2484       
2485       if (IC_LEFT(ic) && IS_SYMOP(IC_LEFT(ic)) && 
2486           isOperandInDirSpace(IC_LEFT(ic)))
2487         return NULL;
2488
2489       /* Only certain rules will work against IY.  Check if this iCode uses
2490          this symbol. */
2491       if (bitVectBitValue(uses, ic->key) != 0)
2492         {
2493           if (ic->op == '=' &&
2494               isOperandEqual(IC_RESULT(ic), op))
2495             continue;
2496
2497           if (ic->op == GET_VALUE_AT_ADDRESS &&
2498               isOperandEqual(IC_LEFT(ic), op))
2499             continue;
2500
2501           if (isOperandEqual(IC_RESULT(ic), IC_LEFT(ic)) == FALSE)
2502             return NULL;
2503
2504           if (IC_RIGHT (ic) && IS_VALOP (IC_RIGHT (ic)))
2505             {
2506               if (ic->op == '+' ||
2507                   ic->op == '-')
2508                 {
2509                   /* Only works if the constant is small */
2510                   if (operandLitValue (IC_RIGHT (ic)) < 4)
2511                     continue;
2512                 }
2513             }
2514
2515           return NULL;
2516         }
2517       else
2518         {
2519           /* This iCode doesn't use the sym.  See if this iCode preserves IY.
2520            */
2521           continue;
2522         }
2523
2524       /* By default give up */
2525       return NULL;
2526     }
2527
2528   D (D_PACK_IY, ("Succeeded IY!\n"));
2529
2530   OP_SYMBOL (op)->accuse = ACCUSE_IY;
2531   return dic;
2532 }
2533
2534 /** Returns TRUE if this operation can use acc and if it preserves the value.
2535  */
2536 static bool 
2537 opPreservesA (iCode * uic)
2538 {
2539   if (uic->op == IFX)
2540     {
2541       /* If we've gotten this far then the thing to compare must be
2542          small enough and must be in A.
2543       */
2544       return TRUE;
2545     }
2546
2547   if (uic->op == JUMPTABLE)
2548     {
2549       D (D_ACCUSE2, ("  + Dropping as operation is a Jumptable\n"));
2550       return FALSE;
2551     }
2552
2553   /* A pointer assign preserves A if A is the left value. */
2554   if (uic->op == '=' && POINTER_SET (uic))
2555     {
2556       return TRUE;
2557     }
2558
2559   /* if the usage has only one operand then we can */
2560   /* PENDING: check */
2561   if (IC_LEFT (uic) == NULL ||
2562       IC_RIGHT (uic) == NULL)
2563     {
2564       D (D_ACCUSE2, ("  + Dropping as operation has only one operand\n"));
2565       return FALSE;
2566     }
2567
2568   /* PENDING: check this rule */
2569   if (getSize (operandType (IC_RESULT (uic))) > 1)
2570     {
2571       D (D_ACCUSE2, ("  + Dropping as operation has size is too big\n"));
2572       return FALSE;
2573     }
2574
2575
2576   /* Disabled all of the old rules as they weren't verified and have
2577      caused at least one problem.
2578    */
2579   return FALSE;
2580 }
2581
2582 /** Returns true if this operand preserves the value of A.
2583  */
2584 static bool
2585 opIgnoresA (iCode * ic, iCode * uic)
2586 {
2587   /* A increment of an iTemp by a constant is OK. */
2588   if ( uic->op == '+' &&
2589        IS_ITEMP (IC_LEFT (uic)) &&
2590        IS_ITEMP (IC_RESULT (uic)) &&
2591        IS_OP_LITERAL (IC_RIGHT (uic)))
2592     {
2593       unsigned int icount = (unsigned int) floatFromVal (IC_RIGHT (uic)->operand.valOperand);
2594
2595       /* Being an ITEMP means that we're already a symbol. */
2596       if (icount == 1 &&
2597           IC_RESULT (uic)->operand.symOperand->key == IC_LEFT (uic)->operand.symOperand->key
2598           )
2599         {
2600           return TRUE;
2601         }
2602     }
2603   else if (uic->op == '=' && !POINTER_SET (uic))
2604     {
2605       /* If they are equal and get optimised out then things are OK. */
2606       if (isOperandEqual (IC_RESULT (uic), IC_RIGHT (uic)))
2607         {
2608           /* Straight assign is OK. */
2609           return TRUE;
2610         }
2611     }
2612
2613   return FALSE;
2614 }
2615
2616
2617 /* Some optimisation cases:
2618
2619    1. Part of memcpy
2620 ;       genPointerGet
2621         ld      l,-4(ix)
2622         ld      h,-3(ix)
2623         ld      c,(hl)
2624 ;       genPlus
2625         inc     -4(ix)
2626         jp      nz,00108$
2627         inc     -3(ix)
2628 00108$:
2629 ;       genAssign (pointer)
2630         ld      a,c
2631         ld      (de),a
2632  
2633       want to optimise down to:
2634         ld       hl,-4(ix) ...
2635         ld       a,(hl)
2636         inc      -4(ix).w  ...
2637         ld       (de),a
2638
2639       So genPointer get is OK
2640       genPlus where the right is constant, left is iTemp, and result is same as left
2641       genAssign (pointer) is OK
2642
2643     2. Part of _strcpy
2644 ;       genPointerGet
2645         ld      a,(de)
2646         ld      c,a
2647 ;       genIfx
2648         xor     a,a
2649         or      a,c
2650         jp      z,00103$
2651 ;       _strcpy.c 40
2652 ;       genAssign (pointer)
2653 ;       AOP_STK for _strcpy_to_1_1
2654         ld      l,-2(ix)
2655         ld      h,-1(ix)
2656         ld      (hl),c
2657
2658       want to optimise down to:
2659         ld      a,(de)
2660         or      a,a
2661         jp      z,00103$
2662         ld      (bc),a
2663       
2664       So genIfx where IC_COND has size of 1 and is a constant.
2665 */
2666
2667 /** Pack registers for acc use.
2668     When the result of this operation is small and short lived it may
2669     be able to be stored in the accumulator.
2670
2671     Note that the 'A preserving' list is currently emperical :)
2672  */
2673 static void 
2674 packRegsForAccUse2 (iCode * ic)
2675 {
2676   iCode *uic;
2677
2678   D (D_ACCUSE2, ("packRegsForAccUse2: running on ic %p line %u\n", ic, ic->lineno));
2679   if (D_ACCUSE2)
2680     piCode (ic, NULL);
2681
2682   /* Filter out all but those 'good' commands */
2683   if (
2684        !POINTER_GET (ic) &&
2685        ic->op != '+' &&
2686        ic->op != '-' &&
2687        !IS_BITWISE_OP (ic) &&
2688        ic->op != '=' &&
2689        ic->op != EQ_OP &&
2690        ic->op != '<' &&
2691        ic->op != '>' &&
2692        ic->op != CAST &&
2693        ic->op != GETHBIT &&
2694        1)
2695     {
2696       D (D_ACCUSE2, ("  + Dropping as not a 'good' source command\n"));
2697       return;
2698     }
2699
2700   /* if + or - then it has to be one byte result.
2701      MLH: Ok.
2702    */
2703   if ((ic->op == '+' || ic->op == '-')
2704       && getSize (operandType (IC_RESULT (ic))) > 1)
2705     {
2706       D (D_ACCUSE2, ("  + Dropping as it's a big + or -\n"));
2707       return;
2708     }
2709
2710   /* has only one definition */
2711   if (bitVectnBitsOn (OP_DEFS (IC_RESULT (ic))) > 1)
2712     {
2713       D (D_ACCUSE2, ("  + Dropping as it has more than one definition\n"));
2714       return;
2715     }
2716
2717   /* Right.  We may be able to propagate it through if:
2718      For each in the chain of uses the intermediate is OK.
2719    */
2720   /* Get next with 'uses result' bit on
2721      If this->next == next
2722      Validate use of next
2723      If OK, increase count
2724    */
2725   /* and the usage immediately follows this iCode */
2726   if (!(uic = hTabItemWithKey (iCodehTab,
2727                                bitVectFirstBit (OP_USES (IC_RESULT (ic))))))
2728     {
2729       D (D_ACCUSE2, ("  + Dropping as usage does not follow first\n"));
2730       return;
2731     }
2732
2733   {
2734     /* Create a copy of the OP_USES bit vect */
2735     bitVect *uses = bitVectCopy (OP_USES (IC_RESULT (ic)));
2736     int setBit;
2737     iCode *scan = ic, *next;
2738
2739     do
2740       {
2741         setBit = bitVectFirstBit (uses);
2742         next = hTabItemWithKey (iCodehTab, setBit);
2743         if (scan->next == next)
2744           {
2745             D (D_ACCUSE2_VERBOSE, ("  ! Is next in line\n"));
2746
2747             bitVectUnSetBit (uses, setBit);
2748             /* Still contigous. */
2749             if (!opPreservesA (next))
2750               {
2751                 D (D_ACCUSE2, ("  + Dropping as operation doesn't preserve A\n"));
2752                 return;
2753               }
2754             D (D_ACCUSE2_VERBOSE, ("  ! Preserves A, so continue scanning\n"));
2755             scan = next;
2756           }
2757         else if (scan->next == NULL && bitVectnBitsOn (uses) == 1 && next != NULL)
2758           {
2759             if (next->prev == NULL)
2760               {
2761                 if (!opPreservesA (next))
2762                   {
2763                     D (D_ACCUSE2, ("  + Dropping as operation doesn't preserve A #2\n"));
2764                     return;
2765                   }
2766                 bitVectUnSetBit (uses, setBit);
2767                 scan = next;
2768               }
2769             else 
2770               {
2771                 D (D_ACCUSE2, ("  + Dropping as last in list and next doesn't start a block\n"));
2772                 return;
2773               }
2774           }
2775         else if (scan->next == NULL)
2776           {
2777             D (D_ACCUSE2, ("  + Dropping as hit the end of the list\n"));
2778             D (D_ACCUSE2, ("  + Next in htab: %p\n", next));
2779             return;
2780           }
2781         else
2782           {
2783             if (opIgnoresA (ic, scan->next))
2784               {
2785                 /* Safe for now. */
2786                 scan = scan->next;
2787                 D (D_ACCUSE2_VERBOSE, ("  ! Op ignores A, so continue scanning\n"));
2788               }
2789             else
2790               {
2791                 D (D_ACCUSE2, ("  + Dropping as parts are not consecuitive and intermediate might use A\n"));
2792                 return;
2793               }
2794           }
2795       }
2796     while (!bitVectIsZero (uses));
2797
2798     OP_SYMBOL (IC_RESULT (ic))->accuse = ACCUSE_A;
2799     return;
2800   }
2801 }
2802
2803 /** Does some transformations to reduce register pressure.
2804  */
2805 static void 
2806 packRegisters (eBBlock * ebp)
2807 {
2808   iCode *ic;
2809   int change = 0;
2810
2811   D (D_ALLOC, ("packRegisters: entered.\n"));
2812
2813   while (1 && !DISABLE_PACK_ASSIGN)
2814     {
2815       change = 0;
2816       /* look for assignments of the form */
2817       /* iTempNN = TRueSym (someoperation) SomeOperand */
2818       /*       ....                       */
2819       /* TrueSym := iTempNN:1             */
2820       for (ic = ebp->sch; ic; ic = ic->next)
2821         {
2822           /* find assignment of the form TrueSym := iTempNN:1 */
2823           if (ic->op == '=' && !POINTER_SET (ic))
2824             change += packRegsForAssign (ic, ebp);
2825         }
2826       if (!change)
2827         break;
2828     }
2829
2830   for (ic = ebp->sch; ic; ic = ic->next)
2831     {
2832       /* Safe: address of a true sym is always constant. */
2833       /* if this is an itemp & result of a address of a true sym 
2834          then mark this as rematerialisable   */
2835       D (D_ALLOC, ("packRegisters: looping on ic %p\n", ic));
2836
2837       if (ic->op == ADDRESS_OF &&
2838           IS_ITEMP (IC_RESULT (ic)) &&
2839           IS_TRUE_SYMOP (IC_LEFT (ic)) &&
2840           bitVectnBitsOn (OP_DEFS (IC_RESULT (ic))) == 1 &&
2841           !OP_SYMBOL (IC_LEFT (ic))->onStack)
2842         {
2843
2844           OP_SYMBOL (IC_RESULT (ic))->remat = 1;
2845           OP_SYMBOL (IC_RESULT (ic))->rematiCode = ic;
2846           OP_SYMBOL (IC_RESULT (ic))->usl.spillLoc = NULL;
2847         }
2848
2849       /* Safe: just propagates the remat flag */
2850       /* if straight assignment then carry remat flag if this is the
2851          only definition */
2852       if (ic->op == '=' &&
2853           !POINTER_SET (ic) &&
2854           IS_SYMOP (IC_RIGHT (ic)) &&
2855           OP_SYMBOL (IC_RIGHT (ic))->remat &&
2856           bitVectnBitsOn (OP_SYMBOL (IC_RESULT (ic))->defs) <= 1)
2857         {
2858
2859           OP_SYMBOL (IC_RESULT (ic))->remat =
2860             OP_SYMBOL (IC_RIGHT (ic))->remat;
2861           OP_SYMBOL (IC_RESULT (ic))->rematiCode =
2862             OP_SYMBOL (IC_RIGHT (ic))->rematiCode;
2863         }
2864
2865       /* if the condition of an if instruction is defined in the
2866          previous instruction then mark the itemp as a conditional */
2867       if ((IS_CONDITIONAL (ic) ||
2868            ((ic->op == BITWISEAND ||
2869              ic->op == '|' ||
2870              ic->op == '^') &&
2871             isBitwiseOptimizable (ic))) &&
2872           ic->next && ic->next->op == IFX &&
2873           bitVectnBitsOn (OP_USES(IC_RESULT(ic)))==1 &&
2874           isOperandEqual (IC_RESULT (ic), IC_COND (ic->next)) &&
2875           OP_SYMBOL (IC_RESULT (ic))->liveTo <= ic->next->seq)
2876         {
2877
2878           OP_SYMBOL (IC_RESULT (ic))->regType = REG_CND;
2879           continue;
2880         }
2881
2882 #if 0
2883       /* reduce for support function calls */
2884       if (ic->supportRtn || ic->op == '+' || ic->op == '-')
2885         packRegsForSupport (ic, ebp);
2886 #endif
2887
2888       /* some cases the redundant moves can
2889          can be eliminated for return statements */
2890       if (ic->op == RETURN || ic->op == SEND)
2891         {
2892           packRegsForOneuse (ic, IC_LEFT (ic), ebp);
2893         }
2894
2895       /* if pointer set & left has a size more than
2896          one and right is not in far space */
2897       if (!DISABLE_PACK_ONE_USE &&
2898           POINTER_SET (ic) &&
2899           /* MLH: no such thing.
2900              !isOperandInFarSpace(IC_RIGHT(ic)) && */
2901           !OP_SYMBOL (IC_RESULT (ic))->remat &&
2902           !IS_OP_RUONLY (IC_RIGHT (ic)) &&
2903           getSize (aggrToPtr (operandType (IC_RESULT (ic)), FALSE)) > 1)
2904         {
2905
2906           packRegsForOneuse (ic, IC_RESULT (ic), ebp);
2907         }
2908
2909       /* if pointer get */
2910       if (!DISABLE_PACK_ONE_USE &&
2911           POINTER_GET (ic) &&
2912       /* MLH: dont have far space
2913          !isOperandInFarSpace(IC_RESULT(ic))&& */
2914           !OP_SYMBOL (IC_LEFT (ic))->remat &&
2915           !IS_OP_RUONLY (IC_RESULT (ic)) &&
2916           getSize (aggrToPtr (operandType (IC_LEFT (ic)), FALSE)) > 1)
2917         {
2918
2919           packRegsForOneuse (ic, IC_LEFT (ic), ebp);
2920         }
2921
2922       /* pack registers for accumulator use, when the result of an
2923          arithmetic or bit wise operation has only one use, that use is
2924          immediately following the defintion and the using iCode has
2925          only one operand or has two operands but one is literal & the
2926          result of that operation is not on stack then we can leave the
2927          result of this operation in acc:b combination */
2928
2929       if (!DISABLE_PACK_HL && IS_ITEMP (IC_RESULT (ic)))
2930         {
2931           if (IS_GB)
2932             packRegsForHLUse (ic);
2933           else
2934             packRegsForHLUse3 (ic, IC_RESULT (ic), ebp);
2935         }
2936
2937       if (!DISABLE_PACK_IY && IS_ITEMP (IC_RESULT (ic)) && IS_Z80)
2938         {
2939           packRegsForIYUse (ic, IC_RESULT (ic), ebp);
2940         }
2941
2942       if (!DISABLE_PACK_ACC && IS_ITEMP (IC_RESULT (ic)) &&
2943           getSize (operandType (IC_RESULT (ic))) == 1)
2944         {
2945           packRegsForAccUse2 (ic);
2946         }
2947     }
2948 }
2949
2950 /** Joins together two byte constant pushes into one word push.
2951  */
2952 static iCode *
2953 joinPushes (iCode *lic)
2954 {
2955   iCode *ic, *uic;
2956
2957   for (ic = lic; ic; ic = ic->next)
2958     {
2959       int first, second;
2960       value *val;
2961
2962       uic = ic->next;
2963
2964       /* Anything past this? */
2965       if (uic == NULL)
2966         {
2967           continue;
2968         }
2969       /* This and the next pushes? */
2970       if (ic->op != IPUSH || uic->op != IPUSH)
2971         {
2972           continue;
2973         }
2974       /* Both literals? */
2975       if ( !IS_OP_LITERAL (IC_LEFT (ic)) || !IS_OP_LITERAL (IC_LEFT (uic)))
2976         {
2977           continue;
2978         }
2979       /* Both characters? */
2980       if ( getSize (operandType (IC_LEFT (ic))) != 1 || getSize (operandType (IC_LEFT (uic))) != 1)
2981         {
2982           continue;
2983         }
2984       /* Pull out the values, make a new type, and create the new iCode for it.
2985        */
2986       first = (int)operandLitValue ( IC_LEFT (ic));
2987       second = (int)operandLitValue ( IC_LEFT (uic));
2988
2989       sprintf (buffer, "%u", ((first << 8) | (second & 0xFF)) & 0xFFFFU);
2990       val = constVal (buffer);
2991       SPEC_NOUN (val->type) = V_INT;
2992       IC_LEFT (ic)->operand.valOperand = val;
2993       
2994       /* Now remove the second one from the list. */
2995       ic->next = uic->next;
2996       if (uic->next)
2997         {
2998           /* Patch up the reverse link */
2999           uic->next->prev = ic;
3000         }
3001     }
3002
3003   return lic;
3004 }
3005
3006 /*-----------------------------------------------------------------*/
3007 /* assignRegisters - assigns registers to each live range as need  */
3008 /*-----------------------------------------------------------------*/
3009 void 
3010 z80_assignRegisters (eBBlock ** ebbs, int count)
3011 {
3012   iCode *ic;
3013   int i;
3014
3015   D (D_ALLOC, ("\n-> z80_assignRegisters: entered.\n"));
3016
3017   setToNull ((void *) &_G.funcrUsed);
3018   setToNull ((void *) &_G.totRegAssigned);  
3019   _G.stackExtend = _G.dataExtend = 0;
3020
3021   if (IS_GB)
3022     {
3023       /* DE is required for the code gen. */
3024       _G.nRegs = GBZ80_MAX_REGS;
3025       regsZ80 = _gbz80_regs;
3026     }
3027   else
3028     {
3029       _G.nRegs = Z80_MAX_REGS;
3030       regsZ80 = _z80_regs;
3031     }
3032
3033   /* change assignments this will remove some
3034      live ranges reducing some register pressure */
3035   for (i = 0; i < count; i++)
3036     packRegisters (ebbs[i]);
3037
3038   if (options.dump_pack)
3039     dumpEbbsToFileExt (DUMP_PACK, ebbs, count);
3040
3041   /* first determine for each live range the number of 
3042      registers & the type of registers required for each */
3043   regTypeNum ();
3044
3045   /* and serially allocate registers */
3046   serialRegAssign (ebbs, count);
3047
3048   freeAllRegs ();
3049   fillGaps();
3050
3051   /* if stack was extended then tell the user */
3052   if (_G.stackExtend)
3053     {
3054 /*      werror(W_TOOMANY_SPILS,"stack", */
3055 /*             _G.stackExtend,currFunc->name,""); */
3056       _G.stackExtend = 0;
3057     }
3058
3059   if (_G.dataExtend)
3060     {
3061 /*      werror(W_TOOMANY_SPILS,"data space", */
3062 /*             _G.dataExtend,currFunc->name,""); */
3063       _G.dataExtend = 0;
3064     }
3065
3066   if (options.dump_rassgn) {
3067     dumpEbbsToFileExt (DUMP_RASSGN, ebbs, count);
3068     dumpLiveRanges (DUMP_LRANGE, liveRanges);
3069   }
3070
3071   /* after that create the register mask
3072      for each of the instruction */
3073   createRegMask (ebbs, count);
3074
3075   /* now get back the chain */
3076   ic = iCodeLabelOptimize (iCodeFromeBBlock (ebbs, count));
3077
3078   ic = joinPushes (ic);
3079
3080   /* redo that offsets for stacked automatic variables */
3081   redoStackOffsets ();
3082
3083   genZ80Code (ic);
3084
3085   /* free up any stackSpil locations allocated */
3086   applyToSet (_G.stackSpil, deallocStackSpil);
3087   _G.slocNum = 0;
3088   setToNull ((void **) &_G.stackSpil);
3089   setToNull ((void **) &_G.spiltSet);
3090   /* mark all registers as free */
3091   freeAllRegs ();
3092
3093   return;
3094 }