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