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