1 //===-- PhyRegAlloc.cpp ---------------------------------------------------===//
3 // Register allocation for LLVM.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/CodeGen/RegisterAllocation.h"
8 #include "llvm/CodeGen/PhyRegAlloc.h"
9 #include "llvm/CodeGen/MachineInstr.h"
10 #include "llvm/CodeGen/MachineInstrAnnot.h"
11 #include "llvm/CodeGen/MachineCodeForBasicBlock.h"
12 #include "llvm/CodeGen/MachineCodeForMethod.h"
13 #include "llvm/Analysis/LiveVar/FunctionLiveVarInfo.h"
14 #include "llvm/Analysis/LoopInfo.h"
15 #include "llvm/Target/TargetMachine.h"
16 #include "llvm/Target/MachineFrameInfo.h"
17 #include "llvm/Function.h"
18 #include "llvm/Type.h"
19 #include "llvm/iOther.h"
20 #include "llvm/CodeGen/RegAllocCommon.h"
21 #include "Support/CommandLine.h"
22 #include "Support/STLExtras.h"
27 RegAllocDebugLevel_t DEBUG_RA;
28 static cl::opt<RegAllocDebugLevel_t, true>
29 DRA_opt("dregalloc", cl::Hidden, cl::location(DEBUG_RA),
30 cl::desc("enable register allocation debugging information"),
32 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
33 clEnumValN(RA_DEBUG_Normal , "y", "enable debug output"),
34 clEnumValN(RA_DEBUG_Verbose, "v", "enable extra debug output"),
38 //----------------------------------------------------------------------------
39 // RegisterAllocation pass front end...
40 //----------------------------------------------------------------------------
42 class RegisterAllocator : public FunctionPass {
43 TargetMachine &Target;
45 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
47 const char *getPassName() const { return "Register Allocation"; }
49 bool runOnFunction(Function &F) {
51 cerr << "\n********* Function "<< F.getName() << " ***********\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>();
63 AU.addRequired<FunctionLiveVarInfo>();
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 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 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 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) {
172 if (DEBUG_RA >= RA_DEBUG_Verbose)
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 >= RA_DEBUG_Verbose) {
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 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
250 if (const Value *RetVal = argDesc->getReturnValue()) {
251 LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
252 assert( RetValLR && "No LR for RetValue of call");
253 RetValLR->clearCallInterference();
256 // If the CALL is an indirect call, find the LR of the function pointer.
257 // That has a call interference because it conflicts with outgoing args.
258 if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
259 LiveRange *AddrValLR = LRI.getLiveRangeForValue( AddrVal );
260 assert( AddrValLR && "No LR for indirect addr val of call");
261 AddrValLR->setCallInterference();
269 //----------------------------------------------------------------------------
270 // This method will walk thru code and create interferences in the IG of
271 // each RegClass. Also, this method calculates the spill cost of each
272 // Live Range (it is done in this method to save another pass over the code).
273 //----------------------------------------------------------------------------
274 void PhyRegAlloc::buildInterferenceGraphs()
277 if (DEBUG_RA) cerr << "Creating interference graphs ...\n";
279 unsigned BBLoopDepthCost;
280 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
283 // find the 10^(loop_depth) of this BB
285 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BBI));
287 // get the iterator for machine instructions
289 const MachineCodeForBasicBlock& MIVec = MachineCodeForBasicBlock::get(BBI);
290 MachineCodeForBasicBlock::const_iterator MII = MIVec.begin();
292 // iterate over all the machine instructions in BB
294 for ( ; MII != MIVec.end(); ++MII) {
296 const MachineInstr *MInst = *MII;
298 // get the LV set after the instruction
300 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BBI);
302 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
305 // set the isCallInterference flag of each live range wich extends
306 // accross this call instruction. This information is used by graph
307 // coloring algo to avoid allocating volatile colors to live ranges
308 // that span across calls (since they have to be saved/restored)
310 setCallInterferences(MInst, &LVSetAI);
314 // iterate over all MI operands to find defs
316 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
317 OpE = MInst->end(); OpI != OpE; ++OpI) {
318 if (OpI.isDef()) // create a new LR iff this operand is a def
319 addInterference(*OpI, &LVSetAI, isCallInst);
321 // Calculate the spill cost of each live range
323 LiveRange *LR = LRI.getLiveRangeForValue(*OpI);
324 if (LR) LR->addSpillCost(BBLoopDepthCost);
328 // if there are multiple defs in this instruction e.g. in SETX
330 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
331 addInterf4PseudoInstr(MInst);
334 // Also add interference for any implicit definitions in a machine
335 // instr (currently, only calls have this).
337 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
338 if ( NumOfImpRefs > 0 ) {
339 for (unsigned z=0; z < NumOfImpRefs; z++)
340 if (MInst->implicitRefIsDefined(z) )
341 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
345 } // for all machine instructions in BB
346 } // for all BBs in function
349 // add interferences for function arguments. Since there are no explict
350 // defs in the function for args, we have to add them manually
352 addInterferencesForArgs();
355 cerr << "Interference graphs calculted!\n";
361 //--------------------------------------------------------------------------
362 // Pseudo instructions will be exapnded to multiple instructions by the
363 // assembler. Consequently, all the opernds must get distinct registers.
364 // Therefore, we mark all operands of a pseudo instruction as they interfere
366 //--------------------------------------------------------------------------
367 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
369 bool setInterf = false;
371 // iterate over MI operands to find defs
373 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
374 ItE = MInst->end(); It1 != ItE; ++It1) {
375 const LiveRange *LROfOp1 = LRI.getLiveRangeForValue(*It1);
376 assert((LROfOp1 || !It1.isDef()) && "No LR for Def in PSEUDO insruction");
378 MachineInstr::const_val_op_iterator It2 = It1;
379 for (++It2; It2 != ItE; ++It2) {
380 const LiveRange *LROfOp2 = LRI.getLiveRangeForValue(*It2);
383 RegClass *RCOfOp1 = LROfOp1->getRegClass();
384 RegClass *RCOfOp2 = LROfOp2->getRegClass();
386 if (RCOfOp1 == RCOfOp2 ){
387 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
391 } // for all other defs in machine instr
392 } // for all operands in an instruction
394 if (!setInterf && MInst->getNumOperands() > 2) {
395 cerr << "\nInterf not set for any operand in pseudo instr:\n";
397 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
403 //----------------------------------------------------------------------------
404 // This method will add interferences for incoming arguments to a function.
405 //----------------------------------------------------------------------------
406 void PhyRegAlloc::addInterferencesForArgs() {
407 // get the InSet of root BB
408 const ValueSet &InSet = LVI->getInSetOfBB(&Meth->front());
410 for (Function::const_aiterator AI = Meth->abegin(); AI != Meth->aend(); ++AI) {
411 // add interferences between args and LVars at start
412 addInterference(AI, &InSet, false);
414 if (DEBUG_RA >= RA_DEBUG_Verbose)
415 cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
420 //----------------------------------------------------------------------------
421 // This method is called after register allocation is complete to set the
422 // allocated reisters in the machine code. This code will add register numbers
423 // to MachineOperands that contain a Value. Also it calls target specific
424 // methods to produce caller saving instructions. At the end, it adds all
425 // additional instructions produced by the register allocator to the
426 // instruction stream.
427 //----------------------------------------------------------------------------
429 //-----------------------------
430 // Utility functions used below
431 //-----------------------------
433 PrependInstructions(vector<MachineInstr *> &IBef,
434 MachineCodeForBasicBlock& MIVec,
435 MachineCodeForBasicBlock::iterator& MII,
436 const std::string& msg)
440 MachineInstr* OrigMI = *MII;
441 std::vector<MachineInstr *>::iterator AdIt;
442 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
445 if (OrigMI) cerr << "For MInst: " << *OrigMI;
446 cerr << msg << " PREPENDed instr: " << **AdIt << "\n";
448 MII = MIVec.insert(MII, *AdIt);
455 AppendInstructions(std::vector<MachineInstr *> &IAft,
456 MachineCodeForBasicBlock& MIVec,
457 MachineCodeForBasicBlock::iterator& MII,
458 const std::string& msg)
462 MachineInstr* OrigMI = *MII;
463 std::vector<MachineInstr *>::iterator AdIt;
464 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
467 if (OrigMI) cerr << "For MInst: " << *OrigMI;
468 cerr << msg << " APPENDed instr: " << **AdIt << "\n";
470 ++MII; // insert before the next instruction
471 MII = MIVec.insert(MII, *AdIt);
477 void PhyRegAlloc::updateMachineCode()
479 MachineCodeForBasicBlock& MIVec = MachineCodeForBasicBlock::get(&Meth->getEntryNode());
481 // Insert any instructions needed at method entry
482 MachineCodeForBasicBlock::iterator MII = MIVec.begin();
483 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MIVec, MII,
484 "At function entry: \n");
485 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
486 "InstrsAfter should be unnecessary since we are just inserting at "
487 "the function entry point here.");
489 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
492 // iterate over all the machine instructions in BB
493 MachineCodeForBasicBlock &MIVec = MachineCodeForBasicBlock::get(BBI);
494 for (MachineCodeForBasicBlock::iterator MII = MIVec.begin();
495 MII != MIVec.end(); ++MII) {
497 MachineInstr *MInst = *MII;
499 unsigned Opcode = MInst->getOpCode();
501 // do not process Phis
502 if (TM.getInstrInfo().isDummyPhiInstr(Opcode))
505 // Reset tmp stack positions so they can be reused for each machine instr.
506 mcInfo.popAllTempValues(TM);
508 // Now insert speical instructions (if necessary) for call/return
511 if (TM.getInstrInfo().isCall(Opcode) ||
512 TM.getInstrInfo().isReturn(Opcode)) {
514 AddedInstrns &AI = AddedInstrMap[MInst];
516 if (TM.getInstrInfo().isCall(Opcode))
517 MRI.colorCallArgs(MInst, LRI, &AI, *this, BBI);
518 else if (TM.getInstrInfo().isReturn(Opcode))
519 MRI.colorRetValue(MInst, LRI, &AI);
522 // Set the registers for operands in the machine instruction
523 // if a register was successfully allocated. If not, insert
524 // code to spill the register value.
526 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
528 MachineOperand& Op = MInst->getOperand(OpNum);
529 if (Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
530 Op.getOperandType() == MachineOperand::MO_CCRegister)
532 const Value *const Val = Op.getVRegValue();
534 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
535 if (!LR) // consts or labels will have no live range
537 // if register is not allocated, mark register as invalid
538 if (Op.getAllocatedRegNum() == -1)
539 MInst->SetRegForOperand(OpNum, MRI.getInvalidRegNum());
544 MInst->SetRegForOperand(OpNum,
545 MRI.getUnifiedRegNum(LR->getRegClass()->getID(),
548 // LR did NOT receive a color (register). Insert spill code.
549 insertCode4SpilledLR(LR, MInst, BBI, OpNum );
551 } // for each operand
554 // Now add instructions that the register allocator inserts before/after
555 // this machine instructions (done only for calls/rets/incoming args)
556 // We do this here, to ensure that spill for an instruction is inserted
557 // closest as possible to an instruction (see above insertCode4Spill...)
559 // If there are instructions to be added, *before* this machine
560 // instruction, add them now.
562 if (AddedInstrMap.count(MInst)) {
563 PrependInstructions(AddedInstrMap[MInst].InstrnsBefore, MIVec, MII,"");
566 // If there are instructions to be added *after* this machine
567 // instruction, add them now
569 if (!AddedInstrMap[MInst].InstrnsAfter.empty()) {
571 // if there are delay slots for this instruction, the instructions
572 // added after it must really go after the delayed instruction(s)
573 // So, we move the InstrAfter of the current instruction to the
574 // corresponding delayed instruction
577 if ((delay=TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) >0){
578 move2DelayedInstr(MInst, *(MII+delay) );
581 // Here we can add the "instructions after" to the current
582 // instruction since there are no delay slots for this instruction
583 AppendInstructions(AddedInstrMap[MInst].InstrnsAfter, MIVec, MII,"");
587 } // for each machine instruction
593 //----------------------------------------------------------------------------
594 // This method inserts spill code for AN operand whose LR was spilled.
595 // This method may be called several times for a single machine instruction
596 // if it contains many spilled operands. Each time it is called, it finds
597 // a register which is not live at that instruction and also which is not
598 // used by other spilled operands of the same instruction. Then it uses
599 // this register temporarily to accomodate the spilled value.
600 //----------------------------------------------------------------------------
601 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
603 const BasicBlock *BB,
604 const unsigned OpNum) {
606 assert(! TM.getInstrInfo().isCall(MInst->getOpCode()) &&
607 (! TM.getInstrInfo().isReturn(MInst->getOpCode())) &&
608 "Arg of a call/ret must be handled elsewhere");
610 MachineOperand& Op = MInst->getOperand(OpNum);
611 bool isDef = MInst->operandIsDefined(OpNum);
612 bool isDefAndUse = MInst->operandIsDefinedAndUsed(OpNum);
613 unsigned RegType = MRI.getRegType( LR );
614 int SpillOff = LR->getSpillOffFromFP();
615 RegClass *RC = LR->getRegClass();
616 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
618 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
620 vector<MachineInstr*> MIBef, MIAft;
621 vector<MachineInstr*> AdIMid;
623 // Choose a register to hold the spilled value. This may insert code
624 // before and after MInst to free up the value. If so, this code should
625 // be first and last in the spill sequence before/after MInst.
626 int TmpRegU = getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef, MIAft);
628 // Set the operand first so that it this register does not get used
629 // as a scratch register for later calls to getUsableUniRegAtMI below
630 MInst->SetRegForOperand(OpNum, TmpRegU);
632 // get the added instructions for this instruction
633 AddedInstrns &AI = AddedInstrMap[MInst];
635 // We may need a scratch register to copy the spilled value to/from memory.
636 // This may itself have to insert code to free up a scratch register.
637 // Any such code should go before (after) the spill code for a load (store).
638 int scratchRegType = -1;
640 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
642 scratchReg = this->getUsableUniRegAtMI(scratchRegType, &LVSetBef,
643 MInst, MIBef, MIAft);
644 assert(scratchReg != MRI.getInvalidRegNum());
645 MInst->getRegsUsed().insert(scratchReg);
648 if (!isDef || isDefAndUse) {
649 // for a USE, we have to load the value of LR from stack to a TmpReg
650 // and use the TmpReg as one operand of instruction
652 // actual loading instruction(s)
653 MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU, RegType,
656 // the actual load should be after the instructions to free up TmpRegU
657 MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
661 if (isDef) { // if this is a Def
662 // for a DEF, we have to store the value produced by this instruction
663 // on the stack position allocated for this LR
665 // actual storing instruction(s)
666 MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff, RegType,
669 MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
672 // Finally, insert the entire spill code sequences before/after MInst
673 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
674 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
677 cerr << "\nFor Inst " << *MInst;
678 cerr << " - SPILLED LR: "; printSet(*LR);
679 cerr << "\n - Added Instructions:";
680 for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
681 for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
686 //----------------------------------------------------------------------------
687 // We can use the following method to get a temporary register to be used
688 // BEFORE any given machine instruction. If there is a register available,
689 // this method will simply return that register and set MIBef = MIAft = NULL.
690 // Otherwise, it will return a register and MIAft and MIBef will contain
691 // two instructions used to free up this returned register.
692 // Returned register number is the UNIFIED register number
693 //----------------------------------------------------------------------------
695 int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
696 const ValueSet *LVSetBef,
698 std::vector<MachineInstr*>& MIBef,
699 std::vector<MachineInstr*>& MIAft) {
701 RegClass* RC = this->getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
703 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
706 // we couldn't find an unused register. Generate code to free up a reg by
707 // saving it on stack and restoring after the instruction
709 int TmpOff = mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
711 RegU = getUniRegNotUsedByThisInst(RC, MInst);
713 // Check if we need a scratch register to copy this register to memory.
714 int scratchRegType = -1;
715 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
717 int scratchReg = this->getUsableUniRegAtMI(scratchRegType, LVSetBef,
718 MInst, MIBef, MIAft);
719 assert(scratchReg != MRI.getInvalidRegNum());
721 // We may as well hold the value in the scratch register instead
722 // of copying it to memory and back. But we have to mark the
723 // register as used by this instruction, so it does not get used
724 // as a scratch reg. by another operand or anyone else.
725 MInst->getRegsUsed().insert(scratchReg);
726 MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
727 MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
730 { // the register can be copied directly to/from memory so do it.
731 MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
732 MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
739 //----------------------------------------------------------------------------
740 // This method is called to get a new unused register that can be used to
741 // accomodate a spilled value.
742 // This method may be called several times for a single machine instruction
743 // if it contains many spilled operands. Each time it is called, it finds
744 // a register which is not live at that instruction and also which is not
745 // used by other spilled operands of the same instruction.
746 // Return register number is relative to the register class. NOT
748 //----------------------------------------------------------------------------
749 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
750 const MachineInstr *MInst,
751 const ValueSet *LVSetBef) {
753 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
755 std::vector<bool> &IsColorUsedArr = RC->getIsColorUsedArr();
757 for (unsigned i=0; i < NumAvailRegs; i++) // Reset array
758 IsColorUsedArr[i] = false;
760 ValueSet::const_iterator LIt = LVSetBef->begin();
762 // for each live var in live variable set after machine inst
763 for ( ; LIt != LVSetBef->end(); ++LIt) {
765 // get the live range corresponding to live var
766 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
768 // LR can be null if it is a const since a const
769 // doesn't have a dominating def - see Assumptions above
770 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor() )
771 IsColorUsedArr[ LRofLV->getColor() ] = true;
774 // It is possible that one operand of this MInst was already spilled
775 // and it received some register temporarily. If that's the case,
776 // it is recorded in machine operand. We must skip such registers.
778 setRelRegsUsedByThisInst(RC, MInst);
780 for (unsigned c=0; c < NumAvailRegs; c++) // find first unused color
781 if (!IsColorUsedArr[c])
782 return MRI.getUnifiedRegNum(RC->getID(), c);
788 //----------------------------------------------------------------------------
789 // Get any other register in a register class, other than what is used
790 // by operands of a machine instruction. Returns the unified reg number.
791 //----------------------------------------------------------------------------
792 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
793 const MachineInstr *MInst) {
795 vector<bool> &IsColorUsedArr = RC->getIsColorUsedArr();
796 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
798 for (unsigned i=0; i < NumAvailRegs ; i++) // Reset array
799 IsColorUsedArr[i] = false;
801 setRelRegsUsedByThisInst(RC, MInst);
803 for (unsigned c=0; c < RC->getNumOfAvailRegs(); c++)// find first unused color
804 if (!IsColorUsedArr[c])
805 return MRI.getUnifiedRegNum(RC->getID(), c);
807 assert(0 && "FATAL: No free register could be found in reg class!!");
812 //----------------------------------------------------------------------------
813 // This method modifies the IsColorUsedArr of the register class passed to it.
814 // It sets the bits corresponding to the registers used by this machine
815 // instructions. Both explicit and implicit operands are set.
816 //----------------------------------------------------------------------------
817 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
818 const MachineInstr *MInst ) {
820 vector<bool> &IsColorUsedArr = RC->getIsColorUsedArr();
822 // Add the registers already marked as used by the instruction.
823 // This should include any scratch registers that are used to save
824 // values across the instruction (e.g., for saving state register values).
825 const hash_set<int>& regsUsed = MInst->getRegsUsed();
826 for (hash_set<int>::const_iterator SI=regsUsed.begin(), SE=regsUsed.end();
829 unsigned classId = 0;
830 int classRegNum = MRI.getClassRegNum(*SI, classId);
831 if (RC->getID() == classId)
833 assert(classRegNum < (int) IsColorUsedArr.size() &&
834 "Illegal register number for this reg class?");
835 IsColorUsedArr[classRegNum] = true;
839 // Now add registers allocated to the live ranges of values used in
840 // the instruction. These are not yet recorded in the instruction.
841 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
843 const MachineOperand& Op = MInst->getOperand(OpNum);
845 if (Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
846 Op.getOperandType() == MachineOperand::MO_CCRegister)
847 if (const Value* Val = Op.getVRegValue())
848 if (MRI.getRegClassIDOfValue(Val) == RC->getID())
849 if (Op.getAllocatedRegNum() == -1)
850 if (LiveRange *LROfVal = LRI.getLiveRangeForValue(Val))
851 if (LROfVal->hasColor() )
852 // this operand is in a LR that received a color
853 IsColorUsedArr[LROfVal->getColor()] = true;
856 // If there are implicit references, mark their allocated regs as well
858 for (unsigned z=0; z < MInst->getNumImplicitRefs(); z++)
860 LRofImpRef = LRI.getLiveRangeForValue(MInst->getImplicitRef(z)))
861 if (LRofImpRef->hasColor())
862 // this implicit reference is in a LR that received a color
863 IsColorUsedArr[LRofImpRef->getColor()] = true;
867 //----------------------------------------------------------------------------
868 // If there are delay slots for an instruction, the instructions
869 // added after it must really go after the delayed instruction(s).
870 // So, we move the InstrAfter of that instruction to the
871 // corresponding delayed instruction using the following method.
873 //----------------------------------------------------------------------------
874 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
875 const MachineInstr *DelayedMI) {
877 // "added after" instructions of the original instr
878 std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
880 // "added instructions" of the delayed instr
881 AddedInstrns &DelayAdI = AddedInstrMap[DelayedMI];
883 // "added after" instructions of the delayed instr
884 std::vector<MachineInstr *> &DelayedAft = DelayAdI.InstrnsAfter;
886 // go thru all the "added after instructions" of the original instruction
887 // and append them to the "addded after instructions" of the delayed
889 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
891 // empty the "added after instructions" of the original instruction
895 //----------------------------------------------------------------------------
896 // This method prints the code with registers after register allocation is
898 //----------------------------------------------------------------------------
899 void PhyRegAlloc::printMachineCode()
902 cerr << "\n;************** Function " << Meth->getName()
903 << " *****************\n";
905 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
907 cerr << "\n"; printLabel(BBI); cerr << ": ";
909 // get the iterator for machine instructions
910 MachineCodeForBasicBlock& MIVec = MachineCodeForBasicBlock::get(BBI);
911 MachineCodeForBasicBlock::iterator MII = MIVec.begin();
913 // iterate over all the machine instructions in BB
914 for ( ; MII != MIVec.end(); ++MII) {
915 MachineInstr *const MInst = *MII;
918 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
920 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
921 MachineOperand& Op = MInst->getOperand(OpNum);
923 if (Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
924 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
925 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
927 const Value *const Val = Op.getVRegValue () ;
928 // ****this code is temporary till NULL Values are fixed
930 cerr << "\t<*NULL*>";
934 // if a label or a constant
935 if (isa<BasicBlock>(Val)) {
936 cerr << "\t"; printLabel( Op.getVRegValue () );
938 // else it must be a register value
939 const int RegNum = Op.getAllocatedRegNum();
941 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
943 cerr << "(" << Val->getName() << ")";
945 cerr << "(" << Val << ")";
950 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
952 if (LROfVal->hasSpillOffset() )
957 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
958 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
962 cerr << "\t" << Op; // use dump field
967 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
968 if (NumOfImpRefs > 0) {
969 cerr << "\tImplicit:";
971 for (unsigned z=0; z < NumOfImpRefs; z++)
972 cerr << RAV(MInst->getImplicitRef(z)) << "\t";
975 } // for all machine instructions
985 //----------------------------------------------------------------------------
987 //----------------------------------------------------------------------------
988 void PhyRegAlloc::colorIncomingArgs()
990 const BasicBlock &FirstBB = Meth->front();
991 const MachineInstr *FirstMI = MachineCodeForBasicBlock::get(&FirstBB).front();
992 assert(FirstMI && "No machine instruction in entry BB");
994 MRI.colorMethodArgs(Meth, LRI, &AddedInstrAtEntry);
998 //----------------------------------------------------------------------------
999 // Used to generate a label for a basic block
1000 //----------------------------------------------------------------------------
1001 void PhyRegAlloc::printLabel(const Value *const Val) {
1003 cerr << Val->getName();
1005 cerr << "Label" << Val;
1009 //----------------------------------------------------------------------------
1010 // This method calls setSugColorUsable method of each live range. This
1011 // will determine whether the suggested color of LR is really usable.
1012 // A suggested color is not usable when the suggested color is volatile
1013 // AND when there are call interferences
1014 //----------------------------------------------------------------------------
1016 void PhyRegAlloc::markUnusableSugColors()
1018 if (DEBUG_RA ) cerr << "\nmarking unusable suggested colors ...\n";
1020 // hash map iterator
1021 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1022 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1024 for (; HMI != HMIEnd ; ++HMI ) {
1026 LiveRange *L = HMI->second; // get the LiveRange
1028 if (L->hasSuggestedColor()) {
1029 int RCID = L->getRegClass()->getID();
1030 if (MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1031 L->isCallInterference() )
1032 L->setSuggestedColorUsable( false );
1034 L->setSuggestedColorUsable( true );
1036 } // if L->hasSuggestedColor()
1038 } // for all LR's in hash map
1043 //----------------------------------------------------------------------------
1044 // The following method will set the stack offsets of the live ranges that
1045 // are decided to be spillled. This must be called just after coloring the
1046 // LRs using the graph coloring algo. For each live range that is spilled,
1047 // this method allocate a new spill position on the stack.
1048 //----------------------------------------------------------------------------
1050 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1051 if (DEBUG_RA) cerr << "\nsetting LR stack offsets ...\n";
1053 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
1054 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
1056 for ( ; HMI != HMIEnd ; ++HMI) {
1057 if (HMI->first && HMI->second) {
1058 LiveRange *L = HMI->second; // get the LiveRange
1059 if (!L->hasColor()) // NOTE: ** allocating the size of long Type **
1060 L->setSpillOffFromFP(mcInfo.allocateSpilledValue(TM, Type::LongTy));
1062 } // for all LR's in hash map
1067 //----------------------------------------------------------------------------
1068 // The entry pont to Register Allocation
1069 //----------------------------------------------------------------------------
1071 void PhyRegAlloc::allocateRegisters()
1074 // make sure that we put all register classes into the RegClassList
1075 // before we call constructLiveRanges (now done in the constructor of
1076 // PhyRegAlloc class).
1078 LRI.constructLiveRanges(); // create LR info
1081 LRI.printLiveRanges();
1083 createIGNodeListsAndIGs(); // create IGNode list and IGs
1085 buildInterferenceGraphs(); // build IGs in all reg classes
1089 // print all LRs in all reg classes
1090 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1091 RegClassList[rc]->printIGNodeList();
1093 // print IGs in all register classes
1094 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1095 RegClassList[rc]->printIG();
1099 LRI.coalesceLRs(); // coalesce all live ranges
1103 // print all LRs in all reg classes
1104 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1105 RegClassList[ rc ]->printIGNodeList();
1107 // print IGs in all register classes
1108 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1109 RegClassList[ rc ]->printIG();
1113 // mark un-usable suggested color before graph coloring algorithm.
1114 // When this is done, the graph coloring algo will not reserve
1115 // suggested color unnecessarily - they can be used by another LR
1117 markUnusableSugColors();
1119 // color all register classes using the graph coloring algo
1120 for (unsigned rc=0; rc < NumOfRegClasses ; rc++)
1121 RegClassList[ rc ]->colorAllRegs();
1123 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1124 // a poistion for such spilled LRs
1126 allocateStackSpace4SpilledLRs();
1128 mcInfo.popAllTempValues(TM); // TODO **Check
1130 // color incoming args - if the correct color was not received
1131 // insert code to copy to the correct register
1133 colorIncomingArgs();
1135 // Now update the machine code with register names and add any
1136 // additional code inserted by the register allocator to the instruction
1139 updateMachineCode();
1142 MachineCodeForMethod::get(Meth).dump();
1143 printMachineCode(); // only for DEBUGGING