1 //===-- PhyRegAlloc.cpp ---------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Traditional graph-coloring global register allocator currently used
11 // by the SPARC back-end.
13 // NOTE: This register allocator has some special support
14 // for the Reoptimizer, such as not saving some registers on calls to
15 // the first-level instrumentation function.
17 // NOTE 2: This register allocator can save its state in a global
18 // variable in the module it's working on. This feature is not
19 // thread-safe; if you have doubts, leave it turned off.
21 //===----------------------------------------------------------------------===//
23 #include "AllocInfo.h"
25 #include "PhyRegAlloc.h"
26 #include "RegAllocCommon.h"
28 #include "../LiveVar/FunctionLiveVarInfo.h"
29 #include "llvm/Constants.h"
30 #include "llvm/DerivedTypes.h"
31 #include "llvm/iPHINode.h"
32 #include "llvm/iOther.h"
33 #include "llvm/Module.h"
34 #include "llvm/Type.h"
35 #include "llvm/Analysis/LoopInfo.h"
36 #include "llvm/CodeGen/InstrSelection.h"
37 #include "llvm/CodeGen/MachineCodeForInstruction.h"
38 #include "llvm/CodeGen/MachineFunction.h"
39 #include "llvm/CodeGen/MachineFunctionInfo.h"
40 #include "llvm/CodeGen/MachineInstr.h"
41 #include "llvm/CodeGen/MachineInstrBuilder.h"
42 #include "../MachineInstrAnnot.h"
43 #include "llvm/CodeGen/Passes.h"
44 #include "llvm/Support/InstIterator.h"
45 #include "llvm/Target/TargetInstrInfo.h"
46 #include "Support/CommandLine.h"
47 #include "Support/SetOperations.h"
48 #include "Support/STLExtras.h"
54 RegAllocDebugLevel_t DEBUG_RA;
56 static cl::opt<RegAllocDebugLevel_t, true>
57 DRA_opt("dregalloc", cl::Hidden, cl::location(DEBUG_RA),
58 cl::desc("enable register allocation debugging information"),
60 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
61 clEnumValN(RA_DEBUG_Results, "y", "debug output for allocation results"),
62 clEnumValN(RA_DEBUG_Coloring, "c", "debug output for graph coloring step"),
63 clEnumValN(RA_DEBUG_Interference,"ig","debug output for interference graphs"),
64 clEnumValN(RA_DEBUG_LiveRanges , "lr","debug output for live ranges"),
65 clEnumValN(RA_DEBUG_Verbose, "v", "extra debug output"),
68 /// The reoptimizer wants to be able to grovel through the register
69 /// allocator's state after it has done its job. This is a hack.
71 PhyRegAlloc::SavedStateMapTy ExportedFnAllocState;
72 bool SaveRegAllocState = false;
73 bool SaveStateToModule = true;
74 static cl::opt<bool, true>
75 SaveRegAllocStateOpt("save-ra-state", cl::Hidden,
76 cl::location (SaveRegAllocState),
78 cl::desc("write reg. allocator state into module"));
80 FunctionPass *getRegisterAllocator(TargetMachine &T) {
81 return new PhyRegAlloc (T);
84 void PhyRegAlloc::getAnalysisUsage(AnalysisUsage &AU) const {
85 AU.addRequired<LoopInfo> ();
86 AU.addRequired<FunctionLiveVarInfo> ();
90 /// Initialize interference graphs (one in each reg class) and IGNodeLists
91 /// (one in each IG). The actual nodes will be pushed later.
93 void PhyRegAlloc::createIGNodeListsAndIGs() {
94 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "Creating LR lists ...\n";
96 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
97 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
99 for (; HMI != HMIEnd ; ++HMI ) {
101 LiveRange *L = HMI->second; // get the LiveRange
103 if (DEBUG_RA && !isa<ConstantIntegral> (HMI->first))
104 std::cerr << "\n**** ?!?WARNING: NULL LIVE RANGE FOUND FOR: "
105 << RAV(HMI->first) << "****\n";
109 // if the Value * is not null, and LR is not yet written to the IGNodeList
110 if (!(L->getUserIGNode()) ) {
111 RegClass *const RC = // RegClass of first value in the LR
112 RegClassList[ L->getRegClassID() ];
113 RC->addLRToIG(L); // add this LR to an IG
119 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
120 RegClassList[rc]->createInterferenceGraph();
122 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "LRLists Created!\n";
126 /// Add all interferences for a given instruction. Interference occurs only
127 /// if the LR of Def (Inst or Arg) is of the same reg class as that of live
128 /// var. The live var passed to this function is the LVset AFTER the
131 void PhyRegAlloc::addInterference(const Value *Def, const ValueSet *LVSet,
133 ValueSet::const_iterator LIt = LVSet->begin();
135 // get the live range of instruction
136 const LiveRange *const LROfDef = LRI->getLiveRangeForValue( Def );
138 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
139 assert( IGNodeOfDef );
141 RegClass *const RCOfDef = LROfDef->getRegClass();
143 // for each live var in live variable set
144 for ( ; LIt != LVSet->end(); ++LIt) {
146 if (DEBUG_RA >= RA_DEBUG_Verbose)
147 std::cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
149 // get the live range corresponding to live var
150 LiveRange *LROfVar = LRI->getLiveRangeForValue(*LIt);
152 // LROfVar can be null if it is a const since a const
153 // doesn't have a dominating def - see Assumptions above
155 if (LROfDef != LROfVar) // do not set interf for same LR
156 if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
157 RCOfDef->setInterference( LROfDef, LROfVar);
162 /// For a call instruction, this method sets the CallInterference flag in
163 /// the LR of each variable live in the Live Variable Set live after the
164 /// call instruction (except the return value of the call instruction - since
165 /// the return value does not interfere with that call itself).
167 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
168 const ValueSet *LVSetAft) {
169 if (DEBUG_RA >= RA_DEBUG_Interference)
170 std::cerr << "\n For call inst: " << *MInst;
172 // for each live var in live variable set after machine inst
173 for (ValueSet::const_iterator LIt = LVSetAft->begin(), LEnd = LVSetAft->end();
174 LIt != LEnd; ++LIt) {
176 // get the live range corresponding to live var
177 LiveRange *const LR = LRI->getLiveRangeForValue(*LIt );
179 // LR can be null if it is a const since a const
180 // doesn't have a dominating def - see Assumptions above
182 if (DEBUG_RA >= RA_DEBUG_Interference) {
183 std::cerr << "\n\tLR after Call: ";
186 LR->setCallInterference();
187 if (DEBUG_RA >= RA_DEBUG_Interference) {
188 std::cerr << "\n ++After adding call interference for LR: " ;
195 // Now find the LR of the return value of the call
196 // We do this because, we look at the LV set *after* the instruction
197 // to determine, which LRs must be saved across calls. The return value
198 // of the call is live in this set - but it does not interfere with call
199 // (i.e., we can allocate a volatile register to the return value)
200 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
202 if (const Value *RetVal = argDesc->getReturnValue()) {
203 LiveRange *RetValLR = LRI->getLiveRangeForValue( RetVal );
204 assert( RetValLR && "No LR for RetValue of call");
205 RetValLR->clearCallInterference();
208 // If the CALL is an indirect call, find the LR of the function pointer.
209 // That has a call interference because it conflicts with outgoing args.
210 if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
211 LiveRange *AddrValLR = LRI->getLiveRangeForValue( AddrVal );
212 assert( AddrValLR && "No LR for indirect addr val of call");
213 AddrValLR->setCallInterference();
218 /// Create interferences in the IG of each RegClass, and calculate the spill
219 /// cost of each Live Range (it is done in this method to save another pass
222 void PhyRegAlloc::buildInterferenceGraphs() {
223 if (DEBUG_RA >= RA_DEBUG_Interference)
224 std::cerr << "Creating interference graphs ...\n";
226 unsigned BBLoopDepthCost;
227 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
229 const MachineBasicBlock &MBB = *BBI;
230 const BasicBlock *BB = MBB.getBasicBlock();
232 // find the 10^(loop_depth) of this BB
233 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BB));
235 // get the iterator for machine instructions
236 MachineBasicBlock::const_iterator MII = MBB.begin();
238 // iterate over all the machine instructions in BB
239 for ( ; MII != MBB.end(); ++MII) {
240 const MachineInstr *MInst = MII;
242 // get the LV set after the instruction
243 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BB);
244 bool isCallInst = TM.getInstrInfo()->isCall(MInst->getOpcode());
247 // set the isCallInterference flag of each live range which extends
248 // across this call instruction. This information is used by graph
249 // coloring algorithm to avoid allocating volatile colors to live ranges
250 // that span across calls (since they have to be saved/restored)
251 setCallInterferences(MInst, &LVSetAI);
254 // iterate over all MI operands to find defs
255 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
256 OpE = MInst->end(); OpI != OpE; ++OpI) {
257 if (OpI.isDef()) // create a new LR since def
258 addInterference(*OpI, &LVSetAI, isCallInst);
260 // Calculate the spill cost of each live range
261 LiveRange *LR = LRI->getLiveRangeForValue(*OpI);
262 if (LR) LR->addSpillCost(BBLoopDepthCost);
265 // Mark all operands of pseudo-instructions as interfering with one
266 // another. This must be done because pseudo-instructions may be
267 // expanded to multiple instructions by the assembler, so all the
268 // operands must get distinct registers.
269 if (TM.getInstrInfo()->isPseudoInstr(MInst->getOpcode()))
270 addInterf4PseudoInstr(MInst);
272 // Also add interference for any implicit definitions in a machine
273 // instr (currently, only calls have this).
274 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
275 for (unsigned z=0; z < NumOfImpRefs; z++)
276 if (MInst->getImplicitOp(z).isDef())
277 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
279 } // for all machine instructions in BB
280 } // for all BBs in function
282 // add interferences for function arguments. Since there are no explicit
283 // defs in the function for args, we have to add them manually
284 addInterferencesForArgs();
286 if (DEBUG_RA >= RA_DEBUG_Interference)
287 std::cerr << "Interference graphs calculated!\n";
291 /// Mark all operands of the given MachineInstr as interfering with one
294 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
295 bool setInterf = false;
297 // iterate over MI operands to find defs
298 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
299 ItE = MInst->end(); It1 != ItE; ++It1) {
300 const LiveRange *LROfOp1 = LRI->getLiveRangeForValue(*It1);
301 assert((LROfOp1 || It1.isDef()) && "No LR for Def in PSEUDO insruction");
303 MachineInstr::const_val_op_iterator It2 = It1;
304 for (++It2; It2 != ItE; ++It2) {
305 const LiveRange *LROfOp2 = LRI->getLiveRangeForValue(*It2);
308 RegClass *RCOfOp1 = LROfOp1->getRegClass();
309 RegClass *RCOfOp2 = LROfOp2->getRegClass();
311 if (RCOfOp1 == RCOfOp2 ){
312 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
316 } // for all other defs in machine instr
317 } // for all operands in an instruction
319 if (!setInterf && MInst->getNumOperands() > 2) {
320 std::cerr << "\nInterf not set for any operand in pseudo instr:\n";
322 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
327 /// Add interferences for incoming arguments to a function.
329 void PhyRegAlloc::addInterferencesForArgs() {
330 // get the InSet of root BB
331 const ValueSet &InSet = LVI->getInSetOfBB(&Fn->front());
333 for (Function::const_aiterator AI = Fn->abegin(); AI != Fn->aend(); ++AI) {
334 // add interferences between args and LVars at start
335 addInterference(AI, &InSet, false);
337 if (DEBUG_RA >= RA_DEBUG_Interference)
338 std::cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
343 /// The following are utility functions used solely by updateMachineCode and
344 /// the functions that it calls. They should probably be folded back into
345 /// updateMachineCode at some point.
348 // used by: updateMachineCode (1 time), PrependInstructions (1 time)
349 inline void InsertBefore(MachineInstr* newMI, MachineBasicBlock& MBB,
350 MachineBasicBlock::iterator& MII) {
351 MII = MBB.insert(MII, newMI);
355 // used by: AppendInstructions (1 time)
356 inline void InsertAfter(MachineInstr* newMI, MachineBasicBlock& MBB,
357 MachineBasicBlock::iterator& MII) {
358 ++MII; // insert before the next instruction
359 MII = MBB.insert(MII, newMI);
362 // used by: updateMachineCode (2 times)
363 inline void PrependInstructions(std::vector<MachineInstr *> &IBef,
364 MachineBasicBlock& MBB,
365 MachineBasicBlock::iterator& MII,
366 const std::string& msg) {
368 MachineInstr* OrigMI = MII;
369 std::vector<MachineInstr *>::iterator AdIt;
370 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt) {
372 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
373 std::cerr << msg << "PREPENDed instr:\n " << **AdIt << "\n";
375 InsertBefore(*AdIt, MBB, MII);
380 // used by: updateMachineCode (1 time)
381 inline void AppendInstructions(std::vector<MachineInstr *> &IAft,
382 MachineBasicBlock& MBB,
383 MachineBasicBlock::iterator& MII,
384 const std::string& msg) {
386 MachineInstr* OrigMI = MII;
387 std::vector<MachineInstr *>::iterator AdIt;
388 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
390 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
391 std::cerr << msg << "APPENDed instr:\n " << **AdIt << "\n";
393 InsertAfter(*AdIt, MBB, MII);
398 /// Set the registers for operands in the given MachineInstr, if a register was
399 /// successfully allocated. Return true if any of its operands has been marked
402 bool PhyRegAlloc::markAllocatedRegs(MachineInstr* MInst)
404 bool instrNeedsSpills = false;
406 // First, set the registers for operands in the machine instruction
407 // if a register was successfully allocated. Do this first because we
408 // will need to know which registers are already used by this instr'n.
409 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
410 MachineOperand& Op = MInst->getOperand(OpNum);
411 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
412 Op.getType() == MachineOperand::MO_CCRegister) {
413 const Value *const Val = Op.getVRegValue();
414 if (const LiveRange* LR = LRI->getLiveRangeForValue(Val)) {
415 // Remember if any operand needs spilling
416 instrNeedsSpills |= LR->isMarkedForSpill();
418 // An operand may have a color whether or not it needs spilling
420 MInst->SetRegForOperand(OpNum,
421 MRI.getUnifiedRegNum(LR->getRegClassID(),
425 } // for each operand
427 return instrNeedsSpills;
430 /// Mark allocated registers (using markAllocatedRegs()) on the instruction
431 /// that MII points to. Then, if it's a call instruction, insert caller-saving
432 /// code before and after it. Finally, insert spill code before and after it,
433 /// using insertCode4SpilledLR().
435 void PhyRegAlloc::updateInstruction(MachineBasicBlock::iterator& MII,
436 MachineBasicBlock &MBB) {
437 MachineInstr* MInst = MII;
438 unsigned Opcode = MInst->getOpcode();
440 // Reset tmp stack positions so they can be reused for each machine instr.
441 MF->getInfo()->popAllTempValues();
443 // Mark the operands for which regs have been allocated.
444 bool instrNeedsSpills = markAllocatedRegs(MII);
447 // Mark that the operands have been updated. Later,
448 // setRelRegsUsedByThisInst() is called to find registers used by each
449 // MachineInst, and it should not be used for an instruction until
450 // this is done. This flag just serves as a sanity check.
451 OperandsColoredMap[MInst] = true;
454 // Now insert caller-saving code before/after the call.
455 // Do this before inserting spill code since some registers must be
456 // used by save/restore and spill code should not use those registers.
457 if (TM.getInstrInfo()->isCall(Opcode)) {
458 AddedInstrns &AI = AddedInstrMap[MInst];
459 insertCallerSavingCode(AI.InstrnsBefore, AI.InstrnsAfter, MInst,
460 MBB.getBasicBlock());
463 // Now insert spill code for remaining operands not allocated to
464 // registers. This must be done even for call return instructions
465 // since those are not handled by the special code above.
466 if (instrNeedsSpills)
467 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) {
471 const Value* Val = Op.getVRegValue();
472 if (const LiveRange *LR = LRI->getLiveRangeForValue(Val))
473 if (LR->isMarkedForSpill())
474 insertCode4SpilledLR(LR, MII, MBB, OpNum);
476 } // for each operand
479 /// Iterate over all the MachineBasicBlocks in the current function and set
480 /// the allocated registers for each instruction (using updateInstruction()),
481 /// after register allocation is complete. Then move code out of delay slots.
483 void PhyRegAlloc::updateMachineCode()
485 // Insert any instructions needed at method entry
486 MachineBasicBlock::iterator MII = MF->front().begin();
487 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MF->front(), MII,
488 "At function entry: \n");
489 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
490 "InstrsAfter should be unnecessary since we are just inserting at "
491 "the function entry point here.");
493 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
495 MachineBasicBlock &MBB = *BBI;
497 // Iterate over all machine instructions in BB and mark operands with
498 // their assigned registers or insert spill code, as appropriate.
499 // Also, fix operands of call/return instructions.
500 for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
501 if (! TM.getInstrInfo()->isDummyPhiInstr(MII->getOpcode()))
502 updateInstruction(MII, MBB);
504 // Now, move code out of delay slots of branches and returns if needed.
505 // (Also, move "after" code from calls to the last delay slot instruction.)
506 // Moving code out of delay slots is needed in 2 situations:
507 // (1) If this is a branch and it needs instructions inserted after it,
508 // move any existing instructions out of the delay slot so that the
509 // instructions can go into the delay slot. This only supports the
510 // case that #instrsAfter <= #delay slots.
512 // (2) If any instruction in the delay slot needs
513 // instructions inserted, move it out of the delay slot and before the
514 // branch because putting code before or after it would be VERY BAD!
516 // If the annul bit of the branch is set, neither of these is legal!
517 // If so, we need to handle spill differently but annulling is not yet used.
518 for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
519 if (unsigned delaySlots =
520 TM.getInstrInfo()->getNumDelaySlots(MII->getOpcode())) {
521 MachineBasicBlock::iterator DelaySlotMI = next(MII);
522 assert(DelaySlotMI != MBB.end() && "no instruction for delay slot");
524 // Check the 2 conditions above:
525 // (1) Does a branch need instructions added after it?
526 // (2) O/w does delay slot instr. need instrns before or after?
527 bool isBranch = (TM.getInstrInfo()->isBranch(MII->getOpcode()) ||
528 TM.getInstrInfo()->isReturn(MII->getOpcode()));
529 bool cond1 = (isBranch &&
530 AddedInstrMap.count(MII) &&
531 AddedInstrMap[MII].InstrnsAfter.size() > 0);
532 bool cond2 = (AddedInstrMap.count(DelaySlotMI) &&
533 (AddedInstrMap[DelaySlotMI].InstrnsBefore.size() > 0 ||
534 AddedInstrMap[DelaySlotMI].InstrnsAfter.size() > 0));
536 if (cond1 || cond2) {
537 assert(delaySlots==1 &&
538 "InsertBefore does not yet handle >1 delay slots!");
541 std::cerr << "\nRegAlloc: Moved instr. with added code: "
543 << " out of delay slots of instr: " << *MII;
546 // move instruction before branch
547 MBB.insert(MII, MBB.remove(DelaySlotMI++));
549 // On cond1 we are done (we already moved the
550 // instruction out of the delay slot). On cond2 we need
551 // to insert a nop in place of the moved instruction
553 MBB.insert(MII, BuildMI(TM.getInstrInfo()->getNOPOpCode(),1));
557 // For non-branch instr with delay slots (probably a call), move
558 // InstrAfter to the instr. in the last delay slot.
559 MachineBasicBlock::iterator tmp = next(MII, delaySlots);
560 move2DelayedInstr(MII, tmp);
564 // Finally iterate over all instructions in BB and insert before/after
565 for (MachineBasicBlock::iterator MII=MBB.begin(); MII != MBB.end(); ++MII) {
566 MachineInstr *MInst = MII;
568 // do not process Phis
569 if (TM.getInstrInfo()->isDummyPhiInstr(MInst->getOpcode()))
572 // if there are any added instructions...
573 if (AddedInstrMap.count(MInst)) {
574 AddedInstrns &CallAI = AddedInstrMap[MInst];
577 bool isBranch = (TM.getInstrInfo()->isBranch(MInst->getOpcode()) ||
578 TM.getInstrInfo()->isReturn(MInst->getOpcode()));
580 AddedInstrMap[MInst].InstrnsAfter.size() <=
581 TM.getInstrInfo()->getNumDelaySlots(MInst->getOpcode())) &&
582 "Cannot put more than #delaySlots instrns after "
583 "branch or return! Need to handle temps differently.");
587 // Temporary sanity checking code to detect whether the same machine
588 // instruction is ever inserted twice before/after a call.
589 // I suspect this is happening but am not sure. --Vikram, 7/1/03.
590 std::set<const MachineInstr*> instrsSeen;
591 for (int i = 0, N = CallAI.InstrnsBefore.size(); i < N; ++i) {
592 assert(instrsSeen.count(CallAI.InstrnsBefore[i]) == 0 &&
593 "Duplicate machine instruction in InstrnsBefore!");
594 instrsSeen.insert(CallAI.InstrnsBefore[i]);
596 for (int i = 0, N = CallAI.InstrnsAfter.size(); i < N; ++i) {
597 assert(instrsSeen.count(CallAI.InstrnsAfter[i]) == 0 &&
598 "Duplicate machine instruction in InstrnsBefore/After!");
599 instrsSeen.insert(CallAI.InstrnsAfter[i]);
603 // Now add the instructions before/after this MI.
604 // We do this here to ensure that spill for an instruction is inserted
605 // as close as possible to an instruction (see above insertCode4Spill)
606 if (! CallAI.InstrnsBefore.empty())
607 PrependInstructions(CallAI.InstrnsBefore, MBB, MII,"");
609 if (! CallAI.InstrnsAfter.empty())
610 AppendInstructions(CallAI.InstrnsAfter, MBB, MII,"");
612 } // if there are any added instructions
613 } // for each machine instruction
618 /// Insert spill code for AN operand whose LR was spilled. May be called
619 /// repeatedly for a single MachineInstr if it has many spilled operands. On
620 /// each call, it finds a register which is not live at that instruction and
621 /// also which is not used by other spilled operands of the same
622 /// instruction. Then it uses this register temporarily to accommodate the
625 void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
626 MachineBasicBlock::iterator& MII,
627 MachineBasicBlock &MBB,
628 const unsigned OpNum) {
629 MachineInstr *MInst = MII;
630 const BasicBlock *BB = MBB.getBasicBlock();
632 assert((! TM.getInstrInfo()->isCall(MInst->getOpcode()) || OpNum == 0) &&
633 "Outgoing arg of a call must be handled elsewhere (func arg ok)");
634 assert(! TM.getInstrInfo()->isReturn(MInst->getOpcode()) &&
635 "Return value of a ret must be handled elsewhere");
637 MachineOperand& Op = MInst->getOperand(OpNum);
638 bool isDef = Op.isDef();
639 bool isUse = Op.isUse();
640 unsigned RegType = MRI.getRegTypeForLR(LR);
641 int SpillOff = LR->getSpillOffFromFP();
642 RegClass *RC = LR->getRegClass();
644 // Get the live-variable set to find registers free before this instr.
645 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
648 // If this instr. is in the delay slot of a branch or return, we need to
649 // include all live variables before that branch or return -- we don't want to
650 // trample those! Verify that the set is included in the LV set before MInst.
651 if (MII != MBB.begin()) {
652 MachineBasicBlock::iterator PredMI = prior(MII);
653 if (unsigned DS = TM.getInstrInfo()->getNumDelaySlots(PredMI->getOpcode()))
654 assert(set_difference(LVI->getLiveVarSetBeforeMInst(PredMI), LVSetBef)
655 .empty() && "Live-var set before branch should be included in "
656 "live-var set of each delay slot instruction!");
660 MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
662 std::vector<MachineInstr*> MIBef, MIAft;
663 std::vector<MachineInstr*> AdIMid;
665 // Choose a register to hold the spilled value, if one was not preallocated.
666 // This may insert code before and after MInst to free up the value. If so,
667 // this code should be first/last in the spill sequence before/after MInst.
668 int TmpRegU=(LR->hasColor()
669 ? MRI.getUnifiedRegNum(LR->getRegClassID(),LR->getColor())
670 : getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef,MIAft));
672 // Set the operand first so that it this register does not get used
673 // as a scratch register for later calls to getUsableUniRegAtMI below
674 MInst->SetRegForOperand(OpNum, TmpRegU);
676 // get the added instructions for this instruction
677 AddedInstrns &AI = AddedInstrMap[MInst];
679 // We may need a scratch register to copy the spilled value to/from memory.
680 // This may itself have to insert code to free up a scratch register.
681 // Any such code should go before (after) the spill code for a load (store).
682 // The scratch reg is not marked as used because it is only used
683 // for the copy and not used across MInst.
684 int scratchRegType = -1;
686 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType)) {
687 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
688 MInst, MIBef, MIAft);
689 assert(scratchReg != MRI.getInvalidRegNum());
693 // for a USE, we have to load the value of LR from stack to a TmpReg
694 // and use the TmpReg as one operand of instruction
696 // actual loading instruction(s)
697 MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU,
698 RegType, scratchReg);
700 // the actual load should be after the instructions to free up TmpRegU
701 MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
705 if (isDef) { // if this is a Def
706 // for a DEF, we have to store the value produced by this instruction
707 // on the stack position allocated for this LR
709 // actual storing instruction(s)
710 MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff,
711 RegType, scratchReg);
713 MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
716 // Finally, insert the entire spill code sequences before/after MInst
717 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
718 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
721 std::cerr << "\nFor Inst:\n " << *MInst;
722 std::cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
723 std::cerr << "; added Instructions:";
724 for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
725 for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
730 /// Insert caller saving/restoring instructions before/after a call machine
731 /// instruction (before or after any other instructions that were inserted for
735 PhyRegAlloc::insertCallerSavingCode(std::vector<MachineInstr*> &instrnsBefore,
736 std::vector<MachineInstr*> &instrnsAfter,
737 MachineInstr *CallMI,
738 const BasicBlock *BB) {
739 assert(TM.getInstrInfo()->isCall(CallMI->getOpcode()));
741 // hash set to record which registers were saved/restored
742 hash_set<unsigned> PushedRegSet;
744 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
746 // if the call is to a instrumentation function, do not insert save and
747 // restore instructions the instrumentation function takes care of save
748 // restore for volatile regs.
750 // FIXME: this should be made general, not specific to the reoptimizer!
751 const Function *Callee = argDesc->getCallInst()->getCalledFunction();
752 bool isLLVMFirstTrigger = Callee && Callee->getName() == "llvm_first_trigger";
754 // Now check if the call has a return value (using argDesc) and if so,
755 // find the LR of the TmpInstruction representing the return value register.
756 // (using the last or second-last *implicit operand* of the call MI).
757 // Insert it to to the PushedRegSet since we must not save that register
758 // and restore it after the call.
759 // We do this because, we look at the LV set *after* the instruction
760 // to determine, which LRs must be saved across calls. The return value
761 // of the call is live in this set - but we must not save/restore it.
762 if (const Value *origRetVal = argDesc->getReturnValue()) {
763 unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
764 (argDesc->getIndirectFuncPtr()? 1 : 2));
765 const TmpInstruction* tmpRetVal =
766 cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
767 assert(tmpRetVal->getOperand(0) == origRetVal &&
768 tmpRetVal->getType() == origRetVal->getType() &&
769 "Wrong implicit ref?");
770 LiveRange *RetValLR = LRI->getLiveRangeForValue(tmpRetVal);
771 assert(RetValLR && "No LR for RetValue of call");
773 if (! RetValLR->isMarkedForSpill())
774 PushedRegSet.insert(MRI.getUnifiedRegNum(RetValLR->getRegClassID(),
775 RetValLR->getColor()));
778 const ValueSet &LVSetAft = LVI->getLiveVarSetAfterMInst(CallMI, BB);
779 ValueSet::const_iterator LIt = LVSetAft.begin();
781 // for each live var in live variable set after machine inst
782 for( ; LIt != LVSetAft.end(); ++LIt) {
783 // get the live range corresponding to live var
784 LiveRange *const LR = LRI->getLiveRangeForValue(*LIt);
786 // LR can be null if it is a const since a const
787 // doesn't have a dominating def - see Assumptions above
789 if (! LR->isMarkedForSpill()) {
790 assert(LR->hasColor() && "LR is neither spilled nor colored?");
791 unsigned RCID = LR->getRegClassID();
792 unsigned Color = LR->getColor();
794 if (MRI.isRegVolatile(RCID, Color) ) {
795 // if this is a call to the first-level reoptimizer
796 // instrumentation entry point, and the register is not
797 // modified by call, don't save and restore it.
798 if (isLLVMFirstTrigger && !MRI.modifiedByCall(RCID, Color))
801 // if the value is in both LV sets (i.e., live before and after
802 // the call machine instruction)
803 unsigned Reg = MRI.getUnifiedRegNum(RCID, Color);
805 // if we haven't already pushed this register...
806 if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
807 unsigned RegType = MRI.getRegTypeForLR(LR);
809 // Now get two instructions - to push on stack and pop from stack
810 // and add them to InstrnsBefore and InstrnsAfter of the
813 MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
815 //---- Insert code for pushing the reg on stack ----------
817 std::vector<MachineInstr*> AdIBef, AdIAft;
819 // We may need a scratch register to copy the saved value
820 // to/from memory. This may itself have to insert code to
821 // free up a scratch register. Any such code should go before
822 // the save code. The scratch register, if any, is by default
823 // temporary and not "used" by the instruction unless the
824 // copy code itself decides to keep the value in the scratch reg.
825 int scratchRegType = -1;
827 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
828 { // Find a register not live in the LVSet before CallMI
829 const ValueSet &LVSetBef =
830 LVI->getLiveVarSetBeforeMInst(CallMI, BB);
831 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
832 CallMI, AdIBef, AdIAft);
833 assert(scratchReg != MRI.getInvalidRegNum());
836 if (AdIBef.size() > 0)
837 instrnsBefore.insert(instrnsBefore.end(),
838 AdIBef.begin(), AdIBef.end());
840 MRI.cpReg2MemMI(instrnsBefore, Reg, MRI.getFramePointer(),
841 StackOff, RegType, scratchReg);
843 if (AdIAft.size() > 0)
844 instrnsBefore.insert(instrnsBefore.end(),
845 AdIAft.begin(), AdIAft.end());
847 //---- Insert code for popping the reg from the stack ----------
851 // We may need a scratch register to copy the saved value
852 // from memory. This may itself have to insert code to
853 // free up a scratch register. Any such code should go
854 // after the save code. As above, scratch is not marked "used".
857 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
858 { // Find a register not live in the LVSet after CallMI
859 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetAft,
860 CallMI, AdIBef, AdIAft);
861 assert(scratchReg != MRI.getInvalidRegNum());
864 if (AdIBef.size() > 0)
865 instrnsAfter.insert(instrnsAfter.end(),
866 AdIBef.begin(), AdIBef.end());
868 MRI.cpMem2RegMI(instrnsAfter, MRI.getFramePointer(), StackOff,
869 Reg, RegType, scratchReg);
871 if (AdIAft.size() > 0)
872 instrnsAfter.insert(instrnsAfter.end(),
873 AdIAft.begin(), AdIAft.end());
875 PushedRegSet.insert(Reg);
878 std::cerr << "\nFor call inst:" << *CallMI;
879 std::cerr << " -inserted caller saving instrs: Before:\n\t ";
880 for_each(instrnsBefore.begin(), instrnsBefore.end(),
881 std::mem_fun(&MachineInstr::dump));
882 std::cerr << " -and After:\n\t ";
883 for_each(instrnsAfter.begin(), instrnsAfter.end(),
884 std::mem_fun(&MachineInstr::dump));
886 } // if not already pushed
887 } // if LR has a volatile color
889 } // if there is a LR for Var
890 } // for each value in the LV set after instruction
894 /// Returns the unified register number of a temporary register to be used
895 /// BEFORE MInst. If no register is available, it will pick one and modify
896 /// MIBef and MIAft to contain instructions used to free up this returned
899 int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
900 const ValueSet *LVSetBef,
902 std::vector<MachineInstr*>& MIBef,
903 std::vector<MachineInstr*>& MIAft) {
904 RegClass* RC = getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
906 int RegU = getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
909 // we couldn't find an unused register. Generate code to free up a reg by
910 // saving it on stack and restoring after the instruction
912 int TmpOff = MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
914 RegU = getUniRegNotUsedByThisInst(RC, RegType, MInst);
916 // Check if we need a scratch register to copy this register to memory.
917 int scratchRegType = -1;
918 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType)) {
919 int scratchReg = getUsableUniRegAtMI(scratchRegType, LVSetBef,
920 MInst, MIBef, MIAft);
921 assert(scratchReg != MRI.getInvalidRegNum());
923 // We may as well hold the value in the scratch register instead
924 // of copying it to memory and back. But we have to mark the
925 // register as used by this instruction, so it does not get used
926 // as a scratch reg. by another operand or anyone else.
927 ScratchRegsUsed.insert(std::make_pair(MInst, scratchReg));
928 MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
929 MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
930 } else { // the register can be copied directly to/from memory so do it.
931 MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
932 MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
940 /// Returns the register-class register number of a new unused register that
941 /// can be used to accommodate a temporary value. May be called repeatedly
942 /// for a single MachineInstr. On each call, it finds a register which is not
943 /// live at that instruction and which is not used by any spilled operands of
944 /// that instruction.
946 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC, const int RegType,
947 const MachineInstr *MInst,
948 const ValueSet* LVSetBef) {
949 RC->clearColorsUsed(); // Reset array
951 if (LVSetBef == NULL) {
952 LVSetBef = &LVI->getLiveVarSetBeforeMInst(MInst);
953 assert(LVSetBef != NULL && "Unable to get live-var set before MInst?");
956 ValueSet::const_iterator LIt = LVSetBef->begin();
958 // for each live var in live variable set after machine inst
959 for ( ; LIt != LVSetBef->end(); ++LIt) {
960 // Get the live range corresponding to live var, and its RegClass
961 LiveRange *const LRofLV = LRI->getLiveRangeForValue(*LIt );
963 // LR can be null if it is a const since a const
964 // doesn't have a dominating def - see Assumptions above
965 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor())
966 RC->markColorsUsed(LRofLV->getColor(),
967 MRI.getRegTypeForLR(LRofLV), RegType);
970 // It is possible that one operand of this MInst was already spilled
971 // and it received some register temporarily. If that's the case,
972 // it is recorded in machine operand. We must skip such registers.
973 setRelRegsUsedByThisInst(RC, RegType, MInst);
975 int unusedReg = RC->getUnusedColor(RegType); // find first unused color
977 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
983 /// Return the unified register number of a register in class RC which is not
984 /// used by any operands of MInst.
986 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
988 const MachineInstr *MInst) {
989 RC->clearColorsUsed();
991 setRelRegsUsedByThisInst(RC, RegType, MInst);
993 // find the first unused color
994 int unusedReg = RC->getUnusedColor(RegType);
995 assert(unusedReg >= 0 &&
996 "FATAL: No free register could be found in reg class!!");
998 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
1002 /// Modify the IsColorUsedArr of register class RC, by setting the bits
1003 /// corresponding to register RegNo. This is a helper method of
1004 /// setRelRegsUsedByThisInst().
1006 static void markRegisterUsed(int RegNo, RegClass *RC, int RegType,
1007 const SparcV9RegInfo &TRI) {
1008 unsigned classId = 0;
1009 int classRegNum = TRI.getClassRegNum(RegNo, classId);
1010 if (RC->getID() == classId)
1011 RC->markColorsUsed(classRegNum, RegType, RegType);
1014 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC, int RegType,
1015 const MachineInstr *MI) {
1016 assert(OperandsColoredMap[MI] == true &&
1017 "Illegal to call setRelRegsUsedByThisInst() until colored operands "
1018 "are marked for an instruction.");
1020 // Add the registers already marked as used by the instruction. Both
1021 // explicit and implicit operands are set.
1022 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
1023 if (MI->getOperand(i).hasAllocatedReg())
1024 markRegisterUsed(MI->getOperand(i).getReg(), RC, RegType,MRI);
1026 for (unsigned i = 0, e = MI->getNumImplicitRefs(); i != e; ++i)
1027 if (MI->getImplicitOp(i).hasAllocatedReg())
1028 markRegisterUsed(MI->getImplicitOp(i).getReg(), RC, RegType,MRI);
1030 // Add all of the scratch registers that are used to save values across the
1031 // instruction (e.g., for saving state register values).
1032 std::pair<ScratchRegsUsedTy::iterator, ScratchRegsUsedTy::iterator>
1033 IR = ScratchRegsUsed.equal_range(MI);
1034 for (ScratchRegsUsedTy::iterator I = IR.first; I != IR.second; ++I)
1035 markRegisterUsed(I->second, RC, RegType, MRI);
1037 // If there are implicit references, mark their allocated regs as well
1038 for (unsigned z=0; z < MI->getNumImplicitRefs(); z++)
1039 if (const LiveRange*
1040 LRofImpRef = LRI->getLiveRangeForValue(MI->getImplicitRef(z)))
1041 if (LRofImpRef->hasColor())
1042 // this implicit reference is in a LR that received a color
1043 RC->markColorsUsed(LRofImpRef->getColor(),
1044 MRI.getRegTypeForLR(LRofImpRef), RegType);
1048 /// If there are delay slots for an instruction, the instructions added after
1049 /// it must really go after the delayed instruction(s). So, we Move the
1050 /// InstrAfter of that instruction to the corresponding delayed instruction
1051 /// using the following method.
1053 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
1054 const MachineInstr *DelayedMI)
1056 // "added after" instructions of the original instr
1057 std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
1059 if (DEBUG_RA && OrigAft.size() > 0) {
1060 std::cerr << "\nRegAlloc: Moved InstrnsAfter for: " << *OrigMI;
1061 std::cerr << " to last delay slot instrn: " << *DelayedMI;
1064 // "added after" instructions of the delayed instr
1065 std::vector<MachineInstr *> &DelayedAft=AddedInstrMap[DelayedMI].InstrnsAfter;
1067 // go thru all the "added after instructions" of the original instruction
1068 // and append them to the "added after instructions" of the delayed
1070 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
1072 // empty the "added after instructions" of the original instruction
1077 void PhyRegAlloc::colorIncomingArgs()
1079 MRI.colorMethodArgs(Fn, *LRI, AddedInstrAtEntry.InstrnsBefore,
1080 AddedInstrAtEntry.InstrnsAfter);
1084 /// Determine whether the suggested color of each live range is really usable,
1085 /// and then call its setSuggestedColorUsable() method to record the answer. A
1086 /// suggested color is NOT usable when the suggested color is volatile AND
1087 /// when there are call interferences.
1089 void PhyRegAlloc::markUnusableSugColors()
1091 LiveRangeMapType::const_iterator HMI = (LRI->getLiveRangeMap())->begin();
1092 LiveRangeMapType::const_iterator HMIEnd = (LRI->getLiveRangeMap())->end();
1094 for (; HMI != HMIEnd ; ++HMI ) {
1096 LiveRange *L = HMI->second; // get the LiveRange
1097 if (L && L->hasSuggestedColor ())
1098 L->setSuggestedColorUsable
1099 (!(MRI.isRegVolatile (L->getRegClassID (), L->getSuggestedColor ())
1100 && L->isCallInterference ()));
1102 } // for all LR's in hash map
1106 /// For each live range that is spilled, allocates a new spill position on the
1107 /// stack, and set the stack offsets of the live range that will be spilled to
1108 /// that position. This must be called just after coloring the LRs.
1110 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1111 if (DEBUG_RA) std::cerr << "\nSetting LR stack offsets for spills...\n";
1113 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
1114 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
1116 for ( ; HMI != HMIEnd ; ++HMI) {
1117 if (HMI->first && HMI->second) {
1118 LiveRange *L = HMI->second; // get the LiveRange
1119 if (L->isMarkedForSpill()) { // NOTE: allocating size of long Type **
1120 int stackOffset = MF->getInfo()->allocateSpilledValue(Type::LongTy);
1121 L->setSpillOffFromFP(stackOffset);
1123 std::cerr << " LR# " << L->getUserIGNode()->getIndex()
1124 << ": stack-offset = " << stackOffset << "\n";
1127 } // for all LR's in hash map
1131 void PhyRegAlloc::saveStateForValue (std::vector<AllocInfo> &state,
1132 const Value *V, int Insn, int Opnd) {
1133 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap ()->find (V);
1134 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap ()->end ();
1135 AllocInfo::AllocStateTy AllocState = AllocInfo::NotAllocated;
1137 if ((HMI != HMIEnd) && HMI->second) {
1138 LiveRange *L = HMI->second;
1139 assert ((L->hasColor () || L->isMarkedForSpill ())
1140 && "Live range exists but not colored or spilled");
1141 if (L->hasColor ()) {
1142 AllocState = AllocInfo::Allocated;
1143 Placement = MRI.getUnifiedRegNum (L->getRegClassID (),
1145 } else if (L->isMarkedForSpill ()) {
1146 AllocState = AllocInfo::Spilled;
1147 assert (L->hasSpillOffset ()
1148 && "Live range marked for spill but has no spill offset");
1149 Placement = L->getSpillOffFromFP ();
1152 state.push_back (AllocInfo (Insn, Opnd, AllocState, Placement));
1156 /// Save the global register allocation decisions made by the register
1157 /// allocator so that they can be accessed later (sort of like "poor man's
1160 void PhyRegAlloc::saveState () {
1161 std::vector<AllocInfo> &state = FnAllocState[Fn];
1162 unsigned ArgNum = 0;
1163 // Arguments encoded as instruction # -1
1164 for (Function::const_aiterator i=Fn->abegin (), e=Fn->aend (); i != e; ++i) {
1165 const Argument *Arg = &*i;
1166 saveStateForValue (state, Arg, -1, ArgNum);
1169 unsigned InstCount = 0;
1170 // Instructions themselves encoded as operand # -1
1171 for (const_inst_iterator II=inst_begin (Fn), IE=inst_end (Fn); II!=IE; ++II){
1172 const Instruction *Inst = &*II;
1173 saveStateForValue (state, Inst, InstCount, -1);
1174 if (isa<PHINode> (Inst)) {
1175 MachineCodeForInstruction &MCforPN = MachineCodeForInstruction::get(Inst);
1176 // Last instr should be the copy...figure out what reg it is reading from
1177 if (Value *PhiCpRes = MCforPN.back()->getOperand(0).getVRegValueOrNull()){
1179 std::cerr << "Found Phi copy result: " << PhiCpRes->getName()
1180 << " in: " << *MCforPN.back() << "\n";
1181 saveStateForValue (state, PhiCpRes, InstCount, -2);
1189 /// Dump the saved state filled in by saveState() out to stderr. Only
1190 /// used when debugging.
1192 void PhyRegAlloc::dumpSavedState () {
1193 std::vector<AllocInfo> &state = FnAllocState[Fn];
1195 for (Function::const_aiterator i=Fn->abegin (), e=Fn->aend (); i != e; ++i) {
1196 const Argument *Arg = &*i;
1197 std::cerr << "Argument: " << *Arg << "\n"
1198 << "FnAllocState:\n";
1199 for (unsigned i = 0; i < state.size (); ++i) {
1200 AllocInfo &S = state[i];
1201 if (S.Instruction == -1 && S.Operand == ArgNum)
1202 std::cerr << " " << S << "\n";
1204 std::cerr << "----------\n";
1208 for (const_inst_iterator II=inst_begin (Fn), IE=inst_end (Fn); II!=IE; ++II) {
1209 const Instruction *I = &*II;
1210 MachineCodeForInstruction &Instrs = MachineCodeForInstruction::get (I);
1211 std::cerr << "Instruction: " << *I
1212 << "MachineCodeForInstruction:\n";
1213 for (unsigned i = 0, n = Instrs.size (); i != n; ++i)
1214 std::cerr << " " << *Instrs[i];
1215 std::cerr << "FnAllocState:\n";
1216 for (unsigned i = 0; i < state.size (); ++i) {
1217 AllocInfo &S = state[i];
1218 if (Insn == S.Instruction)
1219 std::cerr << " " << S << "\n";
1221 std::cerr << "----------\n";
1227 bool PhyRegAlloc::doFinalization (Module &M) {
1228 if (SaveRegAllocState) finishSavingState (M);
1233 /// Finish the job of saveState(), by collapsing FnAllocState into an LLVM
1234 /// Constant and stuffing it inside the Module.
1236 /// FIXME: There should be other, better ways of storing the saved
1237 /// state; this one is cumbersome and does not work well with the JIT.
1239 void PhyRegAlloc::finishSavingState (Module &M) {
1241 std::cerr << "---- Saving reg. alloc state; SaveStateToModule = "
1242 << SaveStateToModule << " ----\n";
1244 // If saving state into the module, just copy new elements to the
1246 if (!SaveStateToModule) {
1247 ExportedFnAllocState = FnAllocState;
1248 // FIXME: should ONLY copy new elements in FnAllocState
1252 // Convert FnAllocState to a single Constant array and add it
1254 ArrayType *AT = ArrayType::get (AllocInfo::getConstantType (), 0);
1255 std::vector<const Type *> TV;
1256 TV.push_back (Type::UIntTy);
1258 PointerType *PT = PointerType::get (StructType::get (TV));
1260 std::vector<Constant *> allstate;
1261 for (Module::iterator I = M.begin (), E = M.end (); I != E; ++I) {
1263 if (F->isExternal ()) continue;
1264 if (FnAllocState.find (F) == FnAllocState.end ()) {
1265 allstate.push_back (ConstantPointerNull::get (PT));
1267 std::vector<AllocInfo> &state = FnAllocState[F];
1269 // Convert state into an LLVM ConstantArray, and put it in a
1270 // ConstantStruct (named S) along with its size.
1271 std::vector<Constant *> stateConstants;
1272 for (unsigned i = 0, s = state.size (); i != s; ++i)
1273 stateConstants.push_back (state[i].toConstant ());
1274 unsigned Size = stateConstants.size ();
1275 ArrayType *AT = ArrayType::get (AllocInfo::getConstantType (), Size);
1276 std::vector<const Type *> TV;
1277 TV.push_back (Type::UIntTy);
1279 StructType *ST = StructType::get (TV);
1280 std::vector<Constant *> CV;
1281 CV.push_back (ConstantUInt::get (Type::UIntTy, Size));
1282 CV.push_back (ConstantArray::get (AT, stateConstants));
1283 Constant *S = ConstantStruct::get (ST, CV);
1285 GlobalVariable *GV =
1286 new GlobalVariable (ST, true,
1287 GlobalValue::InternalLinkage, S,
1288 F->getName () + ".regAllocState", &M);
1290 // Have: { uint, [Size x { uint, int, uint, int }] } *
1291 // Cast it to: { uint, [0 x { uint, int, uint, int }] } *
1292 Constant *CE = ConstantExpr::getCast (GV, PT);
1293 allstate.push_back (CE);
1297 unsigned Size = allstate.size ();
1298 // Final structure type is:
1299 // { uint, [Size x { uint, [0 x { uint, int, uint, int }] } *] }
1300 std::vector<const Type *> TV2;
1301 TV2.push_back (Type::UIntTy);
1302 ArrayType *AT2 = ArrayType::get (PT, Size);
1303 TV2.push_back (AT2);
1304 StructType *ST2 = StructType::get (TV2);
1305 std::vector<Constant *> CV2;
1306 CV2.push_back (ConstantUInt::get (Type::UIntTy, Size));
1307 CV2.push_back (ConstantArray::get (AT2, allstate));
1308 new GlobalVariable (ST2, true, GlobalValue::ExternalLinkage,
1309 ConstantStruct::get (ST2, CV2), "_llvm_regAllocState",
1314 /// Allocate registers for the machine code previously generated for F using
1315 /// the graph-coloring algorithm.
1317 bool PhyRegAlloc::runOnFunction (Function &F) {
1319 std::cerr << "\n********* Function "<< F.getName () << " ***********\n";
1322 MF = &MachineFunction::get (Fn);
1323 LVI = &getAnalysis<FunctionLiveVarInfo> ();
1324 LRI = new LiveRangeInfo (Fn, TM, RegClassList);
1325 LoopDepthCalc = &getAnalysis<LoopInfo> ();
1327 // Create each RegClass for the target machine and add it to the
1328 // RegClassList. This must be done before calling constructLiveRanges().
1329 for (unsigned rc = 0; rc != NumOfRegClasses; ++rc)
1330 RegClassList.push_back (new RegClass (Fn, TM.getRegInfo(),
1331 MRI.getMachineRegClass(rc)));
1333 LRI->constructLiveRanges(); // create LR info
1334 if (DEBUG_RA >= RA_DEBUG_LiveRanges)
1335 LRI->printLiveRanges();
1337 createIGNodeListsAndIGs(); // create IGNode list and IGs
1339 buildInterferenceGraphs(); // build IGs in all reg classes
1341 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1342 // print all LRs in all reg classes
1343 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1344 RegClassList[rc]->printIGNodeList();
1346 // print IGs in all register classes
1347 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1348 RegClassList[rc]->printIG();
1351 LRI->coalesceLRs(); // coalesce all live ranges
1353 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1354 // print all LRs in all reg classes
1355 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1356 RegClassList[rc]->printIGNodeList();
1358 // print IGs in all register classes
1359 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1360 RegClassList[rc]->printIG();
1363 // mark un-usable suggested color before graph coloring algorithm.
1364 // When this is done, the graph coloring algo will not reserve
1365 // suggested color unnecessarily - they can be used by another LR
1366 markUnusableSugColors();
1368 // color all register classes using the graph coloring algo
1369 for (unsigned rc=0; rc < NumOfRegClasses ; rc++)
1370 RegClassList[rc]->colorAllRegs();
1372 // After graph coloring, if some LRs did not receive a color (i.e, spilled)
1373 // a position for such spilled LRs
1374 allocateStackSpace4SpilledLRs();
1376 // Reset the temp. area on the stack before use by the first instruction.
1377 // This will also happen after updating each instruction.
1378 MF->getInfo()->popAllTempValues();
1380 // color incoming args - if the correct color was not received
1381 // insert code to copy to the correct register
1382 colorIncomingArgs();
1384 // Save register allocation state for this function in a Constant.
1385 if (SaveRegAllocState) {
1389 // Now update the machine code with register names and add any additional
1390 // code inserted by the register allocator to the instruction stream.
1391 updateMachineCode();
1393 if (SaveRegAllocState) {
1394 if (DEBUG_RA) // Check our work.
1396 if (!SaveStateToModule)
1397 finishSavingState (const_cast<Module&> (*Fn->getParent ()));
1401 std::cerr << "\n**** Machine Code After Register Allocation:\n\n";
1405 // Tear down temporary data structures
1406 for (unsigned rc = 0; rc < NumOfRegClasses; ++rc)
1407 delete RegClassList[rc];
1408 RegClassList.clear ();
1409 AddedInstrMap.clear ();
1410 OperandsColoredMap.clear ();
1411 ScratchRegsUsed.clear ();
1412 AddedInstrAtEntry.clear ();
1415 if (DEBUG_RA) std::cerr << "\nRegister allocation complete!\n";
1416 return false; // Function was not modified
1419 } // End llvm namespace