blob: 1165ae54fe2ce84278818ccfbcb1c5e4fcd83ab7 [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"
Chris Lattner015959e2004-05-01 21:24:39 +000020#include "llvm/Value.h"
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +000021#include "llvm/Analysis/LoopInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000022#include "llvm/CodeGen/LiveVariables.h"
23#include "llvm/CodeGen/MachineFrameInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000024#include "llvm/CodeGen/MachineInstr.h"
25#include "llvm/CodeGen/Passes.h"
26#include "llvm/CodeGen/SSARegMap.h"
27#include "llvm/Target/MRegisterInfo.h"
28#include "llvm/Target/TargetInstrInfo.h"
29#include "llvm/Target/TargetMachine.h"
Alkis Evlogimenose88280a2004-01-22 23:08:45 +000030#include "Support/CommandLine.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000031#include "Support/Debug.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000032#include "Support/Statistic.h"
Alkis Evlogimenos843b1602004-02-15 10:24:21 +000033#include "Support/STLExtras.h"
Alkis Evlogimenos5f375022004-03-01 20:05:10 +000034#include "VirtRegMap.h"
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +000035#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000036
37using 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 Evlogimenosff0cbe12003-11-20 03:32:25 +000091
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000092 // number MachineInstrs
93 unsigned miIndex = 0;
94 for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
95 mbb != mbbEnd; ++mbb)
96 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
97 mi != miEnd; ++mi) {
98 bool inserted = mi2iMap_.insert(std::make_pair(mi, miIndex)).second;
99 assert(inserted && "multiple MachineInstr -> index mappings");
100 i2miMap_.push_back(mi);
101 miIndex += InstrSlots::NUM;
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000102 }
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000103
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000104 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000105
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000106 numIntervals += getNumIntervals();
107
108#if 1
109 DEBUG(std::cerr << "********** INTERVALS **********\n");
110 DEBUG(for (iterator I = begin(), E = end(); I != E; ++I)
111 std::cerr << I->second << "\n");
112#endif
113
114 // join intervals if requested
115 if (EnableJoining) joinIntervals();
116
117 numIntervalsAfter += getNumIntervals();
118
119 // perform a final pass over the instructions and compute spill
120 // weights, coalesce virtual registers and remove identity moves
121 const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
122 const TargetInstrInfo& tii = *tm_->getInstrInfo();
123
124 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
125 mbbi != mbbe; ++mbbi) {
126 MachineBasicBlock* mbb = mbbi;
127 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
128
129 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
130 mii != mie; ) {
131 // if the move will be an identity move delete it
132 unsigned srcReg, dstReg, RegRep;
133 if (tii.isMoveInstr(*mii, srcReg, dstReg) &&
134 (RegRep = rep(srcReg)) == rep(dstReg)) {
135 // remove from def list
136 LiveInterval &interval = getOrCreateInterval(RegRep);
137 // remove index -> MachineInstr and
138 // MachineInstr -> index mappings
139 Mi2IndexMap::iterator mi2i = mi2iMap_.find(mii);
140 if (mi2i != mi2iMap_.end()) {
141 i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
142 mi2iMap_.erase(mi2i);
143 }
144 mii = mbbi->erase(mii);
145 ++numPeep;
146 }
147 else {
148 for (unsigned i = 0; i < mii->getNumOperands(); ++i) {
149 const MachineOperand& mop = mii->getOperand(i);
150 if (mop.isRegister() && mop.getReg() &&
151 MRegisterInfo::isVirtualRegister(mop.getReg())) {
152 // replace register with representative register
153 unsigned reg = rep(mop.getReg());
154 mii->SetMachineOperandReg(i, reg);
155
156 LiveInterval &RegInt = getInterval(reg);
157 RegInt.weight +=
158 (mop.isUse() + mop.isDef()) * pow(10.0F, loopDepth);
159 }
160 }
161 ++mii;
162 }
163 }
164 }
165
166 DEBUG(std::cerr << "********** INTERVALS **********\n");
167 DEBUG (for (iterator I = begin(), E = end(); I != E; ++I)
168 std::cerr << I->second << "\n");
169 DEBUG(std::cerr << "********** MACHINEINSTRS **********\n");
170 DEBUG(
171 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
172 mbbi != mbbe; ++mbbi) {
173 std::cerr << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
174 for (MachineBasicBlock::iterator mii = mbbi->begin(),
175 mie = mbbi->end(); mii != mie; ++mii) {
176 std::cerr << getInstructionIndex(mii) << '\t';
177 mii->print(std::cerr, tm_);
178 }
179 });
180
181 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000182}
183
Chris Lattner418da552004-06-21 13:10:56 +0000184std::vector<LiveInterval*> LiveIntervals::addIntervalsForSpills(
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000185 const LiveInterval& li,
186 VirtRegMap& vrm,
187 int slot)
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000188{
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000189 // since this is called after the analysis is done we don't know if
190 // LiveVariables is available
191 lv_ = getAnalysisToUpdate<LiveVariables>();
192
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000193 std::vector<LiveInterval*> added;
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000194
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000195 assert(li.weight != HUGE_VAL &&
196 "attempt to spill already spilled interval!");
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000197
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000198 DEBUG(std::cerr << "\t\t\t\tadding intervals for spills for interval: "
199 << li << '\n');
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000200
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000201 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg);
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000202
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000203 for (LiveInterval::Ranges::const_iterator
204 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
205 unsigned index = getBaseIndex(i->start);
206 unsigned end = getBaseIndex(i->end-1) + InstrSlots::NUM;
207 for (; index != end; index += InstrSlots::NUM) {
208 // skip deleted instructions
209 while (index != end && !getInstructionFromIndex(index))
210 index += InstrSlots::NUM;
211 if (index == end) break;
Chris Lattner8640f4e2004-07-19 15:16:53 +0000212
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000213 MachineBasicBlock::iterator mi = getInstructionFromIndex(index);
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000214
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000215 for_operand:
216 for (unsigned i = 0; i != mi->getNumOperands(); ++i) {
217 MachineOperand& mop = mi->getOperand(i);
218 if (mop.isRegister() && mop.getReg() == li.reg) {
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000219 if (MachineInstr* fmi = mri_->foldMemoryOperand(mi, i, slot)) {
220 if (lv_)
221 lv_->instructionChanged(mi, fmi);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000222 vrm.virtFolded(li.reg, mi, fmi);
223 mi2iMap_.erase(mi);
224 i2miMap_[index/InstrSlots::NUM] = fmi;
225 mi2iMap_[fmi] = index;
226 MachineBasicBlock& mbb = *mi->getParent();
227 mi = mbb.insert(mbb.erase(mi), fmi);
228 ++numFolded;
229 goto for_operand;
230 }
231 else {
232 // This is tricky. We need to add information in
233 // the interval about the spill code so we have to
234 // use our extra load/store slots.
235 //
236 // If we have a use we are going to have a load so
237 // we start the interval from the load slot
238 // onwards. Otherwise we start from the def slot.
239 unsigned start = (mop.isUse() ?
240 getLoadIndex(index) :
241 getDefIndex(index));
242 // If we have a def we are going to have a store
243 // right after it so we end the interval after the
244 // use of the next instruction. Otherwise we end
245 // after the use of this instruction.
246 unsigned end = 1 + (mop.isDef() ?
247 getStoreIndex(index) :
248 getUseIndex(index));
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000249
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000250 // create a new register for this spill
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000251 unsigned nReg = mf_->getSSARegMap()->createVirtualRegister(rc);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000252 mi->SetMachineOperandReg(i, nReg);
253 vrm.grow();
254 vrm.assignVirt2StackSlot(nReg, slot);
255 LiveInterval& nI = getOrCreateInterval(nReg);
256 assert(nI.empty());
257 // the spill weight is now infinity as it
258 // cannot be spilled again
259 nI.weight = HUGE_VAL;
260 LiveRange LR(start, end, nI.getNextValue());
261 DEBUG(std::cerr << " +" << LR);
262 nI.addRange(LR);
263 added.push_back(&nI);
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000264 // update live variables if it is available
265 if (lv_)
266 lv_->addVirtualRegisterKilled(nReg, mi);
267 DEBUG(std::cerr << "\t\t\t\tadded new interval: " << nI << '\n');
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000268 }
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000269 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000270 }
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000271 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000272 }
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000273
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000274 return added;
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000275}
276
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000277void LiveIntervals::printRegName(unsigned reg) const
278{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000279 if (MRegisterInfo::isPhysicalRegister(reg))
280 std::cerr << mri_->getName(reg);
281 else
282 std::cerr << "%reg" << reg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000283}
284
285void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
286 MachineBasicBlock::iterator mi,
Chris Lattner418da552004-06-21 13:10:56 +0000287 LiveInterval& interval)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000288{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000289 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
290 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000291
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000292 // Virtual registers may be defined multiple times (due to phi
293 // elimination and 2-addr elimination). Much of what we do only has to be
294 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000295 // time we see a vreg.
296 if (interval.empty()) {
297 // Get the Idx of the defining instructions.
298 unsigned defIndex = getDefIndex(getInstructionIndex(mi));
Chris Lattner6097d132004-07-19 02:15:56 +0000299
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000300 unsigned ValNum = interval.getNextValue();
301 assert(ValNum == 0 && "First value in interval is not 0?");
302 ValNum = 0; // Clue in the optimizer.
Chris Lattner7ac2d312004-07-24 02:59:07 +0000303
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000304 // Loop over all of the blocks that the vreg is defined in. There are
305 // two cases we have to handle here. The most common case is a vreg
306 // whose lifetime is contained within a basic block. In this case there
307 // will be a single kill, in MBB, which comes after the definition.
308 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
309 // FIXME: what about dead vars?
310 unsigned killIdx;
311 if (vi.Kills[0] != mi)
312 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
313 else
314 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000315
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000316 // If the kill happens after the definition, we have an intra-block
317 // live range.
318 if (killIdx > defIndex) {
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000319 assert(vi.AliveBlocks.empty() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000320 "Shouldn't be alive across any blocks!");
321 LiveRange LR(defIndex, killIdx, ValNum);
322 interval.addRange(LR);
323 DEBUG(std::cerr << " +" << LR << "\n");
324 return;
325 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000326 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000327
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000328 // The other case we handle is when a virtual register lives to the end
329 // of the defining block, potentially live across some blocks, then is
330 // live into some number of blocks, but gets killed. Start by adding a
331 // range that goes from this definition to the end of the defining block.
332 LiveRange NewLR(defIndex, getInstructionIndex(&mbb->back()) +
333 InstrSlots::NUM, ValNum);
334 DEBUG(std::cerr << " +" << NewLR);
335 interval.addRange(NewLR);
336
337 // Iterate over all of the blocks that the variable is completely
338 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
339 // live interval.
340 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
341 if (vi.AliveBlocks[i]) {
342 MachineBasicBlock* mbb = mf_->getBlockNumbered(i);
343 if (!mbb->empty()) {
344 LiveRange LR(getInstructionIndex(&mbb->front()),
345 getInstructionIndex(&mbb->back())+InstrSlots::NUM,
346 ValNum);
347 interval.addRange(LR);
348 DEBUG(std::cerr << " +" << LR);
349 }
350 }
351 }
352
353 // Finally, this virtual register is live from the start of any killing
354 // block to the 'use' slot of the killing instruction.
355 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
356 MachineInstr *Kill = vi.Kills[i];
357 LiveRange LR(getInstructionIndex(Kill->getParent()->begin()),
358 getUseIndex(getInstructionIndex(Kill))+1, ValNum);
359 interval.addRange(LR);
360 DEBUG(std::cerr << " +" << LR);
361 }
362
363 } else {
364 // If this is the second time we see a virtual register definition, it
365 // must be due to phi elimination or two addr elimination. If this is
366 // the result of two address elimination, then the vreg is the first
367 // operand, and is a def-and-use.
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000368 if (mi->getOperand(0).isRegister() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000369 mi->getOperand(0).getReg() == interval.reg &&
370 mi->getOperand(0).isDef() && mi->getOperand(0).isUse()) {
371 // If this is a two-address definition, then we have already processed
372 // the live range. The only problem is that we didn't realize there
373 // are actually two values in the live interval. Because of this we
374 // need to take the LiveRegion that defines this register and split it
375 // into two values.
376 unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
377 unsigned RedefIndex = getDefIndex(getInstructionIndex(mi));
378
379 // Delete the initial value, which should be short and continuous,
380 // becuase the 2-addr copy must be in the same MBB as the redef.
381 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000382
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000383 LiveRange LR(DefIndex, RedefIndex, interval.getNextValue());
384 DEBUG(std::cerr << " replace range with " << LR);
385 interval.addRange(LR);
386
387 // If this redefinition is dead, we need to add a dummy unit live
388 // range covering the def slot.
389 for (LiveVariables::killed_iterator KI = lv_->dead_begin(mi),
390 E = lv_->dead_end(mi); KI != E; ++KI)
391 if (KI->second == interval.reg) {
392 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, 0));
393 break;
394 }
395
396 DEBUG(std::cerr << "RESULT: " << interval);
397
398 } else {
399 // Otherwise, this must be because of phi elimination. If this is the
400 // first redefinition of the vreg that we have seen, go back and change
401 // the live range in the PHI block to be a different value number.
402 if (interval.containsOneValue()) {
403 assert(vi.Kills.size() == 1 &&
404 "PHI elimination vreg should have one kill, the PHI itself!");
405
406 // Remove the old range that we now know has an incorrect number.
407 MachineInstr *Killer = vi.Kills[0];
408 unsigned Start = getInstructionIndex(Killer->getParent()->begin());
409 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
410 DEBUG(std::cerr << "Removing [" << Start << "," << End << "] from: "
411 << interval << "\n");
412 interval.removeRange(Start, End);
413 DEBUG(std::cerr << "RESULT: " << interval);
414
415 // Replace the interval with one of a NEW value number.
416 LiveRange LR(Start, End, interval.getNextValue());
417 DEBUG(std::cerr << " replace range with " << LR);
418 interval.addRange(LR);
419 DEBUG(std::cerr << "RESULT: " << interval);
420 }
421
422 // In the case of PHI elimination, each variable definition is only
423 // live until the end of the block. We've already taken care of the
424 // rest of the live range.
425 unsigned defIndex = getDefIndex(getInstructionIndex(mi));
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000426 LiveRange LR(defIndex,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000427 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
428 interval.getNextValue());
429 interval.addRange(LR);
430 DEBUG(std::cerr << " +" << LR);
431 }
432 }
433
434 DEBUG(std::cerr << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000435}
436
Chris Lattnerf35fef72004-07-23 21:24:19 +0000437void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000438 MachineBasicBlock::iterator mi,
Chris Lattner418da552004-06-21 13:10:56 +0000439 LiveInterval& interval)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000440{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000441 // A physical register cannot be live across basic block, so its
442 // lifetime must end somewhere in its defining basic block.
443 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
444 typedef LiveVariables::killed_iterator KillIter;
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000445
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000446 unsigned baseIndex = getInstructionIndex(mi);
447 unsigned start = getDefIndex(baseIndex);
448 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000449
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000450 // If it is not used after definition, it is considered dead at
451 // the instruction defining it. Hence its interval is:
452 // [defSlot(def), defSlot(def)+1)
453 for (KillIter ki = lv_->dead_begin(mi), ke = lv_->dead_end(mi);
454 ki != ke; ++ki) {
455 if (interval.reg == ki->second) {
456 DEBUG(std::cerr << " dead");
457 end = getDefIndex(start) + 1;
458 goto exit;
459 }
460 }
461
462 // If it is not dead on definition, it must be killed by a
463 // subsequent instruction. Hence its interval is:
464 // [defSlot(def), useSlot(kill)+1)
465 while (true) {
466 ++mi;
467 assert(mi != MBB->end() && "physreg was not killed in defining block!");
468 baseIndex += InstrSlots::NUM;
469 for (KillIter ki = lv_->killed_begin(mi), ke = lv_->killed_end(mi);
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000470 ki != ke; ++ki) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000471 if (interval.reg == ki->second) {
472 DEBUG(std::cerr << " killed");
473 end = getUseIndex(baseIndex) + 1;
474 goto exit;
475 }
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000476 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000477 }
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000478
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000479exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000480 assert(start < end && "did not find end of interval?");
481 LiveRange LR(start, end, interval.getNextValue());
482 interval.addRange(LR);
483 DEBUG(std::cerr << " +" << LR << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000484}
485
Chris Lattnerf35fef72004-07-23 21:24:19 +0000486void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
487 MachineBasicBlock::iterator MI,
488 unsigned reg) {
489 if (MRegisterInfo::isVirtualRegister(reg))
490 handleVirtualRegisterDef(MBB, MI, getOrCreateInterval(reg));
Alkis Evlogimenos53278012004-08-26 22:22:38 +0000491 else if (allocatableRegs_[reg]) {
Chris Lattnerf35fef72004-07-23 21:24:19 +0000492 handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(reg));
493 for (const unsigned* AS = mri_->getAliasSet(reg); *AS; ++AS)
494 handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(*AS));
495 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000496}
497
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000498/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000499/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000500/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000501/// which a variable is live
502void LiveIntervals::computeIntervals()
503{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000504 DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
505 DEBUG(std::cerr << "********** Function: "
506 << ((Value*)mf_->getFunction())->getName() << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000507
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000508 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000509 I != E; ++I) {
510 MachineBasicBlock* mbb = I;
511 DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n");
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000512
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000513 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
514 mi != miEnd; ++mi) {
515 const TargetInstrDescriptor& tid =
516 tm_->getInstrInfo()->get(mi->getOpcode());
517 DEBUG(std::cerr << getInstructionIndex(mi) << "\t";
518 mi->print(std::cerr, tm_));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000519
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000520 // handle implicit defs
521 for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
522 handleRegisterDef(mbb, mi, *id);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000523
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000524 // handle explicit defs
525 for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
526 MachineOperand& mop = mi->getOperand(i);
527 // handle register defs - build intervals
528 if (mop.isRegister() && mop.getReg() && mop.isDef())
529 handleRegisterDef(mbb, mi, mop.getReg());
530 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000531 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000532 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000533}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000534
Chris Lattner1c5c0442004-07-19 14:08:10 +0000535void LiveIntervals::joinIntervalsInMachineBB(MachineBasicBlock *MBB) {
Chris Lattner7ac2d312004-07-24 02:59:07 +0000536 DEBUG(std::cerr << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
537 const TargetInstrInfo &TII = *tm_->getInstrInfo();
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000538
Chris Lattner7ac2d312004-07-24 02:59:07 +0000539 for (MachineBasicBlock::iterator mi = MBB->begin(), mie = MBB->end();
540 mi != mie; ++mi) {
541 DEBUG(std::cerr << getInstructionIndex(mi) << '\t' << *mi);
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000542
Chris Lattner7ac2d312004-07-24 02:59:07 +0000543 // we only join virtual registers with allocatable
544 // physical registers since we do not have liveness information
545 // on not allocatable physical registers
546 unsigned regA, regB;
547 if (TII.isMoveInstr(*mi, regA, regB) &&
Alkis Evlogimenos53278012004-08-26 22:22:38 +0000548 (MRegisterInfo::isVirtualRegister(regA) || allocatableRegs_[regA]) &&
549 (MRegisterInfo::isVirtualRegister(regB) || allocatableRegs_[regB])) {
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000550
Chris Lattner7ac2d312004-07-24 02:59:07 +0000551 // Get representative registers.
552 regA = rep(regA);
553 regB = rep(regB);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000554
Chris Lattner7ac2d312004-07-24 02:59:07 +0000555 // If they are already joined we continue.
556 if (regA == regB)
557 continue;
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000558
Chris Lattner7ac2d312004-07-24 02:59:07 +0000559 // If they are both physical registers, we cannot join them.
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000560 if (MRegisterInfo::isPhysicalRegister(regA) &&
Chris Lattner7ac2d312004-07-24 02:59:07 +0000561 MRegisterInfo::isPhysicalRegister(regB))
562 continue;
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000563
Chris Lattner7ac2d312004-07-24 02:59:07 +0000564 // If they are not of the same register class, we cannot join them.
565 if (differingRegisterClasses(regA, regB))
566 continue;
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000567
Chris Lattner7ac2d312004-07-24 02:59:07 +0000568 LiveInterval &IntA = getInterval(regA);
569 LiveInterval &IntB = getInterval(regB);
570 assert(IntA.reg == regA && IntB.reg == regB &&
571 "Register mapping is horribly broken!");
Chris Lattner060913c2004-07-24 04:32:22 +0000572
573 DEBUG(std::cerr << "\t\tInspecting " << IntA << " and " << IntB << ": ");
574
Chris Lattner4df98e52004-07-24 03:32:06 +0000575 // If two intervals contain a single value and are joined by a copy, it
576 // does not matter if the intervals overlap, they can always be joined.
Chris Lattner7ac2d312004-07-24 02:59:07 +0000577 bool TriviallyJoinable =
578 IntA.containsOneValue() && IntB.containsOneValue();
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000579
Chris Lattner7ac2d312004-07-24 02:59:07 +0000580 unsigned MIDefIdx = getDefIndex(getInstructionIndex(mi));
Chris Lattnerc25b55a2004-07-25 07:47:25 +0000581 if ((TriviallyJoinable || IntB.joinable(IntA, MIDefIdx)) &&
Chris Lattner7ac2d312004-07-24 02:59:07 +0000582 !overlapsAliases(&IntA, &IntB)) {
583 IntB.join(IntA, MIDefIdx);
Chris Lattner1c5c0442004-07-19 14:08:10 +0000584
Chris Lattner7ac2d312004-07-24 02:59:07 +0000585 if (!MRegisterInfo::isPhysicalRegister(regA)) {
Chris Lattner4df98e52004-07-24 03:32:06 +0000586 r2iMap_.erase(regA);
Chris Lattner7ac2d312004-07-24 02:59:07 +0000587 r2rMap_[regA] = regB;
588 } else {
589 // Otherwise merge the data structures the other way so we don't lose
590 // the physreg information.
591 r2rMap_[regB] = regA;
592 IntB.reg = regA;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000593 IntA.swap(IntB);
Chris Lattner4df98e52004-07-24 03:32:06 +0000594 r2iMap_.erase(regB);
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000595 }
Chris Lattner7ac2d312004-07-24 02:59:07 +0000596 DEBUG(std::cerr << "Joined. Result = " << IntB << "\n");
597 ++numJoins;
598 } else {
599 DEBUG(std::cerr << "Interference!\n");
600 }
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000601 }
Chris Lattner7ac2d312004-07-24 02:59:07 +0000602 }
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000603}
604
Chris Lattnercc0d1562004-07-19 14:40:29 +0000605namespace {
606 // DepthMBBCompare - Comparison predicate that sort first based on the loop
607 // depth of the basic block (the unsigned), and then on the MBB number.
608 struct DepthMBBCompare {
609 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
610 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
611 if (LHS.first > RHS.first) return true; // Deeper loops first
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000612 return LHS.first == RHS.first &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000613 LHS.second->getNumber() < RHS.second->getNumber();
Chris Lattnercc0d1562004-07-19 14:40:29 +0000614 }
615 };
616}
Chris Lattner1c5c0442004-07-19 14:08:10 +0000617
Chris Lattnercc0d1562004-07-19 14:40:29 +0000618void LiveIntervals::joinIntervals() {
619 DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
620
621 const LoopInfo &LI = getAnalysis<LoopInfo>();
622 if (LI.begin() == LI.end()) {
623 // If there are no loops in the function, join intervals in function order.
Chris Lattner1c5c0442004-07-19 14:08:10 +0000624 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
625 I != E; ++I)
626 joinIntervalsInMachineBB(I);
Chris Lattnercc0d1562004-07-19 14:40:29 +0000627 } else {
628 // Otherwise, join intervals in inner loops before other intervals.
629 // Unfortunately we can't just iterate over loop hierarchy here because
630 // there may be more MBB's than BB's. Collect MBB's for sorting.
631 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
632 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
633 I != E; ++I)
634 MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
635
636 // Sort by loop depth.
637 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
638
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000639 // Finally, join intervals in loop nest order.
Chris Lattnercc0d1562004-07-19 14:40:29 +0000640 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
641 joinIntervalsInMachineBB(MBBs[i].second);
642 }
Chris Lattnerc83e40d2004-07-25 03:24:11 +0000643
644 DEBUG(std::cerr << "*** Register mapping ***\n");
645 DEBUG(for (std::map<unsigned, unsigned>::iterator I = r2rMap_.begin(),
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000646 E = r2rMap_.end(); I != E; ++I)
647 std::cerr << " reg " << I->first << " -> reg " << I->second << "\n";);
Chris Lattner1c5c0442004-07-19 14:08:10 +0000648}
649
Chris Lattner7ac2d312004-07-24 02:59:07 +0000650/// Return true if the two specified registers belong to different register
651/// classes. The registers may be either phys or virt regs.
652bool LiveIntervals::differingRegisterClasses(unsigned RegA,
653 unsigned RegB) const {
654 const TargetRegisterClass *RegClass;
Alkis Evlogimenos79b0c3f2004-01-23 13:37:51 +0000655
Chris Lattner7ac2d312004-07-24 02:59:07 +0000656 // Get the register classes for the first reg.
657 if (MRegisterInfo::isVirtualRegister(RegA))
658 RegClass = mf_->getSSARegMap()->getRegClass(RegA);
659 else
660 RegClass = mri_->getRegClass(RegA);
661
662 // Compare against the regclass for the second reg.
663 if (MRegisterInfo::isVirtualRegister(RegB))
664 return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
665 else
Chris Lattnerd0d0a1a2004-08-24 17:48:29 +0000666 return !RegClass->contains(RegB);
Chris Lattner7ac2d312004-07-24 02:59:07 +0000667}
668
669bool LiveIntervals::overlapsAliases(const LiveInterval *LHS,
670 const LiveInterval *RHS) const {
671 if (!MRegisterInfo::isPhysicalRegister(LHS->reg)) {
672 if (!MRegisterInfo::isPhysicalRegister(RHS->reg))
673 return false; // vreg-vreg merge has no aliases!
674 std::swap(LHS, RHS);
675 }
676
677 assert(MRegisterInfo::isPhysicalRegister(LHS->reg) &&
678 MRegisterInfo::isVirtualRegister(RHS->reg) &&
679 "first interval must describe a physical register");
680
Chris Lattner4df98e52004-07-24 03:32:06 +0000681 for (const unsigned *AS = mri_->getAliasSet(LHS->reg); *AS; ++AS)
682 if (RHS->overlaps(getInterval(*AS)))
683 return true;
Alkis Evlogimenos79b0c3f2004-01-23 13:37:51 +0000684
Chris Lattner4df98e52004-07-24 03:32:06 +0000685 return false;
Alkis Evlogimenos79b0c3f2004-01-23 13:37:51 +0000686}
687
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000688LiveInterval LiveIntervals::createInterval(unsigned reg) {
Chris Lattner4df98e52004-07-24 03:32:06 +0000689 float Weight = MRegisterInfo::isPhysicalRegister(reg) ? HUGE_VAL :0.0F;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000690 return LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000691}