1 #include "llvm/CodeGen/PhyRegAlloc.h"
3 cl::Enum<RegAllocDebugLevel_t> DEBUG_RA("dregalloc", cl::NoFlags,
4 "enable register allocation debugging information",
5 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
6 clEnumValN(RA_DEBUG_Normal , "y", "enable debug output"),
7 clEnumValN(RA_DEBUG_Verbose, "v", "enable extra debug output"), 0);
10 //----------------------------------------------------------------------------
11 // Constructor: Init local composite objects and create register classes.
12 //----------------------------------------------------------------------------
13 PhyRegAlloc::PhyRegAlloc(const Method *const M,
14 const TargetMachine& tm,
15 MethodLiveVarInfo *const Lvi)
17 Meth(M), TM(tm), LVI(Lvi), LRI(M, tm, RegClassList),
18 MRI( tm.getRegInfo() ),
19 NumOfRegClasses(MRI.getNumOfRegClasses()),
23 // **TODO: use an actual reserved color list
24 ReservedColorListType *RCL = new ReservedColorListType();
26 // create each RegisterClass and put in RegClassList
27 for( unsigned int rc=0; rc < NumOfRegClasses; rc++)
28 RegClassList.push_back( new RegClass(M, MRI.getMachineRegClass(rc), RCL) );
32 //----------------------------------------------------------------------------
33 // This method initally creates interference graphs (one in each reg class)
34 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
35 //----------------------------------------------------------------------------
37 void PhyRegAlloc::createIGNodeListsAndIGs()
39 if(DEBUG_RA ) cout << "Creating LR lists ..." << endl;
42 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
45 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
47 for( ; HMI != HMIEnd ; ++HMI ) {
51 LiveRange *L = (*HMI).second; // get the LiveRange
55 cout << "\n*?!?Warning: Null liver range found for: ";
56 printValue( (*HMI).first) ; cout << endl;
60 // if the Value * is not null, and LR
61 // is not yet written to the IGNodeList
62 if( !(L->getUserIGNode()) ) {
64 RegClass *const RC = // RegClass of first value in the LR
65 //RegClassList [MRI.getRegClassIDOfValue(*(L->begin()))];
66 RegClassList[ L->getRegClass()->getID() ];
68 RC-> addLRToIG( L ); // add this LR to an IG
74 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
75 RegClassList[ rc ]->createInterferenceGraph();
78 cout << "LRLists Created!" << endl;
83 //----------------------------------------------------------------------------
84 // This method will add all interferences at for a given instruction.
85 // Interence occurs only if the LR of Def (Inst or Arg) is of the same reg
86 // class as that of live var. The live var passed to this function is the
87 // LVset AFTER the instruction
88 //----------------------------------------------------------------------------
90 void PhyRegAlloc::addInterference(const Value *const Def,
91 const LiveVarSet *const LVSet,
92 const bool isCallInst) {
94 LiveVarSet::const_iterator LIt = LVSet->begin();
96 // get the live range of instruction
97 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
99 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
100 assert( IGNodeOfDef );
102 RegClass *const RCOfDef = LROfDef->getRegClass();
104 // for each live var in live variable set
105 for( ; LIt != LVSet->end(); ++LIt) {
108 cout << "< Def="; printValue(Def);
109 cout << ", Lvar="; printValue( *LIt); cout << "> ";
112 // get the live range corresponding to live var
113 LiveRange *const LROfVar = LRI.getLiveRangeForValue(*LIt );
115 // LROfVar can be null if it is a const since a const
116 // doesn't have a dominating def - see Assumptions above
119 if(LROfDef == LROfVar) // do not set interf for same LR
122 // if 2 reg classes are the same set interference
123 if( RCOfDef == LROfVar->getRegClass() ){
124 RCOfDef->setInterference( LROfDef, LROfVar);
128 //the live range of this var interferes with this call
130 LROfVar->addCallInterference( (const Instruction *const) Def );
133 else if(DEBUG_RA > 1) {
134 // we will not have LRs for values not explicitly allocated in the
135 // instruction stream (e.g., constants)
136 cout << " warning: no live range for " ;
137 printValue( *LIt); cout << endl; }
143 //----------------------------------------------------------------------------
144 // This method will walk thru code and create interferences in the IG of
146 //----------------------------------------------------------------------------
148 void PhyRegAlloc::buildInterferenceGraphs()
151 if(DEBUG_RA) cout << "Creating interference graphs ..." << endl;
153 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
155 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
157 // get the iterator for machine instructions
158 const MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
159 MachineCodeForBasicBlock::const_iterator
160 MInstIterator = MIVec.begin();
162 // iterate over all the machine instructions in BB
163 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
165 const MachineInstr *const MInst = *MInstIterator;
167 // get the LV set after the instruction
168 const LiveVarSet *const LVSetAI =
169 LVI->getLiveVarSetAfterMInst(MInst, *BBI);
171 const bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
173 // iterate over MI operands to find defs
174 for( MachineInstr::val_op_const_iterator OpI(MInst);!OpI.done(); ++OpI) {
177 // create a new LR iff this operand is a def
178 addInterference(*OpI, LVSetAI, isCallInst );
182 } // for all operands
184 } // for all machine instructions in BB
189 // go thru LLVM instructions in the basic block and record all CALL
190 // instructions and Return instructions in the CallInstrList
191 // This is done because since there are no reverse pointers in machine
192 // instructions to find the llvm instruction, when we encounter a call
193 // or a return whose args must be specailly colored (e.g., %o's for args)
194 BasicBlock::const_iterator InstIt = (*BBI)->begin();
196 for( ; InstIt != (*BBI)->end() ; ++ InstIt) {
197 unsigned OpCode = (*InstIt)->getOpcode();
199 if( OpCode == Instruction::Call )
200 CallInstrList.push_back( *InstIt );
202 else if( OpCode == Instruction::Ret )
203 RetInstrList.push_back( *InstIt );
209 } // for all BBs in method
212 // add interferences for method arguments. Since there are no explict
213 // defs in method for args, we have to add them manually
215 addInterferencesForArgs(); // add interference for method args
218 cout << "Interference graphs calculted!" << endl;
225 //----------------------------------------------------------------------------
226 // This method will add interferences for incoming arguments to a method.
227 //----------------------------------------------------------------------------
228 void PhyRegAlloc::addInterferencesForArgs()
230 // get the InSet of root BB
231 const LiveVarSet *const InSet = LVI->getInSetOfBB( Meth->front() );
233 // get the argument list
234 const Method::ArgumentListType& ArgList = Meth->getArgumentList();
236 // get an iterator to arg list
237 Method::ArgumentListType::const_iterator ArgIt = ArgList.begin();
240 for( ; ArgIt != ArgList.end() ; ++ArgIt) { // for each argument
241 addInterference( *ArgIt, InSet, false ); // add interferences between
242 // args and LVars at start
244 cout << " - %% adding interference for argument ";
245 printValue( (const Value *) *ArgIt); cout << endl;
251 //----------------------------------------------------------------------------
252 // This method is called after register allocation is complete to set the
253 // allocated reisters in the machine code. This code will add register numbers
254 // to MachineOperands that contain a Value.
255 //----------------------------------------------------------------------------
257 void PhyRegAlloc::updateMachineCode()
260 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
262 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
264 // get the iterator for machine instructions
265 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
266 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
268 // iterate over all the machine instructions in BB
269 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
271 MachineInstr *MInst = *MInstIterator;
274 // If there are instructions before to be added, add them now
275 // ***TODO: Add InstrnsAfter as well
276 if( AddedInstrMap[ MInst ] ) {
278 vector<MachineInstr *> &IBef =
279 (AddedInstrMap[MInst])->InstrnsBefore;
281 if( ! IBef.empty() ) {
283 vector<MachineInstr *>::iterator AdIt;
285 for( AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt ) {
287 cout << "*ADDED instr opcode: ";
288 cout << TargetInstrDescriptors[(*AdIt)->getOpCode()].opCodeString;
291 MInstIterator = MIVec.insert( MInstIterator, *AdIt );
297 // restart from the topmost instruction added
298 //MInst = *MInstIterator;
304 //for(MachineInstr::val_op_const_iterator OpI(MInst);!OpI.done();++OpI) {
306 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
308 MachineOperand& Op = MInst->getOperand(OpNum);
310 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
311 Op.getOperandType() == MachineOperand::MO_CCRegister) {
313 const Value *const Val = Op.getVRegValue();
315 // delete this condition checking later (must assert if Val is null)
318 cout << "Warning: NULL Value found for operand" << endl;
321 assert( Val && "Value is NULL");
323 const LiveRange *const LR = LRI.getLiveRangeForValue(Val);
327 // nothing to worry if it's a const or a label
330 cout << "*NO LR for inst opcode: ";
331 cout << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
334 Op.setRegForValue( 1000 ); // mark register as invalid
337 if( ((Val->getType())->isLabelType()) ||
338 (Val->getValueType() == Value::ConstantVal) )
341 // The return address is not explicitly defined within a
342 // method. So, it is not colored by usual algorithm. In that case
345 //else if (TM.getInstrInfo().isCall(MInst->getOpCode()))
346 //Op.setRegForValue( MRI.getCallAddressReg() );
348 //TM.getInstrInfo().isReturn(MInst->getOpCode())
349 else if(TM.getInstrInfo().isReturn(MInst->getOpCode()) ) {
350 if (DEBUG_RA) cout << endl << "RETURN found" << endl;
351 Op.setRegForValue( MRI.getReturnAddressReg() );
355 if (Val->getValueType() == Value::InstructionVal)
357 cout << "!Warning: No LiveRange for: ";
358 printValue( Val); cout << " Type: " << Val->getValueType();
359 cout << " RegVal=" << Op.getAllocatedRegNum() << endl;
367 unsigned RCID = (LR->getRegClass())->getID();
369 Op.setRegForValue( MRI.getUnifiedRegNum(RCID, LR->getColor()) );
371 int RegNum = MRI.getUnifiedRegNum(RCID, LR->getColor());
384 //----------------------------------------------------------------------------
385 // This method prints the code with registers after register allocation is
387 //----------------------------------------------------------------------------
388 void PhyRegAlloc::printMachineCode()
391 cout << endl << ";************** Method ";
392 cout << Meth->getName() << " *****************" << endl;
394 Method::const_iterator BBI = Meth->begin(); // random iterator for BBs
396 for( ; BBI != Meth->end(); ++BBI) { // traverse BBs in random order
398 cout << endl ; printLabel( *BBI); cout << ": ";
400 // get the iterator for machine instructions
401 MachineCodeForBasicBlock& MIVec = (*BBI)->getMachineInstrVec();
402 MachineCodeForBasicBlock::iterator MInstIterator = MIVec.begin();
404 // iterate over all the machine instructions in BB
405 for( ; MInstIterator != MIVec.end(); ++MInstIterator) {
407 MachineInstr *const MInst = *MInstIterator;
410 cout << endl << "\t";
411 cout << TargetInstrDescriptors[MInst->getOpCode()].opCodeString;
414 //for(MachineInstr::val_op_const_iterator OpI(MInst);!OpI.done();++OpI) {
416 for(unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
418 MachineOperand& Op = MInst->getOperand(OpNum);
420 if( Op.getOperandType() == MachineOperand::MO_VirtualRegister ||
421 Op.getOperandType() == MachineOperand::MO_CCRegister ||
422 Op.getOperandType() == MachineOperand::MO_PCRelativeDisp ) {
424 const Value *const Val = Op.getVRegValue () ;
425 // ****this code is temporary till NULL Values are fixed
427 cout << "\t<*NULL*>";
431 // if a label or a constant
432 if( (Val->getValueType() == Value::BasicBlockVal) ) {
434 cout << "\t"; printLabel( Op.getVRegValue () );
437 // else it must be a register value
438 const int RegNum = Op.getAllocatedRegNum();
440 //if( RegNum != 1000)
442 cout << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
443 // else cout << "\t<*NoReg*>";
448 else if(Op.getOperandType() == MachineOperand::MO_MachineRegister) {
449 cout << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
453 cout << "\t" << Op; // use dump field
466 //----------------------------------------------------------------------------
468 //----------------------------------------------------------------------------
470 void PhyRegAlloc::colorCallRetArgs()
473 CallRetInstrListType &CallRetInstList = LRI.getCallRetInstrList();
474 CallRetInstrListType::const_iterator It = CallRetInstList.begin();
476 for( ; It != CallRetInstList.end(); ++It ) {
478 const Instruction *const CallRetI = *It;
479 unsigned OpCode = (CallRetI)->getOpcode();
481 const MachineInstr *CRMI = *((CallRetI->getMachineInstrVec()).begin());
484 assert( (TM.getInstrInfo().isReturn(CRMI->getOpCode()) ||
485 TM.getInstrInfo().isCall(CRMI->getOpCode()) )
486 && "First Machine Instruction is not a Call/Retrunr" );
488 // get the added instructions for this Call/Ret instruciton
489 AddedInstrns *AI = AddedInstrMap[ CRMI ];
491 AI = new AddedInstrns();
492 AddedInstrMap[ CRMI ] = AI;
495 if( (OpCode == Instruction::Call) )
496 MRI.colorCallArgs( (CallInst *) CallRetI, LRI, AI );
499 else if (OpCode == Instruction::Ret )
500 MRI.colorRetValue( (ReturnInst *) CallRetI, LRI, AI );
503 else assert( 0 && "Non Call/Ret instrn in CallRetInstrList\n" );
509 //----------------------------------------------------------------------------
511 //----------------------------------------------------------------------------
512 void PhyRegAlloc::colorIncomingArgs()
514 const BasicBlock *const FirstBB = Meth->front();
515 const MachineInstr *FirstMI = *((FirstBB->getMachineInstrVec()).begin());
516 assert( FirstMI && "No machine instruction in entry BB");
518 AddedInstrns *AI = AddedInstrMap[ FirstMI ];
520 AI = new AddedInstrns();
521 AddedInstrMap[ FirstMI ] = AI;
524 MRI.colorMethodArgs(Meth, LRI, AI );
528 //----------------------------------------------------------------------------
529 // Used to generate a label for a basic block
530 //----------------------------------------------------------------------------
531 void PhyRegAlloc::printLabel(const Value *const Val)
534 cout << Val->getName();
536 cout << "Label" << Val;
540 //----------------------------------------------------------------------------
541 // The entry pont to Register Allocation
542 //----------------------------------------------------------------------------
544 void PhyRegAlloc::allocateRegisters()
547 // make sure that we put all register classes into the RegClassList
548 // before we call constructLiveRanges (now done in the constructor of
549 // PhyRegAlloc class).
551 constructLiveRanges(); // create LR info
554 LRI.printLiveRanges();
556 createIGNodeListsAndIGs(); // create IGNode list and IGs
558 buildInterferenceGraphs(); // build IGs in all reg classes
562 // print all LRs in all reg classes
563 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
564 RegClassList[ rc ]->printIGNodeList();
566 // print IGs in all register classes
567 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
568 RegClassList[ rc ]->printIG();
571 LRI.coalesceLRs(); // coalesce all live ranges
574 // print all LRs in all reg classes
575 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
576 RegClassList[ rc ]->printIGNodeList();
578 // print IGs in all register classes
579 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
580 RegClassList[ rc ]->printIG();
583 // color all register classes
584 for( unsigned int rc=0; rc < NumOfRegClasses ; rc++)
585 RegClassList[ rc ]->colorAllRegs();
588 // color incoming args and call args
595 // PrintMachineInstructions(Meth);
596 printMachineCode(); // only for DEBUGGING