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