blob: 237dcd32c88d1e743d8465d935e27837a3a8a147 [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 {
Chris Lattner5d8925c2006-08-27 22:30:17 +000041 RegisterPass<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
Chris Lattnerf7da2c72006-08-24 22:43:55 +000064void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000065 AU.addRequired<LiveVariables>();
66 AU.addPreservedID(PHIEliminationID);
67 AU.addRequiredID(PHIEliminationID);
68 AU.addRequiredID(TwoAddressInstructionPassID);
69 AU.addRequired<LoopInfo>();
70 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000071}
72
Chris Lattnerf7da2c72006-08-24 22:43:55 +000073void LiveIntervals::releaseMemory() {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000074 mi2iMap_.clear();
75 i2miMap_.clear();
76 r2iMap_.clear();
77 r2rMap_.clear();
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000078}
79
80
Evan Cheng99314142006-05-11 07:29:24 +000081static bool isZeroLengthInterval(LiveInterval *li) {
82 for (LiveInterval::Ranges::const_iterator
83 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
84 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
85 return false;
86 return true;
87}
88
89
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000090/// runOnMachineFunction - Register allocate the whole function
91///
92bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000093 mf_ = &fn;
94 tm_ = &fn.getTarget();
95 mri_ = tm_->getRegisterInfo();
Chris Lattnerf768bba2005-03-09 23:05:19 +000096 tii_ = tm_->getInstrInfo();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000097 lv_ = &getAnalysis<LiveVariables>();
Alkis Evlogimenos53278012004-08-26 22:22:38 +000098 allocatableRegs_ = mri_->getAllocatableSet(fn);
Alkis Evlogimenos2c4f7b52004-09-09 19:24:38 +000099 r2rMap_.grow(mf_->getSSARegMap()->getLastVirtReg());
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000100
Chris Lattner799a9192005-04-09 16:17:50 +0000101 // If this function has any live ins, insert a dummy instruction at the
102 // beginning of the function that we will pretend "defines" the values. This
103 // is to make the interval analysis simpler by providing a number.
104 if (fn.livein_begin() != fn.livein_end()) {
Chris Lattner712ad0c2005-05-13 07:08:07 +0000105 unsigned FirstLiveIn = fn.livein_begin()->first;
Chris Lattner799a9192005-04-09 16:17:50 +0000106
107 // Find a reg class that contains this live in.
108 const TargetRegisterClass *RC = 0;
109 for (MRegisterInfo::regclass_iterator RCI = mri_->regclass_begin(),
110 E = mri_->regclass_end(); RCI != E; ++RCI)
111 if ((*RCI)->contains(FirstLiveIn)) {
112 RC = *RCI;
113 break;
114 }
115
116 MachineInstr *OldFirstMI = fn.begin()->begin();
117 mri_->copyRegToReg(*fn.begin(), fn.begin()->begin(),
118 FirstLiveIn, FirstLiveIn, RC);
119 assert(OldFirstMI != fn.begin()->begin() &&
120 "copyRetToReg didn't insert anything!");
121 }
122
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000123 // number MachineInstrs
124 unsigned miIndex = 0;
125 for (MachineFunction::iterator mbb = mf_->begin(), mbbEnd = mf_->end();
126 mbb != mbbEnd; ++mbb)
127 for (MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
128 mi != miEnd; ++mi) {
129 bool inserted = mi2iMap_.insert(std::make_pair(mi, miIndex)).second;
130 assert(inserted && "multiple MachineInstr -> index mappings");
131 i2miMap_.push_back(mi);
132 miIndex += InstrSlots::NUM;
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000133 }
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000134
Chris Lattner799a9192005-04-09 16:17:50 +0000135 // Note intervals due to live-in values.
136 if (fn.livein_begin() != fn.livein_end()) {
137 MachineBasicBlock *Entry = fn.begin();
Chris Lattner712ad0c2005-05-13 07:08:07 +0000138 for (MachineFunction::livein_iterator I = fn.livein_begin(),
Chris Lattner799a9192005-04-09 16:17:50 +0000139 E = fn.livein_end(); I != E; ++I) {
Chris Lattner6b128bd2006-09-03 08:07:11 +0000140 handlePhysicalRegisterDef(Entry, Entry->begin(), 0,
Chris Lattner91725b72006-08-31 05:54:43 +0000141 getOrCreateInterval(I->first), 0);
Chris Lattner712ad0c2005-05-13 07:08:07 +0000142 for (const unsigned* AS = mri_->getAliasSet(I->first); *AS; ++AS)
Chris Lattner6b128bd2006-09-03 08:07:11 +0000143 handlePhysicalRegisterDef(Entry, Entry->begin(), 0,
Chris Lattner91725b72006-08-31 05:54:43 +0000144 getOrCreateInterval(*AS), 0);
Chris Lattner799a9192005-04-09 16:17:50 +0000145 }
146 }
147
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000148 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000149
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000150 numIntervals += getNumIntervals();
151
Chris Lattner38135af2005-05-14 05:34:15 +0000152 DEBUG(std::cerr << "********** INTERVALS **********\n";
153 for (iterator I = begin(), E = end(); I != E; ++I) {
154 I->second.print(std::cerr, mri_);
155 std::cerr << "\n";
156 });
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000157
158 // join intervals if requested
159 if (EnableJoining) joinIntervals();
160
161 numIntervalsAfter += getNumIntervals();
162
163 // perform a final pass over the instructions and compute spill
Chris Lattnerfbecc5a2006-09-03 07:53:50 +0000164 // weights, coalesce virtual registers and remove identity moves.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000165 const LoopInfo& loopInfo = getAnalysis<LoopInfo>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000166
167 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
168 mbbi != mbbe; ++mbbi) {
169 MachineBasicBlock* mbb = mbbi;
170 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
171
172 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
173 mii != mie; ) {
174 // if the move will be an identity move delete it
175 unsigned srcReg, dstReg, RegRep;
Chris Lattnerf768bba2005-03-09 23:05:19 +0000176 if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000177 (RegRep = rep(srcReg)) == rep(dstReg)) {
178 // remove from def list
179 LiveInterval &interval = getOrCreateInterval(RegRep);
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000180 RemoveMachineInstrFromMaps(mii);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000181 mii = mbbi->erase(mii);
182 ++numPeep;
183 }
184 else {
Chris Lattnerfbecc5a2006-09-03 07:53:50 +0000185 for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
186 const MachineOperand &mop = mii->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000187 if (mop.isRegister() && mop.getReg() &&
188 MRegisterInfo::isVirtualRegister(mop.getReg())) {
189 // replace register with representative register
190 unsigned reg = rep(mop.getReg());
Chris Lattnere53f4a02006-05-04 17:52:23 +0000191 mii->getOperand(i).setReg(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000192
193 LiveInterval &RegInt = getInterval(reg);
194 RegInt.weight +=
Chris Lattner7a36ae82004-10-25 18:40:47 +0000195 (mop.isUse() + mop.isDef()) * pow(10.0F, (int)loopDepth);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000196 }
197 }
198 ++mii;
199 }
200 }
201 }
202
Evan Cheng99314142006-05-11 07:29:24 +0000203 for (iterator I = begin(), E = end(); I != E; ++I) {
204 LiveInterval &li = I->second;
Chris Lattnerc9d94d12006-08-27 12:47:48 +0000205 if (MRegisterInfo::isVirtualRegister(li.reg)) {
206 // If the live interval length is essentially zero, i.e. in every live
Evan Cheng99314142006-05-11 07:29:24 +0000207 // range the use follows def immediately, it doesn't make sense to spill
208 // it and hope it will be easier to allocate for this li.
209 if (isZeroLengthInterval(&li))
210 li.weight = float(HUGE_VAL);
Chris Lattnerc9d94d12006-08-27 12:47:48 +0000211 }
Evan Cheng99314142006-05-11 07:29:24 +0000212 }
213
Chris Lattner70ca3582004-09-30 15:59:17 +0000214 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000215 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000216}
217
Chris Lattner70ca3582004-09-30 15:59:17 +0000218/// print - Implement the dump method.
Reid Spencerce9653c2004-12-07 04:03:45 +0000219void LiveIntervals::print(std::ostream &O, const Module* ) const {
Chris Lattner70ca3582004-09-30 15:59:17 +0000220 O << "********** INTERVALS **********\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000221 for (const_iterator I = begin(), E = end(); I != E; ++I) {
222 I->second.print(std::cerr, mri_);
223 std::cerr << "\n";
224 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000225
226 O << "********** MACHINEINSTRS **********\n";
227 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
228 mbbi != mbbe; ++mbbi) {
229 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
230 for (MachineBasicBlock::iterator mii = mbbi->begin(),
231 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner477e4552004-09-30 16:10:45 +0000232 O << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner70ca3582004-09-30 15:59:17 +0000233 }
234 }
235}
236
Chris Lattner70ca3582004-09-30 15:59:17 +0000237std::vector<LiveInterval*> LiveIntervals::
238addIntervalsForSpills(const LiveInterval &li, VirtRegMap &vrm, int slot) {
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000239 // since this is called after the analysis is done we don't know if
240 // LiveVariables is available
241 lv_ = getAnalysisToUpdate<LiveVariables>();
242
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000243 std::vector<LiveInterval*> added;
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000244
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000245 assert(li.weight != HUGE_VAL &&
246 "attempt to spill already spilled interval!");
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000247
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000248 DEBUG(std::cerr << "\t\t\t\tadding intervals for spills for interval: ";
249 li.print(std::cerr, mri_); std::cerr << '\n');
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000250
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000251 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg);
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000252
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000253 for (LiveInterval::Ranges::const_iterator
254 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
255 unsigned index = getBaseIndex(i->start);
256 unsigned end = getBaseIndex(i->end-1) + InstrSlots::NUM;
257 for (; index != end; index += InstrSlots::NUM) {
258 // skip deleted instructions
259 while (index != end && !getInstructionFromIndex(index))
260 index += InstrSlots::NUM;
261 if (index == end) break;
Chris Lattner8640f4e2004-07-19 15:16:53 +0000262
Chris Lattner3b9db832006-01-03 07:41:37 +0000263 MachineInstr *MI = getInstructionFromIndex(index);
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000264
Chris Lattner29268692006-09-05 02:12:02 +0000265 RestartInstruction:
Chris Lattner3b9db832006-01-03 07:41:37 +0000266 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
267 MachineOperand& mop = MI->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000268 if (mop.isRegister() && mop.getReg() == li.reg) {
Chris Lattner29268692006-09-05 02:12:02 +0000269 if (MachineInstr *fmi = mri_->foldMemoryOperand(MI, i, slot)) {
Chris Lattnerb11443d2005-09-09 19:17:47 +0000270 // Attempt to fold the memory reference into the instruction. If we
271 // can do this, we don't need to insert spill code.
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000272 if (lv_)
Chris Lattner3b9db832006-01-03 07:41:37 +0000273 lv_->instructionChanged(MI, fmi);
Evan Cheng200370f2006-04-30 08:41:47 +0000274 MachineBasicBlock &MBB = *MI->getParent();
Chris Lattner35f27052006-05-01 21:16:03 +0000275 vrm.virtFolded(li.reg, MI, i, fmi);
Chris Lattner3b9db832006-01-03 07:41:37 +0000276 mi2iMap_.erase(MI);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000277 i2miMap_[index/InstrSlots::NUM] = fmi;
278 mi2iMap_[fmi] = index;
Chris Lattner3b9db832006-01-03 07:41:37 +0000279 MI = MBB.insert(MBB.erase(MI), fmi);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000280 ++numFolded;
Chris Lattner477e4552004-09-30 16:10:45 +0000281 // Folding the load/store can completely change the instruction in
282 // unpredictable ways, rescan it from the beginning.
Chris Lattner29268692006-09-05 02:12:02 +0000283 goto RestartInstruction;
Chris Lattner477e4552004-09-30 16:10:45 +0000284 } else {
Chris Lattner29268692006-09-05 02:12:02 +0000285 // Create a new virtual register for the spill interval.
286 unsigned NewVReg = mf_->getSSARegMap()->createVirtualRegister(rc);
287
288 // Scan all of the operands of this instruction rewriting operands
289 // to use NewVReg instead of li.reg as appropriate. We do this for
290 // two reasons:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000291 //
Chris Lattner29268692006-09-05 02:12:02 +0000292 // 1. If the instr reads the same spilled vreg multiple times, we
293 // want to reuse the NewVReg.
294 // 2. If the instr is a two-addr instruction, we are required to
295 // keep the src/dst regs pinned.
296 //
297 // Keep track of whether we replace a use and/or def so that we can
298 // create the spill interval with the appropriate range.
299 mop.setReg(NewVReg);
300
301 bool HasUse = mop.isUse();
302 bool HasDef = mop.isDef();
303 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
304 if (MI->getOperand(j).isReg() &&
305 MI->getOperand(j).getReg() == li.reg) {
306 MI->getOperand(j).setReg(NewVReg);
307 HasUse |= MI->getOperand(j).isUse();
308 HasDef |= MI->getOperand(j).isDef();
309 }
310 }
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000311
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000312 // create a new register for this spill
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000313 vrm.grow();
Chris Lattner29268692006-09-05 02:12:02 +0000314 vrm.assignVirt2StackSlot(NewVReg, slot);
315 LiveInterval &nI = getOrCreateInterval(NewVReg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000316 assert(nI.empty());
Chris Lattner70ca3582004-09-30 15:59:17 +0000317
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000318 // the spill weight is now infinity as it
319 // cannot be spilled again
Chris Lattner28696be2005-01-08 19:55:00 +0000320 nI.weight = float(HUGE_VAL);
Chris Lattner29268692006-09-05 02:12:02 +0000321
322 if (HasUse) {
323 LiveRange LR(getLoadIndex(index), getUseIndex(index),
324 nI.getNextValue(~0U, 0));
325 DEBUG(std::cerr << " +" << LR);
326 nI.addRange(LR);
327 }
328 if (HasDef) {
329 LiveRange LR(getDefIndex(index), getStoreIndex(index),
330 nI.getNextValue(~0U, 0));
331 DEBUG(std::cerr << " +" << LR);
332 nI.addRange(LR);
333 }
334
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000335 added.push_back(&nI);
Chris Lattner70ca3582004-09-30 15:59:17 +0000336
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000337 // update live variables if it is available
338 if (lv_)
Chris Lattner29268692006-09-05 02:12:02 +0000339 lv_->addVirtualRegisterKilled(NewVReg, MI);
Chris Lattnerb11443d2005-09-09 19:17:47 +0000340
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000341 DEBUG(std::cerr << "\t\t\t\tadded new interval: ";
342 nI.print(std::cerr, mri_); std::cerr << '\n');
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000343 }
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000344 }
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 Evlogimenos26f5a692004-05-30 07:24:39 +0000348
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000349 return added;
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000350}
351
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000352void LiveIntervals::printRegName(unsigned reg) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000353 if (MRegisterInfo::isPhysicalRegister(reg))
354 std::cerr << mri_->getName(reg);
355 else
356 std::cerr << "%reg" << reg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000357}
358
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000359void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000360 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000361 unsigned MIIdx,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000362 LiveInterval &interval) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000363 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
364 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000365
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000366 // Virtual registers may be defined multiple times (due to phi
367 // elimination and 2-addr elimination). Much of what we do only has to be
368 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000369 // time we see a vreg.
370 if (interval.empty()) {
371 // Get the Idx of the defining instructions.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000372 unsigned defIndex = getDefIndex(MIIdx);
Chris Lattner6097d132004-07-19 02:15:56 +0000373
Chris Lattner91725b72006-08-31 05:54:43 +0000374 unsigned ValNum;
375 unsigned SrcReg, DstReg;
376 if (!tii_->isMoveInstr(*mi, SrcReg, DstReg))
377 ValNum = interval.getNextValue(~0U, 0);
378 else
379 ValNum = interval.getNextValue(defIndex, SrcReg);
380
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000381 assert(ValNum == 0 && "First value in interval is not 0?");
382 ValNum = 0; // Clue in the optimizer.
Chris Lattner7ac2d312004-07-24 02:59:07 +0000383
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000384 // Loop over all of the blocks that the vreg is defined in. There are
385 // two cases we have to handle here. The most common case is a vreg
386 // whose lifetime is contained within a basic block. In this case there
387 // will be a single kill, in MBB, which comes after the definition.
388 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
389 // FIXME: what about dead vars?
390 unsigned killIdx;
391 if (vi.Kills[0] != mi)
392 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
393 else
394 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000395
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000396 // If the kill happens after the definition, we have an intra-block
397 // live range.
398 if (killIdx > defIndex) {
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000399 assert(vi.AliveBlocks.empty() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000400 "Shouldn't be alive across any blocks!");
401 LiveRange LR(defIndex, killIdx, ValNum);
402 interval.addRange(LR);
403 DEBUG(std::cerr << " +" << LR << "\n");
404 return;
405 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000406 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000407
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000408 // The other case we handle is when a virtual register lives to the end
409 // of the defining block, potentially live across some blocks, then is
410 // live into some number of blocks, but gets killed. Start by adding a
411 // range that goes from this definition to the end of the defining block.
Alkis Evlogimenosd19e2902004-08-31 17:39:15 +0000412 LiveRange NewLR(defIndex,
413 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
414 ValNum);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000415 DEBUG(std::cerr << " +" << NewLR);
416 interval.addRange(NewLR);
417
418 // Iterate over all of the blocks that the variable is completely
419 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
420 // live interval.
421 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
422 if (vi.AliveBlocks[i]) {
423 MachineBasicBlock* mbb = mf_->getBlockNumbered(i);
424 if (!mbb->empty()) {
425 LiveRange LR(getInstructionIndex(&mbb->front()),
Alkis Evlogimenosd19e2902004-08-31 17:39:15 +0000426 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000427 ValNum);
428 interval.addRange(LR);
429 DEBUG(std::cerr << " +" << LR);
430 }
431 }
432 }
433
434 // Finally, this virtual register is live from the start of any killing
435 // block to the 'use' slot of the killing instruction.
436 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
437 MachineInstr *Kill = vi.Kills[i];
438 LiveRange LR(getInstructionIndex(Kill->getParent()->begin()),
Alkis Evlogimenosd19e2902004-08-31 17:39:15 +0000439 getUseIndex(getInstructionIndex(Kill))+1,
440 ValNum);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000441 interval.addRange(LR);
442 DEBUG(std::cerr << " +" << LR);
443 }
444
445 } else {
446 // If this is the second time we see a virtual register definition, it
447 // must be due to phi elimination or two addr elimination. If this is
448 // the result of two address elimination, then the vreg is the first
449 // operand, and is a def-and-use.
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000450 if (mi->getOperand(0).isRegister() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000451 mi->getOperand(0).getReg() == interval.reg &&
Chris Lattner29268692006-09-05 02:12:02 +0000452 mi->getNumOperands() > 1 && mi->getOperand(1).isRegister() &&
453 mi->getOperand(1).getReg() == interval.reg &&
454 mi->getOperand(0).isDef() && mi->getOperand(1).isUse()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000455 // If this is a two-address definition, then we have already processed
456 // the live range. The only problem is that we didn't realize there
457 // are actually two values in the live interval. Because of this we
458 // need to take the LiveRegion that defines this register and split it
459 // into two values.
460 unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
Chris Lattner6b128bd2006-09-03 08:07:11 +0000461 unsigned RedefIndex = getDefIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000462
463 // Delete the initial value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000464 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000465 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000466
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000467 // Two-address vregs should always only be redefined once. This means
468 // that at this point, there should be exactly one value number in it.
469 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
470
Chris Lattner91725b72006-08-31 05:54:43 +0000471 // The new value number (#1) is defined by the instruction we claimed
472 // defined value #0.
473 unsigned ValNo = interval.getNextValue(0, 0);
474 interval.setValueNumberInfo(1, interval.getValNumInfo(0));
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000475
Chris Lattner91725b72006-08-31 05:54:43 +0000476 // Value#0 is now defined by the 2-addr instruction.
477 interval.setValueNumberInfo(0, std::make_pair(~0U, 0U));
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000478
479 // Add the new live interval which replaces the range for the input copy.
480 LiveRange LR(DefIndex, RedefIndex, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000481 DEBUG(std::cerr << " replace range with " << LR);
482 interval.addRange(LR);
483
484 // If this redefinition is dead, we need to add a dummy unit live
485 // range covering the def slot.
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000486 if (lv_->RegisterDefIsDead(mi, interval.reg))
487 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, 0));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000488
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000489 DEBUG(std::cerr << "RESULT: "; interval.print(std::cerr, mri_));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000490
491 } else {
492 // Otherwise, this must be because of phi elimination. If this is the
493 // first redefinition of the vreg that we have seen, go back and change
494 // the live range in the PHI block to be a different value number.
495 if (interval.containsOneValue()) {
496 assert(vi.Kills.size() == 1 &&
497 "PHI elimination vreg should have one kill, the PHI itself!");
498
499 // Remove the old range that we now know has an incorrect number.
500 MachineInstr *Killer = vi.Kills[0];
501 unsigned Start = getInstructionIndex(Killer->getParent()->begin());
502 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000503 DEBUG(std::cerr << "Removing [" << Start << "," << End << "] from: ";
504 interval.print(std::cerr, mri_); std::cerr << "\n");
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000505 interval.removeRange(Start, End);
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000506 DEBUG(std::cerr << "RESULT: "; interval.print(std::cerr, mri_));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000507
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000508 // Replace the interval with one of a NEW value number. Note that this
509 // value number isn't actually defined by an instruction, weird huh? :)
Chris Lattner91725b72006-08-31 05:54:43 +0000510 LiveRange LR(Start, End, interval.getNextValue(~0U, 0));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000511 DEBUG(std::cerr << " replace range with " << LR);
512 interval.addRange(LR);
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000513 DEBUG(std::cerr << "RESULT: "; interval.print(std::cerr, mri_));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000514 }
515
516 // In the case of PHI elimination, each variable definition is only
517 // live until the end of the block. We've already taken care of the
518 // rest of the live range.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000519 unsigned defIndex = getDefIndex(MIIdx);
Chris Lattner91725b72006-08-31 05:54:43 +0000520
521 unsigned ValNum;
522 unsigned SrcReg, DstReg;
523 if (!tii_->isMoveInstr(*mi, SrcReg, DstReg))
524 ValNum = interval.getNextValue(~0U, 0);
525 else
526 ValNum = interval.getNextValue(defIndex, SrcReg);
527
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000528 LiveRange LR(defIndex,
Chris Lattner91725b72006-08-31 05:54:43 +0000529 getInstructionIndex(&mbb->back()) + InstrSlots::NUM, ValNum);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000530 interval.addRange(LR);
531 DEBUG(std::cerr << " +" << LR);
532 }
533 }
534
535 DEBUG(std::cerr << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000536}
537
Chris Lattnerf35fef72004-07-23 21:24:19 +0000538void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000539 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000540 unsigned MIIdx,
Chris Lattner91725b72006-08-31 05:54:43 +0000541 LiveInterval &interval,
542 unsigned SrcReg) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000543 // A physical register cannot be live across basic block, so its
544 // lifetime must end somewhere in its defining basic block.
545 DEBUG(std::cerr << "\t\tregister: "; printRegName(interval.reg));
546 typedef LiveVariables::killed_iterator KillIter;
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000547
Chris Lattner6b128bd2006-09-03 08:07:11 +0000548 unsigned baseIndex = MIIdx;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000549 unsigned start = getDefIndex(baseIndex);
550 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000551
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000552 // If it is not used after definition, it is considered dead at
553 // the instruction defining it. Hence its interval is:
554 // [defSlot(def), defSlot(def)+1)
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000555 if (lv_->RegisterDefIsDead(mi, interval.reg)) {
556 DEBUG(std::cerr << " dead");
557 end = getDefIndex(start) + 1;
558 goto exit;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000559 }
560
561 // If it is not dead on definition, it must be killed by a
562 // subsequent instruction. Hence its interval is:
563 // [defSlot(def), useSlot(kill)+1)
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000564 while (++mi != MBB->end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000565 baseIndex += InstrSlots::NUM;
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000566 if (lv_->KillsRegister(mi, interval.reg)) {
567 DEBUG(std::cerr << " killed");
568 end = getUseIndex(baseIndex) + 1;
569 goto exit;
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000570 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000571 }
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000572
573 // The only case we should have a dead physreg here without a killing or
574 // instruction where we know it's dead is if it is live-in to the function
575 // and never used.
Chris Lattner91725b72006-08-31 05:54:43 +0000576 assert(!SrcReg && "physreg was not killed in defining block!");
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000577 end = getDefIndex(start) + 1; // It's dead.
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000578
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000579exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000580 assert(start < end && "did not find end of interval?");
Chris Lattnerf768bba2005-03-09 23:05:19 +0000581
Chris Lattner91725b72006-08-31 05:54:43 +0000582 LiveRange LR(start, end, interval.getNextValue(SrcReg != 0 ? start : ~0U,
583 SrcReg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000584 interval.addRange(LR);
585 DEBUG(std::cerr << " +" << LR << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000586}
587
Chris Lattnerf35fef72004-07-23 21:24:19 +0000588void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
589 MachineBasicBlock::iterator MI,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000590 unsigned MIIdx,
Chris Lattnerf35fef72004-07-23 21:24:19 +0000591 unsigned reg) {
592 if (MRegisterInfo::isVirtualRegister(reg))
Chris Lattner6b128bd2006-09-03 08:07:11 +0000593 handleVirtualRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg));
Alkis Evlogimenos53278012004-08-26 22:22:38 +0000594 else if (allocatableRegs_[reg]) {
Chris Lattner91725b72006-08-31 05:54:43 +0000595 unsigned SrcReg, DstReg;
596 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg))
597 SrcReg = 0;
Chris Lattner6b128bd2006-09-03 08:07:11 +0000598 handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg), SrcReg);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000599 for (const unsigned* AS = mri_->getAliasSet(reg); *AS; ++AS)
Chris Lattner6b128bd2006-09-03 08:07:11 +0000600 handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(*AS), 0);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000601 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000602}
603
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000604/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000605/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000606/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000607/// which a variable is live
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000608void LiveIntervals::computeIntervals() {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000609 DEBUG(std::cerr << "********** COMPUTING LIVE INTERVALS **********\n");
610 DEBUG(std::cerr << "********** Function: "
611 << ((Value*)mf_->getFunction())->getName() << '\n');
Chris Lattner799a9192005-04-09 16:17:50 +0000612 bool IgnoreFirstInstr = mf_->livein_begin() != mf_->livein_end();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000613
Chris Lattner6b128bd2006-09-03 08:07:11 +0000614 // Track the index of the current machine instr.
615 unsigned MIIndex = 0;
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000616 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000617 I != E; ++I) {
618 MachineBasicBlock* mbb = I;
619 DEBUG(std::cerr << ((Value*)mbb->getBasicBlock())->getName() << ":\n");
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000620
Chris Lattner799a9192005-04-09 16:17:50 +0000621 MachineBasicBlock::iterator mi = mbb->begin(), miEnd = mbb->end();
Chris Lattnerdffb2e82006-09-04 18:27:40 +0000622 if (IgnoreFirstInstr) {
623 ++mi;
624 IgnoreFirstInstr = false;
625 MIIndex += InstrSlots::NUM;
626 }
627
Chris Lattner799a9192005-04-09 16:17:50 +0000628 for (; mi != miEnd; ++mi) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000629 const TargetInstrDescriptor& tid =
630 tm_->getInstrInfo()->get(mi->getOpcode());
Chris Lattner6b128bd2006-09-03 08:07:11 +0000631 DEBUG(std::cerr << MIIndex << "\t" << *mi);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000632
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000633 // handle implicit defs
Jim Laskeycd4317e2006-07-21 21:15:20 +0000634 if (tid.ImplicitDefs) {
635 for (const unsigned* id = tid.ImplicitDefs; *id; ++id)
Chris Lattner6b128bd2006-09-03 08:07:11 +0000636 handleRegisterDef(mbb, mi, MIIndex, *id);
Jim Laskeycd4317e2006-07-21 21:15:20 +0000637 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000638
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000639 // handle explicit defs
640 for (int i = mi->getNumOperands() - 1; i >= 0; --i) {
641 MachineOperand& mop = mi->getOperand(i);
642 // handle register defs - build intervals
643 if (mop.isRegister() && mop.getReg() && mop.isDef())
Chris Lattner6b128bd2006-09-03 08:07:11 +0000644 handleRegisterDef(mbb, mi, MIIndex, mop.getReg());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000645 }
Chris Lattner6b128bd2006-09-03 08:07:11 +0000646
647 MIIndex += InstrSlots::NUM;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000648 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000649 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000650}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000651
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000652/// AdjustCopiesBackFrom - We found a non-trivially-coallescable copy with IntA
653/// being the source and IntB being the dest, thus this defines a value number
654/// in IntB. If the source value number (in IntA) is defined by a copy from B,
655/// see if we can merge these two pieces of B into a single value number,
656/// eliminating a copy. For example:
657///
658/// A3 = B0
659/// ...
660/// B1 = A3 <- this copy
661///
662/// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
663/// value number to be replaced with B0 (which simplifies the B liveinterval).
664///
665/// This returns true if an interval was modified.
666///
667bool LiveIntervals::AdjustCopiesBackFrom(LiveInterval &IntA, LiveInterval &IntB,
Chris Lattner6d8fbef2006-08-29 23:18:15 +0000668 MachineInstr *CopyMI) {
669 unsigned CopyIdx = getDefIndex(getInstructionIndex(CopyMI));
670
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000671 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
672 // the example above.
673 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
674 unsigned BValNo = BLR->ValId;
Chris Lattneraa51a482005-10-21 06:49:50 +0000675
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000676 // Get the location that B is defined at. Two options: either this value has
677 // an unknown definition point or it is defined at CopyIdx. If unknown, we
678 // can't process it.
679 unsigned BValNoDefIdx = IntB.getInstForValNum(BValNo);
680 if (BValNoDefIdx == ~0U) return false;
681 assert(BValNoDefIdx == CopyIdx &&
682 "Copy doesn't define the value?");
Chris Lattneraa51a482005-10-21 06:49:50 +0000683
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000684 // AValNo is the value number in A that defines the copy, A0 in the example.
685 LiveInterval::iterator AValLR = IntA.FindLiveRangeContaining(CopyIdx-1);
686 unsigned AValNo = AValLR->ValId;
Chris Lattneraa51a482005-10-21 06:49:50 +0000687
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000688 // If AValNo is defined as a copy from IntB, we can potentially process this.
689
690 // Get the instruction that defines this value number.
Chris Lattner91725b72006-08-31 05:54:43 +0000691 unsigned SrcReg = IntA.getSrcRegForValNum(AValNo);
692 if (!SrcReg) return false; // Not defined by a copy.
Chris Lattneraa51a482005-10-21 06:49:50 +0000693
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000694 // If the value number is not defined by a copy instruction, ignore it.
Chris Lattneraa51a482005-10-21 06:49:50 +0000695
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000696 // If the source register comes from an interval other than IntB, we can't
697 // handle this.
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000698 if (rep(SrcReg) != IntB.reg) return false;
Chris Lattner91725b72006-08-31 05:54:43 +0000699
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000700 // Get the LiveRange in IntB that this value number starts with.
Chris Lattner91725b72006-08-31 05:54:43 +0000701 unsigned AValNoInstIdx = IntA.getInstForValNum(AValNo);
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000702 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNoInstIdx-1);
703
704 // Make sure that the end of the live range is inside the same block as
705 // CopyMI.
706 MachineInstr *ValLREndInst = getInstructionFromIndex(ValLR->end-1);
Chris Lattnerc114b2c2006-08-25 23:41:24 +0000707 if (!ValLREndInst ||
708 ValLREndInst->getParent() != CopyMI->getParent()) return false;
Chris Lattneraa51a482005-10-21 06:49:50 +0000709
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000710 // Okay, we now know that ValLR ends in the same block that the CopyMI
711 // live-range starts. If there are no intervening live ranges between them in
712 // IntB, we can merge them.
713 if (ValLR+1 != BLR) return false;
Chris Lattneraa51a482005-10-21 06:49:50 +0000714
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000715 DEBUG(std::cerr << "\nExtending: "; IntB.print(std::cerr, mri_));
Chris Lattnerba256032006-08-30 23:02:29 +0000716
717 // We are about to delete CopyMI, so need to remove it as the 'instruction
718 // that defines this value #'.
Chris Lattner91725b72006-08-31 05:54:43 +0000719 IntB.setValueNumberInfo(BValNo, std::make_pair(~0U, 0));
Chris Lattnerba256032006-08-30 23:02:29 +0000720
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000721 // Okay, we can merge them. We need to insert a new liverange:
722 // [ValLR.end, BLR.begin) of either value number, then we merge the
723 // two value numbers.
Chris Lattnerc114b2c2006-08-25 23:41:24 +0000724 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
725 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
726
727 // If the IntB live range is assigned to a physical register, and if that
728 // physreg has aliases,
729 if (MRegisterInfo::isPhysicalRegister(IntB.reg)) {
730 for (const unsigned *AS = mri_->getAliasSet(IntB.reg); *AS; ++AS) {
731 LiveInterval &AliasLI = getInterval(*AS);
732 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
Chris Lattner91725b72006-08-31 05:54:43 +0000733 AliasLI.getNextValue(~0U, 0)));
Chris Lattnerc114b2c2006-08-25 23:41:24 +0000734 }
735 }
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000736
737 // Okay, merge "B1" into the same value number as "B0".
738 if (BValNo != ValLR->ValId)
739 IntB.MergeValueNumberInto(BValNo, ValLR->ValId);
740 DEBUG(std::cerr << " result = "; IntB.print(std::cerr, mri_);
741 std::cerr << "\n");
Chris Lattneraa51a482005-10-21 06:49:50 +0000742
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000743 // Finally, delete the copy instruction.
744 RemoveMachineInstrFromMaps(CopyMI);
745 CopyMI->eraseFromParent();
746 ++numPeep;
Chris Lattneraa51a482005-10-21 06:49:50 +0000747 return true;
748}
749
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000750
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000751/// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
752/// which are the src/dst of the copy instruction CopyMI. This returns true
753/// if the copy was successfully coallesced away, or if it is never possible
754/// to coallesce these this copy, due to register constraints. It returns
755/// false if it is not currently possible to coallesce this interval, but
756/// it may be possible if other things get coallesced.
757bool LiveIntervals::JoinCopy(MachineInstr *CopyMI,
758 unsigned SrcReg, unsigned DstReg) {
759
760
761 DEBUG(std::cerr << getInstructionIndex(CopyMI) << '\t' << *CopyMI);
762
763 // Get representative registers.
764 SrcReg = rep(SrcReg);
765 DstReg = rep(DstReg);
766
767 // If they are already joined we continue.
768 if (SrcReg == DstReg) {
769 DEBUG(std::cerr << "\tCopy already coallesced.\n");
770 return true; // Not coallescable.
Chris Lattner7ac2d312004-07-24 02:59:07 +0000771 }
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000772
773 // If they are both physical registers, we cannot join them.
774 if (MRegisterInfo::isPhysicalRegister(SrcReg) &&
775 MRegisterInfo::isPhysicalRegister(DstReg)) {
776 DEBUG(std::cerr << "\tCan not coallesce physregs.\n");
777 return true; // Not coallescable.
778 }
779
780 // We only join virtual registers with allocatable physical registers.
781 if (MRegisterInfo::isPhysicalRegister(SrcReg) && !allocatableRegs_[SrcReg]){
782 DEBUG(std::cerr << "\tSrc reg is unallocatable physreg.\n");
783 return true; // Not coallescable.
784 }
785 if (MRegisterInfo::isPhysicalRegister(DstReg) && !allocatableRegs_[DstReg]){
786 DEBUG(std::cerr << "\tDst reg is unallocatable physreg.\n");
787 return true; // Not coallescable.
788 }
789
790 // If they are not of the same register class, we cannot join them.
791 if (differingRegisterClasses(SrcReg, DstReg)) {
792 DEBUG(std::cerr << "\tSrc/Dest are different register classes.\n");
793 return true; // Not coallescable.
794 }
795
796 LiveInterval &SrcInt = getInterval(SrcReg);
797 LiveInterval &DestInt = getInterval(DstReg);
798 assert(SrcInt.reg == SrcReg && DestInt.reg == DstReg &&
799 "Register mapping is horribly broken!");
800
801 DEBUG(std::cerr << "\t\tInspecting "; SrcInt.print(std::cerr, mri_);
802 std::cerr << " and "; DestInt.print(std::cerr, mri_);
803 std::cerr << ": ");
804
Chris Lattner6d8fbef2006-08-29 23:18:15 +0000805 // Okay, attempt to join these two intervals. On failure, this returns false.
806 // Otherwise, if one of the intervals being joined is a physreg, this method
807 // always canonicalizes DestInt to be it. The output "SrcInt" will not have
808 // been modified, so we can use this information below to update aliases.
809 if (!JoinIntervals(DestInt, SrcInt)) {
810 // Coallescing failed.
811
812 // If we can eliminate the copy without merging the live ranges, do so now.
813 if (AdjustCopiesBackFrom(SrcInt, DestInt, CopyMI))
814 return true;
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000815
Chris Lattner6d8fbef2006-08-29 23:18:15 +0000816 // Otherwise, we are unable to join the intervals.
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000817 DEBUG(std::cerr << "Interference!\n");
818 return false;
819 }
820
Chris Lattnere7f729b2006-08-26 01:28:16 +0000821 bool Swapped = SrcReg == DestInt.reg;
822 if (Swapped)
823 std::swap(SrcReg, DstReg);
824 assert(MRegisterInfo::isVirtualRegister(SrcReg) &&
825 "LiveInterval::join didn't work right!");
826
Chris Lattnerc114b2c2006-08-25 23:41:24 +0000827 // If we're about to merge live ranges into a physical register live range,
828 // we have to update any aliased register's live ranges to indicate that they
829 // have clobbered values for this range.
Chris Lattnere7f729b2006-08-26 01:28:16 +0000830 if (MRegisterInfo::isPhysicalRegister(DstReg)) {
831 for (const unsigned *AS = mri_->getAliasSet(DstReg); *AS; ++AS)
832 getInterval(*AS).MergeInClobberRanges(SrcInt);
Chris Lattnerc114b2c2006-08-25 23:41:24 +0000833 }
834
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000835 DEBUG(std::cerr << "\n\t\tJoined. Result = "; DestInt.print(std::cerr, mri_);
836 std::cerr << "\n");
Chris Lattnere7f729b2006-08-26 01:28:16 +0000837
838 // If the intervals were swapped by Join, swap them back so that the register
839 // mapping (in the r2i map) is correct.
840 if (Swapped) SrcInt.swap(DestInt);
841 r2iMap_.erase(SrcReg);
842 r2rMap_[SrcReg] = DstReg;
843
Chris Lattnerbfe180a2006-08-31 05:58:59 +0000844 // Finally, delete the copy instruction.
845 RemoveMachineInstrFromMaps(CopyMI);
846 CopyMI->eraseFromParent();
847 ++numPeep;
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000848 ++numJoins;
849 return true;
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000850}
851
Chris Lattner6d8fbef2006-08-29 23:18:15 +0000852/// ComputeUltimateVN - Assuming we are going to join two live intervals,
853/// compute what the resultant value numbers for each value in the input two
854/// ranges will be. This is complicated by copies between the two which can
855/// and will commonly cause multiple value numbers to be merged into one.
856///
857/// VN is the value number that we're trying to resolve. InstDefiningValue
858/// keeps track of the new InstDefiningValue assignment for the result
859/// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
860/// whether a value in this or other is a copy from the opposite set.
861/// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
862/// already been assigned.
863///
864/// ThisFromOther[x] - If x is defined as a copy from the other interval, this
865/// contains the value number the copy is from.
866///
867static unsigned ComputeUltimateVN(unsigned VN,
Chris Lattner91725b72006-08-31 05:54:43 +0000868 SmallVector<std::pair<unsigned,
869 unsigned>, 16> &ValueNumberInfo,
Chris Lattner6d8fbef2006-08-29 23:18:15 +0000870 SmallVector<int, 16> &ThisFromOther,
871 SmallVector<int, 16> &OtherFromThis,
872 SmallVector<int, 16> &ThisValNoAssignments,
873 SmallVector<int, 16> &OtherValNoAssignments,
874 LiveInterval &ThisLI, LiveInterval &OtherLI) {
875 // If the VN has already been computed, just return it.
876 if (ThisValNoAssignments[VN] >= 0)
877 return ThisValNoAssignments[VN];
Chris Lattner8a67f6e2006-09-01 07:00:23 +0000878// assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
Chris Lattner6d8fbef2006-08-29 23:18:15 +0000879
880 // If this val is not a copy from the other val, then it must be a new value
881 // number in the destination.
882 int OtherValNo = ThisFromOther[VN];
883 if (OtherValNo == -1) {
Chris Lattner91725b72006-08-31 05:54:43 +0000884 ValueNumberInfo.push_back(ThisLI.getValNumInfo(VN));
885 return ThisValNoAssignments[VN] = ValueNumberInfo.size()-1;
Chris Lattner6d8fbef2006-08-29 23:18:15 +0000886 }
887
Chris Lattner8a67f6e2006-09-01 07:00:23 +0000888 // Otherwise, this *is* a copy from the RHS. If the other side has already
889 // been computed, return it.
890 if (OtherValNoAssignments[OtherValNo] >= 0)
891 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo];
892
893 // Mark this value number as currently being computed, then ask what the
894 // ultimate value # of the other value is.
Chris Lattner6d8fbef2006-08-29 23:18:15 +0000895 ThisValNoAssignments[VN] = -2;
896 unsigned UltimateVN =
Chris Lattner91725b72006-08-31 05:54:43 +0000897 ComputeUltimateVN(OtherValNo, ValueNumberInfo,
Chris Lattner6d8fbef2006-08-29 23:18:15 +0000898 OtherFromThis, ThisFromOther,
899 OtherValNoAssignments, ThisValNoAssignments,
900 OtherLI, ThisLI);
901 return ThisValNoAssignments[VN] = UltimateVN;
902}
903
Chris Lattnerf21f0202006-09-02 05:26:59 +0000904static bool InVector(unsigned Val, const SmallVector<unsigned, 8> &V) {
905 return std::find(V.begin(), V.end(), Val) != V.end();
906}
907
908/// SimpleJoin - Attempt to joint the specified interval into this one. The
909/// caller of this method must guarantee that the RHS only contains a single
910/// value number and that the RHS is not defined by a copy from this
911/// interval. This returns false if the intervals are not joinable, or it
912/// joins them and returns true.
913bool LiveIntervals::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS) {
914 assert(RHS.containsOneValue());
915
916 // Some number (potentially more than one) value numbers in the current
917 // interval may be defined as copies from the RHS. Scan the overlapping
918 // portions of the LHS and RHS, keeping track of this and looking for
919 // overlapping live ranges that are NOT defined as copies. If these exist, we
920 // cannot coallesce.
921
922 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
923 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
924
925 if (LHSIt->start < RHSIt->start) {
926 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
927 if (LHSIt != LHS.begin()) --LHSIt;
928 } else if (RHSIt->start < LHSIt->start) {
929 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
930 if (RHSIt != RHS.begin()) --RHSIt;
931 }
932
933 SmallVector<unsigned, 8> EliminatedLHSVals;
934
935 while (1) {
936 // Determine if these live intervals overlap.
937 bool Overlaps = false;
938 if (LHSIt->start <= RHSIt->start)
939 Overlaps = LHSIt->end > RHSIt->start;
940 else
941 Overlaps = RHSIt->end > LHSIt->start;
942
943 // If the live intervals overlap, there are two interesting cases: if the
944 // LHS interval is defined by a copy from the RHS, it's ok and we record
945 // that the LHS value # is the same as the RHS. If it's not, then we cannot
946 // coallesce these live ranges and we bail out.
947 if (Overlaps) {
948 // If we haven't already recorded that this value # is safe, check it.
949 if (!InVector(LHSIt->ValId, EliminatedLHSVals)) {
950 // Copy from the RHS?
951 unsigned SrcReg = LHS.getSrcRegForValNum(LHSIt->ValId);
952 if (rep(SrcReg) != RHS.reg)
953 return false; // Nope, bail out.
954
955 EliminatedLHSVals.push_back(LHSIt->ValId);
956 }
957
958 // We know this entire LHS live range is okay, so skip it now.
959 if (++LHSIt == LHSEnd) break;
960 continue;
961 }
962
963 if (LHSIt->end < RHSIt->end) {
964 if (++LHSIt == LHSEnd) break;
965 } else {
966 // One interesting case to check here. It's possible that we have
967 // something like "X3 = Y" which defines a new value number in the LHS,
968 // and is the last use of this liverange of the RHS. In this case, we
969 // want to notice this copy (so that it gets coallesced away) even though
970 // the live ranges don't actually overlap.
971 if (LHSIt->start == RHSIt->end) {
972 if (InVector(LHSIt->ValId, EliminatedLHSVals)) {
973 // We already know that this value number is going to be merged in
974 // if coallescing succeeds. Just skip the liverange.
975 if (++LHSIt == LHSEnd) break;
976 } else {
977 // Otherwise, if this is a copy from the RHS, mark it as being merged
978 // in.
979 if (rep(LHS.getSrcRegForValNum(LHSIt->ValId)) == RHS.reg) {
980 EliminatedLHSVals.push_back(LHSIt->ValId);
981
982 // We know this entire LHS live range is okay, so skip it now.
983 if (++LHSIt == LHSEnd) break;
984 }
985 }
986 }
987
988 if (++RHSIt == RHSEnd) break;
989 }
990 }
991
992 // If we got here, we know that the coallescing will be successful and that
993 // the value numbers in EliminatedLHSVals will all be merged together. Since
994 // the most common case is that EliminatedLHSVals has a single number, we
995 // optimize for it: if there is more than one value, we merge them all into
996 // the lowest numbered one, then handle the interval as if we were merging
997 // with one value number.
998 unsigned LHSValNo;
999 if (EliminatedLHSVals.size() > 1) {
1000 // Loop through all the equal value numbers merging them into the smallest
1001 // one.
1002 unsigned Smallest = EliminatedLHSVals[0];
1003 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1004 if (EliminatedLHSVals[i] < Smallest) {
1005 // Merge the current notion of the smallest into the smaller one.
1006 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1007 Smallest = EliminatedLHSVals[i];
1008 } else {
1009 // Merge into the smallest.
1010 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1011 }
1012 }
1013 LHSValNo = Smallest;
1014 } else {
1015 assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
1016 LHSValNo = EliminatedLHSVals[0];
1017 }
1018
1019 // Okay, now that there is a single LHS value number that we're merging the
1020 // RHS into, update the value number info for the LHS to indicate that the
1021 // value number is defined where the RHS value number was.
1022 LHS.setValueNumberInfo(LHSValNo, RHS.getValNumInfo(0));
1023
1024 // Okay, the final step is to loop over the RHS live intervals, adding them to
1025 // the LHS.
1026 LHS.MergeRangesInAsValue(RHS, LHSValNo);
1027 LHS.weight += RHS.weight;
1028
1029 return true;
1030}
1031
Chris Lattner6d8fbef2006-08-29 23:18:15 +00001032/// JoinIntervals - Attempt to join these two intervals. On failure, this
1033/// returns false. Otherwise, if one of the intervals being joined is a
1034/// physreg, this method always canonicalizes LHS to be it. The output
1035/// "RHS" will not have been modified, so we can use this information
1036/// below to update aliases.
1037bool LiveIntervals::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS) {
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001038 // Compute the final value assignment, assuming that the live ranges can be
1039 // coallesced.
Chris Lattner6d8fbef2006-08-29 23:18:15 +00001040 SmallVector<int, 16> LHSValNoAssignments;
1041 SmallVector<int, 16> RHSValNoAssignments;
Chris Lattner91725b72006-08-31 05:54:43 +00001042 SmallVector<std::pair<unsigned,unsigned>, 16> ValueNumberInfo;
Chris Lattner238416c2006-09-01 06:10:18 +00001043
Chris Lattner6d8fbef2006-08-29 23:18:15 +00001044 // Compute ultimate value numbers for the LHS and RHS values.
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001045 if (RHS.containsOneValue()) {
1046 // Copies from a liveinterval with a single value are simple to handle and
1047 // very common, handle the special case here. This is important, because
1048 // often RHS is small and LHS is large (e.g. a physreg).
1049
1050 // Find out if the RHS is defined as a copy from some value in the LHS.
1051 int RHSValID = -1;
1052 std::pair<unsigned,unsigned> RHSValNoInfo;
Chris Lattnerf21f0202006-09-02 05:26:59 +00001053 unsigned RHSSrcReg = RHS.getSrcRegForValNum(0);
1054 if ((RHSSrcReg == 0 || rep(RHSSrcReg) != LHS.reg)) {
1055 // If RHS is not defined as a copy from the LHS, we can use simpler and
1056 // faster checks to see if the live ranges are coallescable. This joiner
1057 // can't swap the LHS/RHS intervals though.
1058 if (!MRegisterInfo::isPhysicalRegister(RHS.reg)) {
1059 return SimpleJoin(LHS, RHS);
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001060 } else {
Chris Lattnerf21f0202006-09-02 05:26:59 +00001061 RHSValNoInfo = RHS.getValNumInfo(0);
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001062 }
1063 } else {
Chris Lattnerf21f0202006-09-02 05:26:59 +00001064 // It was defined as a copy from the LHS, find out what value # it is.
1065 unsigned ValInst = RHS.getInstForValNum(0);
1066 RHSValID = LHS.getLiveRangeContaining(ValInst-1)->ValId;
1067 RHSValNoInfo = LHS.getValNumInfo(RHSValID);
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001068 }
1069
Chris Lattnerf21f0202006-09-02 05:26:59 +00001070 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1071 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001072 ValueNumberInfo.resize(LHS.getNumValNums());
1073
1074 // Okay, *all* of the values in LHS that are defined as a copy from RHS
1075 // should now get updated.
1076 for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
1077 if (unsigned LHSSrcReg = LHS.getSrcRegForValNum(VN)) {
1078 if (rep(LHSSrcReg) != RHS.reg) {
1079 // If this is not a copy from the RHS, its value number will be
1080 // unmodified by the coallescing.
1081 ValueNumberInfo[VN] = LHS.getValNumInfo(VN);
1082 LHSValNoAssignments[VN] = VN;
1083 } else if (RHSValID == -1) {
1084 // Otherwise, it is a copy from the RHS, and we don't already have a
1085 // value# for it. Keep the current value number, but remember it.
1086 LHSValNoAssignments[VN] = RHSValID = VN;
1087 ValueNumberInfo[VN] = RHSValNoInfo;
1088 } else {
1089 // Otherwise, use the specified value #.
1090 LHSValNoAssignments[VN] = RHSValID;
1091 if (VN != (unsigned)RHSValID)
1092 ValueNumberInfo[VN].first = ~1U;
1093 else
1094 ValueNumberInfo[VN] = RHSValNoInfo;
1095 }
1096 } else {
1097 ValueNumberInfo[VN] = LHS.getValNumInfo(VN);
1098 LHSValNoAssignments[VN] = VN;
1099 }
1100 }
1101
1102 assert(RHSValID != -1 && "Didn't find value #?");
1103 RHSValNoAssignments[0] = RHSValID;
1104
1105 } else {
Chris Lattner238416c2006-09-01 06:10:18 +00001106 // Loop over the value numbers of the LHS, seeing if any are defined from
1107 // the RHS.
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001108 SmallVector<int, 16> LHSValsDefinedFromRHS;
1109 LHSValsDefinedFromRHS.resize(LHS.getNumValNums(), -1);
1110 for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
1111 unsigned ValSrcReg = LHS.getSrcRegForValNum(VN);
1112 if (ValSrcReg == 0) // Src not defined by a copy?
1113 continue;
1114
Chris Lattner238416c2006-09-01 06:10:18 +00001115 // DstReg is known to be a register in the LHS interval. If the src is
1116 // from the RHS interval, we can use its value #.
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001117 if (rep(ValSrcReg) != RHS.reg)
1118 continue;
1119
1120 // Figure out the value # from the RHS.
1121 unsigned ValInst = LHS.getInstForValNum(VN);
1122 LHSValsDefinedFromRHS[VN] = RHS.getLiveRangeContaining(ValInst-1)->ValId;
1123 }
1124
Chris Lattner238416c2006-09-01 06:10:18 +00001125 // Loop over the value numbers of the RHS, seeing if any are defined from
1126 // the LHS.
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001127 SmallVector<int, 16> RHSValsDefinedFromLHS;
1128 RHSValsDefinedFromLHS.resize(RHS.getNumValNums(), -1);
1129 for (unsigned VN = 0, e = RHS.getNumValNums(); VN != e; ++VN) {
1130 unsigned ValSrcReg = RHS.getSrcRegForValNum(VN);
1131 if (ValSrcReg == 0) // Src not defined by a copy?
1132 continue;
1133
Chris Lattner238416c2006-09-01 06:10:18 +00001134 // DstReg is known to be a register in the RHS interval. If the src is
1135 // from the LHS interval, we can use its value #.
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001136 if (rep(ValSrcReg) != LHS.reg)
1137 continue;
1138
1139 // Figure out the value # from the LHS.
1140 unsigned ValInst = RHS.getInstForValNum(VN);
1141 RHSValsDefinedFromLHS[VN] = LHS.getLiveRangeContaining(ValInst-1)->ValId;
1142 }
1143
Chris Lattnerf21f0202006-09-02 05:26:59 +00001144 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1145 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1146 ValueNumberInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1147
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001148 for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
Chris Lattner8a67f6e2006-09-01 07:00:23 +00001149 if (LHSValNoAssignments[VN] >= 0 || LHS.getInstForValNum(VN) == ~2U)
1150 continue;
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001151 ComputeUltimateVN(VN, ValueNumberInfo,
1152 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1153 LHSValNoAssignments, RHSValNoAssignments, LHS, RHS);
1154 }
1155 for (unsigned VN = 0, e = RHS.getNumValNums(); VN != e; ++VN) {
Chris Lattner8a67f6e2006-09-01 07:00:23 +00001156 if (RHSValNoAssignments[VN] >= 0 || RHS.getInstForValNum(VN) == ~2U)
1157 continue;
1158 // If this value number isn't a copy from the LHS, it's a new number.
1159 if (RHSValsDefinedFromLHS[VN] == -1) {
1160 ValueNumberInfo.push_back(RHS.getValNumInfo(VN));
1161 RHSValNoAssignments[VN] = ValueNumberInfo.size()-1;
1162 continue;
1163 }
1164
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001165 ComputeUltimateVN(VN, ValueNumberInfo,
1166 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1167 RHSValNoAssignments, LHSValNoAssignments, RHS, LHS);
1168 }
Chris Lattner6d8fbef2006-08-29 23:18:15 +00001169 }
1170
1171 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1172 // interval lists to see if these intervals are coallescable.
1173 LiveInterval::const_iterator I = LHS.begin();
1174 LiveInterval::const_iterator IE = LHS.end();
1175 LiveInterval::const_iterator J = RHS.begin();
1176 LiveInterval::const_iterator JE = RHS.end();
1177
1178 // Skip ahead until the first place of potential sharing.
1179 if (I->start < J->start) {
1180 I = std::upper_bound(I, IE, J->start);
1181 if (I != LHS.begin()) --I;
1182 } else if (J->start < I->start) {
1183 J = std::upper_bound(J, JE, I->start);
1184 if (J != RHS.begin()) --J;
1185 }
1186
1187 while (1) {
1188 // Determine if these two live ranges overlap.
1189 bool Overlaps;
1190 if (I->start < J->start) {
1191 Overlaps = I->end > J->start;
1192 } else {
1193 Overlaps = J->end > I->start;
1194 }
1195
1196 // If so, check value # info to determine if they are really different.
1197 if (Overlaps) {
1198 // If the live range overlap will map to the same value number in the
1199 // result liverange, we can still coallesce them. If not, we can't.
1200 if (LHSValNoAssignments[I->ValId] != RHSValNoAssignments[J->ValId])
1201 return false;
1202 }
1203
1204 if (I->end < J->end) {
1205 ++I;
1206 if (I == IE) break;
1207 } else {
1208 ++J;
1209 if (J == JE) break;
1210 }
1211 }
1212
1213 // If we get here, we know that we can coallesce the live ranges. Ask the
1214 // intervals to coallesce themselves now.
1215 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0],
Chris Lattner91725b72006-08-31 05:54:43 +00001216 ValueNumberInfo);
Chris Lattner6d8fbef2006-08-29 23:18:15 +00001217 return true;
1218}
Chris Lattnerf7da2c72006-08-24 22:43:55 +00001219
1220
Chris Lattnercc0d1562004-07-19 14:40:29 +00001221namespace {
1222 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1223 // depth of the basic block (the unsigned), and then on the MBB number.
1224 struct DepthMBBCompare {
1225 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1226 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1227 if (LHS.first > RHS.first) return true; // Deeper loops first
Alkis Evlogimenos70651572004-08-04 09:46:56 +00001228 return LHS.first == RHS.first &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001229 LHS.second->getNumber() < RHS.second->getNumber();
Chris Lattnercc0d1562004-07-19 14:40:29 +00001230 }
1231 };
1232}
Chris Lattner1c5c0442004-07-19 14:08:10 +00001233
Chris Lattnerf7da2c72006-08-24 22:43:55 +00001234
Chris Lattner1acb17c2006-09-02 05:32:53 +00001235void LiveIntervals::CopyCoallesceInMBB(MachineBasicBlock *MBB,
1236 std::vector<CopyRec> &TryAgain) {
Chris Lattnerf7da2c72006-08-24 22:43:55 +00001237 DEBUG(std::cerr << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
1238
1239 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1240 MII != E;) {
1241 MachineInstr *Inst = MII++;
1242
1243 // If this isn't a copy, we can't join intervals.
1244 unsigned SrcReg, DstReg;
1245 if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg)) continue;
1246
Chris Lattner1acb17c2006-09-02 05:32:53 +00001247 if (!JoinCopy(Inst, SrcReg, DstReg))
1248 TryAgain.push_back(getCopyRec(Inst, SrcReg, DstReg));
Chris Lattnerf7da2c72006-08-24 22:43:55 +00001249 }
1250}
1251
1252
Chris Lattnercc0d1562004-07-19 14:40:29 +00001253void LiveIntervals::joinIntervals() {
1254 DEBUG(std::cerr << "********** JOINING INTERVALS ***********\n");
1255
Chris Lattner1acb17c2006-09-02 05:32:53 +00001256 std::vector<CopyRec> TryAgainList;
1257
Chris Lattnercc0d1562004-07-19 14:40:29 +00001258 const LoopInfo &LI = getAnalysis<LoopInfo>();
1259 if (LI.begin() == LI.end()) {
1260 // If there are no loops in the function, join intervals in function order.
Chris Lattner1c5c0442004-07-19 14:08:10 +00001261 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1262 I != E; ++I)
Chris Lattner1acb17c2006-09-02 05:32:53 +00001263 CopyCoallesceInMBB(I, TryAgainList);
Chris Lattnercc0d1562004-07-19 14:40:29 +00001264 } else {
1265 // Otherwise, join intervals in inner loops before other intervals.
1266 // Unfortunately we can't just iterate over loop hierarchy here because
1267 // there may be more MBB's than BB's. Collect MBB's for sorting.
1268 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1269 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1270 I != E; ++I)
1271 MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
1272
1273 // Sort by loop depth.
1274 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1275
Alkis Evlogimenos70651572004-08-04 09:46:56 +00001276 // Finally, join intervals in loop nest order.
Chris Lattnercc0d1562004-07-19 14:40:29 +00001277 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
Chris Lattner1acb17c2006-09-02 05:32:53 +00001278 CopyCoallesceInMBB(MBBs[i].second, TryAgainList);
1279 }
1280
1281 // Joining intervals can allow other intervals to be joined. Iteratively join
1282 // until we make no progress.
1283 bool ProgressMade = true;
1284 while (ProgressMade) {
1285 ProgressMade = false;
1286
1287 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1288 CopyRec &TheCopy = TryAgainList[i];
1289 if (TheCopy.MI &&
1290 JoinCopy(TheCopy.MI, TheCopy.SrcReg, TheCopy.DstReg)) {
1291 TheCopy.MI = 0; // Mark this one as done.
1292 ProgressMade = true;
1293 }
1294 }
Chris Lattnerf7da2c72006-08-24 22:43:55 +00001295 }
1296
Chris Lattnerc83e40d2004-07-25 03:24:11 +00001297 DEBUG(std::cerr << "*** Register mapping ***\n");
Alkis Evlogimenos5d0d1e32004-09-08 03:01:50 +00001298 DEBUG(for (int i = 0, e = r2rMap_.size(); i != e; ++i)
Chris Lattner7c10b0d2006-08-21 22:56:29 +00001299 if (r2rMap_[i]) {
1300 std::cerr << " reg " << i << " -> ";
1301 printRegName(r2rMap_[i]);
1302 std::cerr << "\n";
1303 });
Chris Lattner1c5c0442004-07-19 14:08:10 +00001304}
1305
Evan Cheng647c15e2006-05-12 06:06:34 +00001306/// Return true if the two specified registers belong to different register
1307/// classes. The registers may be either phys or virt regs.
1308bool LiveIntervals::differingRegisterClasses(unsigned RegA,
1309 unsigned RegB) const {
Alkis Evlogimenos79b0c3f2004-01-23 13:37:51 +00001310
Chris Lattner7ac2d312004-07-24 02:59:07 +00001311 // Get the register classes for the first reg.
Chris Lattnerad3c74f2004-10-26 05:29:18 +00001312 if (MRegisterInfo::isPhysicalRegister(RegA)) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00001313 assert(MRegisterInfo::isVirtualRegister(RegB) &&
Chris Lattnerad3c74f2004-10-26 05:29:18 +00001314 "Shouldn't consider two physregs!");
Evan Cheng647c15e2006-05-12 06:06:34 +00001315 return !mf_->getSSARegMap()->getRegClass(RegB)->contains(RegA);
Chris Lattnerad3c74f2004-10-26 05:29:18 +00001316 }
Chris Lattner7ac2d312004-07-24 02:59:07 +00001317
1318 // Compare against the regclass for the second reg.
Evan Cheng647c15e2006-05-12 06:06:34 +00001319 const TargetRegisterClass *RegClass = mf_->getSSARegMap()->getRegClass(RegA);
1320 if (MRegisterInfo::isVirtualRegister(RegB))
1321 return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
1322 else
1323 return !RegClass->contains(RegB);
Chris Lattner7ac2d312004-07-24 02:59:07 +00001324}
1325
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +00001326LiveInterval LiveIntervals::createInterval(unsigned reg) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00001327 float Weight = MRegisterInfo::isPhysicalRegister(reg) ?
Chris Lattnerc9d94d12006-08-27 12:47:48 +00001328 (float)HUGE_VAL : 0.0F;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +00001329 return LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +00001330}