Fix typo in comment. Take out some random whitespace.
[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 "PhyRegAlloc.h"
9 #include "RegAllocCommon.h"
10 #include "RegClass.h"
11 #include "IGNode.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/CodeGen/InstrSelection.h"
18 #include "llvm/Analysis/LoopInfo.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/TargetFrameInfo.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetRegInfo.h"
23 #include "llvm/Function.h"
24 #include "llvm/Type.h"
25 #include "llvm/iOther.h"
26 #include "Support/STLExtras.h"
27 #include "Support/SetOperations.h"
28 #include "Support/CommandLine.h"
29 #include <math.h>
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         std::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) std::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 FunctionPass *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 initially 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) std::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           std::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) std::cerr << "LRLists Created!\n";
143 }
144
145
146 //----------------------------------------------------------------------------
147 // This method will add all interferences at for a given instruction.
148 // Interference 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       std::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     std::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         std::cerr << "\n\tLR after Call: ";
219         printSet(*LR);
220       }
221       LR->setCallInterference();
222       if (DEBUG_RA >= RA_DEBUG_Interference) {
223         std::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     std::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 which extends
294         // across this call instruction. This information is used by graph
295         // coloring algorithm 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 explicit 
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     std::cerr << "Interference graphs calculated!\n";
341 }
342
343
344
345 //--------------------------------------------------------------------------
346 // Pseudo-instructions will be expanded 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     std::cerr << "\nInterf not set for any operand in pseudo instr:\n";
380     std::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       std::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 registers 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(std::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) std::cerr << "For MInst:\n  " << *OrigMI;
464             std::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) std::cerr << "For MInst:\n  " << *OrigMI;
485             std::cerr << msg << "APPENDed instr:\n  "  << **AdIt << "\n";
486           }
487           InsertAfter(*AdIt, MBB, MII);
488         }
489     }
490 }
491
492 static bool MarkAllocatedRegs(MachineInstr* MInst,
493                               LiveRangeInfo& LRI,
494                               const TargetRegInfo& MRI)
495 {
496   bool instrNeedsSpills = false;
497
498   // First, set the registers for operands in the machine instruction
499   // if a register was successfully allocated.  Do this first because we
500   // will need to know which registers are already used by this instr'n.
501   // 
502   for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
503     {
504       MachineOperand& Op = MInst->getOperand(OpNum);
505       if (Op.getType() ==  MachineOperand::MO_VirtualRegister || 
506           Op.getType() ==  MachineOperand::MO_CCRegister)
507         {
508           const Value *const Val =  Op.getVRegValue();
509           if (const LiveRange* LR = LRI.getLiveRangeForValue(Val)) {
510             // Remember if any operand needs spilling
511             instrNeedsSpills |= LR->isMarkedForSpill();
512
513             // An operand may have a color whether or not it needs spilling
514             if (LR->hasColor())
515               MInst->SetRegForOperand(OpNum,
516                           MRI.getUnifiedRegNum(LR->getRegClass()->getID(),
517                                                LR->getColor()));
518           }
519         }
520     } // for each operand
521
522   return instrNeedsSpills;
523 }
524
525 void PhyRegAlloc::updateInstruction(MachineBasicBlock::iterator& MII,
526                                     MachineBasicBlock &MBB)
527 {
528   MachineInstr* MInst = *MII;
529   unsigned Opcode = MInst->getOpCode();
530
531   // Reset tmp stack positions so they can be reused for each machine instr.
532   MF.getInfo()->popAllTempValues();  
533
534   // Mark the operands for which regs have been allocated.
535   bool instrNeedsSpills = MarkAllocatedRegs(*MII, LRI, MRI);
536
537 #ifndef NDEBUG
538   // Mark that the operands have been updated.  Later,
539   // setRelRegsUsedByThisInst() is called to find registers used by each
540   // MachineInst, and it should not be used for an instruction until
541   // this is done.  This flag just serves as a sanity check.
542   OperandsColoredMap[MInst] = true;
543 #endif
544
545   // Now insert caller-saving code before/after the call.
546   // Do this before inserting spill code since some registers must be
547   // used by save/restore and spill code should not use those registers.
548   //
549   if (TM.getInstrInfo().isCall(Opcode)) {
550     AddedInstrns &AI = AddedInstrMap[MInst];
551     insertCallerSavingCode(AI.InstrnsBefore, AI.InstrnsAfter, MInst,
552                            MBB.getBasicBlock());
553   }
554
555   // Now insert spill code for remaining operands not allocated to
556   // registers.  This must be done even for call return instructions
557   // since those are not handled by the special code above.
558   if (instrNeedsSpills)
559     for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
560       {
561         MachineOperand& Op = MInst->getOperand(OpNum);
562         if (Op.getType() ==  MachineOperand::MO_VirtualRegister || 
563             Op.getType() ==  MachineOperand::MO_CCRegister)
564           {
565             const Value* Val = Op.getVRegValue();
566             if (const LiveRange *LR = LRI.getLiveRangeForValue(Val))
567               if (LR->isMarkedForSpill())
568                 insertCode4SpilledLR(LR, MII, MBB, OpNum);
569           }
570       } // for each operand
571 }
572
573 void PhyRegAlloc::updateMachineCode()
574 {
575   // Insert any instructions needed at method entry
576   MachineBasicBlock::iterator MII = MF.front().begin();
577   PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MF.front(), MII,
578                       "At function entry: \n");
579   assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
580          "InstrsAfter should be unnecessary since we are just inserting at "
581          "the function entry point here.");
582   
583   for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end();
584        BBI != BBE; ++BBI) {
585
586     MachineBasicBlock &MBB = *BBI;
587
588     // Iterate over all machine instructions in BB and mark operands with
589     // their assigned registers or insert spill code, as appropriate. 
590     // Also, fix operands of call/return instructions.
591     for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
592       if (! TM.getInstrInfo().isDummyPhiInstr((*MII)->getOpCode()))
593         updateInstruction(MII, MBB);
594
595     // Now, move code out of delay slots of branches and returns if needed.
596     // (Also, move "after" code from calls to the last delay slot instruction.)
597     // Moving code out of delay slots is needed in 2 situations:
598     // (1) If this is a branch and it needs instructions inserted after it,
599     //     move any existing instructions out of the delay slot so that the
600     //     instructions can go into the delay slot.  This only supports the
601     //     case that #instrsAfter <= #delay slots.
602     // 
603     // (2) If any instruction in the delay slot needs
604     //     instructions inserted, move it out of the delay slot and before the
605     //     branch because putting code before or after it would be VERY BAD!
606     // 
607     // If the annul bit of the branch is set, neither of these is legal!
608     // If so, we need to handle spill differently but annulling is not yet used.
609     //
610     for (MachineBasicBlock::iterator MII = MBB.begin();
611          MII != MBB.end(); ++MII)
612       if (unsigned delaySlots =
613           TM.getInstrInfo().getNumDelaySlots((*MII)->getOpCode()))
614         { 
615           MachineInstr *MInst = *MII, *DelaySlotMI = *(MII+1);
616           
617           // Check the 2 conditions above:
618           // (1) Does a branch need instructions added after it?
619           // (2) O/w does delay slot instr. need instrns before or after?
620           bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
621                            TM.getInstrInfo().isReturn(MInst->getOpCode()));
622           bool cond1 = (isBranch &&
623                         AddedInstrMap.count(MInst) &&
624                         AddedInstrMap[MInst].InstrnsAfter.size() > 0);
625           bool cond2 = (AddedInstrMap.count(DelaySlotMI) &&
626                         (AddedInstrMap[DelaySlotMI].InstrnsBefore.size() > 0 ||
627                          AddedInstrMap[DelaySlotMI].InstrnsAfter.size()  > 0));
628
629           if (cond1 || cond2)
630             {
631               assert((MInst->getOpCodeFlags() & AnnulFlag) == 0 &&
632                      "FIXME: Moving an annulled delay slot instruction!"); 
633               assert(delaySlots==1 &&
634                      "InsertBefore does not yet handle >1 delay slots!");
635               InsertBefore(DelaySlotMI, MBB, MII); // MII pts back to branch
636
637               // In case (1), delete it and don't replace with anything!
638               // Otherwise (i.e., case (2) only) replace it with a NOP.
639               if (cond1) {
640                 DeleteInstruction(MBB, ++MII); // MII now points to next inst.
641                 --MII;                         // reset MII for ++MII of loop
642               }
643               else
644                 SubstituteInPlace(BuildMI(TM.getInstrInfo().getNOPOpCode(),1),
645                                   MBB, MII+1);        // replace with NOP
646
647               if (DEBUG_RA) {
648                 std::cerr << "\nRegAlloc: Moved instr. with added code: "
649                      << *DelaySlotMI
650                      << "           out of delay slots of instr: " << *MInst;
651               }
652             }
653           else
654             // For non-branch instr with delay slots (probably a call), move
655             // InstrAfter to the instr. in the last delay slot.
656             move2DelayedInstr(*MII, *(MII+delaySlots));
657         }
658
659     // Finally iterate over all instructions in BB and insert before/after
660     // 
661     for (MachineBasicBlock::iterator MII=MBB.begin(); MII != MBB.end(); ++MII) {
662       MachineInstr *MInst = *MII; 
663
664       // do not process Phis
665       if (TM.getInstrInfo().isDummyPhiInstr(MInst->getOpCode()))
666         continue;
667
668       // if there are any added instructions...
669       if (AddedInstrMap.count(MInst)) {
670         AddedInstrns &CallAI = AddedInstrMap[MInst];
671
672 #ifndef NDEBUG
673         bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
674                          TM.getInstrInfo().isReturn(MInst->getOpCode()));
675         assert((!isBranch ||
676                 AddedInstrMap[MInst].InstrnsAfter.size() <=
677                 TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) &&
678                "Cannot put more than #delaySlots instrns after "
679                "branch or return! Need to handle temps differently.");
680 #endif
681
682 #ifndef NDEBUG
683         // Temporary sanity checking code to detect whether the same machine
684         // instruction is ever inserted twice before/after a call.
685         // I suspect this is happening but am not sure. --Vikram, 7/1/03.
686         // 
687         std::set<const MachineInstr*> instrsSeen;
688         for (int i = 0, N = CallAI.InstrnsBefore.size(); i < N; ++i) {
689           assert(instrsSeen.count(CallAI.InstrnsBefore[i]) == 0 &&
690                  "Duplicate machine instruction in InstrnsBefore!");
691           instrsSeen.insert(CallAI.InstrnsBefore[i]);
692         } 
693         for (int i = 0, N = CallAI.InstrnsAfter.size(); i < N; ++i) {
694           assert(instrsSeen.count(CallAI.InstrnsAfter[i]) == 0 &&
695                  "Duplicate machine instruction in InstrnsBefore/After!");
696           instrsSeen.insert(CallAI.InstrnsAfter[i]);
697         } 
698 #endif
699
700         // Now add the instructions before/after this MI.
701         // We do this here to ensure that spill for an instruction is inserted
702         // as close as possible to an instruction (see above insertCode4Spill)
703         //      
704         if (! CallAI.InstrnsBefore.empty())
705           PrependInstructions(CallAI.InstrnsBefore, MBB, MII,"");
706         
707         if (! CallAI.InstrnsAfter.empty())
708           AppendInstructions(CallAI.InstrnsAfter, MBB, MII,"");
709
710       } // if there are any added instructions
711
712     } // for each machine instruction
713
714   }
715 }
716
717
718
719 //----------------------------------------------------------------------------
720 // This method inserts spill code for AN operand whose LR was spilled.
721 // This method may be called several times for a single machine instruction
722 // if it contains many spilled operands. Each time it is called, it finds
723 // a register which is not live at that instruction and also which is not
724 // used by other spilled operands of the same instruction. Then it uses
725 // this register temporarily to accommodate the spilled value.
726 //----------------------------------------------------------------------------
727
728 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR, 
729                                        MachineBasicBlock::iterator& MII,
730                                        MachineBasicBlock &MBB,
731                                        const unsigned OpNum) {
732
733   MachineInstr *MInst = *MII;
734   const BasicBlock *BB = MBB.getBasicBlock();
735
736   assert((! TM.getInstrInfo().isCall(MInst->getOpCode()) || OpNum == 0) &&
737          "Outgoing arg of a call must be handled elsewhere (func arg ok)");
738   assert(! TM.getInstrInfo().isReturn(MInst->getOpCode()) &&
739          "Return value of a ret must be handled elsewhere");
740
741   MachineOperand& Op = MInst->getOperand(OpNum);
742   bool isDef =  Op.opIsDefOnly();
743   bool isDefAndUse = Op.opIsDefAndUse();
744   unsigned RegType = MRI.getRegTypeForLR(LR);
745   int SpillOff = LR->getSpillOffFromFP();
746   RegClass *RC = LR->getRegClass();
747
748   // Get the live-variable set to find registers free before this instr.
749   const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
750
751 #ifndef NDEBUG
752   // If this instr. is in the delay slot of a branch or return, we need to
753   // include all live variables before that branch or return -- we don't want to
754   // trample those!  Verify that the set is included in the LV set before MInst.
755   // 
756   if (MII != MBB.begin()) {
757     MachineInstr *PredMI = *(MII-1);
758     if (unsigned DS = TM.getInstrInfo().getNumDelaySlots(PredMI->getOpCode()))
759       assert(set_difference(LVI->getLiveVarSetBeforeMInst(PredMI), LVSetBef)
760              .empty() && "Live-var set before branch should be included in "
761              "live-var set of each delay slot instruction!");
762   }
763 #endif
764
765   MF.getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType) );
766   
767   std::vector<MachineInstr*> MIBef, MIAft;
768   std::vector<MachineInstr*> AdIMid;
769   
770   // Choose a register to hold the spilled value, if one was not preallocated.
771   // This may insert code before and after MInst to free up the value.  If so,
772   // this code should be first/last in the spill sequence before/after MInst.
773   int TmpRegU=(LR->hasColor()
774                ? MRI.getUnifiedRegNum(LR->getRegClass()->getID(),LR->getColor())
775                : getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef,MIAft));
776   
777   // Set the operand first so that it this register does not get used
778   // as a scratch register for later calls to getUsableUniRegAtMI below
779   MInst->SetRegForOperand(OpNum, TmpRegU);
780   
781   // get the added instructions for this instruction
782   AddedInstrns &AI = AddedInstrMap[MInst];
783
784   // We may need a scratch register to copy the spilled value to/from memory.
785   // This may itself have to insert code to free up a scratch register.  
786   // Any such code should go before (after) the spill code for a load (store).
787   // The scratch reg is not marked as used because it is only used
788   // for the copy and not used across MInst.
789   int scratchRegType = -1;
790   int scratchReg = -1;
791   if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
792     {
793       scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
794                                        MInst, MIBef, MIAft);
795       assert(scratchReg != MRI.getInvalidRegNum());
796     }
797   
798   if (!isDef || isDefAndUse) {
799     // for a USE, we have to load the value of LR from stack to a TmpReg
800     // and use the TmpReg as one operand of instruction
801     
802     // actual loading instruction(s)
803     MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU,
804                     RegType, scratchReg);
805     
806     // the actual load should be after the instructions to free up TmpRegU
807     MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
808     AdIMid.clear();
809   }
810   
811   if (isDef || isDefAndUse) {   // if this is a Def
812     // for a DEF, we have to store the value produced by this instruction
813     // on the stack position allocated for this LR
814     
815     // actual storing instruction(s)
816     MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff,
817                     RegType, scratchReg);
818     
819     MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
820   }  // if !DEF
821   
822   // Finally, insert the entire spill code sequences before/after MInst
823   AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
824   AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
825   
826   if (DEBUG_RA) {
827     std::cerr << "\nFor Inst:\n  " << *MInst;
828     std::cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
829     std::cerr << "; added Instructions:";
830     for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
831     for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
832   }
833 }
834
835
836
837 //----------------------------------------------------------------------------
838 // This method inserts caller saving/restoring instructions before/after
839 // a call machine instruction. The caller saving/restoring instructions are
840 // inserted like:
841 //    ** caller saving instructions
842 //    other instructions inserted for the call by ColorCallArg
843 //    CALL instruction
844 //    other instructions inserted for the call ColorCallArg
845 //    ** caller restoring instructions
846 //----------------------------------------------------------------------------
847
848 void
849 PhyRegAlloc::insertCallerSavingCode(std::vector<MachineInstr*> &instrnsBefore,
850                                     std::vector<MachineInstr*> &instrnsAfter,
851                                     MachineInstr *CallMI, 
852                                     const BasicBlock *BB)
853 {
854   assert(TM.getInstrInfo().isCall(CallMI->getOpCode()));
855   
856   // has set to record which registers were saved/restored
857   //
858   hash_set<unsigned> PushedRegSet;
859
860   CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
861   
862   // if the call is to a instrumentation function, do not insert save and
863   // restore instructions the instrumentation function takes care of save
864   // restore for volatile regs.
865   //
866   // FIXME: this should be made general, not specific to the reoptimizer!
867   //
868   const Function *Callee = argDesc->getCallInst()->getCalledFunction();
869   bool isLLVMFirstTrigger = Callee && Callee->getName() == "llvm_first_trigger";
870
871   // Now check if the call has a return value (using argDesc) and if so,
872   // find the LR of the TmpInstruction representing the return value register.
873   // (using the last or second-last *implicit operand* of the call MI).
874   // Insert it to to the PushedRegSet since we must not save that register
875   // and restore it after the call.
876   // We do this because, we look at the LV set *after* the instruction
877   // to determine, which LRs must be saved across calls. The return value
878   // of the call is live in this set - but we must not save/restore it.
879   // 
880   if (const Value *origRetVal = argDesc->getReturnValue()) {
881     unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
882                              (argDesc->getIndirectFuncPtr()? 1 : 2));
883     const TmpInstruction* tmpRetVal =
884       cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
885     assert(tmpRetVal->getOperand(0) == origRetVal &&
886            tmpRetVal->getType() == origRetVal->getType() &&
887            "Wrong implicit ref?");
888     LiveRange *RetValLR = LRI.getLiveRangeForValue(tmpRetVal);
889     assert(RetValLR && "No LR for RetValue of call");
890
891     if (! RetValLR->isMarkedForSpill())
892       PushedRegSet.insert(MRI.getUnifiedRegNum(RetValLR->getRegClassID(),
893                                                RetValLR->getColor()));
894   }
895
896   const ValueSet &LVSetAft =  LVI->getLiveVarSetAfterMInst(CallMI, BB);
897   ValueSet::const_iterator LIt = LVSetAft.begin();
898
899   // for each live var in live variable set after machine inst
900   for( ; LIt != LVSetAft.end(); ++LIt) {
901
902    //  get the live range corresponding to live var
903     LiveRange *const LR = LRI.getLiveRangeForValue(*LIt);    
904
905     // LR can be null if it is a const since a const 
906     // doesn't have a dominating def - see Assumptions above
907     if( LR )   {  
908       
909       if(! LR->isMarkedForSpill()) {
910
911         assert(LR->hasColor() && "LR is neither spilled nor colored?");
912         unsigned RCID = LR->getRegClassID();
913         unsigned Color = LR->getColor();
914
915         if (MRI.isRegVolatile(RCID, Color) ) {
916
917           //if the function is special LLVM function,
918           //And the register is not modified by call, don't save and restore
919           if (isLLVMFirstTrigger && !MRI.modifiedByCall(RCID, Color))
920             continue;
921
922           // if the value is in both LV sets (i.e., live before and after 
923           // the call machine instruction)
924           
925           unsigned Reg = MRI.getUnifiedRegNum(RCID, Color);
926           
927           if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
928             
929             // if we haven't already pushed that register
930
931             unsigned RegType = MRI.getRegTypeForLR(LR);
932
933             // Now get two instructions - to push on stack and pop from stack
934             // and add them to InstrnsBefore and InstrnsAfter of the
935             // call instruction
936             // 
937             int StackOff =
938               MF.getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
939             
940             //---- Insert code for pushing the reg on stack ----------
941             
942             std::vector<MachineInstr*> AdIBef, AdIAft;
943             
944             // We may need a scratch register to copy the saved value
945             // to/from memory.  This may itself have to insert code to
946             // free up a scratch register.  Any such code should go before
947             // the save code.  The scratch register, if any, is by default
948             // temporary and not "used" by the instruction unless the
949             // copy code itself decides to keep the value in the scratch reg.
950             int scratchRegType = -1;
951             int scratchReg = -1;
952             if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
953               { // Find a register not live in the LVSet before CallMI
954                 const ValueSet &LVSetBef =
955                   LVI->getLiveVarSetBeforeMInst(CallMI, BB);
956                 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
957                                                  CallMI, AdIBef, AdIAft);
958                 assert(scratchReg != MRI.getInvalidRegNum());
959               }
960             
961             if (AdIBef.size() > 0)
962               instrnsBefore.insert(instrnsBefore.end(),
963                                    AdIBef.begin(), AdIBef.end());
964             
965             MRI.cpReg2MemMI(instrnsBefore, Reg, MRI.getFramePointer(),
966                             StackOff, RegType, scratchReg);
967             
968             if (AdIAft.size() > 0)
969               instrnsBefore.insert(instrnsBefore.end(),
970                                    AdIAft.begin(), AdIAft.end());
971             
972             //---- Insert code for popping the reg from the stack ----------
973             AdIBef.clear();
974             AdIAft.clear();
975             
976             // We may need a scratch register to copy the saved value
977             // from memory.  This may itself have to insert code to
978             // free up a scratch register.  Any such code should go
979             // after the save code.  As above, scratch is not marked "used".
980             // 
981             scratchRegType = -1;
982             scratchReg = -1;
983             if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
984               { // Find a register not live in the LVSet after CallMI
985                 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetAft,
986                                                  CallMI, AdIBef, AdIAft);
987                 assert(scratchReg != MRI.getInvalidRegNum());
988               }
989             
990             if (AdIBef.size() > 0)
991               instrnsAfter.insert(instrnsAfter.end(),
992                                   AdIBef.begin(), AdIBef.end());
993             
994             MRI.cpMem2RegMI(instrnsAfter, MRI.getFramePointer(), StackOff,
995                             Reg, RegType, scratchReg);
996             
997             if (AdIAft.size() > 0)
998               instrnsAfter.insert(instrnsAfter.end(),
999                                   AdIAft.begin(), AdIAft.end());
1000             
1001             PushedRegSet.insert(Reg);
1002             
1003             if(DEBUG_RA) {
1004               std::cerr << "\nFor call inst:" << *CallMI;
1005               std::cerr << " -inserted caller saving instrs: Before:\n\t ";
1006               for_each(instrnsBefore.begin(), instrnsBefore.end(),
1007                        std::mem_fun(&MachineInstr::dump));
1008               std::cerr << " -and After:\n\t ";
1009               for_each(instrnsAfter.begin(), instrnsAfter.end(),
1010                        std::mem_fun(&MachineInstr::dump));
1011             }       
1012           } // if not already pushed
1013
1014         } // if LR has a volatile color
1015         
1016       } // if LR has color
1017
1018     } // if there is a LR for Var
1019     
1020   } // for each value in the LV set after instruction
1021 }
1022
1023
1024 //----------------------------------------------------------------------------
1025 // We can use the following method to get a temporary register to be used
1026 // BEFORE any given machine instruction. If there is a register available,
1027 // this method will simply return that register and set MIBef = MIAft = NULL.
1028 // Otherwise, it will return a register and MIAft and MIBef will contain
1029 // two instructions used to free up this returned register.
1030 // Returned register number is the UNIFIED register number
1031 //----------------------------------------------------------------------------
1032
1033 int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
1034                                      const ValueSet *LVSetBef,
1035                                      MachineInstr *MInst, 
1036                                      std::vector<MachineInstr*>& MIBef,
1037                                      std::vector<MachineInstr*>& MIAft) {
1038   
1039   RegClass* RC = getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
1040   
1041   int RegU =  getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
1042   
1043   if (RegU == -1) {
1044     // we couldn't find an unused register. Generate code to free up a reg by
1045     // saving it on stack and restoring after the instruction
1046     
1047     int TmpOff = MF.getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
1048     
1049     RegU = getUniRegNotUsedByThisInst(RC, RegType, MInst);
1050     
1051     // Check if we need a scratch register to copy this register to memory.
1052     int scratchRegType = -1;
1053     if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
1054       {
1055         int scratchReg = getUsableUniRegAtMI(scratchRegType, LVSetBef,
1056                                              MInst, MIBef, MIAft);
1057         assert(scratchReg != MRI.getInvalidRegNum());
1058         
1059         // We may as well hold the value in the scratch register instead
1060         // of copying it to memory and back.  But we have to mark the
1061         // register as used by this instruction, so it does not get used
1062         // as a scratch reg. by another operand or anyone else.
1063         ScratchRegsUsed.insert(std::make_pair(MInst, scratchReg));
1064         MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
1065         MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
1066       }
1067     else
1068       { // the register can be copied directly to/from memory so do it.
1069         MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
1070         MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
1071       }
1072   }
1073   
1074   return RegU;
1075 }
1076
1077
1078 //----------------------------------------------------------------------------
1079 // This method is called to get a new unused register that can be used
1080 // to accommodate a temporary value.  This method may be called several times
1081 // for a single machine instruction.  Each time it is called, it finds a
1082 // register which is not live at that instruction and also which is not used
1083 // by other spilled operands of the same instruction.  Return register number
1084 // is relative to the register class, NOT the unified number.
1085 //----------------------------------------------------------------------------
1086
1087 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC, 
1088                                      const int RegType,
1089                                      const MachineInstr *MInst,
1090                                      const ValueSet* LVSetBef) {
1091   
1092   RC->clearColorsUsed();     // Reset array
1093
1094   if (LVSetBef == NULL) {
1095       LVSetBef = &LVI->getLiveVarSetBeforeMInst(MInst);
1096       assert(LVSetBef != NULL && "Unable to get live-var set before MInst?");
1097   }
1098
1099   ValueSet::const_iterator LIt = LVSetBef->begin();
1100
1101   // for each live var in live variable set after machine inst
1102   for ( ; LIt != LVSetBef->end(); ++LIt) {
1103
1104    //  get the live range corresponding to live var, and its RegClass
1105     LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );    
1106
1107     // LR can be null if it is a const since a const 
1108     // doesn't have a dominating def - see Assumptions above
1109     if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor())
1110       RC->markColorsUsed(LRofLV->getColor(),
1111                          MRI.getRegTypeForLR(LRofLV), RegType);
1112   }
1113
1114   // It is possible that one operand of this MInst was already spilled
1115   // and it received some register temporarily. If that's the case,
1116   // it is recorded in machine operand. We must skip such registers.
1117   // 
1118   setRelRegsUsedByThisInst(RC, RegType, MInst);
1119
1120   int unusedReg = RC->getUnusedColor(RegType);   // find first unused color
1121   if (unusedReg >= 0)
1122     return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
1123
1124   return -1;
1125 }
1126
1127
1128 //----------------------------------------------------------------------------
1129 // Get any other register in a register class, other than what is used
1130 // by operands of a machine instruction. Returns the unified reg number.
1131 //----------------------------------------------------------------------------
1132 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC, 
1133                                             const int RegType,
1134                                             const MachineInstr *MInst) {
1135   RC->clearColorsUsed();
1136
1137   setRelRegsUsedByThisInst(RC, RegType, MInst);
1138
1139   // find the first unused color
1140   int unusedReg = RC->getUnusedColor(RegType);
1141   assert(unusedReg >= 0 &&
1142          "FATAL: No free register could be found in reg class!!");
1143
1144   return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
1145 }
1146
1147
1148 //----------------------------------------------------------------------------
1149 // This method modifies the IsColorUsedArr of the register class passed to it.
1150 // It sets the bits corresponding to the registers used by this machine
1151 // instructions. Both explicit and implicit operands are set.
1152 //----------------------------------------------------------------------------
1153
1154 static void markRegisterUsed(int RegNo, RegClass *RC, int RegType,
1155                              const TargetRegInfo &TRI) {
1156   unsigned classId = 0;
1157   int classRegNum = TRI.getClassRegNum(RegNo, classId);
1158   if (RC->getID() == classId)
1159     RC->markColorsUsed(classRegNum, RegType, RegType);
1160 }
1161
1162 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC, int RegType,
1163                                            const MachineInstr *MI)
1164 {
1165   assert(OperandsColoredMap[MI] == true &&
1166          "Illegal to call setRelRegsUsedByThisInst() until colored operands "
1167          "are marked for an instruction.");
1168
1169   // Add the registers already marked as used by the instruction.
1170   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
1171     if (MI->getOperand(i).hasAllocatedReg())
1172       markRegisterUsed(MI->getOperand(i).getAllocatedRegNum(), RC, RegType,MRI);
1173
1174   for (unsigned i = 0, e = MI->getNumImplicitRefs(); i != e; ++i)
1175     if (MI->getImplicitOp(i).hasAllocatedReg())
1176       markRegisterUsed(MI->getImplicitOp(i).getAllocatedRegNum(), RC,
1177                        RegType,MRI);
1178
1179   // Add all of the scratch registers that are used to save values across the
1180   // instruction (e.g., for saving state register values).
1181   std::pair<ScratchRegsUsedTy::iterator, ScratchRegsUsedTy::iterator>
1182     IR = ScratchRegsUsed.equal_range(MI);
1183   for (ScratchRegsUsedTy::iterator I = IR.first; I != IR.second; ++I)
1184     markRegisterUsed(I->second, RC, RegType, MRI);
1185
1186   // If there are implicit references, mark their allocated regs as well
1187   // 
1188   for (unsigned z=0; z < MI->getNumImplicitRefs(); z++)
1189     if (const LiveRange*
1190         LRofImpRef = LRI.getLiveRangeForValue(MI->getImplicitRef(z)))    
1191       if (LRofImpRef->hasColor())
1192         // this implicit reference is in a LR that received a color
1193         RC->markColorsUsed(LRofImpRef->getColor(),
1194                            MRI.getRegTypeForLR(LRofImpRef), RegType);
1195 }
1196
1197
1198 //----------------------------------------------------------------------------
1199 // If there are delay slots for an instruction, the instructions
1200 // added after it must really go after the delayed instruction(s).
1201 // So, we move the InstrAfter of that instruction to the 
1202 // corresponding delayed instruction using the following method.
1203 //----------------------------------------------------------------------------
1204
1205 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
1206                                     const MachineInstr *DelayedMI)
1207 {
1208   // "added after" instructions of the original instr
1209   std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
1210
1211   if (DEBUG_RA && OrigAft.size() > 0) {
1212     std::cerr << "\nRegAlloc: Moved InstrnsAfter for: " << *OrigMI;
1213     std::cerr << "         to last delay slot instrn: " << *DelayedMI;
1214   }
1215
1216   // "added after" instructions of the delayed instr
1217   std::vector<MachineInstr *> &DelayedAft=AddedInstrMap[DelayedMI].InstrnsAfter;
1218
1219   // go thru all the "added after instructions" of the original instruction
1220   // and append them to the "added after instructions" of the delayed
1221   // instructions
1222   DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
1223
1224   // empty the "added after instructions" of the original instruction
1225   OrigAft.clear();
1226 }
1227
1228 //----------------------------------------------------------------------------
1229 // This method prints the code with registers after register allocation is
1230 // complete.
1231 //----------------------------------------------------------------------------
1232 void PhyRegAlloc::printMachineCode()
1233 {
1234
1235   std::cerr << "\n;************** Function " << Fn->getName()
1236        << " *****************\n";
1237
1238   for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end();
1239        BBI != BBE; ++BBI) {
1240     std::cerr << "\n"; printLabel(BBI->getBasicBlock()); std::cerr << ": ";
1241
1242     // get the iterator for machine instructions
1243     MachineBasicBlock& MBB = *BBI;
1244     MachineBasicBlock::iterator MII = MBB.begin();
1245
1246     // iterate over all the machine instructions in BB
1247     for ( ; MII != MBB.end(); ++MII) {  
1248       MachineInstr *MInst = *MII; 
1249
1250       std::cerr << "\n\t";
1251       std::cerr << TM.getInstrInfo().getName(MInst->getOpCode());
1252
1253       for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
1254         MachineOperand& Op = MInst->getOperand(OpNum);
1255
1256         if (Op.getType() ==  MachineOperand::MO_VirtualRegister || 
1257             Op.getType() ==  MachineOperand::MO_CCRegister /*|| 
1258             Op.getType() ==  MachineOperand::MO_PCRelativeDisp*/ ) {
1259
1260           const Value *const Val = Op.getVRegValue () ;
1261           // ****this code is temporary till NULL Values are fixed
1262           if (! Val ) {
1263             std::cerr << "\t<*NULL*>";
1264             continue;
1265           }
1266
1267           // if a label or a constant
1268           if (isa<BasicBlock>(Val)) {
1269             std::cerr << "\t"; printLabel(      Op.getVRegValue () );
1270           } else {
1271             // else it must be a register value
1272             const int RegNum = Op.getAllocatedRegNum();
1273
1274             std::cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
1275             if (Val->hasName() )
1276               std::cerr << "(" << Val->getName() << ")";
1277             else 
1278               std::cerr << "(" << Val << ")";
1279
1280             if (Op.opIsDefOnly() || Op.opIsDefAndUse())
1281               std::cerr << "*";
1282
1283             const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
1284             if (LROfVal )
1285               if (LROfVal->hasSpillOffset() )
1286                 std::cerr << "$";
1287           }
1288
1289         } 
1290         else if (Op.getType() ==  MachineOperand::MO_MachineRegister) {
1291           std::cerr << "\t%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1292         }
1293
1294         else 
1295           std::cerr << "\t" << Op;      // use dump field
1296       }
1297
1298     
1299
1300       unsigned NumOfImpRefs =  MInst->getNumImplicitRefs();
1301       if (NumOfImpRefs > 0) {
1302         std::cerr << "\tImplicit:";
1303
1304         for (unsigned z=0; z < NumOfImpRefs; z++)
1305           std::cerr << RAV(MInst->getImplicitRef(z)) << "\t";
1306       }
1307
1308     } // for all machine instructions
1309
1310     std::cerr << "\n";
1311
1312   } // for all BBs
1313
1314   std::cerr << "\n";
1315 }
1316
1317
1318 //----------------------------------------------------------------------------
1319
1320 //----------------------------------------------------------------------------
1321 void PhyRegAlloc::colorIncomingArgs()
1322 {
1323   MRI.colorMethodArgs(Fn, LRI, AddedInstrAtEntry.InstrnsBefore,
1324                       AddedInstrAtEntry.InstrnsAfter);
1325 }
1326
1327
1328 //----------------------------------------------------------------------------
1329 // Used to generate a label for a basic block
1330 //----------------------------------------------------------------------------
1331 void PhyRegAlloc::printLabel(const Value *Val) {
1332   if (Val->hasName())
1333     std::cerr  << Val->getName();
1334   else
1335     std::cerr << "Label" << Val;
1336 }
1337
1338
1339 //----------------------------------------------------------------------------
1340 // This method calls setSugColorUsable method of each live range. This
1341 // will determine whether the suggested color of LR is  really usable.
1342 // A suggested color is not usable when the suggested color is volatile
1343 // AND when there are call interferences
1344 //----------------------------------------------------------------------------
1345
1346 void PhyRegAlloc::markUnusableSugColors()
1347 {
1348   // hash map iterator
1349   LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();   
1350   LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();   
1351
1352     for (; HMI != HMIEnd ; ++HMI ) {
1353       if (HMI->first) { 
1354         LiveRange *L = HMI->second;      // get the LiveRange
1355         if (L) { 
1356           if (L->hasSuggestedColor()) {
1357             int RCID = L->getRegClass()->getID();
1358             if (MRI.isRegVolatile( RCID,  L->getSuggestedColor()) &&
1359                 L->isCallInterference() )
1360               L->setSuggestedColorUsable( false );
1361             else
1362               L->setSuggestedColorUsable( true );
1363           }
1364         } // if L->hasSuggestedColor()
1365       }
1366     } // for all LR's in hash map
1367 }
1368
1369
1370
1371 //----------------------------------------------------------------------------
1372 // The following method will set the stack offsets of the live ranges that
1373 // are decided to be spilled. This must be called just after coloring the
1374 // LRs using the graph coloring algo. For each live range that is spilled,
1375 // this method allocate a new spill position on the stack.
1376 //----------------------------------------------------------------------------
1377
1378 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1379   if (DEBUG_RA) std::cerr << "\nSetting LR stack offsets for spills...\n";
1380
1381   LiveRangeMapType::const_iterator HMI    = LRI.getLiveRangeMap()->begin();   
1382   LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();   
1383
1384   for ( ; HMI != HMIEnd ; ++HMI) {
1385     if (HMI->first && HMI->second) {
1386       LiveRange *L = HMI->second;       // get the LiveRange
1387       if (L->isMarkedForSpill()) {      // NOTE: allocating size of long Type **
1388         int stackOffset = MF.getInfo()->allocateSpilledValue(Type::LongTy);
1389         L->setSpillOffFromFP(stackOffset);
1390         if (DEBUG_RA)
1391           std::cerr << "  LR# " << L->getUserIGNode()->getIndex()
1392                << ": stack-offset = " << stackOffset << "\n";
1393       }
1394     }
1395   } // for all LR's in hash map
1396 }
1397
1398
1399 //----------------------------------------------------------------------------
1400 // The entry point to Register Allocation
1401 //----------------------------------------------------------------------------
1402
1403 void PhyRegAlloc::allocateRegisters()
1404 {
1405   // make sure that we put all register classes into the RegClassList 
1406   // before we call constructLiveRanges (now done in the constructor of 
1407   // PhyRegAlloc class).
1408   //
1409   LRI.constructLiveRanges();            // create LR info
1410   if (DEBUG_RA >= RA_DEBUG_LiveRanges)
1411     LRI.printLiveRanges();
1412   
1413   createIGNodeListsAndIGs();            // create IGNode list and IGs
1414
1415   buildInterferenceGraphs();            // build IGs in all reg classes
1416   
1417   if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1418     // print all LRs in all reg classes
1419     for ( unsigned rc=0; rc < NumOfRegClasses  ; rc++)  
1420       RegClassList[rc]->printIGNodeList(); 
1421     
1422     // print IGs in all register classes
1423     for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)  
1424       RegClassList[rc]->printIG();       
1425   }
1426
1427   LRI.coalesceLRs();                    // coalesce all live ranges
1428
1429   if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1430     // print all LRs in all reg classes
1431     for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1432       RegClassList[rc]->printIGNodeList();
1433     
1434     // print IGs in all register classes
1435     for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1436       RegClassList[rc]->printIG();
1437   }
1438
1439
1440   // mark un-usable suggested color before graph coloring algorithm.
1441   // When this is done, the graph coloring algo will not reserve
1442   // suggested color unnecessarily - they can be used by another LR
1443   //
1444   markUnusableSugColors(); 
1445
1446   // color all register classes using the graph coloring algo
1447   for (unsigned rc=0; rc < NumOfRegClasses ; rc++)  
1448     RegClassList[rc]->colorAllRegs();    
1449
1450   // After graph coloring, if some LRs did not receive a color (i.e, spilled)
1451   // a position for such spilled LRs
1452   //
1453   allocateStackSpace4SpilledLRs();
1454
1455   // Reset the temp. area on the stack before use by the first instruction.
1456   // This will also happen after updating each instruction.
1457   MF.getInfo()->popAllTempValues();
1458
1459   // color incoming args - if the correct color was not received
1460   // insert code to copy to the correct register
1461   //
1462   colorIncomingArgs();
1463
1464   // Now update the machine code with register names and add any 
1465   // additional code inserted by the register allocator to the instruction
1466   // stream
1467   //
1468   updateMachineCode(); 
1469
1470   if (DEBUG_RA) {
1471     std::cerr << "\n**** Machine Code After Register Allocation:\n\n";
1472     MF.dump();
1473   }
1474 }
1475
1476
1477