blob: 6cf95d20903eeb2eabd0cb7d8bb75f077ac40af3 [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 Evlogimenosff0cbe12003-11-20 03:32:25 +000090
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000091 // number MachineInstrs
92 unsigned miIndex = 0;
93 for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
94 mbb != mbbEnd; ++mbb)
95 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
96 mi != miEnd; ++mi) {
97 bool inserted = mi2iMap_.insert(std::make_pair(mi, miIndex)).second;
98 assert(inserted && "multiple MachineInstr -> index mappings");
99 i2miMap_.push_back(mi);
100 miIndex += InstrSlots::NUM;
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000101 }
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000102
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000103 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000104
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000105 numIntervals += getNumIntervals();
106
107#if 1
108 DEBUG(std::cerr << "********** INTERVALS **********\n");
109 DEBUG(for (iterator I = begin(), E = end(); I != E; ++I)
110 std::cerr << I->second << "\n");
111#endif
112
113 // join intervals if requested
114 if (EnableJoining) joinIntervals();
115
116 numIntervalsAfter += getNumIntervals();
117
118 // perform a final pass over the instructions and compute spill
119 // weights, coalesce virtual registers and remove identity moves
120 const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
121 const TargetInstrInfo& tii = *tm_->getInstrInfo();
122
123 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
124 mbbi != mbbe; ++mbbi) {
125 MachineBasicBlock* mbb = mbbi;
126 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
127
128 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
129 mii != mie; ) {
130 // if the move will be an identity move delete it
131 unsigned srcReg, dstReg, RegRep;
132 if (tii.isMoveInstr(*mii, srcReg, dstReg) &&
133 (RegRep = rep(srcReg)) == rep(dstReg)) {
134 // remove from def list
135 LiveInterval &interval = getOrCreateInterval(RegRep);
136 // remove index -> MachineInstr and
137 // MachineInstr -> index mappings
138 Mi2IndexMap::iterator mi2i = mi2iMap_.find(mii);
139 if (mi2i != mi2iMap_.end()) {
140 i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
141 mi2iMap_.erase(mi2i);
142 }
143 mii = mbbi->erase(mii);
144 ++numPeep;
145 }
146 else {
147 for (unsigned i = 0; i < mii->getNumOperands(); ++i) {
148 const MachineOperand& mop = mii->getOperand(i);
149 if (mop.isRegister() && mop.getReg() &&
150 MRegisterInfo::isVirtualRegister(mop.getReg())) {
151 // replace register with representative register
152 unsigned reg = rep(mop.getReg());
153 mii->SetMachineOperandReg(i, reg);
154
155 LiveInterval &RegInt = getInterval(reg);
156 RegInt.weight +=
157 (mop.isUse() + mop.isDef()) * pow(10.0F, loopDepth);
158 }
159 }
160 ++mii;
161 }
162 }
163 }
164
165 DEBUG(std::cerr << "********** INTERVALS **********\n");
166 DEBUG (for (iterator I = begin(), E = end(); I != E; ++I)
167 std::cerr << I->second << "\n");
168 DEBUG(std::cerr << "********** MACHINEINSTRS **********\n");
169 DEBUG(
170 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
171 mbbi != mbbe; ++mbbi) {
172 std::cerr << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
173 for (MachineBasicBlock::iterator mii = mbbi->begin(),
174 mie = mbbi->end(); mii != mie; ++mii) {
175 std::cerr << getInstructionIndex(mii) << '\t';
176 mii->print(std::cerr, tm_);
177 }
178 });
179
180 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000181}
182
Chris Lattner418da552004-06-21 13:10:56 +0000183std::vector<LiveInterval*> LiveIntervals::addIntervalsForSpills(
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000184 const LiveInterval& li,
185 VirtRegMap& vrm,
186 int slot)
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000187{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000188 std::vector<LiveInterval*> added;
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000189
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000190 assert(li.weight != HUGE_VAL &&
191 "attempt to spill already spilled interval!");
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000192
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000193 DEBUG(std::cerr << "\t\t\t\tadding intervals for spills for interval: "
194 << li << '\n');
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000195
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000196 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg);
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000197
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000198 for (LiveInterval::Ranges::const_iterator
199 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
200 unsigned index = getBaseIndex(i->start);
201 unsigned end = getBaseIndex(i->end-1) + InstrSlots::NUM;
202 for (; index != end; index += InstrSlots::NUM) {
203 // skip deleted instructions
204 while (index != end && !getInstructionFromIndex(index))
205 index += InstrSlots::NUM;
206 if (index == end) break;
Chris Lattner8640f4e2004-07-19 15:16:53 +0000207
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000208 MachineBasicBlock::iterator mi = getInstructionFromIndex(index);
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000209
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000210 for_operand:
211 for (unsigned i = 0; i != mi->getNumOperands(); ++i) {
212 MachineOperand& mop = mi->getOperand(i);
213 if (mop.isRegister() && mop.getReg() == li.reg) {
214 if (MachineInstr* fmi =
215 mri_->foldMemoryOperand(mi, i, slot)) {
216 lv_->instructionChanged(mi, fmi);
217 vrm.virtFolded(li.reg, mi, fmi);
218 mi2iMap_.erase(mi);
219 i2miMap_[index/InstrSlots::NUM] = fmi;
220 mi2iMap_[fmi] = index;
221 MachineBasicBlock& mbb = *mi->getParent();
222 mi = mbb.insert(mbb.erase(mi), fmi);
223 ++numFolded;
224 goto for_operand;
225 }
226 else {
227 // This is tricky. We need to add information in
228 // the interval about the spill code so we have to
229 // use our extra load/store slots.
230 //
231 // If we have a use we are going to have a load so
232 // we start the interval from the load slot
233 // onwards. Otherwise we start from the def slot.
234 unsigned start = (mop.isUse() ?
235 getLoadIndex(index) :
236 getDefIndex(index));
237 // If we have a def we are going to have a store
238 // right after it so we end the interval after the
239 // use of the next instruction. Otherwise we end
240 // after the use of this instruction.
241 unsigned end = 1 + (mop.isDef() ?
242 getStoreIndex(index) :
243 getUseIndex(index));
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000244
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000245 // create a new register for this spill
246 unsigned nReg =
247 mf_->getSSARegMap()->createVirtualRegister(rc);
248 mi->SetMachineOperandReg(i, nReg);
249 vrm.grow();
250 vrm.assignVirt2StackSlot(nReg, slot);
251 LiveInterval& nI = getOrCreateInterval(nReg);
252 assert(nI.empty());
253 // the spill weight is now infinity as it
254 // cannot be spilled again
255 nI.weight = HUGE_VAL;
256 LiveRange LR(start, end, nI.getNextValue());
257 DEBUG(std::cerr << " +" << LR);
258 nI.addRange(LR);
259 added.push_back(&nI);
260 // update live variables
261 lv_->addVirtualRegisterKilled(nReg, mi);
262 DEBUG(std::cerr << "\t\t\t\tadded new interval: "
263 << nI << '\n');
264 }
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000265 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000266 }
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000267 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000268 }
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000269
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000270 return added;
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000271}
272
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000273void LiveIntervals::printRegName(unsigned reg) const
274{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000275 if (MRegisterInfo::isPhysicalRegister(reg))
276 std::cerr << mri_->getName(reg);
277 else
278 std::cerr << "%reg" << reg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000279}
280
281void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
282 MachineBasicBlock::iterator mi,
Chris Lattner418da552004-06-21 13:10:56 +0000283 LiveInterval& interval)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000284{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000285 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
286 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000287
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000288 // Virtual registers may be defined multiple times (due to phi
289 // elimination and 2-addr elimination). Much of what we do only has to be
290 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000291 // time we see a vreg.
292 if (interval.empty()) {
293 // Get the Idx of the defining instructions.
294 unsigned defIndex = getDefIndex(getInstructionIndex(mi));
Chris Lattner6097d132004-07-19 02:15:56 +0000295
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000296 unsigned ValNum = interval.getNextValue();
297 assert(ValNum == 0 && "First value in interval is not 0?");
298 ValNum = 0; // Clue in the optimizer.
Chris Lattner7ac2d312004-07-24 02:59:07 +0000299
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000300 // Loop over all of the blocks that the vreg is defined in. There are
301 // two cases we have to handle here. The most common case is a vreg
302 // whose lifetime is contained within a basic block. In this case there
303 // will be a single kill, in MBB, which comes after the definition.
304 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
305 // FIXME: what about dead vars?
306 unsigned killIdx;
307 if (vi.Kills[0] != mi)
308 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
309 else
310 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000311
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000312 // If the kill happens after the definition, we have an intra-block
313 // live range.
314 if (killIdx > defIndex) {
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000315 assert(vi.AliveBlocks.empty() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000316 "Shouldn't be alive across any blocks!");
317 LiveRange LR(defIndex, killIdx, ValNum);
318 interval.addRange(LR);
319 DEBUG(std::cerr << " +" << LR << "\n");
320 return;
321 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000322 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000323
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000324 // The other case we handle is when a virtual register lives to the end
325 // of the defining block, potentially live across some blocks, then is
326 // live into some number of blocks, but gets killed. Start by adding a
327 // range that goes from this definition to the end of the defining block.
328 LiveRange NewLR(defIndex, getInstructionIndex(&mbb->back()) +
329 InstrSlots::NUM, ValNum);
330 DEBUG(std::cerr << " +" << NewLR);
331 interval.addRange(NewLR);
332
333 // Iterate over all of the blocks that the variable is completely
334 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
335 // live interval.
336 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
337 if (vi.AliveBlocks[i]) {
338 MachineBasicBlock* mbb = mf_->getBlockNumbered(i);
339 if (!mbb->empty()) {
340 LiveRange LR(getInstructionIndex(&mbb->front()),
341 getInstructionIndex(&mbb->back())+InstrSlots::NUM,
342 ValNum);
343 interval.addRange(LR);
344 DEBUG(std::cerr << " +" << LR);
345 }
346 }
347 }
348
349 // Finally, this virtual register is live from the start of any killing
350 // block to the 'use' slot of the killing instruction.
351 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
352 MachineInstr *Kill = vi.Kills[i];
353 LiveRange LR(getInstructionIndex(Kill->getParent()->begin()),
354 getUseIndex(getInstructionIndex(Kill))+1, ValNum);
355 interval.addRange(LR);
356 DEBUG(std::cerr << " +" << LR);
357 }
358
359 } else {
360 // If this is the second time we see a virtual register definition, it
361 // must be due to phi elimination or two addr elimination. If this is
362 // the result of two address elimination, then the vreg is the first
363 // operand, and is a def-and-use.
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000364 if (mi->getOperand(0).isRegister() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000365 mi->getOperand(0).getReg() == interval.reg &&
366 mi->getOperand(0).isDef() && mi->getOperand(0).isUse()) {
367 // If this is a two-address definition, then we have already processed
368 // the live range. The only problem is that we didn't realize there
369 // are actually two values in the live interval. Because of this we
370 // need to take the LiveRegion that defines this register and split it
371 // into two values.
372 unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
373 unsigned RedefIndex = getDefIndex(getInstructionIndex(mi));
374
375 // Delete the initial value, which should be short and continuous,
376 // becuase the 2-addr copy must be in the same MBB as the redef.
377 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000378
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000379 LiveRange LR(DefIndex, RedefIndex, interval.getNextValue());
380 DEBUG(std::cerr << " replace range with " << LR);
381 interval.addRange(LR);
382
383 // If this redefinition is dead, we need to add a dummy unit live
384 // range covering the def slot.
385 for (LiveVariables::killed_iterator KI = lv_->dead_begin(mi),
386 E = lv_->dead_end(mi); KI != E; ++KI)
387 if (KI->second == interval.reg) {
388 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, 0));
389 break;
390 }
391
392 DEBUG(std::cerr << "RESULT: " << interval);
393
394 } else {
395 // Otherwise, this must be because of phi elimination. If this is the
396 // first redefinition of the vreg that we have seen, go back and change
397 // the live range in the PHI block to be a different value number.
398 if (interval.containsOneValue()) {
399 assert(vi.Kills.size() == 1 &&
400 "PHI elimination vreg should have one kill, the PHI itself!");
401
402 // Remove the old range that we now know has an incorrect number.
403 MachineInstr *Killer = vi.Kills[0];
404 unsigned Start = getInstructionIndex(Killer->getParent()->begin());
405 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
406 DEBUG(std::cerr << "Removing [" << Start << "," << End << "] from: "
407 << interval << "\n");
408 interval.removeRange(Start, End);
409 DEBUG(std::cerr << "RESULT: " << interval);
410
411 // Replace the interval with one of a NEW value number.
412 LiveRange LR(Start, End, interval.getNextValue());
413 DEBUG(std::cerr << " replace range with " << LR);
414 interval.addRange(LR);
415 DEBUG(std::cerr << "RESULT: " << interval);
416 }
417
418 // In the case of PHI elimination, each variable definition is only
419 // live until the end of the block. We've already taken care of the
420 // rest of the live range.
421 unsigned defIndex = getDefIndex(getInstructionIndex(mi));
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000422 LiveRange LR(defIndex,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000423 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
424 interval.getNextValue());
425 interval.addRange(LR);
426 DEBUG(std::cerr << " +" << LR);
427 }
428 }
429
430 DEBUG(std::cerr << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000431}
432
Chris Lattnerf35fef72004-07-23 21:24:19 +0000433void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000434 MachineBasicBlock::iterator mi,
Chris Lattner418da552004-06-21 13:10:56 +0000435 LiveInterval& interval)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000436{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000437 // A physical register cannot be live across basic block, so its
438 // lifetime must end somewhere in its defining basic block.
439 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
440 typedef LiveVariables::killed_iterator KillIter;
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000441
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000442 unsigned baseIndex = getInstructionIndex(mi);
443 unsigned start = getDefIndex(baseIndex);
444 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000445
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000446 // If it is not used after definition, it is considered dead at
447 // the instruction defining it. Hence its interval is:
448 // [defSlot(def), defSlot(def)+1)
449 for (KillIter ki = lv_->dead_begin(mi), ke = lv_->dead_end(mi);
450 ki != ke; ++ki) {
451 if (interval.reg == ki->second) {
452 DEBUG(std::cerr << " dead");
453 end = getDefIndex(start) + 1;
454 goto exit;
455 }
456 }
457
458 // If it is not dead on definition, it must be killed by a
459 // subsequent instruction. Hence its interval is:
460 // [defSlot(def), useSlot(kill)+1)
461 while (true) {
462 ++mi;
463 assert(mi != MBB->end() && "physreg was not killed in defining block!");
464 baseIndex += InstrSlots::NUM;
465 for (KillIter ki = lv_->killed_begin(mi), ke = lv_->killed_end(mi);
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000466 ki != ke; ++ki) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000467 if (interval.reg == ki->second) {
468 DEBUG(std::cerr << " killed");
469 end = getUseIndex(baseIndex) + 1;
470 goto exit;
471 }
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000472 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000473 }
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000474
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000475exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000476 assert(start < end && "did not find end of interval?");
477 LiveRange LR(start, end, interval.getNextValue());
478 interval.addRange(LR);
479 DEBUG(std::cerr << " +" << LR << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000480}
481
Chris Lattnerf35fef72004-07-23 21:24:19 +0000482void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
483 MachineBasicBlock::iterator MI,
484 unsigned reg) {
485 if (MRegisterInfo::isVirtualRegister(reg))
486 handleVirtualRegisterDef(MBB, MI, getOrCreateInterval(reg));
487 else if (lv_->getAllocatablePhysicalRegisters()[reg]) {
488 handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(reg));
489 for (const unsigned* AS = mri_->getAliasSet(reg); *AS; ++AS)
490 handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(*AS));
491 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000492}
493
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000494/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000495/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000496/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000497/// which a variable is live
498void LiveIntervals::computeIntervals()
499{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000500 DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
501 DEBUG(std::cerr << "********** Function: "
502 << ((Value*)mf_->getFunction())->getName() << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000503
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000504 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000505 I != E; ++I) {
506 MachineBasicBlock* mbb = I;
507 DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n");
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000508
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000509 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
510 mi != miEnd; ++mi) {
511 const TargetInstrDescriptor& tid =
512 tm_->getInstrInfo()->get(mi->getOpcode());
513 DEBUG(std::cerr << getInstructionIndex(mi) << "\t";
514 mi->print(std::cerr, tm_));
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000515
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000516 // handle implicit defs
517 for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
518 handleRegisterDef(mbb, mi, *id);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000519
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000520 // handle explicit defs
521 for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
522 MachineOperand& mop = mi->getOperand(i);
523 // handle register defs - build intervals
524 if (mop.isRegister() && mop.getReg() && mop.isDef())
525 handleRegisterDef(mbb, mi, mop.getReg());
526 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000527 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000528 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000529}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000530
Chris Lattner1c5c0442004-07-19 14:08:10 +0000531void LiveIntervals::joinIntervalsInMachineBB(MachineBasicBlock *MBB) {
Chris Lattner7ac2d312004-07-24 02:59:07 +0000532 DEBUG(std::cerr << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
533 const TargetInstrInfo &TII = *tm_->getInstrInfo();
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000534
Chris Lattner7ac2d312004-07-24 02:59:07 +0000535 for (MachineBasicBlock::iterator mi = MBB->begin(), mie = MBB->end();
536 mi != mie; ++mi) {
537 DEBUG(std::cerr << getInstructionIndex(mi) << '\t' << *mi);
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000538
Chris Lattner7ac2d312004-07-24 02:59:07 +0000539 // we only join virtual registers with allocatable
540 // physical registers since we do not have liveness information
541 // on not allocatable physical registers
542 unsigned regA, regB;
543 if (TII.isMoveInstr(*mi, regA, regB) &&
544 (MRegisterInfo::isVirtualRegister(regA) ||
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000545 lv_->getAllocatablePhysicalRegisters()[regA]) &&
Chris Lattner7ac2d312004-07-24 02:59:07 +0000546 (MRegisterInfo::isVirtualRegister(regB) ||
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000547 lv_->getAllocatablePhysicalRegisters()[regB])) {
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000548
Chris Lattner7ac2d312004-07-24 02:59:07 +0000549 // Get representative registers.
550 regA = rep(regA);
551 regB = rep(regB);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000552
Chris Lattner7ac2d312004-07-24 02:59:07 +0000553 // If they are already joined we continue.
554 if (regA == regB)
555 continue;
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000556
Chris Lattner7ac2d312004-07-24 02:59:07 +0000557 // If they are both physical registers, we cannot join them.
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000558 if (MRegisterInfo::isPhysicalRegister(regA) &&
Chris Lattner7ac2d312004-07-24 02:59:07 +0000559 MRegisterInfo::isPhysicalRegister(regB))
560 continue;
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000561
Chris Lattner7ac2d312004-07-24 02:59:07 +0000562 // If they are not of the same register class, we cannot join them.
563 if (differingRegisterClasses(regA, regB))
564 continue;
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000565
Chris Lattner7ac2d312004-07-24 02:59:07 +0000566 LiveInterval &IntA = getInterval(regA);
567 LiveInterval &IntB = getInterval(regB);
568 assert(IntA.reg == regA && IntB.reg == regB &&
569 "Register mapping is horribly broken!");
Chris Lattner060913c2004-07-24 04:32:22 +0000570
571 DEBUG(std::cerr << "\t\tInspecting " << IntA << " and " << IntB << ": ");
572
Chris Lattner4df98e52004-07-24 03:32:06 +0000573 // If two intervals contain a single value and are joined by a copy, it
574 // does not matter if the intervals overlap, they can always be joined.
Chris Lattner7ac2d312004-07-24 02:59:07 +0000575 bool TriviallyJoinable =
576 IntA.containsOneValue() && IntB.containsOneValue();
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000577
Chris Lattner7ac2d312004-07-24 02:59:07 +0000578 unsigned MIDefIdx = getDefIndex(getInstructionIndex(mi));
Chris Lattnerc25b55a2004-07-25 07:47:25 +0000579 if ((TriviallyJoinable || IntB.joinable(IntA, MIDefIdx)) &&
Chris Lattner7ac2d312004-07-24 02:59:07 +0000580 !overlapsAliases(&IntA, &IntB)) {
581 IntB.join(IntA, MIDefIdx);
Chris Lattner1c5c0442004-07-19 14:08:10 +0000582
Chris Lattner7ac2d312004-07-24 02:59:07 +0000583 if (!MRegisterInfo::isPhysicalRegister(regA)) {
Chris Lattner4df98e52004-07-24 03:32:06 +0000584 r2iMap_.erase(regA);
Chris Lattner7ac2d312004-07-24 02:59:07 +0000585 r2rMap_[regA] = regB;
586 } else {
587 // Otherwise merge the data structures the other way so we don't lose
588 // the physreg information.
589 r2rMap_[regB] = regA;
590 IntB.reg = regA;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000591 IntA.swap(IntB);
Chris Lattner4df98e52004-07-24 03:32:06 +0000592 r2iMap_.erase(regB);
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000593 }
Chris Lattner7ac2d312004-07-24 02:59:07 +0000594 DEBUG(std::cerr << "Joined. Result = " << IntB << "\n");
595 ++numJoins;
596 } else {
597 DEBUG(std::cerr << "Interference!\n");
598 }
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000599 }
Chris Lattner7ac2d312004-07-24 02:59:07 +0000600 }
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000601}
602
Chris Lattnercc0d1562004-07-19 14:40:29 +0000603namespace {
604 // DepthMBBCompare - Comparison predicate that sort first based on the loop
605 // depth of the basic block (the unsigned), and then on the MBB number.
606 struct DepthMBBCompare {
607 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
608 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
609 if (LHS.first > RHS.first) return true; // Deeper loops first
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000610 return LHS.first == RHS.first &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000611 LHS.second->getNumber() < RHS.second->getNumber();
Chris Lattnercc0d1562004-07-19 14:40:29 +0000612 }
613 };
614}
Chris Lattner1c5c0442004-07-19 14:08:10 +0000615
Chris Lattnercc0d1562004-07-19 14:40:29 +0000616void LiveIntervals::joinIntervals() {
617 DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
618
619 const LoopInfo &LI = getAnalysis<LoopInfo>();
620 if (LI.begin() == LI.end()) {
621 // If there are no loops in the function, join intervals in function order.
Chris Lattner1c5c0442004-07-19 14:08:10 +0000622 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
623 I != E; ++I)
624 joinIntervalsInMachineBB(I);
Chris Lattnercc0d1562004-07-19 14:40:29 +0000625 } else {
626 // Otherwise, join intervals in inner loops before other intervals.
627 // Unfortunately we can't just iterate over loop hierarchy here because
628 // there may be more MBB's than BB's. Collect MBB's for sorting.
629 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
630 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
631 I != E; ++I)
632 MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
633
634 // Sort by loop depth.
635 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
636
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000637 // Finally, join intervals in loop nest order.
Chris Lattnercc0d1562004-07-19 14:40:29 +0000638 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
639 joinIntervalsInMachineBB(MBBs[i].second);
640 }
Chris Lattnerc83e40d2004-07-25 03:24:11 +0000641
642 DEBUG(std::cerr << "*** Register mapping ***\n");
643 DEBUG(for (std::map<unsigned, unsigned>::iterator I = r2rMap_.begin(),
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000644 E = r2rMap_.end(); I != E; ++I)
645 std::cerr << " reg " << I->first << " -> reg " << I->second << "\n";);
Chris Lattner1c5c0442004-07-19 14:08:10 +0000646}
647
Chris Lattner7ac2d312004-07-24 02:59:07 +0000648/// Return true if the two specified registers belong to different register
649/// classes. The registers may be either phys or virt regs.
650bool LiveIntervals::differingRegisterClasses(unsigned RegA,
651 unsigned RegB) const {
652 const TargetRegisterClass *RegClass;
Alkis Evlogimenos79b0c3f2004-01-23 13:37:51 +0000653
Chris Lattner7ac2d312004-07-24 02:59:07 +0000654 // Get the register classes for the first reg.
655 if (MRegisterInfo::isVirtualRegister(RegA))
656 RegClass = mf_->getSSARegMap()->getRegClass(RegA);
657 else
658 RegClass = mri_->getRegClass(RegA);
659
660 // Compare against the regclass for the second reg.
661 if (MRegisterInfo::isVirtualRegister(RegB))
662 return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
663 else
Chris Lattnerd0d0a1a2004-08-24 17:48:29 +0000664 return !RegClass->contains(RegB);
Chris Lattner7ac2d312004-07-24 02:59:07 +0000665}
666
667bool LiveIntervals::overlapsAliases(const LiveInterval *LHS,
668 const LiveInterval *RHS) const {
669 if (!MRegisterInfo::isPhysicalRegister(LHS->reg)) {
670 if (!MRegisterInfo::isPhysicalRegister(RHS->reg))
671 return false; // vreg-vreg merge has no aliases!
672 std::swap(LHS, RHS);
673 }
674
675 assert(MRegisterInfo::isPhysicalRegister(LHS->reg) &&
676 MRegisterInfo::isVirtualRegister(RHS->reg) &&
677 "first interval must describe a physical register");
678
Chris Lattner4df98e52004-07-24 03:32:06 +0000679 for (const unsigned *AS = mri_->getAliasSet(LHS->reg); *AS; ++AS)
680 if (RHS->overlaps(getInterval(*AS)))
681 return true;
Alkis Evlogimenos79b0c3f2004-01-23 13:37:51 +0000682
Chris Lattner4df98e52004-07-24 03:32:06 +0000683 return false;
Alkis Evlogimenos79b0c3f2004-01-23 13:37:51 +0000684}
685
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000686LiveInterval LiveIntervals::createInterval(unsigned reg) {
Chris Lattner4df98e52004-07-24 03:32:06 +0000687 float Weight = MRegisterInfo::isPhysicalRegister(reg) ? HUGE_VAL :0.0F;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000688 return LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000689}