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/LoopInfo.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/MachineFrameInfo.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/Method.h"
23 #include "llvm/Type.h"
29 // ***TODO: There are several places we add instructions. Validate the order
30 // of adding these instructions.
32 cl::Enum<RegAllocDebugLevel_t> DEBUG_RA("dregalloc", cl::NoFlags,
33 "enable register allocation debugging information",
34 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
35 clEnumValN(RA_DEBUG_Normal , "y", "enable debug output"),
36 clEnumValN(RA_DEBUG_Verbose, "v", "enable extra debug output"), 0);
39 //----------------------------------------------------------------------------
40 // RegisterAllocation pass front end...
41 //----------------------------------------------------------------------------
43 class RegisterAllocator : public MethodPass {
44 TargetMachine &Target;
46 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
48 bool runOnMethod(Method *M) {
50 cerr << "\n******************** Method "<< M->getName()
51 << " ********************\n";
53 PhyRegAlloc PRA(M, Target, &getAnalysis<MethodLiveVarInfo>(),
54 &getAnalysis<cfg::LoopInfo>());
55 PRA.allocateRegisters();
57 if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
61 virtual void getAnalysisUsageInfo(Pass::AnalysisSet &Requires,
62 Pass::AnalysisSet &Destroyed,
63 Pass::AnalysisSet &Provided) {
64 Requires.push_back(cfg::LoopInfo::ID);
65 Requires.push_back(MethodLiveVarInfo::ID);
66 Destroyed.push_back(MethodLiveVarInfo::ID);
71 MethodPass *getRegisterAllocator(TargetMachine &T) {
72 return new RegisterAllocator(T);
75 //----------------------------------------------------------------------------
76 // Constructor: Init local composite objects and create register classes.
77 //----------------------------------------------------------------------------
78 PhyRegAlloc::PhyRegAlloc(Method *M,
79 const TargetMachine& tm,
80 MethodLiveVarInfo *Lvi,
83 mcInfo(MachineCodeForMethod::get(M)),
84 LVI(Lvi), LRI(M, tm, RegClassList),
85 MRI( tm.getRegInfo() ),
86 NumOfRegClasses(MRI.getNumOfRegClasses()),
89 // create each RegisterClass and put in RegClassList
91 for(unsigned int rc=0; rc < NumOfRegClasses; rc++)
92 RegClassList.push_back( new RegClass(M, MRI.getMachineRegClass(rc),
97 //----------------------------------------------------------------------------
98 // Destructor: Deletes register classes
99 //----------------------------------------------------------------------------
100 PhyRegAlloc::~PhyRegAlloc() {
101 for( unsigned int rc=0; rc < NumOfRegClasses; rc++)
102 delete RegClassList[rc];
105 //----------------------------------------------------------------------------
106 // This method initally creates interference graphs (one in each reg class)
107 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
108 //----------------------------------------------------------------------------
109 void PhyRegAlloc::createIGNodeListsAndIGs() {
110 if (DEBUG_RA) cerr << "Creating LR lists ...\n";
113 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
116 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
118 for (; HMI != HMIEnd ; ++HMI ) {
120 LiveRange *L = HMI->second; // get the LiveRange
123 cerr << "\n*?!?Warning: Null liver range found for: "
124 << RAV(HMI->first) << "\n";
128 // if the Value * is not null, and LR
129 // is not yet written to the IGNodeList
130 if( !(L->getUserIGNode()) ) {
131 RegClass *const RC = // RegClass of first value in the LR
132 RegClassList[ L->getRegClass()->getID() ];
134 RC->addLRToIG(L); // add this LR to an IG
140 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
141 RegClassList[rc]->createInterferenceGraph();
144 cerr << "LRLists Created!\n";
150 //----------------------------------------------------------------------------
151 // This method will add all interferences at for a given instruction.
152 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
153 // class as that of live var. The live var passed to this function is the
154 // LVset AFTER the instruction
155 //----------------------------------------------------------------------------
156 void PhyRegAlloc::addInterference(const Value *Def,
157 const ValueSet *LVSet,
160 ValueSet::const_iterator LIt = LVSet->begin();
162 // get the live range of instruction
164 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
166 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
167 assert( IGNodeOfDef );
169 RegClass *const RCOfDef = LROfDef->getRegClass();
171 // for each live var in live variable set
173 for( ; LIt != LVSet->end(); ++LIt) {
176 cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
178 // get the live range corresponding to live var
180 LiveRange *LROfVar = LRI.getLiveRangeForValue(*LIt);
182 // LROfVar can be null if it is a const since a const
183 // doesn't have a dominating def - see Assumptions above
186 if(LROfDef == LROfVar) // do not set interf for same LR
189 // if 2 reg classes are the same set interference
191 if (RCOfDef == LROfVar->getRegClass()) {
192 RCOfDef->setInterference( LROfDef, LROfVar);
193 } else if (DEBUG_RA > 1) {
194 // we will not have LRs for values not explicitly allocated in the
195 // instruction stream (e.g., constants)
196 cerr << " warning: no live range for " << RAV(*LIt) << "\n";
204 //----------------------------------------------------------------------------
205 // For a call instruction, this method sets the CallInterference flag in
206 // the LR of each variable live int the Live Variable Set live after the
207 // call instruction (except the return value of the call instruction - since
208 // the return value does not interfere with that call itself).
209 //----------------------------------------------------------------------------
211 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
212 const ValueSet *LVSetAft) {
214 // Now find the LR of the return value of the call
215 // We do this because, we look at the LV set *after* the instruction
216 // to determine, which LRs must be saved across calls. The return value
217 // of the call is live in this set - but it does not interfere with call
218 // (i.e., we can allocate a volatile register to the return value)
220 LiveRange *RetValLR = NULL;
221 const Value *RetVal = MRI.getCallInstRetVal( MInst );
224 RetValLR = LRI.getLiveRangeForValue( RetVal );
225 assert( RetValLR && "No LR for RetValue of call");
229 cerr << "\n For call inst: " << *MInst;
231 ValueSet::const_iterator LIt = LVSetAft->begin();
233 // for each live var in live variable set after machine inst
235 for( ; LIt != LVSetAft->end(); ++LIt) {
237 // get the live range corresponding to live var
239 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
241 if( LR && DEBUG_RA) {
242 cerr << "\n\tLR Aft Call: ";
247 // LR can be null if it is a const since a const
248 // doesn't have a dominating def - see Assumptions above
250 if( LR && (LR != RetValLR) ) {
251 LR->setCallInterference();
253 cerr << "\n ++Added call interf for LR: " ;
265 //----------------------------------------------------------------------------
266 // This method will walk thru code and create interferences in the IG of
267 // each RegClass. Also, this method calculates the spill cost of each
268 // Live Range (it is done in this method to save another pass over the code).
269 //----------------------------------------------------------------------------
270 void PhyRegAlloc::buildInterferenceGraphs()
273 if(DEBUG_RA) cerr << "Creating interference graphs ...\n";
275 unsigned BBLoopDepthCost;
276 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
278 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
280 // find the 10^(loop_depth) of this BB
282 BBLoopDepthCost = (unsigned) pow( 10.0, LoopDepthCalc->getLoopDepth(*BBI));
284 // get the iterator for machine instructions
286 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
287 MachineCodeForBasicBlock::const_iterator
288 MInstIterator = MIVec.begin();
290 // iterate over all the machine instructions in BB
292 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
294 const MachineInstr *MInst = *MInstIterator;
296 // get the LV set after the instruction
298 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, *BBI);
300 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
303 // set the isCallInterference flag of each live range wich extends
304 // accross this call instruction. This information is used by graph
305 // coloring algo to avoid allocating volatile colors to live ranges
306 // that span across calls (since they have to be saved/restored)
308 setCallInterferences(MInst, &LVSetAI);
312 // iterate over all MI operands to find defs
314 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
315 OpE = MInst->end(); OpI != OpE; ++OpI) {
316 if (OpI.isDef()) // create a new LR iff this operand is a def
317 addInterference(*OpI, &LVSetAI, isCallInst);
319 // Calculate the spill cost of each live range
321 LiveRange *LR = LRI.getLiveRangeForValue(*OpI);
322 if (LR) LR->addSpillCost(BBLoopDepthCost);
326 // if there are multiple defs in this instruction e.g. in SETX
328 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
329 addInterf4PseudoInstr(MInst);
332 // Also add interference for any implicit definitions in a machine
333 // instr (currently, only calls have this).
335 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
336 if( NumOfImpRefs > 0 ) {
337 for(unsigned z=0; z < NumOfImpRefs; z++)
338 if( MInst->implicitRefIsDefined(z) )
339 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
343 } // for all machine instructions in BB
345 } // for all BBs in method
348 // add interferences for method arguments. Since there are no explict
349 // defs in method for args, we have to add them manually
351 addInterferencesForArgs();
354 cerr << "Interference graphs calculted!\n";
360 //--------------------------------------------------------------------------
361 // Pseudo instructions will be exapnded to multiple instructions by the
362 // assembler. Consequently, all the opernds must get distinct registers.
363 // Therefore, we mark all operands of a pseudo instruction as they interfere
365 //--------------------------------------------------------------------------
366 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
368 bool setInterf = false;
370 // iterate over MI operands to find defs
372 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
373 ItE = MInst->end(); It1 != ItE; ++It1) {
374 const LiveRange *LROfOp1 = LRI.getLiveRangeForValue(*It1);
375 assert((LROfOp1 || !It1.isDef()) && "No LR for Def in PSEUDO insruction");
377 MachineInstr::const_val_op_iterator It2 = It1;
378 for(++It2; It2 != ItE; ++It2) {
379 const LiveRange *LROfOp2 = LRI.getLiveRangeForValue(*It2);
382 RegClass *RCOfOp1 = LROfOp1->getRegClass();
383 RegClass *RCOfOp2 = LROfOp2->getRegClass();
385 if( RCOfOp1 == RCOfOp2 ){
386 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
390 } // for all other defs in machine instr
391 } // for all operands in an instruction
393 if (!setInterf && MInst->getNumOperands() > 2) {
394 cerr << "\nInterf not set for any operand in pseudo instr:\n";
396 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
402 //----------------------------------------------------------------------------
403 // This method will add interferences for incoming arguments to a method.
404 //----------------------------------------------------------------------------
405 void PhyRegAlloc::addInterferencesForArgs() {
406 // get the InSet of root BB
407 const ValueSet &InSet = LVI->getInSetOfBB(Meth->front());
409 // get the argument list
410 const Method::ArgumentListType& ArgList = Meth->getArgumentList();
412 // get an iterator to arg list
413 Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();
416 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
417 addInterference((Value*)*ArgIt, &InSet, false);// add interferences between
418 // args and LVars at start
420 cerr << " - %% adding interference for argument "
421 << RAV((const Value *)*ArgIt) << "\n";
428 //----------------------------------------------------------------------------
429 // This method is called after register allocation is complete to set the
430 // allocated reisters in the machine code. This code will add register numbers
431 // to MachineOperands that contain a Value. Also it calls target specific
432 // methods to produce caller saving instructions. At the end, it adds all
433 // additional instructions produced by the register allocator to the
434 // instruction stream.
435 //----------------------------------------------------------------------------
436 void PhyRegAlloc::updateMachineCode()
439 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
441 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
443 // get the iterator for machine instructions
445 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
446 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
448 // iterate over all the machine instructions in BB
450 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
452 MachineInstr *MInst = *MInstIterator;
454 unsigned Opcode = MInst->getOpCode();
456 // do not process Phis
457 if (TM.getInstrInfo().isDummyPhiInstr(Opcode))
460 // Now insert speical instructions (if necessary) for call/return
463 if (TM.getInstrInfo().isCall(Opcode) ||
464 TM.getInstrInfo().isReturn(Opcode)) {
466 AddedInstrns *AI = AddedInstrMap[ MInst];
468 AI = new AddedInstrns();
469 AddedInstrMap[ MInst ] = AI;
472 // Tmp stack poistions are needed by some calls that have spilled args
473 // So reset it before we call each such method
475 mcInfo.popAllTempValues(TM);
477 if (TM.getInstrInfo().isCall(Opcode))
478 MRI.colorCallArgs(MInst, LRI, AI, *this, *BBI);
479 else if (TM.getInstrInfo().isReturn(Opcode))
480 MRI.colorRetValue(MInst, LRI, AI);
484 /* -- Using above code instead of this
486 // if this machine instr is call, insert caller saving code
488 if( (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
489 MRI.insertCallerSavingCode(MInst, *BBI, *this );
494 // reset the stack offset for temporary variables since we may
495 // need that to spill
496 // mcInfo.popAllTempValues(TM);
497 // TODO ** : do later
499 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
502 // Now replace set the registers for operands in the machine instruction
504 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
506 MachineOperand& Op = MInst->getOperand(OpNum);
508 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
509 Op.getOperandType() == MachineOperand::MO_CCRegister) {
511 const Value *const Val = Op.getVRegValue();
513 // delete this condition checking later (must assert if Val is null)
516 cerr << "Warning: NULL Value found for operand\n";
519 assert( Val && "Value is NULL");
521 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
525 // nothing to worry if it's a const or a label
528 cerr << "*NO LR for operand : " << Op ;
529 cerr << " [reg:" << Op.getAllocatedRegNum() << "]";
530 cerr << " in inst:\t" << *MInst << "\n";
533 // if register is not allocated, mark register as invalid
534 if( Op.getAllocatedRegNum() == -1)
535 Op.setRegForValue( MRI.getInvalidRegNum());
541 unsigned RCID = (LR->getRegClass())->getID();
543 if( LR->hasColor() ) {
544 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
548 // LR did NOT receive a color (register). Now, insert spill code
549 // for spilled opeands in this machine instruction
551 //assert(0 && "LR must be spilled");
552 insertCode4SpilledLR(LR, MInst, *BBI, OpNum );
557 } // for each operand
560 // Now add instructions that the register allocator inserts before/after
561 // this machine instructions (done only for calls/rets/incoming args)
562 // We do this here, to ensure that spill for an instruction is inserted
563 // closest as possible to an instruction (see above insertCode4Spill...)
565 // If there are instructions to be added, *before* this machine
566 // instruction, add them now.
568 if( AddedInstrMap[ MInst ] ) {
569 std::deque<MachineInstr *> &IBef = AddedInstrMap[MInst]->InstrnsBefore;
571 if( ! IBef.empty() ) {
572 std::deque<MachineInstr *>::iterator AdIt;
574 for( AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt ) {
577 cerr << "For inst " << *MInst;
578 cerr << " PREPENDed instr: " << **AdIt << "\n";
581 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
589 // If there are instructions to be added *after* this machine
590 // instruction, add them now
592 if(AddedInstrMap[MInst] &&
593 !AddedInstrMap[MInst]->InstrnsAfter.empty() ) {
595 // if there are delay slots for this instruction, the instructions
596 // added after it must really go after the delayed instruction(s)
597 // So, we move the InstrAfter of the current instruction to the
598 // corresponding delayed instruction
601 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
602 move2DelayedInstr(MInst, *(MInstIterator+delay) );
604 if(DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
610 // Here we can add the "instructions after" to the current
611 // instruction since there are no delay slots for this instruction
613 std::deque<MachineInstr *> &IAft = AddedInstrMap[MInst]->InstrnsAfter;
615 if( ! IAft.empty() ) {
617 std::deque<MachineInstr *>::iterator AdIt;
619 ++MInstIterator; // advance to the next instruction
621 for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
624 cerr << "For inst " << *MInst;
625 cerr << " APPENDed instr: " << **AdIt << "\n";
628 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
632 // MInsterator already points to the next instr. Since the
633 // for loop also increments it, decrement it to point to the
634 // instruction added last
643 } // for each machine instruction
649 //----------------------------------------------------------------------------
650 // This method inserts spill code for AN operand whose LR was spilled.
651 // This method may be called several times for a single machine instruction
652 // if it contains many spilled operands. Each time it is called, it finds
653 // a register which is not live at that instruction and also which is not
654 // used by other spilled operands of the same instruction. Then it uses
655 // this register temporarily to accomodate the spilled value.
656 //----------------------------------------------------------------------------
657 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
659 const BasicBlock *BB,
660 const unsigned OpNum) {
662 assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
663 (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
664 "Arg of a call/ret must be handled elsewhere");
666 MachineOperand& Op = MInst->getOperand(OpNum);
667 bool isDef = MInst->operandIsDefined(OpNum);
668 unsigned RegType = MRI.getRegType( LR );
669 int SpillOff = LR->getSpillOffFromFP();
670 RegClass *RC = LR->getRegClass();
671 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
673 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
675 MachineInstr *MIBef=NULL, *AdIMid=NULL, *MIAft=NULL;
677 int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,&LVSetBef, MIBef, MIAft);
679 // get the added instructions for this instruciton
680 AddedInstrns *AI = AddedInstrMap[ MInst ];
682 AI = new AddedInstrns();
683 AddedInstrMap[ MInst ] = AI;
689 // for a USE, we have to load the value of LR from stack to a TmpReg
690 // and use the TmpReg as one operand of instruction
692 // actual loading instruction
693 AdIMid = MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType);
696 AI->InstrnsBefore.push_back(MIBef);
698 AI->InstrnsBefore.push_back(AdIMid);
701 AI->InstrnsAfter.push_front(MIAft);
703 } else { // if this is a Def
704 // for a DEF, we have to store the value produced by this instruction
705 // on the stack position allocated for this LR
707 // actual storing instruction
708 AdIMid = MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType);
711 AI->InstrnsBefore.push_back(MIBef);
713 AI->InstrnsAfter.push_front(AdIMid);
716 AI->InstrnsAfter.push_front(MIAft);
720 cerr << "\nFor Inst " << *MInst;
721 cerr << " - SPILLED LR: "; printSet(*LR);
722 cerr << "\n - Added Instructions:";
723 if (MIBef) cerr << *MIBef;
725 if (MIAft) cerr << *MIAft;
727 Op.setRegForValue(TmpRegU); // set the opearnd
732 //----------------------------------------------------------------------------
733 // We can use the following method to get a temporary register to be used
734 // BEFORE any given machine instruction. If there is a register available,
735 // this method will simply return that register and set MIBef = MIAft = NULL.
736 // Otherwise, it will return a register and MIAft and MIBef will contain
737 // two instructions used to free up this returned register.
738 // Returned register number is the UNIFIED register number
739 //----------------------------------------------------------------------------
741 int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC,
743 const MachineInstr *MInst,
744 const ValueSet *LVSetBef,
745 MachineInstr *&MIBef,
746 MachineInstr *&MIAft) {
748 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
752 // we found an unused register, so we can simply use it
753 MIBef = MIAft = NULL;
756 // we couldn't find an unused register. Generate code to free up a reg by
757 // saving it on stack and restoring after the instruction
759 int TmpOff = mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
761 RegU = getUniRegNotUsedByThisInst(RC, MInst);
762 MIBef = MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType );
763 MIAft = MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType );
769 //----------------------------------------------------------------------------
770 // This method is called to get a new unused register that can be used to
771 // accomodate a spilled value.
772 // This method may be called several times for a single machine instruction
773 // if it contains many spilled operands. Each time it is called, it finds
774 // a register which is not live at that instruction and also which is not
775 // used by other spilled operands of the same instruction.
776 // Return register number is relative to the register class. NOT
778 //----------------------------------------------------------------------------
779 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
780 const MachineInstr *MInst,
781 const ValueSet *LVSetBef) {
783 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
785 bool *IsColorUsedArr = RC->getIsColorUsedArr();
787 for(unsigned i=0; i < NumAvailRegs; i++) // Reset array
788 IsColorUsedArr[i] = false;
790 ValueSet::const_iterator LIt = LVSetBef->begin();
792 // for each live var in live variable set after machine inst
793 for( ; LIt != LVSetBef->end(); ++LIt) {
795 // get the live range corresponding to live var
796 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
798 // LR can be null if it is a const since a const
799 // doesn't have a dominating def - see Assumptions above
801 if( LRofLV->hasColor() )
802 IsColorUsedArr[ LRofLV->getColor() ] = true;
805 // It is possible that one operand of this MInst was already spilled
806 // and it received some register temporarily. If that's the case,
807 // it is recorded in machine operand. We must skip such registers.
809 setRelRegsUsedByThisInst(RC, MInst);
811 unsigned c; // find first unused color
812 for( c=0; c < NumAvailRegs; c++)
813 if( ! IsColorUsedArr[ c ] ) break;
816 return MRI.getUnifiedRegNum(RC->getID(), c);
824 //----------------------------------------------------------------------------
825 // Get any other register in a register class, other than what is used
826 // by operands of a machine instruction. Returns the unified reg number.
827 //----------------------------------------------------------------------------
828 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
829 const MachineInstr *MInst) {
831 bool *IsColorUsedArr = RC->getIsColorUsedArr();
832 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
835 for(unsigned i=0; i < NumAvailRegs ; i++) // Reset array
836 IsColorUsedArr[i] = false;
838 setRelRegsUsedByThisInst(RC, MInst);
840 unsigned c; // find first unused color
841 for( c=0; c < RC->getNumOfAvailRegs(); c++)
842 if( ! IsColorUsedArr[ c ] ) break;
845 return MRI.getUnifiedRegNum(RC->getID(), c);
847 assert( 0 && "FATAL: No free register could be found in reg class!!");
852 //----------------------------------------------------------------------------
853 // This method modifies the IsColorUsedArr of the register class passed to it.
854 // It sets the bits corresponding to the registers used by this machine
855 // instructions. Both explicit and implicit operands are set.
856 //----------------------------------------------------------------------------
857 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
858 const MachineInstr *MInst ) {
860 bool *IsColorUsedArr = RC->getIsColorUsedArr();
862 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
864 const MachineOperand& Op = MInst->getOperand(OpNum);
866 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
867 Op.getOperandType() == MachineOperand::MO_CCRegister ) {
869 const Value *const Val = Op.getVRegValue();
872 if( MRI.getRegClassIDOfValue(Val) == RC->getID() ) {
874 if( (Reg=Op.getAllocatedRegNum()) != -1) {
875 IsColorUsedArr[ Reg ] = true;
878 // it is possilbe that this operand still is not marked with
879 // a register but it has a LR and that received a color
881 LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
883 if( LROfVal->hasColor() )
884 IsColorUsedArr[ LROfVal->getColor() ] = true;
887 } // if reg classes are the same
889 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
890 IsColorUsedArr[ Op.getMachineRegNum() ] = true;
894 // If there are implicit references, mark them as well
896 for(unsigned z=0; z < MInst->getNumImplicitRefs(); z++) {
898 LiveRange *const LRofImpRef =
899 LRI.getLiveRangeForValue( MInst->getImplicitRef(z) );
901 if(LRofImpRef && LRofImpRef->hasColor())
902 IsColorUsedArr[LRofImpRef->getColor()] = true;
913 //----------------------------------------------------------------------------
914 // If there are delay slots for an instruction, the instructions
915 // added after it must really go after the delayed instruction(s).
916 // So, we move the InstrAfter of that instruction to the
917 // corresponding delayed instruction using the following method.
919 //----------------------------------------------------------------------------
920 void PhyRegAlloc:: move2DelayedInstr(const MachineInstr *OrigMI,
921 const MachineInstr *DelayedMI) {
923 // "added after" instructions of the original instr
924 std::deque<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI]->InstrnsAfter;
926 // "added instructions" of the delayed instr
927 AddedInstrns *DelayAdI = AddedInstrMap[DelayedMI];
929 if(! DelayAdI ) { // create a new "added after" if necessary
930 DelayAdI = new AddedInstrns();
931 AddedInstrMap[DelayedMI] = DelayAdI;
934 // "added after" instructions of the delayed instr
935 std::deque<MachineInstr *> &DelayedAft = DelayAdI->InstrnsAfter;
937 // go thru all the "added after instructions" of the original instruction
938 // and append them to the "addded after instructions" of the delayed
940 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
942 // empty the "added after instructions" of the original instruction
946 //----------------------------------------------------------------------------
947 // This method prints the code with registers after register allocation is
949 //----------------------------------------------------------------------------
950 void PhyRegAlloc::printMachineCode()
953 cerr << "\n;************** Method " << Meth->getName()
954 << " *****************\n";
956 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
958 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
960 cerr << "\n"; printLabel( *BBI); cerr << ": ";
962 // get the iterator for machine instructions
963 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
964 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
966 // iterate over all the machine instructions in BB
967 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
969 MachineInstr *const MInst = *MInstIterator;
973 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
976 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
978 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
980 MachineOperand& Op = MInst->getOperand(OpNum);
982 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
983 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
984 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
986 const Value *const Val = Op.getVRegValue () ;
987 // ****this code is temporary till NULL Values are fixed
989 cerr << "\t<*NULL*>";
993 // if a label or a constant
994 if(isa<BasicBlock>(Val)) {
995 cerr << "\t"; printLabel( Op.getVRegValue () );
997 // else it must be a register value
998 const int RegNum = Op.getAllocatedRegNum();
1000 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
1001 if (Val->hasName() )
1002 cerr << "(" << Val->getName() << ")";
1004 cerr << "(" << Val << ")";
1009 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
1011 if( LROfVal->hasSpillOffset() )
1016 else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
1017 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1021 cerr << "\t" << Op; // use dump field
1026 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1027 if( NumOfImpRefs > 0) {
1028 cerr << "\tImplicit:";
1030 for(unsigned z=0; z < NumOfImpRefs; z++)
1031 cerr << RAV(MInst->getImplicitRef(z)) << "\t";
1034 } // for all machine instructions
1046 //----------------------------------------------------------------------------
1048 //----------------------------------------------------------------------------
1050 void PhyRegAlloc::colorCallRetArgs()
1053 CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
1054 CallRetInstrListType::const_iterator It = CallRetInstList.begin();
1056 for( ; It != CallRetInstList.end(); ++It ) {
1058 const MachineInstr *const CRMI = *It;
1059 unsigned OpCode = CRMI->getOpCode();
1061 // get the added instructions for this Call/Ret instruciton
1062 AddedInstrns *AI = AddedInstrMap[ CRMI ];
1064 AI = new AddedInstrns();
1065 AddedInstrMap[ CRMI ] = AI;
1068 // Tmp stack poistions are needed by some calls that have spilled args
1069 // So reset it before we call each such method
1070 //mcInfo.popAllTempValues(TM);
1074 if (TM.getInstrInfo().isCall(OpCode))
1075 MRI.colorCallArgs(CRMI, LRI, AI, *this);
1076 else if (TM.getInstrInfo().isReturn(OpCode))
1077 MRI.colorRetValue( CRMI, LRI, AI );
1079 assert(0 && "Non Call/Ret instrn in CallRetInstrList\n");
1085 //----------------------------------------------------------------------------
1087 //----------------------------------------------------------------------------
1088 void PhyRegAlloc::colorIncomingArgs()
1090 const BasicBlock *const FirstBB = Meth->front();
1091 const MachineInstr *FirstMI = FirstBB->getMachineInstrVec().front();
1092 assert(FirstMI && "No machine instruction in entry BB");
1094 AddedInstrns *AI = AddedInstrMap[FirstMI];
1096 AddedInstrMap[FirstMI] = AI = new AddedInstrns();
1098 MRI.colorMethodArgs(Meth, LRI, AI);
1102 //----------------------------------------------------------------------------
1103 // Used to generate a label for a basic block
1104 //----------------------------------------------------------------------------
1105 void PhyRegAlloc::printLabel(const Value *const Val) {
1107 cerr << Val->getName();
1109 cerr << "Label" << Val;
1113 //----------------------------------------------------------------------------
1114 // This method calls setSugColorUsable method of each live range. This
1115 // will determine whether the suggested color of LR is really usable.
1116 // A suggested color is not usable when the suggested color is volatile
1117 // AND when there are call interferences
1118 //----------------------------------------------------------------------------
1120 void PhyRegAlloc::markUnusableSugColors()
1122 if(DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
1124 // hash map iterator
1125 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1126 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1128 for(; HMI != HMIEnd ; ++HMI ) {
1130 LiveRange *L = HMI->second; // get the LiveRange
1132 if(L->hasSuggestedColor()) {
1133 int RCID = L->getRegClass()->getID();
1134 if( MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1135 L->isCallInterference() )
1136 L->setSuggestedColorUsable( false );
1138 L->setSuggestedColorUsable( true );
1140 } // if L->hasSuggestedColor()
1142 } // for all LR's in hash map
1147 //----------------------------------------------------------------------------
1148 // The following method will set the stack offsets of the live ranges that
1149 // are decided to be spillled. This must be called just after coloring the
1150 // LRs using the graph coloring algo. For each live range that is spilled,
1151 // this method allocate a new spill position on the stack.
1152 //----------------------------------------------------------------------------
1154 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1155 if (DEBUG_RA) cerr << "\nsetting LR stack offsets ...\n";
1157 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
1158 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
1160 for( ; HMI != HMIEnd ; ++HMI) {
1161 if (HMI->first && HMI->second) {
1162 LiveRange *L = HMI->second; // get the LiveRange
1163 if (!L->hasColor()) // NOTE: ** allocating the size of long Type **
1164 L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
1166 } // for all LR's in hash map
1171 //----------------------------------------------------------------------------
1172 // The entry pont to Register Allocation
1173 //----------------------------------------------------------------------------
1175 void PhyRegAlloc::allocateRegisters()
1178 // make sure that we put all register classes into the RegClassList
1179 // before we call constructLiveRanges (now done in the constructor of
1180 // PhyRegAlloc class).
1182 LRI.constructLiveRanges(); // create LR info
1185 LRI.printLiveRanges();
1187 createIGNodeListsAndIGs(); // create IGNode list and IGs
1189 buildInterferenceGraphs(); // build IGs in all reg classes
1193 // print all LRs in all reg classes
1194 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1195 RegClassList[ rc ]->printIGNodeList();
1197 // print IGs in all register classes
1198 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1199 RegClassList[ rc ]->printIG();
1203 LRI.coalesceLRs(); // coalesce all live ranges
1207 // print all LRs in all reg classes
1208 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1209 RegClassList[ rc ]->printIGNodeList();
1211 // print IGs in all register classes
1212 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1213 RegClassList[ rc ]->printIG();
1217 // mark un-usable suggested color before graph coloring algorithm.
1218 // When this is done, the graph coloring algo will not reserve
1219 // suggested color unnecessarily - they can be used by another LR
1221 markUnusableSugColors();
1223 // color all register classes using the graph coloring algo
1224 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1225 RegClassList[ rc ]->colorAllRegs();
1227 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1228 // a poistion for such spilled LRs
1230 allocateStackSpace4SpilledLRs();
1232 mcInfo.popAllTempValues(TM); // TODO **Check
1234 // color incoming args - if the correct color was not received
1235 // insert code to copy to the correct register
1237 colorIncomingArgs();
1239 // Now update the machine code with register names and add any
1240 // additional code inserted by the register allocator to the instruction
1243 updateMachineCode();
1246 MachineCodeForMethod::get(Meth).dump();
1247 printMachineCode(); // only for DEBUGGING