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