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/FunctionLiveVarInfo.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"
24 #include "llvm/CodeGen/RegAllocCommon.h"
30 // ***TODO: There are several places we add instructions. Validate the order
31 // of adding these instructions.
33 cl::Enum<RegAllocDebugLevel_t> DEBUG_RA("dregalloc", cl::NoFlags,
34 "enable register allocation debugging information",
35 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
36 clEnumValN(RA_DEBUG_Normal , "y", "enable debug output"),
37 clEnumValN(RA_DEBUG_Verbose, "v", "enable extra debug output"), 0);
40 //----------------------------------------------------------------------------
41 // RegisterAllocation pass front end...
42 //----------------------------------------------------------------------------
44 class RegisterAllocator : public FunctionPass {
45 TargetMachine &Target;
47 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
49 const char *getPassName() const { return "Register Allocation"; }
51 bool runOnFunction(Function *F) {
53 cerr << "\n******************** Function "<< F->getName()
54 << " ********************\n";
56 PhyRegAlloc PRA(F, Target, &getAnalysis<FunctionLiveVarInfo>(),
57 &getAnalysis<LoopInfo>());
58 PRA.allocateRegisters();
60 if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
64 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65 AU.addRequired(LoopInfo::ID);
66 AU.addRequired(FunctionLiveVarInfo::ID);
71 Pass *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, const TargetMachine& tm,
79 FunctionLiveVarInfo *Lvi, LoopInfo *LDC)
81 mcInfo(MachineCodeForMethod::get(F)),
82 LVI(Lvi), LRI(F, tm, RegClassList),
84 NumOfRegClasses(MRI.getNumOfRegClasses()),
87 // create each RegisterClass and put in RegClassList
89 for(unsigned int rc=0; rc < NumOfRegClasses; rc++)
90 RegClassList.push_back(new RegClass(F, MRI.getMachineRegClass(rc),
95 //----------------------------------------------------------------------------
96 // Destructor: Deletes register classes
97 //----------------------------------------------------------------------------
98 PhyRegAlloc::~PhyRegAlloc() {
99 for( unsigned int rc=0; rc < NumOfRegClasses; rc++)
100 delete RegClassList[rc];
102 AddedInstrMap.clear();
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 MII = MIVec.begin();
293 // iterate over all the machine instructions in BB
295 for( ; MII != MIVec.end(); ++MII) {
297 const MachineInstr *MInst = *MII;
299 // get the LV set after the instruction
301 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, *BBI);
303 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
306 // set the isCallInterference flag of each live range wich extends
307 // accross this call instruction. This information is used by graph
308 // coloring algo to avoid allocating volatile colors to live ranges
309 // that span across calls (since they have to be saved/restored)
311 setCallInterferences(MInst, &LVSetAI);
315 // iterate over all MI operands to find defs
317 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
318 OpE = MInst->end(); OpI != OpE; ++OpI) {
319 if (OpI.isDef()) // create a new LR iff this operand is a def
320 addInterference(*OpI, &LVSetAI, isCallInst);
322 // Calculate the spill cost of each live range
324 LiveRange *LR = LRI.getLiveRangeForValue(*OpI);
325 if (LR) LR->addSpillCost(BBLoopDepthCost);
329 // if there are multiple defs in this instruction e.g. in SETX
331 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
332 addInterf4PseudoInstr(MInst);
335 // Also add interference for any implicit definitions in a machine
336 // instr (currently, only calls have this).
338 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
339 if( NumOfImpRefs > 0 ) {
340 for(unsigned z=0; z < NumOfImpRefs; z++)
341 if( MInst->implicitRefIsDefined(z) )
342 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
346 } // for all machine instructions in BB
347 } // for all BBs in function
350 // add interferences for function arguments. Since there are no explict
351 // defs in the function for args, we have to add them manually
353 addInterferencesForArgs();
356 cerr << "Interference graphs calculted!\n";
362 //--------------------------------------------------------------------------
363 // Pseudo instructions will be exapnded to multiple instructions by the
364 // assembler. Consequently, all the opernds must get distinct registers.
365 // Therefore, we mark all operands of a pseudo instruction as they interfere
367 //--------------------------------------------------------------------------
368 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
370 bool setInterf = false;
372 // iterate over MI operands to find defs
374 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
375 ItE = MInst->end(); It1 != ItE; ++It1) {
376 const LiveRange *LROfOp1 = LRI.getLiveRangeForValue(*It1);
377 assert((LROfOp1 || !It1.isDef()) && "No LR for Def in PSEUDO insruction");
379 MachineInstr::const_val_op_iterator It2 = It1;
380 for(++It2; It2 != ItE; ++It2) {
381 const LiveRange *LROfOp2 = LRI.getLiveRangeForValue(*It2);
384 RegClass *RCOfOp1 = LROfOp1->getRegClass();
385 RegClass *RCOfOp2 = LROfOp2->getRegClass();
387 if( RCOfOp1 == RCOfOp2 ){
388 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
392 } // for all other defs in machine instr
393 } // for all operands in an instruction
395 if (!setInterf && MInst->getNumOperands() > 2) {
396 cerr << "\nInterf not set for any operand in pseudo instr:\n";
398 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
404 //----------------------------------------------------------------------------
405 // This method will add interferences for incoming arguments to a function.
406 //----------------------------------------------------------------------------
407 void PhyRegAlloc::addInterferencesForArgs() {
408 // get the InSet of root BB
409 const ValueSet &InSet = LVI->getInSetOfBB(Meth->front());
411 // get the argument list
412 const Function::ArgumentListType &ArgList = Meth->getArgumentList();
414 // get an iterator to arg list
415 Function::ArgumentListType::const_iterator ArgIt = ArgList.begin();
418 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
419 addInterference((Value*)*ArgIt, &InSet, false);// add interferences between
420 // args and LVars at start
422 cerr << " - %% adding interference for argument "
423 << RAV((const Value *)*ArgIt) << "\n";
428 //----------------------------------------------------------------------------
429 // This method is called after register allocation is complete to set the
430 // allocated reisters in the machine code. This code will add register numbers
431 // to MachineOperands that contain a Value. Also it calls target specific
432 // methods to produce caller saving instructions. At the end, it adds all
433 // additional instructions produced by the register allocator to the
434 // instruction stream.
435 //----------------------------------------------------------------------------
437 //-----------------------------
438 // Utility functions used below
439 //-----------------------------
441 PrependInstructions(std::deque<MachineInstr *> &IBef,
442 MachineCodeForBasicBlock& MIVec,
443 MachineCodeForBasicBlock::iterator& MII,
444 const std::string& msg)
448 MachineInstr* OrigMI = *MII;
449 std::deque<MachineInstr *>::iterator AdIt;
450 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
453 if (OrigMI) cerr << "For MInst: " << *OrigMI;
454 cerr << msg << " PREPENDed instr: " << **AdIt << "\n";
456 MII = MIVec.insert(MII, *AdIt);
463 AppendInstructions(std::deque<MachineInstr *> &IAft,
464 MachineCodeForBasicBlock& MIVec,
465 MachineCodeForBasicBlock::iterator& MII,
466 const std::string& msg)
470 MachineInstr* OrigMI = *MII;
471 std::deque<MachineInstr *>::iterator AdIt;
472 for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
475 if (OrigMI) cerr << "For MInst: " << *OrigMI;
476 cerr << msg << " APPENDed instr: " << **AdIt << "\n";
478 ++MII; // insert before the next instruction
479 MII = MIVec.insert(MII, *AdIt);
485 void PhyRegAlloc::updateMachineCode()
487 const BasicBlock* entryBB = Meth->getEntryNode();
489 MachineCodeForBasicBlock& MIVec = entryBB->getMachineInstrVec();
490 MachineCodeForBasicBlock::iterator MII = MIVec.begin();
492 // Insert any instructions needed at method entry
493 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MIVec, MII,
494 "At function entry: \n");
495 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
496 "InstrsAfter should be unnecessary since we are just inserting at "
497 "the function entry point here.");
500 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
503 // iterate over all the machine instructions in BB
504 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
505 for(MachineCodeForBasicBlock::iterator MII = MIVec.begin();
506 MII != MIVec.end(); ++MII) {
508 MachineInstr *MInst = *MII;
510 unsigned Opcode = MInst->getOpCode();
512 // do not process Phis
513 if (TM.getInstrInfo().isDummyPhiInstr(Opcode))
516 // Now insert speical instructions (if necessary) for call/return
519 if (TM.getInstrInfo().isCall(Opcode) ||
520 TM.getInstrInfo().isReturn(Opcode)) {
522 AddedInstrns &AI = AddedInstrMap[MInst];
524 // Tmp stack poistions are needed by some calls that have spilled args
525 // So reset it before we call each such method
527 mcInfo.popAllTempValues(TM);
529 if (TM.getInstrInfo().isCall(Opcode))
530 MRI.colorCallArgs(MInst, LRI, &AI, *this, *BBI);
531 else if (TM.getInstrInfo().isReturn(Opcode))
532 MRI.colorRetValue(MInst, LRI, &AI);
536 /* -- Using above code instead of this
538 // if this machine instr is call, insert caller saving code
540 if( (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
541 MRI.insertCallerSavingCode(MInst, *BBI, *this );
546 // reset the stack offset for temporary variables since we may
547 // need that to spill
548 // mcInfo.popAllTempValues(TM);
549 // TODO ** : do later
551 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
554 // Now replace set the registers for operands in the machine instruction
556 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
558 MachineOperand& Op = MInst->getOperand(OpNum);
560 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
561 Op.getOperandType() == MachineOperand::MO_CCRegister) {
563 const Value *const Val = Op.getVRegValue();
565 // delete this condition checking later (must assert if Val is null)
568 cerr << "Warning: NULL Value found for operand\n";
571 assert( Val && "Value is NULL");
573 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
577 // nothing to worry if it's a const or a label
580 cerr << "*NO LR for operand : " << Op ;
581 cerr << " [reg:" << Op.getAllocatedRegNum() << "]";
582 cerr << " in inst:\t" << *MInst << "\n";
585 // if register is not allocated, mark register as invalid
586 if( Op.getAllocatedRegNum() == -1)
587 Op.setRegForValue( MRI.getInvalidRegNum());
593 unsigned RCID = (LR->getRegClass())->getID();
595 if( LR->hasColor() ) {
596 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
600 // LR did NOT receive a color (register). Now, insert spill code
601 // for spilled opeands in this machine instruction
603 //assert(0 && "LR must be spilled");
604 insertCode4SpilledLR(LR, MInst, *BBI, OpNum );
609 } // for each operand
612 // Now add instructions that the register allocator inserts before/after
613 // this machine instructions (done only for calls/rets/incoming args)
614 // We do this here, to ensure that spill for an instruction is inserted
615 // closest as possible to an instruction (see above insertCode4Spill...)
617 // If there are instructions to be added, *before* this machine
618 // instruction, add them now.
620 if(AddedInstrMap.count(MInst)) {
621 PrependInstructions(AddedInstrMap[MInst].InstrnsBefore, MIVec, MII,"");
624 // If there are instructions to be added *after* this machine
625 // instruction, add them now
627 if (!AddedInstrMap[MInst].InstrnsAfter.empty()) {
629 // if there are delay slots for this instruction, the instructions
630 // added after it must really go after the delayed instruction(s)
631 // So, we move the InstrAfter of the current instruction to the
632 // corresponding delayed instruction
635 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
636 move2DelayedInstr(MInst, *(MII+delay) );
638 if(DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
642 // Here we can add the "instructions after" to the current
643 // instruction since there are no delay slots for this instruction
644 AppendInstructions(AddedInstrMap[MInst].InstrnsAfter, MIVec, MII,"");
649 } // for each machine instruction
655 //----------------------------------------------------------------------------
656 // This method inserts spill code for AN operand whose LR was spilled.
657 // This method may be called several times for a single machine instruction
658 // if it contains many spilled operands. Each time it is called, it finds
659 // a register which is not live at that instruction and also which is not
660 // used by other spilled operands of the same instruction. Then it uses
661 // this register temporarily to accomodate the spilled value.
662 //----------------------------------------------------------------------------
663 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
665 const BasicBlock *BB,
666 const unsigned OpNum) {
668 assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
669 (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
670 "Arg of a call/ret must be handled elsewhere");
672 MachineOperand& Op = MInst->getOperand(OpNum);
673 bool isDef = MInst->operandIsDefined(OpNum);
674 unsigned RegType = MRI.getRegType( LR );
675 int SpillOff = LR->getSpillOffFromFP();
676 RegClass *RC = LR->getRegClass();
677 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
679 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
681 MachineInstr *MIBef=NULL, *AdIMid=NULL, *MIAft=NULL;
683 int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,&LVSetBef, MIBef, MIAft);
685 // get the added instructions for this instruciton
686 AddedInstrns &AI = AddedInstrMap[MInst];
689 // for a USE, we have to load the value of LR from stack to a TmpReg
690 // and use the TmpReg as one operand of instruction
692 // actual loading instruction
693 AdIMid = MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType);
696 AI.InstrnsBefore.push_back(MIBef);
698 AI.InstrnsBefore.push_back(AdIMid);
701 AI.InstrnsAfter.push_front(MIAft);
703 } else { // if this is a Def
704 // for a DEF, we have to store the value produced by this instruction
705 // on the stack position allocated for this LR
707 // actual storing instruction
708 AdIMid = MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType);
711 AI.InstrnsBefore.push_back(MIBef);
713 AI.InstrnsAfter.push_front(AdIMid);
716 AI.InstrnsAfter.push_front(MIAft);
720 cerr << "\nFor Inst " << *MInst;
721 cerr << " - SPILLED LR: "; printSet(*LR);
722 cerr << "\n - Added Instructions:";
723 if (MIBef) cerr << *MIBef;
725 if (MIAft) cerr << *MIAft;
727 Op.setRegForValue(TmpRegU); // set the opearnd
732 //----------------------------------------------------------------------------
733 // We can use the following method to get a temporary register to be used
734 // BEFORE any given machine instruction. If there is a register available,
735 // this method will simply return that register and set MIBef = MIAft = NULL.
736 // Otherwise, it will return a register and MIAft and MIBef will contain
737 // two instructions used to free up this returned register.
738 // Returned register number is the UNIFIED register number
739 //----------------------------------------------------------------------------
741 int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC,
743 const MachineInstr *MInst,
744 const ValueSet *LVSetBef,
745 MachineInstr *&MIBef,
746 MachineInstr *&MIAft) {
748 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
752 // we found an unused register, so we can simply use it
753 MIBef = MIAft = NULL;
756 // we couldn't find an unused register. Generate code to free up a reg by
757 // saving it on stack and restoring after the instruction
759 int TmpOff = mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
761 RegU = getUniRegNotUsedByThisInst(RC, MInst);
762 MIBef = MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType );
763 MIAft = MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType );
769 //----------------------------------------------------------------------------
770 // This method is called to get a new unused register that can be used to
771 // accomodate a spilled value.
772 // This method may be called several times for a single machine instruction
773 // if it contains many spilled operands. Each time it is called, it finds
774 // a register which is not live at that instruction and also which is not
775 // used by other spilled operands of the same instruction.
776 // Return register number is relative to the register class. NOT
778 //----------------------------------------------------------------------------
779 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
780 const MachineInstr *MInst,
781 const ValueSet *LVSetBef) {
783 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
785 bool *IsColorUsedArr = RC->getIsColorUsedArr();
787 for(unsigned i=0; i < NumAvailRegs; i++) // Reset array
788 IsColorUsedArr[i] = false;
790 ValueSet::const_iterator LIt = LVSetBef->begin();
792 // for each live var in live variable set after machine inst
793 for( ; LIt != LVSetBef->end(); ++LIt) {
795 // get the live range corresponding to live var
796 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
798 // LR can be null if it is a const since a const
799 // doesn't have a dominating def - see Assumptions above
801 if( LRofLV->hasColor() )
802 IsColorUsedArr[ LRofLV->getColor() ] = true;
805 // It is possible that one operand of this MInst was already spilled
806 // and it received some register temporarily. If that's the case,
807 // it is recorded in machine operand. We must skip such registers.
809 setRelRegsUsedByThisInst(RC, MInst);
811 unsigned c; // find first unused color
812 for( c=0; c < NumAvailRegs; c++)
813 if( ! IsColorUsedArr[ c ] ) break;
816 return MRI.getUnifiedRegNum(RC->getID(), c);
824 //----------------------------------------------------------------------------
825 // Get any other register in a register class, other than what is used
826 // by operands of a machine instruction. Returns the unified reg number.
827 //----------------------------------------------------------------------------
828 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
829 const MachineInstr *MInst) {
831 bool *IsColorUsedArr = RC->getIsColorUsedArr();
832 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
835 for(unsigned i=0; i < NumAvailRegs ; i++) // Reset array
836 IsColorUsedArr[i] = false;
838 setRelRegsUsedByThisInst(RC, MInst);
840 unsigned c; // find first unused color
841 for( c=0; c < RC->getNumOfAvailRegs(); c++)
842 if( ! IsColorUsedArr[ c ] ) break;
845 return MRI.getUnifiedRegNum(RC->getID(), c);
847 assert( 0 && "FATAL: No free register could be found in reg class!!");
852 //----------------------------------------------------------------------------
853 // This method modifies the IsColorUsedArr of the register class passed to it.
854 // It sets the bits corresponding to the registers used by this machine
855 // instructions. Both explicit and implicit operands are set.
856 //----------------------------------------------------------------------------
857 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
858 const MachineInstr *MInst ) {
860 bool *IsColorUsedArr = RC->getIsColorUsedArr();
862 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
864 const MachineOperand& Op = MInst->getOperand(OpNum);
866 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
867 Op.getOperandType() == MachineOperand::MO_CCRegister ) {
869 const Value *const Val = Op.getVRegValue();
872 if( MRI.getRegClassIDOfValue(Val) == RC->getID() ) {
874 if( (Reg=Op.getAllocatedRegNum()) != -1) {
875 IsColorUsedArr[ Reg ] = true;
878 // it is possilbe that this operand still is not marked with
879 // a register but it has a LR and that received a color
881 LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
883 if( LROfVal->hasColor() )
884 IsColorUsedArr[ LROfVal->getColor() ] = true;
887 } // if reg classes are the same
889 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
890 IsColorUsedArr[ Op.getMachineRegNum() ] = true;
894 // If there are implicit references, mark them as well
896 for(unsigned z=0; z < MInst->getNumImplicitRefs(); z++) {
898 LiveRange *const LRofImpRef =
899 LRI.getLiveRangeForValue( MInst->getImplicitRef(z) );
901 if(LRofImpRef && LRofImpRef->hasColor())
902 IsColorUsedArr[LRofImpRef->getColor()] = true;
913 //----------------------------------------------------------------------------
914 // If there are delay slots for an instruction, the instructions
915 // added after it must really go after the delayed instruction(s).
916 // So, we move the InstrAfter of that instruction to the
917 // corresponding delayed instruction using the following method.
919 //----------------------------------------------------------------------------
920 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
921 const MachineInstr *DelayedMI) {
923 // "added after" instructions of the original instr
924 std::deque<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
926 // "added instructions" of the delayed instr
927 AddedInstrns &DelayAdI = AddedInstrMap[DelayedMI];
929 // "added after" instructions of the delayed instr
930 std::deque<MachineInstr *> &DelayedAft = DelayAdI.InstrnsAfter;
932 // go thru all the "added after instructions" of the original instruction
933 // and append them to the "addded after instructions" of the delayed
935 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
937 // empty the "added after instructions" of the original instruction
941 //----------------------------------------------------------------------------
942 // This method prints the code with registers after register allocation is
944 //----------------------------------------------------------------------------
945 void PhyRegAlloc::printMachineCode()
948 cerr << "\n;************** Function " << Meth->getName()
949 << " *****************\n";
951 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
953 cerr << "\n"; printLabel(*BBI); cerr << ": ";
955 // get the iterator for machine instructions
956 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
957 MachineCodeForBasicBlock::iterator MII = MIVec.begin();
959 // iterate over all the machine instructions in BB
960 for( ; MII != MIVec.end(); ++MII) {
961 MachineInstr *const MInst = *MII;
964 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
966 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
967 MachineOperand& Op = MInst->getOperand(OpNum);
969 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
970 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
971 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
973 const Value *const Val = Op.getVRegValue () ;
974 // ****this code is temporary till NULL Values are fixed
976 cerr << "\t<*NULL*>";
980 // if a label or a constant
981 if(isa<BasicBlock>(Val)) {
982 cerr << "\t"; printLabel( Op.getVRegValue () );
984 // else it must be a register value
985 const int RegNum = Op.getAllocatedRegNum();
987 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
989 cerr << "(" << Val->getName() << ")";
991 cerr << "(" << Val << ")";
996 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
998 if( LROfVal->hasSpillOffset() )
1003 else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
1004 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1008 cerr << "\t" << Op; // use dump field
1013 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1014 if( NumOfImpRefs > 0) {
1015 cerr << "\tImplicit:";
1017 for(unsigned z=0; z < NumOfImpRefs; z++)
1018 cerr << RAV(MInst->getImplicitRef(z)) << "\t";
1021 } // for all machine instructions
1033 //----------------------------------------------------------------------------
1035 //----------------------------------------------------------------------------
1037 void PhyRegAlloc::colorCallRetArgs()
1040 CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
1041 CallRetInstrListType::const_iterator It = CallRetInstList.begin();
1043 for( ; It != CallRetInstList.end(); ++It ) {
1045 const MachineInstr *const CRMI = *It;
1046 unsigned OpCode = CRMI->getOpCode();
1048 // get the added instructions for this Call/Ret instruciton
1049 AddedInstrns &AI = AddedInstrMap[CRMI];
1051 // Tmp stack positions are needed by some calls that have spilled args
1052 // So reset it before we call each such method
1053 //mcInfo.popAllTempValues(TM);
1056 if (TM.getInstrInfo().isCall(OpCode))
1057 MRI.colorCallArgs(CRMI, LRI, &AI, *this);
1058 else if (TM.getInstrInfo().isReturn(OpCode))
1059 MRI.colorRetValue(CRMI, LRI, &AI);
1061 assert(0 && "Non Call/Ret instrn in CallRetInstrList\n");
1067 //----------------------------------------------------------------------------
1069 //----------------------------------------------------------------------------
1070 void PhyRegAlloc::colorIncomingArgs()
1072 const BasicBlock *const FirstBB = Meth->front();
1073 const MachineInstr *FirstMI = FirstBB->getMachineInstrVec().front();
1074 assert(FirstMI && "No machine instruction in entry BB");
1076 MRI.colorMethodArgs(Meth, LRI, &AddedInstrAtEntry);
1080 //----------------------------------------------------------------------------
1081 // Used to generate a label for a basic block
1082 //----------------------------------------------------------------------------
1083 void PhyRegAlloc::printLabel(const Value *const Val) {
1085 cerr << Val->getName();
1087 cerr << "Label" << Val;
1091 //----------------------------------------------------------------------------
1092 // This method calls setSugColorUsable method of each live range. This
1093 // will determine whether the suggested color of LR is really usable.
1094 // A suggested color is not usable when the suggested color is volatile
1095 // AND when there are call interferences
1096 //----------------------------------------------------------------------------
1098 void PhyRegAlloc::markUnusableSugColors()
1100 if(DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
1102 // hash map iterator
1103 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1104 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1106 for(; HMI != HMIEnd ; ++HMI ) {
1108 LiveRange *L = HMI->second; // get the LiveRange
1110 if(L->hasSuggestedColor()) {
1111 int RCID = L->getRegClass()->getID();
1112 if( MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1113 L->isCallInterference() )
1114 L->setSuggestedColorUsable( false );
1116 L->setSuggestedColorUsable( true );
1118 } // if L->hasSuggestedColor()
1120 } // for all LR's in hash map
1125 //----------------------------------------------------------------------------
1126 // The following method will set the stack offsets of the live ranges that
1127 // are decided to be spillled. This must be called just after coloring the
1128 // LRs using the graph coloring algo. For each live range that is spilled,
1129 // this method allocate a new spill position on the stack.
1130 //----------------------------------------------------------------------------
1132 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1133 if (DEBUG_RA) cerr << "\nsetting LR stack offsets ...\n";
1135 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
1136 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
1138 for( ; HMI != HMIEnd ; ++HMI) {
1139 if (HMI->first && HMI->second) {
1140 LiveRange *L = HMI->second; // get the LiveRange
1141 if (!L->hasColor()) // NOTE: ** allocating the size of long Type **
1142 L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
1144 } // for all LR's in hash map
1149 //----------------------------------------------------------------------------
1150 // The entry pont to Register Allocation
1151 //----------------------------------------------------------------------------
1153 void PhyRegAlloc::allocateRegisters()
1156 // make sure that we put all register classes into the RegClassList
1157 // before we call constructLiveRanges (now done in the constructor of
1158 // PhyRegAlloc class).
1160 LRI.constructLiveRanges(); // create LR info
1163 LRI.printLiveRanges();
1165 createIGNodeListsAndIGs(); // create IGNode list and IGs
1167 buildInterferenceGraphs(); // build IGs in all reg classes
1171 // print all LRs in all reg classes
1172 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1173 RegClassList[ rc ]->printIGNodeList();
1175 // print IGs in all register classes
1176 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1177 RegClassList[ rc ]->printIG();
1181 LRI.coalesceLRs(); // coalesce all live ranges
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 // mark un-usable suggested color before graph coloring algorithm.
1196 // When this is done, the graph coloring algo will not reserve
1197 // suggested color unnecessarily - they can be used by another LR
1199 markUnusableSugColors();
1201 // color all register classes using the graph coloring algo
1202 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1203 RegClassList[ rc ]->colorAllRegs();
1205 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1206 // a poistion for such spilled LRs
1208 allocateStackSpace4SpilledLRs();
1210 mcInfo.popAllTempValues(TM); // TODO **Check
1212 // color incoming args - if the correct color was not received
1213 // insert code to copy to the correct register
1215 colorIncomingArgs();
1217 // Now update the machine code with register names and add any
1218 // additional code inserted by the register allocator to the instruction
1221 updateMachineCode();
1224 MachineCodeForMethod::get(Meth).dump();
1225 printMachineCode(); // only for DEBUGGING