1 //===-- LiveIntervals.cpp - Live Interval Analysis ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // 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.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "liveintervals"
19 #include "llvm/CodeGen/LiveIntervals.h"
20 #include "llvm/Function.h"
21 #include "llvm/Analysis/LoopInfo.h"
22 #include "llvm/CodeGen/LiveVariables.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #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"
31 #include "llvm/Target/TargetRegInfo.h"
32 #include "llvm/Support/CFG.h"
33 #include "Support/Debug.h"
34 #include "Support/DepthFirstIterator.h"
35 #include "Support/Statistic.h"
43 RegisterAnalysis<LiveIntervals> X("liveintervals",
44 "Live Interval Analysis");
46 Statistic<> numIntervals("liveintervals", "Number of intervals");
49 void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const
51 AU.addPreserved<LiveVariables>();
52 AU.addRequired<LiveVariables>();
53 AU.addPreservedID(PHIEliminationID);
54 AU.addRequiredID(PHIEliminationID);
55 AU.addRequiredID(TwoAddressInstructionPassID);
56 AU.addRequired<LoopInfo>();
57 MachineFunctionPass::getAnalysisUsage(AU);
60 /// runOnMachineFunction - Register allocate the whole function
62 bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
63 DEBUG(std::cerr << "Machine Function\n");
65 tm_ = &fn.getTarget();
66 mri_ = tm_->getRegisterInfo();
67 lv_ = &getAnalysis<LiveVariables>();
68 allocatableRegisters_.clear();
75 // mark allocatable registers
76 allocatableRegisters_.resize(MRegisterInfo::FirstVirtualRegister);
77 // Loop over all of the register classes...
78 for (MRegisterInfo::regclass_iterator
79 rci = mri_->regclass_begin(), rce = mri_->regclass_end();
81 // Loop over all of the allocatable registers in the function...
82 for (TargetRegisterClass::iterator
83 i = (*rci)->allocation_order_begin(*mf_),
84 e = (*rci)->allocation_order_end(*mf_); i != e; ++i) {
85 allocatableRegisters_[*i] = true; // The reg is allocatable!
89 // number MachineInstrs
91 for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
92 mbb != mbbEnd; ++mbb) {
93 const std::pair<MachineBasicBlock*, unsigned>& entry =
94 lv_->getMachineBasicBlockInfo(&*mbb);
95 bool inserted = mbbi2mbbMap_.insert(std::make_pair(entry.second,
97 assert(inserted && "multiple index -> MachineBasicBlock");
99 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
101 inserted = mi2iMap_.insert(std::make_pair(*mi, miIndex)).second;
102 assert(inserted && "multiple MachineInstr -> index mappings");
112 void LiveIntervals::printRegName(unsigned reg) const
114 if (reg < MRegisterInfo::FirstVirtualRegister)
115 std::cerr << mri_->getName(reg);
117 std::cerr << '%' << reg;
120 void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock* mbb,
121 MachineBasicBlock::iterator mi,
124 DEBUG(std::cerr << "\t\t\tregister: ";printRegName(reg); std::cerr << '\n');
126 unsigned instrIndex = getInstructionIndex(*mi);
128 LiveVariables::VarInfo& vi = lv_->getVarInfo(reg);
130 Interval* interval = 0;
131 Reg2IntervalMap::iterator r2iit = r2iMap_.find(reg);
132 if (r2iit == r2iMap_.end()) {
134 intervals_.push_back(Interval(reg));
135 // update interval index for this register
136 r2iMap_[reg] = intervals_.size() - 1;
137 interval = &intervals_.back();
140 interval = &intervals_[r2iit->second];
143 for (MbbIndex2MbbMap::iterator
144 it = mbbi2mbbMap_.begin(), itEnd = mbbi2mbbMap_.end();
146 unsigned liveBlockIndex = it->first;
147 MachineBasicBlock* liveBlock = it->second;
148 if (liveBlockIndex < vi.AliveBlocks.size() &&
149 vi.AliveBlocks[liveBlockIndex] &&
150 !liveBlock->empty()) {
151 unsigned start = getInstructionIndex(liveBlock->front());
152 unsigned end = getInstructionIndex(liveBlock->back()) + 1;
153 interval->addRange(start, end);
157 bool killedInDefiningBasicBlock = false;
158 for (int i = 0, e = vi.Kills.size(); i != e; ++i) {
159 MachineBasicBlock* killerBlock = vi.Kills[i].first;
160 MachineInstr* killerInstr = vi.Kills[i].second;
161 unsigned start = (mbb == killerBlock ?
163 getInstructionIndex(killerBlock->front()));
164 unsigned end = getInstructionIndex(killerInstr) + 1;
166 killedInDefiningBasicBlock |= mbb == killerBlock;
167 interval->addRange(start, end);
171 if (!killedInDefiningBasicBlock) {
172 unsigned end = getInstructionIndex(mbb->back()) + 1;
173 interval->addRange(instrIndex, end);
177 void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock* mbb,
178 MachineBasicBlock::iterator mi,
181 DEBUG(std::cerr << "\t\t\tregister: ";printRegName(reg); std::cerr << '\n');
182 if (!lv_->getAllocatablePhysicalRegisters()[reg]) {
183 DEBUG(std::cerr << "\t\t\t\tnon allocatable register: ignoring\n");
187 unsigned start = getInstructionIndex(*mi);
188 unsigned end = start;
190 for (MachineBasicBlock::iterator e = mbb->end(); mi != e; ++mi) {
191 for (LiveVariables::killed_iterator
192 ki = lv_->dead_begin(*mi),
193 ke = lv_->dead_end(*mi);
195 if (reg == ki->second) {
196 end = getInstructionIndex(ki->first) + 1;
201 for (LiveVariables::killed_iterator
202 ki = lv_->killed_begin(*mi),
203 ke = lv_->killed_end(*mi);
205 if (reg == ki->second) {
206 end = getInstructionIndex(ki->first) + 1;
212 assert(start < end && "did not find end of interval?");
214 Reg2IntervalMap::iterator r2iit = r2iMap_.find(reg);
215 if (r2iit != r2iMap_.end()) {
216 unsigned ii = r2iit->second;
217 Interval& interval = intervals_[ii];
218 interval.addRange(start, end);
221 intervals_.push_back(Interval(reg));
222 Interval& interval = intervals_.back();
223 // update interval index for this register
224 r2iMap_[reg] = intervals_.size() - 1;
225 interval.addRange(start, end);
229 void LiveIntervals::handleRegisterDef(MachineBasicBlock* mbb,
230 MachineBasicBlock::iterator mi,
233 if (reg < MRegisterInfo::FirstVirtualRegister) {
234 if (allocatableRegisters_[reg]) {
235 handlePhysicalRegisterDef(mbb, mi, reg);
239 handleVirtualRegisterDef(mbb, mi, reg);
243 unsigned LiveIntervals::getInstructionIndex(MachineInstr* instr) const
245 assert(mi2iMap_.find(instr) != mi2iMap_.end() &&
246 "instruction not assigned a number");
247 return mi2iMap_.find(instr)->second;
250 /// computeIntervals - computes the live intervals for virtual
251 /// registers. for some ordering of the machine instructions [1,N] a
252 /// live interval is an interval [i, j] where 1 <= i <= j <= N for
253 /// which a variable is live
254 void LiveIntervals::computeIntervals()
256 DEBUG(std::cerr << "computing live intervals:\n");
258 const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
260 for (MbbIndex2MbbMap::iterator
261 it = mbbi2mbbMap_.begin(), itEnd = mbbi2mbbMap_.end();
263 MachineBasicBlock* mbb = it->second;
264 DEBUG(std::cerr << "machine basic block: "
265 << mbb->getBasicBlock()->getName() << "\n");
267 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
269 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
271 MachineInstr* instr = *mi;
272 const TargetInstrDescriptor& tid =
273 tm_->getInstrInfo().get(instr->getOpcode());
274 DEBUG(std::cerr << "\t\tinstruction["
275 << getInstructionIndex(instr) << "]: ";
276 instr->print(std::cerr, *tm_););
278 // handle implicit defs
279 for (const unsigned* id = tid.ImplicitDefs; *id; ++id) {
280 unsigned physReg = *id;
281 handlePhysicalRegisterDef(mbb, mi, physReg);
284 // handle explicit defs
285 for (int i = instr->getNumOperands() - 1; i >= 0; --i) {
286 MachineOperand& mop = instr->getOperand(i);
288 if (!mop.isRegister())
291 unsigned reg = mop.getAllocatedRegNum();
292 // handle defs - build intervals
294 if (reg < MRegisterInfo::FirstVirtualRegister)
295 handlePhysicalRegisterDef(mbb, mi, reg);
297 handleVirtualRegisterDef(mbb, mi, reg);
301 Reg2IntervalMap::iterator r2iit = r2iMap_.find(reg);
302 if (r2iit != r2iMap_.end() &&
303 reg >= MRegisterInfo::FirstVirtualRegister)
304 intervals_[r2iit->second].weight += pow(10.0F, loopDepth);
309 std::sort(intervals_.begin(), intervals_.end(), StartPointComp());
310 DEBUG(std::copy(intervals_.begin(), intervals_.end(),
311 std::ostream_iterator<Interval>(std::cerr, "\n")));
314 LiveIntervals::Interval::Interval(unsigned r)
316 weight((r < MRegisterInfo::FirstVirtualRegister ?
317 std::numeric_limits<float>::max() : 0.0F))
322 void LiveIntervals::Interval::addRange(unsigned start, unsigned end)
324 DEBUG(std::cerr << "\t\t\t\tadding range: [" << start <<','<< end << "]\n");
325 //assert(start < end && "invalid range?");
326 Range range = std::make_pair(start, end);
327 Ranges::iterator it =
328 ranges.insert(std::upper_bound(ranges.begin(), ranges.end(), range),
331 DEBUG(std::cerr << "\t\t\t\tbefore merge forward: " << *this << '\n');
332 mergeRangesForward(it);
333 DEBUG(std::cerr << "\t\t\t\tbefore merge backward: " << *this << '\n');
334 mergeRangesBackward(it);
335 DEBUG(std::cerr << "\t\t\t\tafter merging: " << *this << '\n');
338 void LiveIntervals::Interval::mergeRangesForward(Ranges::iterator it)
340 for (Ranges::iterator next = it + 1;
341 next != ranges.end() && it->second >= next->first; ) {
342 it->second = std::max(it->second, next->second);
343 next = ranges.erase(next);
347 void LiveIntervals::Interval::mergeRangesBackward(Ranges::iterator it)
349 for (Ranges::iterator prev = it - 1;
350 it != ranges.begin() && it->first <= prev->second; ) {
351 it->first = std::min(it->first, prev->first);
352 it->second = std::max(it->second, prev->second);
353 it = ranges.erase(prev);
358 bool LiveIntervals::Interval::liveAt(unsigned index) const
360 Ranges::const_iterator r = ranges.begin();
361 while (r != ranges.end() && index < r->second) {
362 if (index >= r->first)
369 bool LiveIntervals::Interval::overlaps(const Interval& other) const
371 std::vector<bool> bitMap(end(), false);
372 for (Ranges::const_iterator r = ranges.begin(); r != ranges.end(); ++r) {
373 for (unsigned i = r->first; i < r->second; ++i)
376 for (Ranges::const_iterator r = other.ranges.begin();
377 r != other.ranges.end(); ++r) {
378 for (unsigned i = r->first;
379 i < r->second && i < bitMap.size(); ++i)
387 std::ostream& llvm::operator<<(std::ostream& os,
388 const LiveIntervals::Interval& li)
390 os << "%reg" << li.reg << ',' << li.weight << " = ";
391 for (LiveIntervals::Interval::Ranges::const_iterator
392 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
393 os << "[" << i->first << "," << i->second << "]";