blob: 04978d62e82926e3d3f92598e9e1a0d9e59b7ae2 [file] [log] [blame]
Chris Lattnera3b8b5c2004-07-23 17:56:30 +00001//===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00002//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the LiveInterval analysis pass which is used
11// by the Linear Scan Register allocator. This pass linearizes the
12// basic blocks of the function in DFS order and uses the
13// LiveVariables pass to conservatively compute live intervals for
14// each virtual and physical register.
15//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "liveintervals"
Chris Lattnera3b8b5c2004-07-23 17:56:30 +000019#include "LiveIntervalAnalysis.h"
Misha Brukman08a6c762004-09-03 18:25:53 +000020#include "VirtRegMap.h"
Chris Lattner015959e2004-05-01 21:24:39 +000021#include "llvm/Value.h"
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +000022#include "llvm/Analysis/LoopInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000023#include "llvm/CodeGen/LiveVariables.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000025#include "llvm/CodeGen/MachineInstr.h"
26#include "llvm/CodeGen/Passes.h"
27#include "llvm/CodeGen/SSARegMap.h"
28#include "llvm/Target/MRegisterInfo.h"
29#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Target/TargetMachine.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000031#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/ADT/Statistic.h"
34#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000035#include <algorithm>
Misha Brukman08a6c762004-09-03 18:25:53 +000036#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000037using namespace llvm;
38
39namespace {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000040 RegisterAnalysis<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000041
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000042 Statistic<> numIntervals
43 ("liveintervals", "Number of original intervals");
Alkis Evlogimenos007726c2004-02-20 20:53:26 +000044
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000045 Statistic<> numIntervalsAfter
46 ("liveintervals", "Number of intervals after coalescing");
Alkis Evlogimenos007726c2004-02-20 20:53:26 +000047
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000048 Statistic<> numJoins
49 ("liveintervals", "Number of interval joins performed");
Alkis Evlogimenos007726c2004-02-20 20:53:26 +000050
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000051 Statistic<> numPeep
52 ("liveintervals", "Number of identity moves eliminated after coalescing");
Alkis Evlogimenos007726c2004-02-20 20:53:26 +000053
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000054 Statistic<> numFolded
55 ("liveintervals", "Number of loads/stores folded into instructions");
Alkis Evlogimenos007726c2004-02-20 20:53:26 +000056
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000057 cl::opt<bool>
58 EnableJoining("join-liveintervals",
59 cl::desc("Join compatible live intervals"),
60 cl::init(true));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000061};
62
63void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const
64{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000065 AU.addPreserved<LiveVariables>();
66 AU.addRequired<LiveVariables>();
67 AU.addPreservedID(PHIEliminationID);
68 AU.addRequiredID(PHIEliminationID);
69 AU.addRequiredID(TwoAddressInstructionPassID);
70 AU.addRequired<LoopInfo>();
71 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000072}
73
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000074void LiveIntervals::releaseMemory()
75{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000076 mi2iMap_.clear();
77 i2miMap_.clear();
78 r2iMap_.clear();
79 r2rMap_.clear();
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000080}
81
82
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000083/// runOnMachineFunction - Register allocate the whole function
84///
85bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000086 mf_ = &fn;
87 tm_ = &fn.getTarget();
88 mri_ = tm_->getRegisterInfo();
89 lv_ = &getAnalysis<LiveVariables>();
Alkis Evlogimenos53278012004-08-26 22:22:38 +000090 allocatableRegs_ = mri_->getAllocatableSet(fn);
Alkis Evlogimenos2c4f7b52004-09-09 19:24:38 +000091 r2rMap_.grow(mf_->getSSARegMap()->getLastVirtReg());
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000092
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000093 // number MachineInstrs
94 unsigned miIndex = 0;
95 for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
96 mbb != mbbEnd; ++mbb)
97 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
98 mi != miEnd; ++mi) {
99 bool inserted = mi2iMap_.insert(std::make_pair(mi, miIndex)).second;
100 assert(inserted && "multiple MachineInstr -> index mappings");
101 i2miMap_.push_back(mi);
102 miIndex += InstrSlots::NUM;
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000103 }
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000104
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000105 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000106
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000107 numIntervals += getNumIntervals();
108
109#if 1
110 DEBUG(std::cerr << "********** INTERVALS **********\n");
111 DEBUG(for (iterator I = begin(), E = end(); I != E; ++I)
112 std::cerr << I->second << "\n");
113#endif
114
115 // join intervals if requested
116 if (EnableJoining) joinIntervals();
117
118 numIntervalsAfter += getNumIntervals();
119
120 // perform a final pass over the instructions and compute spill
121 // weights, coalesce virtual registers and remove identity moves
122 const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
123 const TargetInstrInfo& tii = *tm_->getInstrInfo();
124
125 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
126 mbbi != mbbe; ++mbbi) {
127 MachineBasicBlock* mbb = mbbi;
128 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
129
130 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
131 mii != mie; ) {
132 // if the move will be an identity move delete it
133 unsigned srcReg, dstReg, RegRep;
134 if (tii.isMoveInstr(*mii, srcReg, dstReg) &&
135 (RegRep = rep(srcReg)) == rep(dstReg)) {
136 // remove from def list
137 LiveInterval &interval = getOrCreateInterval(RegRep);
138 // remove index -> MachineInstr and
139 // MachineInstr -> index mappings
140 Mi2IndexMap::iterator mi2i = mi2iMap_.find(mii);
141 if (mi2i != mi2iMap_.end()) {
142 i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
143 mi2iMap_.erase(mi2i);
144 }
145 mii = mbbi->erase(mii);
146 ++numPeep;
147 }
148 else {
149 for (unsigned i = 0; i < mii->getNumOperands(); ++i) {
150 const MachineOperand& mop = mii->getOperand(i);
151 if (mop.isRegister() && mop.getReg() &&
152 MRegisterInfo::isVirtualRegister(mop.getReg())) {
153 // replace register with representative register
154 unsigned reg = rep(mop.getReg());
155 mii->SetMachineOperandReg(i, reg);
156
157 LiveInterval &RegInt = getInterval(reg);
158 RegInt.weight +=
159 (mop.isUse() + mop.isDef()) * pow(10.0F, loopDepth);
160 }
161 }
162 ++mii;
163 }
164 }
165 }
166
167 DEBUG(std::cerr << "********** INTERVALS **********\n");
168 DEBUG (for (iterator I = begin(), E = end(); I != E; ++I)
169 std::cerr << I->second << "\n");
170 DEBUG(std::cerr << "********** MACHINEINSTRS **********\n");
171 DEBUG(
172 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
173 mbbi != mbbe; ++mbbi) {
174 std::cerr << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
175 for (MachineBasicBlock::iterator mii = mbbi->begin(),
176 mie = mbbi->end(); mii != mie; ++mii) {
177 std::cerr << getInstructionIndex(mii) << '\t';
178 mii->print(std::cerr, tm_);
179 }
180 });
181
182 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000183}
184
Chris Lattner418da552004-06-21 13:10:56 +0000185std::vector<LiveInterval*> LiveIntervals::addIntervalsForSpills(
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000186 const LiveInterval& li,
187 VirtRegMap& vrm,
188 int slot)
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000189{
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000190 // since this is called after the analysis is done we don't know if
191 // LiveVariables is available
192 lv_ = getAnalysisToUpdate<LiveVariables>();
193
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000194 std::vector<LiveInterval*> added;
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000195
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000196 assert(li.weight != HUGE_VAL &&
197 "attempt to spill already spilled interval!");
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000198
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000199 DEBUG(std::cerr << "\t\t\t\tadding intervals for spills for interval: "
200 << li << '\n');
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000201
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000202 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg);
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000203
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000204 for (LiveInterval::Ranges::const_iterator
205 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
206 unsigned index = getBaseIndex(i->start);
207 unsigned end = getBaseIndex(i->end-1) + InstrSlots::NUM;
208 for (; index != end; index += InstrSlots::NUM) {
209 // skip deleted instructions
210 while (index != end && !getInstructionFromIndex(index))
211 index += InstrSlots::NUM;
212 if (index == end) break;
Chris Lattner8640f4e2004-07-19 15:16:53 +0000213
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000214 MachineBasicBlock::iterator mi = getInstructionFromIndex(index);
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000215
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000216 for_operand:
217 for (unsigned i = 0; i != mi->getNumOperands(); ++i) {
218 MachineOperand& mop = mi->getOperand(i);
219 if (mop.isRegister() && mop.getReg() == li.reg) {
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000220 if (MachineInstr* fmi = mri_->foldMemoryOperand(mi, i, slot)) {
221 if (lv_)
222 lv_->instructionChanged(mi, fmi);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000223 vrm.virtFolded(li.reg, mi, fmi);
224 mi2iMap_.erase(mi);
225 i2miMap_[index/InstrSlots::NUM] = fmi;
226 mi2iMap_[fmi] = index;
227 MachineBasicBlock& mbb = *mi->getParent();
228 mi = mbb.insert(mbb.erase(mi), fmi);
229 ++numFolded;
230 goto for_operand;
231 }
232 else {
233 // This is tricky. We need to add information in
234 // the interval about the spill code so we have to
235 // use our extra load/store slots.
236 //
237 // If we have a use we are going to have a load so
238 // we start the interval from the load slot
239 // onwards. Otherwise we start from the def slot.
240 unsigned start = (mop.isUse() ?
241 getLoadIndex(index) :
242 getDefIndex(index));
243 // If we have a def we are going to have a store
244 // right after it so we end the interval after the
245 // use of the next instruction. Otherwise we end
246 // after the use of this instruction.
247 unsigned end = 1 + (mop.isDef() ?
248 getStoreIndex(index) :
249 getUseIndex(index));
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000250
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000251 // create a new register for this spill
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000252 unsigned nReg = mf_->getSSARegMap()->createVirtualRegister(rc);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000253 mi->SetMachineOperandReg(i, nReg);
254 vrm.grow();
255 vrm.assignVirt2StackSlot(nReg, slot);
256 LiveInterval& nI = getOrCreateInterval(nReg);
257 assert(nI.empty());
258 // the spill weight is now infinity as it
259 // cannot be spilled again
260 nI.weight = HUGE_VAL;
261 LiveRange LR(start, end, nI.getNextValue());
262 DEBUG(std::cerr << " +" << LR);
263 nI.addRange(LR);
264 added.push_back(&nI);
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000265 // update live variables if it is available
266 if (lv_)
267 lv_->addVirtualRegisterKilled(nReg, mi);
268 DEBUG(std::cerr << "\t\t\t\tadded new interval: " << nI << '\n');
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000269 }
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000270 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000271 }
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000272 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000273 }
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000274
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000275 return added;
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000276}
277
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000278void LiveIntervals::printRegName(unsigned reg) const
279{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000280 if (MRegisterInfo::isPhysicalRegister(reg))
281 std::cerr << mri_->getName(reg);
282 else
283 std::cerr << "%reg" << reg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000284}
285
286void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
287 MachineBasicBlock::iterator mi,
Chris Lattner418da552004-06-21 13:10:56 +0000288 LiveInterval& interval)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000289{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000290 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
291 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000292
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000293 // Virtual registers may be defined multiple times (due to phi
294 // elimination and 2-addr elimination). Much of what we do only has to be
295 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000296 // time we see a vreg.
297 if (interval.empty()) {
298 // Get the Idx of the defining instructions.
299 unsigned defIndex = getDefIndex(getInstructionIndex(mi));
Chris Lattner6097d132004-07-19 02:15:56 +0000300
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000301 unsigned ValNum = interval.getNextValue();
302 assert(ValNum == 0 && "First value in interval is not 0?");
303 ValNum = 0; // Clue in the optimizer.
Chris Lattner7ac2d312004-07-24 02:59:07 +0000304
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000305 // Loop over all of the blocks that the vreg is defined in. There are
306 // two cases we have to handle here. The most common case is a vreg
307 // whose lifetime is contained within a basic block. In this case there
308 // will be a single kill, in MBB, which comes after the definition.
309 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
310 // FIXME: what about dead vars?
311 unsigned killIdx;
312 if (vi.Kills[0] != mi)
313 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
314 else
315 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000316
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000317 // If the kill happens after the definition, we have an intra-block
318 // live range.
319 if (killIdx > defIndex) {
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000320 assert(vi.AliveBlocks.empty() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000321 "Shouldn't be alive across any blocks!");
322 LiveRange LR(defIndex, killIdx, ValNum);
323 interval.addRange(LR);
324 DEBUG(std::cerr << " +" << LR << "\n");
325 return;
326 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000327 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000328
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000329 // The other case we handle is when a virtual register lives to the end
330 // of the defining block, potentially live across some blocks, then is
331 // live into some number of blocks, but gets killed. Start by adding a
332 // range that goes from this definition to the end of the defining block.
Alkis Evlogimenosd19e2902004-08-31 17:39:15 +0000333 LiveRange NewLR(defIndex,
334 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
335 ValNum);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000336 DEBUG(std::cerr << " +" << NewLR);
337 interval.addRange(NewLR);
338
339 // Iterate over all of the blocks that the variable is completely
340 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
341 // live interval.
342 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
343 if (vi.AliveBlocks[i]) {
344 MachineBasicBlock* mbb = mf_->getBlockNumbered(i);
345 if (!mbb->empty()) {
346 LiveRange LR(getInstructionIndex(&mbb->front()),
Alkis Evlogimenosd19e2902004-08-31 17:39:15 +0000347 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000348 ValNum);
349 interval.addRange(LR);
350 DEBUG(std::cerr << " +" << LR);
351 }
352 }
353 }
354
355 // Finally, this virtual register is live from the start of any killing
356 // block to the 'use' slot of the killing instruction.
357 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
358 MachineInstr *Kill = vi.Kills[i];
359 LiveRange LR(getInstructionIndex(Kill->getParent()->begin()),
Alkis Evlogimenosd19e2902004-08-31 17:39:15 +0000360 getUseIndex(getInstructionIndex(Kill))+1,
361 ValNum);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000362 interval.addRange(LR);
363 DEBUG(std::cerr << " +" << LR);
364 }
365
366 } else {
367 // If this is the second time we see a virtual register definition, it
368 // must be due to phi elimination or two addr elimination. If this is
369 // the result of two address elimination, then the vreg is the first
370 // operand, and is a def-and-use.
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000371 if (mi->getOperand(0).isRegister() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000372 mi->getOperand(0).getReg() == interval.reg &&
373 mi->getOperand(0).isDef() && mi->getOperand(0).isUse()) {
374 // If this is a two-address definition, then we have already processed
375 // the live range. The only problem is that we didn't realize there
376 // are actually two values in the live interval. Because of this we
377 // need to take the LiveRegion that defines this register and split it
378 // into two values.
379 unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
380 unsigned RedefIndex = getDefIndex(getInstructionIndex(mi));
381
382 // Delete the initial value, which should be short and continuous,
383 // becuase the 2-addr copy must be in the same MBB as the redef.
384 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000385
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000386 LiveRange LR(DefIndex, RedefIndex, interval.getNextValue());
387 DEBUG(std::cerr << " replace range with " << LR);
388 interval.addRange(LR);
389
390 // If this redefinition is dead, we need to add a dummy unit live
391 // range covering the def slot.
392 for (LiveVariables::killed_iterator KI = lv_->dead_begin(mi),
393 E = lv_->dead_end(mi); KI != E; ++KI)
394 if (KI->second == interval.reg) {
395 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, 0));
396 break;
397 }
398
399 DEBUG(std::cerr << "RESULT: " << interval);
400
401 } else {
402 // Otherwise, this must be because of phi elimination. If this is the
403 // first redefinition of the vreg that we have seen, go back and change
404 // the live range in the PHI block to be a different value number.
405 if (interval.containsOneValue()) {
406 assert(vi.Kills.size() == 1 &&
407 "PHI elimination vreg should have one kill, the PHI itself!");
408
409 // Remove the old range that we now know has an incorrect number.
410 MachineInstr *Killer = vi.Kills[0];
411 unsigned Start = getInstructionIndex(Killer->getParent()->begin());
412 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
413 DEBUG(std::cerr << "Removing [" << Start << "," << End << "] from: "
414 << interval << "\n");
415 interval.removeRange(Start, End);
416 DEBUG(std::cerr << "RESULT: " << interval);
417
418 // Replace the interval with one of a NEW value number.
419 LiveRange LR(Start, End, interval.getNextValue());
420 DEBUG(std::cerr << " replace range with " << LR);
421 interval.addRange(LR);
422 DEBUG(std::cerr << "RESULT: " << interval);
423 }
424
425 // In the case of PHI elimination, each variable definition is only
426 // live until the end of the block. We've already taken care of the
427 // rest of the live range.
428 unsigned defIndex = getDefIndex(getInstructionIndex(mi));
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000429 LiveRange LR(defIndex,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000430 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
431 interval.getNextValue());
432 interval.addRange(LR);
433 DEBUG(std::cerr << " +" << LR);
434 }
435 }
436
437 DEBUG(std::cerr << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000438}
439
Chris Lattnerf35fef72004-07-23 21:24:19 +0000440void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000441 MachineBasicBlock::iterator mi,
Chris Lattner418da552004-06-21 13:10:56 +0000442 LiveInterval& interval)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000443{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000444 // A physical register cannot be live across basic block, so its
445 // lifetime must end somewhere in its defining basic block.
446 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
447 typedef LiveVariables::killed_iterator KillIter;
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000448
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000449 unsigned baseIndex = getInstructionIndex(mi);
450 unsigned start = getDefIndex(baseIndex);
451 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000452
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000453 // If it is not used after definition, it is considered dead at
454 // the instruction defining it. Hence its interval is:
455 // [defSlot(def), defSlot(def)+1)
456 for (KillIter ki = lv_->dead_begin(mi), ke = lv_->dead_end(mi);
457 ki != ke; ++ki) {
458 if (interval.reg == ki->second) {
459 DEBUG(std::cerr << " dead");
460 end = getDefIndex(start) + 1;
461 goto exit;
462 }
463 }
464
465 // If it is not dead on definition, it must be killed by a
466 // subsequent instruction. Hence its interval is:
467 // [defSlot(def), useSlot(kill)+1)
468 while (true) {
469 ++mi;
470 assert(mi != MBB->end() && "physreg was not killed in defining block!");
471 baseIndex += InstrSlots::NUM;
472 for (KillIter ki = lv_->killed_begin(mi), ke = lv_->killed_end(mi);
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000473 ki != ke; ++ki) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000474 if (interval.reg == ki->second) {
475 DEBUG(std::cerr << " killed");
476 end = getUseIndex(baseIndex) + 1;
477 goto exit;
478 }
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000479 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000480 }
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000481
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000482exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000483 assert(start < end && "did not find end of interval?");
484 LiveRange LR(start, end, interval.getNextValue());
485 interval.addRange(LR);
486 DEBUG(std::cerr << " +" << LR << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000487}
488
Chris Lattnerf35fef72004-07-23 21:24:19 +0000489void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
490 MachineBasicBlock::iterator MI,
491 unsigned reg) {
492 if (MRegisterInfo::isVirtualRegister(reg))
493 handleVirtualRegisterDef(MBB, MI, getOrCreateInterval(reg));
Alkis Evlogimenos53278012004-08-26 22:22:38 +0000494 else if (allocatableRegs_[reg]) {
Chris Lattnerf35fef72004-07-23 21:24:19 +0000495 handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(reg));
496 for (const unsigned* AS = mri_->getAliasSet(reg); *AS; ++AS)
497 handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(*AS));
498 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000499}
500
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000501/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000502/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000503/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000504/// which a variable is live
505void LiveIntervals::computeIntervals()
506{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000507 DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
508 DEBUG(std::cerr << "********** Function: "
509 << ((Value*)mf_->getFunction())->getName() << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000510
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000511 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000512 I != E; ++I) {
513 MachineBasicBlock* mbb = I;
514 DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n");
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000515
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000516 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
517 mi != miEnd; ++mi) {
518 const TargetInstrDescriptor& tid =
519 tm_->getInstrInfo()->get(mi->getOpcode());
520 DEBUG(std::cerr << getInstructionIndex(mi) << "\t";
521 mi->print(std::cerr, tm_));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000522
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000523 // handle implicit defs
524 for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
525 handleRegisterDef(mbb, mi, *id);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000526
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000527 // handle explicit defs
528 for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
529 MachineOperand& mop = mi->getOperand(i);
530 // handle register defs - build intervals
531 if (mop.isRegister() && mop.getReg() && mop.isDef())
532 handleRegisterDef(mbb, mi, mop.getReg());
533 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000534 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000535 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000536}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000537
Chris Lattner1c5c0442004-07-19 14:08:10 +0000538void LiveIntervals::joinIntervalsInMachineBB(MachineBasicBlock *MBB) {
Chris Lattner7ac2d312004-07-24 02:59:07 +0000539 DEBUG(std::cerr << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
540 const TargetInstrInfo &TII = *tm_->getInstrInfo();
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000541
Chris Lattner7ac2d312004-07-24 02:59:07 +0000542 for (MachineBasicBlock::iterator mi = MBB->begin(), mie = MBB->end();
543 mi != mie; ++mi) {
544 DEBUG(std::cerr << getInstructionIndex(mi) << '\t' << *mi);
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000545
Chris Lattner7ac2d312004-07-24 02:59:07 +0000546 // we only join virtual registers with allocatable
547 // physical registers since we do not have liveness information
548 // on not allocatable physical registers
549 unsigned regA, regB;
550 if (TII.isMoveInstr(*mi, regA, regB) &&
Alkis Evlogimenos53278012004-08-26 22:22:38 +0000551 (MRegisterInfo::isVirtualRegister(regA) || allocatableRegs_[regA]) &&
552 (MRegisterInfo::isVirtualRegister(regB) || allocatableRegs_[regB])) {
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000553
Chris Lattner7ac2d312004-07-24 02:59:07 +0000554 // Get representative registers.
555 regA = rep(regA);
556 regB = rep(regB);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000557
Chris Lattner7ac2d312004-07-24 02:59:07 +0000558 // If they are already joined we continue.
559 if (regA == regB)
560 continue;
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000561
Chris Lattner7ac2d312004-07-24 02:59:07 +0000562 // If they are both physical registers, we cannot join them.
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000563 if (MRegisterInfo::isPhysicalRegister(regA) &&
Chris Lattner7ac2d312004-07-24 02:59:07 +0000564 MRegisterInfo::isPhysicalRegister(regB))
565 continue;
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000566
Chris Lattner7ac2d312004-07-24 02:59:07 +0000567 // If they are not of the same register class, we cannot join them.
568 if (differingRegisterClasses(regA, regB))
569 continue;
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000570
Chris Lattner7ac2d312004-07-24 02:59:07 +0000571 LiveInterval &IntA = getInterval(regA);
572 LiveInterval &IntB = getInterval(regB);
573 assert(IntA.reg == regA && IntB.reg == regB &&
574 "Register mapping is horribly broken!");
Chris Lattner060913c2004-07-24 04:32:22 +0000575
576 DEBUG(std::cerr << "\t\tInspecting " << IntA << " and " << IntB << ": ");
577
Chris Lattner4df98e52004-07-24 03:32:06 +0000578 // If two intervals contain a single value and are joined by a copy, it
579 // does not matter if the intervals overlap, they can always be joined.
Chris Lattner7ac2d312004-07-24 02:59:07 +0000580 bool TriviallyJoinable =
581 IntA.containsOneValue() && IntB.containsOneValue();
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000582
Chris Lattner7ac2d312004-07-24 02:59:07 +0000583 unsigned MIDefIdx = getDefIndex(getInstructionIndex(mi));
Chris Lattnerc25b55a2004-07-25 07:47:25 +0000584 if ((TriviallyJoinable || IntB.joinable(IntA, MIDefIdx)) &&
Chris Lattner7ac2d312004-07-24 02:59:07 +0000585 !overlapsAliases(&IntA, &IntB)) {
586 IntB.join(IntA, MIDefIdx);
Chris Lattner1c5c0442004-07-19 14:08:10 +0000587
Chris Lattner7ac2d312004-07-24 02:59:07 +0000588 if (!MRegisterInfo::isPhysicalRegister(regA)) {
Chris Lattner4df98e52004-07-24 03:32:06 +0000589 r2iMap_.erase(regA);
Chris Lattner7ac2d312004-07-24 02:59:07 +0000590 r2rMap_[regA] = regB;
591 } else {
592 // Otherwise merge the data structures the other way so we don't lose
593 // the physreg information.
594 r2rMap_[regB] = regA;
595 IntB.reg = regA;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000596 IntA.swap(IntB);
Chris Lattner4df98e52004-07-24 03:32:06 +0000597 r2iMap_.erase(regB);
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000598 }
Chris Lattner7ac2d312004-07-24 02:59:07 +0000599 DEBUG(std::cerr << "Joined. Result = " << IntB << "\n");
600 ++numJoins;
601 } else {
602 DEBUG(std::cerr << "Interference!\n");
603 }
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000604 }
Chris Lattner7ac2d312004-07-24 02:59:07 +0000605 }
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000606}
607
Chris Lattnercc0d1562004-07-19 14:40:29 +0000608namespace {
609 // DepthMBBCompare - Comparison predicate that sort first based on the loop
610 // depth of the basic block (the unsigned), and then on the MBB number.
611 struct DepthMBBCompare {
612 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
613 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
614 if (LHS.first > RHS.first) return true; // Deeper loops first
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000615 return LHS.first == RHS.first &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000616 LHS.second->getNumber() < RHS.second->getNumber();
Chris Lattnercc0d1562004-07-19 14:40:29 +0000617 }
618 };
619}
Chris Lattner1c5c0442004-07-19 14:08:10 +0000620
Chris Lattnercc0d1562004-07-19 14:40:29 +0000621void LiveIntervals::joinIntervals() {
622 DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
623
624 const LoopInfo &LI = getAnalysis<LoopInfo>();
625 if (LI.begin() == LI.end()) {
626 // If there are no loops in the function, join intervals in function order.
Chris Lattner1c5c0442004-07-19 14:08:10 +0000627 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
628 I != E; ++I)
629 joinIntervalsInMachineBB(I);
Chris Lattnercc0d1562004-07-19 14:40:29 +0000630 } else {
631 // Otherwise, join intervals in inner loops before other intervals.
632 // Unfortunately we can't just iterate over loop hierarchy here because
633 // there may be more MBB's than BB's. Collect MBB's for sorting.
634 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
635 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
636 I != E; ++I)
637 MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
638
639 // Sort by loop depth.
640 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
641
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000642 // Finally, join intervals in loop nest order.
Chris Lattnercc0d1562004-07-19 14:40:29 +0000643 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
644 joinIntervalsInMachineBB(MBBs[i].second);
645 }
Chris Lattnerc83e40d2004-07-25 03:24:11 +0000646
647 DEBUG(std::cerr << "*** Register mapping ***\n");
Alkis Evlogimenos5d0d1e32004-09-08 03:01:50 +0000648 DEBUG(for (int i = 0, e = r2rMap_.size(); i != e; ++i)
649 if (r2rMap_[i])
650 std::cerr << " reg " << i << " -> reg " << r2rMap_[i] << "\n");
Chris Lattner1c5c0442004-07-19 14:08:10 +0000651}
652
Chris Lattner7ac2d312004-07-24 02:59:07 +0000653/// Return true if the two specified registers belong to different register
654/// classes. The registers may be either phys or virt regs.
655bool LiveIntervals::differingRegisterClasses(unsigned RegA,
656 unsigned RegB) const {
657 const TargetRegisterClass *RegClass;
Alkis Evlogimenos79b0c3f2004-01-23 13:37:51 +0000658
Chris Lattner7ac2d312004-07-24 02:59:07 +0000659 // Get the register classes for the first reg.
660 if (MRegisterInfo::isVirtualRegister(RegA))
661 RegClass = mf_->getSSARegMap()->getRegClass(RegA);
662 else
663 RegClass = mri_->getRegClass(RegA);
664
665 // Compare against the regclass for the second reg.
666 if (MRegisterInfo::isVirtualRegister(RegB))
667 return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
668 else
Chris Lattnerd0d0a1a2004-08-24 17:48:29 +0000669 return !RegClass->contains(RegB);
Chris Lattner7ac2d312004-07-24 02:59:07 +0000670}
671
672bool LiveIntervals::overlapsAliases(const LiveInterval *LHS,
673 const LiveInterval *RHS) const {
674 if (!MRegisterInfo::isPhysicalRegister(LHS->reg)) {
675 if (!MRegisterInfo::isPhysicalRegister(RHS->reg))
676 return false; // vreg-vreg merge has no aliases!
677 std::swap(LHS, RHS);
678 }
679
680 assert(MRegisterInfo::isPhysicalRegister(LHS->reg) &&
681 MRegisterInfo::isVirtualRegister(RHS->reg) &&
682 "first interval must describe a physical register");
683
Chris Lattner4df98e52004-07-24 03:32:06 +0000684 for (const unsigned *AS = mri_->getAliasSet(LHS->reg); *AS; ++AS)
685 if (RHS->overlaps(getInterval(*AS)))
686 return true;
Alkis Evlogimenos79b0c3f2004-01-23 13:37:51 +0000687
Chris Lattner4df98e52004-07-24 03:32:06 +0000688 return false;
Alkis Evlogimenos79b0c3f2004-01-23 13:37:51 +0000689}
690
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000691LiveInterval LiveIntervals::createInterval(unsigned reg) {
Chris Lattner4df98e52004-07-24 03:32:06 +0000692 float Weight = MRegisterInfo::isPhysicalRegister(reg) ? HUGE_VAL :0.0F;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000693 return LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000694}