1 //===-- PhyRegAlloc.cpp ---------------------------------------------------===//
3 // Register allocation for LLVM.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/CodeGen/RegisterAllocation.h"
8 #include "llvm/CodeGen/RegAllocCommon.h"
9 #include "llvm/CodeGen/PhyRegAlloc.h"
10 #include "llvm/CodeGen/MachineInstr.h"
11 #include "llvm/CodeGen/MachineInstrAnnot.h"
12 #include "llvm/CodeGen/MachineCodeForBasicBlock.h"
13 #include "llvm/CodeGen/MachineCodeForMethod.h"
14 #include "llvm/Analysis/LiveVar/FunctionLiveVarInfo.h"
15 #include "llvm/Analysis/LoopInfo.h"
16 #include "llvm/Target/TargetMachine.h"
17 #include "llvm/Target/MachineFrameInfo.h"
18 #include "llvm/Function.h"
19 #include "llvm/Type.h"
20 #include "llvm/iOther.h"
21 #include "Support/STLExtras.h"
22 #include "Support/CommandLine.h"
27 RegAllocDebugLevel_t DEBUG_RA;
29 static cl::opt<RegAllocDebugLevel_t, true>
30 DRA_opt("dregalloc", cl::Hidden, cl::location(DEBUG_RA),
31 cl::desc("enable register allocation debugging information"),
33 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
34 clEnumValN(RA_DEBUG_Results, "y", "debug output for allocation results"),
35 clEnumValN(RA_DEBUG_Coloring, "c", "debug output for graph coloring step"),
36 clEnumValN(RA_DEBUG_Interference,"ig","debug output for interference graphs"),
37 clEnumValN(RA_DEBUG_LiveRanges , "lr","debug output for live ranges"),
38 clEnumValN(RA_DEBUG_Verbose, "v", "extra debug output"),
41 //----------------------------------------------------------------------------
42 // RegisterAllocation pass front end...
43 //----------------------------------------------------------------------------
45 class RegisterAllocator : public FunctionPass {
46 TargetMachine &Target;
48 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
50 const char *getPassName() const { return "Register Allocation"; }
52 bool runOnFunction(Function &F) {
54 cerr << "\n********* Function "<< F.getName() << " ***********\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>();
66 AU.addRequired<FunctionLiveVarInfo>();
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 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 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 >= RA_DEBUG_LiveRanges) 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 LIVE RANGE FOUND FOR: "
124 << RAV(HMI->first) << "****\n";
128 // if the Value * is not null, and LR is not yet written to the IGNodeList
129 if (!(L->getUserIGNode()) ) {
130 RegClass *const RC = // RegClass of first value in the LR
131 RegClassList[ L->getRegClass()->getID() ];
132 RC->addLRToIG(L); // add this LR to an IG
138 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
139 RegClassList[rc]->createInterferenceGraph();
141 if (DEBUG_RA >= RA_DEBUG_LiveRanges) cerr << "LRLists Created!\n";
145 //----------------------------------------------------------------------------
146 // This method will add all interferences at for a given instruction.
147 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
148 // class as that of live var. The live var passed to this function is the
149 // LVset AFTER the instruction
150 //----------------------------------------------------------------------------
152 void PhyRegAlloc::addInterference(const Value *Def,
153 const ValueSet *LVSet,
156 ValueSet::const_iterator LIt = LVSet->begin();
158 // get the live range of instruction
160 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
162 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
163 assert( IGNodeOfDef );
165 RegClass *const RCOfDef = LROfDef->getRegClass();
167 // for each live var in live variable set
169 for ( ; LIt != LVSet->end(); ++LIt) {
171 if (DEBUG_RA >= RA_DEBUG_Verbose)
172 cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
174 // get the live range corresponding to live var
176 LiveRange *LROfVar = LRI.getLiveRangeForValue(*LIt);
178 // LROfVar can be null if it is a const since a const
179 // doesn't have a dominating def - see Assumptions above
182 if (LROfDef != LROfVar) // do not set interf for same LR
183 if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
184 RCOfDef->setInterference( LROfDef, LROfVar);
190 //----------------------------------------------------------------------------
191 // For a call instruction, this method sets the CallInterference flag in
192 // the LR of each variable live int the Live Variable Set live after the
193 // call instruction (except the return value of the call instruction - since
194 // the return value does not interfere with that call itself).
195 //----------------------------------------------------------------------------
197 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
198 const ValueSet *LVSetAft) {
200 if (DEBUG_RA >= RA_DEBUG_Interference)
201 cerr << "\n For call inst: " << *MInst;
203 ValueSet::const_iterator LIt = LVSetAft->begin();
205 // for each live var in live variable set after machine inst
207 for ( ; LIt != LVSetAft->end(); ++LIt) {
209 // get the live range corresponding to live var
211 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
213 // LR can be null if it is a const since a const
214 // doesn't have a dominating def - see Assumptions above
217 if (DEBUG_RA >= RA_DEBUG_Interference) {
218 cerr << "\n\tLR after Call: ";
221 LR->setCallInterference();
222 if (DEBUG_RA >= RA_DEBUG_Interference) {
223 cerr << "\n ++After adding call interference for LR: " ;
230 // Now find the LR of the return value of the call
231 // We do this because, we look at the LV set *after* the instruction
232 // to determine, which LRs must be saved across calls. The return value
233 // of the call is live in this set - but it does not interfere with call
234 // (i.e., we can allocate a volatile register to the return value)
236 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
238 if (const Value *RetVal = argDesc->getReturnValue()) {
239 LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
240 assert( RetValLR && "No LR for RetValue of call");
241 RetValLR->clearCallInterference();
244 // If the CALL is an indirect call, find the LR of the function pointer.
245 // That has a call interference because it conflicts with outgoing args.
246 if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
247 LiveRange *AddrValLR = LRI.getLiveRangeForValue( AddrVal );
248 assert( AddrValLR && "No LR for indirect addr val of call");
249 AddrValLR->setCallInterference();
257 //----------------------------------------------------------------------------
258 // This method will walk thru code and create interferences in the IG of
259 // each RegClass. Also, this method calculates the spill cost of each
260 // Live Range (it is done in this method to save another pass over the code).
261 //----------------------------------------------------------------------------
262 void PhyRegAlloc::buildInterferenceGraphs()
265 if (DEBUG_RA >= RA_DEBUG_Interference)
266 cerr << "Creating interference graphs ...\n";
268 unsigned BBLoopDepthCost;
269 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
272 // find the 10^(loop_depth) of this BB
274 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BBI));
276 // get the iterator for machine instructions
278 const MachineCodeForBasicBlock& MIVec = MachineCodeForBasicBlock::get(BBI);
279 MachineCodeForBasicBlock::const_iterator MII = MIVec.begin();
281 // iterate over all the machine instructions in BB
283 for ( ; MII != MIVec.end(); ++MII) {
285 const MachineInstr *MInst = *MII;
287 // get the LV set after the instruction
289 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BBI);
291 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
294 // set the isCallInterference flag of each live range wich extends
295 // accross this call instruction. This information is used by graph
296 // coloring algo to avoid allocating volatile colors to live ranges
297 // that span across calls (since they have to be saved/restored)
299 setCallInterferences(MInst, &LVSetAI);
303 // iterate over all MI operands to find defs
305 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
306 OpE = MInst->end(); OpI != OpE; ++OpI) {
307 if (OpI.isDef()) // create a new LR iff this operand is a def
308 addInterference(*OpI, &LVSetAI, isCallInst);
310 // Calculate the spill cost of each live range
312 LiveRange *LR = LRI.getLiveRangeForValue(*OpI);
313 if (LR) LR->addSpillCost(BBLoopDepthCost);
317 // if there are multiple defs in this instruction e.g. in SETX
319 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
320 addInterf4PseudoInstr(MInst);
323 // Also add interference for any implicit definitions in a machine
324 // instr (currently, only calls have this).
326 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
327 if ( NumOfImpRefs > 0 ) {
328 for (unsigned z=0; z < NumOfImpRefs; z++)
329 if (MInst->implicitRefIsDefined(z) )
330 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
334 } // for all machine instructions in BB
335 } // for all BBs in function
338 // add interferences for function arguments. Since there are no explict
339 // defs in the function for args, we have to add them manually
341 addInterferencesForArgs();
343 if (DEBUG_RA >= RA_DEBUG_Interference)
344 cerr << "Interference graphs calculated!\n";
349 //--------------------------------------------------------------------------
350 // Pseudo instructions will be exapnded to multiple instructions by the
351 // assembler. Consequently, all the opernds must get distinct registers.
352 // Therefore, we mark all operands of a pseudo instruction as they interfere
354 //--------------------------------------------------------------------------
355 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
357 bool setInterf = false;
359 // iterate over MI operands to find defs
361 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
362 ItE = MInst->end(); It1 != ItE; ++It1) {
363 const LiveRange *LROfOp1 = LRI.getLiveRangeForValue(*It1);
364 assert((LROfOp1 || !It1.isDef()) && "No LR for Def in PSEUDO insruction");
366 MachineInstr::const_val_op_iterator It2 = It1;
367 for (++It2; It2 != ItE; ++It2) {
368 const LiveRange *LROfOp2 = LRI.getLiveRangeForValue(*It2);
371 RegClass *RCOfOp1 = LROfOp1->getRegClass();
372 RegClass *RCOfOp2 = LROfOp2->getRegClass();
374 if (RCOfOp1 == RCOfOp2 ){
375 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
379 } // for all other defs in machine instr
380 } // for all operands in an instruction
382 if (!setInterf && MInst->getNumOperands() > 2) {
383 cerr << "\nInterf not set for any operand in pseudo instr:\n";
385 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
391 //----------------------------------------------------------------------------
392 // This method will add interferences for incoming arguments to a function.
393 //----------------------------------------------------------------------------
395 void PhyRegAlloc::addInterferencesForArgs() {
396 // get the InSet of root BB
397 const ValueSet &InSet = LVI->getInSetOfBB(&Meth->front());
399 for (Function::const_aiterator AI=Meth->abegin(); AI != Meth->aend(); ++AI) {
400 // add interferences between args and LVars at start
401 addInterference(AI, &InSet, false);
403 if (DEBUG_RA >= RA_DEBUG_Interference)
404 cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
409 //----------------------------------------------------------------------------
410 // This method is called after register allocation is complete to set the
411 // allocated reisters in the machine code. This code will add register numbers
412 // to MachineOperands that contain a Value. Also it calls target specific
413 // methods to produce caller saving instructions. At the end, it adds all
414 // additional instructions produced by the register allocator to the
415 // instruction stream.
416 //----------------------------------------------------------------------------
418 //-----------------------------
419 // Utility functions used below
420 //-----------------------------
422 PrependInstructions(vector<MachineInstr *> &IBef,
423 MachineCodeForBasicBlock& MIVec,
424 MachineCodeForBasicBlock::iterator& MII,
425 const std::string& msg)
429 MachineInstr* OrigMI = *MII;
430 std::vector<MachineInstr *>::iterator AdIt;
431 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
434 if (OrigMI) cerr << "For MInst:\n " << *OrigMI;
435 cerr << msg << "PREPENDed instr:\n " << **AdIt << "\n";
437 MII = MIVec.insert(MII, *AdIt);
444 AppendInstructions(std::vector<MachineInstr *> &IAft,
445 MachineCodeForBasicBlock& MIVec,
446 MachineCodeForBasicBlock::iterator& MII,
447 const std::string& msg)
451 MachineInstr* OrigMI = *MII;
452 std::vector<MachineInstr *>::iterator AdIt;
453 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
456 if (OrigMI) cerr << "For MInst:\n " << *OrigMI;
457 cerr << msg << "APPENDed instr:\n " << **AdIt << "\n";
459 ++MII; // insert before the next instruction
460 MII = MIVec.insert(MII, *AdIt);
466 void PhyRegAlloc::updateMachineCode()
468 MachineCodeForBasicBlock& MIVec = MachineCodeForBasicBlock::get(&Meth->getEntryNode());
470 // Insert any instructions needed at method entry
471 MachineCodeForBasicBlock::iterator MII = MIVec.begin();
472 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MIVec, MII,
473 "At function entry: \n");
474 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
475 "InstrsAfter should be unnecessary since we are just inserting at "
476 "the function entry point here.");
478 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
481 // iterate over all the machine instructions in BB
482 MachineCodeForBasicBlock &MIVec = MachineCodeForBasicBlock::get(BBI);
483 for (MachineCodeForBasicBlock::iterator MII = MIVec.begin();
484 MII != MIVec.end(); ++MII) {
486 MachineInstr *MInst = *MII;
488 unsigned Opcode = MInst->getOpCode();
490 // do not process Phis
491 if (TM.getInstrInfo().isDummyPhiInstr(Opcode))
494 // Reset tmp stack positions so they can be reused for each machine instr.
495 mcInfo.popAllTempValues(TM);
497 // Now insert speical instructions (if necessary) for call/return
500 if (TM.getInstrInfo().isCall(Opcode) ||
501 TM.getInstrInfo().isReturn(Opcode)) {
503 AddedInstrns &AI = AddedInstrMap[MInst];
505 if (TM.getInstrInfo().isCall(Opcode))
506 MRI.colorCallArgs(MInst, LRI, &AI, *this, BBI);
507 else if (TM.getInstrInfo().isReturn(Opcode))
508 MRI.colorRetValue(MInst, LRI, &AI);
511 // Set the registers for operands in the machine instruction
512 // if a register was successfully allocated. If not, insert
513 // code to spill the register value.
515 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
517 MachineOperand& Op = MInst->getOperand(OpNum);
518 if (Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
519 Op.getOperandType() == MachineOperand::MO_CCRegister)
521 const Value *const Val = Op.getVRegValue();
523 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
524 if (!LR) // consts or labels will have no live range
526 // if register is not allocated, mark register as invalid
527 if (Op.getAllocatedRegNum() == -1)
528 MInst->SetRegForOperand(OpNum, MRI.getInvalidRegNum());
533 MInst->SetRegForOperand(OpNum,
534 MRI.getUnifiedRegNum(LR->getRegClass()->getID(),
537 // LR did NOT receive a color (register). Insert spill code.
538 insertCode4SpilledLR(LR, MInst, BBI, OpNum );
540 } // for each operand
543 // Now add instructions that the register allocator inserts before/after
544 // this machine instructions (done only for calls/rets/incoming args)
545 // We do this here, to ensure that spill for an instruction is inserted
546 // closest as possible to an instruction (see above insertCode4Spill...)
548 // If there are instructions to be added, *before* this machine
549 // instruction, add them now.
551 if (AddedInstrMap.count(MInst)) {
552 PrependInstructions(AddedInstrMap[MInst].InstrnsBefore, MIVec, MII,"");
555 // If there are instructions to be added *after* this machine
556 // instruction, add them now
558 if (!AddedInstrMap[MInst].InstrnsAfter.empty()) {
560 // if there are delay slots for this instruction, the instructions
561 // added after it must really go after the delayed instruction(s)
562 // So, we move the InstrAfter of the current instruction to the
563 // corresponding delayed instruction
566 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
567 move2DelayedInstr(MInst, *(MII+delay) );
570 // Here we can add the "instructions after" to the current
571 // instruction since there are no delay slots for this instruction
572 AppendInstructions(AddedInstrMap[MInst].InstrnsAfter, MIVec, MII,"");
576 } // for each machine instruction
582 //----------------------------------------------------------------------------
583 // This method inserts spill code for AN operand whose LR was spilled.
584 // This method may be called several times for a single machine instruction
585 // if it contains many spilled operands. Each time it is called, it finds
586 // a register which is not live at that instruction and also which is not
587 // used by other spilled operands of the same instruction. Then it uses
588 // this register temporarily to accomodate the spilled value.
589 //----------------------------------------------------------------------------
590 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
592 const BasicBlock *BB,
593 const unsigned OpNum) {
595 assert((! TM.getInstrInfo().isCall(MInst->getOpCode()) || OpNum == 0) &&
596 "Outgoing arg of a call must be handled elsewhere (func arg ok)");
597 assert(! TM.getInstrInfo().isReturn(MInst->getOpCode()) &&
598 "Return value of a ret must be handled elsewhere");
600 MachineOperand& Op = MInst->getOperand(OpNum);
601 bool isDef = MInst->operandIsDefined(OpNum);
602 bool isDefAndUse = MInst->operandIsDefinedAndUsed(OpNum);
603 unsigned RegType = MRI.getRegType( LR );
604 int SpillOff = LR->getSpillOffFromFP();
605 RegClass *RC = LR->getRegClass();
606 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
608 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
610 vector<MachineInstr*> MIBef, MIAft;
611 vector<MachineInstr*> AdIMid;
613 // Choose a register to hold the spilled value. This may insert code
614 // before and after MInst to free up the value. If so, this code should
615 // be first and last in the spill sequence before/after MInst.
616 int TmpRegU = getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef, MIAft);
618 // Set the operand first so that it this register does not get used
619 // as a scratch register for later calls to getUsableUniRegAtMI below
620 MInst->SetRegForOperand(OpNum, TmpRegU);
622 // get the added instructions for this instruction
623 AddedInstrns &AI = AddedInstrMap[MInst];
625 // We may need a scratch register to copy the spilled value to/from memory.
626 // This may itself have to insert code to free up a scratch register.
627 // Any such code should go before (after) the spill code for a load (store).
628 int scratchRegType = -1;
630 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
632 scratchReg = this->getUsableUniRegAtMI(scratchRegType, &LVSetBef,
633 MInst, MIBef, MIAft);
634 assert(scratchReg != MRI.getInvalidRegNum());
635 MInst->getRegsUsed().insert(scratchReg);
638 if (!isDef || isDefAndUse) {
639 // for a USE, we have to load the value of LR from stack to a TmpReg
640 // and use the TmpReg as one operand of instruction
642 // actual loading instruction(s)
643 MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU, RegType,
646 // the actual load should be after the instructions to free up TmpRegU
647 MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
651 if (isDef) { // if this is a Def
652 // for a DEF, we have to store the value produced by this instruction
653 // on the stack position allocated for this LR
655 // actual storing instruction(s)
656 MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff, RegType,
659 MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
662 // Finally, insert the entire spill code sequences before/after MInst
663 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
664 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
667 cerr << "\nFor Inst:\n " << *MInst;
668 cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
669 cerr << "; added Instructions:";
670 for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
671 for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
676 //----------------------------------------------------------------------------
677 // We can use the following method to get a temporary register to be used
678 // BEFORE any given machine instruction. If there is a register available,
679 // this method will simply return that register and set MIBef = MIAft = NULL.
680 // Otherwise, it will return a register and MIAft and MIBef will contain
681 // two instructions used to free up this returned register.
682 // Returned register number is the UNIFIED register number
683 //----------------------------------------------------------------------------
685 int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
686 const ValueSet *LVSetBef,
688 std::vector<MachineInstr*>& MIBef,
689 std::vector<MachineInstr*>& MIAft) {
691 RegClass* RC = this->getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
693 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
696 // we couldn't find an unused register. Generate code to free up a reg by
697 // saving it on stack and restoring after the instruction
699 int TmpOff = mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
701 RegU = getUniRegNotUsedByThisInst(RC, MInst);
703 // Check if we need a scratch register to copy this register to memory.
704 int scratchRegType = -1;
705 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
707 int scratchReg = this->getUsableUniRegAtMI(scratchRegType, LVSetBef,
708 MInst, MIBef, MIAft);
709 assert(scratchReg != MRI.getInvalidRegNum());
711 // We may as well hold the value in the scratch register instead
712 // of copying it to memory and back. But we have to mark the
713 // register as used by this instruction, so it does not get used
714 // as a scratch reg. by another operand or anyone else.
715 MInst->getRegsUsed().insert(scratchReg);
716 MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
717 MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
720 { // the register can be copied directly to/from memory so do it.
721 MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
722 MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
729 //----------------------------------------------------------------------------
730 // This method is called to get a new unused register that can be used to
731 // accomodate a spilled value.
732 // This method may be called several times for a single machine instruction
733 // if it contains many spilled operands. Each time it is called, it finds
734 // a register which is not live at that instruction and also which is not
735 // used by other spilled operands of the same instruction.
736 // Return register number is relative to the register class. NOT
738 //----------------------------------------------------------------------------
739 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
740 const MachineInstr *MInst,
741 const ValueSet *LVSetBef) {
743 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
745 std::vector<bool> &IsColorUsedArr = RC->getIsColorUsedArr();
747 for (unsigned i=0; i < NumAvailRegs; i++) // Reset array
748 IsColorUsedArr[i] = false;
750 ValueSet::const_iterator LIt = LVSetBef->begin();
752 // for each live var in live variable set after machine inst
753 for ( ; LIt != LVSetBef->end(); ++LIt) {
755 // get the live range corresponding to live var
756 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
758 // LR can be null if it is a const since a const
759 // doesn't have a dominating def - see Assumptions above
760 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor() )
761 IsColorUsedArr[ LRofLV->getColor() ] = true;
764 // It is possible that one operand of this MInst was already spilled
765 // and it received some register temporarily. If that's the case,
766 // it is recorded in machine operand. We must skip such registers.
768 setRelRegsUsedByThisInst(RC, MInst);
770 for (unsigned c=0; c < NumAvailRegs; c++) // find first unused color
771 if (!IsColorUsedArr[c])
772 return MRI.getUnifiedRegNum(RC->getID(), c);
778 //----------------------------------------------------------------------------
779 // Get any other register in a register class, other than what is used
780 // by operands of a machine instruction. Returns the unified reg number.
781 //----------------------------------------------------------------------------
782 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
783 const MachineInstr *MInst) {
785 vector<bool> &IsColorUsedArr = RC->getIsColorUsedArr();
786 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
788 for (unsigned i=0; i < NumAvailRegs ; i++) // Reset array
789 IsColorUsedArr[i] = false;
791 setRelRegsUsedByThisInst(RC, MInst);
793 for (unsigned c=0; c < RC->getNumOfAvailRegs(); c++)// find first unused color
794 if (!IsColorUsedArr[c])
795 return MRI.getUnifiedRegNum(RC->getID(), c);
797 assert(0 && "FATAL: No free register could be found in reg class!!");
802 //----------------------------------------------------------------------------
803 // This method modifies the IsColorUsedArr of the register class passed to it.
804 // It sets the bits corresponding to the registers used by this machine
805 // instructions. Both explicit and implicit operands are set.
806 //----------------------------------------------------------------------------
807 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
808 const MachineInstr *MInst ) {
810 vector<bool> &IsColorUsedArr = RC->getIsColorUsedArr();
812 // Add the registers already marked as used by the instruction.
813 // This should include any scratch registers that are used to save
814 // values across the instruction (e.g., for saving state register values).
815 const hash_set<int>& regsUsed = MInst->getRegsUsed();
816 for (hash_set<int>::const_iterator SI=regsUsed.begin(), SE=regsUsed.end();
819 unsigned classId = 0;
820 int classRegNum = MRI.getClassRegNum(*SI, classId);
821 if (RC->getID() == classId)
823 assert(classRegNum < (int) IsColorUsedArr.size() &&
824 "Illegal register number for this reg class?");
825 IsColorUsedArr[classRegNum] = true;
829 // Now add registers allocated to the live ranges of values used in
830 // the instruction. These are not yet recorded in the instruction.
831 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
833 const MachineOperand& Op = MInst->getOperand(OpNum);
835 if (Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
836 Op.getOperandType() == MachineOperand::MO_CCRegister)
837 if (const Value* Val = Op.getVRegValue())
838 if (MRI.getRegClassIDOfValue(Val) == RC->getID())
839 if (Op.getAllocatedRegNum() == -1)
840 if (LiveRange *LROfVal = LRI.getLiveRangeForValue(Val))
841 if (LROfVal->hasColor() )
842 // this operand is in a LR that received a color
843 IsColorUsedArr[LROfVal->getColor()] = true;
846 // If there are implicit references, mark their allocated regs as well
848 for (unsigned z=0; z < MInst->getNumImplicitRefs(); z++)
850 LRofImpRef = LRI.getLiveRangeForValue(MInst->getImplicitRef(z)))
851 if (LRofImpRef->hasColor())
852 // this implicit reference is in a LR that received a color
853 IsColorUsedArr[LRofImpRef->getColor()] = true;
857 //----------------------------------------------------------------------------
858 // If there are delay slots for an instruction, the instructions
859 // added after it must really go after the delayed instruction(s).
860 // So, we move the InstrAfter of that instruction to the
861 // corresponding delayed instruction using the following method.
863 //----------------------------------------------------------------------------
864 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
865 const MachineInstr *DelayedMI) {
867 // "added after" instructions of the original instr
868 std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
870 // "added instructions" of the delayed instr
871 AddedInstrns &DelayAdI = AddedInstrMap[DelayedMI];
873 // "added after" instructions of the delayed instr
874 std::vector<MachineInstr *> &DelayedAft = DelayAdI.InstrnsAfter;
876 // go thru all the "added after instructions" of the original instruction
877 // and append them to the "addded after instructions" of the delayed
879 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
881 // empty the "added after instructions" of the original instruction
885 //----------------------------------------------------------------------------
886 // This method prints the code with registers after register allocation is
888 //----------------------------------------------------------------------------
889 void PhyRegAlloc::printMachineCode()
892 cerr << "\n;************** Function " << Meth->getName()
893 << " *****************\n";
895 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
897 cerr << "\n"; printLabel(BBI); cerr << ": ";
899 // get the iterator for machine instructions
900 MachineCodeForBasicBlock& MIVec = MachineCodeForBasicBlock::get(BBI);
901 MachineCodeForBasicBlock::iterator MII = MIVec.begin();
903 // iterate over all the machine instructions in BB
904 for ( ; MII != MIVec.end(); ++MII) {
905 MachineInstr *const MInst = *MII;
908 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
910 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
911 MachineOperand& Op = MInst->getOperand(OpNum);
913 if (Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
914 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
915 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
917 const Value *const Val = Op.getVRegValue () ;
918 // ****this code is temporary till NULL Values are fixed
920 cerr << "\t<*NULL*>";
924 // if a label or a constant
925 if (isa<BasicBlock>(Val)) {
926 cerr << "\t"; printLabel( Op.getVRegValue () );
928 // else it must be a register value
929 const int RegNum = Op.getAllocatedRegNum();
931 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
933 cerr << "(" << Val->getName() << ")";
935 cerr << "(" << Val << ")";
940 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
942 if (LROfVal->hasSpillOffset() )
947 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
948 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
952 cerr << "\t" << Op; // use dump field
957 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
958 if (NumOfImpRefs > 0) {
959 cerr << "\tImplicit:";
961 for (unsigned z=0; z < NumOfImpRefs; z++)
962 cerr << RAV(MInst->getImplicitRef(z)) << "\t";
965 } // for all machine instructions
975 //----------------------------------------------------------------------------
977 //----------------------------------------------------------------------------
978 void PhyRegAlloc::colorIncomingArgs()
980 const BasicBlock &FirstBB = Meth->front();
981 const MachineInstr *FirstMI = MachineCodeForBasicBlock::get(&FirstBB).front();
982 assert(FirstMI && "No machine instruction in entry BB");
984 MRI.colorMethodArgs(Meth, LRI, &AddedInstrAtEntry);
988 //----------------------------------------------------------------------------
989 // Used to generate a label for a basic block
990 //----------------------------------------------------------------------------
991 void PhyRegAlloc::printLabel(const Value *const Val) {
993 cerr << Val->getName();
995 cerr << "Label" << Val;
999 //----------------------------------------------------------------------------
1000 // This method calls setSugColorUsable method of each live range. This
1001 // will determine whether the suggested color of LR is really usable.
1002 // A suggested color is not usable when the suggested color is volatile
1003 // AND when there are call interferences
1004 //----------------------------------------------------------------------------
1006 void PhyRegAlloc::markUnusableSugColors()
1008 // hash map iterator
1009 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1010 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1012 for (; HMI != HMIEnd ; ++HMI ) {
1014 LiveRange *L = HMI->second; // get the LiveRange
1016 if (L->hasSuggestedColor()) {
1017 int RCID = L->getRegClass()->getID();
1018 if (MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1019 L->isCallInterference() )
1020 L->setSuggestedColorUsable( false );
1022 L->setSuggestedColorUsable( true );
1024 } // if L->hasSuggestedColor()
1026 } // for all LR's in hash map
1031 //----------------------------------------------------------------------------
1032 // The following method will set the stack offsets of the live ranges that
1033 // are decided to be spillled. This must be called just after coloring the
1034 // LRs using the graph coloring algo. For each live range that is spilled,
1035 // this method allocate a new spill position on the stack.
1036 //----------------------------------------------------------------------------
1038 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1039 if (DEBUG_RA) cerr << "\nSetting LR stack offsets for spills...\n";
1041 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
1042 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
1044 for ( ; HMI != HMIEnd ; ++HMI) {
1045 if (HMI->first && HMI->second) {
1046 LiveRange *L = HMI->second; // get the LiveRange
1047 if (!L->hasColor()) { // NOTE: ** allocating the size of long Type **
1048 int stackOffset = mcInfo.allocateSpilledValue(TM, Type::LongTy);
1049 L->setSpillOffFromFP(stackOffset);
1051 cerr << " LR# " << L->getUserIGNode()->getIndex()
1052 << ": stack-offset = " << stackOffset << "\n";
1055 } // for all LR's in hash map
1060 //----------------------------------------------------------------------------
1061 // The entry pont to Register Allocation
1062 //----------------------------------------------------------------------------
1064 void PhyRegAlloc::allocateRegisters()
1067 // make sure that we put all register classes into the RegClassList
1068 // before we call constructLiveRanges (now done in the constructor of
1069 // PhyRegAlloc class).
1071 LRI.constructLiveRanges(); // create LR info
1073 if (DEBUG_RA >= RA_DEBUG_LiveRanges)
1074 LRI.printLiveRanges();
1076 createIGNodeListsAndIGs(); // create IGNode list and IGs
1078 buildInterferenceGraphs(); // build IGs in all reg classes
1081 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1082 // print all LRs in all reg classes
1083 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1084 RegClassList[rc]->printIGNodeList();
1086 // print IGs in all register classes
1087 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1088 RegClassList[rc]->printIG();
1092 LRI.coalesceLRs(); // coalesce all live ranges
1095 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1096 // print all LRs in all reg classes
1097 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1098 RegClassList[ rc ]->printIGNodeList();
1100 // print IGs in all register classes
1101 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1102 RegClassList[ rc ]->printIG();
1106 // mark un-usable suggested color before graph coloring algorithm.
1107 // When this is done, the graph coloring algo will not reserve
1108 // suggested color unnecessarily - they can be used by another LR
1110 markUnusableSugColors();
1112 // color all register classes using the graph coloring algo
1113 for (unsigned rc=0; rc < NumOfRegClasses ; rc++)
1114 RegClassList[ rc ]->colorAllRegs();
1116 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1117 // a poistion for such spilled LRs
1119 allocateStackSpace4SpilledLRs();
1121 mcInfo.popAllTempValues(TM); // TODO **Check
1123 // color incoming args - if the correct color was not received
1124 // insert code to copy to the correct register
1126 colorIncomingArgs();
1128 // Now update the machine code with register names and add any
1129 // additional code inserted by the register allocator to the instruction
1132 updateMachineCode();
1135 cerr << "\n**** Machine Code After Register Allocation:\n\n";
1136 MachineCodeForMethod::get(Meth).dump();