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