a4f7f92aa4fe5a7b950b182f69b9ea5d35b7b20b
[oota-llvm.git] / lib / Target / SparcV9 / RegAlloc / PhyRegAlloc.cpp
1 // $Id$
2 //***************************************************************************
3 // File:
4 //      PhyRegAlloc.cpp
5 // 
6 // Purpose:
7 //      Register allocation for LLVM.
8 //      
9 // History:
10 //      9/10/01  -  Ruchira Sasanka - created.
11 //**************************************************************************/
12
13 #include "llvm/CodeGen/PhyRegAlloc.h"
14 #include "llvm/CodeGen/MachineInstr.h"
15 #include "llvm/Target/TargetMachine.h"
16 #include "llvm/Target/MachineFrameInfo.h"
17
18
19 // ***TODO: There are several places we add instructions. Validate the order
20 //          of adding these instructions.
21
22
23
24 cl::Enum<RegAllocDebugLevel_t> DEBUG_RA("dregalloc", cl::NoFlags,
25   "enable register allocation debugging information",
26   clEnumValN(RA_DEBUG_None   , "n", "disable debug output"),
27   clEnumValN(RA_DEBUG_Normal , "y", "enable debug output"),
28   clEnumValN(RA_DEBUG_Verbose, "v", "enable extra debug output"), 0);
29
30
31 //----------------------------------------------------------------------------
32 // Constructor: Init local composite objects and create register classes.
33 //----------------------------------------------------------------------------
34 PhyRegAlloc::PhyRegAlloc(Method *M, 
35                          const TargetMachine& tm, 
36                          MethodLiveVarInfo *const Lvi) 
37                         : RegClassList(),
38                           TM(tm),
39                           Meth(M),
40                           mcInfo(MachineCodeForMethod::get(M)),
41                           LVI(Lvi), LRI(M, tm, RegClassList), 
42                           MRI( tm.getRegInfo() ),
43                           NumOfRegClasses(MRI.getNumOfRegClasses()),
44                           AddedInstrMap()
45                     
46 {
47   // **TODO: use an actual reserved color list 
48   ReservedColorListType *RCL = new ReservedColorListType();
49
50   // create each RegisterClass and put in RegClassList
51   for( unsigned int rc=0; rc < NumOfRegClasses; rc++)  
52     RegClassList.push_back( new RegClass(M, MRI.getMachineRegClass(rc), RCL) );
53 }
54
55 //----------------------------------------------------------------------------
56 // This method initally creates interference graphs (one in each reg class)
57 // and IGNodeList (one in each IG). The actual nodes will be pushed later. 
58 //----------------------------------------------------------------------------
59
60 void PhyRegAlloc::createIGNodeListsAndIGs()
61 {
62   if(DEBUG_RA ) cout << "Creating LR lists ..." << endl;
63
64   // hash map iterator
65   LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();   
66
67   // hash map end
68   LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();   
69
70     for(  ; HMI != HMIEnd ; ++HMI ) {
71       
72       if( (*HMI).first ) { 
73
74         LiveRange *L = (*HMI).second;      // get the LiveRange
75
76         if( !L) { 
77           if( DEBUG_RA) {
78             cout << "\n*?!?Warning: Null liver range found for: ";
79             printValue( (*HMI).first) ; cout << endl;
80           }
81           continue;
82         }
83                                         // if the Value * is not null, and LR  
84                                         // is not yet written to the IGNodeList
85        if( !(L->getUserIGNode())  ) {  
86                                    
87          RegClass *const RC =           // RegClass of first value in the LR
88            //RegClassList [MRI.getRegClassIDOfValue(*(L->begin()))];
89            RegClassList[ L->getRegClass()->getID() ];
90
91          RC-> addLRToIG( L );           // add this LR to an IG
92        }
93     }
94   }
95
96                                         // init RegClassList
97   for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)  
98     RegClassList[ rc ]->createInterferenceGraph();
99
100   if( DEBUG_RA)
101     cout << "LRLists Created!" << endl;
102 }
103
104
105
106 //----------------------------------------------------------------------------
107 // This method will add all interferences at for a given instruction.
108 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg 
109 // class as that of live var. The live var passed to this function is the 
110 // LVset AFTER the instruction
111 //----------------------------------------------------------------------------
112
113 void PhyRegAlloc::addInterference(const Value *const Def, 
114                                   const LiveVarSet *const LVSet,
115                                   const bool isCallInst) {
116
117   LiveVarSet::const_iterator LIt = LVSet->begin();
118
119   // get the live range of instruction
120   const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );   
121
122   IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
123   assert( IGNodeOfDef );
124
125   RegClass *const RCOfDef = LROfDef->getRegClass(); 
126
127   // for each live var in live variable set
128   for( ; LIt != LVSet->end(); ++LIt) {
129
130     if( DEBUG_RA > 1) {
131       cout << "< Def="; printValue(Def);     
132       cout << ", Lvar=";  printValue( *LIt); cout  << "> ";
133     }
134
135     //  get the live range corresponding to live var
136     LiveRange *const LROfVar = LRI.getLiveRangeForValue(*LIt );    
137
138     // LROfVar can be null if it is a const since a const 
139     // doesn't have a dominating def - see Assumptions above
140     if( LROfVar)   {  
141
142       if(LROfDef == LROfVar)            // do not set interf for same LR
143         continue;
144
145       // if 2 reg classes are the same set interference
146       if( RCOfDef == LROfVar->getRegClass() ){ 
147         RCOfDef->setInterference( LROfDef, LROfVar);  
148
149       }
150
151     else if(DEBUG_RA > 1)  { 
152       // we will not have LRs for values not explicitly allocated in the
153       // instruction stream (e.g., constants)
154       cout << " warning: no live range for " ; 
155       printValue( *LIt); cout << endl; }
156     
157     }
158  
159   }
160
161 }
162
163
164 //----------------------------------------------------------------------------
165 // For a call instruction, this method sets the CallInterference flag in 
166 // the LR of each variable live int the Live Variable Set live after the
167 // call instruction (except the return value of the call instruction - since
168 // the return value does not interfere with that call itself).
169 //----------------------------------------------------------------------------
170
171 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst, 
172                                        const LiveVarSet *const LVSetAft ) 
173 {
174   // Now find the LR of the return value of the call
175
176
177   // We do this because, we look at the LV set *after* the instruction
178   // to determine, which LRs must be saved across calls. The return value
179   // of the call is live in this set - but it does not interfere with call
180   // (i.e., we can allocate a volatile register to the return value)
181
182   LiveRange *RetValLR = NULL;
183
184   const Value *RetVal = MRI.getCallInstRetVal( MInst );
185
186   if( RetVal ) {
187     RetValLR = LRI.getLiveRangeForValue( RetVal );
188     assert( RetValLR && "No LR for RetValue of call");
189   }
190
191   if( DEBUG_RA)
192     cout << "\n For call inst: " << *MInst;
193
194   LiveVarSet::const_iterator LIt = LVSetAft->begin();
195
196   // for each live var in live variable set after machine inst
197   for( ; LIt != LVSetAft->end(); ++LIt) {
198
199    //  get the live range corresponding to live var
200     LiveRange *const LR = LRI.getLiveRangeForValue(*LIt ); 
201
202     if( LR && DEBUG_RA) {
203       cout << "\n\tLR Aft Call: ";
204       LR->printSet();
205     }
206    
207
208     // LR can be null if it is a const since a const 
209     // doesn't have a dominating def - see Assumptions above
210     if( LR && (LR != RetValLR) )   {  
211       LR->setCallInterference();
212       if( DEBUG_RA) {
213         cout << "\n  ++Added call interf for LR: " ;
214         LR->printSet();
215       }
216     }
217
218   }
219
220 }
221
222
223 //----------------------------------------------------------------------------
224 // This method will walk thru code and create interferences in the IG of
225 // each RegClass.
226 //----------------------------------------------------------------------------
227
228 void PhyRegAlloc::buildInterferenceGraphs()
229 {
230
231   if(DEBUG_RA) cout << "Creating interference graphs ..." << endl;
232
233   Method::const_iterator BBI = Meth->begin();  // random iterator for BBs   
234
235   for( ; BBI != Meth->end(); ++BBI) {          // traverse BBs in random order
236
237     // get the iterator for machine instructions
238     const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
239     MachineCodeForBasicBlock::const_iterator 
240       MInstIterator = MIVec.begin();
241
242     // iterate over all the machine instructions in BB
243     for( ; MInstIterator != MIVec.end(); ++MInstIterator) {  
244
245       const MachineInstr * MInst = *MInstIterator; 
246
247       // get the LV set after the instruction
248       const LiveVarSet *const LVSetAI = 
249         LVI->getLiveVarSetAfterMInst(MInst, *BBI);
250     
251       const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
252
253       if( isCallInst ) {
254         //cout << "\nFor call inst: " << *MInst;
255
256         // set the isCallInterference flag of each live range wich extends
257         // accross this call instruction. This information is used by graph
258         // coloring algo to avoid allocating volatile colors to live ranges
259         // that span across calls (since they have to be saved/restored)
260         setCallInterferences( MInst,  LVSetAI);
261       }
262
263
264       // iterate over  MI operands to find defs
265       for( MachineInstr::val_op_const_iterator OpI(MInst);!OpI.done(); ++OpI) {
266
267         if( OpI.isDef() ) {     
268           // create a new LR iff this operand is a def
269           addInterference(*OpI, LVSetAI, isCallInst );
270         } //if this is a def
271       } // for all operands
272
273
274       // if there are multiple defs in this instruction e.g. in SETX
275       //   
276       if( (TM.getInstrInfo()).isPseudoInstr( MInst->getOpCode()) )
277         addInterf4PseudoInstr(MInst);
278
279
280       // Also add interference for any implicit definitions in a machine
281       // instr (currently, only calls have this).
282
283       unsigned NumOfImpRefs =  MInst->getNumImplicitRefs();
284       if(  NumOfImpRefs > 0 ) {
285         for(unsigned z=0; z < NumOfImpRefs; z++) 
286           if( MInst->implicitRefIsDefined(z) )
287             addInterference( MInst->getImplicitRef(z), LVSetAI, isCallInst );
288       }
289
290       /*
291       // record phi instrns in PhiInstList
292       if( TM.getInstrInfo().isDummyPhiInstr(MInst->getOpCode()) )
293         PhiInstList.push_back( MInst );
294       */
295
296     } // for all machine instructions in BB
297     
298   } // for all BBs in method
299
300
301   // add interferences for method arguments. Since there are no explict 
302   // defs in method for args, we have to add them manually
303           
304   addInterferencesForArgs();            // add interference for method args
305
306   if( DEBUG_RA)
307     cout << "Interference graphs calculted!" << endl;
308
309 }
310
311 //--------------------------------------------------------------------------
312 // Pseudo instructions will be exapnded to multiple instructions by the
313 // assembler. Consequently, all the opernds must get distinct registers
314 //--------------------------------------------------------------------------
315
316 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
317
318   bool setInterf = false;
319
320   // iterate over  MI operands to find defs
321   for( MachineInstr::val_op_const_iterator It1(MInst);!It1.done(); ++It1) {
322     
323     const LiveRange *const LROfOp1 = LRI.getLiveRangeForValue( *It1 ); 
324
325     if( !LROfOp1 && It1.isDef() )
326       assert( 0 && "No LR for Def in PSEUDO insruction");
327
328     //if( !LROfOp1 ) continue;
329
330     MachineInstr::val_op_const_iterator It2 = It1;
331     ++It2;
332         
333     for(  ; !It2.done(); ++It2) {
334
335       const LiveRange *const LROfOp2 = LRI.getLiveRangeForValue( *It2 ); 
336
337       if( LROfOp2) {
338             
339         RegClass *const RCOfOp1 = LROfOp1->getRegClass(); 
340         RegClass *const RCOfOp2 = LROfOp2->getRegClass(); 
341  
342         if( RCOfOp1 == RCOfOp2 ){ 
343           RCOfOp1->setInterference( LROfOp1, LROfOp2 );  
344           //cerr << "\nSet interfs for PSEUDO inst: " << *MInst;
345           setInterf = true;
346         }
347
348
349       } // if Op2 has a LR
350
351     } // for all other defs in machine instr
352
353   } // for all operands in an instruction
354
355   if( !setInterf && (MInst->getNumOperands() > 2) ) {
356     cerr << "\nInterf not set for any operand in pseudo instr:\n";
357     cerr << *MInst;
358     assert(0 && "Interf not set for pseudo instr with > 2 operands" );
359     
360   }
361
362
363
364
365
366
367
368 //----------------------------------------------------------------------------
369 // This method will add interferences for incoming arguments to a method.
370 //----------------------------------------------------------------------------
371 void PhyRegAlloc::addInterferencesForArgs()
372 {
373                                               // get the InSet of root BB
374   const LiveVarSet *const InSet = LVI->getInSetOfBB( Meth->front() );  
375
376                                               // get the argument list
377   const Method::ArgumentListType& ArgList = Meth->getArgumentList();  
378
379                                               // get an iterator to arg list
380   Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();          
381
382
383   for( ; ArgIt != ArgList.end() ; ++ArgIt) {  // for each argument
384     addInterference( *ArgIt, InSet, false );  // add interferences between 
385                                               // args and LVars at start
386     if( DEBUG_RA > 1) {
387        cout << " - %% adding interference for  argument ";    
388       printValue( (const Value *) *ArgIt); cout  << endl;
389     }
390   }
391 }
392
393
394 //----------------------------------------------------------------------------
395 // This method is called after register allocation is complete to set the
396 // allocated reisters in the machine code. This code will add register numbers
397 // to MachineOperands that contain a Value.
398 //----------------------------------------------------------------------------
399
400 void PhyRegAlloc::updateMachineCode()
401 {
402
403   Method::const_iterator BBI = Meth->begin();  // random iterator for BBs   
404
405   for( ; BBI != Meth->end(); ++BBI) {          // traverse BBs in random order
406
407     // get the iterator for machine instructions
408     MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
409     MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
410
411     // iterate over all the machine instructions in BB
412     for( ; MInstIterator != MIVec.end(); ++MInstIterator) {  
413       
414       MachineInstr *MInst = *MInstIterator; 
415
416       // do not process Phis
417       if( (TM.getInstrInfo()).isPhi( MInst->getOpCode()) )
418         continue;
419
420
421       // if this machine instr is call, insert caller saving code
422
423       if( (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
424         MRI.insertCallerSavingCode(MInst,  *BBI, *this );
425
426
427       // reset the stack offset for temporary variables since we may
428       // need that to spill
429       mcInfo.popAllTempValues(TM);
430       
431       //for(MachineInstr::val_op_const_iterator OpI(MInst);!OpI.done();++OpI) {
432
433
434       // Now replace set the registers for operands in the machine instruction
435
436       for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
437
438         MachineOperand& Op = MInst->getOperand(OpNum);
439
440         if( Op.getOperandType() ==  MachineOperand::MO_VirtualRegister || 
441             Op.getOperandType() ==  MachineOperand::MO_CCRegister) {
442
443           const Value *const Val =  Op.getVRegValue();
444
445           // delete this condition checking later (must assert if Val is null)
446           if( !Val) {
447             if (DEBUG_RA)
448               cout << "Warning: NULL Value found for operand" << endl;
449             continue;
450           }
451           assert( Val && "Value is NULL");   
452
453           LiveRange *const LR = LRI.getLiveRangeForValue(Val);
454
455           if ( !LR ) {
456
457             // nothing to worry if it's a const or a label
458
459             if (DEBUG_RA) {
460               cout << "*NO LR for operand : " << Op ;
461               cout << " [reg:" <<  Op.getAllocatedRegNum() << "]";
462               cout << " in inst:\t" << *MInst << endl;
463             }
464
465             // if register is not allocated, mark register as invalid
466             if( Op.getAllocatedRegNum() == -1)
467               Op.setRegForValue( MRI.getInvalidRegNum()); 
468             
469
470             continue;
471           }
472         
473           unsigned RCID = (LR->getRegClass())->getID();
474
475           if( LR->hasColor() ) {
476             Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
477           }
478           else {
479
480             // LR did NOT receive a color (register). Now, insert spill code
481             // for spilled opeands in this machine instruction
482
483             //assert(0 && "LR must be spilled");
484             insertCode4SpilledLR(LR, MInst, *BBI, OpNum );
485
486           }
487         }
488
489       } // for each operand
490
491
492       // If there are instructions to be added, *before* this machine
493       // instruction, add them now.
494       
495       if( AddedInstrMap[ MInst ] ) {
496
497         deque<MachineInstr *> &IBef = (AddedInstrMap[MInst])->InstrnsBefore;
498
499         if( ! IBef.empty() ) {
500
501           deque<MachineInstr *>::iterator AdIt; 
502
503           for( AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt ) {
504
505             if( DEBUG_RA) {
506               cerr << "For inst " << *MInst;
507               cerr << " PREPENDed instr: " << **AdIt << endl;
508             }
509                     
510             MInstIterator = MIVec.insert( MInstIterator, *AdIt );
511             ++MInstIterator;
512           }
513
514         }
515
516       }
517
518       // If there are instructions to be added *after* this machine
519       // instruction, add them now
520       
521       if( AddedInstrMap[ MInst ] && 
522           ! (AddedInstrMap[ MInst ]->InstrnsAfter).empty() ) {
523
524         // if there are delay slots for this instruction, the instructions
525         // added after it must really go after the delayed instruction(s)
526         // So, we move the InstrAfter of the current instruction to the 
527         // corresponding delayed instruction
528         
529         unsigned delay;
530         if((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){ 
531           move2DelayedInstr(MInst,  *(MInstIterator+delay) );
532
533           if(DEBUG_RA)  cout<< "\nMoved an added instr after the delay slot";
534         }
535        
536         else {
537         
538
539           // Here we can add the "instructions after" to the current
540           // instruction since there are no delay slots for this instruction
541
542           deque<MachineInstr *> &IAft = (AddedInstrMap[MInst])->InstrnsAfter;
543           
544           if( ! IAft.empty() ) {     
545             
546             deque<MachineInstr *>::iterator AdIt; 
547             
548             ++MInstIterator;   // advance to the next instruction
549             
550             for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
551               
552               if(DEBUG_RA) {
553                 cerr << "For inst " << *MInst;
554                 cerr << " APPENDed instr: "  << **AdIt << endl;
555               }       
556
557               MInstIterator = MIVec.insert( MInstIterator, *AdIt );
558               ++MInstIterator;
559             }
560
561             // MInsterator already points to the next instr. Since the
562             // for loop also increments it, decrement it to point to the
563             // instruction added last
564             --MInstIterator;  
565             
566           }
567           
568         }  // if not delay
569         
570       }
571       
572     } // for each machine instruction
573   }
574 }
575
576
577
578 //----------------------------------------------------------------------------
579 // This method inserts spill code for AN operand whose LR was spilled.
580 // This method may be called several times for a single machine instruction
581 // if it contains many spilled operands. Each time it is called, it finds
582 // a register which is not live at that instruction and also which is not
583 // used by other spilled operands of the same instruction. Then it uses
584 // this register temporarily to accomodate the spilled value.
585 //----------------------------------------------------------------------------
586 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR, 
587                                        MachineInstr *MInst,
588                                        const BasicBlock *BB,
589                                        const unsigned OpNum) {
590
591   assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
592          (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
593          "Arg of a call/ret must be handled elsewhere");
594
595   MachineOperand& Op = MInst->getOperand(OpNum);
596   bool isDef =  MInst->operandIsDefined(OpNum);
597   unsigned RegType = MRI.getRegType( LR );
598   int SpillOff = LR->getSpillOffFromFP();
599   RegClass *RC = LR->getRegClass();
600   const LiveVarSet *LVSetBef =  LVI->getLiveVarSetBeforeMInst(MInst, BB);
601
602   /**** NOTE: THIS SHOULD USE THE RIGHT SIZE FOR THE REG BEING PUSHED ****/
603   int TmpOff = 
604     mcInfo.pushTempValue(TM, 8 /* TM.findOptimalStorageSize(LR->getType()) */);
605   
606   MachineInstr *MIBef=NULL,  *AdIMid=NULL, *MIAft=NULL;
607   
608   int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,LVSetBef, MIBef, MIAft);
609   
610   // get the added instructions for this instruciton
611   AddedInstrns *AI = AddedInstrMap[ MInst ];
612   if ( !AI ) { 
613     AI = new AddedInstrns();
614     AddedInstrMap[ MInst ] = AI;
615   }
616
617     
618   if( !isDef ) {
619
620     // for a USE, we have to load the value of LR from stack to a TmpReg
621     // and use the TmpReg as one operand of instruction
622
623     // actual loading instruction
624     AdIMid = MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType);
625
626     if( MIBef )
627       (AI->InstrnsBefore).push_back(MIBef);
628
629     (AI->InstrnsBefore).push_back(AdIMid);
630
631     if( MIAft)
632       (AI->InstrnsAfter).push_front(MIAft);
633     
634     
635   } 
636   else {   // if this is a Def
637
638     // for a DEF, we have to store the value produced by this instruction
639     // on the stack position allocated for this LR
640
641     // actual storing instruction
642     AdIMid = MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType);
643
644     if( MIBef )
645       (AI->InstrnsBefore).push_back(MIBef);
646
647     (AI->InstrnsAfter).push_front(AdIMid);
648
649     if( MIAft)
650       (AI->InstrnsAfter).push_front(MIAft);
651
652   }  // if !DEF
653
654   cerr << "\nFor Inst " << *MInst;
655   cerr << " - SPILLED LR: "; LR->printSet();
656   cerr << "\n - Added Instructions:";
657   if( MIBef ) cerr <<  *MIBef;
658   cerr <<  *AdIMid;
659   if( MIAft ) cerr <<  *MIAft;
660
661   Op.setRegForValue( TmpRegU );    // set the opearnd
662
663
664 }
665
666
667
668
669
670
671 //----------------------------------------------------------------------------
672 // We can use the following method to get a temporary register to be used
673 // BEFORE any given machine instruction. If there is a register available,
674 // this method will simply return that register and set MIBef = MIAft = NULL.
675 // Otherwise, it will return a register and MIAft and MIBef will contain
676 // two instructions used to free up this returned register.
677 // Returned register number is the UNIFIED register number
678 //----------------------------------------------------------------------------
679
680 int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC, 
681                                   const int RegType,
682                                   const MachineInstr *MInst, 
683                                   const LiveVarSet *LVSetBef,
684                                   MachineInstr *MIBef,
685                                   MachineInstr *MIAft) {
686
687   int RegU =  getUnusedUniRegAtMI(RC, MInst, LVSetBef);
688
689
690   if( RegU != -1) {
691     // we found an unused register, so we can simply use it
692     MIBef = MIAft = NULL;
693   }
694   else {
695     // we couldn't find an unused register. Generate code to free up a reg by
696     // saving it on stack and restoring after the instruction
697
698     /**** NOTE: THIS SHOULD USE THE RIGHT SIZE FOR THE REG BEING PUSHED ****/
699     int TmpOff = mcInfo.pushTempValue(TM, /*size*/ 8);
700     
701     RegU = getUniRegNotUsedByThisInst(RC, MInst);
702     MIBef = MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType );
703     MIAft = MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType );
704   }
705
706   return RegU;
707 }
708
709 //----------------------------------------------------------------------------
710 // This method is called to get a new unused register that can be used to
711 // accomodate a spilled value. 
712 // This method may be called several times for a single machine instruction
713 // if it contains many spilled operands. Each time it is called, it finds
714 // a register which is not live at that instruction and also which is not
715 // used by other spilled operands of the same instruction.
716 // Return register number is relative to the register class. NOT
717 // unified number
718 //----------------------------------------------------------------------------
719 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC, 
720                                   const MachineInstr *MInst, 
721                                   const LiveVarSet *LVSetBef) {
722
723   unsigned NumAvailRegs =  RC->getNumOfAvailRegs();
724   
725   bool *IsColorUsedArr = RC->getIsColorUsedArr();
726   
727   for(unsigned i=0; i <  NumAvailRegs; i++)     // Reset array
728       IsColorUsedArr[i] = false;
729       
730   LiveVarSet::const_iterator LIt = LVSetBef->begin();
731
732   // for each live var in live variable set after machine inst
733   for( ; LIt != LVSetBef->end(); ++LIt) {
734
735    //  get the live range corresponding to live var
736     LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );    
737
738     // LR can be null if it is a const since a const 
739     // doesn't have a dominating def - see Assumptions above
740     if( LRofLV )     
741       if( LRofLV->hasColor() ) 
742         IsColorUsedArr[ LRofLV->getColor() ] = true;
743   }
744
745   // It is possible that one operand of this MInst was already spilled
746   // and it received some register temporarily. If that's the case,
747   // it is recorded in machine operand. We must skip such registers.
748
749   setRelRegsUsedByThisInst(RC, MInst);
750
751   unsigned c;                         // find first unused color
752   for( c=0; c < NumAvailRegs; c++)  
753      if( ! IsColorUsedArr[ c ] ) break;
754    
755   if(c < NumAvailRegs) 
756     return  MRI.getUnifiedRegNum(RC->getID(), c);
757   else 
758     return -1;
759
760
761 }
762
763
764 //----------------------------------------------------------------------------
765 // Get any other register in a register class, other than what is used
766 // by operands of a machine instruction. Returns the unified reg number.
767 //----------------------------------------------------------------------------
768 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC, 
769                                          const MachineInstr *MInst) {
770
771   bool *IsColorUsedArr = RC->getIsColorUsedArr();
772   unsigned NumAvailRegs =  RC->getNumOfAvailRegs();
773
774
775   for(unsigned i=0; i < NumAvailRegs ; i++)   // Reset array
776     IsColorUsedArr[i] = false;
777
778   setRelRegsUsedByThisInst(RC, MInst);
779
780   unsigned c;                         // find first unused color
781   for( c=0; c <  RC->getNumOfAvailRegs(); c++)  
782      if( ! IsColorUsedArr[ c ] ) break;
783    
784   if(c < NumAvailRegs) 
785     return  MRI.getUnifiedRegNum(RC->getID(), c);
786   else 
787     assert( 0 && "FATAL: No free register could be found in reg class!!");
788
789 }
790
791
792
793
794
795 //----------------------------------------------------------------------------
796 // This method modifies the IsColorUsedArr of the register class passed to it.
797 // It sets the bits corresponding to the registers used by this machine
798 // instructions. Both explicit and implicit operands are set.
799 //----------------------------------------------------------------------------
800 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC, 
801                                        const MachineInstr *MInst ) {
802
803  bool *IsColorUsedArr = RC->getIsColorUsedArr();
804   
805  for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
806     
807    const MachineOperand& Op = MInst->getOperand(OpNum);
808
809     if( Op.getOperandType() ==  MachineOperand::MO_VirtualRegister || 
810         Op.getOperandType() ==  MachineOperand::MO_CCRegister ) {
811
812       const Value *const Val =  Op.getVRegValue();
813
814       if( Val ) 
815         if( MRI.getRegClassIDOfValue(Val) == RC->getID() ) {   
816           int Reg;
817           if( (Reg=Op.getAllocatedRegNum()) != -1) {
818             IsColorUsedArr[ Reg ] = true;
819           }
820           else {
821             // it is possilbe that this operand still is not marked with
822             // a register but it has a LR and that received a color
823
824             LiveRange *LROfVal =  LRI.getLiveRangeForValue(Val);
825             if( LROfVal) 
826               if( LROfVal->hasColor() )
827                 IsColorUsedArr[ LROfVal->getColor() ] = true;
828           }
829         
830         } // if reg classes are the same
831     }
832     else if (Op.getOperandType() ==  MachineOperand::MO_MachineRegister) {
833       IsColorUsedArr[ Op.getMachineRegNum() ] = true;
834     }
835  }
836  
837  // If there are implicit references, mark them as well
838
839  for(unsigned z=0; z < MInst->getNumImplicitRefs(); z++) {
840
841    LiveRange *const LRofImpRef = 
842      LRI.getLiveRangeForValue( MInst->getImplicitRef(z)  );    
843
844    if( LRofImpRef )     
845      if( LRofImpRef->hasColor() ) 
846        IsColorUsedArr[ LRofImpRef->getColor() ] = true;
847  }
848
849
850
851 }
852
853
854
855
856
857
858
859
860 //----------------------------------------------------------------------------
861 // If there are delay slots for an instruction, the instructions
862 // added after it must really go after the delayed instruction(s).
863 // So, we move the InstrAfter of that instruction to the 
864 // corresponding delayed instruction using the following method.
865
866 //----------------------------------------------------------------------------
867 void PhyRegAlloc:: move2DelayedInstr(const MachineInstr *OrigMI,
868                                      const MachineInstr *DelayedMI) {
869
870
871   // "added after" instructions of the original instr
872   deque<MachineInstr *> &OrigAft = (AddedInstrMap[OrigMI])->InstrnsAfter;
873
874   // "added instructions" of the delayed instr
875   AddedInstrns *DelayAdI = AddedInstrMap[DelayedMI];
876
877   if(! DelayAdI )  {                // create a new "added after" if necessary
878     DelayAdI = new AddedInstrns();
879     AddedInstrMap[DelayedMI] =  DelayAdI;
880   }
881
882   // "added after" instructions of the delayed instr
883   deque<MachineInstr *> &DelayedAft = DelayAdI->InstrnsAfter;
884
885   // go thru all the "added after instructions" of the original instruction
886   // and append them to the "addded after instructions" of the delayed
887   // instructions
888
889   deque<MachineInstr *>::iterator OrigAdIt; 
890             
891   for( OrigAdIt = OrigAft.begin(); OrigAdIt != OrigAft.end() ; ++OrigAdIt ) { 
892     DelayedAft.push_back( *OrigAdIt );
893   }    
894
895   // empty the "added after instructions" of the original instruction
896   OrigAft.clear();
897     
898 }
899
900 //----------------------------------------------------------------------------
901 // This method prints the code with registers after register allocation is
902 // complete.
903 //----------------------------------------------------------------------------
904 void PhyRegAlloc::printMachineCode()
905 {
906
907   cout << endl << ";************** Method ";
908   cout << Meth->getName() << " *****************" << endl;
909
910   Method::const_iterator BBI = Meth->begin();  // random iterator for BBs   
911
912   for( ; BBI != Meth->end(); ++BBI) {          // traverse BBs in random order
913
914     cout << endl ; printLabel( *BBI); cout << ": ";
915
916     // get the iterator for machine instructions
917     MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
918     MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
919
920     // iterate over all the machine instructions in BB
921     for( ; MInstIterator != MIVec.end(); ++MInstIterator) {  
922       
923       MachineInstr *const MInst = *MInstIterator; 
924
925
926       cout << endl << "\t";
927       cout << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
928       
929
930       //for(MachineInstr::val_op_const_iterator OpI(MInst);!OpI.done();++OpI) {
931
932       for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
933
934         MachineOperand& Op = MInst->getOperand(OpNum);
935
936         if( Op.getOperandType() ==  MachineOperand::MO_VirtualRegister || 
937             Op.getOperandType() ==  MachineOperand::MO_CCRegister /*|| 
938             Op.getOperandType() ==  MachineOperand::MO_PCRelativeDisp*/ ) {
939
940           const Value *const Val = Op.getVRegValue () ;
941           // ****this code is temporary till NULL Values are fixed
942           if( ! Val ) {
943             cout << "\t<*NULL*>";
944             continue;
945           }
946
947           // if a label or a constant
948           if( (Val->getValueType() == Value::BasicBlockVal)  ) {
949
950             cout << "\t"; printLabel(   Op.getVRegValue () );
951           }
952           else {
953             // else it must be a register value
954             const int RegNum = Op.getAllocatedRegNum();
955
956             cout << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
957             if (Val->hasName() )
958               cout << "(" << Val->getName() << ")";
959             else 
960               cout << "(" << Val << ")";
961
962             if( Op.opIsDef() )
963               cout << "*";
964
965             const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
966             if( LROfVal )
967               if( LROfVal->hasSpillOffset() )
968                 cout << "$";
969           }
970
971         } 
972         else if(Op.getOperandType() ==  MachineOperand::MO_MachineRegister) {
973           cout << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
974         }
975
976         else 
977           cout << "\t" << Op;      // use dump field
978       }
979
980     
981
982       unsigned NumOfImpRefs =  MInst->getNumImplicitRefs();
983       if(  NumOfImpRefs > 0 ) {
984         
985         cout << "\tImplicit:";
986
987         for(unsigned z=0; z < NumOfImpRefs; z++) {
988           printValue(  MInst->getImplicitRef(z) );
989           cout << "\t";
990         }
991         
992       }
993
994     } // for all machine instructions
995
996
997     cout << endl;
998
999   } // for all BBs
1000
1001   cout << endl;
1002 }
1003
1004
1005 //----------------------------------------------------------------------------
1006 //
1007 //----------------------------------------------------------------------------
1008
1009 void PhyRegAlloc::colorCallRetArgs()
1010 {
1011
1012   CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
1013   CallRetInstrListType::const_iterator It = CallRetInstList.begin();
1014
1015   for( ; It != CallRetInstList.end(); ++It ) {
1016
1017     const MachineInstr *const CRMI = *It;
1018     unsigned OpCode =  CRMI->getOpCode();
1019  
1020     // get the added instructions for this Call/Ret instruciton
1021     AddedInstrns *AI = AddedInstrMap[ CRMI ];
1022     if ( !AI ) { 
1023       AI = new AddedInstrns();
1024       AddedInstrMap[ CRMI ] = AI;
1025     }
1026
1027     // Tmp stack poistions are needed by some calls that have spilled args
1028     // So reset it before we call each such method
1029     mcInfo.popAllTempValues(TM);  
1030     
1031     if( (TM.getInstrInfo()).isCall( OpCode ) )
1032       MRI.colorCallArgs( CRMI, LRI, AI, *this );
1033     
1034     else if (  (TM.getInstrInfo()).isReturn(OpCode) ) 
1035       MRI.colorRetValue( CRMI, LRI, AI );
1036     
1037     else assert( 0 && "Non Call/Ret instrn in CallRetInstrList\n" );
1038
1039   }
1040
1041 }
1042
1043
1044
1045 //----------------------------------------------------------------------------
1046
1047 //----------------------------------------------------------------------------
1048 void PhyRegAlloc::colorIncomingArgs()
1049 {
1050   const BasicBlock *const FirstBB = Meth->front();
1051   const MachineInstr *FirstMI = *((FirstBB->getMachineInstrVec()).begin());
1052   assert( FirstMI && "No machine instruction in entry BB");
1053
1054   AddedInstrns *AI = AddedInstrMap[ FirstMI ];
1055   if ( !AI ) { 
1056     AI = new AddedInstrns();
1057     AddedInstrMap[ FirstMI  ] = AI;
1058   }
1059
1060   MRI.colorMethodArgs(Meth, LRI, AI );
1061 }
1062
1063
1064 //----------------------------------------------------------------------------
1065 // Used to generate a label for a basic block
1066 //----------------------------------------------------------------------------
1067 void PhyRegAlloc::printLabel(const Value *const Val)
1068 {
1069   if( Val->hasName() )
1070     cout  << Val->getName();
1071   else
1072     cout << "Label" <<  Val;
1073 }
1074
1075
1076 //----------------------------------------------------------------------------
1077 // This method calls setSugColorUsable method of each live range. This
1078 // will determine whether the suggested color of LR is  really usable.
1079 // A suggested color is not usable when the suggested color is volatile
1080 // AND when there are call interferences
1081 //----------------------------------------------------------------------------
1082
1083 void PhyRegAlloc::markUnusableSugColors()
1084 {
1085   if(DEBUG_RA ) cout << "\nmarking unusable suggested colors ..." << endl;
1086
1087   // hash map iterator
1088   LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();   
1089   LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();   
1090
1091     for(  ; HMI != HMIEnd ; ++HMI ) {
1092       
1093       if( (*HMI).first ) { 
1094
1095         LiveRange *L = (*HMI).second;      // get the LiveRange
1096
1097         if(L) { 
1098           if( L->hasSuggestedColor() ) {
1099
1100             int RCID = (L->getRegClass())->getID();
1101             if( MRI.isRegVolatile( RCID,  L->getSuggestedColor()) &&
1102                 L->isCallInterference() )
1103               L->setSuggestedColorUsable( false );
1104             else
1105               L->setSuggestedColorUsable( true );
1106           }
1107         } // if L->hasSuggestedColor()
1108       }
1109     } // for all LR's in hash map
1110 }
1111
1112
1113
1114 //----------------------------------------------------------------------------
1115 // The following method will set the stack offsets of the live ranges that
1116 // are decided to be spillled. This must be called just after coloring the
1117 // LRs using the graph coloring algo. For each live range that is spilled,
1118 // this method allocate a new spill position on the stack.
1119 //----------------------------------------------------------------------------
1120
1121 void PhyRegAlloc::allocateStackSpace4SpilledLRs()
1122 {
1123   if(DEBUG_RA ) cout << "\nsetting LR stack offsets ..." << endl;
1124
1125   // hash map iterator
1126   LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();   
1127   LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();   
1128
1129     for(  ; HMI != HMIEnd ; ++HMI ) {
1130       if( (*HMI).first ) { 
1131         LiveRange *L = (*HMI).second;      // get the LiveRange
1132         if(L)
1133           if( ! L->hasColor() ) 
1134   /**** NOTE: THIS SHOULD USE THE RIGHT SIZE FOR THE REG BEING PUSHED ****/
1135             L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy /*L->getType()*/ ));
1136       }
1137     } // for all LR's in hash map
1138 }
1139
1140
1141
1142 //----------------------------------------------------------------------------
1143 // The entry pont to Register Allocation
1144 //----------------------------------------------------------------------------
1145
1146 void PhyRegAlloc::allocateRegisters()
1147 {
1148
1149   // make sure that we put all register classes into the RegClassList 
1150   // before we call constructLiveRanges (now done in the constructor of 
1151   // PhyRegAlloc class).
1152
1153   constructLiveRanges();                // create LR info
1154
1155   if( DEBUG_RA )
1156     LRI.printLiveRanges();
1157   
1158   createIGNodeListsAndIGs();            // create IGNode list and IGs
1159
1160   buildInterferenceGraphs();            // build IGs in all reg classes
1161   
1162   
1163   if( DEBUG_RA ) {
1164     // print all LRs in all reg classes
1165     for( unsigned int rc=0; rc < NumOfRegClasses  ; rc++)  
1166       RegClassList[ rc ]->printIGNodeList(); 
1167     
1168     // print IGs in all register classes
1169     for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)  
1170       RegClassList[ rc ]->printIG();       
1171   }
1172   
1173   LRI.coalesceLRs();                    // coalesce all live ranges
1174   
1175   // coalscing could not get rid of all phi's, add phi elimination
1176   // instructions
1177   // insertPhiEleminateInstrns();
1178
1179   if( DEBUG_RA) {
1180     // print all LRs in all reg classes
1181     for( unsigned int rc=0; rc < NumOfRegClasses  ; rc++)  
1182       RegClassList[ rc ]->printIGNodeList(); 
1183     
1184     // print IGs in all register classes
1185     for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)  
1186       RegClassList[ rc ]->printIG();       
1187   }
1188
1189
1190   // mark un-usable suggested color before graph coloring algorithm.
1191   // When this is done, the graph coloring algo will not reserve
1192   // suggested color unnecessarily - they can be used by another LR
1193   markUnusableSugColors(); 
1194
1195   // color all register classes using the graph coloring algo
1196   for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)  
1197     RegClassList[ rc ]->colorAllRegs();    
1198
1199   // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1200   // a poistion for such spilled LRs
1201   allocateStackSpace4SpilledLRs();
1202
1203   // color incoming args and call args
1204   colorIncomingArgs();
1205   colorCallRetArgs();
1206
1207  
1208   updateMachineCode(); 
1209   if (DEBUG_RA) {
1210     MachineCodeForMethod::get(Meth).dump();
1211     printMachineCode();                   // only for DEBUGGING
1212   }
1213
1214   /*  
1215   printMachineCode();                   // only for DEBUGGING
1216
1217   cout << "\nAllocted for method " <<  Meth->getName();
1218   char ch;
1219   cin >> ch;
1220   */
1221
1222 }
1223
1224
1225