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