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