blob: e9bdaa11c81a56e3928353abc4ec4f490c439826 [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 Lattner3c3fe462005-09-21 04:19:09 +000019#include "llvm/CodeGen/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>
Chris Lattner2c2c6c62006-01-22 23:41:00 +000037#include <iostream>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000038using namespace llvm;
39
40namespace {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000041 RegisterAnalysis<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000042
Andrew Lenharthed41f1b2006-07-20 17:28:38 +000043 static Statistic<> numIntervals
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000044 ("liveintervals", "Number of original intervals");
Alkis Evlogimenos007726c2004-02-20 20:53:26 +000045
Andrew Lenharthed41f1b2006-07-20 17:28:38 +000046 static Statistic<> numIntervalsAfter
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000047 ("liveintervals", "Number of intervals after coalescing");
Alkis Evlogimenos007726c2004-02-20 20:53:26 +000048
Andrew Lenharthed41f1b2006-07-20 17:28:38 +000049 static Statistic<> numJoins
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000050 ("liveintervals", "Number of interval joins performed");
Alkis Evlogimenos007726c2004-02-20 20:53:26 +000051
Andrew Lenharthed41f1b2006-07-20 17:28:38 +000052 static Statistic<> numPeep
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000053 ("liveintervals", "Number of identity moves eliminated after coalescing");
Alkis Evlogimenos007726c2004-02-20 20:53:26 +000054
Andrew Lenharthed41f1b2006-07-20 17:28:38 +000055 static Statistic<> numFolded
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000056 ("liveintervals", "Number of loads/stores folded into instructions");
Alkis Evlogimenos007726c2004-02-20 20:53:26 +000057
Andrew Lenharthed41f1b2006-07-20 17:28:38 +000058 static cl::opt<bool>
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000059 EnableJoining("join-liveintervals",
60 cl::desc("Join compatible live intervals"),
61 cl::init(true));
Chris Lattnerd74ea2b2006-05-24 17:04:05 +000062}
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000063
64void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const
65{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000066 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
Evan Cheng99314142006-05-11 07:29:24 +000083static bool isZeroLengthInterval(LiveInterval *li) {
84 for (LiveInterval::Ranges::const_iterator
85 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
86 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
87 return false;
88 return true;
89}
90
91
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000092/// runOnMachineFunction - Register allocate the whole function
93///
94bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000095 mf_ = &fn;
96 tm_ = &fn.getTarget();
97 mri_ = tm_->getRegisterInfo();
Chris Lattnerf768bba2005-03-09 23:05:19 +000098 tii_ = tm_->getInstrInfo();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000099 lv_ = &getAnalysis<LiveVariables>();
Alkis Evlogimenos53278012004-08-26 22:22:38 +0000100 allocatableRegs_ = mri_->getAllocatableSet(fn);
Alkis Evlogimenos2c4f7b52004-09-09 19:24:38 +0000101 r2rMap_.grow(mf_->getSSARegMap()->getLastVirtReg());
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000102
Chris Lattner799a9192005-04-09 16:17:50 +0000103 // If this function has any live ins, insert a dummy instruction at the
104 // beginning of the function that we will pretend "defines" the values. This
105 // is to make the interval analysis simpler by providing a number.
106 if (fn.livein_begin() != fn.livein_end()) {
Chris Lattner712ad0c2005-05-13 07:08:07 +0000107 unsigned FirstLiveIn = fn.livein_begin()->first;
Chris Lattner799a9192005-04-09 16:17:50 +0000108
109 // Find a reg class that contains this live in.
110 const TargetRegisterClass *RC = 0;
111 for (MRegisterInfo::regclass_iterator RCI = mri_->regclass_begin(),
112 E = mri_->regclass_end(); RCI != E; ++RCI)
113 if ((*RCI)->contains(FirstLiveIn)) {
114 RC = *RCI;
115 break;
116 }
117
118 MachineInstr *OldFirstMI = fn.begin()->begin();
119 mri_->copyRegToReg(*fn.begin(), fn.begin()->begin(),
120 FirstLiveIn, FirstLiveIn, RC);
121 assert(OldFirstMI != fn.begin()->begin() &&
122 "copyRetToReg didn't insert anything!");
123 }
124
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000125 // number MachineInstrs
126 unsigned miIndex = 0;
127 for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
128 mbb != mbbEnd; ++mbb)
129 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
130 mi != miEnd; ++mi) {
131 bool inserted = mi2iMap_.insert(std::make_pair(mi, miIndex)).second;
132 assert(inserted && "multiple MachineInstr -> index mappings");
133 i2miMap_.push_back(mi);
134 miIndex += InstrSlots::NUM;
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000135 }
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000136
Chris Lattner799a9192005-04-09 16:17:50 +0000137 // Note intervals due to live-in values.
138 if (fn.livein_begin() != fn.livein_end()) {
139 MachineBasicBlock *Entry = fn.begin();
Chris Lattner712ad0c2005-05-13 07:08:07 +0000140 for (MachineFunction::livein_iterator I = fn.livein_begin(),
Chris Lattner799a9192005-04-09 16:17:50 +0000141 E = fn.livein_end(); I != E; ++I) {
142 handlePhysicalRegisterDef(Entry, Entry->begin(),
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000143 getOrCreateInterval(I->first), 0, 0, true);
Chris Lattner712ad0c2005-05-13 07:08:07 +0000144 for (const unsigned* AS = mri_->getAliasSet(I->first); *AS; ++AS)
Chris Lattner799a9192005-04-09 16:17:50 +0000145 handlePhysicalRegisterDef(Entry, Entry->begin(),
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000146 getOrCreateInterval(*AS), 0, 0, true);
Chris Lattner799a9192005-04-09 16:17:50 +0000147 }
148 }
149
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000150 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000151
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000152 numIntervals += getNumIntervals();
153
Chris Lattner38135af2005-05-14 05:34:15 +0000154 DEBUG(std::cerr << "********** INTERVALS **********\n";
155 for (iterator I = begin(), E = end(); I != E; ++I) {
156 I->second.print(std::cerr, mri_);
157 std::cerr << "\n";
158 });
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000159
160 // join intervals if requested
161 if (EnableJoining) joinIntervals();
162
163 numIntervalsAfter += getNumIntervals();
164
165 // perform a final pass over the instructions and compute spill
166 // weights, coalesce virtual registers and remove identity moves
167 const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000168
169 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
170 mbbi != mbbe; ++mbbi) {
171 MachineBasicBlock* mbb = mbbi;
172 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
173
174 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
175 mii != mie; ) {
176 // if the move will be an identity move delete it
177 unsigned srcReg, dstReg, RegRep;
Chris Lattnerf768bba2005-03-09 23:05:19 +0000178 if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000179 (RegRep = rep(srcReg)) == rep(dstReg)) {
180 // remove from def list
181 LiveInterval &interval = getOrCreateInterval(RegRep);
182 // remove index -> MachineInstr and
183 // MachineInstr -> index mappings
184 Mi2IndexMap::iterator mi2i = mi2iMap_.find(mii);
185 if (mi2i != mi2iMap_.end()) {
186 i2miMap_[mi2i->second/InstrSlots::NUM] = 0;
187 mi2iMap_.erase(mi2i);
188 }
189 mii = mbbi->erase(mii);
190 ++numPeep;
191 }
192 else {
193 for (unsigned i = 0; i < mii->getNumOperands(); ++i) {
194 const MachineOperand& mop = mii->getOperand(i);
195 if (mop.isRegister() && mop.getReg() &&
196 MRegisterInfo::isVirtualRegister(mop.getReg())) {
197 // replace register with representative register
198 unsigned reg = rep(mop.getReg());
Chris Lattnere53f4a02006-05-04 17:52:23 +0000199 mii->getOperand(i).setReg(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000200
201 LiveInterval &RegInt = getInterval(reg);
202 RegInt.weight +=
Chris Lattner7a36ae82004-10-25 18:40:47 +0000203 (mop.isUse() + mop.isDef()) * pow(10.0F, (int)loopDepth);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000204 }
205 }
206 ++mii;
207 }
208 }
209 }
210
Evan Cheng99314142006-05-11 07:29:24 +0000211 for (iterator I = begin(), E = end(); I != E; ++I) {
212 LiveInterval &li = I->second;
213 if (MRegisterInfo::isVirtualRegister(li.reg))
214 // If the live interval legnth is essentially zero, i.e. in every live
215 // range the use follows def immediately, it doesn't make sense to spill
216 // it and hope it will be easier to allocate for this li.
217 if (isZeroLengthInterval(&li))
218 li.weight = float(HUGE_VAL);
219 }
220
Chris Lattner70ca3582004-09-30 15:59:17 +0000221 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000222 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000223}
224
Chris Lattner70ca3582004-09-30 15:59:17 +0000225/// print - Implement the dump method.
Reid Spencerce9653c2004-12-07 04:03:45 +0000226void LiveIntervals::print(std::ostream &O, const Module* ) const {
Chris Lattner70ca3582004-09-30 15:59:17 +0000227 O << "********** INTERVALS **********\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000228 for (const_iterator I = begin(), E = end(); I != E; ++I) {
229 I->second.print(std::cerr, mri_);
230 std::cerr << "\n";
231 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000232
233 O << "********** MACHINEINSTRS **********\n";
234 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
235 mbbi != mbbe; ++mbbi) {
236 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
237 for (MachineBasicBlock::iterator mii = mbbi->begin(),
238 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner477e4552004-09-30 16:10:45 +0000239 O << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner70ca3582004-09-30 15:59:17 +0000240 }
241 }
242}
243
Chris Lattner70ca3582004-09-30 15:59:17 +0000244std::vector<LiveInterval*> LiveIntervals::
245addIntervalsForSpills(const LiveInterval &li, VirtRegMap &vrm, int slot) {
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000246 // since this is called after the analysis is done we don't know if
247 // LiveVariables is available
248 lv_ = getAnalysisToUpdate<LiveVariables>();
249
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000250 std::vector<LiveInterval*> added;
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000251
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000252 assert(li.weight != HUGE_VAL &&
253 "attempt to spill already spilled interval!");
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000254
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000255 DEBUG(std::cerr << "\t\t\t\tadding intervals for spills for interval: "
256 << li << '\n');
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000257
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000258 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg);
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000259
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000260 for (LiveInterval::Ranges::const_iterator
261 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
262 unsigned index = getBaseIndex(i->start);
263 unsigned end = getBaseIndex(i->end-1) + InstrSlots::NUM;
264 for (; index != end; index += InstrSlots::NUM) {
265 // skip deleted instructions
266 while (index != end && !getInstructionFromIndex(index))
267 index += InstrSlots::NUM;
268 if (index == end) break;
Chris Lattner8640f4e2004-07-19 15:16:53 +0000269
Chris Lattner3b9db832006-01-03 07:41:37 +0000270 MachineInstr *MI = getInstructionFromIndex(index);
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000271
Chris Lattnerb11443d2005-09-09 19:17:47 +0000272 // NewRegLiveIn - This instruction might have multiple uses of the spilled
273 // register. In this case, for the first use, keep track of the new vreg
274 // that we reload it into. If we see a second use, reuse this vreg
275 // instead of creating live ranges for two reloads.
276 unsigned NewRegLiveIn = 0;
277
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000278 for_operand:
Chris Lattner3b9db832006-01-03 07:41:37 +0000279 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
280 MachineOperand& mop = MI->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000281 if (mop.isRegister() && mop.getReg() == li.reg) {
Chris Lattnerb11443d2005-09-09 19:17:47 +0000282 if (NewRegLiveIn && mop.isUse()) {
283 // We already emitted a reload of this value, reuse it for
284 // subsequent operands.
Chris Lattnere53f4a02006-05-04 17:52:23 +0000285 MI->getOperand(i).setReg(NewRegLiveIn);
Chris Lattnerb11443d2005-09-09 19:17:47 +0000286 DEBUG(std::cerr << "\t\t\t\treused reload into reg" << NewRegLiveIn
287 << " for operand #" << i << '\n');
Chris Lattner3b9db832006-01-03 07:41:37 +0000288 } else if (MachineInstr* fmi = mri_->foldMemoryOperand(MI, i, slot)) {
Chris Lattnerb11443d2005-09-09 19:17:47 +0000289 // Attempt to fold the memory reference into the instruction. If we
290 // can do this, we don't need to insert spill code.
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000291 if (lv_)
Chris Lattner3b9db832006-01-03 07:41:37 +0000292 lv_->instructionChanged(MI, fmi);
Evan Cheng200370f2006-04-30 08:41:47 +0000293 MachineBasicBlock &MBB = *MI->getParent();
Chris Lattner35f27052006-05-01 21:16:03 +0000294 vrm.virtFolded(li.reg, MI, i, fmi);
Chris Lattner3b9db832006-01-03 07:41:37 +0000295 mi2iMap_.erase(MI);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000296 i2miMap_[index/InstrSlots::NUM] = fmi;
297 mi2iMap_[fmi] = index;
Chris Lattner3b9db832006-01-03 07:41:37 +0000298 MI = MBB.insert(MBB.erase(MI), fmi);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000299 ++numFolded;
Chris Lattner477e4552004-09-30 16:10:45 +0000300 // Folding the load/store can completely change the instruction in
301 // unpredictable ways, rescan it from the beginning.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000302 goto for_operand;
Chris Lattner477e4552004-09-30 16:10:45 +0000303 } else {
Chris Lattner70ca3582004-09-30 15:59:17 +0000304 // This is tricky. We need to add information in the interval about
305 // the spill code so we have to use our extra load/store slots.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000306 //
Chris Lattner70ca3582004-09-30 15:59:17 +0000307 // If we have a use we are going to have a load so we start the
308 // interval from the load slot onwards. Otherwise we start from the
309 // def slot.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000310 unsigned start = (mop.isUse() ?
311 getLoadIndex(index) :
312 getDefIndex(index));
Chris Lattner70ca3582004-09-30 15:59:17 +0000313 // If we have a def we are going to have a store right after it so
314 // we end the interval after the use of the next
315 // instruction. Otherwise we end after the use of this instruction.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000316 unsigned end = 1 + (mop.isDef() ?
317 getStoreIndex(index) :
318 getUseIndex(index));
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000319
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000320 // create a new register for this spill
Chris Lattnerb11443d2005-09-09 19:17:47 +0000321 NewRegLiveIn = mf_->getSSARegMap()->createVirtualRegister(rc);
Chris Lattnere53f4a02006-05-04 17:52:23 +0000322 MI->getOperand(i).setReg(NewRegLiveIn);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000323 vrm.grow();
Chris Lattnerb11443d2005-09-09 19:17:47 +0000324 vrm.assignVirt2StackSlot(NewRegLiveIn, slot);
325 LiveInterval& nI = getOrCreateInterval(NewRegLiveIn);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000326 assert(nI.empty());
Chris Lattner70ca3582004-09-30 15:59:17 +0000327
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000328 // the spill weight is now infinity as it
329 // cannot be spilled again
Chris Lattner28696be2005-01-08 19:55:00 +0000330 nI.weight = float(HUGE_VAL);
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000331 LiveRange LR(start, end, nI.getNextValue(~0U));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000332 DEBUG(std::cerr << " +" << LR);
333 nI.addRange(LR);
334 added.push_back(&nI);
Chris Lattner70ca3582004-09-30 15:59:17 +0000335
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000336 // update live variables if it is available
337 if (lv_)
Chris Lattner3b9db832006-01-03 07:41:37 +0000338 lv_->addVirtualRegisterKilled(NewRegLiveIn, MI);
Chris Lattnerb11443d2005-09-09 19:17:47 +0000339
340 // If this is a live in, reuse it for subsequent live-ins. If it's
341 // a def, we can't do this.
342 if (!mop.isUse()) NewRegLiveIn = 0;
343
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000344 DEBUG(std::cerr << "\t\t\t\tadded new interval: " << nI << '\n');
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000345 }
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000346 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000347 }
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000348 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000349 }
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000350
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000351 return added;
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000352}
353
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000354void LiveIntervals::printRegName(unsigned reg) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000355 if (MRegisterInfo::isPhysicalRegister(reg))
356 std::cerr << mri_->getName(reg);
357 else
358 std::cerr << "%reg" << reg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000359}
360
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000361void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000362 MachineBasicBlock::iterator mi,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000363 LiveInterval &interval) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000364 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
365 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000366
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000367 // Virtual registers may be defined multiple times (due to phi
368 // elimination and 2-addr elimination). Much of what we do only has to be
369 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000370 // time we see a vreg.
371 if (interval.empty()) {
372 // Get the Idx of the defining instructions.
373 unsigned defIndex = getDefIndex(getInstructionIndex(mi));
Chris Lattner6097d132004-07-19 02:15:56 +0000374
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000375 unsigned ValNum = interval.getNextValue(defIndex);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000376 assert(ValNum == 0 && "First value in interval is not 0?");
377 ValNum = 0; // Clue in the optimizer.
Chris Lattner7ac2d312004-07-24 02:59:07 +0000378
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000379 // Loop over all of the blocks that the vreg is defined in. There are
380 // two cases we have to handle here. The most common case is a vreg
381 // whose lifetime is contained within a basic block. In this case there
382 // will be a single kill, in MBB, which comes after the definition.
383 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
384 // FIXME: what about dead vars?
385 unsigned killIdx;
386 if (vi.Kills[0] != mi)
387 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
388 else
389 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000390
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000391 // If the kill happens after the definition, we have an intra-block
392 // live range.
393 if (killIdx > defIndex) {
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000394 assert(vi.AliveBlocks.empty() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000395 "Shouldn't be alive across any blocks!");
396 LiveRange LR(defIndex, killIdx, ValNum);
397 interval.addRange(LR);
398 DEBUG(std::cerr << " +" << LR << "\n");
399 return;
400 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000401 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000402
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000403 // The other case we handle is when a virtual register lives to the end
404 // of the defining block, potentially live across some blocks, then is
405 // live into some number of blocks, but gets killed. Start by adding a
406 // range that goes from this definition to the end of the defining block.
Alkis Evlogimenosd19e2902004-08-31 17:39:15 +0000407 LiveRange NewLR(defIndex,
408 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
409 ValNum);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000410 DEBUG(std::cerr << " +" << NewLR);
411 interval.addRange(NewLR);
412
413 // Iterate over all of the blocks that the variable is completely
414 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
415 // live interval.
416 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
417 if (vi.AliveBlocks[i]) {
418 MachineBasicBlock* mbb = mf_->getBlockNumbered(i);
419 if (!mbb->empty()) {
420 LiveRange LR(getInstructionIndex(&mbb->front()),
Alkis Evlogimenosd19e2902004-08-31 17:39:15 +0000421 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000422 ValNum);
423 interval.addRange(LR);
424 DEBUG(std::cerr << " +" << LR);
425 }
426 }
427 }
428
429 // Finally, this virtual register is live from the start of any killing
430 // block to the 'use' slot of the killing instruction.
431 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
432 MachineInstr *Kill = vi.Kills[i];
433 LiveRange LR(getInstructionIndex(Kill->getParent()->begin()),
Alkis Evlogimenosd19e2902004-08-31 17:39:15 +0000434 getUseIndex(getInstructionIndex(Kill))+1,
435 ValNum);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000436 interval.addRange(LR);
437 DEBUG(std::cerr << " +" << LR);
438 }
439
440 } else {
441 // If this is the second time we see a virtual register definition, it
442 // must be due to phi elimination or two addr elimination. If this is
443 // the result of two address elimination, then the vreg is the first
444 // operand, and is a def-and-use.
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000445 if (mi->getOperand(0).isRegister() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000446 mi->getOperand(0).getReg() == interval.reg &&
447 mi->getOperand(0).isDef() && mi->getOperand(0).isUse()) {
448 // If this is a two-address definition, then we have already processed
449 // the live range. The only problem is that we didn't realize there
450 // are actually two values in the live interval. Because of this we
451 // need to take the LiveRegion that defines this register and split it
452 // into two values.
453 unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
454 unsigned RedefIndex = getDefIndex(getInstructionIndex(mi));
455
456 // Delete the initial value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000457 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000458 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000459
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000460 // Two-address vregs should always only be redefined once. This means
461 // that at this point, there should be exactly one value number in it.
462 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
463
464 // The new value number is defined by the instruction we claimed defined
465 // value #0.
466 unsigned ValNo = interval.getNextValue(DefIndex);
467
468 // Value#1 is now defined by the 2-addr instruction.
469 interval.setInstDefiningValNum(0, RedefIndex);
470
471 // Add the new live interval which replaces the range for the input copy.
472 LiveRange LR(DefIndex, RedefIndex, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000473 DEBUG(std::cerr << " replace range with " << LR);
474 interval.addRange(LR);
475
476 // If this redefinition is dead, we need to add a dummy unit live
477 // range covering the def slot.
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000478 if (lv_->RegisterDefIsDead(mi, interval.reg))
479 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, 0));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000480
481 DEBUG(std::cerr << "RESULT: " << interval);
482
483 } else {
484 // Otherwise, this must be because of phi elimination. If this is the
485 // first redefinition of the vreg that we have seen, go back and change
486 // the live range in the PHI block to be a different value number.
487 if (interval.containsOneValue()) {
488 assert(vi.Kills.size() == 1 &&
489 "PHI elimination vreg should have one kill, the PHI itself!");
490
491 // Remove the old range that we now know has an incorrect number.
492 MachineInstr *Killer = vi.Kills[0];
493 unsigned Start = getInstructionIndex(Killer->getParent()->begin());
494 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
495 DEBUG(std::cerr << "Removing [" << Start << "," << End << "] from: "
496 << interval << "\n");
497 interval.removeRange(Start, End);
498 DEBUG(std::cerr << "RESULT: " << interval);
499
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000500 // Replace the interval with one of a NEW value number. Note that this
501 // value number isn't actually defined by an instruction, weird huh? :)
502 LiveRange LR(Start, End, interval.getNextValue(~0U));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000503 DEBUG(std::cerr << " replace range with " << LR);
504 interval.addRange(LR);
505 DEBUG(std::cerr << "RESULT: " << interval);
506 }
507
508 // In the case of PHI elimination, each variable definition is only
509 // live until the end of the block. We've already taken care of the
510 // rest of the live range.
511 unsigned defIndex = getDefIndex(getInstructionIndex(mi));
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000512 LiveRange LR(defIndex,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000513 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000514 interval.getNextValue(defIndex));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000515 interval.addRange(LR);
516 DEBUG(std::cerr << " +" << LR);
517 }
518 }
519
520 DEBUG(std::cerr << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000521}
522
Chris Lattnerf35fef72004-07-23 21:24:19 +0000523void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000524 MachineBasicBlock::iterator mi,
Chris Lattnerf768bba2005-03-09 23:05:19 +0000525 LiveInterval& interval,
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000526 unsigned SrcReg, unsigned DestReg,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000527 bool isLiveIn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000528 // A physical register cannot be live across basic block, so its
529 // lifetime must end somewhere in its defining basic block.
530 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
531 typedef LiveVariables::killed_iterator KillIter;
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000532
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000533 unsigned baseIndex = getInstructionIndex(mi);
534 unsigned start = getDefIndex(baseIndex);
535 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000536
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000537 // If it is not used after definition, it is considered dead at
538 // the instruction defining it. Hence its interval is:
539 // [defSlot(def), defSlot(def)+1)
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000540 if (lv_->RegisterDefIsDead(mi, interval.reg)) {
541 DEBUG(std::cerr << " dead");
542 end = getDefIndex(start) + 1;
543 goto exit;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000544 }
545
546 // If it is not dead on definition, it must be killed by a
547 // subsequent instruction. Hence its interval is:
548 // [defSlot(def), useSlot(kill)+1)
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000549 while (++mi != MBB->end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000550 baseIndex += InstrSlots::NUM;
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000551 if (lv_->KillsRegister(mi, interval.reg)) {
552 DEBUG(std::cerr << " killed");
553 end = getUseIndex(baseIndex) + 1;
554 goto exit;
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000555 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000556 }
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000557
558 // The only case we should have a dead physreg here without a killing or
559 // instruction where we know it's dead is if it is live-in to the function
560 // and never used.
561 assert(isLiveIn && "physreg was not killed in defining block!");
562 end = getDefIndex(start) + 1; // It's dead.
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000563
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000564exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000565 assert(start < end && "did not find end of interval?");
Chris Lattnerf768bba2005-03-09 23:05:19 +0000566
567 // Finally, if this is defining a new range for the physical register, and if
568 // that physreg is just a copy from a vreg, and if THAT vreg was a copy from
569 // the physreg, then the new fragment has the same value as the one copied
570 // into the vreg.
571 if (interval.reg == DestReg && !interval.empty() &&
Chris Lattnere97568c2005-03-10 20:59:51 +0000572 MRegisterInfo::isVirtualRegister(SrcReg)) {
Chris Lattnerf768bba2005-03-09 23:05:19 +0000573
574 // Get the live interval for the vreg, see if it is defined by a copy.
575 LiveInterval &SrcInterval = getOrCreateInterval(SrcReg);
576
577 if (SrcInterval.containsOneValue()) {
578 assert(!SrcInterval.empty() && "Can't contain a value and be empty!");
579
580 // Get the first index of the first range. Though the interval may have
581 // multiple liveranges in it, we only check the first.
582 unsigned StartIdx = SrcInterval.begin()->start;
583 MachineInstr *SrcDefMI = getInstructionFromIndex(StartIdx);
584
585 // Check to see if the vreg was defined by a copy instruction, and that
586 // the source was this physreg.
587 unsigned VRegSrcSrc, VRegSrcDest;
588 if (tii_->isMoveInstr(*SrcDefMI, VRegSrcSrc, VRegSrcDest) &&
589 SrcReg == VRegSrcDest && VRegSrcSrc == DestReg) {
590 // Okay, now we know that the vreg was defined by a copy from this
591 // physreg. Find the value number being copied and use it as the value
592 // for this range.
593 const LiveRange *DefRange = interval.getLiveRangeContaining(StartIdx-1);
594 if (DefRange) {
595 LiveRange LR(start, end, DefRange->ValId);
596 interval.addRange(LR);
597 DEBUG(std::cerr << " +" << LR << '\n');
598 return;
599 }
600 }
601 }
602 }
603
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000604 LiveRange LR(start, end, interval.getNextValue(start));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000605 interval.addRange(LR);
606 DEBUG(std::cerr << " +" << LR << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000607}
608
Chris Lattnerf35fef72004-07-23 21:24:19 +0000609void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
610 MachineBasicBlock::iterator MI,
611 unsigned reg) {
612 if (MRegisterInfo::isVirtualRegister(reg))
613 handleVirtualRegisterDef(MBB, MI, getOrCreateInterval(reg));
Alkis Evlogimenos53278012004-08-26 22:22:38 +0000614 else if (allocatableRegs_[reg]) {
Chris Lattnerf768bba2005-03-09 23:05:19 +0000615 unsigned SrcReg = 0, DestReg = 0;
Chris Lattner60d97d42006-01-10 05:41:59 +0000616 if (!tii_->isMoveInstr(*MI, SrcReg, DestReg))
617 SrcReg = DestReg = 0;
Chris Lattnerf768bba2005-03-09 23:05:19 +0000618
619 handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(reg),
620 SrcReg, DestReg);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000621 for (const unsigned* AS = mri_->getAliasSet(reg); *AS; ++AS)
Chris Lattnerf768bba2005-03-09 23:05:19 +0000622 handlePhysicalRegisterDef(MBB, MI, getOrCreateInterval(*AS),
623 SrcReg, DestReg);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000624 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000625}
626
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000627/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000628/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000629/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000630/// which a variable is live
631void LiveIntervals::computeIntervals()
632{
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000633 DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
634 DEBUG(std::cerr << "********** Function: "
635 << ((Value*)mf_->getFunction())->getName() << '\n');
Chris Lattner799a9192005-04-09 16:17:50 +0000636 bool IgnoreFirstInstr = mf_->livein_begin() != mf_->livein_end();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000637
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000638 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000639 I != E; ++I) {
640 MachineBasicBlock* mbb = I;
641 DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n");
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000642
Chris Lattner799a9192005-04-09 16:17:50 +0000643 MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
644 if (IgnoreFirstInstr) { ++mi; IgnoreFirstInstr = false; }
645 for (; mi != miEnd; ++mi) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000646 const TargetInstrDescriptor& tid =
647 tm_->getInstrInfo()->get(mi->getOpcode());
Chris Lattner477e4552004-09-30 16:10:45 +0000648 DEBUG(std::cerr << getInstructionIndex(mi) << "\t" << *mi);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000649
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000650 // handle implicit defs
Jim Laskeycd4317e2006-07-21 21:15:20 +0000651 if (tid.ImplicitDefs) {
652 for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
653 handleRegisterDef(mbb, mi, *id);
654 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000655
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000656 // handle explicit defs
657 for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
658 MachineOperand& mop = mi->getOperand(i);
659 // handle register defs - build intervals
660 if (mop.isRegister() && mop.getReg() && mop.isDef())
661 handleRegisterDef(mbb, mi, mop.getReg());
662 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000663 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000664 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000665}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000666
Chris Lattneraa51a482005-10-21 06:49:50 +0000667/// IntA is defined as a copy from IntB and we know it only has one value
668/// number. If all of the places that IntA and IntB overlap are defined by
669/// copies from IntA to IntB, we know that these two ranges can really be
670/// merged if we adjust the value numbers. If it is safe, adjust the value
Chris Lattnerc60e6022005-10-26 18:41:41 +0000671/// numbers and return true, allowing coalescing to occur.
Chris Lattneraa51a482005-10-21 06:49:50 +0000672bool LiveIntervals::
673AdjustIfAllOverlappingRangesAreCopiesFrom(LiveInterval &IntA,
674 LiveInterval &IntB,
675 unsigned CopyIdx) {
676 std::vector<LiveRange*> Ranges;
677 IntA.getOverlapingRanges(IntB, CopyIdx, Ranges);
678
679 assert(!Ranges.empty() && "Why didn't we do a simple join of this?");
680
681 unsigned IntBRep = rep(IntB.reg);
682
683 // Check to see if all of the overlaps (entries in Ranges) are defined by a
684 // copy from IntA. If not, exit.
685 for (unsigned i = 0, e = Ranges.size(); i != e; ++i) {
686 unsigned Idx = Ranges[i]->start;
687 MachineInstr *MI = getInstructionFromIndex(Idx);
688 unsigned SrcReg, DestReg;
689 if (!tii_->isMoveInstr(*MI, SrcReg, DestReg)) return false;
690
691 // If this copy isn't actually defining this range, it must be a live
692 // range spanning basic blocks or something.
693 if (rep(DestReg) != rep(IntA.reg)) return false;
694
695 // Check to see if this is coming from IntB. If not, bail out.
696 if (rep(SrcReg) != IntBRep) return false;
697 }
698
699 // Okay, we can change this one. Get the IntB value number that IntA is
700 // copied from.
701 unsigned ActualValNo = IntA.getLiveRangeContaining(CopyIdx-1)->ValId;
702
703 // Change all of the value numbers to the same as what we IntA is copied from.
704 for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
705 Ranges[i]->ValId = ActualValNo;
706
707 return true;
708}
709
Chris Lattner1c5c0442004-07-19 14:08:10 +0000710void LiveIntervals::joinIntervalsInMachineBB(MachineBasicBlock *MBB) {
Chris Lattner7ac2d312004-07-24 02:59:07 +0000711 DEBUG(std::cerr << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000712
Chris Lattner7ac2d312004-07-24 02:59:07 +0000713 for (MachineBasicBlock::iterator mi = MBB->begin(), mie = MBB->end();
714 mi != mie; ++mi) {
715 DEBUG(std::cerr << getInstructionIndex(mi) << '\t' << *mi);
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000716
Chris Lattner7ac2d312004-07-24 02:59:07 +0000717 // we only join virtual registers with allocatable
718 // physical registers since we do not have liveness information
719 // on not allocatable physical registers
Chris Lattneraa51a482005-10-21 06:49:50 +0000720 unsigned SrcReg, DestReg;
721 if (tii_->isMoveInstr(*mi, SrcReg, DestReg) &&
722 (MRegisterInfo::isVirtualRegister(SrcReg) || allocatableRegs_[SrcReg])&&
723 (MRegisterInfo::isVirtualRegister(DestReg)||allocatableRegs_[DestReg])){
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000724
Chris Lattner7ac2d312004-07-24 02:59:07 +0000725 // Get representative registers.
Chris Lattneraa51a482005-10-21 06:49:50 +0000726 SrcReg = rep(SrcReg);
727 DestReg = rep(DestReg);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000728
Chris Lattner7ac2d312004-07-24 02:59:07 +0000729 // If they are already joined we continue.
Chris Lattneraa51a482005-10-21 06:49:50 +0000730 if (SrcReg == DestReg)
Chris Lattner7ac2d312004-07-24 02:59:07 +0000731 continue;
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000732
Chris Lattner7ac2d312004-07-24 02:59:07 +0000733 // If they are both physical registers, we cannot join them.
Chris Lattneraa51a482005-10-21 06:49:50 +0000734 if (MRegisterInfo::isPhysicalRegister(SrcReg) &&
735 MRegisterInfo::isPhysicalRegister(DestReg))
Chris Lattner7ac2d312004-07-24 02:59:07 +0000736 continue;
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000737
Evan Cheng647c15e2006-05-12 06:06:34 +0000738 // If they are not of the same register class, we cannot join them.
739 if (differingRegisterClasses(SrcReg, DestReg))
Chris Lattner7ac2d312004-07-24 02:59:07 +0000740 continue;
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000741
Chris Lattneraa51a482005-10-21 06:49:50 +0000742 LiveInterval &SrcInt = getInterval(SrcReg);
743 LiveInterval &DestInt = getInterval(DestReg);
744 assert(SrcInt.reg == SrcReg && DestInt.reg == DestReg &&
Chris Lattner7ac2d312004-07-24 02:59:07 +0000745 "Register mapping is horribly broken!");
Chris Lattner060913c2004-07-24 04:32:22 +0000746
Chris Lattner8222b2d2006-08-21 23:03:54 +0000747 DEBUG(std::cerr << "\t\tInspecting "; SrcInt.print(std::cerr, mri_);
748 std::cerr << " and "; DestInt.print(std::cerr, mri_);
749 std::cerr << ": ");
Chris Lattner060913c2004-07-24 04:32:22 +0000750
Chris Lattner4df98e52004-07-24 03:32:06 +0000751 // If two intervals contain a single value and are joined by a copy, it
752 // does not matter if the intervals overlap, they can always be joined.
Chris Lattneraa51a482005-10-21 06:49:50 +0000753 bool Joinable = SrcInt.containsOneValue() && DestInt.containsOneValue();
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000754
Chris Lattner7ac2d312004-07-24 02:59:07 +0000755 unsigned MIDefIdx = getDefIndex(getInstructionIndex(mi));
Chris Lattneraa51a482005-10-21 06:49:50 +0000756
757 // If the intervals think that this is joinable, do so now.
758 if (!Joinable && DestInt.joinable(SrcInt, MIDefIdx))
759 Joinable = true;
Chris Lattner1c5c0442004-07-19 14:08:10 +0000760
Chris Lattneraa51a482005-10-21 06:49:50 +0000761 // If DestInt is actually a copy from SrcInt (which we know) that is used
762 // to define another value of SrcInt, we can change the other range of
763 // SrcInt to be the value of the range that defines DestInt, allowing a
Chris Lattnerc60e6022005-10-26 18:41:41 +0000764 // coalesce.
Chris Lattneraa51a482005-10-21 06:49:50 +0000765 if (!Joinable && DestInt.containsOneValue() &&
766 AdjustIfAllOverlappingRangesAreCopiesFrom(SrcInt, DestInt, MIDefIdx))
767 Joinable = true;
768
769 if (!Joinable || overlapsAliases(&SrcInt, &DestInt)) {
770 DEBUG(std::cerr << "Interference!\n");
771 } else {
772 DestInt.join(SrcInt, MIDefIdx);
773 DEBUG(std::cerr << "Joined. Result = " << DestInt << "\n");
774
Evan Cheng647c15e2006-05-12 06:06:34 +0000775 if (!MRegisterInfo::isPhysicalRegister(SrcReg)) {
Chris Lattneraa51a482005-10-21 06:49:50 +0000776 r2iMap_.erase(SrcReg);
777 r2rMap_[SrcReg] = DestReg;
Chris Lattner7ac2d312004-07-24 02:59:07 +0000778 } else {
779 // Otherwise merge the data structures the other way so we don't lose
780 // the physreg information.
Chris Lattneraa51a482005-10-21 06:49:50 +0000781 r2rMap_[DestReg] = SrcReg;
782 DestInt.reg = SrcReg;
783 SrcInt.swap(DestInt);
784 r2iMap_.erase(DestReg);
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000785 }
Chris Lattner7ac2d312004-07-24 02:59:07 +0000786 ++numJoins;
Chris Lattner7ac2d312004-07-24 02:59:07 +0000787 }
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000788 }
Chris Lattner7ac2d312004-07-24 02:59:07 +0000789 }
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000790}
791
Chris Lattnercc0d1562004-07-19 14:40:29 +0000792namespace {
793 // DepthMBBCompare - Comparison predicate that sort first based on the loop
794 // depth of the basic block (the unsigned), and then on the MBB number.
795 struct DepthMBBCompare {
796 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
797 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
798 if (LHS.first > RHS.first) return true; // Deeper loops first
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000799 return LHS.first == RHS.first &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000800 LHS.second->getNumber() < RHS.second->getNumber();
Chris Lattnercc0d1562004-07-19 14:40:29 +0000801 }
802 };
803}
Chris Lattner1c5c0442004-07-19 14:08:10 +0000804
Chris Lattnercc0d1562004-07-19 14:40:29 +0000805void LiveIntervals::joinIntervals() {
806 DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
807
808 const LoopInfo &LI = getAnalysis<LoopInfo>();
809 if (LI.begin() == LI.end()) {
810 // If there are no loops in the function, join intervals in function order.
Chris Lattner1c5c0442004-07-19 14:08:10 +0000811 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
812 I != E; ++I)
813 joinIntervalsInMachineBB(I);
Chris Lattnercc0d1562004-07-19 14:40:29 +0000814 } else {
815 // Otherwise, join intervals in inner loops before other intervals.
816 // Unfortunately we can't just iterate over loop hierarchy here because
817 // there may be more MBB's than BB's. Collect MBB's for sorting.
818 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
819 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
820 I != E; ++I)
821 MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
822
823 // Sort by loop depth.
824 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
825
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000826 // Finally, join intervals in loop nest order.
Chris Lattnercc0d1562004-07-19 14:40:29 +0000827 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
828 joinIntervalsInMachineBB(MBBs[i].second);
829 }
Chris Lattnerc83e40d2004-07-25 03:24:11 +0000830
831 DEBUG(std::cerr << "*** Register mapping ***\n");
Alkis Evlogimenos5d0d1e32004-09-08 03:01:50 +0000832 DEBUG(for (int i = 0, e = r2rMap_.size(); i != e; ++i)
Chris Lattner7c10b0d2006-08-21 22:56:29 +0000833 if (r2rMap_[i]) {
834 std::cerr << " reg " << i << " -> ";
835 printRegName(r2rMap_[i]);
836 std::cerr << "\n";
837 });
Chris Lattner1c5c0442004-07-19 14:08:10 +0000838}
839
Evan Cheng647c15e2006-05-12 06:06:34 +0000840/// Return true if the two specified registers belong to different register
841/// classes. The registers may be either phys or virt regs.
842bool LiveIntervals::differingRegisterClasses(unsigned RegA,
843 unsigned RegB) const {
Alkis Evlogimenos79b0c3f2004-01-23 13:37:51 +0000844
Chris Lattner7ac2d312004-07-24 02:59:07 +0000845 // Get the register classes for the first reg.
Chris Lattnerad3c74f2004-10-26 05:29:18 +0000846 if (MRegisterInfo::isPhysicalRegister(RegA)) {
Misha Brukmanedf128a2005-04-21 22:36:52 +0000847 assert(MRegisterInfo::isVirtualRegister(RegB) &&
Chris Lattnerad3c74f2004-10-26 05:29:18 +0000848 "Shouldn't consider two physregs!");
Evan Cheng647c15e2006-05-12 06:06:34 +0000849 return !mf_->getSSARegMap()->getRegClass(RegB)->contains(RegA);
Chris Lattnerad3c74f2004-10-26 05:29:18 +0000850 }
Chris Lattner7ac2d312004-07-24 02:59:07 +0000851
852 // Compare against the regclass for the second reg.
Evan Cheng647c15e2006-05-12 06:06:34 +0000853 const TargetRegisterClass *RegClass = mf_->getSSARegMap()->getRegClass(RegA);
854 if (MRegisterInfo::isVirtualRegister(RegB))
855 return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
856 else
857 return !RegClass->contains(RegB);
Chris Lattner7ac2d312004-07-24 02:59:07 +0000858}
859
860bool LiveIntervals::overlapsAliases(const LiveInterval *LHS,
861 const LiveInterval *RHS) const {
862 if (!MRegisterInfo::isPhysicalRegister(LHS->reg)) {
863 if (!MRegisterInfo::isPhysicalRegister(RHS->reg))
864 return false; // vreg-vreg merge has no aliases!
865 std::swap(LHS, RHS);
866 }
867
868 assert(MRegisterInfo::isPhysicalRegister(LHS->reg) &&
869 MRegisterInfo::isVirtualRegister(RHS->reg) &&
870 "first interval must describe a physical register");
871
Chris Lattner4df98e52004-07-24 03:32:06 +0000872 for (const unsigned *AS = mri_->getAliasSet(LHS->reg); *AS; ++AS)
873 if (RHS->overlaps(getInterval(*AS)))
874 return true;
Alkis Evlogimenos79b0c3f2004-01-23 13:37:51 +0000875
Chris Lattner4df98e52004-07-24 03:32:06 +0000876 return false;
Alkis Evlogimenos79b0c3f2004-01-23 13:37:51 +0000877}
878
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000879LiveInterval LiveIntervals::createInterval(unsigned reg) {
Misha Brukmanedf128a2005-04-21 22:36:52 +0000880 float Weight = MRegisterInfo::isPhysicalRegister(reg) ?
Chris Lattner28696be2005-01-08 19:55:00 +0000881 (float)HUGE_VAL :0.0F;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000882 return LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000883}