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];
104 AddedInstrMap.clear();
107 //----------------------------------------------------------------------------
108 // This method initally creates interference graphs (one in each reg class)
109 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
110 //----------------------------------------------------------------------------
111 void PhyRegAlloc::createIGNodeListsAndIGs() {
112 if (DEBUG_RA) cerr << "Creating LR lists ...\n";
115 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
118 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
120 for (; HMI != HMIEnd ; ++HMI ) {
122 LiveRange *L = HMI->second; // get the LiveRange
125 cerr << "\n*?!?Warning: Null liver range found for: "
126 << RAV(HMI->first) << "\n";
130 // if the Value * is not null, and LR
131 // is not yet written to the IGNodeList
132 if( !(L->getUserIGNode()) ) {
133 RegClass *const RC = // RegClass of first value in the LR
134 RegClassList[ L->getRegClass()->getID() ];
136 RC->addLRToIG(L); // add this LR to an IG
142 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
143 RegClassList[rc]->createInterferenceGraph();
146 cerr << "LRLists Created!\n";
152 //----------------------------------------------------------------------------
153 // This method will add all interferences at for a given instruction.
154 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
155 // class as that of live var. The live var passed to this function is the
156 // LVset AFTER the instruction
157 //----------------------------------------------------------------------------
158 void PhyRegAlloc::addInterference(const Value *Def,
159 const ValueSet *LVSet,
162 ValueSet::const_iterator LIt = LVSet->begin();
164 // get the live range of instruction
166 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
168 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
169 assert( IGNodeOfDef );
171 RegClass *const RCOfDef = LROfDef->getRegClass();
173 // for each live var in live variable set
175 for( ; LIt != LVSet->end(); ++LIt) {
178 cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
180 // get the live range corresponding to live var
182 LiveRange *LROfVar = LRI.getLiveRangeForValue(*LIt);
184 // LROfVar can be null if it is a const since a const
185 // doesn't have a dominating def - see Assumptions above
188 if(LROfDef == LROfVar) // do not set interf for same LR
191 // if 2 reg classes are the same set interference
193 if (RCOfDef == LROfVar->getRegClass()) {
194 RCOfDef->setInterference( LROfDef, LROfVar);
195 } else if (DEBUG_RA > 1) {
196 // we will not have LRs for values not explicitly allocated in the
197 // instruction stream (e.g., constants)
198 cerr << " warning: no live range for " << RAV(*LIt) << "\n";
206 //----------------------------------------------------------------------------
207 // For a call instruction, this method sets the CallInterference flag in
208 // the LR of each variable live int the Live Variable Set live after the
209 // call instruction (except the return value of the call instruction - since
210 // the return value does not interfere with that call itself).
211 //----------------------------------------------------------------------------
213 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
214 const ValueSet *LVSetAft) {
217 cerr << "\n For call inst: " << *MInst;
219 ValueSet::const_iterator LIt = LVSetAft->begin();
221 // for each live var in live variable set after machine inst
223 for( ; LIt != LVSetAft->end(); ++LIt) {
225 // get the live range corresponding to live var
227 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
229 if( LR && DEBUG_RA) {
230 cerr << "\n\tLR Aft Call: ";
234 // LR can be null if it is a const since a const
235 // doesn't have a dominating def - see Assumptions above
238 LR->setCallInterference();
240 cerr << "\n ++Added call interf for LR: " ;
247 // Now find the LR of the return value of the call
248 // We do this because, we look at the LV set *after* the instruction
249 // to determine, which LRs must be saved across calls. The return value
250 // of the call is live in this set - but it does not interfere with call
251 // (i.e., we can allocate a volatile register to the return value)
253 if( const Value *RetVal = MRI.getCallInstRetVal( MInst )) {
254 LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
255 assert( RetValLR && "No LR for RetValue of call");
256 RetValLR->clearCallInterference();
259 // If the CALL is an indirect call, find the LR of the function pointer.
260 // That has a call interference because it conflicts with outgoing args.
261 if( const Value *AddrVal = MRI.getCallInstIndirectAddrVal( MInst )) {
262 LiveRange *AddrValLR = LRI.getLiveRangeForValue( AddrVal );
263 assert( AddrValLR && "No LR for indirect addr val of call");
264 AddrValLR->setCallInterference();
272 //----------------------------------------------------------------------------
273 // This method will walk thru code and create interferences in the IG of
274 // each RegClass. Also, this method calculates the spill cost of each
275 // Live Range (it is done in this method to save another pass over the code).
276 //----------------------------------------------------------------------------
277 void PhyRegAlloc::buildInterferenceGraphs()
280 if(DEBUG_RA) cerr << "Creating interference graphs ...\n";
282 unsigned BBLoopDepthCost;
283 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
286 // find the 10^(loop_depth) of this BB
288 BBLoopDepthCost = (unsigned) pow(10.0, LoopDepthCalc->getLoopDepth(*BBI));
290 // get the iterator for machine instructions
292 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
293 MachineCodeForBasicBlock::const_iterator
294 MInstIterator = MIVec.begin();
296 // iterate over all the machine instructions in BB
298 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
300 const MachineInstr *MInst = *MInstIterator;
302 // get the LV set after the instruction
304 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, *BBI);
306 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
309 // set the isCallInterference flag of each live range wich extends
310 // accross this call instruction. This information is used by graph
311 // coloring algo to avoid allocating volatile colors to live ranges
312 // that span across calls (since they have to be saved/restored)
314 setCallInterferences(MInst, &LVSetAI);
318 // iterate over all MI operands to find defs
320 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
321 OpE = MInst->end(); OpI != OpE; ++OpI) {
322 if (OpI.isDef()) // create a new LR iff this operand is a def
323 addInterference(*OpI, &LVSetAI, isCallInst);
325 // Calculate the spill cost of each live range
327 LiveRange *LR = LRI.getLiveRangeForValue(*OpI);
328 if (LR) LR->addSpillCost(BBLoopDepthCost);
332 // if there are multiple defs in this instruction e.g. in SETX
334 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
335 addInterf4PseudoInstr(MInst);
338 // Also add interference for any implicit definitions in a machine
339 // instr (currently, only calls have this).
341 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
342 if( NumOfImpRefs > 0 ) {
343 for(unsigned z=0; z < NumOfImpRefs; z++)
344 if( MInst->implicitRefIsDefined(z) )
345 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
349 } // for all machine instructions in BB
350 } // for all BBs in function
353 // add interferences for function arguments. Since there are no explict
354 // defs in the function 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 function.
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 Function::ArgumentListType &ArgList = Meth->getArgumentList();
417 // get an iterator to arg list
418 Function::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 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
446 // get the iterator for machine instructions
448 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
449 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
451 // iterate over all the machine instructions in BB
453 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
455 MachineInstr *MInst = *MInstIterator;
457 unsigned Opcode = MInst->getOpCode();
459 // do not process Phis
460 if (TM.getInstrInfo().isDummyPhiInstr(Opcode))
463 // Now insert speical instructions (if necessary) for call/return
466 if (TM.getInstrInfo().isCall(Opcode) ||
467 TM.getInstrInfo().isReturn(Opcode)) {
469 AddedInstrns &AI = AddedInstrMap[MInst];
471 // Tmp stack poistions are needed by some calls that have spilled args
472 // So reset it before we call each such method
474 mcInfo.popAllTempValues(TM);
476 if (TM.getInstrInfo().isCall(Opcode))
477 MRI.colorCallArgs(MInst, LRI, &AI, *this, *BBI);
478 else if (TM.getInstrInfo().isReturn(Opcode))
479 MRI.colorRetValue(MInst, LRI, &AI);
483 /* -- Using above code instead of this
485 // if this machine instr is call, insert caller saving code
487 if( (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
488 MRI.insertCallerSavingCode(MInst, *BBI, *this );
493 // reset the stack offset for temporary variables since we may
494 // need that to spill
495 // mcInfo.popAllTempValues(TM);
496 // TODO ** : do later
498 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
501 // Now replace set the registers for operands in the machine instruction
503 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
505 MachineOperand& Op = MInst->getOperand(OpNum);
507 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
508 Op.getOperandType() == MachineOperand::MO_CCRegister) {
510 const Value *const Val = Op.getVRegValue();
512 // delete this condition checking later (must assert if Val is null)
515 cerr << "Warning: NULL Value found for operand\n";
518 assert( Val && "Value is NULL");
520 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
524 // nothing to worry if it's a const or a label
527 cerr << "*NO LR for operand : " << Op ;
528 cerr << " [reg:" << Op.getAllocatedRegNum() << "]";
529 cerr << " in inst:\t" << *MInst << "\n";
532 // if register is not allocated, mark register as invalid
533 if( Op.getAllocatedRegNum() == -1)
534 Op.setRegForValue( MRI.getInvalidRegNum());
540 unsigned RCID = (LR->getRegClass())->getID();
542 if( LR->hasColor() ) {
543 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
547 // LR did NOT receive a color (register). Now, insert spill code
548 // for spilled opeands in this machine instruction
550 //assert(0 && "LR must be spilled");
551 insertCode4SpilledLR(LR, MInst, *BBI, OpNum );
556 } // for each operand
559 // Now add instructions that the register allocator inserts before/after
560 // this machine instructions (done only for calls/rets/incoming args)
561 // We do this here, to ensure that spill for an instruction is inserted
562 // closest as possible to an instruction (see above insertCode4Spill...)
564 // If there are instructions to be added, *before* this machine
565 // instruction, add them now.
567 if(AddedInstrMap.count(MInst)) {
568 std::deque<MachineInstr *> &IBef = AddedInstrMap[MInst].InstrnsBefore;
570 if( ! IBef.empty() ) {
571 std::deque<MachineInstr *>::iterator AdIt;
573 for( AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt ) {
576 cerr << "For inst " << *MInst;
577 cerr << " PREPENDed instr: " << **AdIt << "\n";
580 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
588 // If there are instructions to be added *after* this machine
589 // instruction, add them now
591 if (!AddedInstrMap[MInst].InstrnsAfter.empty()) {
593 // if there are delay slots for this instruction, the instructions
594 // added after it must really go after the delayed instruction(s)
595 // So, we move the InstrAfter of the current instruction to the
596 // corresponding delayed instruction
599 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
600 move2DelayedInstr(MInst, *(MInstIterator+delay) );
602 if(DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
608 // Here we can add the "instructions after" to the current
609 // instruction since there are no delay slots for this instruction
611 std::deque<MachineInstr *> &IAft = AddedInstrMap[MInst].InstrnsAfter;
614 ++MInstIterator; // advance to the next instruction
616 std::deque<MachineInstr *>::iterator AdIt;
617 for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
620 cerr << "For inst " << *MInst;
621 cerr << " APPENDed instr: " << **AdIt << "\n";
624 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
628 // MInsterator already points to the next instr. Since the
629 // for loop also increments it, decrement it to point to the
630 // instruction added last
639 } // for each machine instruction
645 //----------------------------------------------------------------------------
646 // This method inserts spill code for AN operand whose LR was spilled.
647 // This method may be called several times for a single machine instruction
648 // if it contains many spilled operands. Each time it is called, it finds
649 // a register which is not live at that instruction and also which is not
650 // used by other spilled operands of the same instruction. Then it uses
651 // this register temporarily to accomodate the spilled value.
652 //----------------------------------------------------------------------------
653 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
655 const BasicBlock *BB,
656 const unsigned OpNum) {
658 assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
659 (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
660 "Arg of a call/ret must be handled elsewhere");
662 MachineOperand& Op = MInst->getOperand(OpNum);
663 bool isDef = MInst->operandIsDefined(OpNum);
664 unsigned RegType = MRI.getRegType( LR );
665 int SpillOff = LR->getSpillOffFromFP();
666 RegClass *RC = LR->getRegClass();
667 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
669 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
671 MachineInstr *MIBef=NULL, *AdIMid=NULL, *MIAft=NULL;
673 int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,&LVSetBef, MIBef, MIAft);
675 // get the added instructions for this instruciton
676 AddedInstrns &AI = AddedInstrMap[MInst];
679 // for a USE, we have to load the value of LR from stack to a TmpReg
680 // and use the TmpReg as one operand of instruction
682 // actual loading instruction
683 AdIMid = MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType);
686 AI.InstrnsBefore.push_back(MIBef);
688 AI.InstrnsBefore.push_back(AdIMid);
691 AI.InstrnsAfter.push_front(MIAft);
693 } else { // if this is a Def
694 // for a DEF, we have to store the value produced by this instruction
695 // on the stack position allocated for this LR
697 // actual storing instruction
698 AdIMid = MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType);
701 AI.InstrnsBefore.push_back(MIBef);
703 AI.InstrnsAfter.push_front(AdIMid);
706 AI.InstrnsAfter.push_front(MIAft);
710 cerr << "\nFor Inst " << *MInst;
711 cerr << " - SPILLED LR: "; printSet(*LR);
712 cerr << "\n - Added Instructions:";
713 if (MIBef) cerr << *MIBef;
715 if (MIAft) cerr << *MIAft;
717 Op.setRegForValue(TmpRegU); // set the opearnd
722 //----------------------------------------------------------------------------
723 // We can use the following method to get a temporary register to be used
724 // BEFORE any given machine instruction. If there is a register available,
725 // this method will simply return that register and set MIBef = MIAft = NULL.
726 // Otherwise, it will return a register and MIAft and MIBef will contain
727 // two instructions used to free up this returned register.
728 // Returned register number is the UNIFIED register number
729 //----------------------------------------------------------------------------
731 int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC,
733 const MachineInstr *MInst,
734 const ValueSet *LVSetBef,
735 MachineInstr *&MIBef,
736 MachineInstr *&MIAft) {
738 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
742 // we found an unused register, so we can simply use it
743 MIBef = MIAft = NULL;
746 // we couldn't find an unused register. Generate code to free up a reg by
747 // saving it on stack and restoring after the instruction
749 int TmpOff = mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
751 RegU = getUniRegNotUsedByThisInst(RC, MInst);
752 MIBef = MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType );
753 MIAft = MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType );
759 //----------------------------------------------------------------------------
760 // This method is called to get a new unused register that can be used to
761 // accomodate a spilled value.
762 // This method may be called several times for a single machine instruction
763 // if it contains many spilled operands. Each time it is called, it finds
764 // a register which is not live at that instruction and also which is not
765 // used by other spilled operands of the same instruction.
766 // Return register number is relative to the register class. NOT
768 //----------------------------------------------------------------------------
769 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
770 const MachineInstr *MInst,
771 const ValueSet *LVSetBef) {
773 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
775 bool *IsColorUsedArr = RC->getIsColorUsedArr();
777 for(unsigned i=0; i < NumAvailRegs; i++) // Reset array
778 IsColorUsedArr[i] = false;
780 ValueSet::const_iterator LIt = LVSetBef->begin();
782 // for each live var in live variable set after machine inst
783 for( ; LIt != LVSetBef->end(); ++LIt) {
785 // get the live range corresponding to live var
786 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
788 // LR can be null if it is a const since a const
789 // doesn't have a dominating def - see Assumptions above
791 if( LRofLV->hasColor() )
792 IsColorUsedArr[ LRofLV->getColor() ] = true;
795 // It is possible that one operand of this MInst was already spilled
796 // and it received some register temporarily. If that's the case,
797 // it is recorded in machine operand. We must skip such registers.
799 setRelRegsUsedByThisInst(RC, MInst);
801 unsigned c; // find first unused color
802 for( c=0; c < NumAvailRegs; c++)
803 if( ! IsColorUsedArr[ c ] ) break;
806 return MRI.getUnifiedRegNum(RC->getID(), c);
814 //----------------------------------------------------------------------------
815 // Get any other register in a register class, other than what is used
816 // by operands of a machine instruction. Returns the unified reg number.
817 //----------------------------------------------------------------------------
818 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
819 const MachineInstr *MInst) {
821 bool *IsColorUsedArr = RC->getIsColorUsedArr();
822 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
825 for(unsigned i=0; i < NumAvailRegs ; i++) // Reset array
826 IsColorUsedArr[i] = false;
828 setRelRegsUsedByThisInst(RC, MInst);
830 unsigned c; // find first unused color
831 for( c=0; c < RC->getNumOfAvailRegs(); c++)
832 if( ! IsColorUsedArr[ c ] ) break;
835 return MRI.getUnifiedRegNum(RC->getID(), c);
837 assert( 0 && "FATAL: No free register could be found in reg class!!");
842 //----------------------------------------------------------------------------
843 // This method modifies the IsColorUsedArr of the register class passed to it.
844 // It sets the bits corresponding to the registers used by this machine
845 // instructions. Both explicit and implicit operands are set.
846 //----------------------------------------------------------------------------
847 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
848 const MachineInstr *MInst ) {
850 bool *IsColorUsedArr = RC->getIsColorUsedArr();
852 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
854 const MachineOperand& Op = MInst->getOperand(OpNum);
856 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
857 Op.getOperandType() == MachineOperand::MO_CCRegister ) {
859 const Value *const Val = Op.getVRegValue();
862 if( MRI.getRegClassIDOfValue(Val) == RC->getID() ) {
864 if( (Reg=Op.getAllocatedRegNum()) != -1) {
865 IsColorUsedArr[ Reg ] = true;
868 // it is possilbe that this operand still is not marked with
869 // a register but it has a LR and that received a color
871 LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
873 if( LROfVal->hasColor() )
874 IsColorUsedArr[ LROfVal->getColor() ] = true;
877 } // if reg classes are the same
879 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
880 IsColorUsedArr[ Op.getMachineRegNum() ] = true;
884 // If there are implicit references, mark them as well
886 for(unsigned z=0; z < MInst->getNumImplicitRefs(); z++) {
888 LiveRange *const LRofImpRef =
889 LRI.getLiveRangeForValue( MInst->getImplicitRef(z) );
891 if(LRofImpRef && LRofImpRef->hasColor())
892 IsColorUsedArr[LRofImpRef->getColor()] = true;
903 //----------------------------------------------------------------------------
904 // If there are delay slots for an instruction, the instructions
905 // added after it must really go after the delayed instruction(s).
906 // So, we move the InstrAfter of that instruction to the
907 // corresponding delayed instruction using the following method.
909 //----------------------------------------------------------------------------
910 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
911 const MachineInstr *DelayedMI) {
913 // "added after" instructions of the original instr
914 std::deque<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
916 // "added instructions" of the delayed instr
917 AddedInstrns &DelayAdI = AddedInstrMap[DelayedMI];
919 // "added after" instructions of the delayed instr
920 std::deque<MachineInstr *> &DelayedAft = DelayAdI.InstrnsAfter;
922 // go thru all the "added after instructions" of the original instruction
923 // and append them to the "addded after instructions" of the delayed
925 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
927 // empty the "added after instructions" of the original instruction
931 //----------------------------------------------------------------------------
932 // This method prints the code with registers after register allocation is
934 //----------------------------------------------------------------------------
935 void PhyRegAlloc::printMachineCode()
938 cerr << "\n;************** Function " << Meth->getName()
939 << " *****************\n";
941 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
943 cerr << "\n"; printLabel(*BBI); cerr << ": ";
945 // get the iterator for machine instructions
946 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
947 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
949 // iterate over all the machine instructions in BB
950 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
951 MachineInstr *const MInst = *MInstIterator;
954 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
956 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
957 MachineOperand& Op = MInst->getOperand(OpNum);
959 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
960 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
961 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
963 const Value *const Val = Op.getVRegValue () ;
964 // ****this code is temporary till NULL Values are fixed
966 cerr << "\t<*NULL*>";
970 // if a label or a constant
971 if(isa<BasicBlock>(Val)) {
972 cerr << "\t"; printLabel( Op.getVRegValue () );
974 // else it must be a register value
975 const int RegNum = Op.getAllocatedRegNum();
977 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
979 cerr << "(" << Val->getName() << ")";
981 cerr << "(" << Val << ")";
986 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
988 if( LROfVal->hasSpillOffset() )
993 else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
994 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
998 cerr << "\t" << Op; // use dump field
1003 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1004 if( NumOfImpRefs > 0) {
1005 cerr << "\tImplicit:";
1007 for(unsigned z=0; z < NumOfImpRefs; z++)
1008 cerr << RAV(MInst->getImplicitRef(z)) << "\t";
1011 } // for all machine instructions
1023 //----------------------------------------------------------------------------
1025 //----------------------------------------------------------------------------
1027 void PhyRegAlloc::colorCallRetArgs()
1030 CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
1031 CallRetInstrListType::const_iterator It = CallRetInstList.begin();
1033 for( ; It != CallRetInstList.end(); ++It ) {
1035 const MachineInstr *const CRMI = *It;
1036 unsigned OpCode = CRMI->getOpCode();
1038 // get the added instructions for this Call/Ret instruciton
1039 AddedInstrns &AI = AddedInstrMap[CRMI];
1041 // Tmp stack positions are needed by some calls that have spilled args
1042 // So reset it before we call each such method
1043 //mcInfo.popAllTempValues(TM);
1046 if (TM.getInstrInfo().isCall(OpCode))
1047 MRI.colorCallArgs(CRMI, LRI, &AI, *this);
1048 else if (TM.getInstrInfo().isReturn(OpCode))
1049 MRI.colorRetValue(CRMI, LRI, &AI);
1051 assert(0 && "Non Call/Ret instrn in CallRetInstrList\n");
1057 //----------------------------------------------------------------------------
1059 //----------------------------------------------------------------------------
1060 void PhyRegAlloc::colorIncomingArgs()
1062 const BasicBlock *const FirstBB = Meth->front();
1063 const MachineInstr *FirstMI = FirstBB->getMachineInstrVec().front();
1064 assert(FirstMI && "No machine instruction in entry BB");
1066 MRI.colorMethodArgs(Meth, LRI, &AddedInstrMap[FirstMI]);
1070 //----------------------------------------------------------------------------
1071 // Used to generate a label for a basic block
1072 //----------------------------------------------------------------------------
1073 void PhyRegAlloc::printLabel(const Value *const Val) {
1075 cerr << Val->getName();
1077 cerr << "Label" << Val;
1081 //----------------------------------------------------------------------------
1082 // This method calls setSugColorUsable method of each live range. This
1083 // will determine whether the suggested color of LR is really usable.
1084 // A suggested color is not usable when the suggested color is volatile
1085 // AND when there are call interferences
1086 //----------------------------------------------------------------------------
1088 void PhyRegAlloc::markUnusableSugColors()
1090 if(DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
1092 // hash map iterator
1093 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1094 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1096 for(; HMI != HMIEnd ; ++HMI ) {
1098 LiveRange *L = HMI->second; // get the LiveRange
1100 if(L->hasSuggestedColor()) {
1101 int RCID = L->getRegClass()->getID();
1102 if( MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1103 L->isCallInterference() )
1104 L->setSuggestedColorUsable( false );
1106 L->setSuggestedColorUsable( true );
1108 } // if L->hasSuggestedColor()
1110 } // for all LR's in hash map
1115 //----------------------------------------------------------------------------
1116 // The following method will set the stack offsets of the live ranges that
1117 // are decided to be spillled. This must be called just after coloring the
1118 // LRs using the graph coloring algo. For each live range that is spilled,
1119 // this method allocate a new spill position on the stack.
1120 //----------------------------------------------------------------------------
1122 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1123 if (DEBUG_RA) cerr << "\nsetting LR stack offsets ...\n";
1125 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
1126 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
1128 for( ; HMI != HMIEnd ; ++HMI) {
1129 if (HMI->first && HMI->second) {
1130 LiveRange *L = HMI->second; // get the LiveRange
1131 if (!L->hasColor()) // NOTE: ** allocating the size of long Type **
1132 L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
1134 } // for all LR's in hash map
1139 //----------------------------------------------------------------------------
1140 // The entry pont to Register Allocation
1141 //----------------------------------------------------------------------------
1143 void PhyRegAlloc::allocateRegisters()
1146 // make sure that we put all register classes into the RegClassList
1147 // before we call constructLiveRanges (now done in the constructor of
1148 // PhyRegAlloc class).
1150 LRI.constructLiveRanges(); // create LR info
1153 LRI.printLiveRanges();
1155 createIGNodeListsAndIGs(); // create IGNode list and IGs
1157 buildInterferenceGraphs(); // build IGs in all reg classes
1161 // print all LRs in all reg classes
1162 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1163 RegClassList[ rc ]->printIGNodeList();
1165 // print IGs in all register classes
1166 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1167 RegClassList[ rc ]->printIG();
1171 LRI.coalesceLRs(); // coalesce all live ranges
1175 // print all LRs in all reg classes
1176 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1177 RegClassList[ rc ]->printIGNodeList();
1179 // print IGs in all register classes
1180 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1181 RegClassList[ rc ]->printIG();
1185 // mark un-usable suggested color before graph coloring algorithm.
1186 // When this is done, the graph coloring algo will not reserve
1187 // suggested color unnecessarily - they can be used by another LR
1189 markUnusableSugColors();
1191 // color all register classes using the graph coloring algo
1192 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1193 RegClassList[ rc ]->colorAllRegs();
1195 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1196 // a poistion for such spilled LRs
1198 allocateStackSpace4SpilledLRs();
1200 mcInfo.popAllTempValues(TM); // TODO **Check
1202 // color incoming args - if the correct color was not received
1203 // insert code to copy to the correct register
1205 colorIncomingArgs();
1207 // Now update the machine code with register names and add any
1208 // additional code inserted by the register allocator to the instruction
1211 updateMachineCode();
1214 MachineCodeForMethod::get(Meth).dump();
1215 printMachineCode(); // only for DEBUGGING