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