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) {
215 cerr << "\n For call inst: " << *MInst;
217 ValueSet::const_iterator LIt = LVSetAft->begin();
219 // for each live var in live variable set after machine inst
221 for( ; LIt != LVSetAft->end(); ++LIt) {
223 // get the live range corresponding to live var
225 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
227 if( LR && DEBUG_RA) {
228 cerr << "\n\tLR Aft Call: ";
232 // LR can be null if it is a const since a const
233 // doesn't have a dominating def - see Assumptions above
236 LR->setCallInterference();
238 cerr << "\n ++Added call interf for LR: " ;
245 // Now find the LR of the return value of the call
246 // We do this because, we look at the LV set *after* the instruction
247 // to determine, which LRs must be saved across calls. The return value
248 // of the call is live in this set - but it does not interfere with call
249 // (i.e., we can allocate a volatile register to the return value)
251 if( const Value *RetVal = MRI.getCallInstRetVal( MInst )) {
252 LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
253 assert( RetValLR && "No LR for RetValue of call");
254 RetValLR->clearCallInterference();
257 // If the CALL is an indirect call, find the LR of the function pointer.
258 // That has a call interference because it conflicts with outgoing args.
259 if( const Value *AddrVal = MRI.getCallInstIndirectAddrVal( MInst )) {
260 LiveRange *AddrValLR = LRI.getLiveRangeForValue( AddrVal );
261 assert( AddrValLR && "No LR for indirect addr val of call");
262 AddrValLR->setCallInterference();
270 //----------------------------------------------------------------------------
271 // This method will walk thru code and create interferences in the IG of
272 // each RegClass. Also, this method calculates the spill cost of each
273 // Live Range (it is done in this method to save another pass over the code).
274 //----------------------------------------------------------------------------
275 void PhyRegAlloc::buildInterferenceGraphs()
278 if(DEBUG_RA) cerr << "Creating interference graphs ...\n";
280 unsigned BBLoopDepthCost;
281 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
283 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
285 // find the 10^(loop_depth) of this BB
287 BBLoopDepthCost = (unsigned) pow( 10.0, LoopDepthCalc->getLoopDepth(*BBI));
289 // get the iterator for machine instructions
291 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
292 MachineCodeForBasicBlock::const_iterator
293 MInstIterator = MIVec.begin();
295 // iterate over all the machine instructions in BB
297 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
299 const MachineInstr *MInst = *MInstIterator;
301 // get the LV set after the instruction
303 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, *BBI);
305 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
308 // set the isCallInterference flag of each live range wich extends
309 // accross this call instruction. This information is used by graph
310 // coloring algo to avoid allocating volatile colors to live ranges
311 // that span across calls (since they have to be saved/restored)
313 setCallInterferences(MInst, &LVSetAI);
317 // iterate over all MI operands to find defs
319 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
320 OpE = MInst->end(); OpI != OpE; ++OpI) {
321 if (OpI.isDef()) // create a new LR iff this operand is a def
322 addInterference(*OpI, &LVSetAI, isCallInst);
324 // Calculate the spill cost of each live range
326 LiveRange *LR = LRI.getLiveRangeForValue(*OpI);
327 if (LR) LR->addSpillCost(BBLoopDepthCost);
331 // if there are multiple defs in this instruction e.g. in SETX
333 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
334 addInterf4PseudoInstr(MInst);
337 // Also add interference for any implicit definitions in a machine
338 // instr (currently, only calls have this).
340 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
341 if( NumOfImpRefs > 0 ) {
342 for(unsigned z=0; z < NumOfImpRefs; z++)
343 if( MInst->implicitRefIsDefined(z) )
344 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
348 } // for all machine instructions in BB
350 } // for all BBs in method
353 // add interferences for method arguments. Since there are no explict
354 // defs in method for args, we have to add them manually
356 addInterferencesForArgs();
359 cerr << "Interference graphs calculted!\n";
365 //--------------------------------------------------------------------------
366 // Pseudo instructions will be exapnded to multiple instructions by the
367 // assembler. Consequently, all the opernds must get distinct registers.
368 // Therefore, we mark all operands of a pseudo instruction as they interfere
370 //--------------------------------------------------------------------------
371 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
373 bool setInterf = false;
375 // iterate over MI operands to find defs
377 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
378 ItE = MInst->end(); It1 != ItE; ++It1) {
379 const LiveRange *LROfOp1 = LRI.getLiveRangeForValue(*It1);
380 assert((LROfOp1 || !It1.isDef()) && "No LR for Def in PSEUDO insruction");
382 MachineInstr::const_val_op_iterator It2 = It1;
383 for(++It2; It2 != ItE; ++It2) {
384 const LiveRange *LROfOp2 = LRI.getLiveRangeForValue(*It2);
387 RegClass *RCOfOp1 = LROfOp1->getRegClass();
388 RegClass *RCOfOp2 = LROfOp2->getRegClass();
390 if( RCOfOp1 == RCOfOp2 ){
391 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
395 } // for all other defs in machine instr
396 } // for all operands in an instruction
398 if (!setInterf && MInst->getNumOperands() > 2) {
399 cerr << "\nInterf not set for any operand in pseudo instr:\n";
401 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
407 //----------------------------------------------------------------------------
408 // This method will add interferences for incoming arguments to a method.
409 //----------------------------------------------------------------------------
410 void PhyRegAlloc::addInterferencesForArgs() {
411 // get the InSet of root BB
412 const ValueSet &InSet = LVI->getInSetOfBB(Meth->front());
414 // get the argument list
415 const Method::ArgumentListType& ArgList = Meth->getArgumentList();
417 // get an iterator to arg list
418 Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();
421 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
422 addInterference((Value*)*ArgIt, &InSet, false);// add interferences between
423 // args and LVars at start
425 cerr << " - %% adding interference for argument "
426 << RAV((const Value *)*ArgIt) << "\n";
433 //----------------------------------------------------------------------------
434 // This method is called after register allocation is complete to set the
435 // allocated reisters in the machine code. This code will add register numbers
436 // to MachineOperands that contain a Value. Also it calls target specific
437 // methods to produce caller saving instructions. At the end, it adds all
438 // additional instructions produced by the register allocator to the
439 // instruction stream.
440 //----------------------------------------------------------------------------
441 void PhyRegAlloc::updateMachineCode()
444 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
446 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
448 // get the iterator for machine instructions
450 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
451 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
453 // iterate over all the machine instructions in BB
455 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
457 MachineInstr *MInst = *MInstIterator;
459 unsigned Opcode = MInst->getOpCode();
461 // do not process Phis
462 if (TM.getInstrInfo().isDummyPhiInstr(Opcode))
465 // Now insert speical instructions (if necessary) for call/return
468 if (TM.getInstrInfo().isCall(Opcode) ||
469 TM.getInstrInfo().isReturn(Opcode)) {
471 AddedInstrns *AI = AddedInstrMap[ MInst];
473 AI = new AddedInstrns();
474 AddedInstrMap[ MInst ] = AI;
477 // Tmp stack poistions are needed by some calls that have spilled args
478 // So reset it before we call each such method
480 mcInfo.popAllTempValues(TM);
482 if (TM.getInstrInfo().isCall(Opcode))
483 MRI.colorCallArgs(MInst, LRI, AI, *this, *BBI);
484 else if (TM.getInstrInfo().isReturn(Opcode))
485 MRI.colorRetValue(MInst, LRI, AI);
489 /* -- Using above code instead of this
491 // if this machine instr is call, insert caller saving code
493 if( (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
494 MRI.insertCallerSavingCode(MInst, *BBI, *this );
499 // reset the stack offset for temporary variables since we may
500 // need that to spill
501 // mcInfo.popAllTempValues(TM);
502 // TODO ** : do later
504 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
507 // Now replace set the registers for operands in the machine instruction
509 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
511 MachineOperand& Op = MInst->getOperand(OpNum);
513 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
514 Op.getOperandType() == MachineOperand::MO_CCRegister) {
516 const Value *const Val = Op.getVRegValue();
518 // delete this condition checking later (must assert if Val is null)
521 cerr << "Warning: NULL Value found for operand\n";
524 assert( Val && "Value is NULL");
526 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
530 // nothing to worry if it's a const or a label
533 cerr << "*NO LR for operand : " << Op ;
534 cerr << " [reg:" << Op.getAllocatedRegNum() << "]";
535 cerr << " in inst:\t" << *MInst << "\n";
538 // if register is not allocated, mark register as invalid
539 if( Op.getAllocatedRegNum() == -1)
540 Op.setRegForValue( MRI.getInvalidRegNum());
546 unsigned RCID = (LR->getRegClass())->getID();
548 if( LR->hasColor() ) {
549 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
553 // LR did NOT receive a color (register). Now, insert spill code
554 // for spilled opeands in this machine instruction
556 //assert(0 && "LR must be spilled");
557 insertCode4SpilledLR(LR, MInst, *BBI, OpNum );
562 } // for each operand
565 // Now add instructions that the register allocator inserts before/after
566 // this machine instructions (done only for calls/rets/incoming args)
567 // We do this here, to ensure that spill for an instruction is inserted
568 // closest as possible to an instruction (see above insertCode4Spill...)
570 // If there are instructions to be added, *before* this machine
571 // instruction, add them now.
573 if( AddedInstrMap[ MInst ] ) {
574 std::deque<MachineInstr *> &IBef = AddedInstrMap[MInst]->InstrnsBefore;
576 if( ! IBef.empty() ) {
577 std::deque<MachineInstr *>::iterator AdIt;
579 for( AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt ) {
582 cerr << "For inst " << *MInst;
583 cerr << " PREPENDed instr: " << **AdIt << "\n";
586 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
594 // If there are instructions to be added *after* this machine
595 // instruction, add them now
597 if(AddedInstrMap[MInst] &&
598 !AddedInstrMap[MInst]->InstrnsAfter.empty() ) {
600 // if there are delay slots for this instruction, the instructions
601 // added after it must really go after the delayed instruction(s)
602 // So, we move the InstrAfter of the current instruction to the
603 // corresponding delayed instruction
606 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
607 move2DelayedInstr(MInst, *(MInstIterator+delay) );
609 if(DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
615 // Here we can add the "instructions after" to the current
616 // instruction since there are no delay slots for this instruction
618 std::deque<MachineInstr *> &IAft = AddedInstrMap[MInst]->InstrnsAfter;
620 if( ! IAft.empty() ) {
622 std::deque<MachineInstr *>::iterator AdIt;
624 ++MInstIterator; // advance to the next instruction
626 for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
629 cerr << "For inst " << *MInst;
630 cerr << " APPENDed instr: " << **AdIt << "\n";
633 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
637 // MInsterator already points to the next instr. Since the
638 // for loop also increments it, decrement it to point to the
639 // instruction added last
648 } // for each machine instruction
654 //----------------------------------------------------------------------------
655 // This method inserts spill code for AN operand whose LR was spilled.
656 // This method may be called several times for a single machine instruction
657 // if it contains many spilled operands. Each time it is called, it finds
658 // a register which is not live at that instruction and also which is not
659 // used by other spilled operands of the same instruction. Then it uses
660 // this register temporarily to accomodate the spilled value.
661 //----------------------------------------------------------------------------
662 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
664 const BasicBlock *BB,
665 const unsigned OpNum) {
667 assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
668 (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
669 "Arg of a call/ret must be handled elsewhere");
671 MachineOperand& Op = MInst->getOperand(OpNum);
672 bool isDef = MInst->operandIsDefined(OpNum);
673 unsigned RegType = MRI.getRegType( LR );
674 int SpillOff = LR->getSpillOffFromFP();
675 RegClass *RC = LR->getRegClass();
676 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
678 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
680 MachineInstr *MIBef=NULL, *AdIMid=NULL, *MIAft=NULL;
682 int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,&LVSetBef, MIBef, MIAft);
684 // get the added instructions for this instruciton
685 AddedInstrns *AI = AddedInstrMap[ MInst ];
687 AI = new AddedInstrns();
688 AddedInstrMap[ MInst ] = AI;
694 // for a USE, we have to load the value of LR from stack to a TmpReg
695 // and use the TmpReg as one operand of instruction
697 // actual loading instruction
698 AdIMid = MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType);
701 AI->InstrnsBefore.push_back(MIBef);
703 AI->InstrnsBefore.push_back(AdIMid);
706 AI->InstrnsAfter.push_front(MIAft);
708 } else { // if this is a Def
709 // for a DEF, we have to store the value produced by this instruction
710 // on the stack position allocated for this LR
712 // actual storing instruction
713 AdIMid = MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType);
716 AI->InstrnsBefore.push_back(MIBef);
718 AI->InstrnsAfter.push_front(AdIMid);
721 AI->InstrnsAfter.push_front(MIAft);
725 cerr << "\nFor Inst " << *MInst;
726 cerr << " - SPILLED LR: "; printSet(*LR);
727 cerr << "\n - Added Instructions:";
728 if (MIBef) cerr << *MIBef;
730 if (MIAft) cerr << *MIAft;
732 Op.setRegForValue(TmpRegU); // set the opearnd
737 //----------------------------------------------------------------------------
738 // We can use the following method to get a temporary register to be used
739 // BEFORE any given machine instruction. If there is a register available,
740 // this method will simply return that register and set MIBef = MIAft = NULL.
741 // Otherwise, it will return a register and MIAft and MIBef will contain
742 // two instructions used to free up this returned register.
743 // Returned register number is the UNIFIED register number
744 //----------------------------------------------------------------------------
746 int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC,
748 const MachineInstr *MInst,
749 const ValueSet *LVSetBef,
750 MachineInstr *&MIBef,
751 MachineInstr *&MIAft) {
753 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
757 // we found an unused register, so we can simply use it
758 MIBef = MIAft = NULL;
761 // we couldn't find an unused register. Generate code to free up a reg by
762 // saving it on stack and restoring after the instruction
764 int TmpOff = mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
766 RegU = getUniRegNotUsedByThisInst(RC, MInst);
767 MIBef = MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType );
768 MIAft = MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType );
774 //----------------------------------------------------------------------------
775 // This method is called to get a new unused register that can be used to
776 // accomodate a spilled value.
777 // This method may be called several times for a single machine instruction
778 // if it contains many spilled operands. Each time it is called, it finds
779 // a register which is not live at that instruction and also which is not
780 // used by other spilled operands of the same instruction.
781 // Return register number is relative to the register class. NOT
783 //----------------------------------------------------------------------------
784 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
785 const MachineInstr *MInst,
786 const ValueSet *LVSetBef) {
788 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
790 bool *IsColorUsedArr = RC->getIsColorUsedArr();
792 for(unsigned i=0; i < NumAvailRegs; i++) // Reset array
793 IsColorUsedArr[i] = false;
795 ValueSet::const_iterator LIt = LVSetBef->begin();
797 // for each live var in live variable set after machine inst
798 for( ; LIt != LVSetBef->end(); ++LIt) {
800 // get the live range corresponding to live var
801 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
803 // LR can be null if it is a const since a const
804 // doesn't have a dominating def - see Assumptions above
806 if( LRofLV->hasColor() )
807 IsColorUsedArr[ LRofLV->getColor() ] = true;
810 // It is possible that one operand of this MInst was already spilled
811 // and it received some register temporarily. If that's the case,
812 // it is recorded in machine operand. We must skip such registers.
814 setRelRegsUsedByThisInst(RC, MInst);
816 unsigned c; // find first unused color
817 for( c=0; c < NumAvailRegs; c++)
818 if( ! IsColorUsedArr[ c ] ) break;
821 return MRI.getUnifiedRegNum(RC->getID(), c);
829 //----------------------------------------------------------------------------
830 // Get any other register in a register class, other than what is used
831 // by operands of a machine instruction. Returns the unified reg number.
832 //----------------------------------------------------------------------------
833 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
834 const MachineInstr *MInst) {
836 bool *IsColorUsedArr = RC->getIsColorUsedArr();
837 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
840 for(unsigned i=0; i < NumAvailRegs ; i++) // Reset array
841 IsColorUsedArr[i] = false;
843 setRelRegsUsedByThisInst(RC, MInst);
845 unsigned c; // find first unused color
846 for( c=0; c < RC->getNumOfAvailRegs(); c++)
847 if( ! IsColorUsedArr[ c ] ) break;
850 return MRI.getUnifiedRegNum(RC->getID(), c);
852 assert( 0 && "FATAL: No free register could be found in reg class!!");
857 //----------------------------------------------------------------------------
858 // This method modifies the IsColorUsedArr of the register class passed to it.
859 // It sets the bits corresponding to the registers used by this machine
860 // instructions. Both explicit and implicit operands are set.
861 //----------------------------------------------------------------------------
862 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
863 const MachineInstr *MInst ) {
865 bool *IsColorUsedArr = RC->getIsColorUsedArr();
867 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
869 const MachineOperand& Op = MInst->getOperand(OpNum);
871 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
872 Op.getOperandType() == MachineOperand::MO_CCRegister ) {
874 const Value *const Val = Op.getVRegValue();
877 if( MRI.getRegClassIDOfValue(Val) == RC->getID() ) {
879 if( (Reg=Op.getAllocatedRegNum()) != -1) {
880 IsColorUsedArr[ Reg ] = true;
883 // it is possilbe that this operand still is not marked with
884 // a register but it has a LR and that received a color
886 LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
888 if( LROfVal->hasColor() )
889 IsColorUsedArr[ LROfVal->getColor() ] = true;
892 } // if reg classes are the same
894 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
895 IsColorUsedArr[ Op.getMachineRegNum() ] = true;
899 // If there are implicit references, mark them as well
901 for(unsigned z=0; z < MInst->getNumImplicitRefs(); z++) {
903 LiveRange *const LRofImpRef =
904 LRI.getLiveRangeForValue( MInst->getImplicitRef(z) );
906 if(LRofImpRef && LRofImpRef->hasColor())
907 IsColorUsedArr[LRofImpRef->getColor()] = true;
918 //----------------------------------------------------------------------------
919 // If there are delay slots for an instruction, the instructions
920 // added after it must really go after the delayed instruction(s).
921 // So, we move the InstrAfter of that instruction to the
922 // corresponding delayed instruction using the following method.
924 //----------------------------------------------------------------------------
925 void PhyRegAlloc:: move2DelayedInstr(const MachineInstr *OrigMI,
926 const MachineInstr *DelayedMI) {
928 // "added after" instructions of the original instr
929 std::deque<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI]->InstrnsAfter;
931 // "added instructions" of the delayed instr
932 AddedInstrns *DelayAdI = AddedInstrMap[DelayedMI];
934 if(! DelayAdI ) { // create a new "added after" if necessary
935 DelayAdI = new AddedInstrns();
936 AddedInstrMap[DelayedMI] = DelayAdI;
939 // "added after" instructions of the delayed instr
940 std::deque<MachineInstr *> &DelayedAft = DelayAdI->InstrnsAfter;
942 // go thru all the "added after instructions" of the original instruction
943 // and append them to the "addded after instructions" of the delayed
945 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
947 // empty the "added after instructions" of the original instruction
951 //----------------------------------------------------------------------------
952 // This method prints the code with registers after register allocation is
954 //----------------------------------------------------------------------------
955 void PhyRegAlloc::printMachineCode()
958 cerr << "\n;************** Method " << Meth->getName()
959 << " *****************\n";
961 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
963 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
965 cerr << "\n"; printLabel( *BBI); cerr << ": ";
967 // get the iterator for machine instructions
968 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
969 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
971 // iterate over all the machine instructions in BB
972 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
974 MachineInstr *const MInst = *MInstIterator;
978 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
981 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
983 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
985 MachineOperand& Op = MInst->getOperand(OpNum);
987 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
988 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
989 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
991 const Value *const Val = Op.getVRegValue () ;
992 // ****this code is temporary till NULL Values are fixed
994 cerr << "\t<*NULL*>";
998 // if a label or a constant
999 if(isa<BasicBlock>(Val)) {
1000 cerr << "\t"; printLabel( Op.getVRegValue () );
1002 // else it must be a register value
1003 const int RegNum = Op.getAllocatedRegNum();
1005 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
1006 if (Val->hasName() )
1007 cerr << "(" << Val->getName() << ")";
1009 cerr << "(" << Val << ")";
1014 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
1016 if( LROfVal->hasSpillOffset() )
1021 else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
1022 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1026 cerr << "\t" << Op; // use dump field
1031 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1032 if( NumOfImpRefs > 0) {
1033 cerr << "\tImplicit:";
1035 for(unsigned z=0; z < NumOfImpRefs; z++)
1036 cerr << RAV(MInst->getImplicitRef(z)) << "\t";
1039 } // for all machine instructions
1051 //----------------------------------------------------------------------------
1053 //----------------------------------------------------------------------------
1055 void PhyRegAlloc::colorCallRetArgs()
1058 CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
1059 CallRetInstrListType::const_iterator It = CallRetInstList.begin();
1061 for( ; It != CallRetInstList.end(); ++It ) {
1063 const MachineInstr *const CRMI = *It;
1064 unsigned OpCode = CRMI->getOpCode();
1066 // get the added instructions for this Call/Ret instruciton
1067 AddedInstrns *AI = AddedInstrMap[ CRMI ];
1069 AI = new AddedInstrns();
1070 AddedInstrMap[ CRMI ] = AI;
1073 // Tmp stack poistions are needed by some calls that have spilled args
1074 // So reset it before we call each such method
1075 //mcInfo.popAllTempValues(TM);
1079 if (TM.getInstrInfo().isCall(OpCode))
1080 MRI.colorCallArgs(CRMI, LRI, AI, *this);
1081 else if (TM.getInstrInfo().isReturn(OpCode))
1082 MRI.colorRetValue( CRMI, LRI, AI );
1084 assert(0 && "Non Call/Ret instrn in CallRetInstrList\n");
1090 //----------------------------------------------------------------------------
1092 //----------------------------------------------------------------------------
1093 void PhyRegAlloc::colorIncomingArgs()
1095 const BasicBlock *const FirstBB = Meth->front();
1096 const MachineInstr *FirstMI = FirstBB->getMachineInstrVec().front();
1097 assert(FirstMI && "No machine instruction in entry BB");
1099 AddedInstrns *AI = AddedInstrMap[FirstMI];
1101 AddedInstrMap[FirstMI] = AI = new AddedInstrns();
1103 MRI.colorMethodArgs(Meth, LRI, AI);
1107 //----------------------------------------------------------------------------
1108 // Used to generate a label for a basic block
1109 //----------------------------------------------------------------------------
1110 void PhyRegAlloc::printLabel(const Value *const Val) {
1112 cerr << Val->getName();
1114 cerr << "Label" << Val;
1118 //----------------------------------------------------------------------------
1119 // This method calls setSugColorUsable method of each live range. This
1120 // will determine whether the suggested color of LR is really usable.
1121 // A suggested color is not usable when the suggested color is volatile
1122 // AND when there are call interferences
1123 //----------------------------------------------------------------------------
1125 void PhyRegAlloc::markUnusableSugColors()
1127 if(DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
1129 // hash map iterator
1130 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1131 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1133 for(; HMI != HMIEnd ; ++HMI ) {
1135 LiveRange *L = HMI->second; // get the LiveRange
1137 if(L->hasSuggestedColor()) {
1138 int RCID = L->getRegClass()->getID();
1139 if( MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1140 L->isCallInterference() )
1141 L->setSuggestedColorUsable( false );
1143 L->setSuggestedColorUsable( true );
1145 } // if L->hasSuggestedColor()
1147 } // for all LR's in hash map
1152 //----------------------------------------------------------------------------
1153 // The following method will set the stack offsets of the live ranges that
1154 // are decided to be spillled. This must be called just after coloring the
1155 // LRs using the graph coloring algo. For each live range that is spilled,
1156 // this method allocate a new spill position on the stack.
1157 //----------------------------------------------------------------------------
1159 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1160 if (DEBUG_RA) cerr << "\nsetting LR stack offsets ...\n";
1162 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
1163 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
1165 for( ; HMI != HMIEnd ; ++HMI) {
1166 if (HMI->first && HMI->second) {
1167 LiveRange *L = HMI->second; // get the LiveRange
1168 if (!L->hasColor()) // NOTE: ** allocating the size of long Type **
1169 L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
1171 } // for all LR's in hash map
1176 //----------------------------------------------------------------------------
1177 // The entry pont to Register Allocation
1178 //----------------------------------------------------------------------------
1180 void PhyRegAlloc::allocateRegisters()
1183 // make sure that we put all register classes into the RegClassList
1184 // before we call constructLiveRanges (now done in the constructor of
1185 // PhyRegAlloc class).
1187 LRI.constructLiveRanges(); // create LR info
1190 LRI.printLiveRanges();
1192 createIGNodeListsAndIGs(); // create IGNode list and IGs
1194 buildInterferenceGraphs(); // build IGs in all reg classes
1198 // print all LRs in all reg classes
1199 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1200 RegClassList[ rc ]->printIGNodeList();
1202 // print IGs in all register classes
1203 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1204 RegClassList[ rc ]->printIG();
1208 LRI.coalesceLRs(); // coalesce all live ranges
1212 // print all LRs in all reg classes
1213 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1214 RegClassList[ rc ]->printIGNodeList();
1216 // print IGs in all register classes
1217 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1218 RegClassList[ rc ]->printIG();
1222 // mark un-usable suggested color before graph coloring algorithm.
1223 // When this is done, the graph coloring algo will not reserve
1224 // suggested color unnecessarily - they can be used by another LR
1226 markUnusableSugColors();
1228 // color all register classes using the graph coloring algo
1229 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1230 RegClassList[ rc ]->colorAllRegs();
1232 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1233 // a poistion for such spilled LRs
1235 allocateStackSpace4SpilledLRs();
1237 mcInfo.popAllTempValues(TM); // TODO **Check
1239 // color incoming args - if the correct color was not received
1240 // insert code to copy to the correct register
1242 colorIncomingArgs();
1244 // Now update the machine code with register names and add any
1245 // additional code inserted by the register allocator to the instruction
1248 updateMachineCode();
1251 MachineCodeForMethod::get(Meth).dump();
1252 printMachineCode(); // only for DEBUGGING