1 //===-- PhyRegAlloc.cpp ---------------------------------------------------===//
3 // Traditional graph-coloring global register allocator currently used
4 // by the SPARC back-end.
6 // NOTE: This register allocator has some special support
7 // for the Reoptimizer, such as not saving some registers on calls to
8 // the first-level instrumentation function.
10 // NOTE 2: This register allocator can save its state in a global
11 // variable in the module it's working on. This feature is not
12 // thread-safe; if you have doubts, leave it turned off.
14 //===----------------------------------------------------------------------===//
16 #include "PhyRegAlloc.h"
17 #include "RegAllocCommon.h"
20 #include "llvm/CodeGen/FunctionLiveVarInfo.h"
21 #include "llvm/CodeGen/InstrSelection.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineInstrAnnot.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineFunctionInfo.h"
27 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/Analysis/LoopInfo.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Type.h"
31 #include "llvm/iOther.h"
32 #include "llvm/DerivedTypes.h"
33 #include "llvm/Constants.h"
34 #include "llvm/Module.h"
35 #include "llvm/Support/InstIterator.h"
36 #include "Support/STLExtras.h"
37 #include "Support/SetOperations.h"
38 #include "Support/CommandLine.h"
41 RegAllocDebugLevel_t DEBUG_RA;
43 static cl::opt<RegAllocDebugLevel_t, true>
44 DRA_opt("dregalloc", cl::Hidden, cl::location(DEBUG_RA),
45 cl::desc("enable register allocation debugging information"),
47 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
48 clEnumValN(RA_DEBUG_Results, "y", "debug output for allocation results"),
49 clEnumValN(RA_DEBUG_Coloring, "c", "debug output for graph coloring step"),
50 clEnumValN(RA_DEBUG_Interference,"ig","debug output for interference graphs"),
51 clEnumValN(RA_DEBUG_LiveRanges , "lr","debug output for live ranges"),
52 clEnumValN(RA_DEBUG_Verbose, "v", "extra debug output"),
56 SaveRegAllocState("save-ra-state", cl::Hidden,
57 cl::desc("write reg. allocator state into module"));
59 FunctionPass *getRegisterAllocator(TargetMachine &T) {
60 return new PhyRegAlloc (T);
63 void PhyRegAlloc::getAnalysisUsage(AnalysisUsage &AU) const {
64 AU.addRequired<LoopInfo> ();
65 AU.addRequired<FunctionLiveVarInfo> ();
70 //----------------------------------------------------------------------------
71 // This method initially creates interference graphs (one in each reg class)
72 // and IGNodeList (one in each IG). The actual nodes will be pushed later.
73 //----------------------------------------------------------------------------
74 void PhyRegAlloc::createIGNodeListsAndIGs() {
75 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "Creating LR lists ...\n";
78 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
81 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
83 for (; HMI != HMIEnd ; ++HMI ) {
85 LiveRange *L = HMI->second; // get the LiveRange
88 std::cerr << "\n**** ?!?WARNING: NULL LIVE RANGE FOUND FOR: "
89 << RAV(HMI->first) << "****\n";
93 // if the Value * is not null, and LR is not yet written to the IGNodeList
94 if (!(L->getUserIGNode()) ) {
95 RegClass *const RC = // RegClass of first value in the LR
96 RegClassList[ L->getRegClassID() ];
97 RC->addLRToIG(L); // add this LR to an IG
103 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
104 RegClassList[rc]->createInterferenceGraph();
106 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "LRLists Created!\n";
110 //----------------------------------------------------------------------------
111 // This method will add all interferences at for a given instruction.
112 // Interference occurs only if the LR of Def (Inst or Arg) is of the same reg
113 // class as that of live var. The live var passed to this function is the
114 // LVset AFTER the instruction
115 //----------------------------------------------------------------------------
117 void PhyRegAlloc::addInterference(const Value *Def,
118 const ValueSet *LVSet,
120 ValueSet::const_iterator LIt = LVSet->begin();
122 // get the live range of instruction
123 const LiveRange *const LROfDef = LRI->getLiveRangeForValue( Def );
125 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
126 assert( IGNodeOfDef );
128 RegClass *const RCOfDef = LROfDef->getRegClass();
130 // for each live var in live variable set
131 for ( ; LIt != LVSet->end(); ++LIt) {
133 if (DEBUG_RA >= RA_DEBUG_Verbose)
134 std::cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
136 // get the live range corresponding to live var
137 LiveRange *LROfVar = LRI->getLiveRangeForValue(*LIt);
139 // LROfVar can be null if it is a const since a const
140 // doesn't have a dominating def - see Assumptions above
142 if (LROfDef != LROfVar) // do not set interf for same LR
143 if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
144 RCOfDef->setInterference( LROfDef, LROfVar);
149 //----------------------------------------------------------------------------
150 // For a call instruction, this method sets the CallInterference flag in
151 // the LR of each variable live int the Live Variable Set live after the
152 // call instruction (except the return value of the call instruction - since
153 // the return value does not interfere with that call itself).
154 //----------------------------------------------------------------------------
156 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
157 const ValueSet *LVSetAft) {
158 if (DEBUG_RA >= RA_DEBUG_Interference)
159 std::cerr << "\n For call inst: " << *MInst;
161 // for each live var in live variable set after machine inst
162 for (ValueSet::const_iterator LIt = LVSetAft->begin(), LEnd = LVSetAft->end();
163 LIt != LEnd; ++LIt) {
165 // get the live range corresponding to live var
166 LiveRange *const LR = LRI->getLiveRangeForValue(*LIt );
168 // LR can be null if it is a const since a const
169 // doesn't have a dominating def - see Assumptions above
171 if (DEBUG_RA >= RA_DEBUG_Interference) {
172 std::cerr << "\n\tLR after Call: ";
175 LR->setCallInterference();
176 if (DEBUG_RA >= RA_DEBUG_Interference) {
177 std::cerr << "\n ++After adding call interference for LR: " ;
184 // Now find the LR of the return value of the call
185 // We do this because, we look at the LV set *after* the instruction
186 // to determine, which LRs must be saved across calls. The return value
187 // of the call is live in this set - but it does not interfere with call
188 // (i.e., we can allocate a volatile register to the return value)
189 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
191 if (const Value *RetVal = argDesc->getReturnValue()) {
192 LiveRange *RetValLR = LRI->getLiveRangeForValue( RetVal );
193 assert( RetValLR && "No LR for RetValue of call");
194 RetValLR->clearCallInterference();
197 // If the CALL is an indirect call, find the LR of the function pointer.
198 // That has a call interference because it conflicts with outgoing args.
199 if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
200 LiveRange *AddrValLR = LRI->getLiveRangeForValue( AddrVal );
201 assert( AddrValLR && "No LR for indirect addr val of call");
202 AddrValLR->setCallInterference();
207 //----------------------------------------------------------------------------
208 // This method will walk thru code and create interferences in the IG of
209 // each RegClass. Also, this method calculates the spill cost of each
210 // Live Range (it is done in this method to save another pass over the code).
211 //----------------------------------------------------------------------------
213 void PhyRegAlloc::buildInterferenceGraphs()
215 if (DEBUG_RA >= RA_DEBUG_Interference)
216 std::cerr << "Creating interference graphs ...\n";
218 unsigned BBLoopDepthCost;
219 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
221 const MachineBasicBlock &MBB = *BBI;
222 const BasicBlock *BB = MBB.getBasicBlock();
224 // find the 10^(loop_depth) of this BB
225 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BB));
227 // get the iterator for machine instructions
228 MachineBasicBlock::const_iterator MII = MBB.begin();
230 // iterate over all the machine instructions in BB
231 for ( ; MII != MBB.end(); ++MII) {
232 const MachineInstr *MInst = *MII;
234 // get the LV set after the instruction
235 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BB);
236 bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
239 // set the isCallInterference flag of each live range which extends
240 // across this call instruction. This information is used by graph
241 // coloring algorithm to avoid allocating volatile colors to live ranges
242 // that span across calls (since they have to be saved/restored)
243 setCallInterferences(MInst, &LVSetAI);
246 // iterate over all MI operands to find defs
247 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
248 OpE = MInst->end(); OpI != OpE; ++OpI) {
249 if (OpI.isDefOnly() || OpI.isDefAndUse()) // create a new LR since def
250 addInterference(*OpI, &LVSetAI, isCallInst);
252 // Calculate the spill cost of each live range
253 LiveRange *LR = LRI->getLiveRangeForValue(*OpI);
254 if (LR) LR->addSpillCost(BBLoopDepthCost);
257 // if there are multiple defs in this instruction e.g. in SETX
258 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
259 addInterf4PseudoInstr(MInst);
261 // Also add interference for any implicit definitions in a machine
262 // instr (currently, only calls have this).
263 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
264 for (unsigned z=0; z < NumOfImpRefs; z++)
265 if (MInst->getImplicitOp(z).opIsDefOnly() ||
266 MInst->getImplicitOp(z).opIsDefAndUse())
267 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
269 } // for all machine instructions in BB
270 } // for all BBs in function
272 // add interferences for function arguments. Since there are no explicit
273 // defs in the function for args, we have to add them manually
274 addInterferencesForArgs();
276 if (DEBUG_RA >= RA_DEBUG_Interference)
277 std::cerr << "Interference graphs calculated!\n";
281 //--------------------------------------------------------------------------
282 // Pseudo-instructions may be expanded to multiple instructions by the
283 // assembler. Consequently, all the operands must get distinct registers.
284 // Therefore, we mark all operands of a pseudo-instruction as interfering
286 //--------------------------------------------------------------------------
288 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
289 bool setInterf = false;
291 // iterate over MI operands to find defs
292 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
293 ItE = MInst->end(); It1 != ItE; ++It1) {
294 const LiveRange *LROfOp1 = LRI->getLiveRangeForValue(*It1);
295 assert((LROfOp1 || !It1.isUseOnly())&&"No LR for Def in PSEUDO insruction");
297 MachineInstr::const_val_op_iterator It2 = It1;
298 for (++It2; It2 != ItE; ++It2) {
299 const LiveRange *LROfOp2 = LRI->getLiveRangeForValue(*It2);
302 RegClass *RCOfOp1 = LROfOp1->getRegClass();
303 RegClass *RCOfOp2 = LROfOp2->getRegClass();
305 if (RCOfOp1 == RCOfOp2 ){
306 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
310 } // for all other defs in machine instr
311 } // for all operands in an instruction
313 if (!setInterf && MInst->getNumOperands() > 2) {
314 std::cerr << "\nInterf not set for any operand in pseudo instr:\n";
316 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
321 //----------------------------------------------------------------------------
322 // This method adds interferences for incoming arguments to a function.
323 //----------------------------------------------------------------------------
325 void PhyRegAlloc::addInterferencesForArgs() {
326 // get the InSet of root BB
327 const ValueSet &InSet = LVI->getInSetOfBB(&Fn->front());
329 for (Function::const_aiterator AI = Fn->abegin(); AI != Fn->aend(); ++AI) {
330 // add interferences between args and LVars at start
331 addInterference(AI, &InSet, false);
333 if (DEBUG_RA >= RA_DEBUG_Interference)
334 std::cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
339 //----------------------------------------------------------------------------
340 // This method is called after register allocation is complete to set the
341 // allocated registers in the machine code. This code will add register numbers
342 // to MachineOperands that contain a Value. Also it calls target specific
343 // methods to produce caller saving instructions. At the end, it adds all
344 // additional instructions produced by the register allocator to the
345 // instruction stream.
346 //----------------------------------------------------------------------------
348 //-----------------------------
349 // Utility functions used below
350 //-----------------------------
352 InsertBefore(MachineInstr* newMI,
353 MachineBasicBlock& MBB,
354 MachineBasicBlock::iterator& MII)
356 MII = MBB.insert(MII, newMI);
361 InsertAfter(MachineInstr* newMI,
362 MachineBasicBlock& MBB,
363 MachineBasicBlock::iterator& MII)
365 ++MII; // insert before the next instruction
366 MII = MBB.insert(MII, newMI);
370 DeleteInstruction(MachineBasicBlock& MBB,
371 MachineBasicBlock::iterator& MII)
373 MII = MBB.erase(MII);
377 SubstituteInPlace(MachineInstr* newMI,
378 MachineBasicBlock& MBB,
379 MachineBasicBlock::iterator MII)
385 PrependInstructions(std::vector<MachineInstr *> &IBef,
386 MachineBasicBlock& MBB,
387 MachineBasicBlock::iterator& MII,
388 const std::string& msg)
392 MachineInstr* OrigMI = *MII;
393 std::vector<MachineInstr *>::iterator AdIt;
394 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
397 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
398 std::cerr << msg << "PREPENDed instr:\n " << **AdIt << "\n";
400 InsertBefore(*AdIt, MBB, MII);
406 AppendInstructions(std::vector<MachineInstr *> &IAft,
407 MachineBasicBlock& MBB,
408 MachineBasicBlock::iterator& MII,
409 const std::string& msg)
413 MachineInstr* OrigMI = *MII;
414 std::vector<MachineInstr *>::iterator AdIt;
415 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
418 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
419 std::cerr << msg << "APPENDed instr:\n " << **AdIt << "\n";
421 InsertAfter(*AdIt, MBB, MII);
426 bool PhyRegAlloc::markAllocatedRegs(MachineInstr* MInst)
428 bool instrNeedsSpills = false;
430 // First, set the registers for operands in the machine instruction
431 // if a register was successfully allocated. Do this first because we
432 // will need to know which registers are already used by this instr'n.
433 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
435 MachineOperand& Op = MInst->getOperand(OpNum);
436 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
437 Op.getType() == MachineOperand::MO_CCRegister)
439 const Value *const Val = Op.getVRegValue();
440 if (const LiveRange* LR = LRI->getLiveRangeForValue(Val)) {
441 // Remember if any operand needs spilling
442 instrNeedsSpills |= LR->isMarkedForSpill();
444 // An operand may have a color whether or not it needs spilling
446 MInst->SetRegForOperand(OpNum,
447 MRI.getUnifiedRegNum(LR->getRegClassID(),
451 } // for each operand
453 return instrNeedsSpills;
456 void PhyRegAlloc::updateInstruction(MachineBasicBlock::iterator& MII,
457 MachineBasicBlock &MBB)
459 MachineInstr* MInst = *MII;
460 unsigned Opcode = MInst->getOpCode();
462 // Reset tmp stack positions so they can be reused for each machine instr.
463 MF->getInfo()->popAllTempValues();
465 // Mark the operands for which regs have been allocated.
466 bool instrNeedsSpills = markAllocatedRegs(*MII);
469 // Mark that the operands have been updated. Later,
470 // setRelRegsUsedByThisInst() is called to find registers used by each
471 // MachineInst, and it should not be used for an instruction until
472 // this is done. This flag just serves as a sanity check.
473 OperandsColoredMap[MInst] = true;
476 // Now insert caller-saving code before/after the call.
477 // Do this before inserting spill code since some registers must be
478 // used by save/restore and spill code should not use those registers.
479 if (TM.getInstrInfo().isCall(Opcode)) {
480 AddedInstrns &AI = AddedInstrMap[MInst];
481 insertCallerSavingCode(AI.InstrnsBefore, AI.InstrnsAfter, MInst,
482 MBB.getBasicBlock());
485 // Now insert spill code for remaining operands not allocated to
486 // registers. This must be done even for call return instructions
487 // since those are not handled by the special code above.
488 if (instrNeedsSpills)
489 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
491 MachineOperand& Op = MInst->getOperand(OpNum);
492 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
493 Op.getType() == MachineOperand::MO_CCRegister)
495 const Value* Val = Op.getVRegValue();
496 if (const LiveRange *LR = LRI->getLiveRangeForValue(Val))
497 if (LR->isMarkedForSpill())
498 insertCode4SpilledLR(LR, MII, MBB, OpNum);
500 } // for each operand
503 void PhyRegAlloc::updateMachineCode()
505 // Insert any instructions needed at method entry
506 MachineBasicBlock::iterator MII = MF->front().begin();
507 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MF->front(), MII,
508 "At function entry: \n");
509 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
510 "InstrsAfter should be unnecessary since we are just inserting at "
511 "the function entry point here.");
513 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
516 MachineBasicBlock &MBB = *BBI;
518 // Iterate over all machine instructions in BB and mark operands with
519 // their assigned registers or insert spill code, as appropriate.
520 // Also, fix operands of call/return instructions.
521 for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
522 if (! TM.getInstrInfo().isDummyPhiInstr((*MII)->getOpCode()))
523 updateInstruction(MII, MBB);
525 // Now, move code out of delay slots of branches and returns if needed.
526 // (Also, move "after" code from calls to the last delay slot instruction.)
527 // Moving code out of delay slots is needed in 2 situations:
528 // (1) If this is a branch and it needs instructions inserted after it,
529 // move any existing instructions out of the delay slot so that the
530 // instructions can go into the delay slot. This only supports the
531 // case that #instrsAfter <= #delay slots.
533 // (2) If any instruction in the delay slot needs
534 // instructions inserted, move it out of the delay slot and before the
535 // branch because putting code before or after it would be VERY BAD!
537 // If the annul bit of the branch is set, neither of these is legal!
538 // If so, we need to handle spill differently but annulling is not yet used.
539 for (MachineBasicBlock::iterator MII = MBB.begin();
540 MII != MBB.end(); ++MII)
541 if (unsigned delaySlots =
542 TM.getInstrInfo().getNumDelaySlots((*MII)->getOpCode()))
544 MachineInstr *MInst = *MII, *DelaySlotMI = *(MII+1);
546 // Check the 2 conditions above:
547 // (1) Does a branch need instructions added after it?
548 // (2) O/w does delay slot instr. need instrns before or after?
549 bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
550 TM.getInstrInfo().isReturn(MInst->getOpCode()));
551 bool cond1 = (isBranch &&
552 AddedInstrMap.count(MInst) &&
553 AddedInstrMap[MInst].InstrnsAfter.size() > 0);
554 bool cond2 = (AddedInstrMap.count(DelaySlotMI) &&
555 (AddedInstrMap[DelaySlotMI].InstrnsBefore.size() > 0 ||
556 AddedInstrMap[DelaySlotMI].InstrnsAfter.size() > 0));
560 assert((MInst->getOpCodeFlags() & AnnulFlag) == 0 &&
561 "FIXME: Moving an annulled delay slot instruction!");
562 assert(delaySlots==1 &&
563 "InsertBefore does not yet handle >1 delay slots!");
564 InsertBefore(DelaySlotMI, MBB, MII); // MII pts back to branch
566 // In case (1), delete it and don't replace with anything!
567 // Otherwise (i.e., case (2) only) replace it with a NOP.
569 DeleteInstruction(MBB, ++MII); // MII now points to next inst.
570 --MII; // reset MII for ++MII of loop
573 SubstituteInPlace(BuildMI(TM.getInstrInfo().getNOPOpCode(),1),
574 MBB, MII+1); // replace with NOP
577 std::cerr << "\nRegAlloc: Moved instr. with added code: "
579 << " out of delay slots of instr: " << *MInst;
583 // For non-branch instr with delay slots (probably a call), move
584 // InstrAfter to the instr. in the last delay slot.
585 move2DelayedInstr(*MII, *(MII+delaySlots));
588 // Finally iterate over all instructions in BB and insert before/after
589 for (MachineBasicBlock::iterator MII=MBB.begin(); MII != MBB.end(); ++MII) {
590 MachineInstr *MInst = *MII;
592 // do not process Phis
593 if (TM.getInstrInfo().isDummyPhiInstr(MInst->getOpCode()))
596 // if there are any added instructions...
597 if (AddedInstrMap.count(MInst)) {
598 AddedInstrns &CallAI = AddedInstrMap[MInst];
601 bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
602 TM.getInstrInfo().isReturn(MInst->getOpCode()));
604 AddedInstrMap[MInst].InstrnsAfter.size() <=
605 TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) &&
606 "Cannot put more than #delaySlots instrns after "
607 "branch or return! Need to handle temps differently.");
611 // Temporary sanity checking code to detect whether the same machine
612 // instruction is ever inserted twice before/after a call.
613 // I suspect this is happening but am not sure. --Vikram, 7/1/03.
614 std::set<const MachineInstr*> instrsSeen;
615 for (int i = 0, N = CallAI.InstrnsBefore.size(); i < N; ++i) {
616 assert(instrsSeen.count(CallAI.InstrnsBefore[i]) == 0 &&
617 "Duplicate machine instruction in InstrnsBefore!");
618 instrsSeen.insert(CallAI.InstrnsBefore[i]);
620 for (int i = 0, N = CallAI.InstrnsAfter.size(); i < N; ++i) {
621 assert(instrsSeen.count(CallAI.InstrnsAfter[i]) == 0 &&
622 "Duplicate machine instruction in InstrnsBefore/After!");
623 instrsSeen.insert(CallAI.InstrnsAfter[i]);
627 // Now add the instructions before/after this MI.
628 // We do this here to ensure that spill for an instruction is inserted
629 // as close as possible to an instruction (see above insertCode4Spill)
630 if (! CallAI.InstrnsBefore.empty())
631 PrependInstructions(CallAI.InstrnsBefore, MBB, MII,"");
633 if (! CallAI.InstrnsAfter.empty())
634 AppendInstructions(CallAI.InstrnsAfter, MBB, MII,"");
636 } // if there are any added instructions
637 } // for each machine instruction
642 //----------------------------------------------------------------------------
643 // This method inserts spill code for AN operand whose LR was spilled.
644 // This method may be called several times for a single machine instruction
645 // if it contains many spilled operands. Each time it is called, it finds
646 // a register which is not live at that instruction and also which is not
647 // used by other spilled operands of the same instruction. Then it uses
648 // this register temporarily to accommodate the spilled value.
649 //----------------------------------------------------------------------------
651 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
652 MachineBasicBlock::iterator& MII,
653 MachineBasicBlock &MBB,
654 const unsigned OpNum) {
655 MachineInstr *MInst = *MII;
656 const BasicBlock *BB = MBB.getBasicBlock();
658 assert((! TM.getInstrInfo().isCall(MInst->getOpCode()) || OpNum == 0) &&
659 "Outgoing arg of a call must be handled elsewhere (func arg ok)");
660 assert(! TM.getInstrInfo().isReturn(MInst->getOpCode()) &&
661 "Return value of a ret must be handled elsewhere");
663 MachineOperand& Op = MInst->getOperand(OpNum);
664 bool isDef = Op.opIsDefOnly();
665 bool isDefAndUse = Op.opIsDefAndUse();
666 unsigned RegType = MRI.getRegTypeForLR(LR);
667 int SpillOff = LR->getSpillOffFromFP();
668 RegClass *RC = LR->getRegClass();
670 // Get the live-variable set to find registers free before this instr.
671 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
674 // If this instr. is in the delay slot of a branch or return, we need to
675 // include all live variables before that branch or return -- we don't want to
676 // trample those! Verify that the set is included in the LV set before MInst.
677 if (MII != MBB.begin()) {
678 MachineInstr *PredMI = *(MII-1);
679 if (unsigned DS = TM.getInstrInfo().getNumDelaySlots(PredMI->getOpCode()))
680 assert(set_difference(LVI->getLiveVarSetBeforeMInst(PredMI), LVSetBef)
681 .empty() && "Live-var set before branch should be included in "
682 "live-var set of each delay slot instruction!");
686 MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType) );
688 std::vector<MachineInstr*> MIBef, MIAft;
689 std::vector<MachineInstr*> AdIMid;
691 // Choose a register to hold the spilled value, if one was not preallocated.
692 // This may insert code before and after MInst to free up the value. If so,
693 // this code should be first/last in the spill sequence before/after MInst.
694 int TmpRegU=(LR->hasColor()
695 ? MRI.getUnifiedRegNum(LR->getRegClassID(),LR->getColor())
696 : getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef,MIAft));
698 // Set the operand first so that it this register does not get used
699 // as a scratch register for later calls to getUsableUniRegAtMI below
700 MInst->SetRegForOperand(OpNum, TmpRegU);
702 // get the added instructions for this instruction
703 AddedInstrns &AI = AddedInstrMap[MInst];
705 // We may need a scratch register to copy the spilled value to/from memory.
706 // This may itself have to insert code to free up a scratch register.
707 // Any such code should go before (after) the spill code for a load (store).
708 // The scratch reg is not marked as used because it is only used
709 // for the copy and not used across MInst.
710 int scratchRegType = -1;
712 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
714 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
715 MInst, MIBef, MIAft);
716 assert(scratchReg != MRI.getInvalidRegNum());
719 if (!isDef || isDefAndUse) {
720 // for a USE, we have to load the value of LR from stack to a TmpReg
721 // and use the TmpReg as one operand of instruction
723 // actual loading instruction(s)
724 MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU,
725 RegType, scratchReg);
727 // the actual load should be after the instructions to free up TmpRegU
728 MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
732 if (isDef || isDefAndUse) { // if this is a Def
733 // for a DEF, we have to store the value produced by this instruction
734 // on the stack position allocated for this LR
736 // actual storing instruction(s)
737 MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff,
738 RegType, scratchReg);
740 MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
743 // Finally, insert the entire spill code sequences before/after MInst
744 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
745 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
748 std::cerr << "\nFor Inst:\n " << *MInst;
749 std::cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
750 std::cerr << "; added Instructions:";
751 for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
752 for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
757 //----------------------------------------------------------------------------
758 // This method inserts caller saving/restoring instructions before/after
759 // a call machine instruction. The caller saving/restoring instructions are
761 // ** caller saving instructions
762 // other instructions inserted for the call by ColorCallArg
764 // other instructions inserted for the call ColorCallArg
765 // ** caller restoring instructions
766 //----------------------------------------------------------------------------
769 PhyRegAlloc::insertCallerSavingCode(std::vector<MachineInstr*> &instrnsBefore,
770 std::vector<MachineInstr*> &instrnsAfter,
771 MachineInstr *CallMI,
772 const BasicBlock *BB)
774 assert(TM.getInstrInfo().isCall(CallMI->getOpCode()));
776 // hash set to record which registers were saved/restored
777 hash_set<unsigned> PushedRegSet;
779 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
781 // if the call is to a instrumentation function, do not insert save and
782 // restore instructions the instrumentation function takes care of save
783 // restore for volatile regs.
785 // FIXME: this should be made general, not specific to the reoptimizer!
786 const Function *Callee = argDesc->getCallInst()->getCalledFunction();
787 bool isLLVMFirstTrigger = Callee && Callee->getName() == "llvm_first_trigger";
789 // Now check if the call has a return value (using argDesc) and if so,
790 // find the LR of the TmpInstruction representing the return value register.
791 // (using the last or second-last *implicit operand* of the call MI).
792 // Insert it to to the PushedRegSet since we must not save that register
793 // and restore it after the call.
794 // We do this because, we look at the LV set *after* the instruction
795 // to determine, which LRs must be saved across calls. The return value
796 // of the call is live in this set - but we must not save/restore it.
797 if (const Value *origRetVal = argDesc->getReturnValue()) {
798 unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
799 (argDesc->getIndirectFuncPtr()? 1 : 2));
800 const TmpInstruction* tmpRetVal =
801 cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
802 assert(tmpRetVal->getOperand(0) == origRetVal &&
803 tmpRetVal->getType() == origRetVal->getType() &&
804 "Wrong implicit ref?");
805 LiveRange *RetValLR = LRI->getLiveRangeForValue(tmpRetVal);
806 assert(RetValLR && "No LR for RetValue of call");
808 if (! RetValLR->isMarkedForSpill())
809 PushedRegSet.insert(MRI.getUnifiedRegNum(RetValLR->getRegClassID(),
810 RetValLR->getColor()));
813 const ValueSet &LVSetAft = LVI->getLiveVarSetAfterMInst(CallMI, BB);
814 ValueSet::const_iterator LIt = LVSetAft.begin();
816 // for each live var in live variable set after machine inst
817 for( ; LIt != LVSetAft.end(); ++LIt) {
818 // get the live range corresponding to live var
819 LiveRange *const LR = LRI->getLiveRangeForValue(*LIt);
821 // LR can be null if it is a const since a const
822 // doesn't have a dominating def - see Assumptions above
824 if(! LR->isMarkedForSpill()) {
825 assert(LR->hasColor() && "LR is neither spilled nor colored?");
826 unsigned RCID = LR->getRegClassID();
827 unsigned Color = LR->getColor();
829 if (MRI.isRegVolatile(RCID, Color) ) {
830 // if this is a call to the first-level reoptimizer
831 // instrumentation entry point, and the register is not
832 // modified by call, don't save and restore it.
833 if (isLLVMFirstTrigger && !MRI.modifiedByCall(RCID, Color))
836 // if the value is in both LV sets (i.e., live before and after
837 // the call machine instruction)
838 unsigned Reg = MRI.getUnifiedRegNum(RCID, Color);
840 // if we haven't already pushed this register...
841 if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
842 unsigned RegType = MRI.getRegTypeForLR(LR);
844 // Now get two instructions - to push on stack and pop from stack
845 // and add them to InstrnsBefore and InstrnsAfter of the
848 MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
850 //---- Insert code for pushing the reg on stack ----------
852 std::vector<MachineInstr*> AdIBef, AdIAft;
854 // We may need a scratch register to copy the saved value
855 // to/from memory. This may itself have to insert code to
856 // free up a scratch register. Any such code should go before
857 // the save code. The scratch register, if any, is by default
858 // temporary and not "used" by the instruction unless the
859 // copy code itself decides to keep the value in the scratch reg.
860 int scratchRegType = -1;
862 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
863 { // Find a register not live in the LVSet before CallMI
864 const ValueSet &LVSetBef =
865 LVI->getLiveVarSetBeforeMInst(CallMI, BB);
866 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
867 CallMI, AdIBef, AdIAft);
868 assert(scratchReg != MRI.getInvalidRegNum());
871 if (AdIBef.size() > 0)
872 instrnsBefore.insert(instrnsBefore.end(),
873 AdIBef.begin(), AdIBef.end());
875 MRI.cpReg2MemMI(instrnsBefore, Reg, MRI.getFramePointer(),
876 StackOff, RegType, scratchReg);
878 if (AdIAft.size() > 0)
879 instrnsBefore.insert(instrnsBefore.end(),
880 AdIAft.begin(), AdIAft.end());
882 //---- Insert code for popping the reg from the stack ----------
886 // We may need a scratch register to copy the saved value
887 // from memory. This may itself have to insert code to
888 // free up a scratch register. Any such code should go
889 // after the save code. As above, scratch is not marked "used".
892 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
893 { // Find a register not live in the LVSet after CallMI
894 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetAft,
895 CallMI, AdIBef, AdIAft);
896 assert(scratchReg != MRI.getInvalidRegNum());
899 if (AdIBef.size() > 0)
900 instrnsAfter.insert(instrnsAfter.end(),
901 AdIBef.begin(), AdIBef.end());
903 MRI.cpMem2RegMI(instrnsAfter, MRI.getFramePointer(), StackOff,
904 Reg, RegType, scratchReg);
906 if (AdIAft.size() > 0)
907 instrnsAfter.insert(instrnsAfter.end(),
908 AdIAft.begin(), AdIAft.end());
910 PushedRegSet.insert(Reg);
913 std::cerr << "\nFor call inst:" << *CallMI;
914 std::cerr << " -inserted caller saving instrs: Before:\n\t ";
915 for_each(instrnsBefore.begin(), instrnsBefore.end(),
916 std::mem_fun(&MachineInstr::dump));
917 std::cerr << " -and After:\n\t ";
918 for_each(instrnsAfter.begin(), instrnsAfter.end(),
919 std::mem_fun(&MachineInstr::dump));
921 } // if not already pushed
922 } // if LR has a volatile color
924 } // if there is a LR for Var
925 } // for each value in the LV set after instruction
929 //----------------------------------------------------------------------------
930 // We can use the following method to get a temporary register to be used
931 // BEFORE any given machine instruction. If there is a register available,
932 // this method will simply return that register and set MIBef = MIAft = NULL.
933 // Otherwise, it will return a register and MIAft and MIBef will contain
934 // two instructions used to free up this returned register.
935 // Returned register number is the UNIFIED register number
936 //----------------------------------------------------------------------------
938 int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
939 const ValueSet *LVSetBef,
941 std::vector<MachineInstr*>& MIBef,
942 std::vector<MachineInstr*>& MIAft) {
943 RegClass* RC = getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
945 int RegU = getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
948 // we couldn't find an unused register. Generate code to free up a reg by
949 // saving it on stack and restoring after the instruction
951 int TmpOff = MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
953 RegU = getUniRegNotUsedByThisInst(RC, RegType, MInst);
955 // Check if we need a scratch register to copy this register to memory.
956 int scratchRegType = -1;
957 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
959 int scratchReg = getUsableUniRegAtMI(scratchRegType, LVSetBef,
960 MInst, MIBef, MIAft);
961 assert(scratchReg != MRI.getInvalidRegNum());
963 // We may as well hold the value in the scratch register instead
964 // of copying it to memory and back. But we have to mark the
965 // register as used by this instruction, so it does not get used
966 // as a scratch reg. by another operand or anyone else.
967 ScratchRegsUsed.insert(std::make_pair(MInst, scratchReg));
968 MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
969 MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
972 { // the register can be copied directly to/from memory so do it.
973 MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
974 MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
982 //----------------------------------------------------------------------------
983 // This method is called to get a new unused register that can be used
984 // to accommodate a temporary value. This method may be called several times
985 // for a single machine instruction. Each time it is called, it finds a
986 // register which is not live at that instruction and also which is not used
987 // by other spilled operands of the same instruction. Return register number
988 // is relative to the register class, NOT the unified number.
989 //----------------------------------------------------------------------------
991 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
993 const MachineInstr *MInst,
994 const ValueSet* LVSetBef) {
995 RC->clearColorsUsed(); // Reset array
997 if (LVSetBef == NULL) {
998 LVSetBef = &LVI->getLiveVarSetBeforeMInst(MInst);
999 assert(LVSetBef != NULL && "Unable to get live-var set before MInst?");
1002 ValueSet::const_iterator LIt = LVSetBef->begin();
1004 // for each live var in live variable set after machine inst
1005 for ( ; LIt != LVSetBef->end(); ++LIt) {
1006 // Get the live range corresponding to live var, and its RegClass
1007 LiveRange *const LRofLV = LRI->getLiveRangeForValue(*LIt );
1009 // LR can be null if it is a const since a const
1010 // doesn't have a dominating def - see Assumptions above
1011 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor())
1012 RC->markColorsUsed(LRofLV->getColor(),
1013 MRI.getRegTypeForLR(LRofLV), RegType);
1016 // It is possible that one operand of this MInst was already spilled
1017 // and it received some register temporarily. If that's the case,
1018 // it is recorded in machine operand. We must skip such registers.
1019 setRelRegsUsedByThisInst(RC, RegType, MInst);
1021 int unusedReg = RC->getUnusedColor(RegType); // find first unused color
1023 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
1029 //----------------------------------------------------------------------------
1030 // Get any other register in a register class, other than what is used
1031 // by operands of a machine instruction. Returns the unified reg number.
1032 //----------------------------------------------------------------------------
1034 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
1036 const MachineInstr *MInst) {
1037 RC->clearColorsUsed();
1039 setRelRegsUsedByThisInst(RC, RegType, MInst);
1041 // find the first unused color
1042 int unusedReg = RC->getUnusedColor(RegType);
1043 assert(unusedReg >= 0 &&
1044 "FATAL: No free register could be found in reg class!!");
1046 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
1050 //----------------------------------------------------------------------------
1051 // This method modifies the IsColorUsedArr of the register class passed to it.
1052 // It sets the bits corresponding to the registers used by this machine
1053 // instructions. Both explicit and implicit operands are set.
1054 //----------------------------------------------------------------------------
1056 static void markRegisterUsed(int RegNo, RegClass *RC, int RegType,
1057 const TargetRegInfo &TRI) {
1058 unsigned classId = 0;
1059 int classRegNum = TRI.getClassRegNum(RegNo, classId);
1060 if (RC->getID() == classId)
1061 RC->markColorsUsed(classRegNum, RegType, RegType);
1064 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC, int RegType,
1065 const MachineInstr *MI)
1067 assert(OperandsColoredMap[MI] == true &&
1068 "Illegal to call setRelRegsUsedByThisInst() until colored operands "
1069 "are marked for an instruction.");
1071 // Add the registers already marked as used by the instruction.
1072 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
1073 if (MI->getOperand(i).hasAllocatedReg())
1074 markRegisterUsed(MI->getOperand(i).getAllocatedRegNum(), RC, RegType,MRI);
1076 for (unsigned i = 0, e = MI->getNumImplicitRefs(); i != e; ++i)
1077 if (MI->getImplicitOp(i).hasAllocatedReg())
1078 markRegisterUsed(MI->getImplicitOp(i).getAllocatedRegNum(), RC,
1081 // Add all of the scratch registers that are used to save values across the
1082 // instruction (e.g., for saving state register values).
1083 std::pair<ScratchRegsUsedTy::iterator, ScratchRegsUsedTy::iterator>
1084 IR = ScratchRegsUsed.equal_range(MI);
1085 for (ScratchRegsUsedTy::iterator I = IR.first; I != IR.second; ++I)
1086 markRegisterUsed(I->second, RC, RegType, MRI);
1088 // If there are implicit references, mark their allocated regs as well
1089 for (unsigned z=0; z < MI->getNumImplicitRefs(); z++)
1090 if (const LiveRange*
1091 LRofImpRef = LRI->getLiveRangeForValue(MI->getImplicitRef(z)))
1092 if (LRofImpRef->hasColor())
1093 // this implicit reference is in a LR that received a color
1094 RC->markColorsUsed(LRofImpRef->getColor(),
1095 MRI.getRegTypeForLR(LRofImpRef), RegType);
1099 //----------------------------------------------------------------------------
1100 // If there are delay slots for an instruction, the instructions
1101 // added after it must really go after the delayed instruction(s).
1102 // So, we move the InstrAfter of that instruction to the
1103 // corresponding delayed instruction using the following method.
1104 //----------------------------------------------------------------------------
1106 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
1107 const MachineInstr *DelayedMI)
1109 // "added after" instructions of the original instr
1110 std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
1112 if (DEBUG_RA && OrigAft.size() > 0) {
1113 std::cerr << "\nRegAlloc: Moved InstrnsAfter for: " << *OrigMI;
1114 std::cerr << " to last delay slot instrn: " << *DelayedMI;
1117 // "added after" instructions of the delayed instr
1118 std::vector<MachineInstr *> &DelayedAft=AddedInstrMap[DelayedMI].InstrnsAfter;
1120 // go thru all the "added after instructions" of the original instruction
1121 // and append them to the "added after instructions" of the delayed
1123 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
1125 // empty the "added after instructions" of the original instruction
1130 void PhyRegAlloc::colorIncomingArgs()
1132 MRI.colorMethodArgs(Fn, *LRI, AddedInstrAtEntry.InstrnsBefore,
1133 AddedInstrAtEntry.InstrnsAfter);
1137 //----------------------------------------------------------------------------
1138 // This method determines whether the suggested color of each live range
1139 // is really usable, and then calls its setSuggestedColorUsable() method to
1140 // record the answer. A suggested color is NOT usable when the suggested color
1141 // is volatile AND when there are call interferences.
1142 //----------------------------------------------------------------------------
1144 void PhyRegAlloc::markUnusableSugColors()
1146 LiveRangeMapType::const_iterator HMI = (LRI->getLiveRangeMap())->begin();
1147 LiveRangeMapType::const_iterator HMIEnd = (LRI->getLiveRangeMap())->end();
1149 for (; HMI != HMIEnd ; ++HMI ) {
1151 LiveRange *L = HMI->second; // get the LiveRange
1152 if (L && L->hasSuggestedColor ())
1153 L->setSuggestedColorUsable
1154 (!(MRI.isRegVolatile (L->getRegClassID (), L->getSuggestedColor ())
1155 && L->isCallInterference ()));
1157 } // for all LR's in hash map
1161 //----------------------------------------------------------------------------
1162 // The following method will set the stack offsets of the live ranges that
1163 // are decided to be spilled. This must be called just after coloring the
1164 // LRs using the graph coloring algo. For each live range that is spilled,
1165 // this method allocate a new spill position on the stack.
1166 //----------------------------------------------------------------------------
1168 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1169 if (DEBUG_RA) std::cerr << "\nSetting LR stack offsets for spills...\n";
1171 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
1172 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
1174 for ( ; HMI != HMIEnd ; ++HMI) {
1175 if (HMI->first && HMI->second) {
1176 LiveRange *L = HMI->second; // get the LiveRange
1177 if (L->isMarkedForSpill()) { // NOTE: allocating size of long Type **
1178 int stackOffset = MF->getInfo()->allocateSpilledValue(Type::LongTy);
1179 L->setSpillOffFromFP(stackOffset);
1181 std::cerr << " LR# " << L->getUserIGNode()->getIndex()
1182 << ": stack-offset = " << stackOffset << "\n";
1185 } // for all LR's in hash map
1190 /// AllocInfo - Structure representing one instruction's
1191 /// operand's-worth of register allocation state. We create tables
1192 /// made out of these data structures to generate mapping information
1193 /// for this register allocator. (FIXME: This might move to a header
1194 /// file at some point.)
1197 unsigned Instruction;
1199 unsigned AllocState;
1201 AllocInfo (unsigned Instruction_, unsigned Operand_,
1202 unsigned AllocState_, int Placement_) :
1203 Instruction (Instruction_), Operand (Operand_),
1204 AllocState (AllocState_), Placement (Placement_) { }
1205 /// getConstantType - Return a StructType representing an AllocInfo
1208 static StructType *getConstantType () {
1209 std::vector<const Type *> TV;
1210 TV.push_back (Type::UIntTy);
1211 TV.push_back (Type::UIntTy);
1212 TV.push_back (Type::UIntTy);
1213 TV.push_back (Type::IntTy);
1214 return StructType::get (TV);
1216 /// toConstant - Convert this AllocInfo into an LLVM Constant of type
1217 /// getConstantType(), and return the Constant.
1219 Constant *toConstant () const {
1220 StructType *ST = getConstantType ();
1221 std::vector<Constant *> CV;
1222 CV.push_back (ConstantUInt::get (Type::UIntTy, Instruction));
1223 CV.push_back (ConstantUInt::get (Type::UIntTy, Operand));
1224 CV.push_back (ConstantUInt::get (Type::UIntTy, AllocState));
1225 CV.push_back (ConstantSInt::get (Type::IntTy, Placement));
1226 return ConstantStruct::get (ST, CV);
1231 void PhyRegAlloc::saveState ()
1233 std::vector<Constant *> state;
1235 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap ()->end ();
1236 for (const_inst_iterator II=inst_begin (Fn), IE=inst_end (Fn); II != IE; ++II)
1237 for (unsigned i = 0; i < (*II)->getNumOperands (); ++i) {
1238 const Value *V = (*II)->getOperand (i);
1239 // Don't worry about it unless it's something whose reg. we'll need.
1240 if (!isa<Argument> (V) && !isa<Instruction> (V))
1242 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap ()->find (V);
1243 static const unsigned NotAllocated = 0, Allocated = 1, Spilled = 2;
1244 unsigned AllocState = NotAllocated;
1246 if ((HMI != HMIEnd) && HMI->second) {
1247 LiveRange *L = HMI->second;
1248 assert ((L->hasColor () || L->isMarkedForSpill ())
1249 && "Live range exists but not colored or spilled");
1250 if (L->hasColor()) {
1251 AllocState = Allocated;
1252 Placement = MRI.getUnifiedRegNum (L->getRegClassID (),
1254 } else if (L->isMarkedForSpill ()) {
1255 AllocState = Spilled;
1256 assert (L->hasSpillOffset ()
1257 && "Live range marked for spill but has no spill offset");
1258 Placement = L->getSpillOffFromFP ();
1261 state.push_back (AllocInfo (Insn, i, AllocState,
1262 Placement).toConstant ());
1264 // Convert state into an LLVM ConstantArray, and put it in a
1265 // ConstantStruct (named S) along with its size.
1266 unsigned Size = state.size ();
1267 ArrayType *AT = ArrayType::get (AllocInfo::getConstantType (), Size);
1268 std::vector<const Type *> TV;
1269 TV.push_back (Type::UIntTy);
1271 StructType *ST = StructType::get (TV);
1272 std::vector<Constant *> CV;
1273 CV.push_back (ConstantUInt::get (Type::UIntTy, Size));
1274 CV.push_back (ConstantArray::get (AT, state));
1275 Constant *S = ConstantStruct::get (ST, CV);
1276 // Save S in the map containing register allocator state for this module.
1277 FnAllocState[Fn] = S;
1281 bool PhyRegAlloc::doFinalization (Module &M) {
1282 if (!SaveRegAllocState)
1283 return false; // Nothing to do here, unless we're saving state.
1285 // Convert FnAllocState to a single Constant array and add it
1287 ArrayType *AT = ArrayType::get (AllocInfo::getConstantType (), 0);
1288 std::vector<const Type *> TV;
1289 TV.push_back (Type::UIntTy);
1291 PointerType *PT = PointerType::get (StructType::get (TV));
1293 std::vector<Constant *> allstate;
1294 for (Module::iterator I = M.begin (), E = M.end (); I != E; ++I) {
1296 if (FnAllocState.find (F) == FnAllocState.end ()) {
1297 allstate.push_back (ConstantPointerNull::get (PT));
1299 GlobalVariable *GV =
1300 new GlobalVariable (FnAllocState[F]->getType (), true,
1301 GlobalValue::InternalLinkage, FnAllocState[F],
1302 F->getName () + ".regAllocState", &M);
1303 // Have: { uint, [Size x { uint, uint, uint, int }] } *
1304 // Cast it to: { uint, [0 x { uint, uint, uint, int }] } *
1305 Constant *CE = ConstantExpr::getCast (ConstantPointerRef::get (GV), PT);
1306 allstate.push_back (CE);
1310 unsigned Size = allstate.size ();
1311 // Final structure type is:
1312 // { uint, [Size x { uint, [0 x { uint, uint, uint, int }] } *] }
1313 std::vector<const Type *> TV2;
1314 TV2.push_back (Type::UIntTy);
1315 ArrayType *AT2 = ArrayType::get (PT, Size);
1316 TV2.push_back (AT2);
1317 StructType *ST2 = StructType::get (TV2);
1318 std::vector<Constant *> CV2;
1319 CV2.push_back (ConstantUInt::get (Type::UIntTy, Size));
1320 CV2.push_back (ConstantArray::get (AT2, allstate));
1321 new GlobalVariable (ST2, true, GlobalValue::InternalLinkage,
1322 ConstantStruct::get (ST2, CV2), "_llvm_regAllocState",
1324 return false; // No error.
1328 //----------------------------------------------------------------------------
1329 // The entry point to Register Allocation
1330 //----------------------------------------------------------------------------
1332 bool PhyRegAlloc::runOnFunction (Function &F) {
1334 std::cerr << "\n********* Function "<< F.getName () << " ***********\n";
1337 MF = &MachineFunction::get (Fn);
1338 LVI = &getAnalysis<FunctionLiveVarInfo> ();
1339 LRI = new LiveRangeInfo (Fn, TM, RegClassList);
1340 LoopDepthCalc = &getAnalysis<LoopInfo> ();
1342 // Create each RegClass for the target machine and add it to the
1343 // RegClassList. This must be done before calling constructLiveRanges().
1344 for (unsigned rc = 0; rc != NumOfRegClasses; ++rc)
1345 RegClassList.push_back (new RegClass (Fn, &TM.getRegInfo (),
1346 MRI.getMachineRegClass (rc)));
1348 LRI->constructLiveRanges(); // create LR info
1349 if (DEBUG_RA >= RA_DEBUG_LiveRanges)
1350 LRI->printLiveRanges();
1352 createIGNodeListsAndIGs(); // create IGNode list and IGs
1354 buildInterferenceGraphs(); // build IGs in all reg classes
1356 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1357 // print all LRs in all reg classes
1358 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1359 RegClassList[rc]->printIGNodeList();
1361 // print IGs in all register classes
1362 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1363 RegClassList[rc]->printIG();
1366 LRI->coalesceLRs(); // coalesce all live ranges
1368 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1369 // print all LRs in all reg classes
1370 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1371 RegClassList[rc]->printIGNodeList();
1373 // print IGs in all register classes
1374 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1375 RegClassList[rc]->printIG();
1378 // mark un-usable suggested color before graph coloring algorithm.
1379 // When this is done, the graph coloring algo will not reserve
1380 // suggested color unnecessarily - they can be used by another LR
1381 markUnusableSugColors();
1383 // color all register classes using the graph coloring algo
1384 for (unsigned rc=0; rc < NumOfRegClasses ; rc++)
1385 RegClassList[rc]->colorAllRegs();
1387 // After graph coloring, if some LRs did not receive a color (i.e, spilled)
1388 // a position for such spilled LRs
1389 allocateStackSpace4SpilledLRs();
1391 // Reset the temp. area on the stack before use by the first instruction.
1392 // This will also happen after updating each instruction.
1393 MF->getInfo()->popAllTempValues();
1395 // color incoming args - if the correct color was not received
1396 // insert code to copy to the correct register
1397 colorIncomingArgs();
1399 // Save register allocation state for this function in a Constant.
1400 if (SaveRegAllocState)
1403 // Now update the machine code with register names and add any
1404 // additional code inserted by the register allocator to the instruction
1406 updateMachineCode();
1409 std::cerr << "\n**** Machine Code After Register Allocation:\n\n";
1413 // Tear down temporary data structures
1414 for (unsigned rc = 0; rc < NumOfRegClasses; ++rc)
1415 delete RegClassList[rc];
1416 RegClassList.clear ();
1417 AddedInstrMap.clear ();
1418 OperandsColoredMap.clear ();
1419 ScratchRegsUsed.clear ();
1420 AddedInstrAtEntry.clear ();
1423 if (DEBUG_RA) std::cerr << "\nRegister allocation complete!\n";
1424 return false; // Function was not modified