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/Analysis/LiveVar/LiveVarSet.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include "llvm/Target/MachineFrameInfo.h"
22 #include "llvm/Method.h"
28 // ***TODO: There are several places we add instructions. Validate the order
29 // of adding these instructions.
31 cl::Enum<RegAllocDebugLevel_t> DEBUG_RA("dregalloc", cl::NoFlags,
32 "enable register allocation debugging information",
33 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
34 clEnumValN(RA_DEBUG_Normal , "y", "enable debug output"),
35 clEnumValN(RA_DEBUG_Verbose, "v", "enable extra debug output"), 0);
38 //----------------------------------------------------------------------------
39 // RegisterAllocation pass front end...
40 //----------------------------------------------------------------------------
42 class RegisterAllocator : public MethodPass {
43 TargetMachine &Target;
45 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
47 bool runOnMethod(Method *M) {
49 cerr << "\n******************** Method "<< M->getName()
50 << " ********************\n";
52 PhyRegAlloc PRA(M, Target, &getAnalysis<MethodLiveVarInfo>(),
53 &getAnalysis<cfg::LoopInfo>());
54 PRA.allocateRegisters();
56 if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
60 virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Requires,
61 Pass::AnalysisSet &Destroyed,
62 Pass::AnalysisSet &Provided) {
63 Requires.push_back(cfg::LoopInfo::ID);
64 Requires.push_back(MethodLiveVarInfo::ID);
69 MethodPass *getRegisterAllocator(TargetMachine &T) {
70 return new RegisterAllocator(T);
73 //----------------------------------------------------------------------------
74 // Constructor: Init local composite objects and create register classes.
75 //----------------------------------------------------------------------------
76 PhyRegAlloc::PhyRegAlloc(Method *M,
77 const TargetMachine& tm,
78 MethodLiveVarInfo *Lvi,
81 mcInfo(MachineCodeForMethod::get(M)),
82 LVI(Lvi), LRI(M, tm, RegClassList),
83 MRI( tm.getRegInfo() ),
84 NumOfRegClasses(MRI.getNumOfRegClasses()),
87 // create each RegisterClass and put in RegClassList
89 for(unsigned int rc=0; rc < NumOfRegClasses; rc++)
90 RegClassList.push_back( new RegClass(M, MRI.getMachineRegClass(rc),
95 //----------------------------------------------------------------------------
96 // Destructor: Deletes register classes
97 //----------------------------------------------------------------------------
98 PhyRegAlloc::~PhyRegAlloc() {
99 for( unsigned int rc=0; rc < NumOfRegClasses; rc++)
100 delete RegClassList[rc];
103 //----------------------------------------------------------------------------
104 // This method initally creates interference graphs (one in each reg class)
105 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
106 //----------------------------------------------------------------------------
107 void PhyRegAlloc::createIGNodeListsAndIGs() {
108 if (DEBUG_RA) cerr << "Creating LR lists ...\n";
111 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
114 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
116 for (; HMI != HMIEnd ; ++HMI ) {
118 LiveRange *L = HMI->second; // get the LiveRange
121 cerr << "\n*?!?Warning: Null liver range found for: "
122 << RAV(HMI->first) << "\n";
126 // if the Value * is not null, and LR
127 // is not yet written to the IGNodeList
128 if( !(L->getUserIGNode()) ) {
129 RegClass *const RC = // RegClass of first value in the LR
130 RegClassList[ L->getRegClass()->getID() ];
132 RC->addLRToIG(L); // add this LR to an IG
138 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
139 RegClassList[rc]->createInterferenceGraph();
142 cerr << "LRLists Created!\n";
148 //----------------------------------------------------------------------------
149 // This method will add all interferences at for a given instruction.
150 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
151 // class as that of live var. The live var passed to this function is the
152 // LVset AFTER the instruction
153 //----------------------------------------------------------------------------
154 void PhyRegAlloc::addInterference(const Value *const Def,
155 const LiveVarSet *const LVSet,
156 const bool isCallInst) {
158 LiveVarSet::const_iterator LIt = LVSet->begin();
160 // get the live range of instruction
162 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
164 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
165 assert( IGNodeOfDef );
167 RegClass *const RCOfDef = LROfDef->getRegClass();
169 // for each live var in live variable set
171 for( ; LIt != LVSet->end(); ++LIt) {
174 cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
176 // get the live range corresponding to live var
178 LiveRange *LROfVar = LRI.getLiveRangeForValue(*LIt);
180 // LROfVar can be null if it is a const since a const
181 // doesn't have a dominating def - see Assumptions above
184 if(LROfDef == LROfVar) // do not set interf for same LR
187 // if 2 reg classes are the same set interference
189 if (RCOfDef == LROfVar->getRegClass()) {
190 RCOfDef->setInterference( LROfDef, LROfVar);
191 } else if (DEBUG_RA > 1) {
192 // we will not have LRs for values not explicitly allocated in the
193 // instruction stream (e.g., constants)
194 cerr << " warning: no live range for " << RAV(*LIt) << "\n";
202 //----------------------------------------------------------------------------
203 // For a call instruction, this method sets the CallInterference flag in
204 // the LR of each variable live int the Live Variable Set live after the
205 // call instruction (except the return value of the call instruction - since
206 // the return value does not interfere with that call itself).
207 //----------------------------------------------------------------------------
209 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
210 const LiveVarSet *const LVSetAft ) {
212 // Now find the LR of the return value of the call
213 // We do this because, we look at the LV set *after* the instruction
214 // to determine, which LRs must be saved across calls. The return value
215 // of the call is live in this set - but it does not interfere with call
216 // (i.e., we can allocate a volatile register to the return value)
218 LiveRange *RetValLR = NULL;
219 const Value *RetVal = MRI.getCallInstRetVal( MInst );
222 RetValLR = LRI.getLiveRangeForValue( RetVal );
223 assert( RetValLR && "No LR for RetValue of call");
227 cerr << "\n For call inst: " << *MInst;
229 LiveVarSet::const_iterator LIt = LVSetAft->begin();
231 // for each live var in live variable set after machine inst
233 for( ; LIt != LVSetAft->end(); ++LIt) {
235 // get the live range corresponding to live var
237 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
239 if( LR && DEBUG_RA) {
240 cerr << "\n\tLR Aft Call: ";
245 // LR can be null if it is a const since a const
246 // doesn't have a dominating def - see Assumptions above
248 if( LR && (LR != RetValLR) ) {
249 LR->setCallInterference();
251 cerr << "\n ++Added call interf for LR: " ;
263 //----------------------------------------------------------------------------
264 // This method will walk thru code and create interferences in the IG of
265 // each RegClass. Also, this method calculates the spill cost of each
266 // Live Range (it is done in this method to save another pass over the code).
267 //----------------------------------------------------------------------------
268 void PhyRegAlloc::buildInterferenceGraphs()
271 if(DEBUG_RA) cerr << "Creating interference graphs ...\n";
273 unsigned BBLoopDepthCost;
274 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
276 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
278 // find the 10^(loop_depth) of this BB
280 BBLoopDepthCost = (unsigned) pow( 10.0, LoopDepthCalc->getLoopDepth(*BBI));
282 // get the iterator for machine instructions
284 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
285 MachineCodeForBasicBlock::const_iterator
286 MInstIterator = MIVec.begin();
288 // iterate over all the machine instructions in BB
290 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
292 const MachineInstr * MInst = *MInstIterator;
294 // get the LV set after the instruction
296 const LiveVarSet *const LVSetAI =
297 LVI->getLiveVarSetAfterMInst(MInst, *BBI);
299 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
302 // set the isCallInterference flag of each live range wich extends
303 // accross this call instruction. This information is used by graph
304 // coloring algo to avoid allocating volatile colors to live ranges
305 // that span across calls (since they have to be saved/restored)
307 setCallInterferences( MInst, LVSetAI);
311 // iterate over all MI operands to find defs
313 for( MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done(); ++OpI) {
316 // create a new LR iff this operand is a def
318 addInterference(*OpI, LVSetAI, isCallInst );
321 // Calculate the spill cost of each live range
323 LiveRange *LR = LRI.getLiveRangeForValue( *OpI );
325 LR->addSpillCost(BBLoopDepthCost);
329 // if there are multiple defs in this instruction e.g. in SETX
331 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
332 addInterf4PseudoInstr(MInst);
335 // Also add interference for any implicit definitions in a machine
336 // instr (currently, only calls have this).
338 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
339 if( NumOfImpRefs > 0 ) {
340 for(unsigned z=0; z < NumOfImpRefs; z++)
341 if( MInst->implicitRefIsDefined(z) )
342 addInterference( MInst->getImplicitRef(z), LVSetAI, isCallInst );
346 } // for all machine instructions in BB
348 } // for all BBs in method
351 // add interferences for method arguments. Since there are no explict
352 // defs in method for args, we have to add them manually
354 addInterferencesForArgs();
357 cerr << "Interference graphs calculted!\n";
363 //--------------------------------------------------------------------------
364 // Pseudo instructions will be exapnded to multiple instructions by the
365 // assembler. Consequently, all the opernds must get distinct registers.
366 // Therefore, we mark all operands of a pseudo instruction as they interfere
368 //--------------------------------------------------------------------------
369 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
371 bool setInterf = false;
373 // iterate over MI operands to find defs
375 for( MachineInstr::val_const_op_iterator It1(MInst);!It1.done(); ++It1) {
377 const LiveRange *const LROfOp1 = LRI.getLiveRangeForValue( *It1 );
379 if( !LROfOp1 && It1.isDef() )
380 assert( 0 && "No LR for Def in PSEUDO insruction");
382 MachineInstr::val_const_op_iterator It2 = It1;
385 for( ; !It2.done(); ++It2) {
387 const LiveRange *const LROfOp2 = LRI.getLiveRangeForValue( *It2 );
391 RegClass *const RCOfOp1 = LROfOp1->getRegClass();
392 RegClass *const RCOfOp2 = LROfOp2->getRegClass();
394 if( RCOfOp1 == RCOfOp2 ){
395 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
401 } // for all other defs in machine instr
403 } // for all operands in an instruction
405 if( !setInterf && (MInst->getNumOperands() > 2) ) {
406 cerr << "\nInterf not set for any operand in pseudo instr:\n";
408 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
416 //----------------------------------------------------------------------------
417 // This method will add interferences for incoming arguments to a method.
418 //----------------------------------------------------------------------------
419 void PhyRegAlloc::addInterferencesForArgs()
421 // get the InSet of root BB
422 const LiveVarSet *const InSet = LVI->getInSetOfBB( Meth->front() );
424 // get the argument list
425 const Method::ArgumentListType& ArgList = Meth->getArgumentList();
427 // get an iterator to arg list
428 Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();
431 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
432 addInterference((Value*)*ArgIt, InSet, false); // add interferences between
433 // args and LVars at start
435 cerr << " - %% adding interference for argument "
436 << RAV((const Value *)*ArgIt) << "\n";
443 //----------------------------------------------------------------------------
444 // This method is called after register allocation is complete to set the
445 // allocated reisters in the machine code. This code will add register numbers
446 // to MachineOperands that contain a Value. Also it calls target specific
447 // methods to produce caller saving instructions. At the end, it adds all
448 // additional instructions produced by the register allocator to the
449 // instruction stream.
450 //----------------------------------------------------------------------------
451 void PhyRegAlloc::updateMachineCode()
454 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
456 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
458 // get the iterator for machine instructions
460 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
461 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
463 // iterate over all the machine instructions in BB
465 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
467 MachineInstr *MInst = *MInstIterator;
469 unsigned Opcode = MInst->getOpCode();
471 // do not process Phis
472 if (TM.getInstrInfo().isPhi(Opcode))
475 // Now insert speical instructions (if necessary) for call/return
478 if (TM.getInstrInfo().isCall(Opcode) ||
479 TM.getInstrInfo().isReturn(Opcode)) {
481 AddedInstrns *AI = AddedInstrMap[ MInst];
483 AI = new AddedInstrns();
484 AddedInstrMap[ MInst ] = AI;
487 // Tmp stack poistions are needed by some calls that have spilled args
488 // So reset it before we call each such method
490 mcInfo.popAllTempValues(TM);
492 if (TM.getInstrInfo().isCall(Opcode))
493 MRI.colorCallArgs(MInst, LRI, AI, *this, *BBI);
494 else if (TM.getInstrInfo().isReturn(Opcode))
495 MRI.colorRetValue(MInst, LRI, AI);
499 /* -- Using above code instead of this
501 // if this machine instr is call, insert caller saving code
503 if( (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
504 MRI.insertCallerSavingCode(MInst, *BBI, *this );
509 // reset the stack offset for temporary variables since we may
510 // need that to spill
511 // mcInfo.popAllTempValues(TM);
512 // TODO ** : do later
514 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
517 // Now replace set the registers for operands in the machine instruction
519 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
521 MachineOperand& Op = MInst->getOperand(OpNum);
523 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
524 Op.getOperandType() == MachineOperand::MO_CCRegister) {
526 const Value *const Val = Op.getVRegValue();
528 // delete this condition checking later (must assert if Val is null)
531 cerr << "Warning: NULL Value found for operand\n";
534 assert( Val && "Value is NULL");
536 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
540 // nothing to worry if it's a const or a label
543 cerr << "*NO LR for operand : " << Op ;
544 cerr << " [reg:" << Op.getAllocatedRegNum() << "]";
545 cerr << " in inst:\t" << *MInst << "\n";
548 // if register is not allocated, mark register as invalid
549 if( Op.getAllocatedRegNum() == -1)
550 Op.setRegForValue( MRI.getInvalidRegNum());
556 unsigned RCID = (LR->getRegClass())->getID();
558 if( LR->hasColor() ) {
559 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
563 // LR did NOT receive a color (register). Now, insert spill code
564 // for spilled opeands in this machine instruction
566 //assert(0 && "LR must be spilled");
567 insertCode4SpilledLR(LR, MInst, *BBI, OpNum );
572 } // for each operand
575 // Now add instructions that the register allocator inserts before/after
576 // this machine instructions (done only for calls/rets/incoming args)
577 // We do this here, to ensure that spill for an instruction is inserted
578 // closest as possible to an instruction (see above insertCode4Spill...)
580 // If there are instructions to be added, *before* this machine
581 // instruction, add them now.
583 if( AddedInstrMap[ MInst ] ) {
584 std::deque<MachineInstr *> &IBef = AddedInstrMap[MInst]->InstrnsBefore;
586 if( ! IBef.empty() ) {
587 std::deque<MachineInstr *>::iterator AdIt;
589 for( AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt ) {
592 cerr << "For inst " << *MInst;
593 cerr << " PREPENDed instr: " << **AdIt << "\n";
596 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
604 // If there are instructions to be added *after* this machine
605 // instruction, add them now
607 if(AddedInstrMap[MInst] &&
608 !AddedInstrMap[MInst]->InstrnsAfter.empty() ) {
610 // if there are delay slots for this instruction, the instructions
611 // added after it must really go after the delayed instruction(s)
612 // So, we move the InstrAfter of the current instruction to the
613 // corresponding delayed instruction
616 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
617 move2DelayedInstr(MInst, *(MInstIterator+delay) );
619 if(DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
625 // Here we can add the "instructions after" to the current
626 // instruction since there are no delay slots for this instruction
628 std::deque<MachineInstr *> &IAft = AddedInstrMap[MInst]->InstrnsAfter;
630 if( ! IAft.empty() ) {
632 std::deque<MachineInstr *>::iterator AdIt;
634 ++MInstIterator; // advance to the next instruction
636 for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
639 cerr << "For inst " << *MInst;
640 cerr << " APPENDed instr: " << **AdIt << "\n";
643 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
647 // MInsterator already points to the next instr. Since the
648 // for loop also increments it, decrement it to point to the
649 // instruction added last
658 } // for each machine instruction
664 //----------------------------------------------------------------------------
665 // This method inserts spill code for AN operand whose LR was spilled.
666 // This method may be called several times for a single machine instruction
667 // if it contains many spilled operands. Each time it is called, it finds
668 // a register which is not live at that instruction and also which is not
669 // used by other spilled operands of the same instruction. Then it uses
670 // this register temporarily to accomodate the spilled value.
671 //----------------------------------------------------------------------------
672 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
674 const BasicBlock *BB,
675 const unsigned OpNum) {
677 assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
678 (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
679 "Arg of a call/ret must be handled elsewhere");
681 MachineOperand& Op = MInst->getOperand(OpNum);
682 bool isDef = MInst->operandIsDefined(OpNum);
683 unsigned RegType = MRI.getRegType( LR );
684 int SpillOff = LR->getSpillOffFromFP();
685 RegClass *RC = LR->getRegClass();
686 const LiveVarSet *LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
688 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
690 MachineInstr *MIBef=NULL, *AdIMid=NULL, *MIAft=NULL;
692 int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,LVSetBef, MIBef, MIAft);
694 // get the added instructions for this instruciton
695 AddedInstrns *AI = AddedInstrMap[ MInst ];
697 AI = new AddedInstrns();
698 AddedInstrMap[ MInst ] = AI;
704 // for a USE, we have to load the value of LR from stack to a TmpReg
705 // and use the TmpReg as one operand of instruction
707 // actual loading instruction
708 AdIMid = MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType);
711 AI->InstrnsBefore.push_back(MIBef);
713 AI->InstrnsBefore.push_back(AdIMid);
716 AI->InstrnsAfter.push_front(MIAft);
720 else { // if this is a Def
722 // for a DEF, we have to store the value produced by this instruction
723 // on the stack position allocated for this LR
725 // actual storing instruction
726 AdIMid = MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType);
729 AI->InstrnsBefore.push_back(MIBef);
731 AI->InstrnsAfter.push_front(AdIMid);
734 AI->InstrnsAfter.push_front(MIAft);
738 cerr << "\nFor Inst " << *MInst;
739 cerr << " - SPILLED LR: "; LR->printSet();
740 cerr << "\n - Added Instructions:";
741 if( MIBef ) cerr << *MIBef;
743 if( MIAft ) cerr << *MIAft;
745 Op.setRegForValue( TmpRegU ); // set the opearnd
755 //----------------------------------------------------------------------------
756 // We can use the following method to get a temporary register to be used
757 // BEFORE any given machine instruction. If there is a register available,
758 // this method will simply return that register and set MIBef = MIAft = NULL.
759 // Otherwise, it will return a register and MIAft and MIBef will contain
760 // two instructions used to free up this returned register.
761 // Returned register number is the UNIFIED register number
762 //----------------------------------------------------------------------------
764 int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC,
766 const MachineInstr *MInst,
767 const LiveVarSet *LVSetBef,
769 MachineInstr *MIAft) {
771 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
775 // we found an unused register, so we can simply use it
776 MIBef = MIAft = NULL;
779 // we couldn't find an unused register. Generate code to free up a reg by
780 // saving it on stack and restoring after the instruction
782 int TmpOff = mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
784 RegU = getUniRegNotUsedByThisInst(RC, MInst);
785 MIBef = MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType );
786 MIAft = MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType );
792 //----------------------------------------------------------------------------
793 // This method is called to get a new unused register that can be used to
794 // accomodate a spilled value.
795 // This method may be called several times for a single machine instruction
796 // if it contains many spilled operands. Each time it is called, it finds
797 // a register which is not live at that instruction and also which is not
798 // used by other spilled operands of the same instruction.
799 // Return register number is relative to the register class. NOT
801 //----------------------------------------------------------------------------
802 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
803 const MachineInstr *MInst,
804 const LiveVarSet *LVSetBef) {
806 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
808 bool *IsColorUsedArr = RC->getIsColorUsedArr();
810 for(unsigned i=0; i < NumAvailRegs; i++) // Reset array
811 IsColorUsedArr[i] = false;
813 LiveVarSet::const_iterator LIt = LVSetBef->begin();
815 // for each live var in live variable set after machine inst
816 for( ; LIt != LVSetBef->end(); ++LIt) {
818 // get the live range corresponding to live var
819 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
821 // LR can be null if it is a const since a const
822 // doesn't have a dominating def - see Assumptions above
824 if( LRofLV->hasColor() )
825 IsColorUsedArr[ LRofLV->getColor() ] = true;
828 // It is possible that one operand of this MInst was already spilled
829 // and it received some register temporarily. If that's the case,
830 // it is recorded in machine operand. We must skip such registers.
832 setRelRegsUsedByThisInst(RC, MInst);
834 unsigned c; // find first unused color
835 for( c=0; c < NumAvailRegs; c++)
836 if( ! IsColorUsedArr[ c ] ) break;
839 return MRI.getUnifiedRegNum(RC->getID(), c);
847 //----------------------------------------------------------------------------
848 // Get any other register in a register class, other than what is used
849 // by operands of a machine instruction. Returns the unified reg number.
850 //----------------------------------------------------------------------------
851 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
852 const MachineInstr *MInst) {
854 bool *IsColorUsedArr = RC->getIsColorUsedArr();
855 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
858 for(unsigned i=0; i < NumAvailRegs ; i++) // Reset array
859 IsColorUsedArr[i] = false;
861 setRelRegsUsedByThisInst(RC, MInst);
863 unsigned c; // find first unused color
864 for( c=0; c < RC->getNumOfAvailRegs(); c++)
865 if( ! IsColorUsedArr[ c ] ) break;
868 return MRI.getUnifiedRegNum(RC->getID(), c);
870 assert( 0 && "FATAL: No free register could be found in reg class!!");
875 //----------------------------------------------------------------------------
876 // This method modifies the IsColorUsedArr of the register class passed to it.
877 // It sets the bits corresponding to the registers used by this machine
878 // instructions. Both explicit and implicit operands are set.
879 //----------------------------------------------------------------------------
880 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
881 const MachineInstr *MInst ) {
883 bool *IsColorUsedArr = RC->getIsColorUsedArr();
885 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
887 const MachineOperand& Op = MInst->getOperand(OpNum);
889 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
890 Op.getOperandType() == MachineOperand::MO_CCRegister ) {
892 const Value *const Val = Op.getVRegValue();
895 if( MRI.getRegClassIDOfValue(Val) == RC->getID() ) {
897 if( (Reg=Op.getAllocatedRegNum()) != -1) {
898 IsColorUsedArr[ Reg ] = true;
901 // it is possilbe that this operand still is not marked with
902 // a register but it has a LR and that received a color
904 LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
906 if( LROfVal->hasColor() )
907 IsColorUsedArr[ LROfVal->getColor() ] = true;
910 } // if reg classes are the same
912 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
913 IsColorUsedArr[ Op.getMachineRegNum() ] = true;
917 // If there are implicit references, mark them as well
919 for(unsigned z=0; z < MInst->getNumImplicitRefs(); z++) {
921 LiveRange *const LRofImpRef =
922 LRI.getLiveRangeForValue( MInst->getImplicitRef(z) );
924 if(LRofImpRef && LRofImpRef->hasColor())
925 IsColorUsedArr[LRofImpRef->getColor()] = true;
936 //----------------------------------------------------------------------------
937 // If there are delay slots for an instruction, the instructions
938 // added after it must really go after the delayed instruction(s).
939 // So, we move the InstrAfter of that instruction to the
940 // corresponding delayed instruction using the following method.
942 //----------------------------------------------------------------------------
943 void PhyRegAlloc:: move2DelayedInstr(const MachineInstr *OrigMI,
944 const MachineInstr *DelayedMI) {
946 // "added after" instructions of the original instr
947 std::deque<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI]->InstrnsAfter;
949 // "added instructions" of the delayed instr
950 AddedInstrns *DelayAdI = AddedInstrMap[DelayedMI];
952 if(! DelayAdI ) { // create a new "added after" if necessary
953 DelayAdI = new AddedInstrns();
954 AddedInstrMap[DelayedMI] = DelayAdI;
957 // "added after" instructions of the delayed instr
958 std::deque<MachineInstr *> &DelayedAft = DelayAdI->InstrnsAfter;
960 // go thru all the "added after instructions" of the original instruction
961 // and append them to the "addded after instructions" of the delayed
963 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
965 // empty the "added after instructions" of the original instruction
969 //----------------------------------------------------------------------------
970 // This method prints the code with registers after register allocation is
972 //----------------------------------------------------------------------------
973 void PhyRegAlloc::printMachineCode()
976 cerr << "\n;************** Method " << Meth->getName()
977 << " *****************\n";
979 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
981 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
983 cerr << "\n"; printLabel( *BBI); cerr << ": ";
985 // get the iterator for machine instructions
986 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
987 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
989 // iterate over all the machine instructions in BB
990 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
992 MachineInstr *const MInst = *MInstIterator;
996 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
999 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
1001 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
1003 MachineOperand& Op = MInst->getOperand(OpNum);
1005 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
1006 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
1007 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
1009 const Value *const Val = Op.getVRegValue () ;
1010 // ****this code is temporary till NULL Values are fixed
1012 cerr << "\t<*NULL*>";
1016 // if a label or a constant
1017 if(isa<BasicBlock>(Val)) {
1018 cerr << "\t"; printLabel( Op.getVRegValue () );
1020 // else it must be a register value
1021 const int RegNum = Op.getAllocatedRegNum();
1023 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
1024 if (Val->hasName() )
1025 cerr << "(" << Val->getName() << ")";
1027 cerr << "(" << Val << ")";
1032 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
1034 if( LROfVal->hasSpillOffset() )
1039 else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
1040 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1044 cerr << "\t" << Op; // use dump field
1049 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1050 if( NumOfImpRefs > 0) {
1051 cerr << "\tImplicit:";
1053 for(unsigned z=0; z < NumOfImpRefs; z++)
1054 cerr << RAV(MInst->getImplicitRef(z)) << "\t";
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