blob: 83470f6580b6c3b6988d09920fac49e4ba1e60cd [file] [log] [blame]
Chris Lattner179cdfb2002-08-09 20:08:03 +00001//===-- PhyRegAlloc.cpp ---------------------------------------------------===//
Vikram S. Adve12af1642001-11-08 04:48:50 +00002//
Chris Lattner179cdfb2002-08-09 20:08:03 +00003// Register allocation for LLVM.
4//
5//===----------------------------------------------------------------------===//
Ruchira Sasanka8e604792001-09-14 21:18:34 +00006
Chris Lattner6dd98a62002-02-04 00:33:08 +00007#include "llvm/CodeGen/RegisterAllocation.h"
Chris Lattner70b2f562003-09-01 20:09:04 +00008#include "PhyRegAlloc.h"
Chris Lattner4309e732003-01-15 19:57:07 +00009#include "RegAllocCommon.h"
Chris Lattner9d4ed152003-01-15 21:14:01 +000010#include "RegClass.h"
Chris Lattnerc083dcc2003-09-01 20:05:47 +000011#include "IGNode.h"
Chris Lattnerf6ee49f2003-01-15 18:08:07 +000012#include "llvm/CodeGen/MachineInstrBuilder.h"
Vikram S. Advedabb41d2002-05-19 15:29:31 +000013#include "llvm/CodeGen/MachineInstrAnnot.h"
Misha Brukmanfce11432002-10-28 00:28:31 +000014#include "llvm/CodeGen/MachineFunction.h"
Chris Lattnere90fcb72002-12-28 20:35:34 +000015#include "llvm/CodeGen/MachineFunctionInfo.h"
Chris Lattner92ba2aa2003-01-14 23:05:08 +000016#include "llvm/CodeGen/FunctionLiveVarInfo.h"
Vikram S. Adve814030a2003-07-29 19:49:21 +000017#include "llvm/CodeGen/InstrSelection.h"
Chris Lattner14ab1ce2002-02-04 17:48:00 +000018#include "llvm/Analysis/LoopInfo.h"
Chris Lattner8bd66e62002-12-28 21:00:25 +000019#include "llvm/Target/TargetFrameInfo.h"
Chris Lattner3501fea2003-01-14 22:00:31 +000020#include "llvm/Target/TargetInstrInfo.h"
Chris Lattner2fbfdcf2002-04-07 20:49:59 +000021#include "llvm/Function.h"
Chris Lattner37730942002-02-05 03:52:29 +000022#include "llvm/Type.h"
Vikram S. Advedabb41d2002-05-19 15:29:31 +000023#include "llvm/iOther.h"
Vikram S. Advef5af6362002-07-08 23:15:32 +000024#include "Support/STLExtras.h"
Vikram S. Advefeb32982003-08-12 22:22:24 +000025#include "Support/SetOperations.h"
Chris Lattner4bc23482002-09-15 07:07:55 +000026#include "Support/CommandLine.h"
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +000027#include <math.h>
Vikram S. Adve12af1642001-11-08 04:48:50 +000028
Chris Lattner70e60cb2002-05-22 17:08:27 +000029RegAllocDebugLevel_t DEBUG_RA;
Vikram S. Adve39c94e12002-09-14 23:05:33 +000030
Chris Lattner5ff62e92002-07-22 02:10:13 +000031static cl::opt<RegAllocDebugLevel_t, true>
32DRA_opt("dregalloc", cl::Hidden, cl::location(DEBUG_RA),
33 cl::desc("enable register allocation debugging information"),
34 cl::values(
Vikram S. Adve39c94e12002-09-14 23:05:33 +000035 clEnumValN(RA_DEBUG_None , "n", "disable debug output"),
36 clEnumValN(RA_DEBUG_Results, "y", "debug output for allocation results"),
37 clEnumValN(RA_DEBUG_Coloring, "c", "debug output for graph coloring step"),
38 clEnumValN(RA_DEBUG_Interference,"ig","debug output for interference graphs"),
39 clEnumValN(RA_DEBUG_LiveRanges , "lr","debug output for live ranges"),
40 clEnumValN(RA_DEBUG_Verbose, "v", "extra debug output"),
Chris Lattner5ff62e92002-07-22 02:10:13 +000041 0));
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +000042
Brian Gaekebf3c4cf2003-08-14 06:09:32 +000043FunctionPass *getRegisterAllocator(TargetMachine &T) {
Brian Gaeke4efe3422003-09-21 01:23:46 +000044 return new PhyRegAlloc (T);
Chris Lattner2f9b28e2002-02-04 15:54:09 +000045}
Chris Lattner6dd98a62002-02-04 00:33:08 +000046
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +000047
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +000048//----------------------------------------------------------------------------
Misha Brukman37f92e22003-09-11 22:34:13 +000049// This method initially creates interference graphs (one in each reg class)
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +000050// and IGNodeList (one in each IG). The actual nodes will be pushed later.
51//----------------------------------------------------------------------------
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000052void PhyRegAlloc::createIGNodeListsAndIGs() {
Chris Lattnerc083dcc2003-09-01 20:05:47 +000053 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "Creating LR lists ...\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +000054
55 // hash map iterator
Brian Gaeke4efe3422003-09-21 01:23:46 +000056 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
Ruchira Sasanka8e604792001-09-14 21:18:34 +000057
58 // hash map end
Brian Gaeke4efe3422003-09-21 01:23:46 +000059 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
Ruchira Sasanka8e604792001-09-14 21:18:34 +000060
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000061 for (; HMI != HMIEnd ; ++HMI ) {
62 if (HMI->first) {
63 LiveRange *L = HMI->second; // get the LiveRange
64 if (!L) {
Vikram S. Adve39c94e12002-09-14 23:05:33 +000065 if (DEBUG_RA)
Chris Lattnerc083dcc2003-09-01 20:05:47 +000066 std::cerr << "\n**** ?!?WARNING: NULL LIVE RANGE FOUND FOR: "
Vikram S. Adve39c94e12002-09-14 23:05:33 +000067 << RAV(HMI->first) << "****\n";
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000068 continue;
69 }
Vikram S. Adve39c94e12002-09-14 23:05:33 +000070
71 // if the Value * is not null, and LR is not yet written to the IGNodeList
Chris Lattner7e708292002-06-25 16:13:24 +000072 if (!(L->getUserIGNode()) ) {
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000073 RegClass *const RC = // RegClass of first value in the LR
74 RegClassList[ L->getRegClass()->getID() ];
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000075 RC->addLRToIG(L); // add this LR to an IG
76 }
Ruchira Sasanka8e604792001-09-14 21:18:34 +000077 }
78 }
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000079
80 // init RegClassList
Chris Lattner7e708292002-06-25 16:13:24 +000081 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
Chris Lattnerdd1e40b2002-02-03 07:46:34 +000082 RegClassList[rc]->createInterferenceGraph();
Ruchira Sasanka8e604792001-09-14 21:18:34 +000083
Chris Lattnerc083dcc2003-09-01 20:05:47 +000084 if (DEBUG_RA >= RA_DEBUG_LiveRanges) std::cerr << "LRLists Created!\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +000085}
86
87
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +000088//----------------------------------------------------------------------------
89// This method will add all interferences at for a given instruction.
Misha Brukman37f92e22003-09-11 22:34:13 +000090// Interference occurs only if the LR of Def (Inst or Arg) is of the same reg
Ruchira Sasanka8e604792001-09-14 21:18:34 +000091// class as that of live var. The live var passed to this function is the
92// LVset AFTER the instruction
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +000093//----------------------------------------------------------------------------
Vikram S. Adve39c94e12002-09-14 23:05:33 +000094
Chris Lattner296b7732002-02-05 02:52:05 +000095void PhyRegAlloc::addInterference(const Value *Def,
96 const ValueSet *LVSet,
97 bool isCallInst) {
Chris Lattner296b7732002-02-05 02:52:05 +000098 ValueSet::const_iterator LIt = LVSet->begin();
Ruchira Sasanka8e604792001-09-14 21:18:34 +000099
100 // get the live range of instruction
Brian Gaeke4efe3422003-09-21 01:23:46 +0000101 const LiveRange *const LROfDef = LRI->getLiveRangeForValue( Def );
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000102
103 IGNode *const IGNodeOfDef = LROfDef->getUserIGNode();
104 assert( IGNodeOfDef );
105
106 RegClass *const RCOfDef = LROfDef->getRegClass();
107
108 // for each live var in live variable set
Chris Lattner7e708292002-06-25 16:13:24 +0000109 for ( ; LIt != LVSet->end(); ++LIt) {
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000110
Vikram S. Advef5af6362002-07-08 23:15:32 +0000111 if (DEBUG_RA >= RA_DEBUG_Verbose)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000112 std::cerr << "< Def=" << RAV(Def) << ", Lvar=" << RAV(*LIt) << "> ";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000113
114 // get the live range corresponding to live var
Brian Gaeke4efe3422003-09-21 01:23:46 +0000115 LiveRange *LROfVar = LRI->getLiveRangeForValue(*LIt);
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000116
117 // LROfVar can be null if it is a const since a const
118 // doesn't have a dominating def - see Assumptions above
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000119 if (LROfVar)
120 if (LROfDef != LROfVar) // do not set interf for same LR
121 if (RCOfDef == LROfVar->getRegClass()) // 2 reg classes are the same
122 RCOfDef->setInterference( LROfDef, LROfVar);
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000123 }
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000124}
125
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000126
127//----------------------------------------------------------------------------
128// For a call instruction, this method sets the CallInterference flag in
129// the LR of each variable live int the Live Variable Set live after the
130// call instruction (except the return value of the call instruction - since
131// the return value does not interfere with that call itself).
132//----------------------------------------------------------------------------
133
134void PhyRegAlloc::setCallInterferences(const MachineInstr *MInst,
Chris Lattner296b7732002-02-05 02:52:05 +0000135 const ValueSet *LVSetAft) {
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000136 if (DEBUG_RA >= RA_DEBUG_Interference)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000137 std::cerr << "\n For call inst: " << *MInst;
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000138
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000139 // for each live var in live variable set after machine inst
Vikram S. Adve65b2f402003-07-02 01:24:00 +0000140 for (ValueSet::const_iterator LIt = LVSetAft->begin(), LEnd = LVSetAft->end();
141 LIt != LEnd; ++LIt) {
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000142
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000143 // get the live range corresponding to live var
Brian Gaeke4efe3422003-09-21 01:23:46 +0000144 LiveRange *const LR = LRI->getLiveRangeForValue(*LIt );
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000145
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000146 // LR can be null if it is a const since a const
147 // doesn't have a dominating def - see Assumptions above
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000148 if (LR ) {
149 if (DEBUG_RA >= RA_DEBUG_Interference) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000150 std::cerr << "\n\tLR after Call: ";
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000151 printSet(*LR);
152 }
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000153 LR->setCallInterference();
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000154 if (DEBUG_RA >= RA_DEBUG_Interference) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000155 std::cerr << "\n ++After adding call interference for LR: " ;
Chris Lattner296b7732002-02-05 02:52:05 +0000156 printSet(*LR);
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000157 }
158 }
159
160 }
161
Vikram S. Adve1a53f032002-03-31 18:54:37 +0000162 // Now find the LR of the return value of the call
163 // We do this because, we look at the LV set *after* the instruction
164 // to determine, which LRs must be saved across calls. The return value
165 // of the call is live in this set - but it does not interfere with call
166 // (i.e., we can allocate a volatile register to the return value)
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000167 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(MInst);
168
169 if (const Value *RetVal = argDesc->getReturnValue()) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000170 LiveRange *RetValLR = LRI->getLiveRangeForValue( RetVal );
Vikram S. Adve1a53f032002-03-31 18:54:37 +0000171 assert( RetValLR && "No LR for RetValue of call");
172 RetValLR->clearCallInterference();
173 }
174
175 // If the CALL is an indirect call, find the LR of the function pointer.
176 // That has a call interference because it conflicts with outgoing args.
Chris Lattner7e708292002-06-25 16:13:24 +0000177 if (const Value *AddrVal = argDesc->getIndirectFuncPtr()) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000178 LiveRange *AddrValLR = LRI->getLiveRangeForValue( AddrVal );
Vikram S. Adve1a53f032002-03-31 18:54:37 +0000179 assert( AddrValLR && "No LR for indirect addr val of call");
180 AddrValLR->setCallInterference();
181 }
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000182}
183
184
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +0000185//----------------------------------------------------------------------------
186// This method will walk thru code and create interferences in the IG of
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000187// each RegClass. Also, this method calculates the spill cost of each
188// Live Range (it is done in this method to save another pass over the code).
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +0000189//----------------------------------------------------------------------------
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000190
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000191void PhyRegAlloc::buildInterferenceGraphs()
192{
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000193 if (DEBUG_RA >= RA_DEBUG_Interference)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000194 std::cerr << "Creating interference graphs ...\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000195
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000196 unsigned BBLoopDepthCost;
Brian Gaeke4efe3422003-09-21 01:23:46 +0000197 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000198 BBI != BBE; ++BBI) {
Chris Lattnerf726e772002-10-28 19:22:04 +0000199 const MachineBasicBlock &MBB = *BBI;
200 const BasicBlock *BB = MBB.getBasicBlock();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000201
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000202 // find the 10^(loop_depth) of this BB
Chris Lattnerf726e772002-10-28 19:22:04 +0000203 BBLoopDepthCost = (unsigned)pow(10.0, LoopDepthCalc->getLoopDepth(BB));
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000204
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000205 // get the iterator for machine instructions
Chris Lattnerf726e772002-10-28 19:22:04 +0000206 MachineBasicBlock::const_iterator MII = MBB.begin();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000207
208 // iterate over all the machine instructions in BB
Chris Lattnerf726e772002-10-28 19:22:04 +0000209 for ( ; MII != MBB.end(); ++MII) {
210 const MachineInstr *MInst = *MII;
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000211
212 // get the LV set after the instruction
Chris Lattnerf726e772002-10-28 19:22:04 +0000213 const ValueSet &LVSetAI = LVI->getLiveVarSetAfterMInst(MInst, BB);
214 bool isCallInst = TM.getInstrInfo().isCall(MInst->getOpCode());
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000215
Chris Lattner7e708292002-06-25 16:13:24 +0000216 if (isCallInst ) {
Misha Brukman37f92e22003-09-11 22:34:13 +0000217 // set the isCallInterference flag of each live range which extends
218 // across this call instruction. This information is used by graph
219 // coloring algorithm to avoid allocating volatile colors to live ranges
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000220 // that span across calls (since they have to be saved/restored)
Chris Lattner748697d2002-02-05 04:20:12 +0000221 setCallInterferences(MInst, &LVSetAI);
Ruchira Sasanka958faf32001-10-19 17:21:03 +0000222 }
223
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000224 // iterate over all MI operands to find defs
Chris Lattner2f898d22002-02-05 06:02:59 +0000225 for (MachineInstr::const_val_op_iterator OpI = MInst->begin(),
226 OpE = MInst->end(); OpI != OpE; ++OpI) {
Vikram S. Adve5f2180c2003-05-27 00:05:23 +0000227 if (OpI.isDefOnly() || OpI.isDefAndUse()) // create a new LR since def
Chris Lattner748697d2002-02-05 04:20:12 +0000228 addInterference(*OpI, &LVSetAI, isCallInst);
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000229
230 // Calculate the spill cost of each live range
Brian Gaeke4efe3422003-09-21 01:23:46 +0000231 LiveRange *LR = LRI->getLiveRangeForValue(*OpI);
Chris Lattner2f898d22002-02-05 06:02:59 +0000232 if (LR) LR->addSpillCost(BBLoopDepthCost);
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000233 }
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000234
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000235 // if there are multiple defs in this instruction e.g. in SETX
Chris Lattnerdd1e40b2002-02-03 07:46:34 +0000236 if (TM.getInstrInfo().isPseudoInstr(MInst->getOpCode()))
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000237 addInterf4PseudoInstr(MInst);
238
Ruchira Sasankac4d4b762001-10-16 01:23:19 +0000239 // Also add interference for any implicit definitions in a machine
240 // instr (currently, only calls have this).
Ruchira Sasankac4d4b762001-10-16 01:23:19 +0000241 unsigned NumOfImpRefs = MInst->getNumImplicitRefs();
Vikram S. Adve5f2180c2003-05-27 00:05:23 +0000242 for (unsigned z=0; z < NumOfImpRefs; z++)
243 if (MInst->getImplicitOp(z).opIsDefOnly() ||
244 MInst->getImplicitOp(z).opIsDefAndUse())
245 addInterference( MInst->getImplicitRef(z), &LVSetAI, isCallInst );
Ruchira Sasankaef1b0cb2001-11-03 17:13:27 +0000246
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000247 } // for all machine instructions in BB
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000248 } // for all BBs in function
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000249
Misha Brukman37f92e22003-09-11 22:34:13 +0000250 // add interferences for function arguments. Since there are no explicit
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000251 // defs in the function for args, we have to add them manually
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000252 addInterferencesForArgs();
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000253
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000254 if (DEBUG_RA >= RA_DEBUG_Interference)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000255 std::cerr << "Interference graphs calculated!\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000256}
257
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000258
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000259//--------------------------------------------------------------------------
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000260// Pseudo-instructions may be expanded to multiple instructions by the
261// assembler. Consequently, all the operands must get distinct registers.
262// Therefore, we mark all operands of a pseudo-instruction as interfering
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000263// with one another.
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000264//--------------------------------------------------------------------------
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000265
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000266void PhyRegAlloc::addInterf4PseudoInstr(const MachineInstr *MInst) {
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000267 bool setInterf = false;
268
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000269 // iterate over MI operands to find defs
Chris Lattner2f898d22002-02-05 06:02:59 +0000270 for (MachineInstr::const_val_op_iterator It1 = MInst->begin(),
271 ItE = MInst->end(); It1 != ItE; ++It1) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000272 const LiveRange *LROfOp1 = LRI->getLiveRangeForValue(*It1);
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000273 assert((LROfOp1 || !It1.isUseOnly())&&"No LR for Def in PSEUDO insruction");
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000274
Chris Lattner2f898d22002-02-05 06:02:59 +0000275 MachineInstr::const_val_op_iterator It2 = It1;
Chris Lattner7e708292002-06-25 16:13:24 +0000276 for (++It2; It2 != ItE; ++It2) {
Brian Gaeke4efe3422003-09-21 01:23:46 +0000277 const LiveRange *LROfOp2 = LRI->getLiveRangeForValue(*It2);
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000278
Chris Lattner2f898d22002-02-05 06:02:59 +0000279 if (LROfOp2) {
280 RegClass *RCOfOp1 = LROfOp1->getRegClass();
281 RegClass *RCOfOp2 = LROfOp2->getRegClass();
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000282
Chris Lattner7e708292002-06-25 16:13:24 +0000283 if (RCOfOp1 == RCOfOp2 ){
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000284 RCOfOp1->setInterference( LROfOp1, LROfOp2 );
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000285 setInterf = true;
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000286 }
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000287 } // if Op2 has a LR
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000288 } // for all other defs in machine instr
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000289 } // for all operands in an instruction
290
Chris Lattner2f898d22002-02-05 06:02:59 +0000291 if (!setInterf && MInst->getNumOperands() > 2) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000292 std::cerr << "\nInterf not set for any operand in pseudo instr:\n";
293 std::cerr << *MInst;
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000294 assert(0 && "Interf not set for pseudo instr with > 2 operands" );
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +0000295 }
Ruchira Sasanka22ccb1b2001-11-14 15:33:58 +0000296}
297
298
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +0000299//----------------------------------------------------------------------------
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000300// This method adds interferences for incoming arguments to a function.
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +0000301//----------------------------------------------------------------------------
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000302
Chris Lattner296b7732002-02-05 02:52:05 +0000303void PhyRegAlloc::addInterferencesForArgs() {
304 // get the InSet of root BB
Chris Lattnerf726e772002-10-28 19:22:04 +0000305 const ValueSet &InSet = LVI->getInSetOfBB(&Fn->front());
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000306
Chris Lattnerf726e772002-10-28 19:22:04 +0000307 for (Function::const_aiterator AI = Fn->abegin(); AI != Fn->aend(); ++AI) {
Chris Lattner7e708292002-06-25 16:13:24 +0000308 // add interferences between args and LVars at start
309 addInterference(AI, &InSet, false);
310
Vikram S. Adve39c94e12002-09-14 23:05:33 +0000311 if (DEBUG_RA >= RA_DEBUG_Interference)
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000312 std::cerr << " - %% adding interference for argument " << RAV(AI) << "\n";
Ruchira Sasanka8e604792001-09-14 21:18:34 +0000313 }
314}
315
316
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +0000317//----------------------------------------------------------------------------
318// This method is called after register allocation is complete to set the
Misha Brukman37f92e22003-09-11 22:34:13 +0000319// allocated registers in the machine code. This code will add register numbers
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +0000320// to MachineOperands that contain a Value. Also it calls target specific
321// methods to produce caller saving instructions. At the end, it adds all
322// additional instructions produced by the register allocator to the
323// instruction stream.
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +0000324//----------------------------------------------------------------------------
Vikram S. Adve48762092002-04-25 04:34:15 +0000325
326//-----------------------------
327// Utility functions used below
328//-----------------------------
329inline void
Vikram S. Advecb202e32002-10-11 16:12:40 +0000330InsertBefore(MachineInstr* newMI,
Chris Lattnerf726e772002-10-28 19:22:04 +0000331 MachineBasicBlock& MBB,
Chris Lattner32be9f62002-10-28 01:41:27 +0000332 MachineBasicBlock::iterator& MII)
Vikram S. Advecb202e32002-10-11 16:12:40 +0000333{
Chris Lattnerf726e772002-10-28 19:22:04 +0000334 MII = MBB.insert(MII, newMI);
Vikram S. Advecb202e32002-10-11 16:12:40 +0000335 ++MII;
336}
337
338inline void
339InsertAfter(MachineInstr* newMI,
Chris Lattnerf726e772002-10-28 19:22:04 +0000340 MachineBasicBlock& MBB,
Chris Lattner32be9f62002-10-28 01:41:27 +0000341 MachineBasicBlock::iterator& MII)
Vikram S. Advecb202e32002-10-11 16:12:40 +0000342{
343 ++MII; // insert before the next instruction
Chris Lattnerf726e772002-10-28 19:22:04 +0000344 MII = MBB.insert(MII, newMI);
Vikram S. Advecb202e32002-10-11 16:12:40 +0000345}
346
347inline void
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000348DeleteInstruction(MachineBasicBlock& MBB,
349 MachineBasicBlock::iterator& MII)
350{
351 MII = MBB.erase(MII);
352}
353
354inline void
Vikram S. Advecb202e32002-10-11 16:12:40 +0000355SubstituteInPlace(MachineInstr* newMI,
Chris Lattnerf726e772002-10-28 19:22:04 +0000356 MachineBasicBlock& MBB,
Chris Lattner32be9f62002-10-28 01:41:27 +0000357 MachineBasicBlock::iterator MII)
Vikram S. Advecb202e32002-10-11 16:12:40 +0000358{
359 *MII = newMI;
360}
361
362inline void
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000363PrependInstructions(std::vector<MachineInstr *> &IBef,
Chris Lattnerf726e772002-10-28 19:22:04 +0000364 MachineBasicBlock& MBB,
Chris Lattner32be9f62002-10-28 01:41:27 +0000365 MachineBasicBlock::iterator& MII,
Vikram S. Adve48762092002-04-25 04:34:15 +0000366 const std::string& msg)
367{
368 if (!IBef.empty())
369 {
370 MachineInstr* OrigMI = *MII;
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000371 std::vector<MachineInstr *>::iterator AdIt;
Vikram S. Adve48762092002-04-25 04:34:15 +0000372 for (AdIt = IBef.begin(); AdIt != IBef.end() ; ++AdIt)
373 {
374 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000375 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
376 std::cerr << msg << "PREPENDed instr:\n " << **AdIt << "\n";
Vikram S. Adve48762092002-04-25 04:34:15 +0000377 }
Chris Lattnerf726e772002-10-28 19:22:04 +0000378 InsertBefore(*AdIt, MBB, MII);
Vikram S. Adve48762092002-04-25 04:34:15 +0000379 }
380 }
381}
382
383inline void
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000384AppendInstructions(std::vector<MachineInstr *> &IAft,
Chris Lattnerf726e772002-10-28 19:22:04 +0000385 MachineBasicBlock& MBB,
Chris Lattner32be9f62002-10-28 01:41:27 +0000386 MachineBasicBlock::iterator& MII,
Vikram S. Adve48762092002-04-25 04:34:15 +0000387 const std::string& msg)
388{
389 if (!IAft.empty())
390 {
391 MachineInstr* OrigMI = *MII;
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000392 std::vector<MachineInstr *>::iterator AdIt;
Chris Lattner7e708292002-06-25 16:13:24 +0000393 for ( AdIt = IAft.begin(); AdIt != IAft.end() ; ++AdIt )
Vikram S. Adve48762092002-04-25 04:34:15 +0000394 {
Chris Lattner7e708292002-06-25 16:13:24 +0000395 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000396 if (OrigMI) std::cerr << "For MInst:\n " << *OrigMI;
397 std::cerr << msg << "APPENDed instr:\n " << **AdIt << "\n";
Vikram S. Adve48762092002-04-25 04:34:15 +0000398 }
Chris Lattnerf726e772002-10-28 19:22:04 +0000399 InsertAfter(*AdIt, MBB, MII);
Vikram S. Adve48762092002-04-25 04:34:15 +0000400 }
401 }
402}
403
Brian Gaeke4efe3422003-09-21 01:23:46 +0000404bool PhyRegAlloc::markAllocatedRegs(MachineInstr* MInst)
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000405{
Vikram S. Adve814030a2003-07-29 19:49:21 +0000406 bool instrNeedsSpills = false;
407
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000408 // First, set the registers for operands in the machine instruction
409 // if a register was successfully allocated. Do this first because we
410 // will need to know which registers are already used by this instr'n.
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000411 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
412 {
413 MachineOperand& Op = MInst->getOperand(OpNum);
414 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
415 Op.getType() == MachineOperand::MO_CCRegister)
416 {
417 const Value *const Val = Op.getVRegValue();
Brian Gaeke4efe3422003-09-21 01:23:46 +0000418 if (const LiveRange* LR = LRI->getLiveRangeForValue(Val)) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000419 // Remember if any operand needs spilling
420 instrNeedsSpills |= LR->isMarkedForSpill();
421
422 // An operand may have a color whether or not it needs spilling
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000423 if (LR->hasColor())
424 MInst->SetRegForOperand(OpNum,
425 MRI.getUnifiedRegNum(LR->getRegClass()->getID(),
426 LR->getColor()));
Vikram S. Adve814030a2003-07-29 19:49:21 +0000427 }
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000428 }
429 } // for each operand
Vikram S. Adve814030a2003-07-29 19:49:21 +0000430
431 return instrNeedsSpills;
432}
433
434void PhyRegAlloc::updateInstruction(MachineBasicBlock::iterator& MII,
435 MachineBasicBlock &MBB)
436{
437 MachineInstr* MInst = *MII;
438 unsigned Opcode = MInst->getOpCode();
439
440 // Reset tmp stack positions so they can be reused for each machine instr.
Brian Gaeke4efe3422003-09-21 01:23:46 +0000441 MF->getInfo()->popAllTempValues();
Vikram S. Adve814030a2003-07-29 19:49:21 +0000442
443 // Mark the operands for which regs have been allocated.
Brian Gaeke4efe3422003-09-21 01:23:46 +0000444 bool instrNeedsSpills = markAllocatedRegs(*MII);
Vikram S. Adve814030a2003-07-29 19:49:21 +0000445
446#ifndef NDEBUG
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.
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000451 OperandsColoredMap[MInst] = true;
Vikram S. Adve814030a2003-07-29 19:49:21 +0000452#endif
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000453
Vikram S. Advebc001b22003-07-25 21:06:09 +0000454 // 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.
Vikram S. Advebc001b22003-07-25 21:06:09 +0000457 if (TM.getInstrInfo().isCall(Opcode)) {
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000458 AddedInstrns &AI = AddedInstrMap[MInst];
Vikram S. Adve814030a2003-07-29 19:49:21 +0000459 insertCallerSavingCode(AI.InstrnsBefore, AI.InstrnsAfter, MInst,
460 MBB.getBasicBlock());
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000461 }
Vikram S. Advebc001b22003-07-25 21:06:09 +0000462
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000463 // 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.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000466 if (instrNeedsSpills)
467 for (unsigned OpNum=0; OpNum < MInst->getNumOperands(); ++OpNum)
468 {
469 MachineOperand& Op = MInst->getOperand(OpNum);
470 if (Op.getType() == MachineOperand::MO_VirtualRegister ||
471 Op.getType() == MachineOperand::MO_CCRegister)
472 {
473 const Value* Val = Op.getVRegValue();
Brian Gaeke4efe3422003-09-21 01:23:46 +0000474 if (const LiveRange *LR = LRI->getLiveRangeForValue(Val))
Vikram S. Adve814030a2003-07-29 19:49:21 +0000475 if (LR->isMarkedForSpill())
476 insertCode4SpilledLR(LR, MII, MBB, OpNum);
477 }
478 } // for each operand
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000479}
480
481void PhyRegAlloc::updateMachineCode()
482{
Chris Lattner7e708292002-06-25 16:13:24 +0000483 // Insert any instructions needed at method entry
Brian Gaeke4efe3422003-09-21 01:23:46 +0000484 MachineBasicBlock::iterator MII = MF->front().begin();
485 PrependInstructions(AddedInstrAtEntry.InstrnsBefore, MF->front(), MII,
Chris Lattner7e708292002-06-25 16:13:24 +0000486 "At function entry: \n");
487 assert(AddedInstrAtEntry.InstrnsAfter.empty() &&
488 "InstrsAfter should be unnecessary since we are just inserting at "
489 "the function entry point here.");
Vikram S. Adve48762092002-04-25 04:34:15 +0000490
Brian Gaeke4efe3422003-09-21 01:23:46 +0000491 for (MachineFunction::iterator BBI = MF->begin(), BBE = MF->end();
Chris Lattner2fbfdcf2002-04-07 20:49:59 +0000492 BBI != BBE; ++BBI) {
Vikram S. Advecb202e32002-10-11 16:12:40 +0000493
Chris Lattnerf726e772002-10-28 19:22:04 +0000494 MachineBasicBlock &MBB = *BBI;
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000495
496 // Iterate over all machine instructions in BB and mark operands with
497 // their assigned registers or insert spill code, as appropriate.
498 // Also, fix operands of call/return instructions.
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000499 for (MachineBasicBlock::iterator MII = MBB.begin(); MII != MBB.end(); ++MII)
Vikram S. Adve814030a2003-07-29 19:49:21 +0000500 if (! TM.getInstrInfo().isDummyPhiInstr((*MII)->getOpCode()))
501 updateInstruction(MII, MBB);
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000502
503 // Now, move code out of delay slots of branches and returns if needed.
504 // (Also, move "after" code from calls to the last delay slot instruction.)
505 // Moving code out of delay slots is needed in 2 situations:
506 // (1) If this is a branch and it needs instructions inserted after it,
507 // move any existing instructions out of the delay slot so that the
508 // instructions can go into the delay slot. This only supports the
509 // case that #instrsAfter <= #delay slots.
510 //
511 // (2) If any instruction in the delay slot needs
512 // instructions inserted, move it out of the delay slot and before the
513 // branch because putting code before or after it would be VERY BAD!
514 //
515 // If the annul bit of the branch is set, neither of these is legal!
516 // If so, we need to handle spill differently but annulling is not yet used.
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000517 for (MachineBasicBlock::iterator MII = MBB.begin();
518 MII != MBB.end(); ++MII)
519 if (unsigned delaySlots =
520 TM.getInstrInfo().getNumDelaySlots((*MII)->getOpCode()))
521 {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000522 MachineInstr *MInst = *MII, *DelaySlotMI = *(MII+1);
523
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000524 // 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?
Vikram S. Adve814030a2003-07-29 19:49:21 +0000527 bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
528 TM.getInstrInfo().isReturn(MInst->getOpCode()));
529 bool cond1 = (isBranch &&
530 AddedInstrMap.count(MInst) &&
531 AddedInstrMap[MInst].InstrnsAfter.size() > 0);
532 bool cond2 = (AddedInstrMap.count(DelaySlotMI) &&
533 (AddedInstrMap[DelaySlotMI].InstrnsBefore.size() > 0 ||
534 AddedInstrMap[DelaySlotMI].InstrnsAfter.size() > 0));
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000535
536 if (cond1 || cond2)
537 {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000538 assert((MInst->getOpCodeFlags() & AnnulFlag) == 0 &&
539 "FIXME: Moving an annulled delay slot instruction!");
540 assert(delaySlots==1 &&
541 "InsertBefore does not yet handle >1 delay slots!");
542 InsertBefore(DelaySlotMI, MBB, MII); // MII pts back to branch
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000543
544 // In case (1), delete it and don't replace with anything!
545 // Otherwise (i.e., case (2) only) replace it with a NOP.
546 if (cond1) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000547 DeleteInstruction(MBB, ++MII); // MII now points to next inst.
548 --MII; // reset MII for ++MII of loop
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000549 }
Vikram S. Adve814030a2003-07-29 19:49:21 +0000550 else
551 SubstituteInPlace(BuildMI(TM.getInstrInfo().getNOPOpCode(),1),
552 MBB, MII+1); // replace with NOP
553
554 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000555 std::cerr << "\nRegAlloc: Moved instr. with added code: "
Vikram S. Adve814030a2003-07-29 19:49:21 +0000556 << *DelaySlotMI
557 << " out of delay slots of instr: " << *MInst;
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000558 }
559 }
Vikram S. Adve814030a2003-07-29 19:49:21 +0000560 else
561 // For non-branch instr with delay slots (probably a call), move
562 // InstrAfter to the instr. in the last delay slot.
563 move2DelayedInstr(*MII, *(MII+delaySlots));
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000564 }
565
566 // Finally iterate over all instructions in BB and insert before/after
Vikram S. Advebc001b22003-07-25 21:06:09 +0000567 for (MachineBasicBlock::iterator MII=MBB.begin(); MII != MBB.end(); ++MII) {
Vikram S. Adve48762092002-04-25 04:34:15 +0000568 MachineInstr *MInst = *MII;
Vikram S. Advebc001b22003-07-25 21:06:09 +0000569
Ruchira Sasanka65480b72001-11-10 21:21:36 +0000570 // do not process Phis
Vikram S. Advebc001b22003-07-25 21:06:09 +0000571 if (TM.getInstrInfo().isDummyPhiInstr(MInst->getOpCode()))
Ruchira Sasanka65480b72001-11-10 21:21:36 +0000572 continue;
573
Vikram S. Advebc001b22003-07-25 21:06:09 +0000574 // if there are any added instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000575 if (AddedInstrMap.count(MInst)) {
Vikram S. Advebc001b22003-07-25 21:06:09 +0000576 AddedInstrns &CallAI = AddedInstrMap[MInst];
577
578#ifndef NDEBUG
Vikram S. Adve814030a2003-07-29 19:49:21 +0000579 bool isBranch = (TM.getInstrInfo().isBranch(MInst->getOpCode()) ||
580 TM.getInstrInfo().isReturn(MInst->getOpCode()));
581 assert((!isBranch ||
582 AddedInstrMap[MInst].InstrnsAfter.size() <=
583 TM.getInstrInfo().getNumDelaySlots(MInst->getOpCode())) &&
584 "Cannot put more than #delaySlots instrns after "
585 "branch or return! Need to handle temps differently.");
586#endif
587
588#ifndef NDEBUG
Vikram S. Advebc001b22003-07-25 21:06:09 +0000589 // Temporary sanity checking code to detect whether the same machine
590 // instruction is ever inserted twice before/after a call.
591 // I suspect this is happening but am not sure. --Vikram, 7/1/03.
Vikram S. Advebc001b22003-07-25 21:06:09 +0000592 std::set<const MachineInstr*> instrsSeen;
593 for (int i = 0, N = CallAI.InstrnsBefore.size(); i < N; ++i) {
594 assert(instrsSeen.count(CallAI.InstrnsBefore[i]) == 0 &&
595 "Duplicate machine instruction in InstrnsBefore!");
596 instrsSeen.insert(CallAI.InstrnsBefore[i]);
597 }
598 for (int i = 0, N = CallAI.InstrnsAfter.size(); i < N; ++i) {
599 assert(instrsSeen.count(CallAI.InstrnsAfter[i]) == 0 &&
600 "Duplicate machine instruction in InstrnsBefore/After!");
601 instrsSeen.insert(CallAI.InstrnsAfter[i]);
602 }
603#endif
604
605 // Now add the instructions before/after this MI.
606 // We do this here to ensure that spill for an instruction is inserted
607 // as close as possible to an instruction (see above insertCode4Spill)
Vikram S. Advebc001b22003-07-25 21:06:09 +0000608 if (! CallAI.InstrnsBefore.empty())
609 PrependInstructions(CallAI.InstrnsBefore, MBB, MII,"");
610
611 if (! CallAI.InstrnsAfter.empty())
612 AppendInstructions(CallAI.InstrnsAfter, MBB, MII,"");
613
614 } // if there are any added instructions
Ruchira Sasankac4d4b762001-10-16 01:23:19 +0000615 } // for each machine instruction
Ruchira Sasanka0931a012001-09-15 19:06:58 +0000616 }
617}
618
619
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000620//----------------------------------------------------------------------------
621// This method inserts spill code for AN operand whose LR was spilled.
622// This method may be called several times for a single machine instruction
623// if it contains many spilled operands. Each time it is called, it finds
624// a register which is not live at that instruction and also which is not
625// used by other spilled operands of the same instruction. Then it uses
Misha Brukman37f92e22003-09-11 22:34:13 +0000626// this register temporarily to accommodate the spilled value.
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000627//----------------------------------------------------------------------------
Vikram S. Advebc001b22003-07-25 21:06:09 +0000628
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000629void PhyRegAlloc::insertCode4SpilledLR(const LiveRange *LR,
Vikram S. Adve814030a2003-07-29 19:49:21 +0000630 MachineBasicBlock::iterator& MII,
631 MachineBasicBlock &MBB,
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000632 const unsigned OpNum) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000633 MachineInstr *MInst = *MII;
634 const BasicBlock *BB = MBB.getBasicBlock();
635
Vikram S. Advead9c9782002-09-28 17:02:40 +0000636 assert((! TM.getInstrInfo().isCall(MInst->getOpCode()) || OpNum == 0) &&
637 "Outgoing arg of a call must be handled elsewhere (func arg ok)");
638 assert(! TM.getInstrInfo().isReturn(MInst->getOpCode()) &&
639 "Return value of a ret must be handled elsewhere");
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000640
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000641 MachineOperand& Op = MInst->getOperand(OpNum);
Vikram S. Adve5f2180c2003-05-27 00:05:23 +0000642 bool isDef = Op.opIsDefOnly();
643 bool isDefAndUse = Op.opIsDefAndUse();
Vikram S. Advebc001b22003-07-25 21:06:09 +0000644 unsigned RegType = MRI.getRegTypeForLR(LR);
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000645 int SpillOff = LR->getSpillOffFromFP();
646 RegClass *RC = LR->getRegClass();
Vikram S. Adve814030a2003-07-29 19:49:21 +0000647
648 // Get the live-variable set to find registers free before this instr.
Vikram S. Advefeb32982003-08-12 22:22:24 +0000649 const ValueSet &LVSetBef = LVI->getLiveVarSetBeforeMInst(MInst, BB);
650
651#ifndef NDEBUG
652 // If this instr. is in the delay slot of a branch or return, we need to
653 // include all live variables before that branch or return -- we don't want to
654 // trample those! Verify that the set is included in the LV set before MInst.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000655 if (MII != MBB.begin()) {
656 MachineInstr *PredMI = *(MII-1);
Vikram S. Advefeb32982003-08-12 22:22:24 +0000657 if (unsigned DS = TM.getInstrInfo().getNumDelaySlots(PredMI->getOpCode()))
658 assert(set_difference(LVI->getLiveVarSetBeforeMInst(PredMI), LVSetBef)
659 .empty() && "Live-var set before branch should be included in "
660 "live-var set of each delay slot instruction!");
Vikram S. Adve814030a2003-07-29 19:49:21 +0000661 }
Vikram S. Advefeb32982003-08-12 22:22:24 +0000662#endif
Vikram S. Adve00521d72001-11-12 23:26:35 +0000663
Brian Gaeke4efe3422003-09-21 01:23:46 +0000664 MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType) );
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000665
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000666 std::vector<MachineInstr*> MIBef, MIAft;
667 std::vector<MachineInstr*> AdIMid;
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000668
Vikram S. Adve3bf08922003-07-10 19:42:55 +0000669 // Choose a register to hold the spilled value, if one was not preallocated.
670 // This may insert code before and after MInst to free up the value. If so,
671 // this code should be first/last in the spill sequence before/after MInst.
672 int TmpRegU=(LR->hasColor()
673 ? MRI.getUnifiedRegNum(LR->getRegClass()->getID(),LR->getColor())
674 : getUsableUniRegAtMI(RegType, &LVSetBef, MInst, MIBef,MIAft));
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000675
Vikram S. Advef5af6362002-07-08 23:15:32 +0000676 // Set the operand first so that it this register does not get used
677 // as a scratch register for later calls to getUsableUniRegAtMI below
678 MInst->SetRegForOperand(OpNum, TmpRegU);
679
680 // get the added instructions for this instruction
Chris Lattner0b0ffa02002-04-09 05:13:04 +0000681 AddedInstrns &AI = AddedInstrMap[MInst];
Vikram S. Advef5af6362002-07-08 23:15:32 +0000682
683 // We may need a scratch register to copy the spilled value to/from memory.
684 // This may itself have to insert code to free up a scratch register.
685 // Any such code should go before (after) the spill code for a load (store).
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000686 // The scratch reg is not marked as used because it is only used
687 // for the copy and not used across MInst.
Vikram S. Advef5af6362002-07-08 23:15:32 +0000688 int scratchRegType = -1;
689 int scratchReg = -1;
690 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
691 {
Chris Lattner27a08932002-10-22 23:16:21 +0000692 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
693 MInst, MIBef, MIAft);
Vikram S. Advef5af6362002-07-08 23:15:32 +0000694 assert(scratchReg != MRI.getInvalidRegNum());
Vikram S. Advef5af6362002-07-08 23:15:32 +0000695 }
696
697 if (!isDef || isDefAndUse) {
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000698 // for a USE, we have to load the value of LR from stack to a TmpReg
699 // and use the TmpReg as one operand of instruction
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000700
Vikram S. Advef5af6362002-07-08 23:15:32 +0000701 // actual loading instruction(s)
Vikram S. Adve814030a2003-07-29 19:49:21 +0000702 MRI.cpMem2RegMI(AdIMid, MRI.getFramePointer(), SpillOff, TmpRegU,
703 RegType, scratchReg);
Ruchira Sasanka226f1f02001-11-08 19:11:30 +0000704
Vikram S. Advef5af6362002-07-08 23:15:32 +0000705 // the actual load should be after the instructions to free up TmpRegU
706 MIBef.insert(MIBef.end(), AdIMid.begin(), AdIMid.end());
707 AdIMid.clear();
708 }
709
Vikram S. Adve3bf08922003-07-10 19:42:55 +0000710 if (isDef || isDefAndUse) { // if this is a Def
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000711 // for a DEF, we have to store the value produced by this instruction
712 // on the stack position allocated for this LR
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000713
Vikram S. Advef5af6362002-07-08 23:15:32 +0000714 // actual storing instruction(s)
Vikram S. Adve814030a2003-07-29 19:49:21 +0000715 MRI.cpReg2MemMI(AdIMid, TmpRegU, MRI.getFramePointer(), SpillOff,
716 RegType, scratchReg);
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000717
Vikram S. Advef5af6362002-07-08 23:15:32 +0000718 MIAft.insert(MIAft.begin(), AdIMid.begin(), AdIMid.end());
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000719 } // if !DEF
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000720
Vikram S. Advef5af6362002-07-08 23:15:32 +0000721 // Finally, insert the entire spill code sequences before/after MInst
722 AI.InstrnsBefore.insert(AI.InstrnsBefore.end(), MIBef.begin(), MIBef.end());
723 AI.InstrnsAfter.insert(AI.InstrnsAfter.begin(), MIAft.begin(), MIAft.end());
724
Chris Lattner7e708292002-06-25 16:13:24 +0000725 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +0000726 std::cerr << "\nFor Inst:\n " << *MInst;
727 std::cerr << "SPILLED LR# " << LR->getUserIGNode()->getIndex();
728 std::cerr << "; added Instructions:";
Anand Shuklad58290e2002-07-09 19:18:56 +0000729 for_each(MIBef.begin(), MIBef.end(), std::mem_fun(&MachineInstr::dump));
730 for_each(MIAft.begin(), MIAft.end(), std::mem_fun(&MachineInstr::dump));
Chris Lattner7e708292002-06-25 16:13:24 +0000731 }
Ruchira Sasanka5a61d852001-11-08 16:43:25 +0000732}
733
734
Vikram S. Adve814030a2003-07-29 19:49:21 +0000735//----------------------------------------------------------------------------
Misha Brukman37f92e22003-09-11 22:34:13 +0000736// This method inserts caller saving/restoring instructions before/after
Vikram S. Adve814030a2003-07-29 19:49:21 +0000737// a call machine instruction. The caller saving/restoring instructions are
738// inserted like:
739// ** caller saving instructions
740// other instructions inserted for the call by ColorCallArg
741// CALL instruction
742// other instructions inserted for the call ColorCallArg
743// ** caller restoring instructions
744//----------------------------------------------------------------------------
745
746void
747PhyRegAlloc::insertCallerSavingCode(std::vector<MachineInstr*> &instrnsBefore,
748 std::vector<MachineInstr*> &instrnsAfter,
749 MachineInstr *CallMI,
750 const BasicBlock *BB)
751{
752 assert(TM.getInstrInfo().isCall(CallMI->getOpCode()));
753
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000754 // hash set to record which registers were saved/restored
Vikram S. Adve814030a2003-07-29 19:49:21 +0000755 hash_set<unsigned> PushedRegSet;
756
757 CallArgsDescriptor* argDesc = CallArgsDescriptor::get(CallMI);
758
759 // if the call is to a instrumentation function, do not insert save and
760 // restore instructions the instrumentation function takes care of save
761 // restore for volatile regs.
762 //
763 // FIXME: this should be made general, not specific to the reoptimizer!
Vikram S. Adve814030a2003-07-29 19:49:21 +0000764 const Function *Callee = argDesc->getCallInst()->getCalledFunction();
765 bool isLLVMFirstTrigger = Callee && Callee->getName() == "llvm_first_trigger";
766
767 // Now check if the call has a return value (using argDesc) and if so,
768 // find the LR of the TmpInstruction representing the return value register.
769 // (using the last or second-last *implicit operand* of the call MI).
770 // Insert it to to the PushedRegSet since we must not save that register
771 // and restore it after the call.
772 // We do this because, we look at the LV set *after* the instruction
773 // to determine, which LRs must be saved across calls. The return value
774 // of the call is live in this set - but we must not save/restore it.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000775 if (const Value *origRetVal = argDesc->getReturnValue()) {
776 unsigned retValRefNum = (CallMI->getNumImplicitRefs() -
777 (argDesc->getIndirectFuncPtr()? 1 : 2));
778 const TmpInstruction* tmpRetVal =
779 cast<TmpInstruction>(CallMI->getImplicitRef(retValRefNum));
780 assert(tmpRetVal->getOperand(0) == origRetVal &&
781 tmpRetVal->getType() == origRetVal->getType() &&
782 "Wrong implicit ref?");
Brian Gaeke4efe3422003-09-21 01:23:46 +0000783 LiveRange *RetValLR = LRI->getLiveRangeForValue(tmpRetVal);
Vikram S. Adve814030a2003-07-29 19:49:21 +0000784 assert(RetValLR && "No LR for RetValue of call");
785
786 if (! RetValLR->isMarkedForSpill())
787 PushedRegSet.insert(MRI.getUnifiedRegNum(RetValLR->getRegClassID(),
788 RetValLR->getColor()));
789 }
790
791 const ValueSet &LVSetAft = LVI->getLiveVarSetAfterMInst(CallMI, BB);
792 ValueSet::const_iterator LIt = LVSetAft.begin();
793
794 // for each live var in live variable set after machine inst
795 for( ; LIt != LVSetAft.end(); ++LIt) {
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000796 // get the live range corresponding to live var
Brian Gaeke4efe3422003-09-21 01:23:46 +0000797 LiveRange *const LR = LRI->getLiveRangeForValue(*LIt);
Vikram S. Adve814030a2003-07-29 19:49:21 +0000798
799 // LR can be null if it is a const since a const
800 // doesn't have a dominating def - see Assumptions above
801 if( LR ) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000802 if(! LR->isMarkedForSpill()) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000803 assert(LR->hasColor() && "LR is neither spilled nor colored?");
804 unsigned RCID = LR->getRegClassID();
805 unsigned Color = LR->getColor();
806
807 if (MRI.isRegVolatile(RCID, Color) ) {
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000808 // if this is a call to the first-level reoptimizer
809 // instrumentation entry point, and the register is not
810 // modified by call, don't save and restore it.
Vikram S. Adve814030a2003-07-29 19:49:21 +0000811 if (isLLVMFirstTrigger && !MRI.modifiedByCall(RCID, Color))
812 continue;
813
814 // if the value is in both LV sets (i.e., live before and after
815 // the call machine instruction)
Vikram S. Adve814030a2003-07-29 19:49:21 +0000816 unsigned Reg = MRI.getUnifiedRegNum(RCID, Color);
817
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000818 // if we haven't already pushed this register...
Vikram S. Adve814030a2003-07-29 19:49:21 +0000819 if( PushedRegSet.find(Reg) == PushedRegSet.end() ) {
Vikram S. Adve814030a2003-07-29 19:49:21 +0000820 unsigned RegType = MRI.getRegTypeForLR(LR);
821
822 // Now get two instructions - to push on stack and pop from stack
823 // and add them to InstrnsBefore and InstrnsAfter of the
824 // call instruction
Vikram S. Adve814030a2003-07-29 19:49:21 +0000825 int StackOff =
Brian Gaeke4efe3422003-09-21 01:23:46 +0000826 MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
Vikram S. Adve814030a2003-07-29 19:49:21 +0000827
828 //---- Insert code for pushing the reg on stack ----------
829
830 std::vector<MachineInstr*> AdIBef, AdIAft;
831
832 // We may need a scratch register to copy the saved value
833 // to/from memory. This may itself have to insert code to
834 // free up a scratch register. Any such code should go before
835 // the save code. The scratch register, if any, is by default
836 // temporary and not "used" by the instruction unless the
837 // copy code itself decides to keep the value in the scratch reg.
838 int scratchRegType = -1;
839 int scratchReg = -1;
840 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
841 { // Find a register not live in the LVSet before CallMI
842 const ValueSet &LVSetBef =
843 LVI->getLiveVarSetBeforeMInst(CallMI, BB);
844 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetBef,
845 CallMI, AdIBef, AdIAft);
846 assert(scratchReg != MRI.getInvalidRegNum());
847 }
848
849 if (AdIBef.size() > 0)
850 instrnsBefore.insert(instrnsBefore.end(),
851 AdIBef.begin(), AdIBef.end());
852
853 MRI.cpReg2MemMI(instrnsBefore, Reg, MRI.getFramePointer(),
854 StackOff, RegType, scratchReg);
855
856 if (AdIAft.size() > 0)
857 instrnsBefore.insert(instrnsBefore.end(),
858 AdIAft.begin(), AdIAft.end());
859
860 //---- Insert code for popping the reg from the stack ----------
Vikram S. Adve814030a2003-07-29 19:49:21 +0000861 AdIBef.clear();
862 AdIAft.clear();
863
864 // We may need a scratch register to copy the saved value
865 // from memory. This may itself have to insert code to
866 // free up a scratch register. Any such code should go
867 // after the save code. As above, scratch is not marked "used".
Vikram S. Adve814030a2003-07-29 19:49:21 +0000868 scratchRegType = -1;
869 scratchReg = -1;
870 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
871 { // Find a register not live in the LVSet after CallMI
872 scratchReg = getUsableUniRegAtMI(scratchRegType, &LVSetAft,
873 CallMI, AdIBef, AdIAft);
874 assert(scratchReg != MRI.getInvalidRegNum());
875 }
876
877 if (AdIBef.size() > 0)
878 instrnsAfter.insert(instrnsAfter.end(),
879 AdIBef.begin(), AdIBef.end());
880
881 MRI.cpMem2RegMI(instrnsAfter, MRI.getFramePointer(), StackOff,
882 Reg, RegType, scratchReg);
883
884 if (AdIAft.size() > 0)
885 instrnsAfter.insert(instrnsAfter.end(),
886 AdIAft.begin(), AdIAft.end());
887
888 PushedRegSet.insert(Reg);
889
890 if(DEBUG_RA) {
891 std::cerr << "\nFor call inst:" << *CallMI;
892 std::cerr << " -inserted caller saving instrs: Before:\n\t ";
893 for_each(instrnsBefore.begin(), instrnsBefore.end(),
894 std::mem_fun(&MachineInstr::dump));
895 std::cerr << " -and After:\n\t ";
896 for_each(instrnsAfter.begin(), instrnsAfter.end(),
897 std::mem_fun(&MachineInstr::dump));
898 }
899 } // if not already pushed
Vikram S. Adve814030a2003-07-29 19:49:21 +0000900 } // if LR has a volatile color
Vikram S. Adve814030a2003-07-29 19:49:21 +0000901 } // if LR has color
Vikram S. Adve814030a2003-07-29 19:49:21 +0000902 } // if there is a LR for Var
Vikram S. Adve814030a2003-07-29 19:49:21 +0000903 } // for each value in the LV set after instruction
904}
905
906
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000907//----------------------------------------------------------------------------
908// We can use the following method to get a temporary register to be used
909// BEFORE any given machine instruction. If there is a register available,
910// this method will simply return that register and set MIBef = MIAft = NULL.
911// Otherwise, it will return a register and MIAft and MIBef will contain
912// two instructions used to free up this returned register.
Ruchira Sasanka80b1a1a2001-11-03 20:41:22 +0000913// Returned register number is the UNIFIED register number
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000914//----------------------------------------------------------------------------
915
Vikram S. Advef5af6362002-07-08 23:15:32 +0000916int PhyRegAlloc::getUsableUniRegAtMI(const int RegType,
917 const ValueSet *LVSetBef,
918 MachineInstr *MInst,
919 std::vector<MachineInstr*>& MIBef,
920 std::vector<MachineInstr*>& MIAft) {
Chris Lattner133f0792002-10-28 04:45:29 +0000921 RegClass* RC = getRegClassByID(MRI.getRegClassIDOfRegType(RegType));
Vikram S. Advef5af6362002-07-08 23:15:32 +0000922
Vikram S. Advebc001b22003-07-25 21:06:09 +0000923 int RegU = getUnusedUniRegAtMI(RC, RegType, MInst, LVSetBef);
Vikram S. Advef5af6362002-07-08 23:15:32 +0000924
925 if (RegU == -1) {
Ruchira Sasanka80b1a1a2001-11-03 20:41:22 +0000926 // we couldn't find an unused register. Generate code to free up a reg by
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000927 // saving it on stack and restoring after the instruction
Vikram S. Advef5af6362002-07-08 23:15:32 +0000928
Brian Gaeke4efe3422003-09-21 01:23:46 +0000929 int TmpOff = MF->getInfo()->pushTempValue(MRI.getSpilledRegSize(RegType));
Vikram S. Adve12af1642001-11-08 04:48:50 +0000930
Vikram S. Advebc001b22003-07-25 21:06:09 +0000931 RegU = getUniRegNotUsedByThisInst(RC, RegType, MInst);
Vikram S. Advedabb41d2002-05-19 15:29:31 +0000932
Vikram S. Advef5af6362002-07-08 23:15:32 +0000933 // Check if we need a scratch register to copy this register to memory.
934 int scratchRegType = -1;
935 if (MRI.regTypeNeedsScratchReg(RegType, scratchRegType))
936 {
Chris Lattner133f0792002-10-28 04:45:29 +0000937 int scratchReg = getUsableUniRegAtMI(scratchRegType, LVSetBef,
938 MInst, MIBef, MIAft);
Vikram S. Advef5af6362002-07-08 23:15:32 +0000939 assert(scratchReg != MRI.getInvalidRegNum());
940
941 // We may as well hold the value in the scratch register instead
942 // of copying it to memory and back. But we have to mark the
943 // register as used by this instruction, so it does not get used
944 // as a scratch reg. by another operand or anyone else.
Chris Lattner3fd1f5b2003-08-05 22:11:13 +0000945 ScratchRegsUsed.insert(std::make_pair(MInst, scratchReg));
Vikram S. Advef5af6362002-07-08 23:15:32 +0000946 MRI.cpReg2RegMI(MIBef, RegU, scratchReg, RegType);
947 MRI.cpReg2RegMI(MIAft, scratchReg, RegU, RegType);
948 }
949 else
950 { // the register can be copied directly to/from memory so do it.
951 MRI.cpReg2MemMI(MIBef, RegU, MRI.getFramePointer(), TmpOff, RegType);
952 MRI.cpMem2RegMI(MIAft, MRI.getFramePointer(), TmpOff, RegU, RegType);
953 }
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000954 }
Vikram S. Advef5af6362002-07-08 23:15:32 +0000955
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000956 return RegU;
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000957}
958
Vikram S. Adve814030a2003-07-29 19:49:21 +0000959
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000960//----------------------------------------------------------------------------
Vikram S. Adve814030a2003-07-29 19:49:21 +0000961// This method is called to get a new unused register that can be used
Misha Brukman37f92e22003-09-11 22:34:13 +0000962// to accommodate a temporary value. This method may be called several times
Vikram S. Adve814030a2003-07-29 19:49:21 +0000963// for a single machine instruction. Each time it is called, it finds a
964// register which is not live at that instruction and also which is not used
965// by other spilled operands of the same instruction. Return register number
966// is relative to the register class, NOT the unified number.
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000967//----------------------------------------------------------------------------
Vikram S. Adved0d06ad2003-05-31 07:32:01 +0000968
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +0000969int PhyRegAlloc::getUnusedUniRegAtMI(RegClass *RC,
Vikram S. Advebc001b22003-07-25 21:06:09 +0000970 const int RegType,
Vikram S. Adve814030a2003-07-29 19:49:21 +0000971 const MachineInstr *MInst,
972 const ValueSet* LVSetBef) {
Vikram S. Advebc001b22003-07-25 21:06:09 +0000973 RC->clearColorsUsed(); // Reset array
Vikram S. Adve814030a2003-07-29 19:49:21 +0000974
975 if (LVSetBef == NULL) {
976 LVSetBef = &LVI->getLiveVarSetBeforeMInst(MInst);
977 assert(LVSetBef != NULL && "Unable to get live-var set before MInst?");
978 }
979
Chris Lattner296b7732002-02-05 02:52:05 +0000980 ValueSet::const_iterator LIt = LVSetBef->begin();
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000981
982 // for each live var in live variable set after machine inst
Chris Lattner7e708292002-06-25 16:13:24 +0000983 for ( ; LIt != LVSetBef->end(); ++LIt) {
Brian Gaeke43ce8fe2003-09-21 02:24:09 +0000984 // Get the live range corresponding to live var, and its RegClass
Brian Gaeke4efe3422003-09-21 01:23:46 +0000985 LiveRange *const LRofLV = LRI->getLiveRangeForValue(*LIt );
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000986
987 // LR can be null if it is a const since a const
988 // doesn't have a dominating def - see Assumptions above
Vikram S. Advebc001b22003-07-25 21:06:09 +0000989 if (LRofLV && LRofLV->getRegClass() == RC && LRofLV->hasColor())
990 RC->markColorsUsed(LRofLV->getColor(),
991 MRI.getRegTypeForLR(LRofLV), RegType);
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000992 }
993
994 // It is possible that one operand of this MInst was already spilled
995 // and it received some register temporarily. If that's the case,
996 // it is recorded in machine operand. We must skip such registers.
Vikram S. Advebc001b22003-07-25 21:06:09 +0000997 setRelRegsUsedByThisInst(RC, RegType, MInst);
Ruchira Sasanka174bded2001-10-28 18:12:02 +0000998
Vikram S. Advebc001b22003-07-25 21:06:09 +0000999 int unusedReg = RC->getUnusedColor(RegType); // find first unused color
1000 if (unusedReg >= 0)
1001 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
1002
Chris Lattner85c54652002-05-23 15:50:03 +00001003 return -1;
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001004}
1005
1006
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001007//----------------------------------------------------------------------------
1008// Get any other register in a register class, other than what is used
1009// by operands of a machine instruction. Returns the unified reg number.
1010//----------------------------------------------------------------------------
Brian Gaeke43ce8fe2003-09-21 02:24:09 +00001011
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001012int PhyRegAlloc::getUniRegNotUsedByThisInst(RegClass *RC,
Vikram S. Advebc001b22003-07-25 21:06:09 +00001013 const int RegType,
Chris Lattner85c54652002-05-23 15:50:03 +00001014 const MachineInstr *MInst) {
Vikram S. Advebc001b22003-07-25 21:06:09 +00001015 RC->clearColorsUsed();
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001016
Vikram S. Advebc001b22003-07-25 21:06:09 +00001017 setRelRegsUsedByThisInst(RC, RegType, MInst);
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001018
Vikram S. Advebc001b22003-07-25 21:06:09 +00001019 // find the first unused color
1020 int unusedReg = RC->getUnusedColor(RegType);
1021 assert(unusedReg >= 0 &&
1022 "FATAL: No free register could be found in reg class!!");
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001023
Vikram S. Advebc001b22003-07-25 21:06:09 +00001024 return MRI.getUnifiedRegNum(RC->getID(), unusedReg);
Ruchira Sasankaba9d5db2001-11-15 20:23:19 +00001025}
1026
1027
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001028//----------------------------------------------------------------------------
1029// This method modifies the IsColorUsedArr of the register class passed to it.
1030// It sets the bits corresponding to the registers used by this machine
Ruchira Sasankaf6dfca12001-11-15 15:00:53 +00001031// instructions. Both explicit and implicit operands are set.
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001032//----------------------------------------------------------------------------
Vikram S. Advebc001b22003-07-25 21:06:09 +00001033
Chris Lattner3bed95b2003-08-05 21:55:58 +00001034static void markRegisterUsed(int RegNo, RegClass *RC, int RegType,
1035 const TargetRegInfo &TRI) {
1036 unsigned classId = 0;
1037 int classRegNum = TRI.getClassRegNum(RegNo, classId);
1038 if (RC->getID() == classId)
1039 RC->markColorsUsed(classRegNum, RegType, RegType);
1040}
1041
1042void PhyRegAlloc::setRelRegsUsedByThisInst(RegClass *RC, int RegType,
1043 const MachineInstr *MI)
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001044{
Chris Lattner3bed95b2003-08-05 21:55:58 +00001045 assert(OperandsColoredMap[MI] == true &&
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001046 "Illegal to call setRelRegsUsedByThisInst() until colored operands "
1047 "are marked for an instruction.");
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001048
Chris Lattner3bed95b2003-08-05 21:55:58 +00001049 // Add the registers already marked as used by the instruction.
1050 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
1051 if (MI->getOperand(i).hasAllocatedReg())
1052 markRegisterUsed(MI->getOperand(i).getAllocatedRegNum(), RC, RegType,MRI);
1053
1054 for (unsigned i = 0, e = MI->getNumImplicitRefs(); i != e; ++i)
1055 if (MI->getImplicitOp(i).hasAllocatedReg())
1056 markRegisterUsed(MI->getImplicitOp(i).getAllocatedRegNum(), RC,
1057 RegType,MRI);
1058
Chris Lattner3fd1f5b2003-08-05 22:11:13 +00001059 // Add all of the scratch registers that are used to save values across the
1060 // instruction (e.g., for saving state register values).
1061 std::pair<ScratchRegsUsedTy::iterator, ScratchRegsUsedTy::iterator>
1062 IR = ScratchRegsUsed.equal_range(MI);
1063 for (ScratchRegsUsedTy::iterator I = IR.first; I != IR.second; ++I)
1064 markRegisterUsed(I->second, RC, RegType, MRI);
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001065
Vikram S. Advef5af6362002-07-08 23:15:32 +00001066 // If there are implicit references, mark their allocated regs as well
Chris Lattner3bed95b2003-08-05 21:55:58 +00001067 for (unsigned z=0; z < MI->getNumImplicitRefs(); z++)
Vikram S. Advef5af6362002-07-08 23:15:32 +00001068 if (const LiveRange*
Brian Gaeke4efe3422003-09-21 01:23:46 +00001069 LRofImpRef = LRI->getLiveRangeForValue(MI->getImplicitRef(z)))
Vikram S. Advef5af6362002-07-08 23:15:32 +00001070 if (LRofImpRef->hasColor())
1071 // this implicit reference is in a LR that received a color
Vikram S. Advebc001b22003-07-25 21:06:09 +00001072 RC->markColorsUsed(LRofImpRef->getColor(),
1073 MRI.getRegTypeForLR(LRofImpRef), RegType);
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001074}
1075
1076
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001077//----------------------------------------------------------------------------
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001078// If there are delay slots for an instruction, the instructions
1079// added after it must really go after the delayed instruction(s).
1080// So, we move the InstrAfter of that instruction to the
1081// corresponding delayed instruction using the following method.
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001082//----------------------------------------------------------------------------
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001083
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001084void PhyRegAlloc::move2DelayedInstr(const MachineInstr *OrigMI,
1085 const MachineInstr *DelayedMI)
1086{
Vikram S. Advefeb32982003-08-12 22:22:24 +00001087 // "added after" instructions of the original instr
1088 std::vector<MachineInstr *> &OrigAft = AddedInstrMap[OrigMI].InstrnsAfter;
1089
1090 if (DEBUG_RA && OrigAft.size() > 0) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001091 std::cerr << "\nRegAlloc: Moved InstrnsAfter for: " << *OrigMI;
1092 std::cerr << " to last delay slot instrn: " << *DelayedMI;
Vikram S. Adve814030a2003-07-29 19:49:21 +00001093 }
1094
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001095 // "added after" instructions of the delayed instr
Vikram S. Adve814030a2003-07-29 19:49:21 +00001096 std::vector<MachineInstr *> &DelayedAft=AddedInstrMap[DelayedMI].InstrnsAfter;
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001097
1098 // go thru all the "added after instructions" of the original instruction
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001099 // and append them to the "added after instructions" of the delayed
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001100 // instructions
Chris Lattner697954c2002-01-20 22:54:45 +00001101 DelayedAft.insert(DelayedAft.end(), OrigAft.begin(), OrigAft.end());
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001102
1103 // empty the "added after instructions" of the original instruction
1104 OrigAft.clear();
Ruchira Sasanka251d8db2001-10-23 21:38:00 +00001105}
Ruchira Sasanka0931a012001-09-15 19:06:58 +00001106
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001107
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001108void PhyRegAlloc::colorIncomingArgs()
1109{
Brian Gaeke4efe3422003-09-21 01:23:46 +00001110 MRI.colorMethodArgs(Fn, *LRI, AddedInstrAtEntry.InstrnsBefore,
Vikram S. Adve814030a2003-07-29 19:49:21 +00001111 AddedInstrAtEntry.InstrnsAfter);
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001112}
1113
Ruchira Sasankae727f852001-09-18 22:43:57 +00001114
1115//----------------------------------------------------------------------------
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001116// This method calls setSugColorUsable method of each live range. This
1117// will determine whether the suggested color of LR is really usable.
1118// A suggested color is not usable when the suggested color is volatile
1119// AND when there are call interferences
1120//----------------------------------------------------------------------------
1121
1122void PhyRegAlloc::markUnusableSugColors()
1123{
Brian Gaeke4efe3422003-09-21 01:23:46 +00001124 LiveRangeMapType::const_iterator HMI = (LRI->getLiveRangeMap())->begin();
1125 LiveRangeMapType::const_iterator HMIEnd = (LRI->getLiveRangeMap())->end();
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001126
Brian Gaeke43ce8fe2003-09-21 02:24:09 +00001127 for (; HMI != HMIEnd ; ++HMI ) {
1128 if (HMI->first) {
1129 LiveRange *L = HMI->second; // get the LiveRange
1130 if (L) {
1131 if (L->hasSuggestedColor()) {
1132 int RCID = L->getRegClass()->getID();
1133 if (MRI.isRegVolatile( RCID, L->getSuggestedColor()) &&
1134 L->isCallInterference() )
1135 L->setSuggestedColorUsable( false );
1136 else
1137 L->setSuggestedColorUsable( true );
1138 }
1139 } // if L->hasSuggestedColor()
1140 }
1141 } // for all LR's in hash map
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001142}
1143
1144
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001145//----------------------------------------------------------------------------
1146// The following method will set the stack offsets of the live ranges that
Misha Brukman37f92e22003-09-11 22:34:13 +00001147// are decided to be spilled. This must be called just after coloring the
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001148// LRs using the graph coloring algo. For each live range that is spilled,
1149// this method allocate a new spill position on the stack.
1150//----------------------------------------------------------------------------
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001151
Chris Lattner37730942002-02-05 03:52:29 +00001152void PhyRegAlloc::allocateStackSpace4SpilledLRs() {
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001153 if (DEBUG_RA) std::cerr << "\nSetting LR stack offsets for spills...\n";
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001154
Brian Gaeke4efe3422003-09-21 01:23:46 +00001155 LiveRangeMapType::const_iterator HMI = LRI->getLiveRangeMap()->begin();
1156 LiveRangeMapType::const_iterator HMIEnd = LRI->getLiveRangeMap()->end();
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001157
Chris Lattner7e708292002-06-25 16:13:24 +00001158 for ( ; HMI != HMIEnd ; ++HMI) {
Chris Lattner37730942002-02-05 03:52:29 +00001159 if (HMI->first && HMI->second) {
Vikram S. Adve3bf08922003-07-10 19:42:55 +00001160 LiveRange *L = HMI->second; // get the LiveRange
1161 if (L->isMarkedForSpill()) { // NOTE: allocating size of long Type **
Brian Gaeke4efe3422003-09-21 01:23:46 +00001162 int stackOffset = MF->getInfo()->allocateSpilledValue(Type::LongTy);
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001163 L->setSpillOffFromFP(stackOffset);
1164 if (DEBUG_RA)
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001165 std::cerr << " LR# " << L->getUserIGNode()->getIndex()
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001166 << ": stack-offset = " << stackOffset << "\n";
1167 }
Chris Lattner37730942002-02-05 03:52:29 +00001168 }
1169 } // for all LR's in hash map
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001170}
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001171
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001172//----------------------------------------------------------------------------
Brian Gaeke305f02d2003-09-16 15:38:05 +00001173// The entry point to Register Allocation
Ruchira Sasankae727f852001-09-18 22:43:57 +00001174//----------------------------------------------------------------------------
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001175
Brian Gaeke4efe3422003-09-21 01:23:46 +00001176bool PhyRegAlloc::runOnFunction (Function &F) {
1177 if (DEBUG_RA)
1178 std::cerr << "\n********* Function "<< F.getName () << " ***********\n";
1179
1180 Fn = &F;
1181 MF = &MachineFunction::get (Fn);
1182 LVI = &getAnalysis<FunctionLiveVarInfo> ();
1183 LRI = new LiveRangeInfo (Fn, TM, RegClassList);
1184 LoopDepthCalc = &getAnalysis<LoopInfo> ();
1185
1186 // Create each RegClass for the target machine and add it to the
1187 // RegClassList. This must be done before calling constructLiveRanges().
1188 for (unsigned rc = 0; rc != NumOfRegClasses; ++rc)
1189 RegClassList.push_back (new RegClass (Fn, &TM.getRegInfo (),
1190 MRI.getMachineRegClass (rc)));
1191
1192 LRI->constructLiveRanges(); // create LR info
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001193 if (DEBUG_RA >= RA_DEBUG_LiveRanges)
Brian Gaeke4efe3422003-09-21 01:23:46 +00001194 LRI->printLiveRanges();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001195
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001196 createIGNodeListsAndIGs(); // create IGNode list and IGs
1197
1198 buildInterferenceGraphs(); // build IGs in all reg classes
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001199
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001200 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001201 // print all LRs in all reg classes
Chris Lattner7e708292002-06-25 16:13:24 +00001202 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1203 RegClassList[rc]->printIGNodeList();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001204
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001205 // print IGs in all register classes
Chris Lattner7e708292002-06-25 16:13:24 +00001206 for ( unsigned rc=0; rc < NumOfRegClasses ; rc++)
1207 RegClassList[rc]->printIG();
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001208 }
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +00001209
Brian Gaeke4efe3422003-09-21 01:23:46 +00001210 LRI->coalesceLRs(); // coalesce all live ranges
Ruchira Sasankaef1b0cb2001-11-03 17:13:27 +00001211
Vikram S. Adve39c94e12002-09-14 23:05:33 +00001212 if (DEBUG_RA >= RA_DEBUG_LiveRanges) {
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001213 // print all LRs in all reg classes
Chris Lattnerf726e772002-10-28 19:22:04 +00001214 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1215 RegClassList[rc]->printIGNodeList();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001216
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001217 // print IGs in all register classes
Chris Lattnerf726e772002-10-28 19:22:04 +00001218 for (unsigned rc=0; rc < NumOfRegClasses; rc++)
1219 RegClassList[rc]->printIG();
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001220 }
1221
Ruchira Sasanka0e62aa62001-10-19 21:39:31 +00001222 // mark un-usable suggested color before graph coloring algorithm.
1223 // When this is done, the graph coloring algo will not reserve
1224 // suggested color unnecessarily - they can be used by another LR
1225 markUnusableSugColors();
1226
1227 // color all register classes using the graph coloring algo
Chris Lattner7e708292002-06-25 16:13:24 +00001228 for (unsigned rc=0; rc < NumOfRegClasses ; rc++)
Chris Lattnerf726e772002-10-28 19:22:04 +00001229 RegClassList[rc]->colorAllRegs();
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001230
Misha Brukman37f92e22003-09-11 22:34:13 +00001231 // After graph coloring, if some LRs did not receive a color (i.e, spilled)
1232 // a position for such spilled LRs
Ruchira Sasanka174bded2001-10-28 18:12:02 +00001233 allocateStackSpace4SpilledLRs();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001234
Vikram S. Adved0d06ad2003-05-31 07:32:01 +00001235 // Reset the temp. area on the stack before use by the first instruction.
1236 // This will also happen after updating each instruction.
Brian Gaeke4efe3422003-09-21 01:23:46 +00001237 MF->getInfo()->popAllTempValues();
Ruchira Sasankaf90870f2001-11-15 22:02:06 +00001238
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +00001239 // color incoming args - if the correct color was not received
1240 // insert code to copy to the correct register
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001241 colorIncomingArgs();
Ruchira Sasankaa5ab9642001-09-30 23:11:59 +00001242
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +00001243 // Now update the machine code with register names and add any
1244 // additional code inserted by the register allocator to the instruction
1245 // stream
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001246 updateMachineCode();
Ruchira Sasanka4f3eb222002-01-07 19:19:18 +00001247
Chris Lattner045e7c82001-09-19 16:26:23 +00001248 if (DEBUG_RA) {
Chris Lattnerc083dcc2003-09-01 20:05:47 +00001249 std::cerr << "\n**** Machine Code After Register Allocation:\n\n";
Brian Gaeke4efe3422003-09-21 01:23:46 +00001250 MF->dump();
Chris Lattner045e7c82001-09-19 16:26:23 +00001251 }
Brian Gaeke4efe3422003-09-21 01:23:46 +00001252
1253 // Tear down temporary data structures
1254 for (unsigned rc = 0; rc < NumOfRegClasses; ++rc)
1255 delete RegClassList[rc];
1256 RegClassList.clear ();
1257 AddedInstrMap.clear ();
1258 OperandsColoredMap.clear ();
1259 ScratchRegsUsed.clear ();
1260 AddedInstrAtEntry.clear ();
1261 delete LRI;
Ruchira Sasanka6b0a8b52001-09-15 21:11:11 +00001262
Brian Gaeke4efe3422003-09-21 01:23:46 +00001263 if (DEBUG_RA) std::cerr << "\nRegister allocation complete!\n";
1264 return false; // Function was not modified
1265}