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 "../MachineCodeForInstruction.h"
30 #include "../MachineFunctionInfo.h"
31 #include "../SparcV9InstrInfo.h"
32 #include "../SparcV9TmpInstr.h"
33 #include "llvm/Constants.h"
34 #include "llvm/DerivedTypes.h"
35 #include "llvm/Instructions.h"
36 #include "llvm/Module.h"
37 #include "llvm/Type.h"
38 #include "llvm/Analysis/LoopInfo.h"
39 #include "llvm/CodeGen/MachineFunction.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 "llvm/Support/CommandLine.h"
47 #include "llvm/ADT/SetOperations.h"
48 #include "llvm/ADT/STLExtras.h"
49 #include "llvm/ADT/Statistic.h"
54 Statistic<> RASpills("regalloc-spills", "Number of registers spilled");
56 RegAllocDebugLevel_t DEBUG_RA;
58 static cl::opt<RegAllocDebugLevel_t, true>
59 DRA_opt("dregalloc", cl::Hidden, cl::location(DEBUG_RA),
60 cl::desc("enable register allocation debugging information"),
62 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
63 clEnumValN(RA_DEBUG_Results, "y", "debug output for allocation results"),
64 clEnumValN(RA_DEBUG_Coloring, "c", "debug output for graph coloring step"),
65 clEnumValN(RA_DEBUG_Interference,"ig","debug output for interference graphs"),
66 clEnumValN(RA_DEBUG_LiveRanges , "lr","debug output for live ranges"),
67 clEnumValN(RA_DEBUG_Verbose, "v", "extra debug output"),
70 /// The reoptimizer wants to be able to grovel through the register
71 /// allocator's state after it has done its job. This is a hack.
73 PhyRegAlloc::SavedStateMapTy ExportedFnAllocState;
74 bool SaveRegAllocState = false;
75 bool SaveStateToModule = true;
76 static cl::opt<bool, true>
77 SaveRegAllocStateOpt("save-ra-state", cl::Hidden,
78 cl::location (SaveRegAllocState),
80 cl::desc("write reg. allocator state into module"));
82 FunctionPass *getRegisterAllocator(TargetMachine &T) {
83 return new PhyRegAlloc (T);
86 void PhyRegAlloc::getAnalysisUsage(AnalysisUsage &AU) const {
87 AU.addRequired<LoopInfo> ();
88 AU.addRequired<FunctionLiveVarInfo> ();
92 /// Initialize interference graphs (one in each reg class) and IGNodeLists
93 /// (one in each IG). The actual nodes will be pushed later.
95 void PhyRegAlloc::createIGNodeListsAndIGs() {
96 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "Creating LR lists ...\n";
98 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
99 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
101 for (; HMI != HMIEnd ; ++HMI ) {
103 V9LiveRange *L = HMI->second; // get the V9LiveRange
105 if (DEBUG_RA && !isa<ConstantIntegral> (HMI->first))
106 std::cerr << "\n**** ?!?WARNING: NULL LIVE RANGE FOUND FOR: "
107 << RAV(HMI->first) << "****\n";
111 // if the Value * is not null, and LR is not yet written to the IGNodeList
112 if (!(L->getUserIGNode()) ) {
113 RegClass *const RC = // RegClass of first value in the LR
114 RegClassList[ L->getRegClassID() ];
115 RC->addLRToIG(L); // add this LR to an IG
121 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
122 RegClassList[rc]->createInterferenceGraph();
124 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "LRLists Created!\n";
128 /// Add all interferences for a given instruction. Interference occurs only
129 /// if the LR of Def (Inst or Arg) is of the same reg class as that of live
130 /// var. The live var passed to this function is the LVset AFTER the
133 void PhyRegAlloc::addInterference(const Value *Def, const ValueSet *LVSet,
135 ValueSet::const_iterator LIt = LVSet->begin();
137 // get the live range of instruction
138 const V9LiveRange *const LROfDef = LRI->getLiveRangeForValue( Def );
140 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
141 assert( IGNodeOfDef );
143 RegClass *const RCOfDef = LROfDef->getRegClass();
145 // for each live var in live variable set
146 for ( ; LIt != LVSet->end(); ++LIt) {
148 if (DEBUG_RA >= RA_DEBUG_Verbose)
149 std::cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
151 // get the live range corresponding to live var
152 V9LiveRange *LROfVar = LRI->getLiveRangeForValue(*LIt);
154 // LROfVar can be null if it is a const since a const
155 // doesn't have a dominating def - see Assumptions above
157 if (LROfDef != LROfVar) // do not set interf for same LR
158 if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
159 RCOfDef->setInterference( LROfDef, LROfVar);
164 /// For a call instruction, this method sets the CallInterference flag in
165 /// the LR of each variable live in the Live Variable Set live after the
166 /// call instruction (except the return value of the call instruction - since
167 /// the return value does not interfere with that call itself).
169 void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
170 const ValueSet *LVSetAft) {
171 if (DEBUG_RA >= RA_DEBUG_Interference)
172 std::cerr << "\n For call inst: " << *MInst;
174 // for each live var in live variable set after machine inst
175 for (ValueSet::const_iterator LIt = LVSetAft->begin(), LEnd = LVSetAft->end();
176 LIt != LEnd; ++LIt) {
178 // get the live range corresponding to live var
179 V9LiveRange *const LR = LRI->getLiveRangeForValue(*LIt);
181 // LR can be null if it is a const since a const
182 // doesn't have a dominating def - see Assumptions above
184 if (DEBUG_RA >= RA_DEBUG_Interference)
185 std::cerr << "\n\tLR after Call: " << *LR << "\n";
186 LR->setCallInterference();
187 if (DEBUG_RA >= RA_DEBUG_Interference)
188 std::cerr << "\n ++After adding call interference for LR: " << *LR << "\n";
192 // Now find the LR of the return value of the call
193 // We do this because, we look at the LV set *after* the instruction
194 // to determine, which LRs must be saved across calls. The return value
195 // of the call is live in this set - but it does not interfere with call
196 // (i.e., we can allocate a volatile register to the return value)
197 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
199 if (const Value *RetVal = argDesc->getReturnValue()) {
200 V9LiveRange *RetValLR = LRI->getLiveRangeForValue( RetVal );
201 assert( RetValLR && "No LR for RetValue of call");
202 RetValLR->clearCallInterference();
205 // If the CALL is an indirect call, find the LR of the function pointer.
206 // That has a call interference because it conflicts with outgoing args.
207 if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
208 V9LiveRange *AddrValLR = LRI->getLiveRangeForValue( AddrVal );
209 // LR can be null if the function pointer is a constant.
211 AddrValLR->setCallInterference();
216 /// Create interferences in the IG of each RegClass, and calculate the spill
217 /// cost of each Live Range (it is done in this method to save another pass
220 void PhyRegAlloc::buildInterferenceGraphs() {
221 if (DEBUG_RA >= RA_DEBUG_Interference)
222 std::cerr << "Creating interference graphs ...\n";
224 unsigned BBLoopDepthCost;
225 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
227 const MachineBasicBlock &MBB = *BBI;
228 const BasicBlock *BB = MBB.getBasicBlock();
230 // find the 10^(loop_depth) of this BB
231 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BB));
233 // get the iterator for machine instructions
234 MachineBasicBlock::const_iterator MII = MBB.begin();
236 // iterate over all the machine instructions in BB
237 for ( ; MII != MBB.end(); ++MII) {
238 const MachineInstr *MInst = MII;
240 // get the LV set after the instruction
241 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BB);
242 bool isCallInst = TM.getInstrInfo()->isCall(MInst->getOpcode());
245 // set the isCallInterference flag of each live range which extends
246 // across this call instruction. This information is used by graph
247 // coloring algorithm to avoid allocating volatile colors to live ranges
248 // that span across calls (since they have to be saved/restored)
249 setCallInterferences(MInst, &LVSetAI);
252 // iterate over all MI operands to find defs
253 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
254 OpE = MInst->end(); OpI != OpE; ++OpI) {
255 if (OpI.isDef()) // create a new LR since def
256 addInterference(*OpI, &LVSetAI, isCallInst);
258 // Calculate the spill cost of each live range
259 V9LiveRange *LR = LRI->getLiveRangeForValue(*OpI);
260 if (LR) LR->addSpillCost(BBLoopDepthCost);
262 // Also add interference for any implicit definitions in a machine
263 // instr (currently, only calls have this).
264 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
265 for (unsigned z=0; z < NumOfImpRefs; z++)
266 if (MInst->getImplicitOp(z).isDef())
267 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
268 } // for all machine instructions in BB
269 } // for all BBs in function
271 // add interferences for function arguments. Since there are no explicit
272 // defs in the function for args, we have to add them manually
273 addInterferencesForArgs();
275 if (DEBUG_RA >= RA_DEBUG_Interference)
276 std::cerr << "Interference graphs calculated!\n";
280 /// Mark all operands of the given MachineInstr as interfering with one
283 void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
284 bool setInterf = false;
286 // iterate over MI operands to find defs
287 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
288 ItE = MInst->end(); It1 != ItE; ++It1) {
289 const V9LiveRange *LROfOp1 = LRI->getLiveRangeForValue(*It1);
290 assert((LROfOp1 || It1.isDef()) && "No LR for Def in PSEUDO insruction");
292 MachineInstr::const_val_op_iterator It2 = It1;
293 for (++It2; It2 != ItE; ++It2) {
294 const V9LiveRange *LROfOp2 = LRI->getLiveRangeForValue(*It2);
297 RegClass *RCOfOp1 = LROfOp1->getRegClass();
298 RegClass *RCOfOp2 = LROfOp2->getRegClass();
300 if (RCOfOp1 == RCOfOp2 ){
301 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
305 } // for all other defs in machine instr
306 } // for all operands in an instruction
308 if (!setInterf && MInst->getNumOperands() > 2) {
309 std::cerr << "\nInterf not set for any operand in pseudo instr:\n";
311 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
316 /// Add interferences for incoming arguments to a function.
318 void PhyRegAlloc::addInterferencesForArgs() {
319 // get the InSet of root BB
320 const ValueSet &InSet = LVI->getInSetOfBB(&Fn->front());
322 for (Function::const_arg_iterator AI = Fn->arg_begin(); AI != Fn->arg_end(); ++AI) {
323 // add interferences between args and LVars at start
324 addInterference(AI, &InSet, false);
326 if (DEBUG_RA >= RA_DEBUG_Interference)
327 std::cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
332 /// The following are utility functions used solely by updateMachineCode and
333 /// the functions that it calls. They should probably be folded back into
334 /// updateMachineCode at some point.
337 // used by: updateMachineCode (1 time), PrependInstructions (1 time)
338 inline void InsertBefore(MachineInstr* newMI, MachineBasicBlock& MBB,
339 MachineBasicBlock::iterator& MII) {
340 MII = MBB.insert(MII, newMI);
344 // used by: AppendInstructions (1 time)
345 inline void InsertAfter(MachineInstr* newMI, MachineBasicBlock& MBB,
346 MachineBasicBlock::iterator& MII) {
347 ++MII; // insert before the next instruction
348 MII = MBB.insert(MII, newMI);
351 // used by: updateMachineCode (2 times)
352 inline void PrependInstructions(std::vector<MachineInstr *> &IBef,
353 MachineBasicBlock& MBB,
354 MachineBasicBlock::iterator& MII,
355 const std::string& msg) {
357 MachineInstr* OrigMI = MII;
358 std::vector<MachineInstr *>::iterator AdIt;
359 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt) {
361 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
362 std::cerr << msg << "PREPENDed instr:\n " << **AdIt << "\n";
364 InsertBefore(*AdIt, MBB, MII);
369 // used by: updateMachineCode (1 time)
370 inline void AppendInstructions(std::vector<MachineInstr *> &IAft,
371 MachineBasicBlock& MBB,
372 MachineBasicBlock::iterator& MII,
373 const std::string& msg) {
375 MachineInstr* OrigMI = MII;
376 std::vector<MachineInstr *>::iterator AdIt;
377 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt ) {
379 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
380 std::cerr << msg << "APPENDed instr:\n " << **AdIt << "\n";
382 InsertAfter(*AdIt, MBB, MII);
387 /// Set the registers for operands in the given MachineInstr, if a register was
388 /// successfully allocated. Return true if any of its operands has been marked
391 bool PhyRegAlloc::markAllocatedRegs(MachineInstr* MInst)
393 bool instrNeedsSpills = false;
395 // First, set the registers for operands in the machine instruction
396 // if a register was successfully allocated. Do this first because we
397 // will need to know which registers are already used by this instr'n.
398 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
399 MachineOperand& Op = MInst->getOperand(OpNum);
400 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
401 Op.getType() == MachineOperand::MO_CCRegister) {
402 const Value *const Val = Op.getVRegValue();
403 if (const V9LiveRange* LR = LRI->getLiveRangeForValue(Val)) {
404 // Remember if any operand needs spilling
405 instrNeedsSpills |= LR->isMarkedForSpill();
407 // An operand may have a color whether or not it needs spilling
409 MInst->SetRegForOperand(OpNum,
410 MRI.getUnifiedRegNum(LR->getRegClassID(),
414 } // for each operand
416 return instrNeedsSpills;
419 /// Mark allocated registers (using markAllocatedRegs()) on the instruction
420 /// that MII points to. Then, if it's a call instruction, insert caller-saving
421 /// code before and after it. Finally, insert spill code before and after it,
422 /// using insertCode4SpilledLR().
424 void PhyRegAlloc::updateInstruction(MachineBasicBlock::iterator& MII,
425 MachineBasicBlock &MBB) {
426 MachineInstr* MInst = MII;
427 unsigned Opcode = MInst->getOpcode();
429 // Reset tmp stack positions so they can be reused for each machine instr.
430 MF->getInfo<SparcV9FunctionInfo>()->popAllTempValues();
432 // Mark the operands for which regs have been allocated.
433 bool instrNeedsSpills = markAllocatedRegs(MII);
436 // Mark that the operands have been updated. Later,
437 // setRelRegsUsedByThisInst() is called to find registers used by each
438 // MachineInst, and it should not be used for an instruction until
439 // this is done. This flag just serves as a sanity check.
440 OperandsColoredMap[MInst] = true;
443 // Now insert caller-saving code before/after the call.
444 // Do this before inserting spill code since some registers must be
445 // used by save/restore and spill code should not use those registers.
446 if (TM.getInstrInfo()->isCall(Opcode)) {
447 AddedInstrns &AI = AddedInstrMap[MInst];
448 insertCallerSavingCode(AI.InstrnsBefore, AI.InstrnsAfter, MInst,
449 MBB.getBasicBlock());
452 // Now insert spill code for remaining operands not allocated to
453 // registers. This must be done even for call return instructions
454 // since those are not handled by the special code above.
455 if (instrNeedsSpills)
456 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum) {
457 MachineOperand& Op = MInst->getOperand(OpNum);
458 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
459 Op.getType() == MachineOperand::MO_CCRegister) {
460 const Value* Val = Op.getVRegValue();
461 if (const V9LiveRange *LR = LRI->getLiveRangeForValue(Val))
462 if (LR->isMarkedForSpill())
463 insertCode4SpilledLR(LR, MII, MBB, OpNum);
465 } // for each operand
468 /// Iterate over all the MachineBasicBlocks in the current function and set
469 /// the allocated registers for each instruction (using updateInstruction()),
470 /// after register allocation is complete. Then move code out of delay slots.
472 void PhyRegAlloc::updateMachineCode()
474 // Insert any instructions needed at method entry
475 MachineBasicBlock::iterator MII = MF->front().begin();
476 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MF->front(), MII,
477 "At function entry: \n");
478 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
479 "InstrsAfter should be unnecessary since we are just inserting at "
480 "the function entry point here.");
482 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
484 MachineBasicBlock &MBB = *BBI;
486 // Iterate over all machine instructions in BB and mark operands with
487 // their assigned registers or insert spill code, as appropriate.
488 // Also, fix operands of call/return instructions.
489 for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
490 if (MII->getOpcode() != V9::PHI)
491 updateInstruction(MII, MBB);
493 // Now, move code out of delay slots of branches and returns if needed.
494 // (Also, move "after" code from calls to the last delay slot instruction.)
495 // Moving code out of delay slots is needed in 2 situations:
496 // (1) If this is a branch and it needs instructions inserted after it,
497 // move any existing instructions out of the delay slot so that the
498 // instructions can go into the delay slot. This only supports the
499 // case that #instrsAfter <= #delay slots.
501 // (2) If any instruction in the delay slot needs
502 // instructions inserted, move it out of the delay slot and before the
503 // branch because putting code before or after it would be VERY BAD!
505 // If the annul bit of the branch is set, neither of these is legal!
506 // If so, we need to handle spill differently but annulling is not yet used.
507 for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
508 if (unsigned delaySlots =
509 TM.getInstrInfo()->getNumDelaySlots(MII->getOpcode())) {
510 MachineBasicBlock::iterator DelaySlotMI = next(MII);
511 assert(DelaySlotMI != MBB.end() && "no instruction for delay slot");
513 // Check the 2 conditions above:
514 // (1) Does a branch need instructions added after it?
515 // (2) O/w does delay slot instr. need instrns before or after?
516 bool isBranch = (TM.getInstrInfo()->isBranch(MII->getOpcode()) ||
517 TM.getInstrInfo()->isReturn(MII->getOpcode()));
518 bool cond1 = (isBranch &&
519 AddedInstrMap.count(MII) &&
520 AddedInstrMap[MII].InstrnsAfter.size() > 0);
521 bool cond2 = (AddedInstrMap.count(DelaySlotMI) &&
522 (AddedInstrMap[DelaySlotMI].InstrnsBefore.size() > 0 ||
523 AddedInstrMap[DelaySlotMI].InstrnsAfter.size() > 0));
525 if (cond1 || cond2) {
526 assert(delaySlots==1 &&
527 "InsertBefore does not yet handle >1 delay slots!");
530 std::cerr << "\nRegAlloc: Moved instr. with added code: "
532 << " out of delay slots of instr: " << *MII;
535 // move instruction before branch
536 MBB.insert(MII, MBB.remove(DelaySlotMI++));
538 // On cond1 we are done (we already moved the
539 // instruction out of the delay slot). On cond2 we need
540 // to insert a nop in place of the moved instruction
542 MBB.insert(MII, BuildMI(V9::NOP, 1));
546 // For non-branch instr with delay slots (probably a call), move
547 // InstrAfter to the instr. in the last delay slot.
548 MachineBasicBlock::iterator tmp = next(MII, delaySlots);
549 move2DelayedInstr(MII, tmp);
553 // Finally iterate over all instructions in BB and insert before/after
554 for (MachineBasicBlock::iterator MII=MBB.begin(); MII != MBB.end(); ++MII) {
555 MachineInstr *MInst = MII;
557 // do not process Phis
558 if (MInst->getOpcode() == V9::PHI)
561 // if there are any added instructions...
562 if (AddedInstrMap.count(MInst)) {
563 AddedInstrns &CallAI = AddedInstrMap[MInst];
566 bool isBranch = (TM.getInstrInfo()->isBranch(MInst->getOpcode()) ||
567 TM.getInstrInfo()->isReturn(MInst->getOpcode()));
569 AddedInstrMap[MInst].InstrnsAfter.size() <=
570 TM.getInstrInfo()->getNumDelaySlots(MInst->getOpcode())) &&
571 "Cannot put more than #delaySlots instrns after "
572 "branch or return! Need to handle temps differently.");
576 // Temporary sanity checking code to detect whether the same machine
577 // instruction is ever inserted twice before/after a call.
578 // I suspect this is happening but am not sure. --Vikram, 7/1/03.
579 std::set<const MachineInstr*> instrsSeen;
580 for (int i = 0, N = CallAI.InstrnsBefore.size(); i < N; ++i) {
581 assert(instrsSeen.count(CallAI.InstrnsBefore[i]) == 0 &&
582 "Duplicate machine instruction in InstrnsBefore!");
583 instrsSeen.insert(CallAI.InstrnsBefore[i]);
585 for (int i = 0, N = CallAI.InstrnsAfter.size(); i < N; ++i) {
586 assert(instrsSeen.count(CallAI.InstrnsAfter[i]) == 0 &&
587 "Duplicate machine instruction in InstrnsBefore/After!");
588 instrsSeen.insert(CallAI.InstrnsAfter[i]);
592 // Now add the instructions before/after this MI.
593 // We do this here to ensure that spill for an instruction is inserted
594 // as close as possible to an instruction (see above insertCode4Spill)
595 if (! CallAI.InstrnsBefore.empty())
596 PrependInstructions(CallAI.InstrnsBefore, MBB, MII,"");
598 if (! CallAI.InstrnsAfter.empty())
599 AppendInstructions(CallAI.InstrnsAfter, MBB, MII,"");
601 } // if there are any added instructions
602 } // for each machine instruction
607 /// Insert spill code for AN operand whose LR was spilled. May be called
608 /// repeatedly for a single MachineInstr if it has many spilled operands. On
609 /// each call, it finds a register which is not live at that instruction and
610 /// also which is not used by other spilled operands of the same
611 /// instruction. Then it uses this register temporarily to accommodate the
614 void PhyRegAlloc::insertCode4SpilledLR(const V9LiveRange *LR,
615 MachineBasicBlock::iterator& MII,
616 MachineBasicBlock &MBB,
617 const unsigned OpNum) {
618 MachineInstr *MInst = MII;
619 const BasicBlock *BB = MBB.getBasicBlock();
621 assert((! TM.getInstrInfo()->isCall(MInst->getOpcode()) || OpNum == 0) &&
622 "Outgoing arg of a call must be handled elsewhere (func arg ok)");
623 assert(! TM.getInstrInfo()->isReturn(MInst->getOpcode()) &&
624 "Return value of a ret must be handled elsewhere");
626 MachineOperand& Op = MInst->getOperand(OpNum);
627 bool isDef = Op.isDef();
628 bool isUse = Op.isUse();
629 unsigned RegType = MRI.getRegTypeForLR(LR);
630 int SpillOff = LR->getSpillOffFromFP();
631 RegClass *RC = LR->getRegClass();
633 // Get the live-variable set to find registers free before this instr.
634 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
637 // If this instr. is in the delay slot of a branch or return, we need to
638 // include all live variables before that branch or return -- we don't want to
639 // trample those! Verify that the set is included in the LV set before MInst.
640 if (MII != MBB.begin()) {
641 MachineBasicBlock::iterator PredMI = prior(MII);
642 if (unsigned DS = TM.getInstrInfo()->getNumDelaySlots(PredMI->getOpcode()))
643 assert(set_difference(LVI->getLiveVarSetBeforeMInst(PredMI), LVSetBef)
644 .empty() && "Live-var set before branch should be included in "
645 "live-var set of each delay slot instruction!");
649 MF->getInfo<SparcV9FunctionInfo>()->pushTempValue(MRI.getSpilledRegSize(RegType));
651 std::vector<MachineInstr*> MIBef, MIAft;
652 std::vector<MachineInstr*> AdIMid;
654 // Choose a register to hold the spilled value, if one was not preallocated.
655 // This may insert code before and after MInst to free up the value. If so,
656 // this code should be first/last in the spill sequence before/after MInst.
657 int TmpRegU=(LR->hasColor()
658 ? MRI.getUnifiedRegNum(LR->getRegClassID(),LR->getColor())
659 : getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef,MIAft));
661 // Set the operand first so that it this register does not get used
662 // as a scratch register for later calls to getUsableUniRegAtMI below
663 MInst->SetRegForOperand(OpNum, TmpRegU);
665 // get the added instructions for this instruction
666 AddedInstrns &AI = AddedInstrMap[MInst];
668 // We may need a scratch register to copy the spilled value to/from memory.
669 // This may itself have to insert code to free up a scratch register.
670 // Any such code should go before (after) the spill code for a load (store).
671 // The scratch reg is not marked as used because it is only used
672 // for the copy and not used across MInst.
673 int scratchRegType = -1;
675 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType)) {
676 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
677 MInst, MIBef, MIAft);
678 assert(scratchReg != MRI.getInvalidRegNum());
682 // for a USE, we have to load the value of LR from stack to a TmpReg
683 // and use the TmpReg as one operand of instruction
685 // actual loading instruction(s)
686 MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU,
687 RegType, scratchReg);
689 // the actual load should be after the instructions to free up TmpRegU
690 MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
694 if (isDef) { // if this is a Def
695 // for a DEF, we have to store the value produced by this instruction
696 // on the stack position allocated for this LR
698 // actual storing instruction(s)
699 MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff,
700 RegType, scratchReg);
702 MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
705 // Finally, insert the entire spill code sequences before/after MInst
706 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
707 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
711 std::cerr << "\nFor Inst:\n " << *MInst;
712 std::cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
713 std::cerr << "; added Instructions:";
714 for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
715 for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
720 /// Insert caller saving/restoring instructions before/after a call machine
721 /// instruction (before or after any other instructions that were inserted for
725 PhyRegAlloc::insertCallerSavingCode(std::vector<MachineInstr*> &instrnsBefore,
726 std::vector<MachineInstr*> &instrnsAfter,
727 MachineInstr *CallMI,
728 const BasicBlock *BB) {
729 assert(TM.getInstrInfo()->isCall(CallMI->getOpcode()));
731 // hash set to record which registers were saved/restored
732 hash_set<unsigned> PushedRegSet;
734 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
736 // if the call is to a instrumentation function, do not insert save and
737 // restore instructions the instrumentation function takes care of save
738 // restore for volatile regs.
740 // FIXME: this should be made general, not specific to the reoptimizer!
741 const Function *Callee = argDesc->getCallInst()->getCalledFunction();
742 bool isLLVMFirstTrigger = Callee && Callee->getName() == "llvm_first_trigger";
744 // Now check if the call has a return value (using argDesc) and if so,
745 // find the LR of the TmpInstruction representing the return value register.
746 // (using the last or second-last *implicit operand* of the call MI).
747 // Insert it to to the PushedRegSet since we must not save that register
748 // and restore it after the call.
749 // We do this because, we look at the LV set *after* the instruction
750 // to determine, which LRs must be saved across calls. The return value
751 // of the call is live in this set - but we must not save/restore it.
752 if (const Value *origRetVal = argDesc->getReturnValue()) {
753 unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
754 (argDesc->getIndirectFuncPtr()? 1 : 2));
755 const TmpInstruction* tmpRetVal =
756 cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
757 assert(tmpRetVal->getOperand(0) == origRetVal &&
758 tmpRetVal->getType() == origRetVal->getType() &&
759 "Wrong implicit ref?");
760 V9LiveRange *RetValLR = LRI->getLiveRangeForValue(tmpRetVal);
761 assert(RetValLR && "No LR for RetValue of call");
763 if (! RetValLR->isMarkedForSpill())
764 PushedRegSet.insert(MRI.getUnifiedRegNum(RetValLR->getRegClassID(),
765 RetValLR->getColor()));
768 const ValueSet &LVSetAft = LVI->getLiveVarSetAfterMInst(CallMI, BB);
769 ValueSet::const_iterator LIt = LVSetAft.begin();
771 // for each live var in live variable set after machine inst
772 for( ; LIt != LVSetAft.end(); ++LIt) {
773 // get the live range corresponding to live var
774 V9LiveRange *const LR = LRI->getLiveRangeForValue(*LIt);
776 // LR can be null if it is a const since a const
777 // doesn't have a dominating def - see Assumptions above
779 if (! LR->isMarkedForSpill()) {
780 assert(LR->hasColor() && "LR is neither spilled nor colored?");
781 unsigned RCID = LR->getRegClassID();
782 unsigned Color = LR->getColor();
784 if (MRI.isRegVolatile(RCID, Color) ) {
785 // if this is a call to the first-level reoptimizer
786 // instrumentation entry point, and the register is not
787 // modified by call, don't save and restore it.
788 if (isLLVMFirstTrigger && !MRI.modifiedByCall(RCID, Color))
791 // if the value is in both LV sets (i.e., live before and after
792 // the call machine instruction)
793 unsigned Reg = MRI.getUnifiedRegNum(RCID, Color);
795 // if we haven't already pushed this register...
796 if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
797 unsigned RegType = MRI.getRegTypeForLR(LR);
799 // Now get two instructions - to push on stack and pop from stack
800 // and add them to InstrnsBefore and InstrnsAfter of the
803 MF->getInfo<SparcV9FunctionInfo>()->pushTempValue(MRI.getSpilledRegSize(RegType));
805 //---- Insert code for pushing the reg on stack ----------
807 std::vector<MachineInstr*> AdIBef, AdIAft;
809 // We may need a scratch register to copy the saved value
810 // to/from memory. This may itself have to insert code to
811 // free up a scratch register. Any such code should go before
812 // the save code. The scratch register, if any, is by default
813 // temporary and not "used" by the instruction unless the
814 // copy code itself decides to keep the value in the scratch reg.
815 int scratchRegType = -1;
817 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
818 { // Find a register not live in the LVSet before CallMI
819 const ValueSet &LVSetBef =
820 LVI->getLiveVarSetBeforeMInst(CallMI, BB);
821 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
822 CallMI, AdIBef, AdIAft);
823 assert(scratchReg != MRI.getInvalidRegNum());
826 if (AdIBef.size() > 0)
827 instrnsBefore.insert(instrnsBefore.end(),
828 AdIBef.begin(), AdIBef.end());
830 MRI.cpReg2MemMI(instrnsBefore, Reg, MRI.getFramePointer(),
831 StackOff, RegType, scratchReg);
833 if (AdIAft.size() > 0)
834 instrnsBefore.insert(instrnsBefore.end(),
835 AdIAft.begin(), AdIAft.end());
837 //---- Insert code for popping the reg from the stack ----------
841 // We may need a scratch register to copy the saved value
842 // from memory. This may itself have to insert code to
843 // free up a scratch register. Any such code should go
844 // after the save code. As above, scratch is not marked "used".
847 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
848 { // Find a register not live in the LVSet after CallMI
849 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetAft,
850 CallMI, AdIBef, AdIAft);
851 assert(scratchReg != MRI.getInvalidRegNum());
854 if (AdIBef.size() > 0)
855 instrnsAfter.insert(instrnsAfter.end(),
856 AdIBef.begin(), AdIBef.end());
858 MRI.cpMem2RegMI(instrnsAfter, MRI.getFramePointer(), StackOff,
859 Reg, RegType, scratchReg);
861 if (AdIAft.size() > 0)
862 instrnsAfter.insert(instrnsAfter.end(),
863 AdIAft.begin(), AdIAft.end());
865 PushedRegSet.insert(Reg);
868 std::cerr << "\nFor call inst:" << *CallMI;
869 std::cerr << " -inserted caller saving instrs: Before:\n\t ";
870 for_each(instrnsBefore.begin(), instrnsBefore.end(),
871 std::mem_fun(&MachineInstr::dump));
872 std::cerr << " -and After:\n\t ";
873 for_each(instrnsAfter.begin(), instrnsAfter.end(),
874 std::mem_fun(&MachineInstr::dump));
876 } // if not already pushed
877 } // if LR has a volatile color
879 } // if there is a LR for Var
880 } // for each value in the LV set after instruction
884 /// Returns the unified register number of a temporary register to be used
885 /// BEFORE MInst. If no register is available, it will pick one and modify
886 /// MIBef and MIAft to contain instructions used to free up this returned
889 int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
890 const ValueSet *LVSetBef,
892 std::vector<MachineInstr*>& MIBef,
893 std::vector<MachineInstr*>& MIAft) {
894 RegClass* RC = getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
896 int RegU = getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
899 // we couldn't find an unused register. Generate code to free up a reg by
900 // saving it on stack and restoring after the instruction
902 int TmpOff = MF->getInfo<SparcV9FunctionInfo>()->pushTempValue(MRI.getSpilledRegSize(RegType));
904 RegU = getUniRegNotUsedByThisInst(RC, RegType, MInst);
906 // Check if we need a scratch register to copy this register to memory.
907 int scratchRegType = -1;
908 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType)) {
909 int scratchReg = getUsableUniRegAtMI(scratchRegType, LVSetBef,
910 MInst, MIBef, MIAft);
911 assert(scratchReg != MRI.getInvalidRegNum());
913 // We may as well hold the value in the scratch register instead
914 // of copying it to memory and back. But we have to mark the
915 // register as used by this instruction, so it does not get used
916 // as a scratch reg. by another operand or anyone else.
917 ScratchRegsUsed.insert(std::make_pair(MInst, scratchReg));
918 MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
919 MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
920 } else { // the register can be copied directly to/from memory so do it.
921 MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
922 MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
930 /// Returns the register-class register number of a new unused register that
931 /// can be used to accommodate a temporary value. May be called repeatedly
932 /// for a single MachineInstr. On each call, it finds a register which is not
933 /// live at that instruction and which is not used by any spilled operands of
934 /// that instruction.
936 int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC, const int RegType,
937 const MachineInstr *MInst,
938 const ValueSet* LVSetBef) {
939 RC->clearColorsUsed(); // Reset array
941 if (LVSetBef == NULL) {
942 LVSetBef = &LVI->getLiveVarSetBeforeMInst(MInst);
943 assert(LVSetBef != NULL && "Unable to get live-var set before MInst?");
946 ValueSet::const_iterator LIt = LVSetBef->begin();
948 // for each live var in live variable set after machine inst
949 for ( ; LIt != LVSetBef->end(); ++LIt) {
950 // Get the live range corresponding to live var, and its RegClass
951 V9LiveRange *const LRofLV = LRI->getLiveRangeForValue(*LIt );
953 // LR can be null if it is a const since a const
954 // doesn't have a dominating def - see Assumptions above
955 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor())
956 RC->markColorsUsed(LRofLV->getColor(),
957 MRI.getRegTypeForLR(LRofLV), RegType);
960 // It is possible that one operand of this MInst was already spilled
961 // and it received some register temporarily. If that's the case,
962 // it is recorded in machine operand. We must skip such registers.
963 setRelRegsUsedByThisInst(RC, RegType, MInst);
965 int unusedReg = RC->getUnusedColor(RegType); // find first unused color
967 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
973 /// Return the unified register number of a register in class RC which is not
974 /// used by any operands of MInst.
976 int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
978 const MachineInstr *MInst) {
979 RC->clearColorsUsed();
981 setRelRegsUsedByThisInst(RC, RegType, MInst);
983 // find the first unused color
984 int unusedReg = RC->getUnusedColor(RegType);
985 assert(unusedReg >= 0 &&
986 "FATAL: No free register could be found in reg class!!");
988 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
992 /// Modify the IsColorUsedArr of register class RC, by setting the bits
993 /// corresponding to register RegNo. This is a helper method of
994 /// setRelRegsUsedByThisInst().
996 static void markRegisterUsed(int RegNo, RegClass *RC, int RegType,
997 const SparcV9RegInfo &TRI) {
998 unsigned classId = 0;
999 int classRegNum = TRI.getClassRegNum(RegNo, classId);
1000 if (RC->getID() == classId)
1001 RC->markColorsUsed(classRegNum, RegType, RegType);
1004 void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC, int RegType,
1005 const MachineInstr *MI) {
1006 assert(OperandsColoredMap[MI] == true &&
1007 "Illegal to call setRelRegsUsedByThisInst() until colored operands "
1008 "are marked for an instruction.");
1010 // Add the registers already marked as used by the instruction. Both
1011 // explicit and implicit operands are set.
1012 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
1013 if (MI->getOperand(i).hasAllocatedReg())
1014 markRegisterUsed(MI->getOperand(i).getReg(), RC, RegType,MRI);
1016 for (unsigned i = 0, e = MI->getNumImplicitRefs(); i != e; ++i)
1017 if (MI->getImplicitOp(i).hasAllocatedReg())
1018 markRegisterUsed(MI->getImplicitOp(i).getReg(), RC, RegType,MRI);
1020 // Add all of the scratch registers that are used to save values across the
1021 // instruction (e.g., for saving state register values).
1022 std::pair<ScratchRegsUsedTy::iterator, ScratchRegsUsedTy::iterator>
1023 IR = ScratchRegsUsed.equal_range(MI);
1024 for (ScratchRegsUsedTy::iterator I = IR.first; I != IR.second; ++I)
1025 markRegisterUsed(I->second, RC, RegType, MRI);
1027 // If there are implicit references, mark their allocated regs as well
1028 for (unsigned z=0; z < MI->getNumImplicitRefs(); z++)
1029 if (const V9LiveRange*
1030 LRofImpRef = LRI->getLiveRangeForValue(MI->getImplicitRef(z)))
1031 if (LRofImpRef->hasColor())
1032 // this implicit reference is in a LR that received a color
1033 RC->markColorsUsed(LRofImpRef->getColor(),
1034 MRI.getRegTypeForLR(LRofImpRef), RegType);
1038 /// If there are delay slots for an instruction, the instructions added after
1039 /// it must really go after the delayed instruction(s). So, we Move the
1040 /// InstrAfter of that instruction to the corresponding delayed instruction
1041 /// using the following method.
1043 void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
1044 const MachineInstr *DelayedMI)
1046 // "added after" instructions of the original instr
1047 std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
1049 if (DEBUG_RA && OrigAft.size() > 0) {
1050 std::cerr << "\nRegAlloc: Moved InstrnsAfter for: " << *OrigMI;
1051 std::cerr << " to last delay slot instrn: " << *DelayedMI;
1054 // "added after" instructions of the delayed instr
1055 std::vector<MachineInstr *> &DelayedAft=AddedInstrMap[DelayedMI].InstrnsAfter;
1057 // go thru all the "added after instructions" of the original instruction
1058 // and append them to the "added after instructions" of the delayed
1060 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
1062 // empty the "added after instructions" of the original instruction
1067 void PhyRegAlloc::colorIncomingArgs()
1069 MRI.colorMethodArgs(Fn, *LRI, AddedInstrAtEntry.InstrnsBefore,
1070 AddedInstrAtEntry.InstrnsAfter);
1074 /// Determine whether the suggested color of each live range is really usable,
1075 /// and then call its setSuggestedColorUsable() method to record the answer. A
1076 /// suggested color is NOT usable when the suggested color is volatile AND
1077 /// when there are call interferences.
1079 void PhyRegAlloc::markUnusableSugColors()
1081 LiveRangeMapType::const_iterator HMI = (LRI->getLiveRangeMap())->begin();
1082 LiveRangeMapType::const_iterator HMIEnd = (LRI->getLiveRangeMap())->end();
1084 for (; HMI != HMIEnd ; ++HMI ) {
1086 V9LiveRange *L = HMI->second; // get the V9LiveRange
1087 if (L && L->hasSuggestedColor ())
1088 L->setSuggestedColorUsable
1089 (!(MRI.isRegVolatile (L->getRegClassID (), L->getSuggestedColor ())
1090 && L->isCallInterference ()));
1092 } // for all LR's in hash map
1096 /// For each live range that is spilled, allocates a new spill position on the
1097 /// stack, and set the stack offsets of the live range that will be spilled to
1098 /// that position. This must be called just after coloring the LRs.
1100 void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
1101 if (DEBUG_RA) std::cerr << "\nSetting LR stack offsets for spills...\n";
1103 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
1104 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
1106 for ( ; HMI != HMIEnd ; ++HMI) {
1107 if (HMI->first && HMI->second) {
1108 V9LiveRange *L = HMI->second; // get the V9LiveRange
1109 if (L->isMarkedForSpill()) { // NOTE: allocating size of long Type **
1110 int stackOffset = MF->getInfo<SparcV9FunctionInfo>()->allocateSpilledValue(Type::LongTy);
1111 L->setSpillOffFromFP(stackOffset);
1113 std::cerr << " LR# " << L->getUserIGNode()->getIndex()
1114 << ": stack-offset = " << stackOffset << "\n";
1117 } // for all LR's in hash map
1121 void PhyRegAlloc::saveStateForValue (std::vector<AllocInfo> &state,
1122 const Value *V, int Insn, int Opnd) {
1123 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap ()->find (V);
1124 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap ()->end ();
1125 AllocInfo::AllocStateTy AllocState = AllocInfo::NotAllocated;
1127 if ((HMI != HMIEnd) && HMI->second) {
1128 V9LiveRange *L = HMI->second;
1129 assert ((L->hasColor () || L->isMarkedForSpill ())
1130 && "Live range exists but not colored or spilled");
1131 if (L->hasColor ()) {
1132 AllocState = AllocInfo::Allocated;
1133 Placement = MRI.getUnifiedRegNum (L->getRegClassID (),
1135 } else if (L->isMarkedForSpill ()) {
1136 AllocState = AllocInfo::Spilled;
1137 assert (L->hasSpillOffset ()
1138 && "Live range marked for spill but has no spill offset");
1139 Placement = L->getSpillOffFromFP ();
1142 state.push_back (AllocInfo (Insn, Opnd, AllocState, Placement));
1146 /// Save the global register allocation decisions made by the register
1147 /// allocator so that they can be accessed later (sort of like "poor man's
1150 void PhyRegAlloc::saveState () {
1151 std::vector<AllocInfo> &state = FnAllocState[Fn];
1152 unsigned ArgNum = 0;
1153 // Arguments encoded as instruction # -1
1154 for (Function::const_arg_iterator i=Fn->arg_begin (), e=Fn->arg_end (); i != e; ++i) {
1155 const Argument *Arg = &*i;
1156 saveStateForValue (state, Arg, -1, ArgNum);
1159 unsigned InstCount = 0;
1160 // Instructions themselves encoded as operand # -1
1161 for (const_inst_iterator II=inst_begin (Fn), IE=inst_end (Fn); II!=IE; ++II){
1162 const Instruction *Inst = &*II;
1163 saveStateForValue (state, Inst, InstCount, -1);
1164 if (isa<PHINode> (Inst)) {
1165 MachineCodeForInstruction &MCforPN = MachineCodeForInstruction::get(Inst);
1166 // Last instr should be the copy...figure out what reg it is reading from
1167 if (Value *PhiCpRes = MCforPN.back()->getOperand(0).getVRegValueOrNull()){
1169 std::cerr << "Found Phi copy result: " << PhiCpRes->getName()
1170 << " in: " << *MCforPN.back() << "\n";
1171 saveStateForValue (state, PhiCpRes, InstCount, -2);
1179 bool PhyRegAlloc::doFinalization (Module &M) {
1180 if (SaveRegAllocState) finishSavingState (M);
1185 /// Finish the job of saveState(), by collapsing FnAllocState into an LLVM
1186 /// Constant and stuffing it inside the Module.
1188 /// FIXME: There should be other, better ways of storing the saved
1189 /// state; this one is cumbersome and does not work well with the JIT.
1191 void PhyRegAlloc::finishSavingState (Module &M) {
1193 std::cerr << "---- Saving reg. alloc state; SaveStateToModule = "
1194 << SaveStateToModule << " ----\n";
1196 // If saving state into the module, just copy new elements to the
1198 if (!SaveStateToModule) {
1199 ExportedFnAllocState = FnAllocState;
1200 // FIXME: should ONLY copy new elements in FnAllocState
1204 // Convert FnAllocState to a single Constant array and add it
1206 ArrayType *AT = ArrayType::get (AllocInfo::getConstantType (), 0);
1207 std::vector<const Type *> TV;
1208 TV.push_back (Type::UIntTy);
1210 PointerType *PT = PointerType::get (StructType::get (TV));
1212 std::vector<Constant *> allstate;
1213 for (Module::iterator I = M.begin (), E = M.end (); I != E; ++I) {
1215 if (F->isExternal ()) continue;
1216 if (FnAllocState.find (F) == FnAllocState.end ()) {
1217 allstate.push_back (ConstantPointerNull::get (PT));
1219 std::vector<AllocInfo> &state = FnAllocState[F];
1221 // Convert state into an LLVM ConstantArray, and put it in a
1222 // ConstantStruct (named S) along with its size.
1223 std::vector<Constant *> stateConstants;
1224 for (unsigned i = 0, s = state.size (); i != s; ++i)
1225 stateConstants.push_back (state[i].toConstant ());
1226 unsigned Size = stateConstants.size ();
1227 ArrayType *AT = ArrayType::get (AllocInfo::getConstantType (), Size);
1228 std::vector<const Type *> TV;
1229 TV.push_back (Type::UIntTy);
1231 StructType *ST = StructType::get (TV);
1232 std::vector<Constant *> CV;
1233 CV.push_back (ConstantUInt::get (Type::UIntTy, Size));
1234 CV.push_back (ConstantArray::get (AT, stateConstants));
1235 Constant *S = ConstantStruct::get (ST, CV);
1237 GlobalVariable *GV =
1238 new GlobalVariable (ST, true,
1239 GlobalValue::InternalLinkage, S,
1240 F->getName () + ".regAllocState", &M);
1242 // Have: { uint, [Size x { uint, int, uint, int }] } *
1243 // Cast it to: { uint, [0 x { uint, int, uint, int }] } *
1244 Constant *CE = ConstantExpr::getCast (GV, PT);
1245 allstate.push_back (CE);
1249 unsigned Size = allstate.size ();
1250 // Final structure type is:
1251 // { uint, [Size x { uint, [0 x { uint, int, uint, int }] } *] }
1252 std::vector<const Type *> TV2;
1253 TV2.push_back (Type::UIntTy);
1254 ArrayType *AT2 = ArrayType::get (PT, Size);
1255 TV2.push_back (AT2);
1256 StructType *ST2 = StructType::get (TV2);
1257 std::vector<Constant *> CV2;
1258 CV2.push_back (ConstantUInt::get (Type::UIntTy, Size));
1259 CV2.push_back (ConstantArray::get (AT2, allstate));
1260 new GlobalVariable (ST2, true, GlobalValue::ExternalLinkage,
1261 ConstantStruct::get (ST2, CV2), "_llvm_regAllocState",
1266 /// Allocate registers for the machine code previously generated for F using
1267 /// the graph-coloring algorithm.
1269 bool PhyRegAlloc::runOnFunction (Function &F) {
1271 std::cerr << "\n********* Function "<< F.getName () << " ***********\n";
1274 MF = &MachineFunction::get (Fn);
1275 LVI = &getAnalysis<FunctionLiveVarInfo> ();
1276 LRI = new LiveRangeInfo (Fn, TM, RegClassList);
1277 LoopDepthCalc = &getAnalysis<LoopInfo> ();
1279 // Create each RegClass for the target machine and add it to the
1280 // RegClassList. This must be done before calling constructLiveRanges().
1281 for (unsigned rc = 0; rc != NumOfRegClasses; ++rc)
1282 RegClassList.push_back (new RegClass (Fn, TM.getRegInfo(),
1283 MRI.getMachineRegClass(rc)));
1285 LRI->constructLiveRanges(); // create LR info
1286 if (DEBUG_RA >= RA_DEBUG_LiveRanges)
1287 LRI->printLiveRanges();
1289 createIGNodeListsAndIGs(); // create IGNode list and IGs
1291 buildInterferenceGraphs(); // build IGs in all reg classes
1293 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1294 // print all LRs in all reg classes
1295 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1296 RegClassList[rc]->printIGNodeList();
1298 // print IGs in all register classes
1299 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1300 RegClassList[rc]->printIG();
1303 LRI->coalesceLRs(); // coalesce all live ranges
1305 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
1306 // print all LRs in all reg classes
1307 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1308 RegClassList[rc]->printIGNodeList();
1310 // print IGs in all register classes
1311 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1312 RegClassList[rc]->printIG();
1315 // mark un-usable suggested color before graph coloring algorithm.
1316 // When this is done, the graph coloring algo will not reserve
1317 // suggested color unnecessarily - they can be used by another LR
1318 markUnusableSugColors();
1320 // color all register classes using the graph coloring algo
1321 for (unsigned rc=0; rc < NumOfRegClasses ; rc++)
1322 RegClassList[rc]->colorAllRegs();
1324 // After graph coloring, if some LRs did not receive a color (i.e, spilled)
1325 // a position for such spilled LRs
1326 allocateStackSpace4SpilledLRs();
1328 // Reset the temp. area on the stack before use by the first instruction.
1329 // This will also happen after updating each instruction.
1330 MF->getInfo<SparcV9FunctionInfo>()->popAllTempValues();
1332 // color incoming args - if the correct color was not received
1333 // insert code to copy to the correct register
1334 colorIncomingArgs();
1336 // Save register allocation state for this function in a Constant.
1337 if (SaveRegAllocState)
1340 // Now update the machine code with register names and add any additional
1341 // code inserted by the register allocator to the instruction stream.
1342 updateMachineCode();
1344 if (SaveRegAllocState && !SaveStateToModule)
1345 finishSavingState (const_cast<Module&> (*Fn->getParent ()));
1348 std::cerr << "\n**** Machine Code After Register Allocation:\n\n";
1352 // Tear down temporary data structures
1353 for (unsigned rc = 0; rc < NumOfRegClasses; ++rc)
1354 delete RegClassList[rc];
1355 RegClassList.clear ();
1356 AddedInstrMap.clear ();
1357 OperandsColoredMap.clear ();
1358 ScratchRegsUsed.clear ();
1359 AddedInstrAtEntry.clear ();
1362 if (DEBUG_RA) std::cerr << "\nRegister allocation complete!\n";
1363 return false; // Function was not modified
1366 } // End llvm namespace