1 //===-- PhyRegAlloc.cpp ---------------------------------------------------===//
3 // Register allocation for LLVM.
5 //===----------------------------------------------------------------------===//
7 #include "PhyRegAlloc.h"
8 #include "RegAllocCommon.h"
11 #include "llvm/CodeGen/MachineInstr.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/TargetInstrInfo.h"
20 #include "llvm/Function.h"
21 #include "llvm/Type.h"
22 #include "llvm/iOther.h"
23 #include "Support/STLExtras.h"
24 #include "Support/SetOperations.h"
25 #include "Support/CommandLine.h"
28 RegAllocDebugLevel_t DEBUG_RA;
30 static cl::opt<RegAllocDebugLevel_t, true>
31 DRA_opt("dregalloc", cl::Hidden, cl::location(DEBUG_RA),
32 cl::desc("enable register allocation debugging information"),
34 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
35 clEnumValN(RA_DEBUG_Results, "y", "debug output for allocation results"),
36 clEnumValN(RA_DEBUG_Coloring, "c", "debug output for graph coloring step"),
37 clEnumValN(RA_DEBUG_Interference,"ig","debug output for interference graphs"),
38 clEnumValN(RA_DEBUG_LiveRanges , "lr","debug output for live ranges"),
39 clEnumValN(RA_DEBUG_Verbose, "v", "extra debug output"),
42 FunctionPass *getRegisterAllocator(TargetMachine &T) {
43 return new PhyRegAlloc (T);
47 //----------------------------------------------------------------------------
48 // This method initially creates interference graphs (one in each reg class)
49 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
50 //----------------------------------------------------------------------------
51 void PhyRegAlloc::createIGNodeListsAndIGs() {
52 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "Creating LR lists ...\n";
55 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
58 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
60 for (; HMI != HMIEnd ; ++HMI ) {
62 LiveRange *L = HMI->second; // get the LiveRange
65 std::cerr << "\n**** ?!?WARNING: NULL LIVE RANGE FOUND FOR: "
66 << RAV(HMI->first) << "****\n";
70 // if the Value * is not null, and LR is not yet written to the IGNodeList
71 if (!(L->getUserIGNode()) ) {
72 RegClass *const RC = // RegClass of first value in the LR
73 RegClassList[ L->getRegClass()->getID() ];
74 RC->addLRToIG(L); // add this LR to an IG
80 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
81 RegClassList[rc]->createInterferenceGraph();
83 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "LRLists Created!\n";
87 //----------------------------------------------------------------------------
88 // This method will add all interferences at for a given instruction.
89 // Interference occurs only if the LR of Def (Inst or Arg) is of the same reg
90 // class as that of live var. The live var passed to this function is the
91 // LVset AFTER the instruction
92 //----------------------------------------------------------------------------
94 void PhyRegAlloc::addInterference(const Value *Def,
95 const ValueSet *LVSet,
97 ValueSet::const_iterator LIt = LVSet->begin();
99 // get the live range of instruction
100 const LiveRange *const LROfDef = LRI->getLiveRangeForValue( Def );
102 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
103 assert( IGNodeOfDef );
105 RegClass *const RCOfDef = LROfDef->getRegClass();
107 // for each live var in live variable set
108 for ( ; LIt != LVSet->end(); ++LIt) {
110 if (DEBUG_RA >= RA_DEBUG_Verbose)
111 std::cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
113 // get the live range corresponding to live var
114 LiveRange *LROfVar = LRI->getLiveRangeForValue(*LIt);
116 // LROfVar can be null if it is a const since a const
117 // doesn't have a dominating def - see Assumptions above
119 if (LROfDef != LROfVar) // do not set interf for same LR
120 if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
121 RCOfDef->setInterference( LROfDef, LROfVar);
126 //----------------------------------------------------------------------------
127 // For a call instruction, this method sets the CallInterference flag in
128 // the LR of each variable live int the Live Variable Set live after the
129 // call instruction (except the return value of the call instruction - since
130 // the return value does not interfere with that call itself).
131 //----------------------------------------------------------------------------
133 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
134 const ValueSet *LVSetAft) {
135 if (DEBUG_RA >= RA_DEBUG_Interference)
136 std::cerr << "\n For call inst: " << *MInst;
138 // for each live var in live variable set after machine inst
139 for (ValueSet::const_iterator LIt = LVSetAft->begin(), LEnd = LVSetAft->end();
140 LIt != LEnd; ++LIt) {
142 // get the live range corresponding to live var
143 LiveRange *const LR = LRI->getLiveRangeForValue(*LIt );
145 // LR can be null if it is a const since a const
146 // doesn't have a dominating def - see Assumptions above
148 if (DEBUG_RA >= RA_DEBUG_Interference) {
149 std::cerr << "\n\tLR after Call: ";
152 LR->setCallInterference();
153 if (DEBUG_RA >= RA_DEBUG_Interference) {
154 std::cerr << "\n ++After adding call interference for LR: " ;
161 // Now find the LR of the return value of the call
162 // We do this because, we look at the LV set *after* the instruction
163 // to determine, which LRs must be saved across calls. The return value
164 // of the call is live in this set - but it does not interfere with call
165 // (i.e., we can allocate a volatile register to the return value)
166 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
168 if (const Value *RetVal = argDesc->getReturnValue()) {
169 LiveRange *RetValLR = LRI->getLiveRangeForValue( RetVal );
170 assert( RetValLR && "No LR for RetValue of call");
171 RetValLR->clearCallInterference();
174 // If the CALL is an indirect call, find the LR of the function pointer.
175 // That has a call interference because it conflicts with outgoing args.
176 if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
177 LiveRange *AddrValLR = LRI->getLiveRangeForValue( AddrVal );
178 assert( AddrValLR && "No LR for indirect addr val of call");
179 AddrValLR->setCallInterference();
184 //----------------------------------------------------------------------------
185 // This method will walk thru code and create interferences in the IG of
186 // each RegClass. Also, this method calculates the spill cost of each
187 // Live Range (it is done in this method to save another pass over the code).
188 //----------------------------------------------------------------------------
190 void PhyRegAlloc::buildInterferenceGraphs()
192 if (DEBUG_RA >= RA_DEBUG_Interference)
193 std::cerr << "Creating interference graphs ...\n";
195 unsigned BBLoopDepthCost;
196 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
198 const MachineBasicBlock &MBB = *BBI;
199 const BasicBlock *BB = MBB.getBasicBlock();
201 // find the 10^(loop_depth) of this BB
202 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BB));
204 // get the iterator for machine instructions
205 MachineBasicBlock::const_iterator MII = MBB.begin();
207 // iterate over all the machine instructions in BB
208 for ( ; MII != MBB.end(); ++MII) {
209 const MachineInstr *MInst = *MII;
211 // get the LV set after the instruction
212 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BB);
213 bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
216 // set the isCallInterference flag of each live range which extends
217 // across this call instruction. This information is used by graph
218 // coloring algorithm to avoid allocating volatile colors to live ranges
219 // that span across calls (since they have to be saved/restored)
220 setCallInterferences(MInst, &LVSetAI);
223 // iterate over all MI operands to find defs
224 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
225 OpE = MInst->end(); OpI != OpE; ++OpI) {
226 if (OpI.isDefOnly() || OpI.isDefAndUse()) // create a new LR since def
227 addInterference(*OpI, &LVSetAI, isCallInst);
229 // Calculate the spill cost of each live range
230 LiveRange *LR = LRI->getLiveRangeForValue(*OpI);
231 if (LR) LR->addSpillCost(BBLoopDepthCost);
234 // if there are multiple defs in this instruction e.g. in SETX
235 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
236 addInterf4PseudoInstr(MInst);
238 // Also add interference for any implicit definitions in a machine
239 // instr (currently, only calls have this).
240 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
241 for (unsigned z=0; z < NumOfImpRefs; z++)
242 if (MInst->getImplicitOp(z).opIsDefOnly() ||
243 MInst->getImplicitOp(z).opIsDefAndUse())
244 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
246 } // for all machine instructions in BB
247 } // for all BBs in function
249 // add interferences for function arguments. Since there are no explicit
250 // defs in the function for args, we have to add them manually
251 addInterferencesForArgs();
253 if (DEBUG_RA >= RA_DEBUG_Interference)
254 std::cerr << "Interference graphs calculated!\n";
258 //--------------------------------------------------------------------------
259 // Pseudo-instructions may be expanded to multiple instructions by the
260 // assembler. Consequently, all the operands must get distinct registers.
261 // Therefore, we mark all operands of a pseudo-instruction as interfering
263 //--------------------------------------------------------------------------
265 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
266 bool setInterf = false;
268 // iterate over MI operands to find defs
269 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
270 ItE = MInst->end(); It1 != ItE; ++It1) {
271 const LiveRange *LROfOp1 = LRI->getLiveRangeForValue(*It1);
272 assert((LROfOp1 || !It1.isUseOnly())&&"No LR for Def in PSEUDO insruction");
274 MachineInstr::const_val_op_iterator It2 = It1;
275 for (++It2; It2 != ItE; ++It2) {
276 const LiveRange *LROfOp2 = LRI->getLiveRangeForValue(*It2);
279 RegClass *RCOfOp1 = LROfOp1->getRegClass();
280 RegClass *RCOfOp2 = LROfOp2->getRegClass();
282 if (RCOfOp1 == RCOfOp2 ){
283 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
287 } // for all other defs in machine instr
288 } // for all operands in an instruction
290 if (!setInterf && MInst->getNumOperands() > 2) {
291 std::cerr << "\nInterf not set for any operand in pseudo instr:\n";
293 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
298 //----------------------------------------------------------------------------
299 // This method adds interferences for incoming arguments to a function.
300 //----------------------------------------------------------------------------
302 void PhyRegAlloc::addInterferencesForArgs() {
303 // get the InSet of root BB
304 const ValueSet &InSet = LVI->getInSetOfBB(&Fn->front());
306 for (Function::const_aiterator AI = Fn->abegin(); AI != Fn->aend(); ++AI) {
307 // add interferences between args and LVars at start
308 addInterference(AI, &InSet, false);
310 if (DEBUG_RA >= RA_DEBUG_Interference)
311 std::cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
316 //----------------------------------------------------------------------------
317 // This method is called after register allocation is complete to set the
318 // allocated registers in the machine code. This code will add register numbers
319 // to MachineOperands that contain a Value. Also it calls target specific
320 // methods to produce caller saving instructions. At the end, it adds all
321 // additional instructions produced by the register allocator to the
322 // instruction stream.
323 //----------------------------------------------------------------------------
325 //-----------------------------
326 // Utility functions used below
327 //-----------------------------
329 InsertBefore(MachineInstr* newMI,
330 MachineBasicBlock& MBB,
331 MachineBasicBlock::iterator& MII)
333 MII = MBB.insert(MII, newMI);
338 InsertAfter(MachineInstr* newMI,
339 MachineBasicBlock& MBB,
340 MachineBasicBlock::iterator& MII)
342 ++MII; // insert before the next instruction
343 MII = MBB.insert(MII, newMI);
347 DeleteInstruction(MachineBasicBlock& MBB,
348 MachineBasicBlock::iterator& MII)
350 MII = MBB.erase(MII);
354 SubstituteInPlace(MachineInstr* newMI,
355 MachineBasicBlock& MBB,
356 MachineBasicBlock::iterator MII)
362 PrependInstructions(std::vector<MachineInstr *> &IBef,
363 MachineBasicBlock& MBB,
364 MachineBasicBlock::iterator& MII,
365 const std::string& msg)
369 MachineInstr* OrigMI = *MII;
370 std::vector<MachineInstr *>::iterator AdIt;
371 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
374 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
375 std::cerr << msg << "PREPENDed instr:\n " << **AdIt << "\n";
377 InsertBefore(*AdIt, MBB, MII);
383 AppendInstructions(std::vector<MachineInstr *> &IAft,
384 MachineBasicBlock& MBB,
385 MachineBasicBlock::iterator& MII,
386 const std::string& msg)
390 MachineInstr* OrigMI = *MII;
391 std::vector<MachineInstr *>::iterator AdIt;
392 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
395 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
396 std::cerr << msg << "APPENDed instr:\n " << **AdIt << "\n";
398 InsertAfter(*AdIt, MBB, MII);
403 bool PhyRegAlloc::markAllocatedRegs(MachineInstr* MInst)
405 bool instrNeedsSpills = false;
407 // First, set the registers for operands in the machine instruction
408 // if a register was successfully allocated. Do this first because we
409 // will need to know which registers are already used by this instr'n.
410 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
412 MachineOperand& Op = MInst->getOperand(OpNum);
413 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
414 Op.getType() == MachineOperand::MO_CCRegister)
416 const Value *const Val = Op.getVRegValue();
417 if (const LiveRange* LR = LRI->getLiveRangeForValue(Val)) {
418 // Remember if any operand needs spilling
419 instrNeedsSpills |= LR->isMarkedForSpill();
421 // An operand may have a color whether or not it needs spilling
423 MInst->SetRegForOperand(OpNum,
424 MRI.getUnifiedRegNum(LR->getRegClass()->getID(),
428 } // for each operand
430 return instrNeedsSpills;
433 void PhyRegAlloc::updateInstruction(MachineBasicBlock::iterator& MII,
434 MachineBasicBlock &MBB)
436 MachineInstr* MInst = *MII;
437 unsigned Opcode = MInst->getOpCode();
439 // Reset tmp stack positions so they can be reused for each machine instr.
440 MF->getInfo()->popAllTempValues();
442 // Mark the operands for which regs have been allocated.
443 bool instrNeedsSpills = markAllocatedRegs(*MII);
446 // Mark that the operands have been updated. Later,
447 // setRelRegsUsedByThisInst() is called to find registers used by each
448 // MachineInst, and it should not be used for an instruction until
449 // this is done. This flag just serves as a sanity check.
450 OperandsColoredMap[MInst] = true;
453 // Now insert caller-saving code before/after the call.
454 // Do this before inserting spill code since some registers must be
455 // used by save/restore and spill code should not use those registers.
456 if (TM.getInstrInfo().isCall(Opcode)) {
457 AddedInstrns &AI = AddedInstrMap[MInst];
458 insertCallerSavingCode(AI.InstrnsBefore, AI.InstrnsAfter, MInst,
459 MBB.getBasicBlock());
462 // Now insert spill code for remaining operands not allocated to
463 // registers. This must be done even for call return instructions
464 // since those are not handled by the special code above.
465 if (instrNeedsSpills)
466 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
468 MachineOperand& Op = MInst->getOperand(OpNum);
469 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
470 Op.getType() == MachineOperand::MO_CCRegister)
472 const Value* Val = Op.getVRegValue();
473 if (const LiveRange *LR = LRI->getLiveRangeForValue(Val))
474 if (LR->isMarkedForSpill())
475 insertCode4SpilledLR(LR, MII, MBB, OpNum);
477 } // for each operand
480 void PhyRegAlloc::updateMachineCode()
482 // Insert any instructions needed at method entry
483 MachineBasicBlock::iterator MII = MF->front().begin();
484 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MF->front(), MII,
485 "At function entry: \n");
486 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
487 "InstrsAfter should be unnecessary since we are just inserting at "
488 "the function entry point here.");
490 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
493 MachineBasicBlock &MBB = *BBI;
495 // Iterate over all machine instructions in BB and mark operands with
496 // their assigned registers or insert spill code, as appropriate.
497 // Also, fix operands of call/return instructions.
498 for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
499 if (! TM.getInstrInfo().isDummyPhiInstr((*MII)->getOpCode()))
500 updateInstruction(MII, MBB);
502 // Now, move code out of delay slots of branches and returns if needed.
503 // (Also, move "after" code from calls to the last delay slot instruction.)
504 // Moving code out of delay slots is needed in 2 situations:
505 // (1) If this is a branch and it needs instructions inserted after it,
506 // move any existing instructions out of the delay slot so that the
507 // instructions can go into the delay slot. This only supports the
508 // case that #instrsAfter <= #delay slots.
510 // (2) If any instruction in the delay slot needs
511 // instructions inserted, move it out of the delay slot and before the
512 // branch because putting code before or after it would be VERY BAD!
514 // If the annul bit of the branch is set, neither of these is legal!
515 // If so, we need to handle spill differently but annulling is not yet used.
516 for (MachineBasicBlock::iterator MII = MBB.begin();
517 MII != MBB.end(); ++MII)
518 if (unsigned delaySlots =
519 TM.getInstrInfo().getNumDelaySlots((*MII)->getOpCode()))
521 MachineInstr *MInst = *MII, *DelaySlotMI = *(MII+1);
523 // Check the 2 conditions above:
524 // (1) Does a branch need instructions added after it?
525 // (2) O/w does delay slot instr. need instrns before or after?
526 bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
527 TM.getInstrInfo().isReturn(MInst->getOpCode()));
528 bool cond1 = (isBranch &&
529 AddedInstrMap.count(MInst) &&
530 AddedInstrMap[MInst].InstrnsAfter.size() > 0);
531 bool cond2 = (AddedInstrMap.count(DelaySlotMI) &&
532 (AddedInstrMap[DelaySlotMI].InstrnsBefore.size() > 0 ||
533 AddedInstrMap[DelaySlotMI].InstrnsAfter.size() > 0));
537 assert((MInst->getOpCodeFlags() & AnnulFlag) == 0 &&
538 "FIXME: Moving an annulled delay slot instruction!");
539 assert(delaySlots==1 &&
540 "InsertBefore does not yet handle >1 delay slots!");
541 InsertBefore(DelaySlotMI, MBB, MII); // MII pts back to branch
543 // In case (1), delete it and don't replace with anything!
544 // Otherwise (i.e., case (2) only) replace it with a NOP.
546 DeleteInstruction(MBB, ++MII); // MII now points to next inst.
547 --MII; // reset MII for ++MII of loop
550 SubstituteInPlace(BuildMI(TM.getInstrInfo().getNOPOpCode(),1),
551 MBB, MII+1); // replace with NOP
554 std::cerr << "\nRegAlloc: Moved instr. with added code: "
556 << " out of delay slots of instr: " << *MInst;
560 // For non-branch instr with delay slots (probably a call), move
561 // InstrAfter to the instr. in the last delay slot.
562 move2DelayedInstr(*MII, *(MII+delaySlots));
565 // Finally iterate over all instructions in BB and insert before/after
566 for (MachineBasicBlock::iterator MII=MBB.begin(); MII != MBB.end(); ++MII) {
567 MachineInstr *MInst = *MII;
569 // do not process Phis
570 if (TM.getInstrInfo().isDummyPhiInstr(MInst->getOpCode()))
573 // if there are any added instructions...
574 if (AddedInstrMap.count(MInst)) {
575 AddedInstrns &CallAI = AddedInstrMap[MInst];
578 bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
579 TM.getInstrInfo().isReturn(MInst->getOpCode()));
581 AddedInstrMap[MInst].InstrnsAfter.size() <=
582 TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) &&
583 "Cannot put more than #delaySlots instrns after "
584 "branch or return! Need to handle temps differently.");
588 // Temporary sanity checking code to detect whether the same machine
589 // instruction is ever inserted twice before/after a call.
590 // I suspect this is happening but am not sure. --Vikram, 7/1/03.
591 std::set<const MachineInstr*> instrsSeen;
592 for (int i = 0, N = CallAI.InstrnsBefore.size(); i < N; ++i) {
593 assert(instrsSeen.count(CallAI.InstrnsBefore[i]) == 0 &&
594 "Duplicate machine instruction in InstrnsBefore!");
595 instrsSeen.insert(CallAI.InstrnsBefore[i]);
597 for (int i = 0, N = CallAI.InstrnsAfter.size(); i < N; ++i) {
598 assert(instrsSeen.count(CallAI.InstrnsAfter[i]) == 0 &&
599 "Duplicate machine instruction in InstrnsBefore/After!");
600 instrsSeen.insert(CallAI.InstrnsAfter[i]);
604 // Now add the instructions before/after this MI.
605 // We do this here to ensure that spill for an instruction is inserted
606 // as close as possible to an instruction (see above insertCode4Spill)
607 if (! CallAI.InstrnsBefore.empty())
608 PrependInstructions(CallAI.InstrnsBefore, MBB, MII,"");
610 if (! CallAI.InstrnsAfter.empty())
611 AppendInstructions(CallAI.InstrnsAfter, MBB, MII,"");
613 } // if there are any added instructions
614 } // for each machine instruction
619 //----------------------------------------------------------------------------
620 // This method inserts spill code for AN operand whose LR was spilled.
621 // This method may be called several times for a single machine instruction
622 // if it contains many spilled operands. Each time it is called, it finds
623 // a register which is not live at that instruction and also which is not
624 // used by other spilled operands of the same instruction. Then it uses
625 // this register temporarily to accommodate the spilled value.
626 //----------------------------------------------------------------------------
628 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
629 MachineBasicBlock::iterator& MII,
630 MachineBasicBlock &MBB,
631 const unsigned OpNum) {
632 MachineInstr *MInst = *MII;
633 const BasicBlock *BB = MBB.getBasicBlock();
635 assert((! TM.getInstrInfo().isCall(MInst->getOpCode()) || OpNum == 0) &&
636 "Outgoing arg of a call must be handled elsewhere (func arg ok)");
637 assert(! TM.getInstrInfo().isReturn(MInst->getOpCode()) &&
638 "Return value of a ret must be handled elsewhere");
640 MachineOperand& Op = MInst->getOperand(OpNum);
641 bool isDef = Op.opIsDefOnly();
642 bool isDefAndUse = Op.opIsDefAndUse();
643 unsigned RegType = MRI.getRegTypeForLR(LR);
644 int SpillOff = LR->getSpillOffFromFP();
645 RegClass *RC = LR->getRegClass();
647 // Get the live-variable set to find registers free before this instr.
648 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
651 // If this instr. is in the delay slot of a branch or return, we need to
652 // include all live variables before that branch or return -- we don't want to
653 // trample those! Verify that the set is included in the LV set before MInst.
654 if (MII != MBB.begin()) {
655 MachineInstr *PredMI = *(MII-1);
656 if (unsigned DS = TM.getInstrInfo().getNumDelaySlots(PredMI->getOpCode()))
657 assert(set_difference(LVI->getLiveVarSetBeforeMInst(PredMI), LVSetBef)
658 .empty() && "Live-var set before branch should be included in "
659 "live-var set of each delay slot instruction!");
663 MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType) );
665 std::vector<MachineInstr*> MIBef, MIAft;
666 std::vector<MachineInstr*> AdIMid;
668 // Choose a register to hold the spilled value, if one was not preallocated.
669 // This may insert code before and after MInst to free up the value. If so,
670 // this code should be first/last in the spill sequence before/after MInst.
671 int TmpRegU=(LR->hasColor()
672 ? MRI.getUnifiedRegNum(LR->getRegClass()->getID(),LR->getColor())
673 : getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef,MIAft));
675 // Set the operand first so that it this register does not get used
676 // as a scratch register for later calls to getUsableUniRegAtMI below
677 MInst->SetRegForOperand(OpNum, TmpRegU);
679 // get the added instructions for this instruction
680 AddedInstrns &AI = AddedInstrMap[MInst];
682 // We may need a scratch register to copy the spilled value to/from memory.
683 // This may itself have to insert code to free up a scratch register.
684 // Any such code should go before (after) the spill code for a load (store).
685 // The scratch reg is not marked as used because it is only used
686 // for the copy and not used across MInst.
687 int scratchRegType = -1;
689 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
691 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
692 MInst, MIBef, MIAft);
693 assert(scratchReg != MRI.getInvalidRegNum());
696 if (!isDef || isDefAndUse) {
697 // for a USE, we have to load the value of LR from stack to a TmpReg
698 // and use the TmpReg as one operand of instruction
700 // actual loading instruction(s)
701 MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU,
702 RegType, scratchReg);
704 // the actual load should be after the instructions to free up TmpRegU
705 MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
709 if (isDef || isDefAndUse) { // if this is a Def
710 // for a DEF, we have to store the value produced by this instruction
711 // on the stack position allocated for this LR
713 // actual storing instruction(s)
714 MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff,
715 RegType, scratchReg);
717 MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
720 // Finally, insert the entire spill code sequences before/after MInst
721 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
722 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
725 std::cerr << "\nFor Inst:\n " << *MInst;
726 std::cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
727 std::cerr << "; added Instructions:";
728 for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
729 for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
734 //----------------------------------------------------------------------------
735 // This method inserts caller saving/restoring instructions before/after
736 // a call machine instruction. The caller saving/restoring instructions are
738 // ** caller saving instructions
739 // other instructions inserted for the call by ColorCallArg
741 // other instructions inserted for the call ColorCallArg
742 // ** caller restoring instructions
743 //----------------------------------------------------------------------------
746 PhyRegAlloc::insertCallerSavingCode(std::vector<MachineInstr*> &instrnsBefore,
747 std::vector<MachineInstr*> &instrnsAfter,
748 MachineInstr *CallMI,
749 const BasicBlock *BB)
751 assert(TM.getInstrInfo().isCall(CallMI->getOpCode()));
753 // hash set to record which registers were saved/restored
754 hash_set<unsigned> PushedRegSet;
756 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
758 // if the call is to a instrumentation function, do not insert save and
759 // restore instructions the instrumentation function takes care of save
760 // restore for volatile regs.
762 // FIXME: this should be made general, not specific to the reoptimizer!
763 const Function *Callee = argDesc->getCallInst()->getCalledFunction();
764 bool isLLVMFirstTrigger = Callee && Callee->getName() == "llvm_first_trigger";
766 // Now check if the call has a return value (using argDesc) and if so,
767 // find the LR of the TmpInstruction representing the return value register.
768 // (using the last or second-last *implicit operand* of the call MI).
769 // Insert it to to the PushedRegSet since we must not save that register
770 // and restore it after the call.
771 // We do this because, we look at the LV set *after* the instruction
772 // to determine, which LRs must be saved across calls. The return value
773 // of the call is live in this set - but we must not save/restore it.
774 if (const Value *origRetVal = argDesc->getReturnValue()) {
775 unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
776 (argDesc->getIndirectFuncPtr()? 1 : 2));
777 const TmpInstruction* tmpRetVal =
778 cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
779 assert(tmpRetVal->getOperand(0) == origRetVal &&
780 tmpRetVal->getType() == origRetVal->getType() &&
781 "Wrong implicit ref?");
782 LiveRange *RetValLR = LRI->getLiveRangeForValue(tmpRetVal);
783 assert(RetValLR && "No LR for RetValue of call");
785 if (! RetValLR->isMarkedForSpill())
786 PushedRegSet.insert(MRI.getUnifiedRegNum(RetValLR->getRegClassID(),
787 RetValLR->getColor()));
790 const ValueSet &LVSetAft = LVI->getLiveVarSetAfterMInst(CallMI, BB);
791 ValueSet::const_iterator LIt = LVSetAft.begin();
793 // for each live var in live variable set after machine inst
794 for( ; LIt != LVSetAft.end(); ++LIt) {
795 // get the live range corresponding to live var
796 LiveRange *const LR = LRI->getLiveRangeForValue(*LIt);
798 // LR can be null if it is a const since a const
799 // doesn't have a dominating def - see Assumptions above
801 if(! LR->isMarkedForSpill()) {
802 assert(LR->hasColor() && "LR is neither spilled nor colored?");
803 unsigned RCID = LR->getRegClassID();
804 unsigned Color = LR->getColor();
806 if (MRI.isRegVolatile(RCID, Color) ) {
807 // if this is a call to the first-level reoptimizer
808 // instrumentation entry point, and the register is not
809 // modified by call, don't save and restore it.
810 if (isLLVMFirstTrigger && !MRI.modifiedByCall(RCID, Color))
813 // if the value is in both LV sets (i.e., live before and after
814 // the call machine instruction)
815 unsigned Reg = MRI.getUnifiedRegNum(RCID, Color);
817 // if we haven't already pushed this register...
818 if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
819 unsigned RegType = MRI.getRegTypeForLR(LR);
821 // Now get two instructions - to push on stack and pop from stack
822 // and add them to InstrnsBefore and InstrnsAfter of the
825 MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
827 //---- Insert code for pushing the reg on stack ----------
829 std::vector<MachineInstr*> AdIBef, AdIAft;
831 // We may need a scratch register to copy the saved value
832 // to/from memory. This may itself have to insert code to
833 // free up a scratch register. Any such code should go before
834 // the save code. The scratch register, if any, is by default
835 // temporary and not "used" by the instruction unless the
836 // copy code itself decides to keep the value in the scratch reg.
837 int scratchRegType = -1;
839 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
840 { // Find a register not live in the LVSet before CallMI
841 const ValueSet &LVSetBef =
842 LVI->getLiveVarSetBeforeMInst(CallMI, BB);
843 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
844 CallMI, AdIBef, AdIAft);
845 assert(scratchReg != MRI.getInvalidRegNum());
848 if (AdIBef.size() > 0)
849 instrnsBefore.insert(instrnsBefore.end(),
850 AdIBef.begin(), AdIBef.end());
852 MRI.cpReg2MemMI(instrnsBefore, Reg, MRI.getFramePointer(),
853 StackOff, RegType, scratchReg);
855 if (AdIAft.size() > 0)
856 instrnsBefore.insert(instrnsBefore.end(),
857 AdIAft.begin(), AdIAft.end());
859 //---- Insert code for popping the reg from the stack ----------
863 // We may need a scratch register to copy the saved value
864 // from memory. This may itself have to insert code to
865 // free up a scratch register. Any such code should go
866 // after the save code. As above, scratch is not marked "used".
869 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
870 { // Find a register not live in the LVSet after CallMI
871 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetAft,
872 CallMI, AdIBef, AdIAft);
873 assert(scratchReg != MRI.getInvalidRegNum());
876 if (AdIBef.size() > 0)
877 instrnsAfter.insert(instrnsAfter.end(),
878 AdIBef.begin(), AdIBef.end());
880 MRI.cpMem2RegMI(instrnsAfter, MRI.getFramePointer(), StackOff,
881 Reg, RegType, scratchReg);
883 if (AdIAft.size() > 0)
884 instrnsAfter.insert(instrnsAfter.end(),
885 AdIAft.begin(), AdIAft.end());
887 PushedRegSet.insert(Reg);
890 std::cerr << "\nFor call inst:" << *CallMI;
891 std::cerr << " -inserted caller saving instrs: Before:\n\t ";
892 for_each(instrnsBefore.begin(), instrnsBefore.end(),
893 std::mem_fun(&MachineInstr::dump));
894 std::cerr << " -and After:\n\t ";
895 for_each(instrnsAfter.begin(), instrnsAfter.end(),
896 std::mem_fun(&MachineInstr::dump));
898 } // if not already pushed
899 } // if LR has a volatile color
901 } // if there is a LR for Var
902 } // for each value in the LV set after instruction
906 //----------------------------------------------------------------------------
907 // We can use the following method to get a temporary register to be used
908 // BEFORE any given machine instruction. If there is a register available,
909 // this method will simply return that register and set MIBef = MIAft = NULL.
910 // Otherwise, it will return a register and MIAft and MIBef will contain
911 // two instructions used to free up this returned register.
912 // Returned register number is the UNIFIED register number
913 //----------------------------------------------------------------------------
915 int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
916 const ValueSet *LVSetBef,
918 std::vector<MachineInstr*>& MIBef,
919 std::vector<MachineInstr*>& MIAft) {
920 RegClass* RC = getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
922 int RegU = getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
925 // we couldn't find an unused register. Generate code to free up a reg by
926 // saving it on stack and restoring after the instruction
928 int TmpOff = MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
930 RegU = getUniRegNotUsedByThisInst(RC, RegType, MInst);
932 // Check if we need a scratch register to copy this register to memory.
933 int scratchRegType = -1;
934 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
936 int scratchReg = getUsableUniRegAtMI(scratchRegType, LVSetBef,
937 MInst, MIBef, MIAft);
938 assert(scratchReg != MRI.getInvalidRegNum());
940 // We may as well hold the value in the scratch register instead
941 // of copying it to memory and back. But we have to mark the
942 // register as used by this instruction, so it does not get used
943 // as a scratch reg. by another operand or anyone else.
944 ScratchRegsUsed.insert(std::make_pair(MInst, scratchReg));
945 MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
946 MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
949 { // the register can be copied directly to/from memory so do it.
950 MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
951 MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
959 //----------------------------------------------------------------------------
960 // This method is called to get a new unused register that can be used
961 // to accommodate a temporary value. This method may be called several times
962 // for a single machine instruction. Each time it is called, it finds a
963 // register which is not live at that instruction and also which is not used
964 // by other spilled operands of the same instruction. Return register number
965 // is relative to the register class, NOT the unified number.
966 //----------------------------------------------------------------------------
968 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
970 const MachineInstr *MInst,
971 const ValueSet* LVSetBef) {
972 RC->clearColorsUsed(); // Reset array
974 if (LVSetBef == NULL) {
975 LVSetBef = &LVI->getLiveVarSetBeforeMInst(MInst);
976 assert(LVSetBef != NULL && "Unable to get live-var set before MInst?");
979 ValueSet::const_iterator LIt = LVSetBef->begin();
981 // for each live var in live variable set after machine inst
982 for ( ; LIt != LVSetBef->end(); ++LIt) {
983 // Get the live range corresponding to live var, and its RegClass
984 LiveRange *const LRofLV = LRI->getLiveRangeForValue(*LIt );
986 // LR can be null if it is a const since a const
987 // doesn't have a dominating def - see Assumptions above
988 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor())
989 RC->markColorsUsed(LRofLV->getColor(),
990 MRI.getRegTypeForLR(LRofLV), RegType);
993 // It is possible that one operand of this MInst was already spilled
994 // and it received some register temporarily. If that's the case,
995 // it is recorded in machine operand. We must skip such registers.
996 setRelRegsUsedByThisInst(RC, RegType, MInst);
998 int unusedReg = RC->getUnusedColor(RegType); // find first unused color
1000 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
1006 //----------------------------------------------------------------------------
1007 // Get any other register in a register class, other than what is used
1008 // by operands of a machine instruction. Returns the unified reg number.
1009 //----------------------------------------------------------------------------
1011 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
1013 const MachineInstr *MInst) {
1014 RC->clearColorsUsed();
1016 setRelRegsUsedByThisInst(RC, RegType, MInst);
1018 // find the first unused color
1019 int unusedReg = RC->getUnusedColor(RegType);
1020 assert(unusedReg >= 0 &&
1021 "FATAL: No free register could be found in reg class!!");
1023 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
1027 //----------------------------------------------------------------------------
1028 // This method modifies the IsColorUsedArr of the register class passed to it.
1029 // It sets the bits corresponding to the registers used by this machine
1030 // instructions. Both explicit and implicit operands are set.
1031 //----------------------------------------------------------------------------
1033 static void markRegisterUsed(int RegNo, RegClass *RC, int RegType,
1034 const TargetRegInfo &TRI) {
1035 unsigned classId = 0;
1036 int classRegNum = TRI.getClassRegNum(RegNo, classId);
1037 if (RC->getID() == classId)
1038 RC->markColorsUsed(classRegNum, RegType, RegType);
1041 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC, int RegType,
1042 const MachineInstr *MI)
1044 assert(OperandsColoredMap[MI] == true &&
1045 "Illegal to call setRelRegsUsedByThisInst() until colored operands "
1046 "are marked for an instruction.");
1048 // Add the registers already marked as used by the instruction.
1049 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
1050 if (MI->getOperand(i).hasAllocatedReg())
1051 markRegisterUsed(MI->getOperand(i).getAllocatedRegNum(), RC, RegType,MRI);
1053 for (unsigned i = 0, e = MI->getNumImplicitRefs(); i != e; ++i)
1054 if (MI->getImplicitOp(i).hasAllocatedReg())
1055 markRegisterUsed(MI->getImplicitOp(i).getAllocatedRegNum(), RC,
1058 // Add all of the scratch registers that are used to save values across the
1059 // instruction (e.g., for saving state register values).
1060 std::pair<ScratchRegsUsedTy::iterator, ScratchRegsUsedTy::iterator>
1061 IR = ScratchRegsUsed.equal_range(MI);
1062 for (ScratchRegsUsedTy::iterator I = IR.first; I != IR.second; ++I)
1063 markRegisterUsed(I->second, RC, RegType, MRI);
1065 // If there are implicit references, mark their allocated regs as well
1066 for (unsigned z=0; z < MI->getNumImplicitRefs(); z++)
1067 if (const LiveRange*
1068 LRofImpRef = LRI->getLiveRangeForValue(MI->getImplicitRef(z)))
1069 if (LRofImpRef->hasColor())
1070 // this implicit reference is in a LR that received a color
1071 RC->markColorsUsed(LRofImpRef->getColor(),
1072 MRI.getRegTypeForLR(LRofImpRef), RegType);
1076 //----------------------------------------------------------------------------
1077 // If there are delay slots for an instruction, the instructions
1078 // added after it must really go after the delayed instruction(s).
1079 // So, we move the InstrAfter of that instruction to the
1080 // corresponding delayed instruction using the following method.
1081 //----------------------------------------------------------------------------
1083 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
1084 const MachineInstr *DelayedMI)
1086 // "added after" instructions of the original instr
1087 std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
1089 if (DEBUG_RA && OrigAft.size() > 0) {
1090 std::cerr << "\nRegAlloc: Moved InstrnsAfter for: " << *OrigMI;
1091 std::cerr << " to last delay slot instrn: " << *DelayedMI;
1094 // "added after" instructions of the delayed instr
1095 std::vector<MachineInstr *> &DelayedAft=AddedInstrMap[DelayedMI].InstrnsAfter;
1097 // go thru all the "added after instructions" of the original instruction
1098 // and append them to the "added after instructions" of the delayed
1100 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
1102 // empty the "added after instructions" of the original instruction
1107 void PhyRegAlloc::colorIncomingArgs()
1109 MRI.colorMethodArgs(Fn, *LRI, AddedInstrAtEntry.InstrnsBefore,
1110 AddedInstrAtEntry.InstrnsAfter);
1114 //----------------------------------------------------------------------------
1115 // This method calls setSugColorUsable method of each live range. This
1116 // will determine whether the suggested color of LR is really usable.
1117 // A suggested color is not usable when the suggested color is volatile
1118 // AND when there are call interferences
1119 //----------------------------------------------------------------------------
1121 void PhyRegAlloc::markUnusableSugColors()
1123 LiveRangeMapType::const_iterator HMI = (LRI->getLiveRangeMap())->begin();
1124 LiveRangeMapType::const_iterator HMIEnd = (LRI->getLiveRangeMap())->end();
1126 for (; HMI != HMIEnd ; ++HMI ) {
1128 LiveRange *L = HMI->second; // get the LiveRange
1130 if (L->hasSuggestedColor()) {
1131 int RCID = L->getRegClass()->getID();
1132 if (MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1133 L->isCallInterference() )
1134 L->setSuggestedColorUsable( false );
1136 L->setSuggestedColorUsable( true );
1138 } // if L->hasSuggestedColor()
1140 } // for all LR's in hash map
1144 //----------------------------------------------------------------------------
1145 // The following method will set the stack offsets of the live ranges that
1146 // are decided to be spilled. This must be called just after coloring the
1147 // LRs using the graph coloring algo. For each live range that is spilled,
1148 // this method allocate a new spill position on the stack.
1149 //----------------------------------------------------------------------------
1151 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1152 if (DEBUG_RA) std::cerr << "\nSetting LR stack offsets for spills...\n";
1154 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
1155 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
1157 for ( ; HMI != HMIEnd ; ++HMI) {
1158 if (HMI->first && HMI->second) {
1159 LiveRange *L = HMI->second; // get the LiveRange
1160 if (L->isMarkedForSpill()) { // NOTE: allocating size of long Type **
1161 int stackOffset = MF->getInfo()->allocateSpilledValue(Type::LongTy);
1162 L->setSpillOffFromFP(stackOffset);
1164 std::cerr << " LR# " << L->getUserIGNode()->getIndex()
1165 << ": stack-offset = " << stackOffset << "\n";
1168 } // for all LR's in hash map
1172 //----------------------------------------------------------------------------
1173 // The entry point to Register Allocation
1174 //----------------------------------------------------------------------------
1176 bool PhyRegAlloc::runOnFunction (Function &F) {
1178 std::cerr << "\n********* Function "<< F.getName () << " ***********\n";
1181 MF = &MachineFunction::get (Fn);
1182 LVI = &getAnalysis<FunctionLiveVarInfo> ();
1183 LRI = new LiveRangeInfo (Fn, TM, RegClassList);
1184 LoopDepthCalc = &getAnalysis<LoopInfo> ();
1186 // Create each RegClass for the target machine and add it to the
1187 // RegClassList. This must be done before calling constructLiveRanges().
1188 for (unsigned rc = 0; rc != NumOfRegClasses; ++rc)
1189 RegClassList.push_back (new RegClass (Fn, &TM.getRegInfo (),
1190 MRI.getMachineRegClass (rc)));
1192 LRI->constructLiveRanges(); // create LR info
1193 if (DEBUG_RA >= RA_DEBUG_LiveRanges)
1194 LRI->printLiveRanges();
1196 createIGNodeListsAndIGs(); // create IGNode list and IGs
1198 buildInterferenceGraphs(); // build IGs in all reg classes
1200 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1201 // print all LRs in all reg classes
1202 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1203 RegClassList[rc]->printIGNodeList();
1205 // print IGs in all register classes
1206 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1207 RegClassList[rc]->printIG();
1210 LRI->coalesceLRs(); // coalesce all live ranges
1212 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1213 // print all LRs in all reg classes
1214 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1215 RegClassList[rc]->printIGNodeList();
1217 // print IGs in all register classes
1218 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1219 RegClassList[rc]->printIG();
1222 // mark un-usable suggested color before graph coloring algorithm.
1223 // When this is done, the graph coloring algo will not reserve
1224 // suggested color unnecessarily - they can be used by another LR
1225 markUnusableSugColors();
1227 // color all register classes using the graph coloring algo
1228 for (unsigned rc=0; rc < NumOfRegClasses ; rc++)
1229 RegClassList[rc]->colorAllRegs();
1231 // After graph coloring, if some LRs did not receive a color (i.e, spilled)
1232 // a position for such spilled LRs
1233 allocateStackSpace4SpilledLRs();
1235 // Reset the temp. area on the stack before use by the first instruction.
1236 // This will also happen after updating each instruction.
1237 MF->getInfo()->popAllTempValues();
1239 // color incoming args - if the correct color was not received
1240 // insert code to copy to the correct register
1241 colorIncomingArgs();
1243 // Now update the machine code with register names and add any
1244 // additional code inserted by the register allocator to the instruction
1246 updateMachineCode();
1249 std::cerr << "\n**** Machine Code After Register Allocation:\n\n";
1253 // Tear down temporary data structures
1254 for (unsigned rc = 0; rc < NumOfRegClasses; ++rc)
1255 delete RegClassList[rc];
1256 RegClassList.clear ();
1257 AddedInstrMap.clear ();
1258 OperandsColoredMap.clear ();
1259 ScratchRegsUsed.clear ();
1260 AddedInstrAtEntry.clear ();
1263 if (DEBUG_RA) std::cerr << "\nRegister allocation complete!\n";
1264 return false; // Function was not modified