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/Analysis/LiveVar/MethodLiveVarInfo.h"
18 #include "llvm/Target/TargetMachine.h"
19 #include "llvm/Target/MachineFrameInfo.h"
25 // ***TODO: There are several places we add instructions. Validate the order
26 // of adding these instructions.
28 cl::Enum<RegAllocDebugLevel_t> DEBUG_RA("dregalloc", cl::NoFlags,
29 "enable register allocation debugging information",
30 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
31 clEnumValN(RA_DEBUG_Normal , "y", "enable debug output"),
32 clEnumValN(RA_DEBUG_Verbose, "v", "enable extra debug output"), 0);
35 bool RegisterAllocation::runOnMethod(Method *M) {
37 cerr << "\n******************** Method "<< M->getName()
38 << " ********************\n";
40 MethodLiveVarInfo LVI(M); // Analyze live varaibles
43 PhyRegAlloc PRA(M, Target, &LVI); // allocate registers
44 PRA.allocateRegisters();
46 if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
51 //----------------------------------------------------------------------------
52 // Constructor: Init local composite objects and create register classes.
53 //----------------------------------------------------------------------------
54 PhyRegAlloc::PhyRegAlloc(Method *M,
55 const TargetMachine& tm,
56 MethodLiveVarInfo *const Lvi)
58 mcInfo(MachineCodeForMethod::get(M)),
59 LVI(Lvi), LRI(M, tm, RegClassList),
60 MRI( tm.getRegInfo() ),
61 NumOfRegClasses(MRI.getNumOfRegClasses()),
64 // create each RegisterClass and put in RegClassList
66 for(unsigned int rc=0; rc < NumOfRegClasses; rc++)
67 RegClassList.push_back( new RegClass(M, MRI.getMachineRegClass(rc),
72 //----------------------------------------------------------------------------
73 // Destructor: Deletes register classes
74 //----------------------------------------------------------------------------
75 PhyRegAlloc::~PhyRegAlloc() {
76 for( unsigned int rc=0; rc < NumOfRegClasses; rc++)
77 delete RegClassList[rc];
80 //----------------------------------------------------------------------------
81 // This method initally creates interference graphs (one in each reg class)
82 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
83 //----------------------------------------------------------------------------
84 void PhyRegAlloc::createIGNodeListsAndIGs() {
85 if (DEBUG_RA) cerr << "Creating LR lists ...\n";
88 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
91 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
93 for (; HMI != HMIEnd ; ++HMI ) {
95 LiveRange *L = HMI->second; // get the LiveRange
98 cerr << "\n*?!?Warning: Null liver range found for: ";
99 printValue(HMI->first); cerr << "\n";
103 // if the Value * is not null, and LR
104 // is not yet written to the IGNodeList
105 if( !(L->getUserIGNode()) ) {
106 RegClass *const RC = // RegClass of first value in the LR
107 RegClassList[ L->getRegClass()->getID() ];
109 RC->addLRToIG(L); // add this LR to an IG
115 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
116 RegClassList[rc]->createInterferenceGraph();
119 cerr << "LRLists Created!\n";
125 //----------------------------------------------------------------------------
126 // This method will add all interferences at for a given instruction.
127 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
128 // class as that of live var. The live var passed to this function is the
129 // LVset AFTER the instruction
130 //----------------------------------------------------------------------------
131 void PhyRegAlloc::addInterference(const Value *const Def,
132 const LiveVarSet *const LVSet,
133 const bool isCallInst) {
135 LiveVarSet::const_iterator LIt = LVSet->begin();
137 // get the live range of instruction
139 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
141 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
142 assert( IGNodeOfDef );
144 RegClass *const RCOfDef = LROfDef->getRegClass();
146 // for each live var in live variable set
148 for( ; LIt != LVSet->end(); ++LIt) {
151 cerr << "< Def="; printValue(Def);
152 cerr << ", Lvar="; printValue( *LIt); cerr << "> ";
155 // get the live range corresponding to live var
157 LiveRange *const LROfVar = LRI.getLiveRangeForValue(*LIt );
159 // LROfVar can be null if it is a const since a const
160 // doesn't have a dominating def - see Assumptions above
163 if(LROfDef == LROfVar) // do not set interf for same LR
166 // if 2 reg classes are the same set interference
168 if(RCOfDef == LROfVar->getRegClass()) {
169 RCOfDef->setInterference( LROfDef, LROfVar);
170 } else if(DEBUG_RA > 1) {
171 // we will not have LRs for values not explicitly allocated in the
172 // instruction stream (e.g., constants)
173 cerr << " warning: no live range for " ;
174 printValue(*LIt); cerr << "\n";
182 //----------------------------------------------------------------------------
183 // For a call instruction, this method sets the CallInterference flag in
184 // the LR of each variable live int the Live Variable Set live after the
185 // call instruction (except the return value of the call instruction - since
186 // the return value does not interfere with that call itself).
187 //----------------------------------------------------------------------------
189 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
190 const LiveVarSet *const LVSetAft ) {
192 // Now find the LR of the return value of the call
193 // We do this because, we look at the LV set *after* the instruction
194 // to determine, which LRs must be saved across calls. The return value
195 // of the call is live in this set - but it does not interfere with call
196 // (i.e., we can allocate a volatile register to the return value)
198 LiveRange *RetValLR = NULL;
199 const Value *RetVal = MRI.getCallInstRetVal( MInst );
202 RetValLR = LRI.getLiveRangeForValue( RetVal );
203 assert( RetValLR && "No LR for RetValue of call");
207 cerr << "\n For call inst: " << *MInst;
209 LiveVarSet::const_iterator LIt = LVSetAft->begin();
211 // for each live var in live variable set after machine inst
213 for( ; LIt != LVSetAft->end(); ++LIt) {
215 // get the live range corresponding to live var
217 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
219 if( LR && DEBUG_RA) {
220 cerr << "\n\tLR Aft Call: ";
225 // LR can be null if it is a const since a const
226 // doesn't have a dominating def - see Assumptions above
228 if( LR && (LR != RetValLR) ) {
229 LR->setCallInterference();
231 cerr << "\n ++Added call interf for LR: " ;
243 //----------------------------------------------------------------------------
244 // This method will walk thru code and create interferences in the IG of
245 // each RegClass. Also, this method calculates the spill cost of each
246 // Live Range (it is done in this method to save another pass over the code).
247 //----------------------------------------------------------------------------
248 void PhyRegAlloc::buildInterferenceGraphs()
251 if(DEBUG_RA) cerr << "Creating interference graphs ...\n";
253 unsigned BBLoopDepthCost;
254 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
256 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
258 // find the 10^(loop_depth) of this BB
260 BBLoopDepthCost = (unsigned) pow( 10.0, LoopDepthCalc.getLoopDepth(*BBI));
262 // get the iterator for machine instructions
264 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
265 MachineCodeForBasicBlock::const_iterator
266 MInstIterator = MIVec.begin();
268 // iterate over all the machine instructions in BB
270 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
272 const MachineInstr * MInst = *MInstIterator;
274 // get the LV set after the instruction
276 const LiveVarSet *const LVSetAI =
277 LVI->getLiveVarSetAfterMInst(MInst, *BBI);
279 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
282 // set the isCallInterference flag of each live range wich extends
283 // accross this call instruction. This information is used by graph
284 // coloring algo to avoid allocating volatile colors to live ranges
285 // that span across calls (since they have to be saved/restored)
287 setCallInterferences( MInst, LVSetAI);
291 // iterate over all MI operands to find defs
293 for( MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done(); ++OpI) {
296 // create a new LR iff this operand is a def
298 addInterference(*OpI, LVSetAI, isCallInst );
301 // Calculate the spill cost of each live range
303 LiveRange *LR = LRI.getLiveRangeForValue( *OpI );
305 LR->addSpillCost(BBLoopDepthCost);
309 // if there are multiple defs in this instruction e.g. in SETX
311 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
312 addInterf4PseudoInstr(MInst);
315 // Also add interference for any implicit definitions in a machine
316 // instr (currently, only calls have this).
318 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
319 if( NumOfImpRefs > 0 ) {
320 for(unsigned z=0; z < NumOfImpRefs; z++)
321 if( MInst->implicitRefIsDefined(z) )
322 addInterference( MInst->getImplicitRef(z), LVSetAI, isCallInst );
326 } // for all machine instructions in BB
328 } // for all BBs in method
331 // add interferences for method arguments. Since there are no explict
332 // defs in method for args, we have to add them manually
334 addInterferencesForArgs();
337 cerr << "Interference graphs calculted!\n";
343 //--------------------------------------------------------------------------
344 // Pseudo instructions will be exapnded to multiple instructions by the
345 // assembler. Consequently, all the opernds must get distinct registers.
346 // Therefore, we mark all operands of a pseudo instruction as they interfere
348 //--------------------------------------------------------------------------
349 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
351 bool setInterf = false;
353 // iterate over MI operands to find defs
355 for( MachineInstr::val_const_op_iterator It1(MInst);!It1.done(); ++It1) {
357 const LiveRange *const LROfOp1 = LRI.getLiveRangeForValue( *It1 );
359 if( !LROfOp1 && It1.isDef() )
360 assert( 0 && "No LR for Def in PSEUDO insruction");
362 MachineInstr::val_const_op_iterator It2 = It1;
365 for( ; !It2.done(); ++It2) {
367 const LiveRange *const LROfOp2 = LRI.getLiveRangeForValue( *It2 );
371 RegClass *const RCOfOp1 = LROfOp1->getRegClass();
372 RegClass *const RCOfOp2 = LROfOp2->getRegClass();
374 if( RCOfOp1 == RCOfOp2 ){
375 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
381 } // for all other defs in machine instr
383 } // for all operands in an instruction
385 if( !setInterf && (MInst->getNumOperands() > 2) ) {
386 cerr << "\nInterf not set for any operand in pseudo instr:\n";
388 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
396 //----------------------------------------------------------------------------
397 // This method will add interferences for incoming arguments to a method.
398 //----------------------------------------------------------------------------
399 void PhyRegAlloc::addInterferencesForArgs()
401 // get the InSet of root BB
402 const LiveVarSet *const InSet = LVI->getInSetOfBB( Meth->front() );
404 // get the argument list
405 const Method::ArgumentListType& ArgList = Meth->getArgumentList();
407 // get an iterator to arg list
408 Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();
411 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
412 addInterference( *ArgIt, InSet, false ); // add interferences between
413 // args and LVars at start
415 cerr << " - %% adding interference for argument ";
416 printValue((const Value *)*ArgIt); cerr << "\n";
424 //----------------------------------------------------------------------------
425 // This method is called after register allocation is complete to set the
426 // allocated reisters in the machine code. This code will add register numbers
427 // to MachineOperands that contain a Value. Also it calls target specific
428 // methods to produce caller saving instructions. At the end, it adds all
429 // additional instructions produced by the register allocator to the
430 // instruction stream.
431 //----------------------------------------------------------------------------
432 void PhyRegAlloc::updateMachineCode()
435 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
437 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
439 // get the iterator for machine instructions
441 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
442 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
444 // iterate over all the machine instructions in BB
446 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
448 MachineInstr *MInst = *MInstIterator;
450 unsigned Opcode = MInst->getOpCode();
452 // do not process Phis
453 if (TM.getInstrInfo().isPhi(Opcode))
456 // Now insert speical instructions (if necessary) for call/return
459 if (TM.getInstrInfo().isCall(Opcode) ||
460 TM.getInstrInfo().isReturn(Opcode)) {
462 AddedInstrns *AI = AddedInstrMap[ MInst];
464 AI = new AddedInstrns();
465 AddedInstrMap[ MInst ] = AI;
468 // Tmp stack poistions are needed by some calls that have spilled args
469 // So reset it before we call each such method
471 mcInfo.popAllTempValues(TM);
473 if (TM.getInstrInfo().isCall(Opcode))
474 MRI.colorCallArgs(MInst, LRI, AI, *this, *BBI);
475 else if (TM.getInstrInfo().isReturn(Opcode))
476 MRI.colorRetValue(MInst, LRI, AI);
480 /* -- Using above code instead of this
482 // if this machine instr is call, insert caller saving code
484 if( (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
485 MRI.insertCallerSavingCode(MInst, *BBI, *this );
490 // reset the stack offset for temporary variables since we may
491 // need that to spill
492 // mcInfo.popAllTempValues(TM);
493 // TODO ** : do later
495 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
498 // Now replace set the registers for operands in the machine instruction
500 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
502 MachineOperand& Op = MInst->getOperand(OpNum);
504 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
505 Op.getOperandType() == MachineOperand::MO_CCRegister) {
507 const Value *const Val = Op.getVRegValue();
509 // delete this condition checking later (must assert if Val is null)
512 cerr << "Warning: NULL Value found for operand\n";
515 assert( Val && "Value is NULL");
517 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
521 // nothing to worry if it's a const or a label
524 cerr << "*NO LR for operand : " << Op ;
525 cerr << " [reg:" << Op.getAllocatedRegNum() << "]";
526 cerr << " in inst:\t" << *MInst << "\n";
529 // if register is not allocated, mark register as invalid
530 if( Op.getAllocatedRegNum() == -1)
531 Op.setRegForValue( MRI.getInvalidRegNum());
537 unsigned RCID = (LR->getRegClass())->getID();
539 if( LR->hasColor() ) {
540 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
544 // LR did NOT receive a color (register). Now, insert spill code
545 // for spilled opeands in this machine instruction
547 //assert(0 && "LR must be spilled");
548 insertCode4SpilledLR(LR, MInst, *BBI, OpNum );
553 } // for each operand
556 // Now add instructions that the register allocator inserts before/after
557 // this machine instructions (done only for calls/rets/incoming args)
558 // We do this here, to ensure that spill for an instruction is inserted
559 // closest as possible to an instruction (see above insertCode4Spill...)
561 // If there are instructions to be added, *before* this machine
562 // instruction, add them now.
564 if( AddedInstrMap[ MInst ] ) {
565 std::deque<MachineInstr *> &IBef = AddedInstrMap[MInst]->InstrnsBefore;
567 if( ! IBef.empty() ) {
568 std::deque<MachineInstr *>::iterator AdIt;
570 for( AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt ) {
573 cerr << "For inst " << *MInst;
574 cerr << " PREPENDed instr: " << **AdIt << "\n";
577 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
585 // If there are instructions to be added *after* this machine
586 // instruction, add them now
588 if(AddedInstrMap[MInst] &&
589 !AddedInstrMap[MInst]->InstrnsAfter.empty() ) {
591 // if there are delay slots for this instruction, the instructions
592 // added after it must really go after the delayed instruction(s)
593 // So, we move the InstrAfter of the current instruction to the
594 // corresponding delayed instruction
597 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
598 move2DelayedInstr(MInst, *(MInstIterator+delay) );
600 if(DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
606 // Here we can add the "instructions after" to the current
607 // instruction since there are no delay slots for this instruction
609 std::deque<MachineInstr *> &IAft = AddedInstrMap[MInst]->InstrnsAfter;
611 if( ! IAft.empty() ) {
613 std::deque<MachineInstr *>::iterator AdIt;
615 ++MInstIterator; // advance to the next instruction
617 for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
620 cerr << "For inst " << *MInst;
621 cerr << " APPENDed instr: " << **AdIt << "\n";
624 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
628 // MInsterator already points to the next instr. Since the
629 // for loop also increments it, decrement it to point to the
630 // instruction added last
639 } // for each machine instruction
645 //----------------------------------------------------------------------------
646 // This method inserts spill code for AN operand whose LR was spilled.
647 // This method may be called several times for a single machine instruction
648 // if it contains many spilled operands. Each time it is called, it finds
649 // a register which is not live at that instruction and also which is not
650 // used by other spilled operands of the same instruction. Then it uses
651 // this register temporarily to accomodate the spilled value.
652 //----------------------------------------------------------------------------
653 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
655 const BasicBlock *BB,
656 const unsigned OpNum) {
658 assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
659 (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
660 "Arg of a call/ret must be handled elsewhere");
662 MachineOperand& Op = MInst->getOperand(OpNum);
663 bool isDef = MInst->operandIsDefined(OpNum);
664 unsigned RegType = MRI.getRegType( LR );
665 int SpillOff = LR->getSpillOffFromFP();
666 RegClass *RC = LR->getRegClass();
667 const LiveVarSet *LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
669 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
671 MachineInstr *MIBef=NULL, *AdIMid=NULL, *MIAft=NULL;
673 int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,LVSetBef, MIBef, MIAft);
675 // get the added instructions for this instruciton
676 AddedInstrns *AI = AddedInstrMap[ MInst ];
678 AI = new AddedInstrns();
679 AddedInstrMap[ MInst ] = AI;
685 // for a USE, we have to load the value of LR from stack to a TmpReg
686 // and use the TmpReg as one operand of instruction
688 // actual loading instruction
689 AdIMid = MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType);
692 AI->InstrnsBefore.push_back(MIBef);
694 AI->InstrnsBefore.push_back(AdIMid);
697 AI->InstrnsAfter.push_front(MIAft);
701 else { // if this is a Def
703 // for a DEF, we have to store the value produced by this instruction
704 // on the stack position allocated for this LR
706 // actual storing instruction
707 AdIMid = MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType);
710 AI->InstrnsBefore.push_back(MIBef);
712 AI->InstrnsAfter.push_front(AdIMid);
715 AI->InstrnsAfter.push_front(MIAft);
719 cerr << "\nFor Inst " << *MInst;
720 cerr << " - SPILLED LR: "; LR->printSet();
721 cerr << "\n - Added Instructions:";
722 if( MIBef ) cerr << *MIBef;
724 if( MIAft ) cerr << *MIAft;
726 Op.setRegForValue( TmpRegU ); // set the opearnd
736 //----------------------------------------------------------------------------
737 // We can use the following method to get a temporary register to be used
738 // BEFORE any given machine instruction. If there is a register available,
739 // this method will simply return that register and set MIBef = MIAft = NULL.
740 // Otherwise, it will return a register and MIAft and MIBef will contain
741 // two instructions used to free up this returned register.
742 // Returned register number is the UNIFIED register number
743 //----------------------------------------------------------------------------
745 int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC,
747 const MachineInstr *MInst,
748 const LiveVarSet *LVSetBef,
750 MachineInstr *MIAft) {
752 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
756 // we found an unused register, so we can simply use it
757 MIBef = MIAft = NULL;
760 // we couldn't find an unused register. Generate code to free up a reg by
761 // saving it on stack and restoring after the instruction
763 int TmpOff = mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
765 RegU = getUniRegNotUsedByThisInst(RC, MInst);
766 MIBef = MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType );
767 MIAft = MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType );
773 //----------------------------------------------------------------------------
774 // This method is called to get a new unused register that can be used to
775 // accomodate a spilled value.
776 // This method may be called several times for a single machine instruction
777 // if it contains many spilled operands. Each time it is called, it finds
778 // a register which is not live at that instruction and also which is not
779 // used by other spilled operands of the same instruction.
780 // Return register number is relative to the register class. NOT
782 //----------------------------------------------------------------------------
783 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
784 const MachineInstr *MInst,
785 const LiveVarSet *LVSetBef) {
787 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
789 bool *IsColorUsedArr = RC->getIsColorUsedArr();
791 for(unsigned i=0; i < NumAvailRegs; i++) // Reset array
792 IsColorUsedArr[i] = false;
794 LiveVarSet::const_iterator LIt = LVSetBef->begin();
796 // for each live var in live variable set after machine inst
797 for( ; LIt != LVSetBef->end(); ++LIt) {
799 // get the live range corresponding to live var
800 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
802 // LR can be null if it is a const since a const
803 // doesn't have a dominating def - see Assumptions above
805 if( LRofLV->hasColor() )
806 IsColorUsedArr[ LRofLV->getColor() ] = true;
809 // It is possible that one operand of this MInst was already spilled
810 // and it received some register temporarily. If that's the case,
811 // it is recorded in machine operand. We must skip such registers.
813 setRelRegsUsedByThisInst(RC, MInst);
815 unsigned c; // find first unused color
816 for( c=0; c < NumAvailRegs; c++)
817 if( ! IsColorUsedArr[ c ] ) break;
820 return MRI.getUnifiedRegNum(RC->getID(), c);
828 //----------------------------------------------------------------------------
829 // Get any other register in a register class, other than what is used
830 // by operands of a machine instruction. Returns the unified reg number.
831 //----------------------------------------------------------------------------
832 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
833 const MachineInstr *MInst) {
835 bool *IsColorUsedArr = RC->getIsColorUsedArr();
836 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
839 for(unsigned i=0; i < NumAvailRegs ; i++) // Reset array
840 IsColorUsedArr[i] = false;
842 setRelRegsUsedByThisInst(RC, MInst);
844 unsigned c; // find first unused color
845 for( c=0; c < RC->getNumOfAvailRegs(); c++)
846 if( ! IsColorUsedArr[ c ] ) break;
849 return MRI.getUnifiedRegNum(RC->getID(), c);
851 assert( 0 && "FATAL: No free register could be found in reg class!!");
856 //----------------------------------------------------------------------------
857 // This method modifies the IsColorUsedArr of the register class passed to it.
858 // It sets the bits corresponding to the registers used by this machine
859 // instructions. Both explicit and implicit operands are set.
860 //----------------------------------------------------------------------------
861 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
862 const MachineInstr *MInst ) {
864 bool *IsColorUsedArr = RC->getIsColorUsedArr();
866 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
868 const MachineOperand& Op = MInst->getOperand(OpNum);
870 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
871 Op.getOperandType() == MachineOperand::MO_CCRegister ) {
873 const Value *const Val = Op.getVRegValue();
876 if( MRI.getRegClassIDOfValue(Val) == RC->getID() ) {
878 if( (Reg=Op.getAllocatedRegNum()) != -1) {
879 IsColorUsedArr[ Reg ] = true;
882 // it is possilbe that this operand still is not marked with
883 // a register but it has a LR and that received a color
885 LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
887 if( LROfVal->hasColor() )
888 IsColorUsedArr[ LROfVal->getColor() ] = true;
891 } // if reg classes are the same
893 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
894 IsColorUsedArr[ Op.getMachineRegNum() ] = true;
898 // If there are implicit references, mark them as well
900 for(unsigned z=0; z < MInst->getNumImplicitRefs(); z++) {
902 LiveRange *const LRofImpRef =
903 LRI.getLiveRangeForValue( MInst->getImplicitRef(z) );
905 if(LRofImpRef && LRofImpRef->hasColor())
906 IsColorUsedArr[LRofImpRef->getColor()] = true;
917 //----------------------------------------------------------------------------
918 // If there are delay slots for an instruction, the instructions
919 // added after it must really go after the delayed instruction(s).
920 // So, we move the InstrAfter of that instruction to the
921 // corresponding delayed instruction using the following method.
923 //----------------------------------------------------------------------------
924 void PhyRegAlloc:: move2DelayedInstr(const MachineInstr *OrigMI,
925 const MachineInstr *DelayedMI) {
927 // "added after" instructions of the original instr
928 std::deque<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI]->InstrnsAfter;
930 // "added instructions" of the delayed instr
931 AddedInstrns *DelayAdI = AddedInstrMap[DelayedMI];
933 if(! DelayAdI ) { // create a new "added after" if necessary
934 DelayAdI = new AddedInstrns();
935 AddedInstrMap[DelayedMI] = DelayAdI;
938 // "added after" instructions of the delayed instr
939 std::deque<MachineInstr *> &DelayedAft = DelayAdI->InstrnsAfter;
941 // go thru all the "added after instructions" of the original instruction
942 // and append them to the "addded after instructions" of the delayed
944 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
946 // empty the "added after instructions" of the original instruction
950 //----------------------------------------------------------------------------
951 // This method prints the code with registers after register allocation is
953 //----------------------------------------------------------------------------
954 void PhyRegAlloc::printMachineCode()
957 cerr << "\n;************** Method " << Meth->getName()
958 << " *****************\n";
960 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
962 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
964 cerr << "\n"; printLabel( *BBI); cerr << ": ";
966 // get the iterator for machine instructions
967 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
968 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
970 // iterate over all the machine instructions in BB
971 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
973 MachineInstr *const MInst = *MInstIterator;
977 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
980 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
982 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
984 MachineOperand& Op = MInst->getOperand(OpNum);
986 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
987 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
988 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
990 const Value *const Val = Op.getVRegValue () ;
991 // ****this code is temporary till NULL Values are fixed
993 cerr << "\t<*NULL*>";
997 // if a label or a constant
998 if(isa<BasicBlock>(Val)) {
999 cerr << "\t"; printLabel( Op.getVRegValue () );
1001 // else it must be a register value
1002 const int RegNum = Op.getAllocatedRegNum();
1004 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
1005 if (Val->hasName() )
1006 cerr << "(" << Val->getName() << ")";
1008 cerr << "(" << Val << ")";
1013 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
1015 if( LROfVal->hasSpillOffset() )
1020 else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
1021 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1025 cerr << "\t" << Op; // use dump field
1030 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1031 if( NumOfImpRefs > 0 ) {
1033 cerr << "\tImplicit:";
1035 for(unsigned z=0; z < NumOfImpRefs; z++) {
1036 printValue( MInst->getImplicitRef(z) );
1042 } // for all machine instructions
1054 //----------------------------------------------------------------------------
1056 //----------------------------------------------------------------------------
1058 void PhyRegAlloc::colorCallRetArgs()
1061 CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
1062 CallRetInstrListType::const_iterator It = CallRetInstList.begin();
1064 for( ; It != CallRetInstList.end(); ++It ) {
1066 const MachineInstr *const CRMI = *It;
1067 unsigned OpCode = CRMI->getOpCode();
1069 // get the added instructions for this Call/Ret instruciton
1070 AddedInstrns *AI = AddedInstrMap[ CRMI ];
1072 AI = new AddedInstrns();
1073 AddedInstrMap[ CRMI ] = AI;
1076 // Tmp stack poistions are needed by some calls that have spilled args
1077 // So reset it before we call each such method
1078 //mcInfo.popAllTempValues(TM);
1082 if (TM.getInstrInfo().isCall(OpCode))
1083 MRI.colorCallArgs(CRMI, LRI, AI, *this);
1084 else if (TM.getInstrInfo().isReturn(OpCode))
1085 MRI.colorRetValue( CRMI, LRI, AI );
1087 assert(0 && "Non Call/Ret instrn in CallRetInstrList\n");
1093 //----------------------------------------------------------------------------
1095 //----------------------------------------------------------------------------
1096 void PhyRegAlloc::colorIncomingArgs()
1098 const BasicBlock *const FirstBB = Meth->front();
1099 const MachineInstr *FirstMI = FirstBB->getMachineInstrVec().front();
1100 assert(FirstMI && "No machine instruction in entry BB");
1102 AddedInstrns *AI = AddedInstrMap[FirstMI];
1104 AddedInstrMap[FirstMI] = AI = new AddedInstrns();
1106 MRI.colorMethodArgs(Meth, LRI, AI);
1110 //----------------------------------------------------------------------------
1111 // Used to generate a label for a basic block
1112 //----------------------------------------------------------------------------
1113 void PhyRegAlloc::printLabel(const Value *const Val) {
1115 cerr << Val->getName();
1117 cerr << "Label" << Val;
1121 //----------------------------------------------------------------------------
1122 // This method calls setSugColorUsable method of each live range. This
1123 // will determine whether the suggested color of LR is really usable.
1124 // A suggested color is not usable when the suggested color is volatile
1125 // AND when there are call interferences
1126 //----------------------------------------------------------------------------
1128 void PhyRegAlloc::markUnusableSugColors()
1130 if(DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
1132 // hash map iterator
1133 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1134 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1136 for(; HMI != HMIEnd ; ++HMI ) {
1138 LiveRange *L = HMI->second; // get the LiveRange
1140 if(L->hasSuggestedColor()) {
1141 int RCID = L->getRegClass()->getID();
1142 if( MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1143 L->isCallInterference() )
1144 L->setSuggestedColorUsable( false );
1146 L->setSuggestedColorUsable( true );
1148 } // if L->hasSuggestedColor()
1150 } // for all LR's in hash map
1155 //----------------------------------------------------------------------------
1156 // The following method will set the stack offsets of the live ranges that
1157 // are decided to be spillled. This must be called just after coloring the
1158 // LRs using the graph coloring algo. For each live range that is spilled,
1159 // this method allocate a new spill position on the stack.
1160 //----------------------------------------------------------------------------
1162 void PhyRegAlloc::allocateStackSpace4SpilledLRs()
1164 if(DEBUG_RA ) cerr << "\nsetting LR stack offsets ...\n";
1166 // hash map iterator
1167 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1168 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1170 for( ; HMI != HMIEnd ; ++HMI ) {
1171 if(HMI->first && HMI->second) {
1172 LiveRange *L = HMI->second; // get the LiveRange
1173 if( ! L->hasColor() )
1174 // NOTE: ** allocating the size of long Type **
1175 L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
1177 } // for all LR's in hash map
1182 //----------------------------------------------------------------------------
1183 // The entry pont to Register Allocation
1184 //----------------------------------------------------------------------------
1186 void PhyRegAlloc::allocateRegisters()
1189 // make sure that we put all register classes into the RegClassList
1190 // before we call constructLiveRanges (now done in the constructor of
1191 // PhyRegAlloc class).
1193 LRI.constructLiveRanges(); // create LR info
1196 LRI.printLiveRanges();
1198 createIGNodeListsAndIGs(); // create IGNode list and IGs
1200 buildInterferenceGraphs(); // build IGs in all reg classes
1204 // print all LRs in all reg classes
1205 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1206 RegClassList[ rc ]->printIGNodeList();
1208 // print IGs in all register classes
1209 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1210 RegClassList[ rc ]->printIG();
1214 LRI.coalesceLRs(); // coalesce all live ranges
1218 // print all LRs in all reg classes
1219 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1220 RegClassList[ rc ]->printIGNodeList();
1222 // print IGs in all register classes
1223 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1224 RegClassList[ rc ]->printIG();
1228 // mark un-usable suggested color before graph coloring algorithm.
1229 // When this is done, the graph coloring algo will not reserve
1230 // suggested color unnecessarily - they can be used by another LR
1232 markUnusableSugColors();
1234 // color all register classes using the graph coloring algo
1235 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1236 RegClassList[ rc ]->colorAllRegs();
1238 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1239 // a poistion for such spilled LRs
1241 allocateStackSpace4SpilledLRs();
1243 mcInfo.popAllTempValues(TM); // TODO **Check
1245 // color incoming args - if the correct color was not received
1246 // insert code to copy to the correct register
1248 colorIncomingArgs();
1250 // Now update the machine code with register names and add any
1251 // additional code inserted by the register allocator to the instruction
1254 updateMachineCode();
1257 MachineCodeForMethod::get(Meth).dump();
1258 printMachineCode(); // only for DEBUGGING