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"
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 FunctionPass {
44 TargetMachine &Target;
46 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
48 bool runOnFunction(Function *F) {
50 cerr << "\n******************** Function "<< F->getName()
51 << " ********************\n";
53 PhyRegAlloc PRA(F, Target, &getAnalysis<FunctionLiveVarInfo>(),
54 &getAnalysis<LoopInfo>());
55 PRA.allocateRegisters();
57 if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
61 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
62 AU.addRequired(LoopInfo::ID);
63 AU.addRequired(FunctionLiveVarInfo::ID);
68 Pass *getRegisterAllocator(TargetMachine &T) {
69 return new RegisterAllocator(T);
72 //----------------------------------------------------------------------------
73 // Constructor: Init local composite objects and create register classes.
74 //----------------------------------------------------------------------------
75 PhyRegAlloc::PhyRegAlloc(Function *F, const TargetMachine& tm,
76 FunctionLiveVarInfo *Lvi, LoopInfo *LDC)
78 mcInfo(MachineCodeForMethod::get(F)),
79 LVI(Lvi), LRI(F, tm, RegClassList),
81 NumOfRegClasses(MRI.getNumOfRegClasses()),
84 // create each RegisterClass and put in RegClassList
86 for(unsigned int rc=0; rc < NumOfRegClasses; rc++)
87 RegClassList.push_back(new RegClass(F, MRI.getMachineRegClass(rc),
92 //----------------------------------------------------------------------------
93 // Destructor: Deletes register classes
94 //----------------------------------------------------------------------------
95 PhyRegAlloc::~PhyRegAlloc() {
96 for( unsigned int rc=0; rc < NumOfRegClasses; rc++)
97 delete RegClassList[rc];
99 AddedInstrMap.clear();
102 //----------------------------------------------------------------------------
103 // This method initally creates interference graphs (one in each reg class)
104 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
105 //----------------------------------------------------------------------------
106 void PhyRegAlloc::createIGNodeListsAndIGs() {
107 if (DEBUG_RA) cerr << "Creating LR lists ...\n";
110 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
113 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
115 for (; HMI != HMIEnd ; ++HMI ) {
117 LiveRange *L = HMI->second; // get the LiveRange
120 cerr << "\n*?!?Warning: Null liver range found for: "
121 << RAV(HMI->first) << "\n";
125 // if the Value * is not null, and LR
126 // is not yet written to the IGNodeList
127 if( !(L->getUserIGNode()) ) {
128 RegClass *const RC = // RegClass of first value in the LR
129 RegClassList[ L->getRegClass()->getID() ];
131 RC->addLRToIG(L); // add this LR to an IG
137 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
138 RegClassList[rc]->createInterferenceGraph();
141 cerr << "LRLists Created!\n";
147 //----------------------------------------------------------------------------
148 // This method will add all interferences at for a given instruction.
149 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
150 // class as that of live var. The live var passed to this function is the
151 // LVset AFTER the instruction
152 //----------------------------------------------------------------------------
153 void PhyRegAlloc::addInterference(const Value *Def,
154 const ValueSet *LVSet,
157 ValueSet::const_iterator LIt = LVSet->begin();
159 // get the live range of instruction
161 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
163 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
164 assert( IGNodeOfDef );
166 RegClass *const RCOfDef = LROfDef->getRegClass();
168 // for each live var in live variable set
170 for( ; LIt != LVSet->end(); ++LIt) {
173 cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
175 // get the live range corresponding to live var
177 LiveRange *LROfVar = LRI.getLiveRangeForValue(*LIt);
179 // LROfVar can be null if it is a const since a const
180 // doesn't have a dominating def - see Assumptions above
183 if(LROfDef == LROfVar) // do not set interf for same LR
186 // if 2 reg classes are the same set interference
188 if (RCOfDef == LROfVar->getRegClass()) {
189 RCOfDef->setInterference( LROfDef, LROfVar);
190 } else if (DEBUG_RA > 1) {
191 // we will not have LRs for values not explicitly allocated in the
192 // instruction stream (e.g., constants)
193 cerr << " warning: no live range for " << RAV(*LIt) << "\n";
201 //----------------------------------------------------------------------------
202 // For a call instruction, this method sets the CallInterference flag in
203 // the LR of each variable live int the Live Variable Set live after the
204 // call instruction (except the return value of the call instruction - since
205 // the return value does not interfere with that call itself).
206 //----------------------------------------------------------------------------
208 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
209 const ValueSet *LVSetAft) {
212 cerr << "\n For call inst: " << *MInst;
214 ValueSet::const_iterator LIt = LVSetAft->begin();
216 // for each live var in live variable set after machine inst
218 for( ; LIt != LVSetAft->end(); ++LIt) {
220 // get the live range corresponding to live var
222 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
224 if( LR && DEBUG_RA) {
225 cerr << "\n\tLR Aft Call: ";
229 // LR can be null if it is a const since a const
230 // doesn't have a dominating def - see Assumptions above
233 LR->setCallInterference();
235 cerr << "\n ++Added call interf for LR: " ;
242 // Now find the LR of the return value of the call
243 // We do this because, we look at the LV set *after* the instruction
244 // to determine, which LRs must be saved across calls. The return value
245 // of the call is live in this set - but it does not interfere with call
246 // (i.e., we can allocate a volatile register to the return value)
248 if( const Value *RetVal = MRI.getCallInstRetVal( MInst )) {
249 LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
250 assert( RetValLR && "No LR for RetValue of call");
251 RetValLR->clearCallInterference();
254 // If the CALL is an indirect call, find the LR of the function pointer.
255 // That has a call interference because it conflicts with outgoing args.
256 if( const Value *AddrVal = MRI.getCallInstIndirectAddrVal( MInst )) {
257 LiveRange *AddrValLR = LRI.getLiveRangeForValue( AddrVal );
258 assert( AddrValLR && "No LR for indirect addr val of call");
259 AddrValLR->setCallInterference();
267 //----------------------------------------------------------------------------
268 // This method will walk thru code and create interferences in the IG of
269 // each RegClass. Also, this method calculates the spill cost of each
270 // Live Range (it is done in this method to save another pass over the code).
271 //----------------------------------------------------------------------------
272 void PhyRegAlloc::buildInterferenceGraphs()
275 if(DEBUG_RA) cerr << "Creating interference graphs ...\n";
277 unsigned BBLoopDepthCost;
278 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
281 // find the 10^(loop_depth) of this BB
283 BBLoopDepthCost = (unsigned) pow(10.0, LoopDepthCalc->getLoopDepth(*BBI));
285 // get the iterator for machine instructions
287 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
288 MachineCodeForBasicBlock::const_iterator MII = MIVec.begin();
290 // iterate over all the machine instructions in BB
292 for( ; MII != MIVec.end(); ++MII) {
294 const MachineInstr *MInst = *MII;
296 // get the LV set after the instruction
298 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, *BBI);
300 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
303 // set the isCallInterference flag of each live range wich extends
304 // accross this call instruction. This information is used by graph
305 // coloring algo to avoid allocating volatile colors to live ranges
306 // that span across calls (since they have to be saved/restored)
308 setCallInterferences(MInst, &LVSetAI);
312 // iterate over all MI operands to find defs
314 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
315 OpE = MInst->end(); OpI != OpE; ++OpI) {
316 if (OpI.isDef()) // create a new LR iff this operand is a def
317 addInterference(*OpI, &LVSetAI, isCallInst);
319 // Calculate the spill cost of each live range
321 LiveRange *LR = LRI.getLiveRangeForValue(*OpI);
322 if (LR) LR->addSpillCost(BBLoopDepthCost);
326 // if there are multiple defs in this instruction e.g. in SETX
328 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
329 addInterf4PseudoInstr(MInst);
332 // Also add interference for any implicit definitions in a machine
333 // instr (currently, only calls have this).
335 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
336 if( NumOfImpRefs > 0 ) {
337 for(unsigned z=0; z < NumOfImpRefs; z++)
338 if( MInst->implicitRefIsDefined(z) )
339 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
343 } // for all machine instructions in BB
344 } // for all BBs in function
347 // add interferences for function arguments. Since there are no explict
348 // defs in the function for args, we have to add them manually
350 addInterferencesForArgs();
353 cerr << "Interference graphs calculted!\n";
359 //--------------------------------------------------------------------------
360 // Pseudo instructions will be exapnded to multiple instructions by the
361 // assembler. Consequently, all the opernds must get distinct registers.
362 // Therefore, we mark all operands of a pseudo instruction as they interfere
364 //--------------------------------------------------------------------------
365 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
367 bool setInterf = false;
369 // iterate over MI operands to find defs
371 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
372 ItE = MInst->end(); It1 != ItE; ++It1) {
373 const LiveRange *LROfOp1 = LRI.getLiveRangeForValue(*It1);
374 assert((LROfOp1 || !It1.isDef()) && "No LR for Def in PSEUDO insruction");
376 MachineInstr::const_val_op_iterator It2 = It1;
377 for(++It2; It2 != ItE; ++It2) {
378 const LiveRange *LROfOp2 = LRI.getLiveRangeForValue(*It2);
381 RegClass *RCOfOp1 = LROfOp1->getRegClass();
382 RegClass *RCOfOp2 = LROfOp2->getRegClass();
384 if( RCOfOp1 == RCOfOp2 ){
385 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
389 } // for all other defs in machine instr
390 } // for all operands in an instruction
392 if (!setInterf && MInst->getNumOperands() > 2) {
393 cerr << "\nInterf not set for any operand in pseudo instr:\n";
395 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
401 //----------------------------------------------------------------------------
402 // This method will add interferences for incoming arguments to a function.
403 //----------------------------------------------------------------------------
404 void PhyRegAlloc::addInterferencesForArgs() {
405 // get the InSet of root BB
406 const ValueSet &InSet = LVI->getInSetOfBB(Meth->front());
408 // get the argument list
409 const Function::ArgumentListType &ArgList = Meth->getArgumentList();
411 // get an iterator to arg list
412 Function::ArgumentListType::const_iterator ArgIt = ArgList.begin();
415 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
416 addInterference((Value*)*ArgIt, &InSet, false);// add interferences between
417 // args and LVars at start
419 cerr << " - %% adding interference for argument "
420 << RAV((const Value *)*ArgIt) << "\n";
425 //----------------------------------------------------------------------------
426 // This method is called after register allocation is complete to set the
427 // allocated reisters in the machine code. This code will add register numbers
428 // to MachineOperands that contain a Value. Also it calls target specific
429 // methods to produce caller saving instructions. At the end, it adds all
430 // additional instructions produced by the register allocator to the
431 // instruction stream.
432 //----------------------------------------------------------------------------
434 //-----------------------------
435 // Utility functions used below
436 //-----------------------------
438 PrependInstructions(std::deque<MachineInstr *> &IBef,
439 MachineCodeForBasicBlock& MIVec,
440 MachineCodeForBasicBlock::iterator& MII,
441 const std::string& msg)
445 MachineInstr* OrigMI = *MII;
446 std::deque<MachineInstr *>::iterator AdIt;
447 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
450 if (OrigMI) cerr << "For MInst: " << *OrigMI;
451 cerr << msg << " PREPENDed instr: " << **AdIt << "\n";
453 MII = MIVec.insert(MII, *AdIt);
460 AppendInstructions(std::deque<MachineInstr *> &IAft,
461 MachineCodeForBasicBlock& MIVec,
462 MachineCodeForBasicBlock::iterator& MII,
463 const std::string& msg)
467 MachineInstr* OrigMI = *MII;
468 std::deque<MachineInstr *>::iterator AdIt;
469 for( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
472 if (OrigMI) cerr << "For MInst: " << *OrigMI;
473 cerr << msg << " APPENDed instr: " << **AdIt << "\n";
475 ++MII; // insert before the next instruction
476 MII = MIVec.insert(MII, *AdIt);
482 void PhyRegAlloc::updateMachineCode()
484 const BasicBlock* entryBB = Meth->getEntryNode();
486 MachineCodeForBasicBlock& MIVec = entryBB->getMachineInstrVec();
487 MachineCodeForBasicBlock::iterator MII = MIVec.begin();
489 // Insert any instructions needed at method entry
490 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MIVec, MII,
491 "At function entry: \n");
492 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
493 "InstrsAfter should be unnecessary since we are just inserting at "
494 "the function entry point here.");
497 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
500 // iterate over all the machine instructions in BB
501 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
502 for(MachineCodeForBasicBlock::iterator MII = MIVec.begin();
503 MII != MIVec.end(); ++MII) {
505 MachineInstr *MInst = *MII;
507 unsigned Opcode = MInst->getOpCode();
509 // do not process Phis
510 if (TM.getInstrInfo().isDummyPhiInstr(Opcode))
513 // Now insert speical instructions (if necessary) for call/return
516 if (TM.getInstrInfo().isCall(Opcode) ||
517 TM.getInstrInfo().isReturn(Opcode)) {
519 AddedInstrns &AI = AddedInstrMap[MInst];
521 // Tmp stack poistions are needed by some calls that have spilled args
522 // So reset it before we call each such method
524 mcInfo.popAllTempValues(TM);
526 if (TM.getInstrInfo().isCall(Opcode))
527 MRI.colorCallArgs(MInst, LRI, &AI, *this, *BBI);
528 else if (TM.getInstrInfo().isReturn(Opcode))
529 MRI.colorRetValue(MInst, LRI, &AI);
533 /* -- Using above code instead of this
535 // if this machine instr is call, insert caller saving code
537 if( (TM.getInstrInfo()).isCall( MInst->getOpCode()) )
538 MRI.insertCallerSavingCode(MInst, *BBI, *this );
543 // reset the stack offset for temporary variables since we may
544 // need that to spill
545 // mcInfo.popAllTempValues(TM);
546 // TODO ** : do later
548 //for(MachineInstr::val_const_op_iterator OpI(MInst);!OpI.done();++OpI) {
551 // Now replace set the registers for operands in the machine instruction
553 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
555 MachineOperand& Op = MInst->getOperand(OpNum);
557 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
558 Op.getOperandType() == MachineOperand::MO_CCRegister) {
560 const Value *const Val = Op.getVRegValue();
562 // delete this condition checking later (must assert if Val is null)
565 cerr << "Warning: NULL Value found for operand\n";
568 assert( Val && "Value is NULL");
570 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
574 // nothing to worry if it's a const or a label
577 cerr << "*NO LR for operand : " << Op ;
578 cerr << " [reg:" << Op.getAllocatedRegNum() << "]";
579 cerr << " in inst:\t" << *MInst << "\n";
582 // if register is not allocated, mark register as invalid
583 if( Op.getAllocatedRegNum() == -1)
584 Op.setRegForValue( MRI.getInvalidRegNum());
590 unsigned RCID = (LR->getRegClass())->getID();
592 if( LR->hasColor() ) {
593 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
597 // LR did NOT receive a color (register). Now, insert spill code
598 // for spilled opeands in this machine instruction
600 //assert(0 && "LR must be spilled");
601 insertCode4SpilledLR(LR, MInst, *BBI, OpNum );
606 } // for each operand
609 // Now add instructions that the register allocator inserts before/after
610 // this machine instructions (done only for calls/rets/incoming args)
611 // We do this here, to ensure that spill for an instruction is inserted
612 // closest as possible to an instruction (see above insertCode4Spill...)
614 // If there are instructions to be added, *before* this machine
615 // instruction, add them now.
617 if(AddedInstrMap.count(MInst)) {
618 PrependInstructions(AddedInstrMap[MInst].InstrnsBefore, MIVec, MII,"");
621 // If there are instructions to be added *after* this machine
622 // instruction, add them now
624 if (!AddedInstrMap[MInst].InstrnsAfter.empty()) {
626 // if there are delay slots for this instruction, the instructions
627 // added after it must really go after the delayed instruction(s)
628 // So, we move the InstrAfter of the current instruction to the
629 // corresponding delayed instruction
632 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
633 move2DelayedInstr(MInst, *(MII+delay) );
635 if(DEBUG_RA) cerr<< "\nMoved an added instr after the delay slot";
639 // Here we can add the "instructions after" to the current
640 // instruction since there are no delay slots for this instruction
641 AppendInstructions(AddedInstrMap[MInst].InstrnsAfter, MIVec, MII,"");
646 } // for each machine instruction
652 //----------------------------------------------------------------------------
653 // This method inserts spill code for AN operand whose LR was spilled.
654 // This method may be called several times for a single machine instruction
655 // if it contains many spilled operands. Each time it is called, it finds
656 // a register which is not live at that instruction and also which is not
657 // used by other spilled operands of the same instruction. Then it uses
658 // this register temporarily to accomodate the spilled value.
659 //----------------------------------------------------------------------------
660 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
662 const BasicBlock *BB,
663 const unsigned OpNum) {
665 assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
666 (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
667 "Arg of a call/ret must be handled elsewhere");
669 MachineOperand& Op = MInst->getOperand(OpNum);
670 bool isDef = MInst->operandIsDefined(OpNum);
671 unsigned RegType = MRI.getRegType( LR );
672 int SpillOff = LR->getSpillOffFromFP();
673 RegClass *RC = LR->getRegClass();
674 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
676 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
678 MachineInstr *MIBef=NULL, *AdIMid=NULL, *MIAft=NULL;
680 int TmpRegU = getUsableUniRegAtMI(RC, RegType, MInst,&LVSetBef, MIBef, MIAft);
682 // get the added instructions for this instruciton
683 AddedInstrns &AI = AddedInstrMap[MInst];
686 // for a USE, we have to load the value of LR from stack to a TmpReg
687 // and use the TmpReg as one operand of instruction
689 // actual loading instruction
690 AdIMid = MRI.cpMem2RegMI(MRI.getFramePointer(), SpillOff, TmpRegU,RegType);
693 AI.InstrnsBefore.push_back(MIBef);
695 AI.InstrnsBefore.push_back(AdIMid);
698 AI.InstrnsAfter.push_front(MIAft);
700 } else { // if this is a Def
701 // for a DEF, we have to store the value produced by this instruction
702 // on the stack position allocated for this LR
704 // actual storing instruction
705 AdIMid = MRI.cpReg2MemMI(TmpRegU, MRI.getFramePointer(), SpillOff,RegType);
708 AI.InstrnsBefore.push_back(MIBef);
710 AI.InstrnsAfter.push_front(AdIMid);
713 AI.InstrnsAfter.push_front(MIAft);
717 cerr << "\nFor Inst " << *MInst;
718 cerr << " - SPILLED LR: "; printSet(*LR);
719 cerr << "\n - Added Instructions:";
720 if (MIBef) cerr << *MIBef;
722 if (MIAft) cerr << *MIAft;
724 Op.setRegForValue(TmpRegU); // set the opearnd
729 //----------------------------------------------------------------------------
730 // We can use the following method to get a temporary register to be used
731 // BEFORE any given machine instruction. If there is a register available,
732 // this method will simply return that register and set MIBef = MIAft = NULL.
733 // Otherwise, it will return a register and MIAft and MIBef will contain
734 // two instructions used to free up this returned register.
735 // Returned register number is the UNIFIED register number
736 //----------------------------------------------------------------------------
738 int PhyRegAlloc::getUsableUniRegAtMI(RegClass *RC,
740 const MachineInstr *MInst,
741 const ValueSet *LVSetBef,
742 MachineInstr *&MIBef,
743 MachineInstr *&MIAft) {
745 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
749 // we found an unused register, so we can simply use it
750 MIBef = MIAft = NULL;
753 // we couldn't find an unused register. Generate code to free up a reg by
754 // saving it on stack and restoring after the instruction
756 int TmpOff = mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
758 RegU = getUniRegNotUsedByThisInst(RC, MInst);
759 MIBef = MRI.cpReg2MemMI(RegU, MRI.getFramePointer(), TmpOff, RegType );
760 MIAft = MRI.cpMem2RegMI(MRI.getFramePointer(), TmpOff, RegU, RegType );
766 //----------------------------------------------------------------------------
767 // This method is called to get a new unused register that can be used to
768 // accomodate a spilled value.
769 // This method may be called several times for a single machine instruction
770 // if it contains many spilled operands. Each time it is called, it finds
771 // a register which is not live at that instruction and also which is not
772 // used by other spilled operands of the same instruction.
773 // Return register number is relative to the register class. NOT
775 //----------------------------------------------------------------------------
776 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
777 const MachineInstr *MInst,
778 const ValueSet *LVSetBef) {
780 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
782 bool *IsColorUsedArr = RC->getIsColorUsedArr();
784 for(unsigned i=0; i < NumAvailRegs; i++) // Reset array
785 IsColorUsedArr[i] = false;
787 ValueSet::const_iterator LIt = LVSetBef->begin();
789 // for each live var in live variable set after machine inst
790 for( ; LIt != LVSetBef->end(); ++LIt) {
792 // get the live range corresponding to live var
793 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
795 // LR can be null if it is a const since a const
796 // doesn't have a dominating def - see Assumptions above
798 if( LRofLV->hasColor() )
799 IsColorUsedArr[ LRofLV->getColor() ] = true;
802 // It is possible that one operand of this MInst was already spilled
803 // and it received some register temporarily. If that's the case,
804 // it is recorded in machine operand. We must skip such registers.
806 setRelRegsUsedByThisInst(RC, MInst);
808 unsigned c; // find first unused color
809 for( c=0; c < NumAvailRegs; c++)
810 if( ! IsColorUsedArr[ c ] ) break;
813 return MRI.getUnifiedRegNum(RC->getID(), c);
821 //----------------------------------------------------------------------------
822 // Get any other register in a register class, other than what is used
823 // by operands of a machine instruction. Returns the unified reg number.
824 //----------------------------------------------------------------------------
825 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
826 const MachineInstr *MInst) {
828 bool *IsColorUsedArr = RC->getIsColorUsedArr();
829 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
832 for(unsigned i=0; i < NumAvailRegs ; i++) // Reset array
833 IsColorUsedArr[i] = false;
835 setRelRegsUsedByThisInst(RC, MInst);
837 unsigned c; // find first unused color
838 for( c=0; c < RC->getNumOfAvailRegs(); c++)
839 if( ! IsColorUsedArr[ c ] ) break;
842 return MRI.getUnifiedRegNum(RC->getID(), c);
844 assert( 0 && "FATAL: No free register could be found in reg class!!");
849 //----------------------------------------------------------------------------
850 // This method modifies the IsColorUsedArr of the register class passed to it.
851 // It sets the bits corresponding to the registers used by this machine
852 // instructions. Both explicit and implicit operands are set.
853 //----------------------------------------------------------------------------
854 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
855 const MachineInstr *MInst ) {
857 bool *IsColorUsedArr = RC->getIsColorUsedArr();
859 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
861 const MachineOperand& Op = MInst->getOperand(OpNum);
863 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
864 Op.getOperandType() == MachineOperand::MO_CCRegister ) {
866 const Value *const Val = Op.getVRegValue();
869 if( MRI.getRegClassIDOfValue(Val) == RC->getID() ) {
871 if( (Reg=Op.getAllocatedRegNum()) != -1) {
872 IsColorUsedArr[ Reg ] = true;
875 // it is possilbe that this operand still is not marked with
876 // a register but it has a LR and that received a color
878 LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
880 if( LROfVal->hasColor() )
881 IsColorUsedArr[ LROfVal->getColor() ] = true;
884 } // if reg classes are the same
886 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
887 IsColorUsedArr[ Op.getMachineRegNum() ] = true;
891 // If there are implicit references, mark them as well
893 for(unsigned z=0; z < MInst->getNumImplicitRefs(); z++) {
895 LiveRange *const LRofImpRef =
896 LRI.getLiveRangeForValue( MInst->getImplicitRef(z) );
898 if(LRofImpRef && LRofImpRef->hasColor())
899 IsColorUsedArr[LRofImpRef->getColor()] = true;
910 //----------------------------------------------------------------------------
911 // If there are delay slots for an instruction, the instructions
912 // added after it must really go after the delayed instruction(s).
913 // So, we move the InstrAfter of that instruction to the
914 // corresponding delayed instruction using the following method.
916 //----------------------------------------------------------------------------
917 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
918 const MachineInstr *DelayedMI) {
920 // "added after" instructions of the original instr
921 std::deque<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
923 // "added instructions" of the delayed instr
924 AddedInstrns &DelayAdI = AddedInstrMap[DelayedMI];
926 // "added after" instructions of the delayed instr
927 std::deque<MachineInstr *> &DelayedAft = DelayAdI.InstrnsAfter;
929 // go thru all the "added after instructions" of the original instruction
930 // and append them to the "addded after instructions" of the delayed
932 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
934 // empty the "added after instructions" of the original instruction
938 //----------------------------------------------------------------------------
939 // This method prints the code with registers after register allocation is
941 //----------------------------------------------------------------------------
942 void PhyRegAlloc::printMachineCode()
945 cerr << "\n;************** Function " << Meth->getName()
946 << " *****************\n";
948 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
950 cerr << "\n"; printLabel(*BBI); cerr << ": ";
952 // get the iterator for machine instructions
953 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
954 MachineCodeForBasicBlock::iterator MII = MIVec.begin();
956 // iterate over all the machine instructions in BB
957 for( ; MII != MIVec.end(); ++MII) {
958 MachineInstr *const MInst = *MII;
961 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
963 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
964 MachineOperand& Op = MInst->getOperand(OpNum);
966 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
967 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
968 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
970 const Value *const Val = Op.getVRegValue () ;
971 // ****this code is temporary till NULL Values are fixed
973 cerr << "\t<*NULL*>";
977 // if a label or a constant
978 if(isa<BasicBlock>(Val)) {
979 cerr << "\t"; printLabel( Op.getVRegValue () );
981 // else it must be a register value
982 const int RegNum = Op.getAllocatedRegNum();
984 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
986 cerr << "(" << Val->getName() << ")";
988 cerr << "(" << Val << ")";
993 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
995 if( LROfVal->hasSpillOffset() )
1000 else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
1001 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1005 cerr << "\t" << Op; // use dump field
1010 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1011 if( NumOfImpRefs > 0) {
1012 cerr << "\tImplicit:";
1014 for(unsigned z=0; z < NumOfImpRefs; z++)
1015 cerr << RAV(MInst->getImplicitRef(z)) << "\t";
1018 } // for all machine instructions
1030 //----------------------------------------------------------------------------
1032 //----------------------------------------------------------------------------
1034 void PhyRegAlloc::colorCallRetArgs()
1037 CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
1038 CallRetInstrListType::const_iterator It = CallRetInstList.begin();
1040 for( ; It != CallRetInstList.end(); ++It ) {
1042 const MachineInstr *const CRMI = *It;
1043 unsigned OpCode = CRMI->getOpCode();
1045 // get the added instructions for this Call/Ret instruciton
1046 AddedInstrns &AI = AddedInstrMap[CRMI];
1048 // Tmp stack positions are needed by some calls that have spilled args
1049 // So reset it before we call each such method
1050 //mcInfo.popAllTempValues(TM);
1053 if (TM.getInstrInfo().isCall(OpCode))
1054 MRI.colorCallArgs(CRMI, LRI, &AI, *this);
1055 else if (TM.getInstrInfo().isReturn(OpCode))
1056 MRI.colorRetValue(CRMI, LRI, &AI);
1058 assert(0 && "Non Call/Ret instrn in CallRetInstrList\n");
1064 //----------------------------------------------------------------------------
1066 //----------------------------------------------------------------------------
1067 void PhyRegAlloc::colorIncomingArgs()
1069 const BasicBlock *const FirstBB = Meth->front();
1070 const MachineInstr *FirstMI = FirstBB->getMachineInstrVec().front();
1071 assert(FirstMI && "No machine instruction in entry BB");
1073 MRI.colorMethodArgs(Meth, LRI, &AddedInstrAtEntry);
1077 //----------------------------------------------------------------------------
1078 // Used to generate a label for a basic block
1079 //----------------------------------------------------------------------------
1080 void PhyRegAlloc::printLabel(const Value *const Val) {
1082 cerr << Val->getName();
1084 cerr << "Label" << Val;
1088 //----------------------------------------------------------------------------
1089 // This method calls setSugColorUsable method of each live range. This
1090 // will determine whether the suggested color of LR is really usable.
1091 // A suggested color is not usable when the suggested color is volatile
1092 // AND when there are call interferences
1093 //----------------------------------------------------------------------------
1095 void PhyRegAlloc::markUnusableSugColors()
1097 if(DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
1099 // hash map iterator
1100 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1101 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1103 for(; HMI != HMIEnd ; ++HMI ) {
1105 LiveRange *L = HMI->second; // get the LiveRange
1107 if(L->hasSuggestedColor()) {
1108 int RCID = L->getRegClass()->getID();
1109 if( MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1110 L->isCallInterference() )
1111 L->setSuggestedColorUsable( false );
1113 L->setSuggestedColorUsable( true );
1115 } // if L->hasSuggestedColor()
1117 } // for all LR's in hash map
1122 //----------------------------------------------------------------------------
1123 // The following method will set the stack offsets of the live ranges that
1124 // are decided to be spillled. This must be called just after coloring the
1125 // LRs using the graph coloring algo. For each live range that is spilled,
1126 // this method allocate a new spill position on the stack.
1127 //----------------------------------------------------------------------------
1129 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1130 if (DEBUG_RA) cerr << "\nsetting LR stack offsets ...\n";
1132 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
1133 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
1135 for( ; HMI != HMIEnd ; ++HMI) {
1136 if (HMI->first && HMI->second) {
1137 LiveRange *L = HMI->second; // get the LiveRange
1138 if (!L->hasColor()) // NOTE: ** allocating the size of long Type **
1139 L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
1141 } // for all LR's in hash map
1146 //----------------------------------------------------------------------------
1147 // The entry pont to Register Allocation
1148 //----------------------------------------------------------------------------
1150 void PhyRegAlloc::allocateRegisters()
1153 // make sure that we put all register classes into the RegClassList
1154 // before we call constructLiveRanges (now done in the constructor of
1155 // PhyRegAlloc class).
1157 LRI.constructLiveRanges(); // create LR info
1160 LRI.printLiveRanges();
1162 createIGNodeListsAndIGs(); // create IGNode list and IGs
1164 buildInterferenceGraphs(); // build IGs in all reg classes
1168 // print all LRs in all reg classes
1169 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1170 RegClassList[ rc ]->printIGNodeList();
1172 // print IGs in all register classes
1173 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1174 RegClassList[ rc ]->printIG();
1178 LRI.coalesceLRs(); // coalesce all live ranges
1182 // print all LRs in all reg classes
1183 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1184 RegClassList[ rc ]->printIGNodeList();
1186 // print IGs in all register classes
1187 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1188 RegClassList[ rc ]->printIG();
1192 // mark un-usable suggested color before graph coloring algorithm.
1193 // When this is done, the graph coloring algo will not reserve
1194 // suggested color unnecessarily - they can be used by another LR
1196 markUnusableSugColors();
1198 // color all register classes using the graph coloring algo
1199 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
1200 RegClassList[ rc ]->colorAllRegs();
1202 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1203 // a poistion for such spilled LRs
1205 allocateStackSpace4SpilledLRs();
1207 mcInfo.popAllTempValues(TM); // TODO **Check
1209 // color incoming args - if the correct color was not received
1210 // insert code to copy to the correct register
1212 colorIncomingArgs();
1214 // Now update the machine code with register names and add any
1215 // additional code inserted by the register allocator to the instruction
1218 updateMachineCode();
1221 MachineCodeForMethod::get(Meth).dump();
1222 printMachineCode(); // only for DEBUGGING