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/Function.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(Function *F) {
50 cerr << "\n******************** Method "<< F->getName()
51 << " ********************\n";
53 PhyRegAlloc PRA(F, 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(Function *F,
79 const TargetMachine& tm,
80 MethodLiveVarInfo *Lvi,
83 mcInfo(MachineCodeForMethod::get(F)),
84 LVI(Lvi), LRI(F, tm, RegClassList),
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(F, 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 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
284 // find the 10^(loop_depth) of this BB
286 BBLoopDepthCost = (unsigned) pow(10.0, LoopDepthCalc->getLoopDepth(*BBI));
288 // get the iterator for machine instructions
290 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
291 MachineCodeForBasicBlock::const_iterator
292 MInstIterator = MIVec.begin();
294 // iterate over all the machine instructions in BB
296 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
298 const MachineInstr *MInst = *MInstIterator;
300 // get the LV set after the instruction
302 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, *BBI);
304 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
307 // set the isCallInterference flag of each live range wich extends
308 // accross this call instruction. This information is used by graph
309 // coloring algo to avoid allocating volatile colors to live ranges
310 // that span across calls (since they have to be saved/restored)
312 setCallInterferences(MInst, &LVSetAI);
316 // iterate over all MI operands to find defs
318 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
319 OpE = MInst->end(); OpI != OpE; ++OpI) {
320 if (OpI.isDef()) // create a new LR iff this operand is a def
321 addInterference(*OpI, &LVSetAI, isCallInst);
323 // Calculate the spill cost of each live range
325 LiveRange *LR = LRI.getLiveRangeForValue(*OpI);
326 if (LR) LR->addSpillCost(BBLoopDepthCost);
330 // if there are multiple defs in this instruction e.g. in SETX
332 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
333 addInterf4PseudoInstr(MInst);
336 // Also add interference for any implicit definitions in a machine
337 // instr (currently, only calls have this).
339 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
340 if( NumOfImpRefs > 0 ) {
341 for(unsigned z=0; z < NumOfImpRefs; z++)
342 if( MInst->implicitRefIsDefined(z) )
343 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
347 } // for all machine instructions in BB
348 } // for all BBs in function
351 // add interferences for function arguments. Since there are no explict
352 // defs in the function for args, we have to add them manually
354 addInterferencesForArgs();
357 cerr << "Interference graphs calculted!\n";
363 //--------------------------------------------------------------------------
364 // Pseudo instructions will be exapnded to multiple instructions by the
365 // assembler. Consequently, all the opernds must get distinct registers.
366 // Therefore, we mark all operands of a pseudo instruction as they interfere
368 //--------------------------------------------------------------------------
369 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
371 bool setInterf = false;
373 // iterate over MI operands to find defs
375 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
376 ItE = MInst->end(); It1 != ItE; ++It1) {
377 const LiveRange *LROfOp1 = LRI.getLiveRangeForValue(*It1);
378 assert((LROfOp1 || !It1.isDef()) && "No LR for Def in PSEUDO insruction");
380 MachineInstr::const_val_op_iterator It2 = It1;
381 for(++It2; It2 != ItE; ++It2) {
382 const LiveRange *LROfOp2 = LRI.getLiveRangeForValue(*It2);
385 RegClass *RCOfOp1 = LROfOp1->getRegClass();
386 RegClass *RCOfOp2 = LROfOp2->getRegClass();
388 if( RCOfOp1 == RCOfOp2 ){
389 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
393 } // for all other defs in machine instr
394 } // for all operands in an instruction
396 if (!setInterf && MInst->getNumOperands() > 2) {
397 cerr << "\nInterf not set for any operand in pseudo instr:\n";
399 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
405 //----------------------------------------------------------------------------
406 // This method will add interferences for incoming arguments to a function.
407 //----------------------------------------------------------------------------
408 void PhyRegAlloc::addInterferencesForArgs() {
409 // get the InSet of root BB
410 const ValueSet &InSet = LVI->getInSetOfBB(Meth->front());
412 // get the argument list
413 const Function::ArgumentListType &ArgList = Meth->getArgumentList();
415 // get an iterator to arg list
416 Function::ArgumentListType::const_iterator ArgIt = ArgList.begin();
419 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
420 addInterference((Value*)*ArgIt, &InSet, false);// add interferences between
421 // args and LVars at start
423 cerr << " - %% adding interference for argument "
424 << RAV((const Value *)*ArgIt) << "\n";
431 //----------------------------------------------------------------------------
432 // This method is called after register allocation is complete to set the
433 // allocated reisters in the machine code. This code will add register numbers
434 // to MachineOperands that contain a Value. Also it calls target specific
435 // methods to produce caller saving instructions. At the end, it adds all
436 // additional instructions produced by the register allocator to the
437 // instruction stream.
438 //----------------------------------------------------------------------------
439 void PhyRegAlloc::updateMachineCode()
442 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
444 // get the iterator for machine instructions
446 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
447 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
449 // iterate over all the machine instructions in BB
451 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
453 MachineInstr *MInst = *MInstIterator;
455 unsigned Opcode = MInst->getOpCode();
457 // do not process Phis
458 if (TM.getInstrInfo().isDummyPhiInstr(Opcode))
461 // Now insert speical instructions (if necessary) for call/return
464 if (TM.getInstrInfo().isCall(Opcode) ||
465 TM.getInstrInfo().isReturn(Opcode)) {
467 AddedInstrns *AI = AddedInstrMap[ MInst];
469 AI = new AddedInstrns();
470 AddedInstrMap[ MInst ] = AI;
473 // Tmp stack poistions are needed by some calls that have spilled args
474 // So reset it before we call each such method
476 mcInfo.popAllTempValues(TM);
478 if (TM.getInstrInfo().isCall(Opcode))
479 MRI.colorCallArgs(MInst, LRI, AI, *this, *BBI);
480 else if (TM.getInstrInfo().isReturn(Opcode))
481 MRI.colorRetValue(MInst, LRI, AI);
485 /* -- Using above code instead of this
487 // if this machine instr is call, insert caller saving code
489 if( (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
490 MRI.insertCallerSavingCode(MInst, *BBI, *this );
495 // reset the stack offset for temporary variables since we may
496 // need that to spill
497 // mcInfo.popAllTempValues(TM);
498 // TODO ** : do later
500 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
503 // Now replace set the registers for operands in the machine instruction
505 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
507 MachineOperand& Op = MInst->getOperand(OpNum);
509 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
510 Op.getOperandType() == MachineOperand::MO_CCRegister) {
512 const Value *const Val = Op.getVRegValue();
514 // delete this condition checking later (must assert if Val is null)
517 cerr << "Warning: NULL Value found for operand\n";
520 assert( Val && "Value is NULL");
522 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
526 // nothing to worry if it's a const or a label
529 cerr << "*NO LR for operand : " << Op ;
530 cerr << " [reg:" << Op.getAllocatedRegNum() << "]";
531 cerr << " in inst:\t" << *MInst << "\n";
534 // if register is not allocated, mark register as invalid
535 if( Op.getAllocatedRegNum() == -1)
536 Op.setRegForValue( MRI.getInvalidRegNum());
542 unsigned RCID = (LR->getRegClass())->getID();
544 if( LR->hasColor() ) {
545 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
549 // LR did NOT receive a color (register). Now, insert spill code
550 // for spilled opeands in this machine instruction
552 //assert(0 && "LR must be spilled");
553 insertCode4SpilledLR(LR, MInst, *BBI, OpNum );
558 } // for each operand
561 // Now add instructions that the register allocator inserts before/after
562 // this machine instructions (done only for calls/rets/incoming args)
563 // We do this here, to ensure that spill for an instruction is inserted
564 // closest as possible to an instruction (see above insertCode4Spill...)
566 // If there are instructions to be added, *before* this machine
567 // instruction, add them now.
569 if( AddedInstrMap[ MInst ] ) {
570 std::deque<MachineInstr *> &IBef = AddedInstrMap[MInst]->InstrnsBefore;
572 if( ! IBef.empty() ) {
573 std::deque<MachineInstr *>::iterator AdIt;
575 for( AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt ) {
578 cerr << "For inst " << *MInst;
579 cerr << " PREPENDed instr: " << **AdIt << "\n";
582 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
590 // If there are instructions to be added *after* this machine
591 // instruction, add them now
593 if(AddedInstrMap[MInst] &&
594 !AddedInstrMap[MInst]->InstrnsAfter.empty() ) {
596 // if there are delay slots for this instruction, the instructions
597 // added after it must really go after the delayed instruction(s)
598 // So, we move the InstrAfter of the current instruction to the
599 // corresponding delayed instruction
602 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
603 move2DelayedInstr(MInst, *(MInstIterator+delay) );
605 if(DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
611 // Here we can add the "instructions after" to the current
612 // instruction since there are no delay slots for this instruction
614 std::deque<MachineInstr *> &IAft = AddedInstrMap[MInst]->InstrnsAfter;
616 if( ! IAft.empty() ) {
618 std::deque<MachineInstr *>::iterator AdIt;
620 ++MInstIterator; // advance to the next instruction
622 for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
625 cerr << "For inst " << *MInst;
626 cerr << " APPENDed instr: " << **AdIt << "\n";
629 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
633 // MInsterator already points to the next instr. Since the
634 // for loop also increments it, decrement it to point to the
635 // instruction added last
644 } // for each machine instruction
650 //----------------------------------------------------------------------------
651 // This method inserts spill code for AN operand whose LR was spilled.
652 // This method may be called several times for a single machine instruction
653 // if it contains many spilled operands. Each time it is called, it finds
654 // a register which is not live at that instruction and also which is not
655 // used by other spilled operands of the same instruction. Then it uses
656 // this register temporarily to accomodate the spilled value.
657 //----------------------------------------------------------------------------
658 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
660 const BasicBlock *BB,
661 const unsigned OpNum) {
663 assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
664 (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
665 "Arg of a call/ret must be handled elsewhere");
667 MachineOperand& Op = MInst->getOperand(OpNum);
668 bool isDef = MInst->operandIsDefined(OpNum);
669 unsigned RegType = MRI.getRegType( LR );
670 int SpillOff = LR->getSpillOffFromFP();
671 RegClass *RC = LR->getRegClass();
672 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
674 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
676 MachineInstr *MIBef=NULL, *AdIMid=NULL, *MIAft=NULL;
678 int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,&LVSetBef, MIBef, MIAft);
680 // get the added instructions for this instruciton
681 AddedInstrns *AI = AddedInstrMap[ MInst ];
683 AI = new AddedInstrns();
684 AddedInstrMap[ MInst ] = AI;
690 // for a USE, we have to load the value of LR from stack to a TmpReg
691 // and use the TmpReg as one operand of instruction
693 // actual loading instruction
694 AdIMid = MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType);
697 AI->InstrnsBefore.push_back(MIBef);
699 AI->InstrnsBefore.push_back(AdIMid);
702 AI->InstrnsAfter.push_front(MIAft);
704 } else { // if this is a Def
705 // for a DEF, we have to store the value produced by this instruction
706 // on the stack position allocated for this LR
708 // actual storing instruction
709 AdIMid = MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType);
712 AI->InstrnsBefore.push_back(MIBef);
714 AI->InstrnsAfter.push_front(AdIMid);
717 AI->InstrnsAfter.push_front(MIAft);
721 cerr << "\nFor Inst " << *MInst;
722 cerr << " - SPILLED LR: "; printSet(*LR);
723 cerr << "\n - Added Instructions:";
724 if (MIBef) cerr << *MIBef;
726 if (MIAft) cerr << *MIAft;
728 Op.setRegForValue(TmpRegU); // set the opearnd
733 //----------------------------------------------------------------------------
734 // We can use the following method to get a temporary register to be used
735 // BEFORE any given machine instruction. If there is a register available,
736 // this method will simply return that register and set MIBef = MIAft = NULL.
737 // Otherwise, it will return a register and MIAft and MIBef will contain
738 // two instructions used to free up this returned register.
739 // Returned register number is the UNIFIED register number
740 //----------------------------------------------------------------------------
742 int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC,
744 const MachineInstr *MInst,
745 const ValueSet *LVSetBef,
746 MachineInstr *&MIBef,
747 MachineInstr *&MIAft) {
749 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
753 // we found an unused register, so we can simply use it
754 MIBef = MIAft = NULL;
757 // we couldn't find an unused register. Generate code to free up a reg by
758 // saving it on stack and restoring after the instruction
760 int TmpOff = mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
762 RegU = getUniRegNotUsedByThisInst(RC, MInst);
763 MIBef = MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType );
764 MIAft = MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType );
770 //----------------------------------------------------------------------------
771 // This method is called to get a new unused register that can be used to
772 // accomodate a spilled value.
773 // This method may be called several times for a single machine instruction
774 // if it contains many spilled operands. Each time it is called, it finds
775 // a register which is not live at that instruction and also which is not
776 // used by other spilled operands of the same instruction.
777 // Return register number is relative to the register class. NOT
779 //----------------------------------------------------------------------------
780 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
781 const MachineInstr *MInst,
782 const ValueSet *LVSetBef) {
784 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
786 bool *IsColorUsedArr = RC->getIsColorUsedArr();
788 for(unsigned i=0; i < NumAvailRegs; i++) // Reset array
789 IsColorUsedArr[i] = false;
791 ValueSet::const_iterator LIt = LVSetBef->begin();
793 // for each live var in live variable set after machine inst
794 for( ; LIt != LVSetBef->end(); ++LIt) {
796 // get the live range corresponding to live var
797 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
799 // LR can be null if it is a const since a const
800 // doesn't have a dominating def - see Assumptions above
802 if( LRofLV->hasColor() )
803 IsColorUsedArr[ LRofLV->getColor() ] = true;
806 // It is possible that one operand of this MInst was already spilled
807 // and it received some register temporarily. If that's the case,
808 // it is recorded in machine operand. We must skip such registers.
810 setRelRegsUsedByThisInst(RC, MInst);
812 unsigned c; // find first unused color
813 for( c=0; c < NumAvailRegs; c++)
814 if( ! IsColorUsedArr[ c ] ) break;
817 return MRI.getUnifiedRegNum(RC->getID(), c);
825 //----------------------------------------------------------------------------
826 // Get any other register in a register class, other than what is used
827 // by operands of a machine instruction. Returns the unified reg number.
828 //----------------------------------------------------------------------------
829 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
830 const MachineInstr *MInst) {
832 bool *IsColorUsedArr = RC->getIsColorUsedArr();
833 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
836 for(unsigned i=0; i < NumAvailRegs ; i++) // Reset array
837 IsColorUsedArr[i] = false;
839 setRelRegsUsedByThisInst(RC, MInst);
841 unsigned c; // find first unused color
842 for( c=0; c < RC->getNumOfAvailRegs(); c++)
843 if( ! IsColorUsedArr[ c ] ) break;
846 return MRI.getUnifiedRegNum(RC->getID(), c);
848 assert( 0 && "FATAL: No free register could be found in reg class!!");
853 //----------------------------------------------------------------------------
854 // This method modifies the IsColorUsedArr of the register class passed to it.
855 // It sets the bits corresponding to the registers used by this machine
856 // instructions. Both explicit and implicit operands are set.
857 //----------------------------------------------------------------------------
858 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
859 const MachineInstr *MInst ) {
861 bool *IsColorUsedArr = RC->getIsColorUsedArr();
863 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
865 const MachineOperand& Op = MInst->getOperand(OpNum);
867 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
868 Op.getOperandType() == MachineOperand::MO_CCRegister ) {
870 const Value *const Val = Op.getVRegValue();
873 if( MRI.getRegClassIDOfValue(Val) == RC->getID() ) {
875 if( (Reg=Op.getAllocatedRegNum()) != -1) {
876 IsColorUsedArr[ Reg ] = true;
879 // it is possilbe that this operand still is not marked with
880 // a register but it has a LR and that received a color
882 LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
884 if( LROfVal->hasColor() )
885 IsColorUsedArr[ LROfVal->getColor() ] = true;
888 } // if reg classes are the same
890 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
891 IsColorUsedArr[ Op.getMachineRegNum() ] = true;
895 // If there are implicit references, mark them as well
897 for(unsigned z=0; z < MInst->getNumImplicitRefs(); z++) {
899 LiveRange *const LRofImpRef =
900 LRI.getLiveRangeForValue( MInst->getImplicitRef(z) );
902 if(LRofImpRef && LRofImpRef->hasColor())
903 IsColorUsedArr[LRofImpRef->getColor()] = true;
914 //----------------------------------------------------------------------------
915 // If there are delay slots for an instruction, the instructions
916 // added after it must really go after the delayed instruction(s).
917 // So, we move the InstrAfter of that instruction to the
918 // corresponding delayed instruction using the following method.
920 //----------------------------------------------------------------------------
921 void PhyRegAlloc:: move2DelayedInstr(const MachineInstr *OrigMI,
922 const MachineInstr *DelayedMI) {
924 // "added after" instructions of the original instr
925 std::deque<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI]->InstrnsAfter;
927 // "added instructions" of the delayed instr
928 AddedInstrns *DelayAdI = AddedInstrMap[DelayedMI];
930 if(! DelayAdI ) { // create a new "added after" if necessary
931 DelayAdI = new AddedInstrns();
932 AddedInstrMap[DelayedMI] = DelayAdI;
935 // "added after" instructions of the delayed instr
936 std::deque<MachineInstr *> &DelayedAft = DelayAdI->InstrnsAfter;
938 // go thru all the "added after instructions" of the original instruction
939 // and append them to the "addded after instructions" of the delayed
941 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
943 // empty the "added after instructions" of the original instruction
947 //----------------------------------------------------------------------------
948 // This method prints the code with registers after register allocation is
950 //----------------------------------------------------------------------------
951 void PhyRegAlloc::printMachineCode()
954 cerr << "\n;************** Function " << Meth->getName()
955 << " *****************\n";
957 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
959 cerr << "\n"; printLabel(*BBI); cerr << ": ";
961 // get the iterator for machine instructions
962 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
963 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
965 // iterate over all the machine instructions in BB
966 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
967 MachineInstr *const MInst = *MInstIterator;
970 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
972 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
973 MachineOperand& Op = MInst->getOperand(OpNum);
975 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
976 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
977 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
979 const Value *const Val = Op.getVRegValue () ;
980 // ****this code is temporary till NULL Values are fixed
982 cerr << "\t<*NULL*>";
986 // if a label or a constant
987 if(isa<BasicBlock>(Val)) {
988 cerr << "\t"; printLabel( Op.getVRegValue () );
990 // else it must be a register value
991 const int RegNum = Op.getAllocatedRegNum();
993 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
995 cerr << "(" << Val->getName() << ")";
997 cerr << "(" << Val << ")";
1002 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
1004 if( LROfVal->hasSpillOffset() )
1009 else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
1010 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1014 cerr << "\t" << Op; // use dump field
1019 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1020 if( NumOfImpRefs > 0) {
1021 cerr << "\tImplicit:";
1023 for(unsigned z=0; z < NumOfImpRefs; z++)
1024 cerr << RAV(MInst->getImplicitRef(z)) << "\t";
1027 } // for all machine instructions
1039 //----------------------------------------------------------------------------
1041 //----------------------------------------------------------------------------
1043 void PhyRegAlloc::colorCallRetArgs()
1046 CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
1047 CallRetInstrListType::const_iterator It = CallRetInstList.begin();
1049 for( ; It != CallRetInstList.end(); ++It ) {
1051 const MachineInstr *const CRMI = *It;
1052 unsigned OpCode = CRMI->getOpCode();
1054 // get the added instructions for this Call/Ret instruciton
1055 AddedInstrns *AI = AddedInstrMap[ CRMI ];
1057 AI = new AddedInstrns();
1058 AddedInstrMap[ CRMI ] = AI;
1061 // Tmp stack poistions are needed by some calls that have spilled args
1062 // So reset it before we call each such method
1063 //mcInfo.popAllTempValues(TM);
1066 if (TM.getInstrInfo().isCall(OpCode))
1067 MRI.colorCallArgs(CRMI, LRI, AI, *this);
1068 else if (TM.getInstrInfo().isReturn(OpCode))
1069 MRI.colorRetValue( CRMI, LRI, AI );
1071 assert(0 && "Non Call/Ret instrn in CallRetInstrList\n");
1077 //----------------------------------------------------------------------------
1079 //----------------------------------------------------------------------------
1080 void PhyRegAlloc::colorIncomingArgs()
1082 const BasicBlock *const FirstBB = Meth->front();
1083 const MachineInstr *FirstMI = FirstBB->getMachineInstrVec().front();
1084 assert(FirstMI && "No machine instruction in entry BB");
1086 AddedInstrns *AI = AddedInstrMap[FirstMI];
1088 AddedInstrMap[FirstMI] = AI = new AddedInstrns();
1090 MRI.colorMethodArgs(Meth, LRI, AI);
1094 //----------------------------------------------------------------------------
1095 // Used to generate a label for a basic block
1096 //----------------------------------------------------------------------------
1097 void PhyRegAlloc::printLabel(const Value *const Val) {
1099 cerr << Val->getName();
1101 cerr << "Label" << Val;
1105 //----------------------------------------------------------------------------
1106 // This method calls setSugColorUsable method of each live range. This
1107 // will determine whether the suggested color of LR is really usable.
1108 // A suggested color is not usable when the suggested color is volatile
1109 // AND when there are call interferences
1110 //----------------------------------------------------------------------------
1112 void PhyRegAlloc::markUnusableSugColors()
1114 if(DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
1116 // hash map iterator
1117 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1118 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1120 for(; HMI != HMIEnd ; ++HMI ) {
1122 LiveRange *L = HMI->second; // get the LiveRange
1124 if(L->hasSuggestedColor()) {
1125 int RCID = L->getRegClass()->getID();
1126 if( MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1127 L->isCallInterference() )
1128 L->setSuggestedColorUsable( false );
1130 L->setSuggestedColorUsable( true );
1132 } // if L->hasSuggestedColor()
1134 } // for all LR's in hash map
1139 //----------------------------------------------------------------------------
1140 // The following method will set the stack offsets of the live ranges that
1141 // are decided to be spillled. This must be called just after coloring the
1142 // LRs using the graph coloring algo. For each live range that is spilled,
1143 // this method allocate a new spill position on the stack.
1144 //----------------------------------------------------------------------------
1146 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1147 if (DEBUG_RA) cerr << "\nsetting LR stack offsets ...\n";
1149 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
1150 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
1152 for( ; HMI != HMIEnd ; ++HMI) {
1153 if (HMI->first && HMI->second) {
1154 LiveRange *L = HMI->second; // get the LiveRange
1155 if (!L->hasColor()) // NOTE: ** allocating the size of long Type **
1156 L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
1158 } // for all LR's in hash map
1163 //----------------------------------------------------------------------------
1164 // The entry pont to Register Allocation
1165 //----------------------------------------------------------------------------
1167 void PhyRegAlloc::allocateRegisters()
1170 // make sure that we put all register classes into the RegClassList
1171 // before we call constructLiveRanges (now done in the constructor of
1172 // PhyRegAlloc class).
1174 LRI.constructLiveRanges(); // create LR info
1177 LRI.printLiveRanges();
1179 createIGNodeListsAndIGs(); // create IGNode list and IGs
1181 buildInterferenceGraphs(); // build IGs in all reg classes
1185 // print all LRs in all reg classes
1186 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1187 RegClassList[ rc ]->printIGNodeList();
1189 // print IGs in all register classes
1190 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1191 RegClassList[ rc ]->printIG();
1195 LRI.coalesceLRs(); // coalesce all live ranges
1199 // print all LRs in all reg classes
1200 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1201 RegClassList[ rc ]->printIGNodeList();
1203 // print IGs in all register classes
1204 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1205 RegClassList[ rc ]->printIG();
1209 // mark un-usable suggested color before graph coloring algorithm.
1210 // When this is done, the graph coloring algo will not reserve
1211 // suggested color unnecessarily - they can be used by another LR
1213 markUnusableSugColors();
1215 // color all register classes using the graph coloring algo
1216 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1217 RegClassList[ rc ]->colorAllRegs();
1219 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1220 // a poistion for such spilled LRs
1222 allocateStackSpace4SpilledLRs();
1224 mcInfo.popAllTempValues(TM); // TODO **Check
1226 // color incoming args - if the correct color was not received
1227 // insert code to copy to the correct register
1229 colorIncomingArgs();
1231 // Now update the machine code with register names and add any
1232 // additional code inserted by the register allocator to the instruction
1235 updateMachineCode();
1238 MachineCodeForMethod::get(Meth).dump();
1239 printMachineCode(); // only for DEBUGGING