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/MachineFunction.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 "Support/STLExtras.h"
21 #include "Support/CommandLine.h"
26 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_Results, "y", "debug output for allocation results"),
34 clEnumValN(RA_DEBUG_Coloring, "c", "debug output for graph coloring step"),
35 clEnumValN(RA_DEBUG_Interference,"ig","debug output for interference graphs"),
36 clEnumValN(RA_DEBUG_LiveRanges , "lr","debug output for live ranges"),
37 clEnumValN(RA_DEBUG_Verbose, "v", "extra debug output"),
40 //----------------------------------------------------------------------------
41 // RegisterAllocation pass front end...
42 //----------------------------------------------------------------------------
44 class RegisterAllocator : public FunctionPass {
45 TargetMachine &Target;
47 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
49 const char *getPassName() const { return "Register Allocation"; }
51 bool runOnFunction(Function &F) {
53 cerr << "\n********* Function "<< F.getName() << " ***********\n";
55 PhyRegAlloc PRA(&F, Target, &getAnalysis<FunctionLiveVarInfo>(),
56 &getAnalysis<LoopInfo>());
57 PRA.allocateRegisters();
59 if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
63 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
64 AU.addRequired<LoopInfo>();
65 AU.addRequired<FunctionLiveVarInfo>();
70 Pass *getRegisterAllocator(TargetMachine &T) {
71 return new RegisterAllocator(T);
74 //----------------------------------------------------------------------------
75 // Constructor: Init local composite objects and create register classes.
76 //----------------------------------------------------------------------------
77 PhyRegAlloc::PhyRegAlloc(Function *F, const TargetMachine& tm,
78 FunctionLiveVarInfo *Lvi, LoopInfo *LDC)
80 mcInfo(MachineFunction::get(F)),
81 LVI(Lvi), LRI(F, tm, RegClassList),
83 NumOfRegClasses(MRI.getNumOfRegClasses()),
86 // create each RegisterClass and put in RegClassList
88 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
89 RegClassList.push_back(new RegClass(F, MRI.getMachineRegClass(rc),
94 //----------------------------------------------------------------------------
95 // Destructor: Deletes register classes
96 //----------------------------------------------------------------------------
97 PhyRegAlloc::~PhyRegAlloc() {
98 for ( unsigned rc=0; rc < NumOfRegClasses; rc++)
99 delete RegClassList[rc];
101 AddedInstrMap.clear();
104 //----------------------------------------------------------------------------
105 // This method initally creates interference graphs (one in each reg class)
106 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
107 //----------------------------------------------------------------------------
108 void PhyRegAlloc::createIGNodeListsAndIGs() {
109 if (DEBUG_RA >= RA_DEBUG_LiveRanges) cerr << "Creating LR lists ...\n";
112 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
115 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
117 for (; HMI != HMIEnd ; ++HMI ) {
119 LiveRange *L = HMI->second; // get the LiveRange
122 cerr << "\n**** ?!?WARNING: NULL LIVE RANGE FOUND FOR: "
123 << RAV(HMI->first) << "****\n";
127 // if the Value * is not null, and LR is not yet written to the IGNodeList
128 if (!(L->getUserIGNode()) ) {
129 RegClass *const RC = // RegClass of first value in the LR
130 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();
140 if (DEBUG_RA >= RA_DEBUG_LiveRanges) cerr << "LRLists Created!\n";
144 //----------------------------------------------------------------------------
145 // This method will add all interferences at for a given instruction.
146 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
147 // class as that of live var. The live var passed to this function is the
148 // LVset AFTER the instruction
149 //----------------------------------------------------------------------------
151 void PhyRegAlloc::addInterference(const Value *Def,
152 const ValueSet *LVSet,
155 ValueSet::const_iterator LIt = LVSet->begin();
157 // get the live range of instruction
159 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
161 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
162 assert( IGNodeOfDef );
164 RegClass *const RCOfDef = LROfDef->getRegClass();
166 // for each live var in live variable set
168 for ( ; LIt != LVSet->end(); ++LIt) {
170 if (DEBUG_RA >= RA_DEBUG_Verbose)
171 cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
173 // get the live range corresponding to live var
175 LiveRange *LROfVar = LRI.getLiveRangeForValue(*LIt);
177 // LROfVar can be null if it is a const since a const
178 // doesn't have a dominating def - see Assumptions above
181 if (LROfDef != LROfVar) // do not set interf for same LR
182 if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
183 RCOfDef->setInterference( LROfDef, LROfVar);
189 //----------------------------------------------------------------------------
190 // For a call instruction, this method sets the CallInterference flag in
191 // the LR of each variable live int the Live Variable Set live after the
192 // call instruction (except the return value of the call instruction - since
193 // the return value does not interfere with that call itself).
194 //----------------------------------------------------------------------------
196 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
197 const ValueSet *LVSetAft) {
199 if (DEBUG_RA >= RA_DEBUG_Interference)
200 cerr << "\n For call inst: " << *MInst;
202 ValueSet::const_iterator LIt = LVSetAft->begin();
204 // for each live var in live variable set after machine inst
206 for ( ; LIt != LVSetAft->end(); ++LIt) {
208 // get the live range corresponding to live var
210 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
212 // LR can be null if it is a const since a const
213 // doesn't have a dominating def - see Assumptions above
216 if (DEBUG_RA >= RA_DEBUG_Interference) {
217 cerr << "\n\tLR after Call: ";
220 LR->setCallInterference();
221 if (DEBUG_RA >= RA_DEBUG_Interference) {
222 cerr << "\n ++After adding call interference for LR: " ;
229 // Now find the LR of the return value of the call
230 // We do this because, we look at the LV set *after* the instruction
231 // to determine, which LRs must be saved across calls. The return value
232 // of the call is live in this set - but it does not interfere with call
233 // (i.e., we can allocate a volatile register to the return value)
235 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
237 if (const Value *RetVal = argDesc->getReturnValue()) {
238 LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
239 assert( RetValLR && "No LR for RetValue of call");
240 RetValLR->clearCallInterference();
243 // If the CALL is an indirect call, find the LR of the function pointer.
244 // That has a call interference because it conflicts with outgoing args.
245 if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
246 LiveRange *AddrValLR = LRI.getLiveRangeForValue( AddrVal );
247 assert( AddrValLR && "No LR for indirect addr val of call");
248 AddrValLR->setCallInterference();
256 //----------------------------------------------------------------------------
257 // This method will walk thru code and create interferences in the IG of
258 // each RegClass. Also, this method calculates the spill cost of each
259 // Live Range (it is done in this method to save another pass over the code).
260 //----------------------------------------------------------------------------
261 void PhyRegAlloc::buildInterferenceGraphs()
264 if (DEBUG_RA >= RA_DEBUG_Interference)
265 cerr << "Creating interference graphs ...\n";
267 unsigned BBLoopDepthCost;
268 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
271 // find the 10^(loop_depth) of this BB
273 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BBI));
275 // get the iterator for machine instructions
277 const MachineBasicBlock& MIVec = MachineBasicBlock::get(BBI);
278 MachineBasicBlock::const_iterator MII = MIVec.begin();
280 // iterate over all the machine instructions in BB
282 for ( ; MII != MIVec.end(); ++MII) {
284 const MachineInstr *MInst = *MII;
286 // get the LV set after the instruction
288 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BBI);
290 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
293 // set the isCallInterference flag of each live range wich extends
294 // accross this call instruction. This information is used by graph
295 // coloring algo to avoid allocating volatile colors to live ranges
296 // that span across calls (since they have to be saved/restored)
298 setCallInterferences(MInst, &LVSetAI);
302 // iterate over all MI operands to find defs
304 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
305 OpE = MInst->end(); OpI != OpE; ++OpI) {
306 if (OpI.isDef()) // create a new LR iff this operand is a def
307 addInterference(*OpI, &LVSetAI, isCallInst);
309 // Calculate the spill cost of each live range
311 LiveRange *LR = LRI.getLiveRangeForValue(*OpI);
312 if (LR) LR->addSpillCost(BBLoopDepthCost);
316 // if there are multiple defs in this instruction e.g. in SETX
318 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
319 addInterf4PseudoInstr(MInst);
322 // Also add interference for any implicit definitions in a machine
323 // instr (currently, only calls have this).
325 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
326 if ( NumOfImpRefs > 0 ) {
327 for (unsigned z=0; z < NumOfImpRefs; z++)
328 if (MInst->implicitRefIsDefined(z) )
329 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
333 } // for all machine instructions in BB
334 } // for all BBs in function
337 // add interferences for function arguments. Since there are no explict
338 // defs in the function for args, we have to add them manually
340 addInterferencesForArgs();
342 if (DEBUG_RA >= RA_DEBUG_Interference)
343 cerr << "Interference graphs calculated!\n";
348 //--------------------------------------------------------------------------
349 // Pseudo instructions will be exapnded to multiple instructions by the
350 // assembler. Consequently, all the opernds must get distinct registers.
351 // Therefore, we mark all operands of a pseudo instruction as they interfere
353 //--------------------------------------------------------------------------
354 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
356 bool setInterf = false;
358 // iterate over MI operands to find defs
360 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
361 ItE = MInst->end(); It1 != ItE; ++It1) {
362 const LiveRange *LROfOp1 = LRI.getLiveRangeForValue(*It1);
363 assert((LROfOp1 || !It1.isDef()) && "No LR for Def in PSEUDO insruction");
365 MachineInstr::const_val_op_iterator It2 = It1;
366 for (++It2; It2 != ItE; ++It2) {
367 const LiveRange *LROfOp2 = LRI.getLiveRangeForValue(*It2);
370 RegClass *RCOfOp1 = LROfOp1->getRegClass();
371 RegClass *RCOfOp2 = LROfOp2->getRegClass();
373 if (RCOfOp1 == RCOfOp2 ){
374 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
378 } // for all other defs in machine instr
379 } // for all operands in an instruction
381 if (!setInterf && MInst->getNumOperands() > 2) {
382 cerr << "\nInterf not set for any operand in pseudo instr:\n";
384 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
390 //----------------------------------------------------------------------------
391 // This method will add interferences for incoming arguments to a function.
392 //----------------------------------------------------------------------------
394 void PhyRegAlloc::addInterferencesForArgs() {
395 // get the InSet of root BB
396 const ValueSet &InSet = LVI->getInSetOfBB(&Meth->front());
398 for (Function::const_aiterator AI=Meth->abegin(); AI != Meth->aend(); ++AI) {
399 // add interferences between args and LVars at start
400 addInterference(AI, &InSet, false);
402 if (DEBUG_RA >= RA_DEBUG_Interference)
403 cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
408 //----------------------------------------------------------------------------
409 // This method is called after register allocation is complete to set the
410 // allocated reisters in the machine code. This code will add register numbers
411 // to MachineOperands that contain a Value. Also it calls target specific
412 // methods to produce caller saving instructions. At the end, it adds all
413 // additional instructions produced by the register allocator to the
414 // instruction stream.
415 //----------------------------------------------------------------------------
417 //-----------------------------
418 // Utility functions used below
419 //-----------------------------
421 InsertBefore(MachineInstr* newMI,
422 MachineBasicBlock& MIVec,
423 MachineBasicBlock::iterator& MII)
425 MII = MIVec.insert(MII, newMI);
430 InsertAfter(MachineInstr* newMI,
431 MachineBasicBlock& MIVec,
432 MachineBasicBlock::iterator& MII)
434 ++MII; // insert before the next instruction
435 MII = MIVec.insert(MII, newMI);
439 SubstituteInPlace(MachineInstr* newMI,
440 MachineBasicBlock& MIVec,
441 MachineBasicBlock::iterator MII)
447 PrependInstructions(vector<MachineInstr *> &IBef,
448 MachineBasicBlock& MIVec,
449 MachineBasicBlock::iterator& MII,
450 const std::string& msg)
454 MachineInstr* OrigMI = *MII;
455 std::vector<MachineInstr *>::iterator AdIt;
456 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
459 if (OrigMI) cerr << "For MInst:\n " << *OrigMI;
460 cerr << msg << "PREPENDed instr:\n " << **AdIt << "\n";
462 InsertBefore(*AdIt, MIVec, MII);
468 AppendInstructions(std::vector<MachineInstr *> &IAft,
469 MachineBasicBlock& MIVec,
470 MachineBasicBlock::iterator& MII,
471 const std::string& msg)
475 MachineInstr* OrigMI = *MII;
476 std::vector<MachineInstr *>::iterator AdIt;
477 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
480 if (OrigMI) cerr << "For MInst:\n " << *OrigMI;
481 cerr << msg << "APPENDed instr:\n " << **AdIt << "\n";
483 InsertAfter(*AdIt, MIVec, MII);
489 void PhyRegAlloc::updateMachineCode()
491 MachineBasicBlock& MIVec = MachineBasicBlock::get(&Meth->getEntryNode());
493 // Insert any instructions needed at method entry
494 MachineBasicBlock::iterator MII = MIVec.begin();
495 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MIVec, MII,
496 "At function entry: \n");
497 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
498 "InstrsAfter should be unnecessary since we are just inserting at "
499 "the function entry point here.");
501 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
504 // iterate over all the machine instructions in BB
505 MachineBasicBlock &MIVec = MachineBasicBlock::get(BBI);
506 for (MachineBasicBlock::iterator MII = MIVec.begin();
507 MII != MIVec.end(); ++MII) {
509 MachineInstr *MInst = *MII;
511 unsigned Opcode = MInst->getOpCode();
513 // do not process Phis
514 if (TM.getInstrInfo().isDummyPhiInstr(Opcode))
517 // Reset tmp stack positions so they can be reused for each machine instr.
518 mcInfo.popAllTempValues(TM);
520 // Now insert speical instructions (if necessary) for call/return
523 if (TM.getInstrInfo().isCall(Opcode) ||
524 TM.getInstrInfo().isReturn(Opcode)) {
526 AddedInstrns &AI = AddedInstrMap[MInst];
528 if (TM.getInstrInfo().isCall(Opcode))
529 MRI.colorCallArgs(MInst, LRI, &AI, *this, BBI);
530 else if (TM.getInstrInfo().isReturn(Opcode))
531 MRI.colorRetValue(MInst, LRI, &AI);
534 // Set the registers for operands in the machine instruction
535 // if a register was successfully allocated. If not, insert
536 // code to spill the register value.
538 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
540 MachineOperand& Op = MInst->getOperand(OpNum);
541 if (Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
542 Op.getOperandType() == MachineOperand::MO_CCRegister)
544 const Value *const Val = Op.getVRegValue();
546 LiveRange *const LR = LRI.getLiveRangeForValue(Val);
547 if (!LR) // consts or labels will have no live range
549 // if register is not allocated, mark register as invalid
550 if (Op.getAllocatedRegNum() == -1)
551 MInst->SetRegForOperand(OpNum, MRI.getInvalidRegNum());
556 MInst->SetRegForOperand(OpNum,
557 MRI.getUnifiedRegNum(LR->getRegClass()->getID(),
560 // LR did NOT receive a color (register). Insert spill code.
561 insertCode4SpilledLR(LR, MInst, BBI, OpNum );
563 } // for each operand
565 // Now add instructions that the register allocator inserts before/after
566 // this machine instructions (done only for calls/rets/incoming args)
567 // We do this here, to ensure that spill for an instruction is inserted
568 // closest as possible to an instruction (see above insertCode4Spill...)
570 // First, if the instruction in the delay slot of a branch needs
571 // instructions inserted, move it out of the delay slot and before the
572 // branch because putting code before or after it would be VERY BAD!
574 unsigned bumpIteratorBy = 0;
575 if (MII != MIVec.begin())
576 if (unsigned predDelaySlots =
577 TM.getInstrInfo().getNumDelaySlots((*(MII-1))->getOpCode()))
579 assert(predDelaySlots==1 && "Not handling multiple delay slots!");
580 if (TM.getInstrInfo().isBranch((*(MII-1))->getOpCode())
581 && (AddedInstrMap.count(MInst) ||
582 AddedInstrMap[MInst].InstrnsAfter.size() > 0))
584 // Current instruction is in the delay slot of a branch and it
585 // needs spill code inserted before or after it.
586 // Move it before the preceding branch.
587 InsertBefore(MInst, MIVec, --MII);
589 new MachineInstr(TM.getInstrInfo().getNOPOpCode());
590 SubstituteInPlace(nopI, MIVec, MII+1); // replace orig with NOP
591 --MII; // point to MInst in new location
592 bumpIteratorBy = 2; // later skip the branch and the NOP!
596 // If there are instructions to be added, *before* this machine
597 // instruction, add them now.
599 if (AddedInstrMap.count(MInst)) {
600 PrependInstructions(AddedInstrMap[MInst].InstrnsBefore, MIVec, MII,"");
603 // If there are instructions to be added *after* this machine
604 // instruction, add them now
606 if (!AddedInstrMap[MInst].InstrnsAfter.empty()) {
608 // if there are delay slots for this instruction, the instructions
609 // added after it must really go after the delayed instruction(s)
610 // So, we move the InstrAfter of the current instruction to the
611 // corresponding delayed instruction
613 TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) {
615 // Delayed instructions are typically branches or calls. Let's make
616 // sure this is not a branch, otherwise "insert-after" is meaningless,
617 // and should never happen for any reason (spill code, register
619 assert(! TM.getInstrInfo().isBranch(MInst->getOpCode()) &&
620 ! TM.getInstrInfo().isReturn(MInst->getOpCode()) &&
621 "INTERNAL ERROR: Register allocator should not be inserting "
622 "any code after a branch or return!");
624 move2DelayedInstr(MInst, *(MII+delay) );
627 // Here we can add the "instructions after" to the current
628 // instruction since there are no delay slots for this instruction
629 AppendInstructions(AddedInstrMap[MInst].InstrnsAfter, MIVec, MII,"");
633 // If we mucked with the instruction order above, adjust the loop iterator
635 MII = MII + bumpIteratorBy;
637 } // for each machine instruction
643 //----------------------------------------------------------------------------
644 // This method inserts spill code for AN operand whose LR was spilled.
645 // This method may be called several times for a single machine instruction
646 // if it contains many spilled operands. Each time it is called, it finds
647 // a register which is not live at that instruction and also which is not
648 // used by other spilled operands of the same instruction. Then it uses
649 // this register temporarily to accomodate the spilled value.
650 //----------------------------------------------------------------------------
651 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
653 const BasicBlock *BB,
654 const unsigned OpNum) {
656 assert((! TM.getInstrInfo().isCall(MInst->getOpCode()) || OpNum == 0) &&
657 "Outgoing arg of a call must be handled elsewhere (func arg ok)");
658 assert(! TM.getInstrInfo().isReturn(MInst->getOpCode()) &&
659 "Return value of a ret must be handled elsewhere");
661 MachineOperand& Op = MInst->getOperand(OpNum);
662 bool isDef = MInst->operandIsDefined(OpNum);
663 bool isDefAndUse = MInst->operandIsDefinedAndUsed(OpNum);
664 unsigned RegType = MRI.getRegType( LR );
665 int SpillOff = LR->getSpillOffFromFP();
666 RegClass *RC = LR->getRegClass();
667 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
669 mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
671 vector<MachineInstr*> MIBef, MIAft;
672 vector<MachineInstr*> AdIMid;
674 // Choose a register to hold the spilled value. This may insert code
675 // before and after MInst to free up the value. If so, this code should
676 // be first and last in the spill sequence before/after MInst.
677 int TmpRegU = getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef, MIAft);
679 // Set the operand first so that it this register does not get used
680 // as a scratch register for later calls to getUsableUniRegAtMI below
681 MInst->SetRegForOperand(OpNum, TmpRegU);
683 // get the added instructions for this instruction
684 AddedInstrns &AI = AddedInstrMap[MInst];
686 // We may need a scratch register to copy the spilled value to/from memory.
687 // This may itself have to insert code to free up a scratch register.
688 // Any such code should go before (after) the spill code for a load (store).
689 int scratchRegType = -1;
691 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
693 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
694 MInst, MIBef, MIAft);
695 assert(scratchReg != MRI.getInvalidRegNum());
696 MInst->insertUsedReg(scratchReg);
699 if (!isDef || isDefAndUse) {
700 // for a USE, we have to load the value of LR from stack to a TmpReg
701 // and use the TmpReg as one operand of instruction
703 // actual loading instruction(s)
704 MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU, RegType,
707 // the actual load should be after the instructions to free up TmpRegU
708 MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
712 if (isDef) { // if this is a Def
713 // for a DEF, we have to store the value produced by this instruction
714 // on the stack position allocated for this LR
716 // actual storing instruction(s)
717 MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff, RegType,
720 MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
723 // Finally, insert the entire spill code sequences before/after MInst
724 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
725 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
728 cerr << "\nFor Inst:\n " << *MInst;
729 cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
730 cerr << "; added Instructions:";
731 for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
732 for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
737 //----------------------------------------------------------------------------
738 // We can use the following method to get a temporary register to be used
739 // BEFORE any given machine instruction. If there is a register available,
740 // this method will simply return that register and set MIBef = MIAft = NULL.
741 // Otherwise, it will return a register and MIAft and MIBef will contain
742 // two instructions used to free up this returned register.
743 // Returned register number is the UNIFIED register number
744 //----------------------------------------------------------------------------
746 int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
747 const ValueSet *LVSetBef,
749 std::vector<MachineInstr*>& MIBef,
750 std::vector<MachineInstr*>& MIAft) {
752 RegClass* RC = this->getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
754 int RegU = getUnusedUniRegAtMI(RC, MInst, LVSetBef);
757 // we couldn't find an unused register. Generate code to free up a reg by
758 // saving it on stack and restoring after the instruction
760 int TmpOff = mcInfo.pushTempValue(TM, MRI.getSpilledRegSize(RegType) );
762 RegU = getUniRegNotUsedByThisInst(RC, MInst);
764 // Check if we need a scratch register to copy this register to memory.
765 int scratchRegType = -1;
766 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
768 int scratchReg = this->getUsableUniRegAtMI(scratchRegType, LVSetBef,
769 MInst, MIBef, MIAft);
770 assert(scratchReg != MRI.getInvalidRegNum());
772 // We may as well hold the value in the scratch register instead
773 // of copying it to memory and back. But we have to mark the
774 // register as used by this instruction, so it does not get used
775 // as a scratch reg. by another operand or anyone else.
776 MInst->insertUsedReg(scratchReg);
777 MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
778 MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
781 { // the register can be copied directly to/from memory so do it.
782 MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
783 MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
790 //----------------------------------------------------------------------------
791 // This method is called to get a new unused register that can be used to
792 // accomodate a spilled value.
793 // This method may be called several times for a single machine instruction
794 // if it contains many spilled operands. Each time it is called, it finds
795 // a register which is not live at that instruction and also which is not
796 // used by other spilled operands of the same instruction.
797 // Return register number is relative to the register class. NOT
799 //----------------------------------------------------------------------------
800 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
801 const MachineInstr *MInst,
802 const ValueSet *LVSetBef) {
804 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
806 std::vector<bool> &IsColorUsedArr = RC->getIsColorUsedArr();
808 for (unsigned i=0; i < NumAvailRegs; i++) // Reset array
809 IsColorUsedArr[i] = false;
811 ValueSet::const_iterator LIt = LVSetBef->begin();
813 // for each live var in live variable set after machine inst
814 for ( ; LIt != LVSetBef->end(); ++LIt) {
816 // get the live range corresponding to live var
817 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
819 // LR can be null if it is a const since a const
820 // doesn't have a dominating def - see Assumptions above
821 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor() )
822 IsColorUsedArr[ LRofLV->getColor() ] = true;
825 // It is possible that one operand of this MInst was already spilled
826 // and it received some register temporarily. If that's the case,
827 // it is recorded in machine operand. We must skip such registers.
829 setRelRegsUsedByThisInst(RC, MInst);
831 for (unsigned c=0; c < NumAvailRegs; c++) // find first unused color
832 if (!IsColorUsedArr[c])
833 return MRI.getUnifiedRegNum(RC->getID(), c);
839 //----------------------------------------------------------------------------
840 // Get any other register in a register class, other than what is used
841 // by operands of a machine instruction. Returns the unified reg number.
842 //----------------------------------------------------------------------------
843 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
844 const MachineInstr *MInst) {
846 vector<bool> &IsColorUsedArr = RC->getIsColorUsedArr();
847 unsigned NumAvailRegs = RC->getNumOfAvailRegs();
849 for (unsigned i=0; i < NumAvailRegs ; i++) // Reset array
850 IsColorUsedArr[i] = false;
852 setRelRegsUsedByThisInst(RC, MInst);
854 for (unsigned c=0; c < RC->getNumOfAvailRegs(); c++)// find first unused color
855 if (!IsColorUsedArr[c])
856 return MRI.getUnifiedRegNum(RC->getID(), c);
858 assert(0 && "FATAL: No free register could be found in reg class!!");
863 //----------------------------------------------------------------------------
864 // This method modifies the IsColorUsedArr of the register class passed to it.
865 // It sets the bits corresponding to the registers used by this machine
866 // instructions. Both explicit and implicit operands are set.
867 //----------------------------------------------------------------------------
868 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC,
869 const MachineInstr *MInst ) {
871 vector<bool> &IsColorUsedArr = RC->getIsColorUsedArr();
873 // Add the registers already marked as used by the instruction.
874 // This should include any scratch registers that are used to save
875 // values across the instruction (e.g., for saving state register values).
876 const vector<bool> ®sUsed = MInst->getRegsUsed();
877 for (unsigned i = 0, e = regsUsed.size(); i != e; ++i)
879 unsigned classId = 0;
880 int classRegNum = MRI.getClassRegNum(i, classId);
881 if (RC->getID() == classId)
883 assert(classRegNum < (int) IsColorUsedArr.size() &&
884 "Illegal register number for this reg class?");
885 IsColorUsedArr[classRegNum] = true;
889 // Now add registers allocated to the live ranges of values used in
890 // the instruction. These are not yet recorded in the instruction.
891 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
893 const MachineOperand& Op = MInst->getOperand(OpNum);
895 if (Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
896 Op.getOperandType() == MachineOperand::MO_CCRegister)
897 if (const Value* Val = Op.getVRegValue())
898 if (MRI.getRegClassIDOfValue(Val) == RC->getID())
899 if (Op.getAllocatedRegNum() == -1)
900 if (LiveRange *LROfVal = LRI.getLiveRangeForValue(Val))
901 if (LROfVal->hasColor() )
902 // this operand is in a LR that received a color
903 IsColorUsedArr[LROfVal->getColor()] = true;
906 // If there are implicit references, mark their allocated regs as well
908 for (unsigned z=0; z < MInst->getNumImplicitRefs(); z++)
910 LRofImpRef = LRI.getLiveRangeForValue(MInst->getImplicitRef(z)))
911 if (LRofImpRef->hasColor())
912 // this implicit reference is in a LR that received a color
913 IsColorUsedArr[LRofImpRef->getColor()] = true;
917 //----------------------------------------------------------------------------
918 // If there are delay slots for an instruction, the instructions
919 // added after it must really go after the delayed instruction(s).
920 // So, we move the InstrAfter of that instruction to the
921 // corresponding delayed instruction using the following method.
923 //----------------------------------------------------------------------------
924 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
925 const MachineInstr *DelayedMI) {
927 // "added after" instructions of the original instr
928 std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
930 // "added instructions" of the delayed instr
931 AddedInstrns &DelayAdI = AddedInstrMap[DelayedMI];
933 // "added after" instructions of the delayed instr
934 std::vector<MachineInstr *> &DelayedAft = DelayAdI.InstrnsAfter;
936 // go thru all the "added after instructions" of the original instruction
937 // and append them to the "addded after instructions" of the delayed
939 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
941 // empty the "added after instructions" of the original instruction
945 //----------------------------------------------------------------------------
946 // This method prints the code with registers after register allocation is
948 //----------------------------------------------------------------------------
949 void PhyRegAlloc::printMachineCode()
952 cerr << "\n;************** Function " << Meth->getName()
953 << " *****************\n";
955 for (Function::const_iterator BBI = Meth->begin(), BBE = Meth->end();
957 cerr << "\n"; printLabel(BBI); cerr << ": ";
959 // get the iterator for machine instructions
960 MachineBasicBlock& MIVec = MachineBasicBlock::get(BBI);
961 MachineBasicBlock::iterator MII = MIVec.begin();
963 // iterate over all the machine instructions in BB
964 for ( ; MII != MIVec.end(); ++MII) {
965 MachineInstr *const MInst = *MII;
968 cerr << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
970 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
971 MachineOperand& Op = MInst->getOperand(OpNum);
973 if (Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
974 Op.getOperandType() == MachineOperand::MO_CCRegister /*||
975 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp*/ ) {
977 const Value *const Val = Op.getVRegValue () ;
978 // ****this code is temporary till NULL Values are fixed
980 cerr << "\t<*NULL*>";
984 // if a label or a constant
985 if (isa<BasicBlock>(Val)) {
986 cerr << "\t"; printLabel( Op.getVRegValue () );
988 // else it must be a register value
989 const int RegNum = Op.getAllocatedRegNum();
991 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
993 cerr << "(" << Val->getName() << ")";
995 cerr << "(" << Val << ")";
1000 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
1002 if (LROfVal->hasSpillOffset() )
1007 else if (Op.getOperandType() == MachineOperand::MO_MachineRegister) {
1008 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1012 cerr << "\t" << Op; // use dump field
1017 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1018 if (NumOfImpRefs > 0) {
1019 cerr << "\tImplicit:";
1021 for (unsigned z=0; z < NumOfImpRefs; z++)
1022 cerr << RAV(MInst->getImplicitRef(z)) << "\t";
1025 } // for all machine instructions
1035 //----------------------------------------------------------------------------
1037 //----------------------------------------------------------------------------
1038 void PhyRegAlloc::colorIncomingArgs()
1040 const BasicBlock &FirstBB = Meth->front();
1041 const MachineInstr *FirstMI = MachineBasicBlock::get(&FirstBB).front();
1042 assert(FirstMI && "No machine instruction in entry BB");
1044 MRI.colorMethodArgs(Meth, LRI, &AddedInstrAtEntry);
1048 //----------------------------------------------------------------------------
1049 // Used to generate a label for a basic block
1050 //----------------------------------------------------------------------------
1051 void PhyRegAlloc::printLabel(const Value *const Val) {
1053 cerr << Val->getName();
1055 cerr << "Label" << Val;
1059 //----------------------------------------------------------------------------
1060 // This method calls setSugColorUsable method of each live range. This
1061 // will determine whether the suggested color of LR is really usable.
1062 // A suggested color is not usable when the suggested color is volatile
1063 // AND when there are call interferences
1064 //----------------------------------------------------------------------------
1066 void PhyRegAlloc::markUnusableSugColors()
1068 // hash map iterator
1069 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1070 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1072 for (; HMI != HMIEnd ; ++HMI ) {
1074 LiveRange *L = HMI->second; // get the LiveRange
1076 if (L->hasSuggestedColor()) {
1077 int RCID = L->getRegClass()->getID();
1078 if (MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1079 L->isCallInterference() )
1080 L->setSuggestedColorUsable( false );
1082 L->setSuggestedColorUsable( true );
1084 } // if L->hasSuggestedColor()
1086 } // for all LR's in hash map
1091 //----------------------------------------------------------------------------
1092 // The following method will set the stack offsets of the live ranges that
1093 // are decided to be spillled. This must be called just after coloring the
1094 // LRs using the graph coloring algo. For each live range that is spilled,
1095 // this method allocate a new spill position on the stack.
1096 //----------------------------------------------------------------------------
1098 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1099 if (DEBUG_RA) cerr << "\nSetting LR stack offsets for spills...\n";
1101 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
1102 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
1104 for ( ; HMI != HMIEnd ; ++HMI) {
1105 if (HMI->first && HMI->second) {
1106 LiveRange *L = HMI->second; // get the LiveRange
1107 if (!L->hasColor()) { // NOTE: ** allocating the size of long Type **
1108 int stackOffset = mcInfo.allocateSpilledValue(TM, Type::LongTy);
1109 L->setSpillOffFromFP(stackOffset);
1111 cerr << " LR# " << L->getUserIGNode()->getIndex()
1112 << ": stack-offset = " << stackOffset << "\n";
1115 } // for all LR's in hash map
1120 //----------------------------------------------------------------------------
1121 // The entry pont to Register Allocation
1122 //----------------------------------------------------------------------------
1124 void PhyRegAlloc::allocateRegisters()
1127 // make sure that we put all register classes into the RegClassList
1128 // before we call constructLiveRanges (now done in the constructor of
1129 // PhyRegAlloc class).
1131 LRI.constructLiveRanges(); // create LR info
1133 if (DEBUG_RA >= RA_DEBUG_LiveRanges)
1134 LRI.printLiveRanges();
1136 createIGNodeListsAndIGs(); // create IGNode list and IGs
1138 buildInterferenceGraphs(); // build IGs in all reg classes
1141 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1142 // print all LRs in all reg classes
1143 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1144 RegClassList[rc]->printIGNodeList();
1146 // print IGs in all register classes
1147 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1148 RegClassList[rc]->printIG();
1152 LRI.coalesceLRs(); // coalesce all live ranges
1155 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1156 // print all LRs in all reg classes
1157 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1158 RegClassList[ rc ]->printIGNodeList();
1160 // print IGs in all register classes
1161 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1162 RegClassList[ rc ]->printIG();
1166 // mark un-usable suggested color before graph coloring algorithm.
1167 // When this is done, the graph coloring algo will not reserve
1168 // suggested color unnecessarily - they can be used by another LR
1170 markUnusableSugColors();
1172 // color all register classes using the graph coloring algo
1173 for (unsigned rc=0; rc < NumOfRegClasses ; rc++)
1174 RegClassList[ rc ]->colorAllRegs();
1176 // Atter grpah coloring, if some LRs did not receive a color (i.e, spilled)
1177 // a poistion for such spilled LRs
1179 allocateStackSpace4SpilledLRs();
1181 mcInfo.popAllTempValues(TM); // TODO **Check
1183 // color incoming args - if the correct color was not received
1184 // insert code to copy to the correct register
1186 colorIncomingArgs();
1188 // Now update the machine code with register names and add any
1189 // additional code inserted by the register allocator to the instruction
1192 updateMachineCode();
1195 cerr << "\n**** Machine Code After Register Allocation:\n\n";
1196 MachineFunction::get(Meth).dump();