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