Merge of the izt changes.
[fw/sdcc] / src / izt / ralloc.c
1 /** @file izt/ralloc.c
2  */
3 #include "izt.h"
4
5 /// Static data.
6 static struct {
7     struct {
8         /// Used to generate a unique name for the spill location.
9         int loc;
10         /// Set of all iTemps spilt onto the stack.
11         set *set;
12         /// Similar to stackSpill
13         bitVect *vect;
14     } spill;
15     /// Bitvector of all registers used in this function.
16     bitVect *funcUsedRegs;
17     /// If a bit is set in this then the iCode at that sequence has had
18     /// registers allocated.
19     bitVect *regAssigned;
20     int blockSpill;
21     int stackExtend;
22 } _G;
23
24 static REG *_findRegById(REG_ID id)
25 {
26     REG *r = izt_port->regs;
27     
28     while (r->size) {
29         if (r->id == id)
30             return r;
31         r++;
32     }
33     wassert(0);
34     return NULL;
35 }
36
37 static REG *_getSubReg(REG *r, int size, int offset)
38 {
39     wassert(r->size >= size);
40     
41     if (r->size == size) {
42         wassert(offset == 0);
43         return r;
44     }
45     // We use the hiding table to get the parts of the register.
46     else if (size == 1) {
47         wassert(offset == 0 || offset == 1);
48         return _findRegById(r->hides[offset]);
49     }
50     else if (size == 2) {
51         wassert(offset == 0);
52         return _findRegById(r->hides[2]);
53     }
54     // Cant.
55     wassert(0);
56     return NULL;
57 }
58
59 static int _numRegsAvailable(int size)
60 {
61     REG *r = izt_port->regs;
62     int ret = 0;
63
64     while (r->size) {
65         if (r->size == size && r->used == 0)
66             ret++;
67         r++;
68     }
69     
70     return ret;
71 }
72
73 static void _setClearUsed(REG_ID id, int clear)
74 {
75     REG *r = _findRegById(id);
76     wassert(r);
77
78     if (!clear) {
79         // The parent shouldnt be able to be allocated if this child
80         // is already.
81         wassert((r->used & REG_USED_HIDDEN) == 0);
82         r->used |= REG_USED_HIDDEN;
83     }
84     else {
85         wassert((r->used & REG_USED_HIDDEN) != 0);
86         r->used &= ~REG_USED_HIDDEN;
87     }
88 }
89
90 static void _markAsUsed(REG_ID id)
91 {
92     _setClearUsed(id, FALSE);
93 }
94
95 static void _markAsFree(REG_ID id)
96 {
97     _setClearUsed(id, TRUE);
98 }
99
100 static REG *_allocateReg(int size)
101 {
102     REG *r = izt_port->regs;
103     
104     while (r->size) {
105         if (r->size == size && r->used == 0) {
106             // Now go through the interference table and mark all other
107             // registers as used.
108             int i;
109             for (i=0; i < NUM_OF(r->hides); i++) {
110                 if (r->hides[i] == REG_ID_NONE) {
111                     break;
112                 }
113                 _markAsUsed(r->hides[i]);
114             }
115             r->used |= REG_USED;
116             return r;
117         }
118         r++;
119     }
120     return NULL;
121 }
122
123 static bitVect *_markRegBits(bitVect *v, REG *r)
124 {
125     int i;
126
127     // Mark the primary register.
128     v = bitVectSetBit(v, r->id);
129
130     // Now add all the hidden registers.
131     for (i=0; i < NUM_OF(r->hides); i++) {
132         if (r->hides[i] == REG_ID_NONE) {
133             break;
134         }
135         v = bitVectSetBit(v, r->hides[i]);
136     }
137
138     return v;
139 }
140
141 static void _freeReg(REG *r)
142 {
143     int i;
144     wassert(r->used == REG_USED);
145     
146     r->used = 0;
147
148     for (i=0; i < NUM_OF(r->hides); i++) {
149         if (r->hides[i] == REG_ID_NONE) {
150             break;
151         }
152         _markAsFree(r->hides[i]);
153     }
154 }
155
156 static void _freeAllRegs(viod)
157 {
158     REG *r = izt_port->regs;
159
160     while (r->size) {
161         r->used = 0;
162         r++;
163     }
164 }
165
166 static void _dumpRegs(void)
167 {
168     REG *r = izt_port->regs;
169
170     while (r->size) {
171         printf("%u\t%u\t%s\t%u\n", r->size, r->id, r->name, r->used);
172         r++;
173     }
174 }
175
176 void izt_init(IZT_PORT *port)
177 {
178     wassert(port && port->regs);
179     izt_port = port;
180     izt_initEmitters();
181 }
182
183 /// Lower register pressure by packing iTemps where possible.
184 static void _packRegisters(eBBlock *ebp)
185 {
186     // PENDING: Assignment packing
187     // PENDING: Mark address of a true symbol as remat.
188     // PENDING: Propagate remat through equals.
189     // PENDING: Assign bitwise which is followed by a conditional into carry.
190     // PENDING: Pack for one use on pointer get or set.  Assumes that the pointer
191     //  is stored in the scratch register.
192     // PENDING: Pack short use iTemps into ACC or the scratch register.
193 }
194
195 static void _computeRequiredRegs(void)
196 {
197     symbol *sym;
198     int k;
199
200     // Iterate over each live range.
201     for (sym = hTabFirstItem(liveRanges, &k); sym ;
202          sym = hTabNextItem(liveRanges, &k)) {
203
204         sym->nRegs = 0;
205
206         // If the symbol is never used, then next.
207         if ((sym->liveTo - sym->liveFrom) == 0)
208             continue;
209
210         // Only temporaries need registers.
211         if (!sym->isitmp)
212             continue;
213
214         // Conditionals live in carry and dont need registers.
215         if (sym->regType == REG_TYPE_CND)
216             continue;
217
218         
219 #if 0 // PENDING.  Currently we dont compute ruonly or accuse.
220         if (sym->ruonly || sym->accuse) {
221             if (IS_AGGREGATE(sym->type) || sym->isptr)
222                 sym->type = aggrToPtr(sym->type,FALSE);
223             continue ;
224         }
225 #endif
226         // We need registers.
227         if (IS_AGGREGATE(sym->type) || sym->isptr) {
228             // Turn an aggregate into something real.
229             sym->type = aggrToPtr(sym->type, FALSE);
230         }
231
232         sym->nRegs = getSize(sym->type);
233         wassert(sym->nRegs <= 4);
234     }
235 }
236
237 static bool _doesntNeedRegs(iCode *ic)
238 {
239     // Some types of instructions dont need registers.
240     // PENDING: Flush out the types and make processor specific.
241     if (SKIP_IC2(ic) ||
242         ic->op == JUMPTABLE ||
243         ic->op == IFX ||
244         ic->op == IPUSH ||
245         ic->op == IPOP ||
246         ic->op == RETURN) {
247         return TRUE;
248     }
249     return FALSE;
250 }
251
252 static bool _willCauseSpill(int size)
253 {
254     return _numRegsAvailable(size) == 0;
255 }
256
257 static void _deassignLRs(iCode *ic, eBBlock *ebp)
258 {
259     symbol *sym;
260     int ignored;
261     symbol *result;
262
263     // For each symbol
264     for (sym = hTabFirstItem(liveRanges, &ignored); sym; sym = hTabNextItem(liveRanges, &ignored)) {
265         
266         // Has this symbol expired yet?
267         if (sym->liveTo > ic->seq) {
268             // No.  Cant deassign.
269             continue;
270         }
271
272         // It has expired.  Free up the resources.
273         
274         // If it was spilt, then free up the stack spill location.
275         if (sym->isspilt) {
276             if (sym->stackSpil) {
277                 sym->usl.spillLoc->isFree = 1;
278                 sym->stackSpil = 0;
279             }
280             continue;
281         }
282
283         // If it currently has no registers assigned, then continue.
284         if (bitVectBitValue(_G.regAssigned, sym->key) == 0) {
285             continue;
286         }
287         
288         // If it has no registers assigned to it, then continue.
289         if (sym->nRegs == 0) {
290             continue;
291         }
292
293         // Mark this sym as not having registers assigned.
294         bitVectUnSetBit(_G.regAssigned, sym->key);
295         
296         // Free the registers.
297         _freeReg(sym->regs[0]);
298
299         // If deallocating will free up enough registers for this iCode
300         // then steal them immediatly.
301         if (IC_RESULT(ic) && !_doesntNeedRegs(ic)) {
302             result = OP_SYMBOL(IC_RESULT(ic));
303             if (result &&                       // Has a result
304                 result->liveTo > ic->seq &&     // and lives past this instruction
305                 result->liveTo <= ebp->lSeq &&  // and doesnt go past this block
306                 result->nRegs &&                // and actually needs registers
307                 !result->isspilt &&             // and doesnt have them yet
308                 !result->remat &&               // and wouldnt waste them
309                 !bitVectBitValue(_G.regAssigned, result->key) && // doesnt have them yet
310                 !_willCauseSpill(result->nRegs)
311                 ) {
312                 result->regs[0] = _allocateReg(result->nRegs);
313             }
314         }
315     }
316 }
317
318 /// Returns true if the live range of the given symbol doesnt overlap
319 /// with any of the live ranges in the set.
320 static bool _noOverlap (set *itmpStack, symbol *fsym)
321 {
322     symbol *sym;
323    
324     for (sym = setFirstItem(itmpStack); sym; sym = setNextItem(itmpStack)) {
325         if (sym->liveTo > fsym->liveFrom) {
326             return FALSE;
327         }
328     }
329     return TRUE;
330 }
331
332 /// Set operator that returns 1 if a free spill location is found.
333 DEFSETFUNC(_stackIsFree)
334 {
335     symbol *sym = item;
336     V_ARG(symbol **,sloc);
337     V_ARG(symbol *,fsym);
338
339     // Dont bother if one has already been found.
340     if (*sloc)
341         return 0;
342
343     if (sym->isFree &&                                  // This location is free...
344         _noOverlap(sym->usl.itmpStack, fsym) &&         // and its usage doesnt overlap with the usage of this sym
345         getSize(sym->type) >= getSize(fsym->type) &&    // and the location is big enough to hold the sym
346         1) {
347         // All good.  Take this location.
348         *sloc = sym;
349         return 1;
350     }
351     else {
352         // No match.
353         return 0;
354     }
355 }
356
357 /// Create a new spill location on the stack for this symbol.
358 symbol *_createStackSpill(symbol *sym)
359 {
360     symbol *sloc= NULL;
361
362     // Try to reuse an exisiting spill location.
363     if (applyToSet(_G.spill.set, _stackIsFree, &sloc, sym)) {
364         // Found one.  Take it over.
365         sym->usl.spillLoc = sloc;
366         sym->stackSpil = TRUE;
367         sloc->isFree = 0;
368         addSetHead(&sloc->usl.itmpStack, sym);
369         return sym;
370     }
371
372     // No existing location.  Time to create one.
373     // Give it a pretty name.
374     sprintf(buffer, "sloc%d", ++_G.spill.loc);
375     // And create.
376     sloc = newiTemp(buffer);
377
378     // Setup the type.
379     sloc->type = copyLinkChain(sym->type);
380     sloc->etype = getSpec(sloc->type);
381     SPEC_SCLS(sloc->etype) = S_AUTO ;    
382
383     allocLocal(sloc);
384
385     // "To prevent compiler warning"
386     sloc->isref = 1;
387
388     // Increase the local variable stack size on this function.
389     if (IN_STACK(sloc->etype)) {
390         currFunc->stack += getSize(sloc->type);
391         _G.stackExtend += getSize(sloc->type);
392     } else {
393         // The IZT port currently doesnt support loading locals into data space.
394         wassert(0);
395     }
396
397     // And add it to the spill set.
398     addSetHead(&_G.spill.set, sloc);
399     sym->usl.spillLoc = sloc;
400     sym->stackSpil = TRUE;
401     
402     // "Add it to the set of itempStack set of the spill location
403     addSetHead(&sloc->usl.itmpStack,sym);
404
405     return sym;
406 }
407
408 static void _spillThis(symbol *sym)
409 {
410     // Create a spill location if it needs one and doesnt have one yet.
411     if (!(sym->remat || sym->usl.spillLoc)) {
412         _createStackSpill(sym);
413     }
414
415     sym->isspilt = TRUE;
416     // Add it to the spilt set.
417     _G.spill.vect = bitVectSetBit(_G.spill.vect, sym->key);
418     // and remove it from the 'has registers' set.
419     bitVectUnSetBit(_G.regAssigned, sym->key);
420
421     // Free up any registers that were assigned to this.
422     if (sym->regs[0]) {
423         _freeReg(sym->regs[0]);
424         sym->regs[0] = NULL;
425     }
426
427     // CHECK: If this sym now has a spill location, mark it as allocated
428     // so that the stack packing later doesnt remove it.
429     if (sym->usl.spillLoc && !sym->remat) {
430         sym->usl.spillLoc->allocreq = TRUE;
431     }
432
433     return;
434 }
435
436 static bitVect *_findSpillable(iCode *ic)
437 {
438     bitVect *spillable;
439
440     // First create a copy of the currently live ranges.
441     spillable = bitVectCopy(ic->rlive);
442     // Remove those which are already spilt.
443     spillable = bitVectCplAnd(spillable, _G.spill.vect);
444     // Remove those that this iCode uses.
445     spillable = bitVectCplAnd(spillable, ic->uses);
446     // Remove those that this iCode defines.
447     bitVectUnSetBit(spillable, ic->defKey);
448
449     // Only those that have registers assigned can actually be spilt :)
450     spillable = bitVectIntersect(spillable, _G.regAssigned);
451
452     return spillable;
453 }
454
455 /// Finds the least used live range
456 static symbol *_leastUsedLR(set *sset)
457 {
458     // sym is the currently least used symbol.
459     symbol *sym;
460     // walk walks the list of symbols in the scan set.
461     symbol *walk;
462     
463     // Use the first as the seed.
464     sym = walk = setFirstItem(sset);
465
466     while (walk) {
467         // Prefer spilling the symbol with the least allocated registers.
468         // PENDING: Why?
469         if (walk->used == sym->used) {
470             if (getSize(walk->type) < getSize(sym->type)) {
471                 sym = walk;
472             }
473         }
474         else if (walk->used < sym->used) {
475             // This is used less than the current best.  It looses.
476             sym = walk;
477         }
478         
479         walk = setNextItem(sset);
480    }
481
482     setToNull((void **)&sset);
483     sym->blockSpil = 0;
484
485     return sym;
486 }
487
488 /// Applies a function to a given set of live ranges.
489 static set *_liveRangesWith(bitVect *lrs, int (func)(symbol *,eBBlock *, iCode *),
490                      eBBlock *ebp, iCode *ic)
491 {
492     set *rset = NULL;
493     int i;
494
495     // Dont do anything if the bitVect is empty.
496     if (!lrs || !lrs->size)
497         return NULL;
498
499     for (i = 1; i < lrs->size; i++ ) {
500         symbol *sym;
501
502         // If this bit isnt turned on, skip.
503         if (!bitVectBitValue(lrs, i))
504             continue ;
505
506         // If we don't find it in the live range hash table we are in serious trouble.
507         if (!(sym = hTabItemWithKey(liveRanges, i))) {
508             werror(E_INTERNAL_ERROR,__FILE__,__LINE__,
509                    "liveRangesWith could not find liveRange");
510             exit(1);
511         }
512         
513         // If the function likes it, and it has registers assigned to
514         // it, add it to the return set.
515         if (func(sym, ebp, ic) && bitVectBitValue(_G.regAssigned, sym->key)) {
516             addSetHead(&rset,sym);
517         }
518     }
519
520     return rset;
521 }
522
523 /// Returns TRUE always.  Used to fetch all live ranges.
524 static int _allLRs(symbol *sym, eBBlock *ebp, iCode *ic)
525 {
526     return 1;
527 }
528
529 static void _serialRegAssign(eBBlock **ebbs, int count)
530 {
531     int i;
532
533     // For each block, do...
534     for (i=0; i<count; i++) {
535         iCode *ic;
536
537         if (ebbs[i]->noPath &&
538             (ebbs[i]->entryLabel != entryLabel &&
539              ebbs[i]->entryLabel != returnLabel )) {
540             // PENDING:  Dont understand.
541             continue;
542         }
543         
544         
545         // For each iCode in this block, do...
546         for (ic = ebbs[i]->sch; ic; ic = ic->next) {
547             symbol *sym;
548             bitVect *spillable;
549             int willCauseSpill;
550
551             // Dont support IPOP
552             wassert(ic->op != IPOP);
553
554             // if result is present && is a true symbol
555             if (IC_RESULT(ic) && ic->op != IFX &&
556                 IS_TRUE_SYMOP(IC_RESULT(ic)))
557                 OP_SYMBOL(IC_RESULT(ic))->allocreq = 1;
558
559             // Take away registers from live ranges that end at this
560             // instruction.
561             _deassignLRs(ic, ebbs[i]);
562             
563             // Some instructions dont need registers.
564             if (_doesntNeedRegs(ic)) {
565                 continue;
566             }
567
568             // If there is no result, then it doesnt need registers.
569             if (!IC_RESULT(ic)) {
570                 continue;
571             }
572
573             sym = OP_SYMBOL(IC_RESULT(ic));
574
575             // Does it need any registers?
576             if (sym->nRegs == 0) {
577                 continue;
578             }
579
580             // Is it already split?
581             if (sym->isspilt) {
582                 continue;
583             }
584
585             // Does it already have registers assigned?
586             if (bitVectBitValue(_G.regAssigned,sym->key)) {
587                 continue;
588             }
589
590             // Will it live past this instruction?
591             if (sym->liveTo <= ic->seq) {
592                 continue;
593             }
594
595             // MLH Doesnt understand this.
596             /* "Iif some liverange has been spilt at the block level
597                and this one live beyond this block then spil this
598                to be safe" */
599             if (_G.blockSpill && sym->liveTo > ebbs[i]->lSeq) {
600                 _spillThis(sym);
601                 continue;
602             }
603             
604             // Seems that this symbol needs registers.  See if 
605             // allocating will cause a spill.
606             willCauseSpill = _willCauseSpill(sym->nRegs);
607             spillable = _findSpillable(ic);
608
609             // If this is remat., then dont waste any regsiters on it.
610             if (sym->remat) {
611                 _spillThis(sym);
612                 continue;
613             }
614
615             // If trying to allocate will cause a spill, and nothing
616             // else is spillable then this sym looses.
617             if (willCauseSpill && bitVectIsZero(spillable)) {
618                 _spillThis(sym);
619                 continue;
620             }
621
622             // If this will cause a spill, and it already has a spill
623             // location then spill this if it is the least used.
624             if (willCauseSpill && sym->usl.spillLoc) {
625                 symbol *leastUsed = _leastUsedLR(_liveRangesWith(spillable, _allLRs, ebbs[i], ic));
626                 if (leastUsed && leastUsed->used > sym->used) {
627                     _spillThis(sym);
628                     continue;
629                 }
630             }
631
632             // Hmm.  Here we could have no registers available but
633             // we'll still try to allocate.  MLH wonders how this will
634             // work.
635             
636             // Mark this iCode as having registers assigned to it.
637             _G.regAssigned = bitVectSetBit(_G.regAssigned, sym->key);
638
639             // And do it.
640             sym->regs[0] = _allocateReg(sym->nRegs);
641         }
642     }
643 }
644
645 static DEFSETFUNC(_deallocStackSpil)
646 {
647     symbol *sym = item;
648
649     deallocLocal(sym);
650     return 0;
651 }
652
653 /// Compute the register mask for an operand.
654 bitVect *_rUmaskForOp(operand *op)
655 {
656     bitVect *rumask;
657     symbol *sym;
658     
659     // "Only temporaries are assigned registers"
660     if (!IS_ITEMP(op)) 
661         return NULL;
662
663     sym = OP_SYMBOL(op);
664     
665     // If its spilt or no registers are needed, then no regs are assigned.
666     if (sym->isspilt || !sym->nRegs)
667         return NULL;
668
669     rumask = newBitVect(REG_ID_MAX);
670
671     if (sym->regs[0]) {
672         rumask = _markRegBits(rumask, sym->regs[0]);
673     }
674
675     return rumask;
676 }
677
678 /// Returns bit vector of registers used in iCode.
679 bitVect *_regsUsedIniCode (iCode *ic)
680 {
681     bitVect *rmask = newBitVect(REG_ID_MAX);
682
683     do {
684         // Special cases first.
685         if (ic->op == IFX ) {
686             rmask = bitVectUnion(rmask, _rUmaskForOp(IC_COND(ic)));
687             break;
688         }
689
690         if (ic->op == JUMPTABLE) {
691             rmask = bitVectUnion(rmask, _rUmaskForOp(IC_JTCOND(ic)));
692             break;
693         }
694
695         // Now the good old left, right, and result.
696         if (IC_LEFT(ic)) {
697             rmask = bitVectUnion(rmask, _rUmaskForOp(IC_LEFT(ic)));
698         }
699         
700         if (IC_RIGHT(ic)) {
701             rmask = bitVectUnion(rmask, _rUmaskForOp(IC_RIGHT(ic)));
702         }
703
704         if (IC_RESULT(ic)) {
705             rmask = bitVectUnion(rmask, _rUmaskForOp(IC_RESULT(ic)));
706         }
707     } while (0);
708
709     return rmask;
710 }
711
712 /// Compute the helper bitVect that contains the register used mask.
713 static void _createRegMask(eBBlock **ebbs, int count)
714 {
715     int i;
716
717     /* for all blocks */
718     for (i = 0; i < count; i++) {
719         iCode *ic ;
720
721         // If this code is unused, skip it.
722         if ( ebbs[i]->noPath &&
723              ( ebbs[i]->entryLabel != entryLabel &&
724                ebbs[i]->entryLabel != returnLabel )) {
725             continue;
726         }
727
728         /* for all instructions */
729         for (ic = ebbs[i]->sch; ic; ic = ic->next) {
730             int j;
731
732             if (SKIP_IC2(ic) || !ic->rlive)
733                 continue ;
734             
735             // Mark the registers used in this instruction.
736             ic->rUsed = _regsUsedIniCode(ic);
737             // Mark them as used at least once in the function.
738             _G.funcUsedRegs = bitVectUnion(_G.funcUsedRegs, ic->rUsed);
739
740             /* now create the register mask for those 
741                registers that are in use : this is a
742                super set of ic->rUsed */
743             ic->rMask = newBitVect(REG_ID_MAX+1);
744
745             // "For all live Ranges alive at this point"
746             for (j = 1; j < ic->rlive->size; j++) {
747                 symbol *sym;
748
749                 // "If if not alive then continue"
750                 if (!bitVectBitValue(ic->rlive,j)) {
751                     continue;
752                 }
753
754                 // "Find the live range we are interested in"
755                 if (!(sym = hTabItemWithKey(liveRanges,j))) {
756                     werror (E_INTERNAL_ERROR,__FILE__,__LINE__,
757                             "createRegMask cannot find live range");
758                     exit(0);
759                 }
760
761                 // "If no register assigned to it"
762                 if (!sym->nRegs || sym->isspilt) {
763                     continue;
764                 }
765
766                 // If this has any registers allocated, mark them as such.
767                 if (sym->regs[0]) {
768                     ic->rMask = _markRegBits(ic->rMask, sym->regs[0]);
769                 }
770             }
771         }
772     }
773 }
774
775 void izt_assignRegisters(eBBlock **ebbs, int count)
776 {
777     // Contains a flat version of ebbs used in code generation.
778     iCode *chain;
779
780     // Clear the bit vector of registers used in this function.
781     // Assumes that assignRegisters is called once per function.
782     setToNull((void *)&_G.funcUsedRegs);
783
784     // First scan each live range, and figure out what registers
785     // are required.
786     _computeRequiredRegs();
787
788     // Now allocate the registers.
789     _serialRegAssign(ebbs, count);
790
791     // And create the helper register used mask.
792     _createRegMask(ebbs, count);
793
794     // Turn the bblock array into an optimised list of iCode entries.
795     chain = iCodeLabelOptimize(iCodeFromeBBlock(ebbs,count));
796
797     // Redo the stack offsets.  This will remove any redundent stack
798     // locations ie iTemps that exist only in registers.
799     redoStackOffsets();
800
801     izt_gen(chain);
802
803     // Deallocate any stack spill locations.
804     applyToSet(_G.spill.set, _deallocStackSpil);
805
806     _G.spill.loc = 0;
807     setToNull((void **)&_G.spill.set);
808     setToNull((void **)&_G.spill.vect);
809
810     // And free all registers.
811     _freeAllRegs();
812 }
813
814 void warningStopper(void)
815 {
816     // For now references all unused functions.
817     _dumpRegs();
818     _packRegisters(NULL);
819     _getSubReg(NULL, 0, 0);
820 }