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