2 //***************************************************************************
7 // Register allocation for LLVM.
10 // 9/10/01 - Ruchira Sasanka - created.
11 //**************************************************************************/
13 #include "llvm/CodeGen/RegisterAllocation.h"
14 #include "llvm/CodeGen/PhyRegAlloc.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "llvm/CodeGen/MachineCodeForMethod.h"
17 #include "llvm/Target/TargetMachine.h"
18 #include "llvm/Target/MachineFrameInfo.h"
24 // ***TODO: There are several places we add instructions. Validate the order
25 // of adding these instructions.
27 cl::Enum<RegAllocDebugLevel_t> DEBUG_RA("dregalloc", cl::NoFlags,
28 "enable register allocation debugging information",
29 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
30 clEnumValN(RA_DEBUG_Normal , "y", "enable debug output"),
31 clEnumValN(RA_DEBUG_Verbose, "v", "enable extra debug output"), 0);
34 bool RegisterAllocation::runOnMethod(Method *M) {
36 cerr << "\n******************** Method "<< M->getName()
37 << " ********************\n";
39 MethodLiveVarInfo LVI(M ); // Analyze live varaibles
42 PhyRegAlloc PRA(M, Target, &LVI); // allocate registers
43 PRA.allocateRegisters();
45 if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
50 //----------------------------------------------------------------------------
51 // Constructor: Init local composite objects and create register classes.
52 //----------------------------------------------------------------------------
53 PhyRegAlloc::PhyRegAlloc(Method *M,
54 const TargetMachine& tm,
55 MethodLiveVarInfo *const Lvi)
57 mcInfo(MachineCodeForMethod::get(M)),
58 LVI(Lvi), LRI(M, tm, RegClassList),
59 MRI( tm.getRegInfo() ),
60 NumOfRegClasses(MRI.getNumOfRegClasses()),
63 // create each RegisterClass and put in RegClassList
65 for(unsigned int rc=0; rc < NumOfRegClasses; rc++)
66 RegClassList.push_back( new RegClass(M, MRI.getMachineRegClass(rc),
71 //----------------------------------------------------------------------------
72 // Destructor: Deletes register classes
73 //----------------------------------------------------------------------------
74 PhyRegAlloc::~PhyRegAlloc() {
75 for( unsigned int rc=0; rc < NumOfRegClasses; rc++)
76 delete RegClassList[rc];
79 //----------------------------------------------------------------------------
80 // This method initally creates interference graphs (one in each reg class)
81 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
82 //----------------------------------------------------------------------------
83 void PhyRegAlloc::createIGNodeListsAndIGs() {
84 if (DEBUG_RA) cerr << "Creating LR lists ...\n";
87 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
90 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
92 for (; HMI != HMIEnd ; ++HMI ) {
94 LiveRange *L = HMI->second; // get the LiveRange
97 cerr << "\n*?!?Warning: Null liver range found for: ";
98 printValue(HMI->first); cerr << "\n";
102 // if the Value * is not null, and LR
103 // is not yet written to the IGNodeList
104 if( !(L->getUserIGNode()) ) {
105 RegClass *const RC = // RegClass of first value in the LR
106 RegClassList[ L->getRegClass()->getID() ];
108 RC->addLRToIG(L); // add this LR to an IG
114 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
115 RegClassList[rc]->createInterferenceGraph();
118 cerr << "LRLists Created!\n";
124 //----------------------------------------------------------------------------
125 // This method will add all interferences at for a given instruction.
126 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
127 // class as that of live var. The live var passed to this function is the
128 // LVset AFTER the instruction
129 //----------------------------------------------------------------------------
130 void PhyRegAlloc::addInterference(const Value *const Def,
131 const LiveVarSet *const LVSet,
132 const bool isCallInst) {
134 LiveVarSet::const_iterator LIt = LVSet->begin();
136 // get the live range of instruction
138 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
140 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
141 assert( IGNodeOfDef );
143 RegClass *const RCOfDef = LROfDef->getRegClass();
145 // for each live var in live variable set
147 for( ; LIt != LVSet->end(); ++LIt) {
150 cerr << "< Def="; printValue(Def);
151 cerr << ", Lvar="; printValue( *LIt); cerr << "> ";
154 // get the live range corresponding to live var
156 LiveRange *const LROfVar = LRI.getLiveRangeForValue(*LIt );
158 // LROfVar can be null if it is a const since a const
159 // doesn't have a dominating def - see Assumptions above
162 if(LROfDef == LROfVar) // do not set interf for same LR
165 // if 2 reg classes are the same set interference
167 if(RCOfDef == LROfVar->getRegClass()) {
168 RCOfDef->setInterference( LROfDef, LROfVar);
169 } else if(DEBUG_RA > 1) {
170 // we will not have LRs for values not explicitly allocated in the
171 // instruction stream (e.g., constants)
172 cerr << " warning: no live range for " ;
173 printValue(*LIt); cerr << "\n";
181 //----------------------------------------------------------------------------
182 // For a call instruction, this method sets the CallInterference flag in
183 // the LR of each variable live int the Live Variable Set live after the
184 // call instruction (except the return value of the call instruction - since
185 // the return value does not interfere with that call itself).
186 //----------------------------------------------------------------------------
188 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
189 const LiveVarSet *const LVSetAft ) {
191 // Now find the LR of the return value of the call
192 // We do this because, we look at the LV set *after* the instruction
193 // to determine, which LRs must be saved across calls. The return value
194 // of the call is live in this set - but it does not interfere with call
195 // (i.e., we can allocate a volatile register to the return value)
197 LiveRange *RetValLR = NULL;
198 const Value *RetVal = MRI.getCallInstRetVal( MInst );
201 RetValLR = LRI.getLiveRangeForValue( RetVal );
202 assert( RetValLR && "No LR for RetValue of call");
206 cerr << "\n For call inst: " << *MInst;
208 LiveVarSet::const_iterator LIt = LVSetAft->begin();
210 // for each live var in live variable set after machine inst
212 for( ; LIt != LVSetAft->end(); ++LIt) {
214 // get the live range corresponding to live var
216 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
218 if( LR && DEBUG_RA) {
219 cerr << "\n\tLR Aft Call: ";
224 // LR can be null if it is a const since a const
225 // doesn't have a dominating def - see Assumptions above
227 if( LR && (LR != RetValLR) ) {
228 LR->setCallInterference();
230 cerr << "\n ++Added call interf for LR: " ;
242 //----------------------------------------------------------------------------
243 // This method will walk thru code and create interferences in the IG of
244 // each RegClass. Also, this method calculates the spill cost of each
245 // Live Range (it is done in this method to save another pass over the code).
246 //----------------------------------------------------------------------------
247 void PhyRegAlloc::buildInterferenceGraphs()
250 if(DEBUG_RA) cerr << "Creating interference graphs ...\n";
252 unsigned BBLoopDepthCost;
253 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
255 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
257 // find the 10^(loop_depth) of this BB
259 BBLoopDepthCost = (unsigned) pow( 10.0, LoopDepthCalc.getLoopDepth(*BBI));
261 // get the iterator for machine instructions
263 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
264 MachineCodeForBasicBlock::const_iterator
265 MInstIterator = MIVec.begin();
267 // iterate over all the machine instructions in BB
269 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
271 const MachineInstr * MInst = *MInstIterator;
273 // get the LV set after the instruction
275 const LiveVarSet *const LVSetAI =
276 LVI->getLiveVarSetAfterMInst(MInst, *BBI);
278 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
281 // set the isCallInterference flag of each live range wich extends
282 // accross this call instruction. This information is used by graph
283 // coloring algo to avoid allocating volatile colors to live ranges
284 // that span across calls (since they have to be saved/restored)
286 setCallInterferences( MInst, LVSetAI);
290 // iterate over all MI operands to find defs
292 for( MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done(); ++OpI) {
295 // create a new LR iff this operand is a def
297 addInterference(*OpI, LVSetAI, isCallInst );
300 // Calculate the spill cost of each live range
302 LiveRange *LR = LRI.getLiveRangeForValue( *OpI );
304 LR->addSpillCost(BBLoopDepthCost);
308 // if there are multiple defs in this instruction e.g. in SETX
310 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
311 addInterf4PseudoInstr(MInst);
314 // Also add interference for any implicit definitions in a machine
315 // instr (currently, only calls have this).
317 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
318 if( NumOfImpRefs > 0 ) {
319 for(unsigned z=0; z < NumOfImpRefs; z++)
320 if( MInst->implicitRefIsDefined(z) )
321 addInterference( MInst->getImplicitRef(z), LVSetAI, isCallInst );
325 } // for all machine instructions in BB
327 } // for all BBs in method
330 // add interferences for method arguments. Since there are no explict
331 // defs in method for args, we have to add them manually
333 addInterferencesForArgs();
336 cerr << "Interference graphs calculted!\n";
342 //--------------------------------------------------------------------------
343 // Pseudo instructions will be exapnded to multiple instructions by the
344 // assembler. Consequently, all the opernds must get distinct registers.
345 // Therefore, we mark all operands of a pseudo instruction as they interfere
347 //--------------------------------------------------------------------------
348 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
350 bool setInterf = false;
352 // iterate over MI operands to find defs
354 for( MachineInstr::val_const_op_iterator It1(MInst);!It1.done(); ++It1) {
356 const LiveRange *const LROfOp1 = LRI.getLiveRangeForValue( *It1 );
358 if( !LROfOp1 && It1.isDef() )
359 assert( 0 && "No LR for Def in PSEUDO insruction");
361 MachineInstr::val_const_op_iterator It2 = It1;
364 for( ; !It2.done(); ++It2) {
366 const LiveRange *const LROfOp2 = LRI.getLiveRangeForValue( *It2 );
370 RegClass *const RCOfOp1 = LROfOp1->getRegClass();
371 RegClass *const RCOfOp2 = LROfOp2->getRegClass();
373 if( RCOfOp1 == RCOfOp2 ){
374 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
380 } // for all other defs in machine instr
382 } // for all operands in an instruction
384 if( !setInterf && (MInst->getNumOperands() > 2) ) {
385 cerr << "\nInterf not set for any operand in pseudo instr:\n";
387 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
395 //----------------------------------------------------------------------------
396 // This method will add interferences for incoming arguments to a method.
397 //----------------------------------------------------------------------------
398 void PhyRegAlloc::addInterferencesForArgs()
400 // get the InSet of root BB
401 const LiveVarSet *const InSet = LVI->getInSetOfBB( Meth->front() );
403 // get the argument list
404 const Method::ArgumentListType& ArgList = Meth->getArgumentList();
406 // get an iterator to arg list
407 Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();
410 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
411 addInterference( *ArgIt, InSet, false ); // add interferences between
412 // args and LVars at start
414 cerr << " - %% adding interference for argument ";
415 printValue((const Value *)*ArgIt); cerr << "\n";
423 //----------------------------------------------------------------------------
424 // This method is called after register allocation is complete to set the
425 // allocated reisters in the machine code. This code will add register numbers
426 // to MachineOperands that contain a Value. Also it calls target specific
427 // methods to produce caller saving instructions. At the end, it adds all
428 // additional instructions produced by the register allocator to the
429 // instruction stream.
430 //----------------------------------------------------------------------------
431 void PhyRegAlloc::updateMachineCode()
434 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
436 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
438 // get the iterator for machine instructions
440 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
441 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
443 // iterate over all the machine instructions in BB
445 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
447 MachineInstr *MInst = *MInstIterator;
449 unsigned Opcode = MInst->getOpCode();
451 // do not process Phis
452 if (TM.getInstrInfo().isPhi(Opcode))
455 // Now insert speical instructions (if necessary) for call/return
458 if (TM.getInstrInfo().isCall(Opcode) ||
459 TM.getInstrInfo().isReturn(Opcode)) {
461 AddedInstrns *AI = AddedInstrMap[ MInst];
463 AI = new AddedInstrns();
464 AddedInstrMap[ MInst ] = AI;
467 // Tmp stack poistions are needed by some calls that have spilled args
468 // So reset it before we call each such method
470 mcInfo.popAllTempValues(TM);
472 if (TM.getInstrInfo().isCall(Opcode))
473 MRI.colorCallArgs(MInst, LRI, AI, *this, *BBI);
474 else if (TM.getInstrInfo().isReturn(Opcode))
475 MRI.colorRetValue(MInst, LRI, AI);
479 /* -- Using above code instead of this
481 // if this machine instr is call, insert caller saving code
483 if( (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
484 MRI.insertCallerSavingCode(MInst, *BBI, *this );
489 // reset the stack offset for temporary variables since we may
490 // need that to spill
491 // mcInfo.popAllTempValues(TM);
492 // TODO ** : do later
494 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
497 // Now replace set the registers for operands in the machine instruction
499 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
501 MachineOperand& Op = MInst->getOperand(OpNum);
503 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
504 Op.getOperandType() == MachineOperand::MO_CCRegister) {
506 const Value *const Val = Op.getVRegValue();
508 // delete this condition checking later (must assert if Val is null)
511 cerr << "Warning: NULL Value found for operand\n";
514 assert( Val && "Value is NULL");
516 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
520 // nothing to worry if it's a const or a label
523 cerr << "*NO LR for operand : " << Op ;
524 cerr << " [reg:" << Op.getAllocatedRegNum() << "]";
525 cerr << " in inst:\t" << *MInst << "\n";
528 // if register is not allocated, mark register as invalid
529 if( Op.getAllocatedRegNum() == -1)
530 Op.setRegForValue( MRI.getInvalidRegNum());
536 unsigned RCID = (LR->getRegClass())->getID();
538 if( LR->hasColor() ) {
539 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
543 // LR did NOT receive a color (register). Now, insert spill code
544 // for spilled opeands in this machine instruction
546 //assert(0 && "LR must be spilled");
547 insertCode4SpilledLR(LR, MInst, *BBI, OpNum );
552 } // for each operand
555 // Now add instructions that the register allocator inserts before/after
556 // this machine instructions (done only for calls/rets/incoming args)
557 // We do this here, to ensure that spill for an instruction is inserted
558 // closest as possible to an instruction (see above insertCode4Spill...)
560 // If there are instructions to be added, *before* this machine
561 // instruction, add them now.
563 if( AddedInstrMap[ MInst ] ) {
564 std::deque<MachineInstr *> &IBef = AddedInstrMap[MInst]->InstrnsBefore;
566 if( ! IBef.empty() ) {
567 std::deque<MachineInstr *>::iterator AdIt;
569 for( AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt ) {
572 cerr << "For inst " << *MInst;
573 cerr << " PREPENDed instr: " << **AdIt << "\n";
576 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
584 // If there are instructions to be added *after* this machine
585 // instruction, add them now
587 if(AddedInstrMap[MInst] &&
588 !AddedInstrMap[MInst]->InstrnsAfter.empty() ) {
590 // if there are delay slots for this instruction, the instructions
591 // added after it must really go after the delayed instruction(s)
592 // So, we move the InstrAfter of the current instruction to the
593 // corresponding delayed instruction
596 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
597 move2DelayedInstr(MInst, *(MInstIterator+delay) );
599 if(DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
605 // Here we can add the "instructions after" to the current
606 // instruction since there are no delay slots for this instruction
608 std::deque<MachineInstr *> &IAft = AddedInstrMap[MInst]->InstrnsAfter;
610 if( ! IAft.empty() ) {
612 std::deque<MachineInstr *>::iterator AdIt;
614 ++MInstIterator; // advance to the next instruction
616 for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
619 cerr << "For inst " << *MInst;
620 cerr << " APPENDed instr: " << **AdIt << "\n";
623 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
627 // MInsterator already points to the next instr. Since the
628 // for loop also increments it, decrement it to point to the
629 // instruction added last
638 } // for each machine instruction
644 //----------------------------------------------------------------------------
645 // This method inserts spill code for AN operand whose LR was spilled.
646 // This method may be called several times for a single machine instruction
647 // if it contains many spilled operands. Each time it is called, it finds
648 // a register which is not live at that instruction and also which is not
649 // used by other spilled operands of the same instruction. Then it uses
650 // this register temporarily to accomodate the spilled value.
651 //----------------------------------------------------------------------------
652 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
654 const BasicBlock *BB,
655 const unsigned OpNum) {
657 assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
658 (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
659 "Arg of a call/ret must be handled elsewhere");
661 MachineOperand& Op = MInst->getOperand(OpNum);
662 bool isDef = MInst->operandIsDefined(OpNum);
663 unsigned RegType = MRI.getRegType( LR );
664 int SpillOff = LR->getSpillOffFromFP();
665 RegClass *RC = LR->getRegClass();
666 const LiveVarSet *LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
668 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
670 MachineInstr *MIBef=NULL, *AdIMid=NULL, *MIAft=NULL;
672 int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,LVSetBef, MIBef, MIAft);
674 // get the added instructions for this instruciton
675 AddedInstrns *AI = AddedInstrMap[ MInst ];
677 AI = new AddedInstrns();
678 AddedInstrMap[ MInst ] = AI;
684 // for a USE, we have to load the value of LR from stack to a TmpReg
685 // and use the TmpReg as one operand of instruction
687 // actual loading instruction
688 AdIMid = MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType);
691 AI->InstrnsBefore.push_back(MIBef);
693 AI->InstrnsBefore.push_back(AdIMid);
696 AI->InstrnsAfter.push_front(MIAft);
700 else { // if this is a Def
702 // for a DEF, we have to store the value produced by this instruction
703 // on the stack position allocated for this LR
705 // actual storing instruction
706 AdIMid = MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType);
709 AI->InstrnsBefore.push_back(MIBef);
711 AI->InstrnsAfter.push_front(AdIMid);
714 AI->InstrnsAfter.push_front(MIAft);
718 cerr << "\nFor Inst " << *MInst;
719 cerr << " - SPILLED LR: "; LR->printSet();
720 cerr << "\n - Added Instructions:";
721 if( MIBef ) cerr << *MIBef;
723 if( MIAft ) cerr << *MIAft;
725 Op.setRegForValue( TmpRegU ); // set the opearnd
735 //----------------------------------------------------------------------------
736 // We can use the following method to get a temporary register to be used
737 // BEFORE any given machine instruction. If there is a register available,
738 // this method will simply return that register and set MIBef = MIAft = NULL.
739 // Otherwise, it will return a register and MIAft and MIBef will contain
740 // two instructions used to free up this returned register.
741 // Returned register number is the UNIFIED register number
742 //----------------------------------------------------------------------------
744 int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC,
746 const MachineInstr *MInst,
747 const LiveVarSet *LVSetBef,
749 MachineInstr *MIAft) {
751 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
755 // we found an unused register, so we can simply use it
756 MIBef = MIAft = NULL;
759 // we couldn't find an unused register. Generate code to free up a reg by
760 // saving it on stack and restoring after the instruction
762 int TmpOff = mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
764 RegU = getUniRegNotUsedByThisInst(RC, MInst);
765 MIBef = MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType );
766 MIAft = MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType );
772 //----------------------------------------------------------------------------
773 // This method is called to get a new unused register that can be used to
774 // accomodate a spilled value.
775 // This method may be called several times for a single machine instruction
776 // if it contains many spilled operands. Each time it is called, it finds
777 // a register which is not live at that instruction and also which is not
778 // used by other spilled operands of the same instruction.
779 // Return register number is relative to the register class. NOT
781 //----------------------------------------------------------------------------
782 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
783 const MachineInstr *MInst,
784 const LiveVarSet *LVSetBef) {
786 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
788 bool *IsColorUsedArr = RC->getIsColorUsedArr();
790 for(unsigned i=0; i < NumAvailRegs; i++) // Reset array
791 IsColorUsedArr[i] = false;
793 LiveVarSet::const_iterator LIt = LVSetBef->begin();
795 // for each live var in live variable set after machine inst
796 for( ; LIt != LVSetBef->end(); ++LIt) {
798 // get the live range corresponding to live var
799 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
801 // LR can be null if it is a const since a const
802 // doesn't have a dominating def - see Assumptions above
804 if( LRofLV->hasColor() )
805 IsColorUsedArr[ LRofLV->getColor() ] = true;
808 // It is possible that one operand of this MInst was already spilled
809 // and it received some register temporarily. If that's the case,
810 // it is recorded in machine operand. We must skip such registers.
812 setRelRegsUsedByThisInst(RC, MInst);
814 unsigned c; // find first unused color
815 for( c=0; c < NumAvailRegs; c++)
816 if( ! IsColorUsedArr[ c ] ) break;
819 return MRI.getUnifiedRegNum(RC->getID(), c);
827 //----------------------------------------------------------------------------
828 // Get any other register in a register class, other than what is used
829 // by operands of a machine instruction. Returns the unified reg number.
830 //----------------------------------------------------------------------------
831 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
832 const MachineInstr *MInst) {
834 bool *IsColorUsedArr = RC->getIsColorUsedArr();
835 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
838 for(unsigned i=0; i < NumAvailRegs ; i++) // Reset array
839 IsColorUsedArr[i] = false;
841 setRelRegsUsedByThisInst(RC, MInst);
843 unsigned c; // find first unused color
844 for( c=0; c < RC->getNumOfAvailRegs(); c++)
845 if( ! IsColorUsedArr[ c ] ) break;
848 return MRI.getUnifiedRegNum(RC->getID(), c);
850 assert( 0 && "FATAL: No free register could be found in reg class!!");
855 //----------------------------------------------------------------------------
856 // This method modifies the IsColorUsedArr of the register class passed to it.
857 // It sets the bits corresponding to the registers used by this machine
858 // instructions. Both explicit and implicit operands are set.
859 //----------------------------------------------------------------------------
860 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
861 const MachineInstr *MInst ) {
863 bool *IsColorUsedArr = RC->getIsColorUsedArr();
865 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
867 const MachineOperand& Op = MInst->getOperand(OpNum);
869 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
870 Op.getOperandType() == MachineOperand::MO_CCRegister ) {
872 const Value *const Val = Op.getVRegValue();
875 if( MRI.getRegClassIDOfValue(Val) == RC->getID() ) {
877 if( (Reg=Op.getAllocatedRegNum()) != -1) {
878 IsColorUsedArr[ Reg ] = true;
881 // it is possilbe that this operand still is not marked with
882 // a register but it has a LR and that received a color
884 LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
886 if( LROfVal->hasColor() )
887 IsColorUsedArr[ LROfVal->getColor() ] = true;
890 } // if reg classes are the same
892 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
893 IsColorUsedArr[ Op.getMachineRegNum() ] = true;
897 // If there are implicit references, mark them as well
899 for(unsigned z=0; z < MInst->getNumImplicitRefs(); z++) {
901 LiveRange *const LRofImpRef =
902 LRI.getLiveRangeForValue( MInst->getImplicitRef(z) );
904 if(LRofImpRef && LRofImpRef->hasColor())
905 IsColorUsedArr[LRofImpRef->getColor()] = true;
916 //----------------------------------------------------------------------------
917 // If there are delay slots for an instruction, the instructions
918 // added after it must really go after the delayed instruction(s).
919 // So, we move the InstrAfter of that instruction to the
920 // corresponding delayed instruction using the following method.
922 //----------------------------------------------------------------------------
923 void PhyRegAlloc:: move2DelayedInstr(const MachineInstr *OrigMI,
924 const MachineInstr *DelayedMI) {
926 // "added after" instructions of the original instr
927 std::deque<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI]->InstrnsAfter;
929 // "added instructions" of the delayed instr
930 AddedInstrns *DelayAdI = AddedInstrMap[DelayedMI];
932 if(! DelayAdI ) { // create a new "added after" if necessary
933 DelayAdI = new AddedInstrns();
934 AddedInstrMap[DelayedMI] = DelayAdI;
937 // "added after" instructions of the delayed instr
938 std::deque<MachineInstr *> &DelayedAft = DelayAdI->InstrnsAfter;
940 // go thru all the "added after instructions" of the original instruction
941 // and append them to the "addded after instructions" of the delayed
943 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
945 // empty the "added after instructions" of the original instruction
949 //----------------------------------------------------------------------------
950 // This method prints the code with registers after register allocation is
952 //----------------------------------------------------------------------------
953 void PhyRegAlloc::printMachineCode()
956 cerr << "\n;************** Method " << Meth->getName()
957 << " *****************\n";
959 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
961 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
963 cerr << "\n"; printLabel( *BBI); cerr << ": ";
965 // get the iterator for machine instructions
966 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
967 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
969 // iterate over all the machine instructions in BB
970 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
972 MachineInstr *const MInst = *MInstIterator;
976 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
979 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
981 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
983 MachineOperand& Op = MInst->getOperand(OpNum);
985 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
986 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
987 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
989 const Value *const Val = Op.getVRegValue () ;
990 // ****this code is temporary till NULL Values are fixed
992 cerr << "\t<*NULL*>";
996 // if a label or a constant
997 if(isa<BasicBlock>(Val)) {
998 cerr << "\t"; printLabel( Op.getVRegValue () );
1000 // else it must be a register value
1001 const int RegNum = Op.getAllocatedRegNum();
1003 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
1004 if (Val->hasName() )
1005 cerr << "(" << Val->getName() << ")";
1007 cerr << "(" << Val << ")";
1012 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
1014 if( LROfVal->hasSpillOffset() )
1019 else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
1020 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1024 cerr << "\t" << Op; // use dump field
1029 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1030 if( NumOfImpRefs > 0 ) {
1032 cerr << "\tImplicit:";
1034 for(unsigned z=0; z < NumOfImpRefs; z++) {
1035 printValue( MInst->getImplicitRef(z) );
1041 } // for all machine instructions
1053 //----------------------------------------------------------------------------
1055 //----------------------------------------------------------------------------
1057 void PhyRegAlloc::colorCallRetArgs()
1060 CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
1061 CallRetInstrListType::const_iterator It = CallRetInstList.begin();
1063 for( ; It != CallRetInstList.end(); ++It ) {
1065 const MachineInstr *const CRMI = *It;
1066 unsigned OpCode = CRMI->getOpCode();
1068 // get the added instructions for this Call/Ret instruciton
1069 AddedInstrns *AI = AddedInstrMap[ CRMI ];
1071 AI = new AddedInstrns();
1072 AddedInstrMap[ CRMI ] = AI;
1075 // Tmp stack poistions are needed by some calls that have spilled args
1076 // So reset it before we call each such method
1077 //mcInfo.popAllTempValues(TM);
1081 if (TM.getInstrInfo().isCall(OpCode))
1082 MRI.colorCallArgs(CRMI, LRI, AI, *this);
1083 else if (TM.getInstrInfo().isReturn(OpCode))
1084 MRI.colorRetValue( CRMI, LRI, AI );
1086 assert(0 && "Non Call/Ret instrn in CallRetInstrList\n");
1092 //----------------------------------------------------------------------------
1094 //----------------------------------------------------------------------------
1095 void PhyRegAlloc::colorIncomingArgs()
1097 const BasicBlock *const FirstBB = Meth->front();
1098 const MachineInstr *FirstMI = FirstBB->getMachineInstrVec().front();
1099 assert(FirstMI && "No machine instruction in entry BB");
1101 AddedInstrns *AI = AddedInstrMap[FirstMI];
1103 AddedInstrMap[FirstMI] = AI = new AddedInstrns();
1105 MRI.colorMethodArgs(Meth, LRI, AI);
1109 //----------------------------------------------------------------------------
1110 // Used to generate a label for a basic block
1111 //----------------------------------------------------------------------------
1112 void PhyRegAlloc::printLabel(const Value *const Val) {
1114 cerr << Val->getName();
1116 cerr << "Label" << Val;
1120 //----------------------------------------------------------------------------
1121 // This method calls setSugColorUsable method of each live range. This
1122 // will determine whether the suggested color of LR is really usable.
1123 // A suggested color is not usable when the suggested color is volatile
1124 // AND when there are call interferences
1125 //----------------------------------------------------------------------------
1127 void PhyRegAlloc::markUnusableSugColors()
1129 if(DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
1131 // hash map iterator
1132 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1133 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1135 for(; HMI != HMIEnd ; ++HMI ) {
1137 LiveRange *L = HMI->second; // get the LiveRange
1139 if(L->hasSuggestedColor()) {
1140 int RCID = L->getRegClass()->getID();
1141 if( MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1142 L->isCallInterference() )
1143 L->setSuggestedColorUsable( false );
1145 L->setSuggestedColorUsable( true );
1147 } // if L->hasSuggestedColor()
1149 } // for all LR's in hash map
1154 //----------------------------------------------------------------------------
1155 // The following method will set the stack offsets of the live ranges that
1156 // are decided to be spillled. This must be called just after coloring the
1157 // LRs using the graph coloring algo. For each live range that is spilled,
1158 // this method allocate a new spill position on the stack.
1159 //----------------------------------------------------------------------------
1161 void PhyRegAlloc::allocateStackSpace4SpilledLRs()
1163 if(DEBUG_RA ) cerr << "\nsetting LR stack offsets ...\n";
1165 // hash map iterator
1166 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1167 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1169 for( ; HMI != HMIEnd ; ++HMI ) {
1170 if(HMI->first && HMI->second) {
1171 LiveRange *L = HMI->second; // get the LiveRange
1172 if( ! L->hasColor() )
1173 // NOTE: ** allocating the size of long Type **
1174 L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
1176 } // for all LR's in hash map
1181 //----------------------------------------------------------------------------
1182 // The entry pont to Register Allocation
1183 //----------------------------------------------------------------------------
1185 void PhyRegAlloc::allocateRegisters()
1188 // make sure that we put all register classes into the RegClassList
1189 // before we call constructLiveRanges (now done in the constructor of
1190 // PhyRegAlloc class).
1192 LRI.constructLiveRanges(); // create LR info
1195 LRI.printLiveRanges();
1197 createIGNodeListsAndIGs(); // create IGNode list and IGs
1199 buildInterferenceGraphs(); // build IGs in all reg classes
1203 // print all LRs in all reg classes
1204 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1205 RegClassList[ rc ]->printIGNodeList();
1207 // print IGs in all register classes
1208 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1209 RegClassList[ rc ]->printIG();
1213 LRI.coalesceLRs(); // coalesce all live ranges
1217 // print all LRs in all reg classes
1218 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1219 RegClassList[ rc ]->printIGNodeList();
1221 // print IGs in all register classes
1222 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1223 RegClassList[ rc ]->printIG();
1227 // mark un-usable suggested color before graph coloring algorithm.
1228 // When this is done, the graph coloring algo will not reserve
1229 // suggested color unnecessarily - they can be used by another LR
1231 markUnusableSugColors();
1233 // color all register classes using the graph coloring algo
1234 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1235 RegClassList[ rc ]->colorAllRegs();
1237 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1238 // a poistion for such spilled LRs
1240 allocateStackSpace4SpilledLRs();
1242 mcInfo.popAllTempValues(TM); // TODO **Check
1244 // color incoming args - if the correct color was not received
1245 // insert code to copy to the correct register
1247 colorIncomingArgs();
1249 // Now update the machine code with register names and add any
1250 // additional code inserted by the register allocator to the instruction
1253 updateMachineCode();
1256 MachineCodeForMethod::get(Meth).dump();
1257 printMachineCode(); // only for DEBUGGING