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"
20 #include "llvm/Method.h"
26 // ***TODO: There are several places we add instructions. Validate the order
27 // of adding these instructions.
29 cl::Enum<RegAllocDebugLevel_t> DEBUG_RA("dregalloc", cl::NoFlags,
30 "enable register allocation debugging information",
31 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
32 clEnumValN(RA_DEBUG_Normal , "y", "enable debug output"),
33 clEnumValN(RA_DEBUG_Verbose, "v", "enable extra debug output"), 0);
36 //----------------------------------------------------------------------------
37 // RegisterAllocation pass front end...
38 //----------------------------------------------------------------------------
40 class RegisterAllocator : public MethodPass {
41 TargetMachine &Target;
43 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
45 bool runOnMethod(Method *M) {
47 cerr << "\n******************** Method "<< M->getName()
48 << " ********************\n";
50 MethodLiveVarInfo LVI(M); // Analyze live varaibles
53 PhyRegAlloc PRA(M, Target, &LVI); // allocate registers
54 PRA.allocateRegisters();
56 if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
62 MethodPass *getRegisterAllocator(TargetMachine &T) {
63 return new RegisterAllocator(T);
66 //----------------------------------------------------------------------------
67 // Constructor: Init local composite objects and create register classes.
68 //----------------------------------------------------------------------------
69 PhyRegAlloc::PhyRegAlloc(Method *M,
70 const TargetMachine& tm,
71 MethodLiveVarInfo *const Lvi)
73 mcInfo(MachineCodeForMethod::get(M)),
74 LVI(Lvi), LRI(M, tm, RegClassList),
75 MRI( tm.getRegInfo() ),
76 NumOfRegClasses(MRI.getNumOfRegClasses()),
79 // create each RegisterClass and put in RegClassList
81 for(unsigned int rc=0; rc < NumOfRegClasses; rc++)
82 RegClassList.push_back( new RegClass(M, MRI.getMachineRegClass(rc),
87 //----------------------------------------------------------------------------
88 // Destructor: Deletes register classes
89 //----------------------------------------------------------------------------
90 PhyRegAlloc::~PhyRegAlloc() {
91 for( unsigned int rc=0; rc < NumOfRegClasses; rc++)
92 delete RegClassList[rc];
95 //----------------------------------------------------------------------------
96 // This method initally creates interference graphs (one in each reg class)
97 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
98 //----------------------------------------------------------------------------
99 void PhyRegAlloc::createIGNodeListsAndIGs() {
100 if (DEBUG_RA) cerr << "Creating LR lists ...\n";
103 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
106 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
108 for (; HMI != HMIEnd ; ++HMI ) {
110 LiveRange *L = HMI->second; // get the LiveRange
113 cerr << "\n*?!?Warning: Null liver range found for: ";
114 printValue(HMI->first); cerr << "\n";
118 // if the Value * is not null, and LR
119 // is not yet written to the IGNodeList
120 if( !(L->getUserIGNode()) ) {
121 RegClass *const RC = // RegClass of first value in the LR
122 RegClassList[ L->getRegClass()->getID() ];
124 RC->addLRToIG(L); // add this LR to an IG
130 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
131 RegClassList[rc]->createInterferenceGraph();
134 cerr << "LRLists Created!\n";
140 //----------------------------------------------------------------------------
141 // This method will add all interferences at for a given instruction.
142 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
143 // class as that of live var. The live var passed to this function is the
144 // LVset AFTER the instruction
145 //----------------------------------------------------------------------------
146 void PhyRegAlloc::addInterference(const Value *const Def,
147 const LiveVarSet *const LVSet,
148 const bool isCallInst) {
150 LiveVarSet::const_iterator LIt = LVSet->begin();
152 // get the live range of instruction
154 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
156 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
157 assert( IGNodeOfDef );
159 RegClass *const RCOfDef = LROfDef->getRegClass();
161 // for each live var in live variable set
163 for( ; LIt != LVSet->end(); ++LIt) {
166 cerr << "< Def="; printValue(Def);
167 cerr << ", Lvar="; printValue( *LIt); cerr << "> ";
170 // get the live range corresponding to live var
172 LiveRange *const LROfVar = LRI.getLiveRangeForValue(*LIt );
174 // LROfVar can be null if it is a const since a const
175 // doesn't have a dominating def - see Assumptions above
178 if(LROfDef == LROfVar) // do not set interf for same LR
181 // if 2 reg classes are the same set interference
183 if(RCOfDef == LROfVar->getRegClass()) {
184 RCOfDef->setInterference( LROfDef, LROfVar);
185 } else if(DEBUG_RA > 1) {
186 // we will not have LRs for values not explicitly allocated in the
187 // instruction stream (e.g., constants)
188 cerr << " warning: no live range for " ;
189 printValue(*LIt); cerr << "\n";
197 //----------------------------------------------------------------------------
198 // For a call instruction, this method sets the CallInterference flag in
199 // the LR of each variable live int the Live Variable Set live after the
200 // call instruction (except the return value of the call instruction - since
201 // the return value does not interfere with that call itself).
202 //----------------------------------------------------------------------------
204 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
205 const LiveVarSet *const LVSetAft ) {
207 // Now find the LR of the return value of the call
208 // We do this because, we look at the LV set *after* the instruction
209 // to determine, which LRs must be saved across calls. The return value
210 // of the call is live in this set - but it does not interfere with call
211 // (i.e., we can allocate a volatile register to the return value)
213 LiveRange *RetValLR = NULL;
214 const Value *RetVal = MRI.getCallInstRetVal( MInst );
217 RetValLR = LRI.getLiveRangeForValue( RetVal );
218 assert( RetValLR && "No LR for RetValue of call");
222 cerr << "\n For call inst: " << *MInst;
224 LiveVarSet::const_iterator LIt = LVSetAft->begin();
226 // for each live var in live variable set after machine inst
228 for( ; LIt != LVSetAft->end(); ++LIt) {
230 // get the live range corresponding to live var
232 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
234 if( LR && DEBUG_RA) {
235 cerr << "\n\tLR Aft Call: ";
240 // LR can be null if it is a const since a const
241 // doesn't have a dominating def - see Assumptions above
243 if( LR && (LR != RetValLR) ) {
244 LR->setCallInterference();
246 cerr << "\n ++Added call interf for LR: " ;
258 //----------------------------------------------------------------------------
259 // This method will walk thru code and create interferences in the IG of
260 // each RegClass. Also, this method calculates the spill cost of each
261 // Live Range (it is done in this method to save another pass over the code).
262 //----------------------------------------------------------------------------
263 void PhyRegAlloc::buildInterferenceGraphs()
266 if(DEBUG_RA) cerr << "Creating interference graphs ...\n";
268 unsigned BBLoopDepthCost;
269 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
271 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
273 // find the 10^(loop_depth) of this BB
275 BBLoopDepthCost = (unsigned) pow( 10.0, LoopDepthCalc.getLoopDepth(*BBI));
277 // get the iterator for machine instructions
279 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
280 MachineCodeForBasicBlock::const_iterator
281 MInstIterator = MIVec.begin();
283 // iterate over all the machine instructions in BB
285 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
287 const MachineInstr * MInst = *MInstIterator;
289 // get the LV set after the instruction
291 const LiveVarSet *const LVSetAI =
292 LVI->getLiveVarSetAfterMInst(MInst, *BBI);
294 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
297 // set the isCallInterference flag of each live range wich extends
298 // accross this call instruction. This information is used by graph
299 // coloring algo to avoid allocating volatile colors to live ranges
300 // that span across calls (since they have to be saved/restored)
302 setCallInterferences( MInst, LVSetAI);
306 // iterate over all MI operands to find defs
308 for( MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done(); ++OpI) {
311 // create a new LR iff this operand is a def
313 addInterference(*OpI, LVSetAI, isCallInst );
316 // Calculate the spill cost of each live range
318 LiveRange *LR = LRI.getLiveRangeForValue( *OpI );
320 LR->addSpillCost(BBLoopDepthCost);
324 // if there are multiple defs in this instruction e.g. in SETX
326 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
327 addInterf4PseudoInstr(MInst);
330 // Also add interference for any implicit definitions in a machine
331 // instr (currently, only calls have this).
333 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
334 if( NumOfImpRefs > 0 ) {
335 for(unsigned z=0; z < NumOfImpRefs; z++)
336 if( MInst->implicitRefIsDefined(z) )
337 addInterference( MInst->getImplicitRef(z), LVSetAI, isCallInst );
341 } // for all machine instructions in BB
343 } // for all BBs in method
346 // add interferences for method arguments. Since there are no explict
347 // defs in method for args, we have to add them manually
349 addInterferencesForArgs();
352 cerr << "Interference graphs calculted!\n";
358 //--------------------------------------------------------------------------
359 // Pseudo instructions will be exapnded to multiple instructions by the
360 // assembler. Consequently, all the opernds must get distinct registers.
361 // Therefore, we mark all operands of a pseudo instruction as they interfere
363 //--------------------------------------------------------------------------
364 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
366 bool setInterf = false;
368 // iterate over MI operands to find defs
370 for( MachineInstr::val_const_op_iterator It1(MInst);!It1.done(); ++It1) {
372 const LiveRange *const LROfOp1 = LRI.getLiveRangeForValue( *It1 );
374 if( !LROfOp1 && It1.isDef() )
375 assert( 0 && "No LR for Def in PSEUDO insruction");
377 MachineInstr::val_const_op_iterator It2 = It1;
380 for( ; !It2.done(); ++It2) {
382 const LiveRange *const LROfOp2 = LRI.getLiveRangeForValue( *It2 );
386 RegClass *const RCOfOp1 = LROfOp1->getRegClass();
387 RegClass *const RCOfOp2 = LROfOp2->getRegClass();
389 if( RCOfOp1 == RCOfOp2 ){
390 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
396 } // for all other defs in machine instr
398 } // for all operands in an instruction
400 if( !setInterf && (MInst->getNumOperands() > 2) ) {
401 cerr << "\nInterf not set for any operand in pseudo instr:\n";
403 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
411 //----------------------------------------------------------------------------
412 // This method will add interferences for incoming arguments to a method.
413 //----------------------------------------------------------------------------
414 void PhyRegAlloc::addInterferencesForArgs()
416 // get the InSet of root BB
417 const LiveVarSet *const InSet = LVI->getInSetOfBB( Meth->front() );
419 // get the argument list
420 const Method::ArgumentListType& ArgList = Meth->getArgumentList();
422 // get an iterator to arg list
423 Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();
426 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
427 addInterference((Value*)*ArgIt, InSet, false); // add interferences between
428 // args and LVars at start
430 cerr << " - %% adding interference for argument ";
431 printValue((const Value *)*ArgIt); cerr << "\n";
439 //----------------------------------------------------------------------------
440 // This method is called after register allocation is complete to set the
441 // allocated reisters in the machine code. This code will add register numbers
442 // to MachineOperands that contain a Value. Also it calls target specific
443 // methods to produce caller saving instructions. At the end, it adds all
444 // additional instructions produced by the register allocator to the
445 // instruction stream.
446 //----------------------------------------------------------------------------
447 void PhyRegAlloc::updateMachineCode()
450 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
452 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
454 // get the iterator for machine instructions
456 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
457 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
459 // iterate over all the machine instructions in BB
461 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
463 MachineInstr *MInst = *MInstIterator;
465 unsigned Opcode = MInst->getOpCode();
467 // do not process Phis
468 if (TM.getInstrInfo().isPhi(Opcode))
471 // Now insert speical instructions (if necessary) for call/return
474 if (TM.getInstrInfo().isCall(Opcode) ||
475 TM.getInstrInfo().isReturn(Opcode)) {
477 AddedInstrns *AI = AddedInstrMap[ MInst];
479 AI = new AddedInstrns();
480 AddedInstrMap[ MInst ] = AI;
483 // Tmp stack poistions are needed by some calls that have spilled args
484 // So reset it before we call each such method
486 mcInfo.popAllTempValues(TM);
488 if (TM.getInstrInfo().isCall(Opcode))
489 MRI.colorCallArgs(MInst, LRI, AI, *this, *BBI);
490 else if (TM.getInstrInfo().isReturn(Opcode))
491 MRI.colorRetValue(MInst, LRI, AI);
495 /* -- Using above code instead of this
497 // if this machine instr is call, insert caller saving code
499 if( (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
500 MRI.insertCallerSavingCode(MInst, *BBI, *this );
505 // reset the stack offset for temporary variables since we may
506 // need that to spill
507 // mcInfo.popAllTempValues(TM);
508 // TODO ** : do later
510 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
513 // Now replace set the registers for operands in the machine instruction
515 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
517 MachineOperand& Op = MInst->getOperand(OpNum);
519 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
520 Op.getOperandType() == MachineOperand::MO_CCRegister) {
522 const Value *const Val = Op.getVRegValue();
524 // delete this condition checking later (must assert if Val is null)
527 cerr << "Warning: NULL Value found for operand\n";
530 assert( Val && "Value is NULL");
532 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
536 // nothing to worry if it's a const or a label
539 cerr << "*NO LR for operand : " << Op ;
540 cerr << " [reg:" << Op.getAllocatedRegNum() << "]";
541 cerr << " in inst:\t" << *MInst << "\n";
544 // if register is not allocated, mark register as invalid
545 if( Op.getAllocatedRegNum() == -1)
546 Op.setRegForValue( MRI.getInvalidRegNum());
552 unsigned RCID = (LR->getRegClass())->getID();
554 if( LR->hasColor() ) {
555 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
559 // LR did NOT receive a color (register). Now, insert spill code
560 // for spilled opeands in this machine instruction
562 //assert(0 && "LR must be spilled");
563 insertCode4SpilledLR(LR, MInst, *BBI, OpNum );
568 } // for each operand
571 // Now add instructions that the register allocator inserts before/after
572 // this machine instructions (done only for calls/rets/incoming args)
573 // We do this here, to ensure that spill for an instruction is inserted
574 // closest as possible to an instruction (see above insertCode4Spill...)
576 // If there are instructions to be added, *before* this machine
577 // instruction, add them now.
579 if( AddedInstrMap[ MInst ] ) {
580 std::deque<MachineInstr *> &IBef = AddedInstrMap[MInst]->InstrnsBefore;
582 if( ! IBef.empty() ) {
583 std::deque<MachineInstr *>::iterator AdIt;
585 for( AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt ) {
588 cerr << "For inst " << *MInst;
589 cerr << " PREPENDed instr: " << **AdIt << "\n";
592 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
600 // If there are instructions to be added *after* this machine
601 // instruction, add them now
603 if(AddedInstrMap[MInst] &&
604 !AddedInstrMap[MInst]->InstrnsAfter.empty() ) {
606 // if there are delay slots for this instruction, the instructions
607 // added after it must really go after the delayed instruction(s)
608 // So, we move the InstrAfter of the current instruction to the
609 // corresponding delayed instruction
612 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
613 move2DelayedInstr(MInst, *(MInstIterator+delay) );
615 if(DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
621 // Here we can add the "instructions after" to the current
622 // instruction since there are no delay slots for this instruction
624 std::deque<MachineInstr *> &IAft = AddedInstrMap[MInst]->InstrnsAfter;
626 if( ! IAft.empty() ) {
628 std::deque<MachineInstr *>::iterator AdIt;
630 ++MInstIterator; // advance to the next instruction
632 for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
635 cerr << "For inst " << *MInst;
636 cerr << " APPENDed instr: " << **AdIt << "\n";
639 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
643 // MInsterator already points to the next instr. Since the
644 // for loop also increments it, decrement it to point to the
645 // instruction added last
654 } // for each machine instruction
660 //----------------------------------------------------------------------------
661 // This method inserts spill code for AN operand whose LR was spilled.
662 // This method may be called several times for a single machine instruction
663 // if it contains many spilled operands. Each time it is called, it finds
664 // a register which is not live at that instruction and also which is not
665 // used by other spilled operands of the same instruction. Then it uses
666 // this register temporarily to accomodate the spilled value.
667 //----------------------------------------------------------------------------
668 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
670 const BasicBlock *BB,
671 const unsigned OpNum) {
673 assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
674 (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
675 "Arg of a call/ret must be handled elsewhere");
677 MachineOperand& Op = MInst->getOperand(OpNum);
678 bool isDef = MInst->operandIsDefined(OpNum);
679 unsigned RegType = MRI.getRegType( LR );
680 int SpillOff = LR->getSpillOffFromFP();
681 RegClass *RC = LR->getRegClass();
682 const LiveVarSet *LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
684 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
686 MachineInstr *MIBef=NULL, *AdIMid=NULL, *MIAft=NULL;
688 int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,LVSetBef, MIBef, MIAft);
690 // get the added instructions for this instruciton
691 AddedInstrns *AI = AddedInstrMap[ MInst ];
693 AI = new AddedInstrns();
694 AddedInstrMap[ MInst ] = AI;
700 // for a USE, we have to load the value of LR from stack to a TmpReg
701 // and use the TmpReg as one operand of instruction
703 // actual loading instruction
704 AdIMid = MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType);
707 AI->InstrnsBefore.push_back(MIBef);
709 AI->InstrnsBefore.push_back(AdIMid);
712 AI->InstrnsAfter.push_front(MIAft);
716 else { // if this is a Def
718 // for a DEF, we have to store the value produced by this instruction
719 // on the stack position allocated for this LR
721 // actual storing instruction
722 AdIMid = MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType);
725 AI->InstrnsBefore.push_back(MIBef);
727 AI->InstrnsAfter.push_front(AdIMid);
730 AI->InstrnsAfter.push_front(MIAft);
734 cerr << "\nFor Inst " << *MInst;
735 cerr << " - SPILLED LR: "; LR->printSet();
736 cerr << "\n - Added Instructions:";
737 if( MIBef ) cerr << *MIBef;
739 if( MIAft ) cerr << *MIAft;
741 Op.setRegForValue( TmpRegU ); // set the opearnd
751 //----------------------------------------------------------------------------
752 // We can use the following method to get a temporary register to be used
753 // BEFORE any given machine instruction. If there is a register available,
754 // this method will simply return that register and set MIBef = MIAft = NULL.
755 // Otherwise, it will return a register and MIAft and MIBef will contain
756 // two instructions used to free up this returned register.
757 // Returned register number is the UNIFIED register number
758 //----------------------------------------------------------------------------
760 int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC,
762 const MachineInstr *MInst,
763 const LiveVarSet *LVSetBef,
765 MachineInstr *MIAft) {
767 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
771 // we found an unused register, so we can simply use it
772 MIBef = MIAft = NULL;
775 // we couldn't find an unused register. Generate code to free up a reg by
776 // saving it on stack and restoring after the instruction
778 int TmpOff = mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
780 RegU = getUniRegNotUsedByThisInst(RC, MInst);
781 MIBef = MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType );
782 MIAft = MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType );
788 //----------------------------------------------------------------------------
789 // This method is called to get a new unused register that can be used to
790 // accomodate a spilled value.
791 // This method may be called several times for a single machine instruction
792 // if it contains many spilled operands. Each time it is called, it finds
793 // a register which is not live at that instruction and also which is not
794 // used by other spilled operands of the same instruction.
795 // Return register number is relative to the register class. NOT
797 //----------------------------------------------------------------------------
798 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
799 const MachineInstr *MInst,
800 const LiveVarSet *LVSetBef) {
802 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
804 bool *IsColorUsedArr = RC->getIsColorUsedArr();
806 for(unsigned i=0; i < NumAvailRegs; i++) // Reset array
807 IsColorUsedArr[i] = false;
809 LiveVarSet::const_iterator LIt = LVSetBef->begin();
811 // for each live var in live variable set after machine inst
812 for( ; LIt != LVSetBef->end(); ++LIt) {
814 // get the live range corresponding to live var
815 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
817 // LR can be null if it is a const since a const
818 // doesn't have a dominating def - see Assumptions above
820 if( LRofLV->hasColor() )
821 IsColorUsedArr[ LRofLV->getColor() ] = true;
824 // It is possible that one operand of this MInst was already spilled
825 // and it received some register temporarily. If that's the case,
826 // it is recorded in machine operand. We must skip such registers.
828 setRelRegsUsedByThisInst(RC, MInst);
830 unsigned c; // find first unused color
831 for( c=0; c < NumAvailRegs; c++)
832 if( ! IsColorUsedArr[ c ] ) break;
835 return MRI.getUnifiedRegNum(RC->getID(), c);
843 //----------------------------------------------------------------------------
844 // Get any other register in a register class, other than what is used
845 // by operands of a machine instruction. Returns the unified reg number.
846 //----------------------------------------------------------------------------
847 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
848 const MachineInstr *MInst) {
850 bool *IsColorUsedArr = RC->getIsColorUsedArr();
851 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
854 for(unsigned i=0; i < NumAvailRegs ; i++) // Reset array
855 IsColorUsedArr[i] = false;
857 setRelRegsUsedByThisInst(RC, MInst);
859 unsigned c; // find first unused color
860 for( c=0; c < RC->getNumOfAvailRegs(); c++)
861 if( ! IsColorUsedArr[ c ] ) break;
864 return MRI.getUnifiedRegNum(RC->getID(), c);
866 assert( 0 && "FATAL: No free register could be found in reg class!!");
871 //----------------------------------------------------------------------------
872 // This method modifies the IsColorUsedArr of the register class passed to it.
873 // It sets the bits corresponding to the registers used by this machine
874 // instructions. Both explicit and implicit operands are set.
875 //----------------------------------------------------------------------------
876 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
877 const MachineInstr *MInst ) {
879 bool *IsColorUsedArr = RC->getIsColorUsedArr();
881 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
883 const MachineOperand& Op = MInst->getOperand(OpNum);
885 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
886 Op.getOperandType() == MachineOperand::MO_CCRegister ) {
888 const Value *const Val = Op.getVRegValue();
891 if( MRI.getRegClassIDOfValue(Val) == RC->getID() ) {
893 if( (Reg=Op.getAllocatedRegNum()) != -1) {
894 IsColorUsedArr[ Reg ] = true;
897 // it is possilbe that this operand still is not marked with
898 // a register but it has a LR and that received a color
900 LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
902 if( LROfVal->hasColor() )
903 IsColorUsedArr[ LROfVal->getColor() ] = true;
906 } // if reg classes are the same
908 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
909 IsColorUsedArr[ Op.getMachineRegNum() ] = true;
913 // If there are implicit references, mark them as well
915 for(unsigned z=0; z < MInst->getNumImplicitRefs(); z++) {
917 LiveRange *const LRofImpRef =
918 LRI.getLiveRangeForValue( MInst->getImplicitRef(z) );
920 if(LRofImpRef && LRofImpRef->hasColor())
921 IsColorUsedArr[LRofImpRef->getColor()] = true;
932 //----------------------------------------------------------------------------
933 // If there are delay slots for an instruction, the instructions
934 // added after it must really go after the delayed instruction(s).
935 // So, we move the InstrAfter of that instruction to the
936 // corresponding delayed instruction using the following method.
938 //----------------------------------------------------------------------------
939 void PhyRegAlloc:: move2DelayedInstr(const MachineInstr *OrigMI,
940 const MachineInstr *DelayedMI) {
942 // "added after" instructions of the original instr
943 std::deque<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI]->InstrnsAfter;
945 // "added instructions" of the delayed instr
946 AddedInstrns *DelayAdI = AddedInstrMap[DelayedMI];
948 if(! DelayAdI ) { // create a new "added after" if necessary
949 DelayAdI = new AddedInstrns();
950 AddedInstrMap[DelayedMI] = DelayAdI;
953 // "added after" instructions of the delayed instr
954 std::deque<MachineInstr *> &DelayedAft = DelayAdI->InstrnsAfter;
956 // go thru all the "added after instructions" of the original instruction
957 // and append them to the "addded after instructions" of the delayed
959 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
961 // empty the "added after instructions" of the original instruction
965 //----------------------------------------------------------------------------
966 // This method prints the code with registers after register allocation is
968 //----------------------------------------------------------------------------
969 void PhyRegAlloc::printMachineCode()
972 cerr << "\n;************** Method " << Meth->getName()
973 << " *****************\n";
975 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
977 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
979 cerr << "\n"; printLabel( *BBI); cerr << ": ";
981 // get the iterator for machine instructions
982 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
983 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
985 // iterate over all the machine instructions in BB
986 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
988 MachineInstr *const MInst = *MInstIterator;
992 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
995 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
997 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
999 MachineOperand& Op = MInst->getOperand(OpNum);
1001 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
1002 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
1003 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
1005 const Value *const Val = Op.getVRegValue () ;
1006 // ****this code is temporary till NULL Values are fixed
1008 cerr << "\t<*NULL*>";
1012 // if a label or a constant
1013 if(isa<BasicBlock>(Val)) {
1014 cerr << "\t"; printLabel( Op.getVRegValue () );
1016 // else it must be a register value
1017 const int RegNum = Op.getAllocatedRegNum();
1019 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
1020 if (Val->hasName() )
1021 cerr << "(" << Val->getName() << ")";
1023 cerr << "(" << Val << ")";
1028 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
1030 if( LROfVal->hasSpillOffset() )
1035 else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
1036 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1040 cerr << "\t" << Op; // use dump field
1045 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1046 if( NumOfImpRefs > 0 ) {
1048 cerr << "\tImplicit:";
1050 for(unsigned z=0; z < NumOfImpRefs; z++) {
1051 printValue( MInst->getImplicitRef(z) );
1057 } // for all machine instructions
1069 //----------------------------------------------------------------------------
1071 //----------------------------------------------------------------------------
1073 void PhyRegAlloc::colorCallRetArgs()
1076 CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
1077 CallRetInstrListType::const_iterator It = CallRetInstList.begin();
1079 for( ; It != CallRetInstList.end(); ++It ) {
1081 const MachineInstr *const CRMI = *It;
1082 unsigned OpCode = CRMI->getOpCode();
1084 // get the added instructions for this Call/Ret instruciton
1085 AddedInstrns *AI = AddedInstrMap[ CRMI ];
1087 AI = new AddedInstrns();
1088 AddedInstrMap[ CRMI ] = AI;
1091 // Tmp stack poistions are needed by some calls that have spilled args
1092 // So reset it before we call each such method
1093 //mcInfo.popAllTempValues(TM);
1097 if (TM.getInstrInfo().isCall(OpCode))
1098 MRI.colorCallArgs(CRMI, LRI, AI, *this);
1099 else if (TM.getInstrInfo().isReturn(OpCode))
1100 MRI.colorRetValue( CRMI, LRI, AI );
1102 assert(0 && "Non Call/Ret instrn in CallRetInstrList\n");
1108 //----------------------------------------------------------------------------
1110 //----------------------------------------------------------------------------
1111 void PhyRegAlloc::colorIncomingArgs()
1113 const BasicBlock *const FirstBB = Meth->front();
1114 const MachineInstr *FirstMI = FirstBB->getMachineInstrVec().front();
1115 assert(FirstMI && "No machine instruction in entry BB");
1117 AddedInstrns *AI = AddedInstrMap[FirstMI];
1119 AddedInstrMap[FirstMI] = AI = new AddedInstrns();
1121 MRI.colorMethodArgs(Meth, LRI, AI);
1125 //----------------------------------------------------------------------------
1126 // Used to generate a label for a basic block
1127 //----------------------------------------------------------------------------
1128 void PhyRegAlloc::printLabel(const Value *const Val) {
1130 cerr << Val->getName();
1132 cerr << "Label" << Val;
1136 //----------------------------------------------------------------------------
1137 // This method calls setSugColorUsable method of each live range. This
1138 // will determine whether the suggested color of LR is really usable.
1139 // A suggested color is not usable when the suggested color is volatile
1140 // AND when there are call interferences
1141 //----------------------------------------------------------------------------
1143 void PhyRegAlloc::markUnusableSugColors()
1145 if(DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
1147 // hash map iterator
1148 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1149 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1151 for(; HMI != HMIEnd ; ++HMI ) {
1153 LiveRange *L = HMI->second; // get the LiveRange
1155 if(L->hasSuggestedColor()) {
1156 int RCID = L->getRegClass()->getID();
1157 if( MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1158 L->isCallInterference() )
1159 L->setSuggestedColorUsable( false );
1161 L->setSuggestedColorUsable( true );
1163 } // if L->hasSuggestedColor()
1165 } // for all LR's in hash map
1170 //----------------------------------------------------------------------------
1171 // The following method will set the stack offsets of the live ranges that
1172 // are decided to be spillled. This must be called just after coloring the
1173 // LRs using the graph coloring algo. For each live range that is spilled,
1174 // this method allocate a new spill position on the stack.
1175 //----------------------------------------------------------------------------
1177 void PhyRegAlloc::allocateStackSpace4SpilledLRs()
1179 if(DEBUG_RA ) cerr << "\nsetting LR stack offsets ...\n";
1181 // hash map iterator
1182 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1183 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1185 for( ; HMI != HMIEnd ; ++HMI ) {
1186 if(HMI->first && HMI->second) {
1187 LiveRange *L = HMI->second; // get the LiveRange
1188 if( ! L->hasColor() )
1189 // NOTE: ** allocating the size of long Type **
1190 L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
1192 } // for all LR's in hash map
1197 //----------------------------------------------------------------------------
1198 // The entry pont to Register Allocation
1199 //----------------------------------------------------------------------------
1201 void PhyRegAlloc::allocateRegisters()
1204 // make sure that we put all register classes into the RegClassList
1205 // before we call constructLiveRanges (now done in the constructor of
1206 // PhyRegAlloc class).
1208 LRI.constructLiveRanges(); // create LR info
1211 LRI.printLiveRanges();
1213 createIGNodeListsAndIGs(); // create IGNode list and IGs
1215 buildInterferenceGraphs(); // build IGs in all reg classes
1219 // print all LRs in all reg classes
1220 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1221 RegClassList[ rc ]->printIGNodeList();
1223 // print IGs in all register classes
1224 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1225 RegClassList[ rc ]->printIG();
1229 LRI.coalesceLRs(); // coalesce all live ranges
1233 // print all LRs in all reg classes
1234 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1235 RegClassList[ rc ]->printIGNodeList();
1237 // print IGs in all register classes
1238 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1239 RegClassList[ rc ]->printIG();
1243 // mark un-usable suggested color before graph coloring algorithm.
1244 // When this is done, the graph coloring algo will not reserve
1245 // suggested color unnecessarily - they can be used by another LR
1247 markUnusableSugColors();
1249 // color all register classes using the graph coloring algo
1250 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1251 RegClassList[ rc ]->colorAllRegs();
1253 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1254 // a poistion for such spilled LRs
1256 allocateStackSpace4SpilledLRs();
1258 mcInfo.popAllTempValues(TM); // TODO **Check
1260 // color incoming args - if the correct color was not received
1261 // insert code to copy to the correct register
1263 colorIncomingArgs();
1265 // Now update the machine code with register names and add any
1266 // additional code inserted by the register allocator to the instruction
1269 updateMachineCode();
1272 MachineCodeForMethod::get(Meth).dump();
1273 printMachineCode(); // only for DEBUGGING