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 //----------------------------------------------------------------------------
36 // RegisterAllocation pass front end...
37 //----------------------------------------------------------------------------
39 class RegisterAllocator : public MethodPass {
40 TargetMachine &Target;
42 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
44 bool runOnMethod(Method *M) {
46 cerr << "\n******************** Method "<< M->getName()
47 << " ********************\n";
49 MethodLiveVarInfo LVI(M); // Analyze live varaibles
52 PhyRegAlloc PRA(M, Target, &LVI); // allocate registers
53 PRA.allocateRegisters();
55 if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
61 MethodPass *getRegisterAllocator(TargetMachine &T) {
62 return new RegisterAllocator(T);
65 //----------------------------------------------------------------------------
66 // Constructor: Init local composite objects and create register classes.
67 //----------------------------------------------------------------------------
68 PhyRegAlloc::PhyRegAlloc(Method *M,
69 const TargetMachine& tm,
70 MethodLiveVarInfo *const Lvi)
72 mcInfo(MachineCodeForMethod::get(M)),
73 LVI(Lvi), LRI(M, tm, RegClassList),
74 MRI( tm.getRegInfo() ),
75 NumOfRegClasses(MRI.getNumOfRegClasses()),
78 // create each RegisterClass and put in RegClassList
80 for(unsigned int rc=0; rc < NumOfRegClasses; rc++)
81 RegClassList.push_back( new RegClass(M, MRI.getMachineRegClass(rc),
86 //----------------------------------------------------------------------------
87 // Destructor: Deletes register classes
88 //----------------------------------------------------------------------------
89 PhyRegAlloc::~PhyRegAlloc() {
90 for( unsigned int rc=0; rc < NumOfRegClasses; rc++)
91 delete RegClassList[rc];
94 //----------------------------------------------------------------------------
95 // This method initally creates interference graphs (one in each reg class)
96 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
97 //----------------------------------------------------------------------------
98 void PhyRegAlloc::createIGNodeListsAndIGs() {
99 if (DEBUG_RA) cerr << "Creating LR lists ...\n";
102 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
105 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
107 for (; HMI != HMIEnd ; ++HMI ) {
109 LiveRange *L = HMI->second; // get the LiveRange
112 cerr << "\n*?!?Warning: Null liver range found for: ";
113 printValue(HMI->first); cerr << "\n";
117 // if the Value * is not null, and LR
118 // is not yet written to the IGNodeList
119 if( !(L->getUserIGNode()) ) {
120 RegClass *const RC = // RegClass of first value in the LR
121 RegClassList[ L->getRegClass()->getID() ];
123 RC->addLRToIG(L); // add this LR to an IG
129 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
130 RegClassList[rc]->createInterferenceGraph();
133 cerr << "LRLists Created!\n";
139 //----------------------------------------------------------------------------
140 // This method will add all interferences at for a given instruction.
141 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
142 // class as that of live var. The live var passed to this function is the
143 // LVset AFTER the instruction
144 //----------------------------------------------------------------------------
145 void PhyRegAlloc::addInterference(const Value *const Def,
146 const LiveVarSet *const LVSet,
147 const bool isCallInst) {
149 LiveVarSet::const_iterator LIt = LVSet->begin();
151 // get the live range of instruction
153 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
155 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
156 assert( IGNodeOfDef );
158 RegClass *const RCOfDef = LROfDef->getRegClass();
160 // for each live var in live variable set
162 for( ; LIt != LVSet->end(); ++LIt) {
165 cerr << "< Def="; printValue(Def);
166 cerr << ", Lvar="; printValue( *LIt); cerr << "> ";
169 // get the live range corresponding to live var
171 LiveRange *const LROfVar = LRI.getLiveRangeForValue(*LIt );
173 // LROfVar can be null if it is a const since a const
174 // doesn't have a dominating def - see Assumptions above
177 if(LROfDef == LROfVar) // do not set interf for same LR
180 // if 2 reg classes are the same set interference
182 if(RCOfDef == LROfVar->getRegClass()) {
183 RCOfDef->setInterference( LROfDef, LROfVar);
184 } else if(DEBUG_RA > 1) {
185 // we will not have LRs for values not explicitly allocated in the
186 // instruction stream (e.g., constants)
187 cerr << " warning: no live range for " ;
188 printValue(*LIt); cerr << "\n";
196 //----------------------------------------------------------------------------
197 // For a call instruction, this method sets the CallInterference flag in
198 // the LR of each variable live int the Live Variable Set live after the
199 // call instruction (except the return value of the call instruction - since
200 // the return value does not interfere with that call itself).
201 //----------------------------------------------------------------------------
203 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
204 const LiveVarSet *const LVSetAft ) {
206 // Now find the LR of the return value of the call
207 // We do this because, we look at the LV set *after* the instruction
208 // to determine, which LRs must be saved across calls. The return value
209 // of the call is live in this set - but it does not interfere with call
210 // (i.e., we can allocate a volatile register to the return value)
212 LiveRange *RetValLR = NULL;
213 const Value *RetVal = MRI.getCallInstRetVal( MInst );
216 RetValLR = LRI.getLiveRangeForValue( RetVal );
217 assert( RetValLR && "No LR for RetValue of call");
221 cerr << "\n For call inst: " << *MInst;
223 LiveVarSet::const_iterator LIt = LVSetAft->begin();
225 // for each live var in live variable set after machine inst
227 for( ; LIt != LVSetAft->end(); ++LIt) {
229 // get the live range corresponding to live var
231 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
233 if( LR && DEBUG_RA) {
234 cerr << "\n\tLR Aft Call: ";
239 // LR can be null if it is a const since a const
240 // doesn't have a dominating def - see Assumptions above
242 if( LR && (LR != RetValLR) ) {
243 LR->setCallInterference();
245 cerr << "\n ++Added call interf for LR: " ;
257 //----------------------------------------------------------------------------
258 // This method will walk thru code and create interferences in the IG of
259 // each RegClass. Also, this method calculates the spill cost of each
260 // Live Range (it is done in this method to save another pass over the code).
261 //----------------------------------------------------------------------------
262 void PhyRegAlloc::buildInterferenceGraphs()
265 if(DEBUG_RA) cerr << "Creating interference graphs ...\n";
267 unsigned BBLoopDepthCost;
268 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
270 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
272 // find the 10^(loop_depth) of this BB
274 BBLoopDepthCost = (unsigned) pow( 10.0, LoopDepthCalc.getLoopDepth(*BBI));
276 // get the iterator for machine instructions
278 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
279 MachineCodeForBasicBlock::const_iterator
280 MInstIterator = MIVec.begin();
282 // iterate over all the machine instructions in BB
284 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
286 const MachineInstr * MInst = *MInstIterator;
288 // get the LV set after the instruction
290 const LiveVarSet *const LVSetAI =
291 LVI->getLiveVarSetAfterMInst(MInst, *BBI);
293 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
296 // set the isCallInterference flag of each live range wich extends
297 // accross this call instruction. This information is used by graph
298 // coloring algo to avoid allocating volatile colors to live ranges
299 // that span across calls (since they have to be saved/restored)
301 setCallInterferences( MInst, LVSetAI);
305 // iterate over all MI operands to find defs
307 for( MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done(); ++OpI) {
310 // create a new LR iff this operand is a def
312 addInterference(*OpI, LVSetAI, isCallInst );
315 // Calculate the spill cost of each live range
317 LiveRange *LR = LRI.getLiveRangeForValue( *OpI );
319 LR->addSpillCost(BBLoopDepthCost);
323 // if there are multiple defs in this instruction e.g. in SETX
325 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
326 addInterf4PseudoInstr(MInst);
329 // Also add interference for any implicit definitions in a machine
330 // instr (currently, only calls have this).
332 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
333 if( NumOfImpRefs > 0 ) {
334 for(unsigned z=0; z < NumOfImpRefs; z++)
335 if( MInst->implicitRefIsDefined(z) )
336 addInterference( MInst->getImplicitRef(z), LVSetAI, isCallInst );
340 } // for all machine instructions in BB
342 } // for all BBs in method
345 // add interferences for method arguments. Since there are no explict
346 // defs in method for args, we have to add them manually
348 addInterferencesForArgs();
351 cerr << "Interference graphs calculted!\n";
357 //--------------------------------------------------------------------------
358 // Pseudo instructions will be exapnded to multiple instructions by the
359 // assembler. Consequently, all the opernds must get distinct registers.
360 // Therefore, we mark all operands of a pseudo instruction as they interfere
362 //--------------------------------------------------------------------------
363 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
365 bool setInterf = false;
367 // iterate over MI operands to find defs
369 for( MachineInstr::val_const_op_iterator It1(MInst);!It1.done(); ++It1) {
371 const LiveRange *const LROfOp1 = LRI.getLiveRangeForValue( *It1 );
373 if( !LROfOp1 && It1.isDef() )
374 assert( 0 && "No LR for Def in PSEUDO insruction");
376 MachineInstr::val_const_op_iterator It2 = It1;
379 for( ; !It2.done(); ++It2) {
381 const LiveRange *const LROfOp2 = LRI.getLiveRangeForValue( *It2 );
385 RegClass *const RCOfOp1 = LROfOp1->getRegClass();
386 RegClass *const RCOfOp2 = LROfOp2->getRegClass();
388 if( RCOfOp1 == RCOfOp2 ){
389 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
395 } // for all other defs in machine instr
397 } // for all operands in an instruction
399 if( !setInterf && (MInst->getNumOperands() > 2) ) {
400 cerr << "\nInterf not set for any operand in pseudo instr:\n";
402 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
410 //----------------------------------------------------------------------------
411 // This method will add interferences for incoming arguments to a method.
412 //----------------------------------------------------------------------------
413 void PhyRegAlloc::addInterferencesForArgs()
415 // get the InSet of root BB
416 const LiveVarSet *const InSet = LVI->getInSetOfBB( Meth->front() );
418 // get the argument list
419 const Method::ArgumentListType& ArgList = Meth->getArgumentList();
421 // get an iterator to arg list
422 Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();
425 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
426 addInterference( *ArgIt, InSet, false ); // add interferences between
427 // args and LVars at start
429 cerr << " - %% adding interference for argument ";
430 printValue((const Value *)*ArgIt); cerr << "\n";
438 //----------------------------------------------------------------------------
439 // This method is called after register allocation is complete to set the
440 // allocated reisters in the machine code. This code will add register numbers
441 // to MachineOperands that contain a Value. Also it calls target specific
442 // methods to produce caller saving instructions. At the end, it adds all
443 // additional instructions produced by the register allocator to the
444 // instruction stream.
445 //----------------------------------------------------------------------------
446 void PhyRegAlloc::updateMachineCode()
449 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
451 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
453 // get the iterator for machine instructions
455 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
456 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
458 // iterate over all the machine instructions in BB
460 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
462 MachineInstr *MInst = *MInstIterator;
464 unsigned Opcode = MInst->getOpCode();
466 // do not process Phis
467 if (TM.getInstrInfo().isPhi(Opcode))
470 // Now insert speical instructions (if necessary) for call/return
473 if (TM.getInstrInfo().isCall(Opcode) ||
474 TM.getInstrInfo().isReturn(Opcode)) {
476 AddedInstrns *AI = AddedInstrMap[ MInst];
478 AI = new AddedInstrns();
479 AddedInstrMap[ MInst ] = AI;
482 // Tmp stack poistions are needed by some calls that have spilled args
483 // So reset it before we call each such method
485 mcInfo.popAllTempValues(TM);
487 if (TM.getInstrInfo().isCall(Opcode))
488 MRI.colorCallArgs(MInst, LRI, AI, *this, *BBI);
489 else if (TM.getInstrInfo().isReturn(Opcode))
490 MRI.colorRetValue(MInst, LRI, AI);
494 /* -- Using above code instead of this
496 // if this machine instr is call, insert caller saving code
498 if( (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
499 MRI.insertCallerSavingCode(MInst, *BBI, *this );
504 // reset the stack offset for temporary variables since we may
505 // need that to spill
506 // mcInfo.popAllTempValues(TM);
507 // TODO ** : do later
509 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
512 // Now replace set the registers for operands in the machine instruction
514 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
516 MachineOperand& Op = MInst->getOperand(OpNum);
518 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
519 Op.getOperandType() == MachineOperand::MO_CCRegister) {
521 const Value *const Val = Op.getVRegValue();
523 // delete this condition checking later (must assert if Val is null)
526 cerr << "Warning: NULL Value found for operand\n";
529 assert( Val && "Value is NULL");
531 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
535 // nothing to worry if it's a const or a label
538 cerr << "*NO LR for operand : " << Op ;
539 cerr << " [reg:" << Op.getAllocatedRegNum() << "]";
540 cerr << " in inst:\t" << *MInst << "\n";
543 // if register is not allocated, mark register as invalid
544 if( Op.getAllocatedRegNum() == -1)
545 Op.setRegForValue( MRI.getInvalidRegNum());
551 unsigned RCID = (LR->getRegClass())->getID();
553 if( LR->hasColor() ) {
554 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
558 // LR did NOT receive a color (register). Now, insert spill code
559 // for spilled opeands in this machine instruction
561 //assert(0 && "LR must be spilled");
562 insertCode4SpilledLR(LR, MInst, *BBI, OpNum );
567 } // for each operand
570 // Now add instructions that the register allocator inserts before/after
571 // this machine instructions (done only for calls/rets/incoming args)
572 // We do this here, to ensure that spill for an instruction is inserted
573 // closest as possible to an instruction (see above insertCode4Spill...)
575 // If there are instructions to be added, *before* this machine
576 // instruction, add them now.
578 if( AddedInstrMap[ MInst ] ) {
579 std::deque<MachineInstr *> &IBef = AddedInstrMap[MInst]->InstrnsBefore;
581 if( ! IBef.empty() ) {
582 std::deque<MachineInstr *>::iterator AdIt;
584 for( AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt ) {
587 cerr << "For inst " << *MInst;
588 cerr << " PREPENDed instr: " << **AdIt << "\n";
591 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
599 // If there are instructions to be added *after* this machine
600 // instruction, add them now
602 if(AddedInstrMap[MInst] &&
603 !AddedInstrMap[MInst]->InstrnsAfter.empty() ) {
605 // if there are delay slots for this instruction, the instructions
606 // added after it must really go after the delayed instruction(s)
607 // So, we move the InstrAfter of the current instruction to the
608 // corresponding delayed instruction
611 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
612 move2DelayedInstr(MInst, *(MInstIterator+delay) );
614 if(DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
620 // Here we can add the "instructions after" to the current
621 // instruction since there are no delay slots for this instruction
623 std::deque<MachineInstr *> &IAft = AddedInstrMap[MInst]->InstrnsAfter;
625 if( ! IAft.empty() ) {
627 std::deque<MachineInstr *>::iterator AdIt;
629 ++MInstIterator; // advance to the next instruction
631 for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
634 cerr << "For inst " << *MInst;
635 cerr << " APPENDed instr: " << **AdIt << "\n";
638 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
642 // MInsterator already points to the next instr. Since the
643 // for loop also increments it, decrement it to point to the
644 // instruction added last
653 } // for each machine instruction
659 //----------------------------------------------------------------------------
660 // This method inserts spill code for AN operand whose LR was spilled.
661 // This method may be called several times for a single machine instruction
662 // if it contains many spilled operands. Each time it is called, it finds
663 // a register which is not live at that instruction and also which is not
664 // used by other spilled operands of the same instruction. Then it uses
665 // this register temporarily to accomodate the spilled value.
666 //----------------------------------------------------------------------------
667 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
669 const BasicBlock *BB,
670 const unsigned OpNum) {
672 assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
673 (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
674 "Arg of a call/ret must be handled elsewhere");
676 MachineOperand& Op = MInst->getOperand(OpNum);
677 bool isDef = MInst->operandIsDefined(OpNum);
678 unsigned RegType = MRI.getRegType( LR );
679 int SpillOff = LR->getSpillOffFromFP();
680 RegClass *RC = LR->getRegClass();
681 const LiveVarSet *LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
683 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
685 MachineInstr *MIBef=NULL, *AdIMid=NULL, *MIAft=NULL;
687 int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,LVSetBef, MIBef, MIAft);
689 // get the added instructions for this instruciton
690 AddedInstrns *AI = AddedInstrMap[ MInst ];
692 AI = new AddedInstrns();
693 AddedInstrMap[ MInst ] = AI;
699 // for a USE, we have to load the value of LR from stack to a TmpReg
700 // and use the TmpReg as one operand of instruction
702 // actual loading instruction
703 AdIMid = MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType);
706 AI->InstrnsBefore.push_back(MIBef);
708 AI->InstrnsBefore.push_back(AdIMid);
711 AI->InstrnsAfter.push_front(MIAft);
715 else { // if this is a Def
717 // for a DEF, we have to store the value produced by this instruction
718 // on the stack position allocated for this LR
720 // actual storing instruction
721 AdIMid = MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType);
724 AI->InstrnsBefore.push_back(MIBef);
726 AI->InstrnsAfter.push_front(AdIMid);
729 AI->InstrnsAfter.push_front(MIAft);
733 cerr << "\nFor Inst " << *MInst;
734 cerr << " - SPILLED LR: "; LR->printSet();
735 cerr << "\n - Added Instructions:";
736 if( MIBef ) cerr << *MIBef;
738 if( MIAft ) cerr << *MIAft;
740 Op.setRegForValue( TmpRegU ); // set the opearnd
750 //----------------------------------------------------------------------------
751 // We can use the following method to get a temporary register to be used
752 // BEFORE any given machine instruction. If there is a register available,
753 // this method will simply return that register and set MIBef = MIAft = NULL.
754 // Otherwise, it will return a register and MIAft and MIBef will contain
755 // two instructions used to free up this returned register.
756 // Returned register number is the UNIFIED register number
757 //----------------------------------------------------------------------------
759 int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC,
761 const MachineInstr *MInst,
762 const LiveVarSet *LVSetBef,
764 MachineInstr *MIAft) {
766 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
770 // we found an unused register, so we can simply use it
771 MIBef = MIAft = NULL;
774 // we couldn't find an unused register. Generate code to free up a reg by
775 // saving it on stack and restoring after the instruction
777 int TmpOff = mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
779 RegU = getUniRegNotUsedByThisInst(RC, MInst);
780 MIBef = MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType );
781 MIAft = MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType );
787 //----------------------------------------------------------------------------
788 // This method is called to get a new unused register that can be used to
789 // accomodate a spilled value.
790 // This method may be called several times for a single machine instruction
791 // if it contains many spilled operands. Each time it is called, it finds
792 // a register which is not live at that instruction and also which is not
793 // used by other spilled operands of the same instruction.
794 // Return register number is relative to the register class. NOT
796 //----------------------------------------------------------------------------
797 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
798 const MachineInstr *MInst,
799 const LiveVarSet *LVSetBef) {
801 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
803 bool *IsColorUsedArr = RC->getIsColorUsedArr();
805 for(unsigned i=0; i < NumAvailRegs; i++) // Reset array
806 IsColorUsedArr[i] = false;
808 LiveVarSet::const_iterator LIt = LVSetBef->begin();
810 // for each live var in live variable set after machine inst
811 for( ; LIt != LVSetBef->end(); ++LIt) {
813 // get the live range corresponding to live var
814 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
816 // LR can be null if it is a const since a const
817 // doesn't have a dominating def - see Assumptions above
819 if( LRofLV->hasColor() )
820 IsColorUsedArr[ LRofLV->getColor() ] = true;
823 // It is possible that one operand of this MInst was already spilled
824 // and it received some register temporarily. If that's the case,
825 // it is recorded in machine operand. We must skip such registers.
827 setRelRegsUsedByThisInst(RC, MInst);
829 unsigned c; // find first unused color
830 for( c=0; c < NumAvailRegs; c++)
831 if( ! IsColorUsedArr[ c ] ) break;
834 return MRI.getUnifiedRegNum(RC->getID(), c);
842 //----------------------------------------------------------------------------
843 // Get any other register in a register class, other than what is used
844 // by operands of a machine instruction. Returns the unified reg number.
845 //----------------------------------------------------------------------------
846 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
847 const MachineInstr *MInst) {
849 bool *IsColorUsedArr = RC->getIsColorUsedArr();
850 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
853 for(unsigned i=0; i < NumAvailRegs ; i++) // Reset array
854 IsColorUsedArr[i] = false;
856 setRelRegsUsedByThisInst(RC, MInst);
858 unsigned c; // find first unused color
859 for( c=0; c < RC->getNumOfAvailRegs(); c++)
860 if( ! IsColorUsedArr[ c ] ) break;
863 return MRI.getUnifiedRegNum(RC->getID(), c);
865 assert( 0 && "FATAL: No free register could be found in reg class!!");
870 //----------------------------------------------------------------------------
871 // This method modifies the IsColorUsedArr of the register class passed to it.
872 // It sets the bits corresponding to the registers used by this machine
873 // instructions. Both explicit and implicit operands are set.
874 //----------------------------------------------------------------------------
875 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
876 const MachineInstr *MInst ) {
878 bool *IsColorUsedArr = RC->getIsColorUsedArr();
880 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
882 const MachineOperand& Op = MInst->getOperand(OpNum);
884 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
885 Op.getOperandType() == MachineOperand::MO_CCRegister ) {
887 const Value *const Val = Op.getVRegValue();
890 if( MRI.getRegClassIDOfValue(Val) == RC->getID() ) {
892 if( (Reg=Op.getAllocatedRegNum()) != -1) {
893 IsColorUsedArr[ Reg ] = true;
896 // it is possilbe that this operand still is not marked with
897 // a register but it has a LR and that received a color
899 LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
901 if( LROfVal->hasColor() )
902 IsColorUsedArr[ LROfVal->getColor() ] = true;
905 } // if reg classes are the same
907 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
908 IsColorUsedArr[ Op.getMachineRegNum() ] = true;
912 // If there are implicit references, mark them as well
914 for(unsigned z=0; z < MInst->getNumImplicitRefs(); z++) {
916 LiveRange *const LRofImpRef =
917 LRI.getLiveRangeForValue( MInst->getImplicitRef(z) );
919 if(LRofImpRef && LRofImpRef->hasColor())
920 IsColorUsedArr[LRofImpRef->getColor()] = true;
931 //----------------------------------------------------------------------------
932 // If there are delay slots for an instruction, the instructions
933 // added after it must really go after the delayed instruction(s).
934 // So, we move the InstrAfter of that instruction to the
935 // corresponding delayed instruction using the following method.
937 //----------------------------------------------------------------------------
938 void PhyRegAlloc:: move2DelayedInstr(const MachineInstr *OrigMI,
939 const MachineInstr *DelayedMI) {
941 // "added after" instructions of the original instr
942 std::deque<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI]->InstrnsAfter;
944 // "added instructions" of the delayed instr
945 AddedInstrns *DelayAdI = AddedInstrMap[DelayedMI];
947 if(! DelayAdI ) { // create a new "added after" if necessary
948 DelayAdI = new AddedInstrns();
949 AddedInstrMap[DelayedMI] = DelayAdI;
952 // "added after" instructions of the delayed instr
953 std::deque<MachineInstr *> &DelayedAft = DelayAdI->InstrnsAfter;
955 // go thru all the "added after instructions" of the original instruction
956 // and append them to the "addded after instructions" of the delayed
958 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
960 // empty the "added after instructions" of the original instruction
964 //----------------------------------------------------------------------------
965 // This method prints the code with registers after register allocation is
967 //----------------------------------------------------------------------------
968 void PhyRegAlloc::printMachineCode()
971 cerr << "\n;************** Method " << Meth->getName()
972 << " *****************\n";
974 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
976 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
978 cerr << "\n"; printLabel( *BBI); cerr << ": ";
980 // get the iterator for machine instructions
981 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
982 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
984 // iterate over all the machine instructions in BB
985 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
987 MachineInstr *const MInst = *MInstIterator;
991 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
994 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
996 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
998 MachineOperand& Op = MInst->getOperand(OpNum);
1000 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
1001 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
1002 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
1004 const Value *const Val = Op.getVRegValue () ;
1005 // ****this code is temporary till NULL Values are fixed
1007 cerr << "\t<*NULL*>";
1011 // if a label or a constant
1012 if(isa<BasicBlock>(Val)) {
1013 cerr << "\t"; printLabel( Op.getVRegValue () );
1015 // else it must be a register value
1016 const int RegNum = Op.getAllocatedRegNum();
1018 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
1019 if (Val->hasName() )
1020 cerr << "(" << Val->getName() << ")";
1022 cerr << "(" << Val << ")";
1027 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
1029 if( LROfVal->hasSpillOffset() )
1034 else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
1035 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1039 cerr << "\t" << Op; // use dump field
1044 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1045 if( NumOfImpRefs > 0 ) {
1047 cerr << "\tImplicit:";
1049 for(unsigned z=0; z < NumOfImpRefs; z++) {
1050 printValue( MInst->getImplicitRef(z) );
1056 } // for all machine instructions
1068 //----------------------------------------------------------------------------
1070 //----------------------------------------------------------------------------
1072 void PhyRegAlloc::colorCallRetArgs()
1075 CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
1076 CallRetInstrListType::const_iterator It = CallRetInstList.begin();
1078 for( ; It != CallRetInstList.end(); ++It ) {
1080 const MachineInstr *const CRMI = *It;
1081 unsigned OpCode = CRMI->getOpCode();
1083 // get the added instructions for this Call/Ret instruciton
1084 AddedInstrns *AI = AddedInstrMap[ CRMI ];
1086 AI = new AddedInstrns();
1087 AddedInstrMap[ CRMI ] = AI;
1090 // Tmp stack poistions are needed by some calls that have spilled args
1091 // So reset it before we call each such method
1092 //mcInfo.popAllTempValues(TM);
1096 if (TM.getInstrInfo().isCall(OpCode))
1097 MRI.colorCallArgs(CRMI, LRI, AI, *this);
1098 else if (TM.getInstrInfo().isReturn(OpCode))
1099 MRI.colorRetValue( CRMI, LRI, AI );
1101 assert(0 && "Non Call/Ret instrn in CallRetInstrList\n");
1107 //----------------------------------------------------------------------------
1109 //----------------------------------------------------------------------------
1110 void PhyRegAlloc::colorIncomingArgs()
1112 const BasicBlock *const FirstBB = Meth->front();
1113 const MachineInstr *FirstMI = FirstBB->getMachineInstrVec().front();
1114 assert(FirstMI && "No machine instruction in entry BB");
1116 AddedInstrns *AI = AddedInstrMap[FirstMI];
1118 AddedInstrMap[FirstMI] = AI = new AddedInstrns();
1120 MRI.colorMethodArgs(Meth, LRI, AI);
1124 //----------------------------------------------------------------------------
1125 // Used to generate a label for a basic block
1126 //----------------------------------------------------------------------------
1127 void PhyRegAlloc::printLabel(const Value *const Val) {
1129 cerr << Val->getName();
1131 cerr << "Label" << Val;
1135 //----------------------------------------------------------------------------
1136 // This method calls setSugColorUsable method of each live range. This
1137 // will determine whether the suggested color of LR is really usable.
1138 // A suggested color is not usable when the suggested color is volatile
1139 // AND when there are call interferences
1140 //----------------------------------------------------------------------------
1142 void PhyRegAlloc::markUnusableSugColors()
1144 if(DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
1146 // hash map iterator
1147 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1148 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1150 for(; HMI != HMIEnd ; ++HMI ) {
1152 LiveRange *L = HMI->second; // get the LiveRange
1154 if(L->hasSuggestedColor()) {
1155 int RCID = L->getRegClass()->getID();
1156 if( MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1157 L->isCallInterference() )
1158 L->setSuggestedColorUsable( false );
1160 L->setSuggestedColorUsable( true );
1162 } // if L->hasSuggestedColor()
1164 } // for all LR's in hash map
1169 //----------------------------------------------------------------------------
1170 // The following method will set the stack offsets of the live ranges that
1171 // are decided to be spillled. This must be called just after coloring the
1172 // LRs using the graph coloring algo. For each live range that is spilled,
1173 // this method allocate a new spill position on the stack.
1174 //----------------------------------------------------------------------------
1176 void PhyRegAlloc::allocateStackSpace4SpilledLRs()
1178 if(DEBUG_RA ) cerr << "\nsetting LR stack offsets ...\n";
1180 // hash map iterator
1181 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1182 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1184 for( ; HMI != HMIEnd ; ++HMI ) {
1185 if(HMI->first && HMI->second) {
1186 LiveRange *L = HMI->second; // get the LiveRange
1187 if( ! L->hasColor() )
1188 // NOTE: ** allocating the size of long Type **
1189 L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
1191 } // for all LR's in hash map
1196 //----------------------------------------------------------------------------
1197 // The entry pont to Register Allocation
1198 //----------------------------------------------------------------------------
1200 void PhyRegAlloc::allocateRegisters()
1203 // make sure that we put all register classes into the RegClassList
1204 // before we call constructLiveRanges (now done in the constructor of
1205 // PhyRegAlloc class).
1207 LRI.constructLiveRanges(); // create LR info
1210 LRI.printLiveRanges();
1212 createIGNodeListsAndIGs(); // create IGNode list and IGs
1214 buildInterferenceGraphs(); // build IGs in all reg classes
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 LRI.coalesceLRs(); // coalesce all live ranges
1232 // print all LRs in all reg classes
1233 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1234 RegClassList[ rc ]->printIGNodeList();
1236 // print IGs in all register classes
1237 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1238 RegClassList[ rc ]->printIG();
1242 // mark un-usable suggested color before graph coloring algorithm.
1243 // When this is done, the graph coloring algo will not reserve
1244 // suggested color unnecessarily - they can be used by another LR
1246 markUnusableSugColors();
1248 // color all register classes using the graph coloring algo
1249 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1250 RegClassList[ rc ]->colorAllRegs();
1252 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1253 // a poistion for such spilled LRs
1255 allocateStackSpace4SpilledLRs();
1257 mcInfo.popAllTempValues(TM); // TODO **Check
1259 // color incoming args - if the correct color was not received
1260 // insert code to copy to the correct register
1262 colorIncomingArgs();
1264 // Now update the machine code with register names and add any
1265 // additional code inserted by the register allocator to the instruction
1268 updateMachineCode();
1271 MachineCodeForMethod::get(Meth).dump();
1272 printMachineCode(); // only for DEBUGGING