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