1 //===-- PhyRegAlloc.cpp ---------------------------------------------------===//
3 // Register allocation for LLVM.
5 //===----------------------------------------------------------------------===//
7 #include "llvm/CodeGen/RegisterAllocation.h"
8 #include "RegAllocCommon.h"
10 #include "llvm/CodeGen/IGNode.h"
11 #include "llvm/CodeGen/PhyRegAlloc.h"
12 #include "llvm/CodeGen/MachineInstrBuilder.h"
13 #include "llvm/CodeGen/MachineInstrAnnot.h"
14 #include "llvm/CodeGen/MachineFunction.h"
15 #include "llvm/CodeGen/MachineFunctionInfo.h"
16 #include "llvm/CodeGen/FunctionLiveVarInfo.h"
17 #include "llvm/CodeGen/InstrSelection.h"
18 #include "llvm/Analysis/LoopInfo.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/TargetFrameInfo.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetRegInfo.h"
23 #include "llvm/Function.h"
24 #include "llvm/Type.h"
25 #include "llvm/iOther.h"
26 #include "Support/STLExtras.h"
27 #include "Support/CommandLine.h"
32 RegAllocDebugLevel_t DEBUG_RA;
34 static cl::opt<RegAllocDebugLevel_t, true>
35 DRA_opt("dregalloc", cl::Hidden, cl::location(DEBUG_RA),
36 cl::desc("enable register allocation debugging information"),
38 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
39 clEnumValN(RA_DEBUG_Results, "y", "debug output for allocation results"),
40 clEnumValN(RA_DEBUG_Coloring, "c", "debug output for graph coloring step"),
41 clEnumValN(RA_DEBUG_Interference,"ig","debug output for interference graphs"),
42 clEnumValN(RA_DEBUG_LiveRanges , "lr","debug output for live ranges"),
43 clEnumValN(RA_DEBUG_Verbose, "v", "extra debug output"),
46 //----------------------------------------------------------------------------
47 // RegisterAllocation pass front end...
48 //----------------------------------------------------------------------------
50 class RegisterAllocator : public FunctionPass {
51 TargetMachine &Target;
53 inline RegisterAllocator(TargetMachine &T) : Target(T) {}
55 const char *getPassName() const { return "Register Allocation"; }
57 bool runOnFunction(Function &F) {
59 cerr << "\n********* Function "<< F.getName() << " ***********\n";
61 PhyRegAlloc PRA(&F, Target, &getAnalysis<FunctionLiveVarInfo>(),
62 &getAnalysis<LoopInfo>());
63 PRA.allocateRegisters();
65 if (DEBUG_RA) cerr << "\nRegister allocation complete!\n";
69 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
70 AU.addRequired<LoopInfo>();
71 AU.addRequired<FunctionLiveVarInfo>();
76 Pass *getRegisterAllocator(TargetMachine &T) {
77 return new RegisterAllocator(T);
80 //----------------------------------------------------------------------------
81 // Constructor: Init local composite objects and create register classes.
82 //----------------------------------------------------------------------------
83 PhyRegAlloc::PhyRegAlloc(Function *F, const TargetMachine& tm,
84 FunctionLiveVarInfo *Lvi, LoopInfo *LDC)
85 : TM(tm), Fn(F), MF(MachineFunction::get(F)), LVI(Lvi),
86 LRI(F, tm, RegClassList), MRI(tm.getRegInfo()),
87 NumOfRegClasses(MRI.getNumOfRegClasses()), LoopDepthCalc(LDC) {
89 // create each RegisterClass and put in RegClassList
91 for (unsigned rc=0; rc != NumOfRegClasses; rc++)
92 RegClassList.push_back(new RegClass(F, &tm.getRegInfo(),
93 MRI.getMachineRegClass(rc)));
97 //----------------------------------------------------------------------------
98 // Destructor: Deletes register classes
99 //----------------------------------------------------------------------------
100 PhyRegAlloc::~PhyRegAlloc() {
101 for ( unsigned rc=0; rc < NumOfRegClasses; rc++)
102 delete RegClassList[rc];
104 AddedInstrMap.clear();
107 //----------------------------------------------------------------------------
108 // This method initally creates interference graphs (one in each reg class)
109 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
110 //----------------------------------------------------------------------------
111 void PhyRegAlloc::createIGNodeListsAndIGs() {
112 if (DEBUG_RA >= RA_DEBUG_LiveRanges) cerr << "Creating LR lists ...\n";
115 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
118 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
120 for (; HMI != HMIEnd ; ++HMI ) {
122 LiveRange *L = HMI->second; // get the LiveRange
125 cerr << "\n**** ?!?WARNING: NULL LIVE RANGE FOUND FOR: "
126 << RAV(HMI->first) << "****\n";
130 // if the Value * is not null, and LR is not yet written to the IGNodeList
131 if (!(L->getUserIGNode()) ) {
132 RegClass *const RC = // RegClass of first value in the LR
133 RegClassList[ L->getRegClass()->getID() ];
134 RC->addLRToIG(L); // add this LR to an IG
140 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
141 RegClassList[rc]->createInterferenceGraph();
143 if (DEBUG_RA >= RA_DEBUG_LiveRanges) 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 //----------------------------------------------------------------------------
154 void PhyRegAlloc::addInterference(const Value *Def,
155 const ValueSet *LVSet,
158 ValueSet::const_iterator LIt = LVSet->begin();
160 // get the live range of instruction
162 const LiveRange *const LROfDef = LRI.getLiveRangeForValue( Def );
164 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
165 assert( IGNodeOfDef );
167 RegClass *const RCOfDef = LROfDef->getRegClass();
169 // for each live var in live variable set
171 for ( ; LIt != LVSet->end(); ++LIt) {
173 if (DEBUG_RA >= RA_DEBUG_Verbose)
174 cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
176 // get the live range corresponding to live var
178 LiveRange *LROfVar = LRI.getLiveRangeForValue(*LIt);
180 // LROfVar can be null if it is a const since a const
181 // doesn't have a dominating def - see Assumptions above
184 if (LROfDef != LROfVar) // do not set interf for same LR
185 if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
186 RCOfDef->setInterference( LROfDef, LROfVar);
192 //----------------------------------------------------------------------------
193 // For a call instruction, this method sets the CallInterference flag in
194 // the LR of each variable live int the Live Variable Set live after the
195 // call instruction (except the return value of the call instruction - since
196 // the return value does not interfere with that call itself).
197 //----------------------------------------------------------------------------
199 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
200 const ValueSet *LVSetAft) {
202 if (DEBUG_RA >= RA_DEBUG_Interference)
203 cerr << "\n For call inst: " << *MInst;
205 // for each live var in live variable set after machine inst
207 for (ValueSet::const_iterator LIt = LVSetAft->begin(), LEnd = LVSetAft->end();
208 LIt != LEnd; ++LIt) {
210 // get the live range corresponding to live var
212 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt );
214 // LR can be null if it is a const since a const
215 // doesn't have a dominating def - see Assumptions above
218 if (DEBUG_RA >= RA_DEBUG_Interference) {
219 cerr << "\n\tLR after Call: ";
222 LR->setCallInterference();
223 if (DEBUG_RA >= RA_DEBUG_Interference) {
224 cerr << "\n ++After adding call interference for LR: " ;
231 // Now find the LR of the return value of the call
232 // We do this because, we look at the LV set *after* the instruction
233 // to determine, which LRs must be saved across calls. The return value
234 // of the call is live in this set - but it does not interfere with call
235 // (i.e., we can allocate a volatile register to the return value)
237 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
239 if (const Value *RetVal = argDesc->getReturnValue()) {
240 LiveRange *RetValLR = LRI.getLiveRangeForValue( RetVal );
241 assert( RetValLR && "No LR for RetValue of call");
242 RetValLR->clearCallInterference();
245 // If the CALL is an indirect call, find the LR of the function pointer.
246 // That has a call interference because it conflicts with outgoing args.
247 if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
248 LiveRange *AddrValLR = LRI.getLiveRangeForValue( AddrVal );
249 assert( AddrValLR && "No LR for indirect addr val of call");
250 AddrValLR->setCallInterference();
258 //----------------------------------------------------------------------------
259 // This method will walk thru code and create interferences in the IG of
260 // each RegClass. Also, this method calculates the spill cost of each
261 // Live Range (it is done in this method to save another pass over the code).
262 //----------------------------------------------------------------------------
263 void PhyRegAlloc::buildInterferenceGraphs()
266 if (DEBUG_RA >= RA_DEBUG_Interference)
267 cerr << "Creating interference graphs ...\n";
269 unsigned BBLoopDepthCost;
270 for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end();
272 const MachineBasicBlock &MBB = *BBI;
273 const BasicBlock *BB = MBB.getBasicBlock();
275 // find the 10^(loop_depth) of this BB
277 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BB));
279 // get the iterator for machine instructions
281 MachineBasicBlock::const_iterator MII = MBB.begin();
283 // iterate over all the machine instructions in BB
285 for ( ; MII != MBB.end(); ++MII) {
286 const MachineInstr *MInst = *MII;
288 // get the LV set after the instruction
290 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BB);
291 bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
294 // set the isCallInterference flag of each live range wich extends
295 // accross this call instruction. This information is used by graph
296 // coloring algo to avoid allocating volatile colors to live ranges
297 // that span across calls (since they have to be saved/restored)
299 setCallInterferences(MInst, &LVSetAI);
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.isDefOnly() || OpI.isDefAndUse()) // create a new LR since 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 for (unsigned z=0; z < NumOfImpRefs; z++)
327 if (MInst->getImplicitOp(z).opIsDefOnly() ||
328 MInst->getImplicitOp(z).opIsDefAndUse())
329 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
331 } // for all machine instructions in BB
332 } // for all BBs in function
335 // add interferences for function arguments. Since there are no explict
336 // defs in the function for args, we have to add them manually
338 addInterferencesForArgs();
340 if (DEBUG_RA >= RA_DEBUG_Interference)
341 cerr << "Interference graphs calculated!\n";
346 //--------------------------------------------------------------------------
347 // Pseudo instructions will be exapnded to multiple instructions by the
348 // assembler. Consequently, all the opernds must get distinct registers.
349 // Therefore, we mark all operands of a pseudo instruction as they interfere
351 //--------------------------------------------------------------------------
352 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
354 bool setInterf = false;
356 // iterate over MI operands to find defs
358 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
359 ItE = MInst->end(); It1 != ItE; ++It1) {
360 const LiveRange *LROfOp1 = LRI.getLiveRangeForValue(*It1);
361 assert((LROfOp1 || !It1.isUseOnly())&& "No LR for Def in PSEUDO insruction");
363 MachineInstr::const_val_op_iterator It2 = It1;
364 for (++It2; It2 != ItE; ++It2) {
365 const LiveRange *LROfOp2 = LRI.getLiveRangeForValue(*It2);
368 RegClass *RCOfOp1 = LROfOp1->getRegClass();
369 RegClass *RCOfOp2 = LROfOp2->getRegClass();
371 if (RCOfOp1 == RCOfOp2 ){
372 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
376 } // for all other defs in machine instr
377 } // for all operands in an instruction
379 if (!setInterf && MInst->getNumOperands() > 2) {
380 cerr << "\nInterf not set for any operand in pseudo instr:\n";
382 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
388 //----------------------------------------------------------------------------
389 // This method will add interferences for incoming arguments to a function.
390 //----------------------------------------------------------------------------
392 void PhyRegAlloc::addInterferencesForArgs() {
393 // get the InSet of root BB
394 const ValueSet &InSet = LVI->getInSetOfBB(&Fn->front());
396 for (Function::const_aiterator AI = Fn->abegin(); AI != Fn->aend(); ++AI) {
397 // add interferences between args and LVars at start
398 addInterference(AI, &InSet, false);
400 if (DEBUG_RA >= RA_DEBUG_Interference)
401 cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
406 //----------------------------------------------------------------------------
407 // This method is called after register allocation is complete to set the
408 // allocated reisters in the machine code. This code will add register numbers
409 // to MachineOperands that contain a Value. Also it calls target specific
410 // methods to produce caller saving instructions. At the end, it adds all
411 // additional instructions produced by the register allocator to the
412 // instruction stream.
413 //----------------------------------------------------------------------------
415 //-----------------------------
416 // Utility functions used below
417 //-----------------------------
419 InsertBefore(MachineInstr* newMI,
420 MachineBasicBlock& MBB,
421 MachineBasicBlock::iterator& MII)
423 MII = MBB.insert(MII, newMI);
428 InsertAfter(MachineInstr* newMI,
429 MachineBasicBlock& MBB,
430 MachineBasicBlock::iterator& MII)
432 ++MII; // insert before the next instruction
433 MII = MBB.insert(MII, newMI);
437 DeleteInstruction(MachineBasicBlock& MBB,
438 MachineBasicBlock::iterator& MII)
440 MII = MBB.erase(MII);
444 SubstituteInPlace(MachineInstr* newMI,
445 MachineBasicBlock& MBB,
446 MachineBasicBlock::iterator MII)
452 PrependInstructions(vector<MachineInstr *> &IBef,
453 MachineBasicBlock& MBB,
454 MachineBasicBlock::iterator& MII,
455 const std::string& msg)
459 MachineInstr* OrigMI = *MII;
460 std::vector<MachineInstr *>::iterator AdIt;
461 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
464 if (OrigMI) cerr << "For MInst:\n " << *OrigMI;
465 cerr << msg << "PREPENDed instr:\n " << **AdIt << "\n";
467 InsertBefore(*AdIt, MBB, MII);
473 AppendInstructions(std::vector<MachineInstr *> &IAft,
474 MachineBasicBlock& MBB,
475 MachineBasicBlock::iterator& MII,
476 const std::string& msg)
480 MachineInstr* OrigMI = *MII;
481 std::vector<MachineInstr *>::iterator AdIt;
482 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
485 if (OrigMI) cerr << "For MInst:\n " << *OrigMI;
486 cerr << msg << "APPENDed instr:\n " << **AdIt << "\n";
488 InsertAfter(*AdIt, MBB, MII);
493 static bool MarkAllocatedRegs(MachineInstr* MInst,
495 const TargetRegInfo& MRI)
497 bool instrNeedsSpills = false;
499 // First, set the registers for operands in the machine instruction
500 // if a register was successfully allocated. Do this first because we
501 // will need to know which registers are already used by this instr'n.
503 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
505 MachineOperand& Op = MInst->getOperand(OpNum);
506 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
507 Op.getType() == MachineOperand::MO_CCRegister)
509 const Value *const Val = Op.getVRegValue();
510 if (const LiveRange* LR = LRI.getLiveRangeForValue(Val)) {
511 // Remember if any operand needs spilling
512 instrNeedsSpills |= LR->isMarkedForSpill();
514 // An operand may have a color whether or not it needs spilling
516 MInst->SetRegForOperand(OpNum,
517 MRI.getUnifiedRegNum(LR->getRegClass()->getID(),
521 } // for each operand
523 return instrNeedsSpills;
526 void PhyRegAlloc::updateInstruction(MachineBasicBlock::iterator& MII,
527 MachineBasicBlock &MBB)
529 MachineInstr* MInst = *MII;
530 unsigned Opcode = MInst->getOpCode();
532 // Reset tmp stack positions so they can be reused for each machine instr.
533 MF.getInfo()->popAllTempValues();
535 // Mark the operands for which regs have been allocated.
536 bool instrNeedsSpills = MarkAllocatedRegs(*MII, LRI, MRI);
539 // Mark that the operands have been updated. Later,
540 // setRelRegsUsedByThisInst() is called to find registers used by each
541 // MachineInst, and it should not be used for an instruction until
542 // this is done. This flag just serves as a sanity check.
543 OperandsColoredMap[MInst] = true;
546 // Now insert caller-saving code before/after the call.
547 // Do this before inserting spill code since some registers must be
548 // used by save/restore and spill code should not use those registers.
550 if (TM.getInstrInfo().isCall(Opcode)) {
551 AddedInstrns &AI = AddedInstrMap[MInst];
552 insertCallerSavingCode(AI.InstrnsBefore, AI.InstrnsAfter, MInst,
553 MBB.getBasicBlock());
556 // Now insert spill code for remaining operands not allocated to
557 // registers. This must be done even for call return instructions
558 // since those are not handled by the special code above.
559 if (instrNeedsSpills)
560 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
562 MachineOperand& Op = MInst->getOperand(OpNum);
563 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
564 Op.getType() == MachineOperand::MO_CCRegister)
566 const Value* Val = Op.getVRegValue();
567 if (const LiveRange *LR = LRI.getLiveRangeForValue(Val))
568 if (LR->isMarkedForSpill())
569 insertCode4SpilledLR(LR, MII, MBB, OpNum);
571 } // for each operand
574 void PhyRegAlloc::updateMachineCode()
576 // Insert any instructions needed at method entry
577 MachineBasicBlock::iterator MII = MF.front().begin();
578 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MF.front(), MII,
579 "At function entry: \n");
580 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
581 "InstrsAfter should be unnecessary since we are just inserting at "
582 "the function entry point here.");
584 for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end();
587 MachineBasicBlock &MBB = *BBI;
589 // Iterate over all machine instructions in BB and mark operands with
590 // their assigned registers or insert spill code, as appropriate.
591 // Also, fix operands of call/return instructions.
592 for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
593 if (! TM.getInstrInfo().isDummyPhiInstr((*MII)->getOpCode()))
594 updateInstruction(MII, MBB);
596 // Now, move code out of delay slots of branches and returns if needed.
597 // (Also, move "after" code from calls to the last delay slot instruction.)
598 // Moving code out of delay slots is needed in 2 situations:
599 // (1) If this is a branch and it needs instructions inserted after it,
600 // move any existing instructions out of the delay slot so that the
601 // instructions can go into the delay slot. This only supports the
602 // case that #instrsAfter <= #delay slots.
604 // (2) If any instruction in the delay slot needs
605 // instructions inserted, move it out of the delay slot and before the
606 // branch because putting code before or after it would be VERY BAD!
608 // If the annul bit of the branch is set, neither of these is legal!
609 // If so, we need to handle spill differently but annulling is not yet used.
611 for (MachineBasicBlock::iterator MII = MBB.begin();
612 MII != MBB.end(); ++MII)
613 if (unsigned delaySlots =
614 TM.getInstrInfo().getNumDelaySlots((*MII)->getOpCode()))
616 MachineInstr *MInst = *MII, *DelaySlotMI = *(MII+1);
618 // Check the 2 conditions above:
619 // (1) Does a branch need instructions added after it?
620 // (2) O/w does delay slot instr. need instrns before or after?
621 bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
622 TM.getInstrInfo().isReturn(MInst->getOpCode()));
623 bool cond1 = (isBranch &&
624 AddedInstrMap.count(MInst) &&
625 AddedInstrMap[MInst].InstrnsAfter.size() > 0);
626 bool cond2 = (AddedInstrMap.count(DelaySlotMI) &&
627 (AddedInstrMap[DelaySlotMI].InstrnsBefore.size() > 0 ||
628 AddedInstrMap[DelaySlotMI].InstrnsAfter.size() > 0));
632 assert((MInst->getOpCodeFlags() & AnnulFlag) == 0 &&
633 "FIXME: Moving an annulled delay slot instruction!");
634 assert(delaySlots==1 &&
635 "InsertBefore does not yet handle >1 delay slots!");
636 InsertBefore(DelaySlotMI, MBB, MII); // MII pts back to branch
638 // In case (1), delete it and don't replace with anything!
639 // Otherwise (i.e., case (2) only) replace it with a NOP.
641 DeleteInstruction(MBB, ++MII); // MII now points to next inst.
642 --MII; // reset MII for ++MII of loop
645 SubstituteInPlace(BuildMI(TM.getInstrInfo().getNOPOpCode(),1),
646 MBB, MII+1); // replace with NOP
649 cerr << "\nRegAlloc: Moved instr. with added code: "
651 << " out of delay slots of instr: " << *MInst;
655 // For non-branch instr with delay slots (probably a call), move
656 // InstrAfter to the instr. in the last delay slot.
657 move2DelayedInstr(*MII, *(MII+delaySlots));
660 // Finally iterate over all instructions in BB and insert before/after
662 for (MachineBasicBlock::iterator MII=MBB.begin(); MII != MBB.end(); ++MII) {
663 MachineInstr *MInst = *MII;
665 // do not process Phis
666 if (TM.getInstrInfo().isDummyPhiInstr(MInst->getOpCode()))
669 // if there are any added instructions...
670 if (AddedInstrMap.count(MInst)) {
671 AddedInstrns &CallAI = AddedInstrMap[MInst];
674 bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
675 TM.getInstrInfo().isReturn(MInst->getOpCode()));
677 AddedInstrMap[MInst].InstrnsAfter.size() <=
678 TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) &&
679 "Cannot put more than #delaySlots instrns after "
680 "branch or return! Need to handle temps differently.");
684 // Temporary sanity checking code to detect whether the same machine
685 // instruction is ever inserted twice before/after a call.
686 // I suspect this is happening but am not sure. --Vikram, 7/1/03.
688 std::set<const MachineInstr*> instrsSeen;
689 for (int i = 0, N = CallAI.InstrnsBefore.size(); i < N; ++i) {
690 assert(instrsSeen.count(CallAI.InstrnsBefore[i]) == 0 &&
691 "Duplicate machine instruction in InstrnsBefore!");
692 instrsSeen.insert(CallAI.InstrnsBefore[i]);
694 for (int i = 0, N = CallAI.InstrnsAfter.size(); i < N; ++i) {
695 assert(instrsSeen.count(CallAI.InstrnsAfter[i]) == 0 &&
696 "Duplicate machine instruction in InstrnsBefore/After!");
697 instrsSeen.insert(CallAI.InstrnsAfter[i]);
701 // Now add the instructions before/after this MI.
702 // We do this here to ensure that spill for an instruction is inserted
703 // as close as possible to an instruction (see above insertCode4Spill)
705 if (! CallAI.InstrnsBefore.empty())
706 PrependInstructions(CallAI.InstrnsBefore, MBB, MII,"");
708 if (! CallAI.InstrnsAfter.empty())
709 AppendInstructions(CallAI.InstrnsAfter, MBB, MII,"");
711 } // if there are any added instructions
713 } // for each machine instruction
720 //----------------------------------------------------------------------------
721 // This method inserts spill code for AN operand whose LR was spilled.
722 // This method may be called several times for a single machine instruction
723 // if it contains many spilled operands. Each time it is called, it finds
724 // a register which is not live at that instruction and also which is not
725 // used by other spilled operands of the same instruction. Then it uses
726 // this register temporarily to accomodate the spilled value.
727 //----------------------------------------------------------------------------
729 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
730 MachineBasicBlock::iterator& MII,
731 MachineBasicBlock &MBB,
732 const unsigned OpNum) {
734 MachineInstr *MInst = *MII;
735 const BasicBlock *BB = MBB.getBasicBlock();
737 assert((! TM.getInstrInfo().isCall(MInst->getOpCode()) || OpNum == 0) &&
738 "Outgoing arg of a call must be handled elsewhere (func arg ok)");
739 assert(! TM.getInstrInfo().isReturn(MInst->getOpCode()) &&
740 "Return value of a ret must be handled elsewhere");
742 MachineOperand& Op = MInst->getOperand(OpNum);
743 bool isDef = Op.opIsDefOnly();
744 bool isDefAndUse = Op.opIsDefAndUse();
745 unsigned RegType = MRI.getRegTypeForLR(LR);
746 int SpillOff = LR->getSpillOffFromFP();
747 RegClass *RC = LR->getRegClass();
749 // Get the live-variable set to find registers free before this instr.
750 // If this instr. is in the delay slot of a branch or return, use the live
751 // var set before that branch or return -- we don't want to trample those!
753 MachineInstr *LiveBeforeThisMI = MInst;
754 if (MII != MBB.begin()) {
755 MachineInstr *PredMI = *(MII-1);
756 if (unsigned DS = TM.getInstrInfo().getNumDelaySlots(PredMI->getOpCode())) {
757 assert(DS == 1 && "Only checking immediate pred. for delay slots!");
758 LiveBeforeThisMI = PredMI;
761 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(LiveBeforeThisMI,BB);
763 MF.getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType) );
765 vector<MachineInstr*> MIBef, MIAft;
766 vector<MachineInstr*> AdIMid;
768 // Choose a register to hold the spilled value, if one was not preallocated.
769 // This may insert code before and after MInst to free up the value. If so,
770 // this code should be first/last in the spill sequence before/after MInst.
771 int TmpRegU=(LR->hasColor()
772 ? MRI.getUnifiedRegNum(LR->getRegClass()->getID(),LR->getColor())
773 : getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef,MIAft));
775 // Set the operand first so that it this register does not get used
776 // as a scratch register for later calls to getUsableUniRegAtMI below
777 MInst->SetRegForOperand(OpNum, TmpRegU);
779 // get the added instructions for this instruction
780 AddedInstrns &AI = AddedInstrMap[MInst];
782 // We may need a scratch register to copy the spilled value to/from memory.
783 // This may itself have to insert code to free up a scratch register.
784 // Any such code should go before (after) the spill code for a load (store).
785 // The scratch reg is not marked as used because it is only used
786 // for the copy and not used across MInst.
787 int scratchRegType = -1;
789 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
791 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
792 MInst, MIBef, MIAft);
793 assert(scratchReg != MRI.getInvalidRegNum());
796 if (!isDef || isDefAndUse) {
797 // for a USE, we have to load the value of LR from stack to a TmpReg
798 // and use the TmpReg as one operand of instruction
800 // actual loading instruction(s)
801 MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU,
802 RegType, scratchReg);
804 // the actual load should be after the instructions to free up TmpRegU
805 MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
809 if (isDef || isDefAndUse) { // if this is a Def
810 // for a DEF, we have to store the value produced by this instruction
811 // on the stack position allocated for this LR
813 // actual storing instruction(s)
814 MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff,
815 RegType, scratchReg);
817 MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
820 // Finally, insert the entire spill code sequences before/after MInst
821 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
822 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
825 cerr << "\nFor Inst:\n " << *MInst;
826 cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
827 cerr << "; added Instructions:";
828 for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
829 for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
835 //----------------------------------------------------------------------------
836 // This method inserts caller saving/restoring instructons before/after
837 // a call machine instruction. The caller saving/restoring instructions are
839 // ** caller saving instructions
840 // other instructions inserted for the call by ColorCallArg
842 // other instructions inserted for the call ColorCallArg
843 // ** caller restoring instructions
844 //----------------------------------------------------------------------------
847 PhyRegAlloc::insertCallerSavingCode(std::vector<MachineInstr*> &instrnsBefore,
848 std::vector<MachineInstr*> &instrnsAfter,
849 MachineInstr *CallMI,
850 const BasicBlock *BB)
852 assert(TM.getInstrInfo().isCall(CallMI->getOpCode()));
854 // has set to record which registers were saved/restored
856 hash_set<unsigned> PushedRegSet;
858 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
860 // if the call is to a instrumentation function, do not insert save and
861 // restore instructions the instrumentation function takes care of save
862 // restore for volatile regs.
864 // FIXME: this should be made general, not specific to the reoptimizer!
866 const Function *Callee = argDesc->getCallInst()->getCalledFunction();
867 bool isLLVMFirstTrigger = Callee && Callee->getName() == "llvm_first_trigger";
869 // Now check if the call has a return value (using argDesc) and if so,
870 // find the LR of the TmpInstruction representing the return value register.
871 // (using the last or second-last *implicit operand* of the call MI).
872 // Insert it to to the PushedRegSet since we must not save that register
873 // and restore it after the call.
874 // We do this because, we look at the LV set *after* the instruction
875 // to determine, which LRs must be saved across calls. The return value
876 // of the call is live in this set - but we must not save/restore it.
878 if (const Value *origRetVal = argDesc->getReturnValue()) {
879 unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
880 (argDesc->getIndirectFuncPtr()? 1 : 2));
881 const TmpInstruction* tmpRetVal =
882 cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
883 assert(tmpRetVal->getOperand(0) == origRetVal &&
884 tmpRetVal->getType() == origRetVal->getType() &&
885 "Wrong implicit ref?");
886 LiveRange *RetValLR = LRI.getLiveRangeForValue(tmpRetVal);
887 assert(RetValLR && "No LR for RetValue of call");
889 if (! RetValLR->isMarkedForSpill())
890 PushedRegSet.insert(MRI.getUnifiedRegNum(RetValLR->getRegClassID(),
891 RetValLR->getColor()));
894 const ValueSet &LVSetAft = LVI->getLiveVarSetAfterMInst(CallMI, BB);
895 ValueSet::const_iterator LIt = LVSetAft.begin();
897 // for each live var in live variable set after machine inst
898 for( ; LIt != LVSetAft.end(); ++LIt) {
900 // get the live range corresponding to live var
901 LiveRange *const LR = LRI.getLiveRangeForValue(*LIt);
903 // LR can be null if it is a const since a const
904 // doesn't have a dominating def - see Assumptions above
907 if(! LR->isMarkedForSpill()) {
909 assert(LR->hasColor() && "LR is neither spilled nor colored?");
910 unsigned RCID = LR->getRegClassID();
911 unsigned Color = LR->getColor();
913 if (MRI.isRegVolatile(RCID, Color) ) {
915 //if the function is special LLVM function,
916 //And the register is not modified by call, don't save and restore
917 if (isLLVMFirstTrigger && !MRI.modifiedByCall(RCID, Color))
920 // if the value is in both LV sets (i.e., live before and after
921 // the call machine instruction)
923 unsigned Reg = MRI.getUnifiedRegNum(RCID, Color);
925 if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
927 // if we haven't already pushed that register
929 unsigned RegType = MRI.getRegTypeForLR(LR);
931 // Now get two instructions - to push on stack and pop from stack
932 // and add them to InstrnsBefore and InstrnsAfter of the
936 MF.getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
938 //---- Insert code for pushing the reg on stack ----------
940 std::vector<MachineInstr*> AdIBef, AdIAft;
942 // We may need a scratch register to copy the saved value
943 // to/from memory. This may itself have to insert code to
944 // free up a scratch register. Any such code should go before
945 // the save code. The scratch register, if any, is by default
946 // temporary and not "used" by the instruction unless the
947 // copy code itself decides to keep the value in the scratch reg.
948 int scratchRegType = -1;
950 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
951 { // Find a register not live in the LVSet before CallMI
952 const ValueSet &LVSetBef =
953 LVI->getLiveVarSetBeforeMInst(CallMI, BB);
954 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
955 CallMI, AdIBef, AdIAft);
956 assert(scratchReg != MRI.getInvalidRegNum());
959 if (AdIBef.size() > 0)
960 instrnsBefore.insert(instrnsBefore.end(),
961 AdIBef.begin(), AdIBef.end());
963 MRI.cpReg2MemMI(instrnsBefore, Reg, MRI.getFramePointer(),
964 StackOff, RegType, scratchReg);
966 if (AdIAft.size() > 0)
967 instrnsBefore.insert(instrnsBefore.end(),
968 AdIAft.begin(), AdIAft.end());
970 //---- Insert code for popping the reg from the stack ----------
975 // We may need a scratch register to copy the saved value
976 // from memory. This may itself have to insert code to
977 // free up a scratch register. Any such code should go
978 // after the save code. As above, scratch is not marked "used".
982 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
983 { // Find a register not live in the LVSet after CallMI
984 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetAft,
985 CallMI, AdIBef, AdIAft);
986 assert(scratchReg != MRI.getInvalidRegNum());
989 if (AdIBef.size() > 0)
990 instrnsAfter.insert(instrnsAfter.end(),
991 AdIBef.begin(), AdIBef.end());
993 MRI.cpMem2RegMI(instrnsAfter, MRI.getFramePointer(), StackOff,
994 Reg, RegType, scratchReg);
996 if (AdIAft.size() > 0)
997 instrnsAfter.insert(instrnsAfter.end(),
998 AdIAft.begin(), AdIAft.end());
1000 PushedRegSet.insert(Reg);
1003 std::cerr << "\nFor call inst:" << *CallMI;
1004 std::cerr << " -inserted caller saving instrs: Before:\n\t ";
1005 for_each(instrnsBefore.begin(), instrnsBefore.end(),
1006 std::mem_fun(&MachineInstr::dump));
1007 std::cerr << " -and After:\n\t ";
1008 for_each(instrnsAfter.begin(), instrnsAfter.end(),
1009 std::mem_fun(&MachineInstr::dump));
1011 } // if not already pushed
1013 } // if LR has a volatile color
1015 } // if LR has color
1017 } // if there is a LR for Var
1019 } // for each value in the LV set after instruction
1023 //----------------------------------------------------------------------------
1024 // We can use the following method to get a temporary register to be used
1025 // BEFORE any given machine instruction. If there is a register available,
1026 // this method will simply return that register and set MIBef = MIAft = NULL.
1027 // Otherwise, it will return a register and MIAft and MIBef will contain
1028 // two instructions used to free up this returned register.
1029 // Returned register number is the UNIFIED register number
1030 //----------------------------------------------------------------------------
1032 int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
1033 const ValueSet *LVSetBef,
1034 MachineInstr *MInst,
1035 std::vector<MachineInstr*>& MIBef,
1036 std::vector<MachineInstr*>& MIAft) {
1038 RegClass* RC = getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
1040 int RegU = getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
1043 // we couldn't find an unused register. Generate code to free up a reg by
1044 // saving it on stack and restoring after the instruction
1046 int TmpOff = MF.getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
1048 RegU = getUniRegNotUsedByThisInst(RC, RegType, MInst);
1050 // Check if we need a scratch register to copy this register to memory.
1051 int scratchRegType = -1;
1052 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
1054 int scratchReg = getUsableUniRegAtMI(scratchRegType, LVSetBef,
1055 MInst, MIBef, MIAft);
1056 assert(scratchReg != MRI.getInvalidRegNum());
1058 // We may as well hold the value in the scratch register instead
1059 // of copying it to memory and back. But we have to mark the
1060 // register as used by this instruction, so it does not get used
1061 // as a scratch reg. by another operand or anyone else.
1062 MInst->insertUsedReg(scratchReg);
1063 MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
1064 MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
1067 { // the register can be copied directly to/from memory so do it.
1068 MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
1069 MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
1077 //----------------------------------------------------------------------------
1078 // This method is called to get a new unused register that can be used
1079 // to accomodate a temporary value. This method may be called several times
1080 // for a single machine instruction. Each time it is called, it finds a
1081 // register which is not live at that instruction and also which is not used
1082 // by other spilled operands of the same instruction. Return register number
1083 // is relative to the register class, NOT the unified number.
1084 //----------------------------------------------------------------------------
1086 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
1088 const MachineInstr *MInst,
1089 const ValueSet* LVSetBef) {
1091 RC->clearColorsUsed(); // Reset array
1093 if (LVSetBef == NULL) {
1094 LVSetBef = &LVI->getLiveVarSetBeforeMInst(MInst);
1095 assert(LVSetBef != NULL && "Unable to get live-var set before MInst?");
1098 ValueSet::const_iterator LIt = LVSetBef->begin();
1100 // for each live var in live variable set after machine inst
1101 for ( ; LIt != LVSetBef->end(); ++LIt) {
1103 // get the live range corresponding to live var, and its RegClass
1104 LiveRange *const LRofLV = LRI.getLiveRangeForValue(*LIt );
1106 // LR can be null if it is a const since a const
1107 // doesn't have a dominating def - see Assumptions above
1108 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor())
1109 RC->markColorsUsed(LRofLV->getColor(),
1110 MRI.getRegTypeForLR(LRofLV), RegType);
1113 // It is possible that one operand of this MInst was already spilled
1114 // and it received some register temporarily. If that's the case,
1115 // it is recorded in machine operand. We must skip such registers.
1117 setRelRegsUsedByThisInst(RC, RegType, MInst);
1119 int unusedReg = RC->getUnusedColor(RegType); // find first unused color
1121 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
1127 //----------------------------------------------------------------------------
1128 // Get any other register in a register class, other than what is used
1129 // by operands of a machine instruction. Returns the unified reg number.
1130 //----------------------------------------------------------------------------
1131 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
1133 const MachineInstr *MInst) {
1134 RC->clearColorsUsed();
1136 setRelRegsUsedByThisInst(RC, RegType, MInst);
1138 // find the first unused color
1139 int unusedReg = RC->getUnusedColor(RegType);
1140 assert(unusedReg >= 0 &&
1141 "FATAL: No free register could be found in reg class!!");
1143 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
1147 //----------------------------------------------------------------------------
1148 // This method modifies the IsColorUsedArr of the register class passed to it.
1149 // It sets the bits corresponding to the registers used by this machine
1150 // instructions. Both explicit and implicit operands are set.
1151 //----------------------------------------------------------------------------
1153 static void markRegisterUsed(int RegNo, RegClass *RC, int RegType,
1154 const TargetRegInfo &TRI) {
1155 unsigned classId = 0;
1156 int classRegNum = TRI.getClassRegNum(RegNo, classId);
1157 if (RC->getID() == classId)
1158 RC->markColorsUsed(classRegNum, RegType, RegType);
1161 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC, int RegType,
1162 const MachineInstr *MI)
1164 assert(OperandsColoredMap[MI] == true &&
1165 "Illegal to call setRelRegsUsedByThisInst() until colored operands "
1166 "are marked for an instruction.");
1168 // Add the registers already marked as used by the instruction.
1169 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
1170 if (MI->getOperand(i).hasAllocatedReg())
1171 markRegisterUsed(MI->getOperand(i).getAllocatedRegNum(), RC, RegType,MRI);
1173 for (unsigned i = 0, e = MI->getNumImplicitRefs(); i != e; ++i)
1174 if (MI->getImplicitOp(i).hasAllocatedReg())
1175 markRegisterUsed(MI->getImplicitOp(i).getAllocatedRegNum(), RC,
1178 // The getRegsUsed() method returns the set of scratch registers that are used
1179 // to save values across the instruction (e.g., for saving state register
1181 const std::set<int> ®sUsed = MI->getRegsUsed();
1182 for (std::set<int>::iterator I = regsUsed.begin(),
1183 E = regsUsed.end(); I != E; ++I)
1184 markRegisterUsed(*I, RC, RegType, MRI);
1186 // If there are implicit references, mark their allocated regs as well
1188 for (unsigned z=0; z < MI->getNumImplicitRefs(); z++)
1189 if (const LiveRange*
1190 LRofImpRef = LRI.getLiveRangeForValue(MI->getImplicitRef(z)))
1191 if (LRofImpRef->hasColor())
1192 // this implicit reference is in a LR that received a color
1193 RC->markColorsUsed(LRofImpRef->getColor(),
1194 MRI.getRegTypeForLR(LRofImpRef), RegType);
1198 //----------------------------------------------------------------------------
1199 // If there are delay slots for an instruction, the instructions
1200 // added after it must really go after the delayed instruction(s).
1201 // So, we move the InstrAfter of that instruction to the
1202 // corresponding delayed instruction using the following method.
1203 //----------------------------------------------------------------------------
1205 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
1206 const MachineInstr *DelayedMI)
1209 cerr << "\nRegAlloc: Moved InstrnsAfter for: " << *OrigMI;
1210 cerr << " to last delay slot instrn: " << *DelayedMI;
1213 // "added after" instructions of the original instr
1214 std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
1216 // "added after" instructions of the delayed instr
1217 std::vector<MachineInstr *> &DelayedAft=AddedInstrMap[DelayedMI].InstrnsAfter;
1219 // go thru all the "added after instructions" of the original instruction
1220 // and append them to the "added after instructions" of the delayed
1222 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
1224 // empty the "added after instructions" of the original instruction
1228 //----------------------------------------------------------------------------
1229 // This method prints the code with registers after register allocation is
1231 //----------------------------------------------------------------------------
1232 void PhyRegAlloc::printMachineCode()
1235 cerr << "\n;************** Function " << Fn->getName()
1236 << " *****************\n";
1238 for (MachineFunction::iterator BBI = MF.begin(), BBE = MF.end();
1239 BBI != BBE; ++BBI) {
1240 cerr << "\n"; printLabel(BBI->getBasicBlock()); cerr << ": ";
1242 // get the iterator for machine instructions
1243 MachineBasicBlock& MBB = *BBI;
1244 MachineBasicBlock::iterator MII = MBB.begin();
1246 // iterate over all the machine instructions in BB
1247 for ( ; MII != MBB.end(); ++MII) {
1248 MachineInstr *MInst = *MII;
1251 cerr << TM.getInstrInfo().getName(MInst->getOpCode());
1253 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
1254 MachineOperand& Op = MInst->getOperand(OpNum);
1256 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
1257 Op.getType() == MachineOperand::MO_CCRegister /*||
1258 Op.getType() == MachineOperand::MO_PCRelativeDisp*/ ) {
1260 const Value *const Val = Op.getVRegValue () ;
1261 // ****this code is temporary till NULL Values are fixed
1263 cerr << "\t<*NULL*>";
1267 // if a label or a constant
1268 if (isa<BasicBlock>(Val)) {
1269 cerr << "\t"; printLabel( Op.getVRegValue () );
1271 // else it must be a register value
1272 const int RegNum = Op.getAllocatedRegNum();
1274 cerr << "\t" << "%" << MRI.getUnifiedRegName( RegNum );
1275 if (Val->hasName() )
1276 cerr << "(" << Val->getName() << ")";
1278 cerr << "(" << Val << ")";
1280 if (Op.opIsDefOnly() || Op.opIsDefAndUse())
1283 const LiveRange *LROfVal = LRI.getLiveRangeForValue(Val);
1285 if (LROfVal->hasSpillOffset() )
1290 else if (Op.getType() == MachineOperand::MO_MachineRegister) {
1291 cerr << "\t" << "%" << MRI.getUnifiedRegName(Op.getMachineRegNum());
1295 cerr << "\t" << Op; // use dump field
1300 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
1301 if (NumOfImpRefs > 0) {
1302 cerr << "\tImplicit:";
1304 for (unsigned z=0; z < NumOfImpRefs; z++)
1305 cerr << RAV(MInst->getImplicitRef(z)) << "\t";
1308 } // for all machine instructions
1318 //----------------------------------------------------------------------------
1320 //----------------------------------------------------------------------------
1321 void PhyRegAlloc::colorIncomingArgs()
1323 MRI.colorMethodArgs(Fn, LRI, AddedInstrAtEntry.InstrnsBefore,
1324 AddedInstrAtEntry.InstrnsAfter);
1328 //----------------------------------------------------------------------------
1329 // Used to generate a label for a basic block
1330 //----------------------------------------------------------------------------
1331 void PhyRegAlloc::printLabel(const Value *Val) {
1333 cerr << Val->getName();
1335 cerr << "Label" << Val;
1339 //----------------------------------------------------------------------------
1340 // This method calls setSugColorUsable method of each live range. This
1341 // will determine whether the suggested color of LR is really usable.
1342 // A suggested color is not usable when the suggested color is volatile
1343 // AND when there are call interferences
1344 //----------------------------------------------------------------------------
1346 void PhyRegAlloc::markUnusableSugColors()
1348 // hash map iterator
1349 LiveRangeMapType::const_iterator HMI = (LRI.getLiveRangeMap())->begin();
1350 LiveRangeMapType::const_iterator HMIEnd = (LRI.getLiveRangeMap())->end();
1352 for (; HMI != HMIEnd ; ++HMI ) {
1354 LiveRange *L = HMI->second; // get the LiveRange
1356 if (L->hasSuggestedColor()) {
1357 int RCID = L->getRegClass()->getID();
1358 if (MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1359 L->isCallInterference() )
1360 L->setSuggestedColorUsable( false );
1362 L->setSuggestedColorUsable( true );
1364 } // if L->hasSuggestedColor()
1366 } // for all LR's in hash map
1371 //----------------------------------------------------------------------------
1372 // The following method will set the stack offsets of the live ranges that
1373 // are decided to be spillled. This must be called just after coloring the
1374 // LRs using the graph coloring algo. For each live range that is spilled,
1375 // this method allocate a new spill position on the stack.
1376 //----------------------------------------------------------------------------
1378 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1379 if (DEBUG_RA) cerr << "\nSetting LR stack offsets for spills...\n";
1381 LiveRangeMapType::const_iterator HMI = LRI.getLiveRangeMap()->begin();
1382 LiveRangeMapType::const_iterator HMIEnd = LRI.getLiveRangeMap()->end();
1384 for ( ; HMI != HMIEnd ; ++HMI) {
1385 if (HMI->first && HMI->second) {
1386 LiveRange *L = HMI->second; // get the LiveRange
1387 if (L->isMarkedForSpill()) { // NOTE: allocating size of long Type **
1388 int stackOffset = MF.getInfo()->allocateSpilledValue(Type::LongTy);
1389 L->setSpillOffFromFP(stackOffset);
1391 cerr << " LR# " << L->getUserIGNode()->getIndex()
1392 << ": stack-offset = " << stackOffset << "\n";
1395 } // for all LR's in hash map
1399 //----------------------------------------------------------------------------
1400 // The entry pont to Register Allocation
1401 //----------------------------------------------------------------------------
1403 void PhyRegAlloc::allocateRegisters()
1406 // make sure that we put all register classes into the RegClassList
1407 // before we call constructLiveRanges (now done in the constructor of
1408 // PhyRegAlloc class).
1410 LRI.constructLiveRanges(); // create LR info
1412 if (DEBUG_RA >= RA_DEBUG_LiveRanges)
1413 LRI.printLiveRanges();
1415 createIGNodeListsAndIGs(); // create IGNode list and IGs
1417 buildInterferenceGraphs(); // build IGs in all reg classes
1420 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1421 // print all LRs in all reg classes
1422 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1423 RegClassList[rc]->printIGNodeList();
1425 // print IGs in all register classes
1426 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1427 RegClassList[rc]->printIG();
1430 LRI.coalesceLRs(); // coalesce all live ranges
1432 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1433 // print all LRs in all reg classes
1434 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1435 RegClassList[rc]->printIGNodeList();
1437 // print IGs in all register classes
1438 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1439 RegClassList[rc]->printIG();
1443 // mark un-usable suggested color before graph coloring algorithm.
1444 // When this is done, the graph coloring algo will not reserve
1445 // suggested color unnecessarily - they can be used by another LR
1447 markUnusableSugColors();
1449 // color all register classes using the graph coloring algo
1450 for (unsigned rc=0; rc < NumOfRegClasses ; rc++)
1451 RegClassList[rc]->colorAllRegs();
1453 // Atter graph coloring, if some LRs did not receive a color (i.e, spilled)
1454 // a poistion for such spilled LRs
1456 allocateStackSpace4SpilledLRs();
1458 // Reset the temp. area on the stack before use by the first instruction.
1459 // This will also happen after updating each instruction.
1460 MF.getInfo()->popAllTempValues();
1462 // color incoming args - if the correct color was not received
1463 // insert code to copy to the correct register
1465 colorIncomingArgs();
1467 // Now update the machine code with register names and add any
1468 // additional code inserted by the register allocator to the instruction
1471 updateMachineCode();
1474 cerr << "\n**** Machine Code After Register Allocation:\n\n";