blob: 68d194883757ce6859bcb0b9f9b2c3162fdaa377 [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>
Jeff Cohen97af7512006-12-02 02:22:01 +000036#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000037using namespace llvm;
38
Chris Lattnercd3245a2006-12-19 22:41:21 +000039STATISTIC(numIntervals, "Number of original intervals");
40STATISTIC(numIntervalsAfter, "Number of intervals after coalescing");
41STATISTIC(numJoins , "Number of interval joins performed");
42STATISTIC(numPeep , "Number of identity moves eliminated after coalescing");
43STATISTIC(numFolded , "Number of loads/stores folded into instructions");
44
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000045namespace {
Chris Lattner5d8925c2006-08-27 22:30:17 +000046 RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000047
Andrew Lenharthed41f1b2006-07-20 17:28:38 +000048 static cl::opt<bool>
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000049 EnableJoining("join-liveintervals",
Chris Lattner428b92e2006-09-15 03:57:23 +000050 cl::desc("Coallesce copies (default=true)"),
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000051 cl::init(true));
Chris Lattnerd74ea2b2006-05-24 17:04:05 +000052}
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000053
Chris Lattnerf7da2c72006-08-24 22:43:55 +000054void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000055 AU.addRequired<LiveVariables>();
56 AU.addPreservedID(PHIEliminationID);
57 AU.addRequiredID(PHIEliminationID);
58 AU.addRequiredID(TwoAddressInstructionPassID);
59 AU.addRequired<LoopInfo>();
60 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000061}
62
Chris Lattnerf7da2c72006-08-24 22:43:55 +000063void LiveIntervals::releaseMemory() {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000064 mi2iMap_.clear();
65 i2miMap_.clear();
66 r2iMap_.clear();
67 r2rMap_.clear();
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000068}
69
70
Evan Cheng99314142006-05-11 07:29:24 +000071static bool isZeroLengthInterval(LiveInterval *li) {
72 for (LiveInterval::Ranges::const_iterator
73 i = li->ranges.begin(), e = li->ranges.end(); i != e; ++i)
74 if (i->end - i->start > LiveIntervals::InstrSlots::NUM)
75 return false;
76 return true;
77}
78
79
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000080/// runOnMachineFunction - Register allocate the whole function
81///
82bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000083 mf_ = &fn;
84 tm_ = &fn.getTarget();
85 mri_ = tm_->getRegisterInfo();
Chris Lattnerf768bba2005-03-09 23:05:19 +000086 tii_ = tm_->getInstrInfo();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000087 lv_ = &getAnalysis<LiveVariables>();
Alkis Evlogimenos53278012004-08-26 22:22:38 +000088 allocatableRegs_ = mri_->getAllocatableSet(fn);
Alkis Evlogimenos2c4f7b52004-09-09 19:24:38 +000089 r2rMap_.grow(mf_->getSSARegMap()->getLastVirtReg());
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000090
Chris Lattner799a9192005-04-09 16:17:50 +000091 // If this function has any live ins, insert a dummy instruction at the
92 // beginning of the function that we will pretend "defines" the values. This
93 // is to make the interval analysis simpler by providing a number.
94 if (fn.livein_begin() != fn.livein_end()) {
Chris Lattner712ad0c2005-05-13 07:08:07 +000095 unsigned FirstLiveIn = fn.livein_begin()->first;
Chris Lattner799a9192005-04-09 16:17:50 +000096
97 // Find a reg class that contains this live in.
98 const TargetRegisterClass *RC = 0;
99 for (MRegisterInfo::regclass_iterator RCI = mri_->regclass_begin(),
100 E = mri_->regclass_end(); RCI != E; ++RCI)
101 if ((*RCI)->contains(FirstLiveIn)) {
102 RC = *RCI;
103 break;
104 }
105
106 MachineInstr *OldFirstMI = fn.begin()->begin();
107 mri_->copyRegToReg(*fn.begin(), fn.begin()->begin(),
108 FirstLiveIn, FirstLiveIn, RC);
109 assert(OldFirstMI != fn.begin()->begin() &&
110 "copyRetToReg didn't insert anything!");
111 }
112
Chris Lattner428b92e2006-09-15 03:57:23 +0000113 // Number MachineInstrs and MachineBasicBlocks.
114 // Initialize MBB indexes to a sentinal.
115 MBB2IdxMap.resize(mf_->getNumBlockIDs(), ~0U);
116
117 unsigned MIIndex = 0;
118 for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
119 MBB != E; ++MBB) {
120 // Set the MBB2IdxMap entry for this MBB.
121 MBB2IdxMap[MBB->getNumber()] = MIIndex;
122
123 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
124 I != E; ++I) {
125 bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000126 assert(inserted && "multiple MachineInstr -> index mappings");
Chris Lattner428b92e2006-09-15 03:57:23 +0000127 i2miMap_.push_back(I);
128 MIIndex += InstrSlots::NUM;
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000129 }
Chris Lattner428b92e2006-09-15 03:57:23 +0000130 }
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000131
Chris Lattner799a9192005-04-09 16:17:50 +0000132 // Note intervals due to live-in values.
133 if (fn.livein_begin() != fn.livein_end()) {
134 MachineBasicBlock *Entry = fn.begin();
Chris Lattner712ad0c2005-05-13 07:08:07 +0000135 for (MachineFunction::livein_iterator I = fn.livein_begin(),
Chris Lattner799a9192005-04-09 16:17:50 +0000136 E = fn.livein_end(); I != E; ++I) {
Chris Lattner6b128bd2006-09-03 08:07:11 +0000137 handlePhysicalRegisterDef(Entry, Entry->begin(), 0,
Chris Lattner91725b72006-08-31 05:54:43 +0000138 getOrCreateInterval(I->first), 0);
Chris Lattner712ad0c2005-05-13 07:08:07 +0000139 for (const unsigned* AS = mri_->getAliasSet(I->first); *AS; ++AS)
Chris Lattner6b128bd2006-09-03 08:07:11 +0000140 handlePhysicalRegisterDef(Entry, Entry->begin(), 0,
Chris Lattner91725b72006-08-31 05:54:43 +0000141 getOrCreateInterval(*AS), 0);
Chris Lattner799a9192005-04-09 16:17:50 +0000142 }
143 }
144
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000145 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000146
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000147 numIntervals += getNumIntervals();
148
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000149 DOUT << "********** INTERVALS **********\n";
150 for (iterator I = begin(), E = end(); I != E; ++I) {
151 I->second.print(DOUT, mri_);
152 DOUT << "\n";
153 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000154
Chris Lattner428b92e2006-09-15 03:57:23 +0000155 // Join (coallesce) intervals if requested.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000156 if (EnableJoining) joinIntervals();
157
158 numIntervalsAfter += getNumIntervals();
Chris Lattner428b92e2006-09-15 03:57:23 +0000159
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000160
161 // perform a final pass over the instructions and compute spill
Chris Lattnerfbecc5a2006-09-03 07:53:50 +0000162 // weights, coalesce virtual registers and remove identity moves.
Chris Lattner428b92e2006-09-15 03:57:23 +0000163 const LoopInfo &loopInfo = getAnalysis<LoopInfo>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000164
165 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
166 mbbi != mbbe; ++mbbi) {
167 MachineBasicBlock* mbb = mbbi;
168 unsigned loopDepth = loopInfo.getLoopDepth(mbb->getBasicBlock());
169
170 for (MachineBasicBlock::iterator mii = mbb->begin(), mie = mbb->end();
171 mii != mie; ) {
172 // if the move will be an identity move delete it
173 unsigned srcReg, dstReg, RegRep;
Chris Lattnerf768bba2005-03-09 23:05:19 +0000174 if (tii_->isMoveInstr(*mii, srcReg, dstReg) &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000175 (RegRep = rep(srcReg)) == rep(dstReg)) {
176 // remove from def list
Reid Spencer3ed469c2006-11-02 20:25:50 +0000177 getOrCreateInterval(RegRep);
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000178 RemoveMachineInstrFromMaps(mii);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000179 mii = mbbi->erase(mii);
180 ++numPeep;
181 }
182 else {
Chris Lattnerfbecc5a2006-09-03 07:53:50 +0000183 for (unsigned i = 0, e = mii->getNumOperands(); i != e; ++i) {
184 const MachineOperand &mop = mii->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000185 if (mop.isRegister() && mop.getReg() &&
186 MRegisterInfo::isVirtualRegister(mop.getReg())) {
187 // replace register with representative register
188 unsigned reg = rep(mop.getReg());
Chris Lattnere53f4a02006-05-04 17:52:23 +0000189 mii->getOperand(i).setReg(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000190
191 LiveInterval &RegInt = getInterval(reg);
192 RegInt.weight +=
Chris Lattner7a36ae82004-10-25 18:40:47 +0000193 (mop.isUse() + mop.isDef()) * pow(10.0F, (int)loopDepth);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000194 }
195 }
196 ++mii;
197 }
198 }
199 }
200
Chris Lattnerb75a6632006-11-07 07:18:40 +0000201
Evan Cheng99314142006-05-11 07:29:24 +0000202 for (iterator I = begin(), E = end(); I != E; ++I) {
Chris Lattnerb75a6632006-11-07 07:18:40 +0000203 LiveInterval &LI = I->second;
204 if (MRegisterInfo::isVirtualRegister(LI.reg)) {
Chris Lattnerc9d94d12006-08-27 12:47:48 +0000205 // If the live interval length is essentially zero, i.e. in every live
Evan Cheng99314142006-05-11 07:29:24 +0000206 // range the use follows def immediately, it doesn't make sense to spill
207 // it and hope it will be easier to allocate for this li.
Chris Lattnerb75a6632006-11-07 07:18:40 +0000208 if (isZeroLengthInterval(&LI))
Jim Laskey7902c752006-11-07 12:25:45 +0000209 LI.weight = HUGE_VALF;
Chris Lattnerb75a6632006-11-07 07:18:40 +0000210
Chris Lattner393ebae2006-11-07 18:04:58 +0000211 // Divide the weight of the interval by its size. This encourages
212 // spilling of intervals that are large and have few uses, and
213 // discourages spilling of small intervals with many uses.
214 unsigned Size = 0;
215 for (LiveInterval::iterator II = LI.begin(), E = LI.end(); II != E;++II)
216 Size += II->end - II->start;
Chris Lattnerb75a6632006-11-07 07:18:40 +0000217
Chris Lattner393ebae2006-11-07 18:04:58 +0000218 LI.weight /= Size;
Chris Lattnerc9d94d12006-08-27 12:47:48 +0000219 }
Evan Cheng99314142006-05-11 07:29:24 +0000220 }
221
Chris Lattner70ca3582004-09-30 15:59:17 +0000222 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000223 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000224}
225
Chris Lattner70ca3582004-09-30 15:59:17 +0000226/// print - Implement the dump method.
Reid Spencerce9653c2004-12-07 04:03:45 +0000227void LiveIntervals::print(std::ostream &O, const Module* ) const {
Chris Lattner70ca3582004-09-30 15:59:17 +0000228 O << "********** INTERVALS **********\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000229 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000230 I->second.print(DOUT, mri_);
231 DOUT << "\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000232 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000233
234 O << "********** MACHINEINSTRS **********\n";
235 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
236 mbbi != mbbe; ++mbbi) {
237 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
238 for (MachineBasicBlock::iterator mii = mbbi->begin(),
239 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner477e4552004-09-30 16:10:45 +0000240 O << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner70ca3582004-09-30 15:59:17 +0000241 }
242 }
243}
244
Bill Wendling01352aa2006-11-16 02:41:50 +0000245/// CreateNewLiveInterval - Create a new live interval with the given live
246/// ranges. The new live interval will have an infinite spill weight.
247LiveInterval&
248LiveIntervals::CreateNewLiveInterval(const LiveInterval *LI,
249 const std::vector<LiveRange> &LRs) {
250 const TargetRegisterClass *RC = mf_->getSSARegMap()->getRegClass(LI->reg);
251
252 // Create a new virtual register for the spill interval.
253 unsigned NewVReg = mf_->getSSARegMap()->createVirtualRegister(RC);
254
255 // Replace the old virtual registers in the machine operands with the shiny
256 // new one.
257 for (std::vector<LiveRange>::const_iterator
258 I = LRs.begin(), E = LRs.end(); I != E; ++I) {
259 unsigned Index = getBaseIndex(I->start);
260 unsigned End = getBaseIndex(I->end - 1) + InstrSlots::NUM;
261
262 for (; Index != End; Index += InstrSlots::NUM) {
263 // Skip deleted instructions
264 while (Index != End && !getInstructionFromIndex(Index))
265 Index += InstrSlots::NUM;
266
267 if (Index == End) break;
268
269 MachineInstr *MI = getInstructionFromIndex(Index);
270
Bill Wendlingbeeb77f2006-11-16 07:35:18 +0000271 for (unsigned J = 0, e = MI->getNumOperands(); J != e; ++J) {
Bill Wendling01352aa2006-11-16 02:41:50 +0000272 MachineOperand &MOp = MI->getOperand(J);
273 if (MOp.isRegister() && rep(MOp.getReg()) == LI->reg)
274 MOp.setReg(NewVReg);
275 }
276 }
277 }
278
279 LiveInterval &NewLI = getOrCreateInterval(NewVReg);
280
281 // The spill weight is now infinity as it cannot be spilled again
282 NewLI.weight = float(HUGE_VAL);
283
284 for (std::vector<LiveRange>::const_iterator
285 I = LRs.begin(), E = LRs.end(); I != E; ++I) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000286 DOUT << " Adding live range " << *I << " to new interval\n";
Bill Wendling01352aa2006-11-16 02:41:50 +0000287 NewLI.addRange(*I);
288 }
289
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000290 DOUT << "Created new live interval " << NewLI << "\n";
Bill Wendling01352aa2006-11-16 02:41:50 +0000291 return NewLI;
292}
293
Chris Lattner70ca3582004-09-30 15:59:17 +0000294std::vector<LiveInterval*> LiveIntervals::
295addIntervalsForSpills(const LiveInterval &li, VirtRegMap &vrm, int slot) {
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000296 // since this is called after the analysis is done we don't know if
297 // LiveVariables is available
298 lv_ = getAnalysisToUpdate<LiveVariables>();
299
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000300 std::vector<LiveInterval*> added;
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000301
Jim Laskey7902c752006-11-07 12:25:45 +0000302 assert(li.weight != HUGE_VALF &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000303 "attempt to spill already spilled interval!");
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000304
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000305 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
306 li.print(DOUT, mri_);
307 DOUT << '\n';
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000308
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000309 const TargetRegisterClass* rc = mf_->getSSARegMap()->getRegClass(li.reg);
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000310
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000311 for (LiveInterval::Ranges::const_iterator
312 i = li.ranges.begin(), e = li.ranges.end(); i != e; ++i) {
313 unsigned index = getBaseIndex(i->start);
314 unsigned end = getBaseIndex(i->end-1) + InstrSlots::NUM;
315 for (; index != end; index += InstrSlots::NUM) {
316 // skip deleted instructions
317 while (index != end && !getInstructionFromIndex(index))
318 index += InstrSlots::NUM;
319 if (index == end) break;
Chris Lattner8640f4e2004-07-19 15:16:53 +0000320
Chris Lattner3b9db832006-01-03 07:41:37 +0000321 MachineInstr *MI = getInstructionFromIndex(index);
Alkis Evlogimenos39a0d5c2004-02-20 06:15:40 +0000322
Chris Lattner29268692006-09-05 02:12:02 +0000323 RestartInstruction:
Chris Lattner3b9db832006-01-03 07:41:37 +0000324 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
325 MachineOperand& mop = MI->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000326 if (mop.isRegister() && mop.getReg() == li.reg) {
Chris Lattner29268692006-09-05 02:12:02 +0000327 if (MachineInstr *fmi = mri_->foldMemoryOperand(MI, i, slot)) {
Chris Lattnerb11443d2005-09-09 19:17:47 +0000328 // Attempt to fold the memory reference into the instruction. If we
329 // can do this, we don't need to insert spill code.
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000330 if (lv_)
Chris Lattner3b9db832006-01-03 07:41:37 +0000331 lv_->instructionChanged(MI, fmi);
Evan Cheng200370f2006-04-30 08:41:47 +0000332 MachineBasicBlock &MBB = *MI->getParent();
Chris Lattner35f27052006-05-01 21:16:03 +0000333 vrm.virtFolded(li.reg, MI, i, fmi);
Chris Lattner3b9db832006-01-03 07:41:37 +0000334 mi2iMap_.erase(MI);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000335 i2miMap_[index/InstrSlots::NUM] = fmi;
336 mi2iMap_[fmi] = index;
Chris Lattner3b9db832006-01-03 07:41:37 +0000337 MI = MBB.insert(MBB.erase(MI), fmi);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000338 ++numFolded;
Chris Lattner477e4552004-09-30 16:10:45 +0000339 // Folding the load/store can completely change the instruction in
340 // unpredictable ways, rescan it from the beginning.
Chris Lattner29268692006-09-05 02:12:02 +0000341 goto RestartInstruction;
Chris Lattner477e4552004-09-30 16:10:45 +0000342 } else {
Chris Lattner29268692006-09-05 02:12:02 +0000343 // Create a new virtual register for the spill interval.
344 unsigned NewVReg = mf_->getSSARegMap()->createVirtualRegister(rc);
345
346 // Scan all of the operands of this instruction rewriting operands
347 // to use NewVReg instead of li.reg as appropriate. We do this for
348 // two reasons:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000349 //
Chris Lattner29268692006-09-05 02:12:02 +0000350 // 1. If the instr reads the same spilled vreg multiple times, we
351 // want to reuse the NewVReg.
352 // 2. If the instr is a two-addr instruction, we are required to
353 // keep the src/dst regs pinned.
354 //
355 // Keep track of whether we replace a use and/or def so that we can
356 // create the spill interval with the appropriate range.
357 mop.setReg(NewVReg);
358
359 bool HasUse = mop.isUse();
360 bool HasDef = mop.isDef();
361 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
362 if (MI->getOperand(j).isReg() &&
363 MI->getOperand(j).getReg() == li.reg) {
364 MI->getOperand(j).setReg(NewVReg);
365 HasUse |= MI->getOperand(j).isUse();
366 HasDef |= MI->getOperand(j).isDef();
367 }
368 }
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000369
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000370 // create a new register for this spill
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000371 vrm.grow();
Chris Lattner29268692006-09-05 02:12:02 +0000372 vrm.assignVirt2StackSlot(NewVReg, slot);
373 LiveInterval &nI = getOrCreateInterval(NewVReg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000374 assert(nI.empty());
Chris Lattner70ca3582004-09-30 15:59:17 +0000375
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000376 // the spill weight is now infinity as it
377 // cannot be spilled again
Jim Laskey7902c752006-11-07 12:25:45 +0000378 nI.weight = HUGE_VALF;
Chris Lattner29268692006-09-05 02:12:02 +0000379
380 if (HasUse) {
381 LiveRange LR(getLoadIndex(index), getUseIndex(index),
382 nI.getNextValue(~0U, 0));
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000383 DOUT << " +" << LR;
Chris Lattner29268692006-09-05 02:12:02 +0000384 nI.addRange(LR);
385 }
386 if (HasDef) {
387 LiveRange LR(getDefIndex(index), getStoreIndex(index),
388 nI.getNextValue(~0U, 0));
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000389 DOUT << " +" << LR;
Chris Lattner29268692006-09-05 02:12:02 +0000390 nI.addRange(LR);
391 }
392
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000393 added.push_back(&nI);
Chris Lattner70ca3582004-09-30 15:59:17 +0000394
Alkis Evlogimenosd8d26b32004-08-27 18:59:22 +0000395 // update live variables if it is available
396 if (lv_)
Chris Lattner29268692006-09-05 02:12:02 +0000397 lv_->addVirtualRegisterKilled(NewVReg, MI);
Chris Lattnerb11443d2005-09-09 19:17:47 +0000398
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000399 DOUT << "\t\t\t\tadded new interval: ";
400 nI.print(DOUT, mri_);
401 DOUT << '\n';
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000402 }
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000403 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000404 }
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000405 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000406 }
Alkis Evlogimenos26f5a692004-05-30 07:24:39 +0000407
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000408 return added;
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000409}
410
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000411void LiveIntervals::printRegName(unsigned reg) const {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000412 if (MRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge8156192006-12-07 01:30:32 +0000413 cerr << mri_->getName(reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000414 else
Bill Wendlinge8156192006-12-07 01:30:32 +0000415 cerr << "%reg" << reg;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000416}
417
Evan Chengbf105c82006-11-03 03:04:46 +0000418/// isReDefinedByTwoAddr - Returns true if the Reg re-definition is due to
419/// two addr elimination.
420static bool isReDefinedByTwoAddr(MachineInstr *MI, unsigned Reg,
421 const TargetInstrInfo *TII) {
422 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
423 MachineOperand &MO1 = MI->getOperand(i);
424 if (MO1.isRegister() && MO1.isDef() && MO1.getReg() == Reg) {
425 for (unsigned j = i+1; j < e; ++j) {
426 MachineOperand &MO2 = MI->getOperand(j);
427 if (MO2.isRegister() && MO2.isUse() && MO2.getReg() == Reg &&
Evan Cheng51cdcd12006-12-07 01:21:59 +0000428 MI->getInstrDescriptor()->
429 getOperandConstraint(j, TOI::TIED_TO) == (int)i)
Evan Chengbf105c82006-11-03 03:04:46 +0000430 return true;
431 }
432 }
433 }
434 return false;
435}
436
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000437void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000438 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000439 unsigned MIIdx,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000440 LiveInterval &interval) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000441 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000442 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000443
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000444 // Virtual registers may be defined multiple times (due to phi
445 // elimination and 2-addr elimination). Much of what we do only has to be
446 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000447 // time we see a vreg.
448 if (interval.empty()) {
449 // Get the Idx of the defining instructions.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000450 unsigned defIndex = getDefIndex(MIIdx);
Chris Lattner6097d132004-07-19 02:15:56 +0000451
Chris Lattner91725b72006-08-31 05:54:43 +0000452 unsigned ValNum;
453 unsigned SrcReg, DstReg;
454 if (!tii_->isMoveInstr(*mi, SrcReg, DstReg))
455 ValNum = interval.getNextValue(~0U, 0);
456 else
457 ValNum = interval.getNextValue(defIndex, SrcReg);
458
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000459 assert(ValNum == 0 && "First value in interval is not 0?");
460 ValNum = 0; // Clue in the optimizer.
Chris Lattner7ac2d312004-07-24 02:59:07 +0000461
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000462 // Loop over all of the blocks that the vreg is defined in. There are
463 // two cases we have to handle here. The most common case is a vreg
464 // whose lifetime is contained within a basic block. In this case there
465 // will be a single kill, in MBB, which comes after the definition.
466 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
467 // FIXME: what about dead vars?
468 unsigned killIdx;
469 if (vi.Kills[0] != mi)
470 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
471 else
472 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000473
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000474 // If the kill happens after the definition, we have an intra-block
475 // live range.
476 if (killIdx > defIndex) {
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000477 assert(vi.AliveBlocks.empty() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000478 "Shouldn't be alive across any blocks!");
479 LiveRange LR(defIndex, killIdx, ValNum);
480 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000481 DOUT << " +" << LR << "\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000482 return;
483 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000484 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000485
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000486 // The other case we handle is when a virtual register lives to the end
487 // of the defining block, potentially live across some blocks, then is
488 // live into some number of blocks, but gets killed. Start by adding a
489 // range that goes from this definition to the end of the defining block.
Alkis Evlogimenosd19e2902004-08-31 17:39:15 +0000490 LiveRange NewLR(defIndex,
491 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
492 ValNum);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000493 DOUT << " +" << NewLR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000494 interval.addRange(NewLR);
495
496 // Iterate over all of the blocks that the variable is completely
497 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
498 // live interval.
499 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
500 if (vi.AliveBlocks[i]) {
Chris Lattner428b92e2006-09-15 03:57:23 +0000501 MachineBasicBlock *MBB = mf_->getBlockNumbered(i);
502 if (!MBB->empty()) {
503 LiveRange LR(getMBBStartIdx(i),
504 getInstructionIndex(&MBB->back()) + InstrSlots::NUM,
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000505 ValNum);
506 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000507 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000508 }
509 }
510 }
511
512 // Finally, this virtual register is live from the start of any killing
513 // block to the 'use' slot of the killing instruction.
514 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
515 MachineInstr *Kill = vi.Kills[i];
Chris Lattner428b92e2006-09-15 03:57:23 +0000516 LiveRange LR(getMBBStartIdx(Kill->getParent()),
Alkis Evlogimenosd19e2902004-08-31 17:39:15 +0000517 getUseIndex(getInstructionIndex(Kill))+1,
518 ValNum);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000519 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000520 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000521 }
522
523 } else {
524 // If this is the second time we see a virtual register definition, it
525 // must be due to phi elimination or two addr elimination. If this is
Evan Chengbf105c82006-11-03 03:04:46 +0000526 // the result of two address elimination, then the vreg is one of the
527 // def-and-use register operand.
528 if (isReDefinedByTwoAddr(mi, interval.reg, tii_)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000529 // If this is a two-address definition, then we have already processed
530 // the live range. The only problem is that we didn't realize there
531 // are actually two values in the live interval. Because of this we
532 // need to take the LiveRegion that defines this register and split it
533 // into two values.
534 unsigned DefIndex = getDefIndex(getInstructionIndex(vi.DefInst));
Chris Lattner6b128bd2006-09-03 08:07:11 +0000535 unsigned RedefIndex = getDefIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000536
537 // Delete the initial value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000538 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000539 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000540
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000541 // Two-address vregs should always only be redefined once. This means
542 // that at this point, there should be exactly one value number in it.
543 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
544
Chris Lattner91725b72006-08-31 05:54:43 +0000545 // The new value number (#1) is defined by the instruction we claimed
546 // defined value #0.
547 unsigned ValNo = interval.getNextValue(0, 0);
548 interval.setValueNumberInfo(1, interval.getValNumInfo(0));
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000549
Chris Lattner91725b72006-08-31 05:54:43 +0000550 // Value#0 is now defined by the 2-addr instruction.
551 interval.setValueNumberInfo(0, std::make_pair(~0U, 0U));
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000552
553 // Add the new live interval which replaces the range for the input copy.
554 LiveRange LR(DefIndex, RedefIndex, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000555 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000556 interval.addRange(LR);
557
558 // If this redefinition is dead, we need to add a dummy unit live
559 // range covering the def slot.
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000560 if (lv_->RegisterDefIsDead(mi, interval.reg))
561 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, 0));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000562
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000563 DOUT << "RESULT: ";
564 interval.print(DOUT, mri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000565
566 } else {
567 // Otherwise, this must be because of phi elimination. If this is the
568 // first redefinition of the vreg that we have seen, go back and change
569 // the live range in the PHI block to be a different value number.
570 if (interval.containsOneValue()) {
571 assert(vi.Kills.size() == 1 &&
572 "PHI elimination vreg should have one kill, the PHI itself!");
573
574 // Remove the old range that we now know has an incorrect number.
575 MachineInstr *Killer = vi.Kills[0];
Chris Lattner428b92e2006-09-15 03:57:23 +0000576 unsigned Start = getMBBStartIdx(Killer->getParent());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000577 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000578 DOUT << "Removing [" << Start << "," << End << "] from: ";
579 interval.print(DOUT, mri_); DOUT << "\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000580 interval.removeRange(Start, End);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000581 DOUT << "RESULT: "; interval.print(DOUT, mri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000582
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000583 // Replace the interval with one of a NEW value number. Note that this
584 // value number isn't actually defined by an instruction, weird huh? :)
Chris Lattner91725b72006-08-31 05:54:43 +0000585 LiveRange LR(Start, End, interval.getNextValue(~0U, 0));
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000586 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000587 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000588 DOUT << "RESULT: "; interval.print(DOUT, mri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000589 }
590
591 // In the case of PHI elimination, each variable definition is only
592 // live until the end of the block. We've already taken care of the
593 // rest of the live range.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000594 unsigned defIndex = getDefIndex(MIIdx);
Chris Lattner91725b72006-08-31 05:54:43 +0000595
596 unsigned ValNum;
597 unsigned SrcReg, DstReg;
598 if (!tii_->isMoveInstr(*mi, SrcReg, DstReg))
599 ValNum = interval.getNextValue(~0U, 0);
600 else
601 ValNum = interval.getNextValue(defIndex, SrcReg);
602
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000603 LiveRange LR(defIndex,
Chris Lattner91725b72006-08-31 05:54:43 +0000604 getInstructionIndex(&mbb->back()) + InstrSlots::NUM, ValNum);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000605 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000606 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000607 }
608 }
609
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000610 DOUT << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000611}
612
Chris Lattnerf35fef72004-07-23 21:24:19 +0000613void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000614 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000615 unsigned MIIdx,
Chris Lattner91725b72006-08-31 05:54:43 +0000616 LiveInterval &interval,
617 unsigned SrcReg) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000618 // A physical register cannot be live across basic block, so its
619 // lifetime must end somewhere in its defining basic block.
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000620 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000621
Chris Lattner6b128bd2006-09-03 08:07:11 +0000622 unsigned baseIndex = MIIdx;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000623 unsigned start = getDefIndex(baseIndex);
624 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000625
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000626 // If it is not used after definition, it is considered dead at
627 // the instruction defining it. Hence its interval is:
628 // [defSlot(def), defSlot(def)+1)
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000629 if (lv_->RegisterDefIsDead(mi, interval.reg)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000630 DOUT << " dead";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000631 end = getDefIndex(start) + 1;
632 goto exit;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000633 }
634
635 // If it is not dead on definition, it must be killed by a
636 // subsequent instruction. Hence its interval is:
637 // [defSlot(def), useSlot(kill)+1)
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000638 while (++mi != MBB->end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000639 baseIndex += InstrSlots::NUM;
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000640 if (lv_->KillsRegister(mi, interval.reg)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000641 DOUT << " killed";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000642 end = getUseIndex(baseIndex) + 1;
643 goto exit;
Evan Cheng9a1956a2006-11-15 20:54:11 +0000644 } else if (lv_->ModifiesRegister(mi, interval.reg)) {
645 // Another instruction redefines the register before it is ever read.
646 // Then the register is essentially dead at the instruction that defines
647 // it. Hence its interval is:
648 // [defSlot(def), defSlot(def)+1)
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000649 DOUT << " dead";
Evan Cheng9a1956a2006-11-15 20:54:11 +0000650 end = getDefIndex(start) + 1;
651 goto exit;
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000652 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000653 }
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000654
655 // The only case we should have a dead physreg here without a killing or
656 // instruction where we know it's dead is if it is live-in to the function
657 // and never used.
Chris Lattner91725b72006-08-31 05:54:43 +0000658 assert(!SrcReg && "physreg was not killed in defining block!");
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000659 end = getDefIndex(start) + 1; // It's dead.
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000660
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000661exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000662 assert(start < end && "did not find end of interval?");
Chris Lattnerf768bba2005-03-09 23:05:19 +0000663
Chris Lattner91725b72006-08-31 05:54:43 +0000664 LiveRange LR(start, end, interval.getNextValue(SrcReg != 0 ? start : ~0U,
665 SrcReg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000666 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000667 DOUT << " +" << LR << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000668}
669
Chris Lattnerf35fef72004-07-23 21:24:19 +0000670void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
671 MachineBasicBlock::iterator MI,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000672 unsigned MIIdx,
Chris Lattnerf35fef72004-07-23 21:24:19 +0000673 unsigned reg) {
674 if (MRegisterInfo::isVirtualRegister(reg))
Chris Lattner6b128bd2006-09-03 08:07:11 +0000675 handleVirtualRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg));
Alkis Evlogimenos53278012004-08-26 22:22:38 +0000676 else if (allocatableRegs_[reg]) {
Chris Lattner91725b72006-08-31 05:54:43 +0000677 unsigned SrcReg, DstReg;
678 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg))
679 SrcReg = 0;
Chris Lattner6b128bd2006-09-03 08:07:11 +0000680 handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg), SrcReg);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000681 for (const unsigned* AS = mri_->getAliasSet(reg); *AS; ++AS)
Chris Lattner6b128bd2006-09-03 08:07:11 +0000682 handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(*AS), 0);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000683 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000684}
685
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000686/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000687/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000688/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000689/// which a variable is live
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000690void LiveIntervals::computeIntervals() {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000691 DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
692 << "********** Function: "
693 << ((Value*)mf_->getFunction())->getName() << '\n';
Chris Lattner799a9192005-04-09 16:17:50 +0000694 bool IgnoreFirstInstr = mf_->livein_begin() != mf_->livein_end();
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000695
Chris Lattner6b128bd2006-09-03 08:07:11 +0000696 // Track the index of the current machine instr.
697 unsigned MIIndex = 0;
Chris Lattner428b92e2006-09-15 03:57:23 +0000698 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
699 MBBI != E; ++MBBI) {
700 MachineBasicBlock *MBB = MBBI;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000701 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000702
Chris Lattner428b92e2006-09-15 03:57:23 +0000703 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
Chris Lattnerdffb2e82006-09-04 18:27:40 +0000704 if (IgnoreFirstInstr) {
Chris Lattner428b92e2006-09-15 03:57:23 +0000705 ++MI;
Chris Lattnerdffb2e82006-09-04 18:27:40 +0000706 IgnoreFirstInstr = false;
707 MIIndex += InstrSlots::NUM;
708 }
709
Chris Lattner428b92e2006-09-15 03:57:23 +0000710 for (; MI != miEnd; ++MI) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000711 DOUT << MIIndex << "\t" << *MI;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000712
Evan Cheng438f7bc2006-11-10 08:43:01 +0000713 // Handle defs.
Chris Lattner428b92e2006-09-15 03:57:23 +0000714 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
715 MachineOperand &MO = MI->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000716 // handle register defs - build intervals
Chris Lattner428b92e2006-09-15 03:57:23 +0000717 if (MO.isRegister() && MO.getReg() && MO.isDef())
718 handleRegisterDef(MBB, MI, MIIndex, MO.getReg());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000719 }
Chris Lattner6b128bd2006-09-03 08:07:11 +0000720
721 MIIndex += InstrSlots::NUM;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000722 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000723 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000724}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000725
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000726/// AdjustCopiesBackFrom - We found a non-trivially-coallescable copy with IntA
727/// being the source and IntB being the dest, thus this defines a value number
728/// in IntB. If the source value number (in IntA) is defined by a copy from B,
729/// see if we can merge these two pieces of B into a single value number,
730/// eliminating a copy. For example:
731///
732/// A3 = B0
733/// ...
734/// B1 = A3 <- this copy
735///
736/// In this case, B0 can be extended to where the B1 copy lives, allowing the B1
737/// value number to be replaced with B0 (which simplifies the B liveinterval).
738///
739/// This returns true if an interval was modified.
740///
741bool LiveIntervals::AdjustCopiesBackFrom(LiveInterval &IntA, LiveInterval &IntB,
Chris Lattner6d8fbef2006-08-29 23:18:15 +0000742 MachineInstr *CopyMI) {
743 unsigned CopyIdx = getDefIndex(getInstructionIndex(CopyMI));
744
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000745 // BValNo is a value number in B that is defined by a copy from A. 'B3' in
746 // the example above.
747 LiveInterval::iterator BLR = IntB.FindLiveRangeContaining(CopyIdx);
748 unsigned BValNo = BLR->ValId;
Chris Lattneraa51a482005-10-21 06:49:50 +0000749
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000750 // Get the location that B is defined at. Two options: either this value has
751 // an unknown definition point or it is defined at CopyIdx. If unknown, we
752 // can't process it.
753 unsigned BValNoDefIdx = IntB.getInstForValNum(BValNo);
754 if (BValNoDefIdx == ~0U) return false;
755 assert(BValNoDefIdx == CopyIdx &&
756 "Copy doesn't define the value?");
Chris Lattneraa51a482005-10-21 06:49:50 +0000757
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000758 // AValNo is the value number in A that defines the copy, A0 in the example.
759 LiveInterval::iterator AValLR = IntA.FindLiveRangeContaining(CopyIdx-1);
760 unsigned AValNo = AValLR->ValId;
Chris Lattneraa51a482005-10-21 06:49:50 +0000761
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000762 // If AValNo is defined as a copy from IntB, we can potentially process this.
763
764 // Get the instruction that defines this value number.
Chris Lattner91725b72006-08-31 05:54:43 +0000765 unsigned SrcReg = IntA.getSrcRegForValNum(AValNo);
766 if (!SrcReg) return false; // Not defined by a copy.
Chris Lattneraa51a482005-10-21 06:49:50 +0000767
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000768 // If the value number is not defined by a copy instruction, ignore it.
Chris Lattneraa51a482005-10-21 06:49:50 +0000769
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000770 // If the source register comes from an interval other than IntB, we can't
771 // handle this.
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000772 if (rep(SrcReg) != IntB.reg) return false;
Chris Lattner91725b72006-08-31 05:54:43 +0000773
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000774 // Get the LiveRange in IntB that this value number starts with.
Chris Lattner91725b72006-08-31 05:54:43 +0000775 unsigned AValNoInstIdx = IntA.getInstForValNum(AValNo);
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000776 LiveInterval::iterator ValLR = IntB.FindLiveRangeContaining(AValNoInstIdx-1);
777
778 // Make sure that the end of the live range is inside the same block as
779 // CopyMI.
780 MachineInstr *ValLREndInst = getInstructionFromIndex(ValLR->end-1);
Chris Lattnerc114b2c2006-08-25 23:41:24 +0000781 if (!ValLREndInst ||
782 ValLREndInst->getParent() != CopyMI->getParent()) return false;
Chris Lattneraa51a482005-10-21 06:49:50 +0000783
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000784 // Okay, we now know that ValLR ends in the same block that the CopyMI
785 // live-range starts. If there are no intervening live ranges between them in
786 // IntB, we can merge them.
787 if (ValLR+1 != BLR) return false;
Chris Lattneraa51a482005-10-21 06:49:50 +0000788
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000789 DOUT << "\nExtending: "; IntB.print(DOUT, mri_);
Chris Lattnerba256032006-08-30 23:02:29 +0000790
791 // We are about to delete CopyMI, so need to remove it as the 'instruction
792 // that defines this value #'.
Chris Lattner91725b72006-08-31 05:54:43 +0000793 IntB.setValueNumberInfo(BValNo, std::make_pair(~0U, 0));
Chris Lattnerba256032006-08-30 23:02:29 +0000794
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000795 // Okay, we can merge them. We need to insert a new liverange:
796 // [ValLR.end, BLR.begin) of either value number, then we merge the
797 // two value numbers.
Chris Lattnerc114b2c2006-08-25 23:41:24 +0000798 unsigned FillerStart = ValLR->end, FillerEnd = BLR->start;
799 IntB.addRange(LiveRange(FillerStart, FillerEnd, BValNo));
800
801 // If the IntB live range is assigned to a physical register, and if that
802 // physreg has aliases,
803 if (MRegisterInfo::isPhysicalRegister(IntB.reg)) {
804 for (const unsigned *AS = mri_->getAliasSet(IntB.reg); *AS; ++AS) {
805 LiveInterval &AliasLI = getInterval(*AS);
806 AliasLI.addRange(LiveRange(FillerStart, FillerEnd,
Chris Lattner91725b72006-08-31 05:54:43 +0000807 AliasLI.getNextValue(~0U, 0)));
Chris Lattnerc114b2c2006-08-25 23:41:24 +0000808 }
809 }
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000810
811 // Okay, merge "B1" into the same value number as "B0".
812 if (BValNo != ValLR->ValId)
813 IntB.MergeValueNumberInto(BValNo, ValLR->ValId);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000814 DOUT << " result = "; IntB.print(DOUT, mri_);
815 DOUT << "\n";
Chris Lattneraa51a482005-10-21 06:49:50 +0000816
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000817 // Finally, delete the copy instruction.
818 RemoveMachineInstrFromMaps(CopyMI);
819 CopyMI->eraseFromParent();
820 ++numPeep;
Chris Lattneraa51a482005-10-21 06:49:50 +0000821 return true;
822}
823
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000824
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000825/// JoinCopy - Attempt to join intervals corresponding to SrcReg/DstReg,
826/// which are the src/dst of the copy instruction CopyMI. This returns true
827/// if the copy was successfully coallesced away, or if it is never possible
828/// to coallesce these this copy, due to register constraints. It returns
829/// false if it is not currently possible to coallesce this interval, but
830/// it may be possible if other things get coallesced.
831bool LiveIntervals::JoinCopy(MachineInstr *CopyMI,
832 unsigned SrcReg, unsigned DstReg) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000833 DOUT << getInstructionIndex(CopyMI) << '\t' << *CopyMI;
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000834
835 // Get representative registers.
836 SrcReg = rep(SrcReg);
837 DstReg = rep(DstReg);
838
839 // If they are already joined we continue.
840 if (SrcReg == DstReg) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000841 DOUT << "\tCopy already coallesced.\n";
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000842 return true; // Not coallescable.
Chris Lattner7ac2d312004-07-24 02:59:07 +0000843 }
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000844
845 // If they are both physical registers, we cannot join them.
846 if (MRegisterInfo::isPhysicalRegister(SrcReg) &&
847 MRegisterInfo::isPhysicalRegister(DstReg)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000848 DOUT << "\tCan not coallesce physregs.\n";
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000849 return true; // Not coallescable.
850 }
851
852 // We only join virtual registers with allocatable physical registers.
853 if (MRegisterInfo::isPhysicalRegister(SrcReg) && !allocatableRegs_[SrcReg]){
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000854 DOUT << "\tSrc reg is unallocatable physreg.\n";
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000855 return true; // Not coallescable.
856 }
857 if (MRegisterInfo::isPhysicalRegister(DstReg) && !allocatableRegs_[DstReg]){
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000858 DOUT << "\tDst reg is unallocatable physreg.\n";
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000859 return true; // Not coallescable.
860 }
861
862 // If they are not of the same register class, we cannot join them.
863 if (differingRegisterClasses(SrcReg, DstReg)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000864 DOUT << "\tSrc/Dest are different register classes.\n";
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000865 return true; // Not coallescable.
866 }
867
868 LiveInterval &SrcInt = getInterval(SrcReg);
869 LiveInterval &DestInt = getInterval(DstReg);
870 assert(SrcInt.reg == SrcReg && DestInt.reg == DstReg &&
871 "Register mapping is horribly broken!");
872
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000873 DOUT << "\t\tInspecting "; SrcInt.print(DOUT, mri_);
874 DOUT << " and "; DestInt.print(DOUT, mri_);
875 DOUT << ": ";
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000876
Chris Lattner6d8fbef2006-08-29 23:18:15 +0000877 // Okay, attempt to join these two intervals. On failure, this returns false.
878 // Otherwise, if one of the intervals being joined is a physreg, this method
879 // always canonicalizes DestInt to be it. The output "SrcInt" will not have
880 // been modified, so we can use this information below to update aliases.
881 if (!JoinIntervals(DestInt, SrcInt)) {
882 // Coallescing failed.
883
884 // If we can eliminate the copy without merging the live ranges, do so now.
885 if (AdjustCopiesBackFrom(SrcInt, DestInt, CopyMI))
886 return true;
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000887
Chris Lattner6d8fbef2006-08-29 23:18:15 +0000888 // Otherwise, we are unable to join the intervals.
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000889 DOUT << "Interference!\n";
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000890 return false;
891 }
892
Chris Lattnere7f729b2006-08-26 01:28:16 +0000893 bool Swapped = SrcReg == DestInt.reg;
894 if (Swapped)
895 std::swap(SrcReg, DstReg);
896 assert(MRegisterInfo::isVirtualRegister(SrcReg) &&
897 "LiveInterval::join didn't work right!");
898
Chris Lattnerc114b2c2006-08-25 23:41:24 +0000899 // If we're about to merge live ranges into a physical register live range,
900 // we have to update any aliased register's live ranges to indicate that they
901 // have clobbered values for this range.
Chris Lattnere7f729b2006-08-26 01:28:16 +0000902 if (MRegisterInfo::isPhysicalRegister(DstReg)) {
903 for (const unsigned *AS = mri_->getAliasSet(DstReg); *AS; ++AS)
904 getInterval(*AS).MergeInClobberRanges(SrcInt);
Chris Lattnerc114b2c2006-08-25 23:41:24 +0000905 }
906
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000907 DOUT << "\n\t\tJoined. Result = "; DestInt.print(DOUT, mri_);
908 DOUT << "\n";
Chris Lattnere7f729b2006-08-26 01:28:16 +0000909
910 // If the intervals were swapped by Join, swap them back so that the register
911 // mapping (in the r2i map) is correct.
912 if (Swapped) SrcInt.swap(DestInt);
913 r2iMap_.erase(SrcReg);
914 r2rMap_[SrcReg] = DstReg;
915
Chris Lattnerbfe180a2006-08-31 05:58:59 +0000916 // Finally, delete the copy instruction.
917 RemoveMachineInstrFromMaps(CopyMI);
918 CopyMI->eraseFromParent();
919 ++numPeep;
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000920 ++numJoins;
921 return true;
Alkis Evlogimenose88280a2004-01-22 23:08:45 +0000922}
923
Chris Lattner6d8fbef2006-08-29 23:18:15 +0000924/// ComputeUltimateVN - Assuming we are going to join two live intervals,
925/// compute what the resultant value numbers for each value in the input two
926/// ranges will be. This is complicated by copies between the two which can
927/// and will commonly cause multiple value numbers to be merged into one.
928///
929/// VN is the value number that we're trying to resolve. InstDefiningValue
930/// keeps track of the new InstDefiningValue assignment for the result
931/// LiveInterval. ThisFromOther/OtherFromThis are sets that keep track of
932/// whether a value in this or other is a copy from the opposite set.
933/// ThisValNoAssignments/OtherValNoAssignments keep track of value #'s that have
934/// already been assigned.
935///
936/// ThisFromOther[x] - If x is defined as a copy from the other interval, this
937/// contains the value number the copy is from.
938///
939static unsigned ComputeUltimateVN(unsigned VN,
Chris Lattner91725b72006-08-31 05:54:43 +0000940 SmallVector<std::pair<unsigned,
941 unsigned>, 16> &ValueNumberInfo,
Chris Lattner6d8fbef2006-08-29 23:18:15 +0000942 SmallVector<int, 16> &ThisFromOther,
943 SmallVector<int, 16> &OtherFromThis,
944 SmallVector<int, 16> &ThisValNoAssignments,
945 SmallVector<int, 16> &OtherValNoAssignments,
946 LiveInterval &ThisLI, LiveInterval &OtherLI) {
947 // If the VN has already been computed, just return it.
948 if (ThisValNoAssignments[VN] >= 0)
949 return ThisValNoAssignments[VN];
Chris Lattner8a67f6e2006-09-01 07:00:23 +0000950// assert(ThisValNoAssignments[VN] != -2 && "Cyclic case?");
Chris Lattner6d8fbef2006-08-29 23:18:15 +0000951
952 // If this val is not a copy from the other val, then it must be a new value
953 // number in the destination.
954 int OtherValNo = ThisFromOther[VN];
955 if (OtherValNo == -1) {
Chris Lattner91725b72006-08-31 05:54:43 +0000956 ValueNumberInfo.push_back(ThisLI.getValNumInfo(VN));
957 return ThisValNoAssignments[VN] = ValueNumberInfo.size()-1;
Chris Lattner6d8fbef2006-08-29 23:18:15 +0000958 }
959
Chris Lattner8a67f6e2006-09-01 07:00:23 +0000960 // Otherwise, this *is* a copy from the RHS. If the other side has already
961 // been computed, return it.
962 if (OtherValNoAssignments[OtherValNo] >= 0)
963 return ThisValNoAssignments[VN] = OtherValNoAssignments[OtherValNo];
964
965 // Mark this value number as currently being computed, then ask what the
966 // ultimate value # of the other value is.
Chris Lattner6d8fbef2006-08-29 23:18:15 +0000967 ThisValNoAssignments[VN] = -2;
968 unsigned UltimateVN =
Chris Lattner91725b72006-08-31 05:54:43 +0000969 ComputeUltimateVN(OtherValNo, ValueNumberInfo,
Chris Lattner6d8fbef2006-08-29 23:18:15 +0000970 OtherFromThis, ThisFromOther,
971 OtherValNoAssignments, ThisValNoAssignments,
972 OtherLI, ThisLI);
973 return ThisValNoAssignments[VN] = UltimateVN;
974}
975
Chris Lattnerf21f0202006-09-02 05:26:59 +0000976static bool InVector(unsigned Val, const SmallVector<unsigned, 8> &V) {
977 return std::find(V.begin(), V.end(), Val) != V.end();
978}
979
980/// SimpleJoin - Attempt to joint the specified interval into this one. The
981/// caller of this method must guarantee that the RHS only contains a single
982/// value number and that the RHS is not defined by a copy from this
983/// interval. This returns false if the intervals are not joinable, or it
984/// joins them and returns true.
985bool LiveIntervals::SimpleJoin(LiveInterval &LHS, LiveInterval &RHS) {
986 assert(RHS.containsOneValue());
987
988 // Some number (potentially more than one) value numbers in the current
989 // interval may be defined as copies from the RHS. Scan the overlapping
990 // portions of the LHS and RHS, keeping track of this and looking for
991 // overlapping live ranges that are NOT defined as copies. If these exist, we
992 // cannot coallesce.
993
994 LiveInterval::iterator LHSIt = LHS.begin(), LHSEnd = LHS.end();
995 LiveInterval::iterator RHSIt = RHS.begin(), RHSEnd = RHS.end();
996
997 if (LHSIt->start < RHSIt->start) {
998 LHSIt = std::upper_bound(LHSIt, LHSEnd, RHSIt->start);
999 if (LHSIt != LHS.begin()) --LHSIt;
1000 } else if (RHSIt->start < LHSIt->start) {
1001 RHSIt = std::upper_bound(RHSIt, RHSEnd, LHSIt->start);
1002 if (RHSIt != RHS.begin()) --RHSIt;
1003 }
1004
1005 SmallVector<unsigned, 8> EliminatedLHSVals;
1006
1007 while (1) {
1008 // Determine if these live intervals overlap.
1009 bool Overlaps = false;
1010 if (LHSIt->start <= RHSIt->start)
1011 Overlaps = LHSIt->end > RHSIt->start;
1012 else
1013 Overlaps = RHSIt->end > LHSIt->start;
1014
1015 // If the live intervals overlap, there are two interesting cases: if the
1016 // LHS interval is defined by a copy from the RHS, it's ok and we record
1017 // that the LHS value # is the same as the RHS. If it's not, then we cannot
1018 // coallesce these live ranges and we bail out.
1019 if (Overlaps) {
1020 // If we haven't already recorded that this value # is safe, check it.
1021 if (!InVector(LHSIt->ValId, EliminatedLHSVals)) {
1022 // Copy from the RHS?
1023 unsigned SrcReg = LHS.getSrcRegForValNum(LHSIt->ValId);
1024 if (rep(SrcReg) != RHS.reg)
1025 return false; // Nope, bail out.
1026
1027 EliminatedLHSVals.push_back(LHSIt->ValId);
1028 }
1029
1030 // We know this entire LHS live range is okay, so skip it now.
1031 if (++LHSIt == LHSEnd) break;
1032 continue;
1033 }
1034
1035 if (LHSIt->end < RHSIt->end) {
1036 if (++LHSIt == LHSEnd) break;
1037 } else {
1038 // One interesting case to check here. It's possible that we have
1039 // something like "X3 = Y" which defines a new value number in the LHS,
1040 // and is the last use of this liverange of the RHS. In this case, we
1041 // want to notice this copy (so that it gets coallesced away) even though
1042 // the live ranges don't actually overlap.
1043 if (LHSIt->start == RHSIt->end) {
1044 if (InVector(LHSIt->ValId, EliminatedLHSVals)) {
1045 // We already know that this value number is going to be merged in
1046 // if coallescing succeeds. Just skip the liverange.
1047 if (++LHSIt == LHSEnd) break;
1048 } else {
1049 // Otherwise, if this is a copy from the RHS, mark it as being merged
1050 // in.
1051 if (rep(LHS.getSrcRegForValNum(LHSIt->ValId)) == RHS.reg) {
1052 EliminatedLHSVals.push_back(LHSIt->ValId);
1053
1054 // We know this entire LHS live range is okay, so skip it now.
1055 if (++LHSIt == LHSEnd) break;
1056 }
1057 }
1058 }
1059
1060 if (++RHSIt == RHSEnd) break;
1061 }
1062 }
1063
1064 // If we got here, we know that the coallescing will be successful and that
1065 // the value numbers in EliminatedLHSVals will all be merged together. Since
1066 // the most common case is that EliminatedLHSVals has a single number, we
1067 // optimize for it: if there is more than one value, we merge them all into
1068 // the lowest numbered one, then handle the interval as if we were merging
1069 // with one value number.
1070 unsigned LHSValNo;
1071 if (EliminatedLHSVals.size() > 1) {
1072 // Loop through all the equal value numbers merging them into the smallest
1073 // one.
1074 unsigned Smallest = EliminatedLHSVals[0];
1075 for (unsigned i = 1, e = EliminatedLHSVals.size(); i != e; ++i) {
1076 if (EliminatedLHSVals[i] < Smallest) {
1077 // Merge the current notion of the smallest into the smaller one.
1078 LHS.MergeValueNumberInto(Smallest, EliminatedLHSVals[i]);
1079 Smallest = EliminatedLHSVals[i];
1080 } else {
1081 // Merge into the smallest.
1082 LHS.MergeValueNumberInto(EliminatedLHSVals[i], Smallest);
1083 }
1084 }
1085 LHSValNo = Smallest;
1086 } else {
1087 assert(!EliminatedLHSVals.empty() && "No copies from the RHS?");
1088 LHSValNo = EliminatedLHSVals[0];
1089 }
1090
1091 // Okay, now that there is a single LHS value number that we're merging the
1092 // RHS into, update the value number info for the LHS to indicate that the
1093 // value number is defined where the RHS value number was.
1094 LHS.setValueNumberInfo(LHSValNo, RHS.getValNumInfo(0));
1095
1096 // Okay, the final step is to loop over the RHS live intervals, adding them to
1097 // the LHS.
1098 LHS.MergeRangesInAsValue(RHS, LHSValNo);
1099 LHS.weight += RHS.weight;
1100
1101 return true;
1102}
1103
Chris Lattner6d8fbef2006-08-29 23:18:15 +00001104/// JoinIntervals - Attempt to join these two intervals. On failure, this
1105/// returns false. Otherwise, if one of the intervals being joined is a
1106/// physreg, this method always canonicalizes LHS to be it. The output
1107/// "RHS" will not have been modified, so we can use this information
1108/// below to update aliases.
1109bool LiveIntervals::JoinIntervals(LiveInterval &LHS, LiveInterval &RHS) {
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001110 // Compute the final value assignment, assuming that the live ranges can be
1111 // coallesced.
Chris Lattner6d8fbef2006-08-29 23:18:15 +00001112 SmallVector<int, 16> LHSValNoAssignments;
1113 SmallVector<int, 16> RHSValNoAssignments;
Chris Lattner91725b72006-08-31 05:54:43 +00001114 SmallVector<std::pair<unsigned,unsigned>, 16> ValueNumberInfo;
Chris Lattner238416c2006-09-01 06:10:18 +00001115
Chris Lattner6d8fbef2006-08-29 23:18:15 +00001116 // Compute ultimate value numbers for the LHS and RHS values.
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001117 if (RHS.containsOneValue()) {
1118 // Copies from a liveinterval with a single value are simple to handle and
1119 // very common, handle the special case here. This is important, because
1120 // often RHS is small and LHS is large (e.g. a physreg).
1121
1122 // Find out if the RHS is defined as a copy from some value in the LHS.
1123 int RHSValID = -1;
1124 std::pair<unsigned,unsigned> RHSValNoInfo;
Chris Lattnerf21f0202006-09-02 05:26:59 +00001125 unsigned RHSSrcReg = RHS.getSrcRegForValNum(0);
1126 if ((RHSSrcReg == 0 || rep(RHSSrcReg) != LHS.reg)) {
1127 // If RHS is not defined as a copy from the LHS, we can use simpler and
1128 // faster checks to see if the live ranges are coallescable. This joiner
1129 // can't swap the LHS/RHS intervals though.
1130 if (!MRegisterInfo::isPhysicalRegister(RHS.reg)) {
1131 return SimpleJoin(LHS, RHS);
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001132 } else {
Chris Lattnerf21f0202006-09-02 05:26:59 +00001133 RHSValNoInfo = RHS.getValNumInfo(0);
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001134 }
1135 } else {
Chris Lattnerf21f0202006-09-02 05:26:59 +00001136 // It was defined as a copy from the LHS, find out what value # it is.
1137 unsigned ValInst = RHS.getInstForValNum(0);
1138 RHSValID = LHS.getLiveRangeContaining(ValInst-1)->ValId;
1139 RHSValNoInfo = LHS.getValNumInfo(RHSValID);
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001140 }
1141
Chris Lattnerf21f0202006-09-02 05:26:59 +00001142 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1143 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001144 ValueNumberInfo.resize(LHS.getNumValNums());
1145
1146 // Okay, *all* of the values in LHS that are defined as a copy from RHS
1147 // should now get updated.
1148 for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
1149 if (unsigned LHSSrcReg = LHS.getSrcRegForValNum(VN)) {
1150 if (rep(LHSSrcReg) != RHS.reg) {
1151 // If this is not a copy from the RHS, its value number will be
1152 // unmodified by the coallescing.
1153 ValueNumberInfo[VN] = LHS.getValNumInfo(VN);
1154 LHSValNoAssignments[VN] = VN;
1155 } else if (RHSValID == -1) {
1156 // Otherwise, it is a copy from the RHS, and we don't already have a
1157 // value# for it. Keep the current value number, but remember it.
1158 LHSValNoAssignments[VN] = RHSValID = VN;
1159 ValueNumberInfo[VN] = RHSValNoInfo;
1160 } else {
1161 // Otherwise, use the specified value #.
1162 LHSValNoAssignments[VN] = RHSValID;
1163 if (VN != (unsigned)RHSValID)
1164 ValueNumberInfo[VN].first = ~1U;
1165 else
1166 ValueNumberInfo[VN] = RHSValNoInfo;
1167 }
1168 } else {
1169 ValueNumberInfo[VN] = LHS.getValNumInfo(VN);
1170 LHSValNoAssignments[VN] = VN;
1171 }
1172 }
1173
1174 assert(RHSValID != -1 && "Didn't find value #?");
1175 RHSValNoAssignments[0] = RHSValID;
1176
1177 } else {
Chris Lattner238416c2006-09-01 06:10:18 +00001178 // Loop over the value numbers of the LHS, seeing if any are defined from
1179 // the RHS.
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001180 SmallVector<int, 16> LHSValsDefinedFromRHS;
1181 LHSValsDefinedFromRHS.resize(LHS.getNumValNums(), -1);
1182 for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
1183 unsigned ValSrcReg = LHS.getSrcRegForValNum(VN);
1184 if (ValSrcReg == 0) // Src not defined by a copy?
1185 continue;
1186
Chris Lattner238416c2006-09-01 06:10:18 +00001187 // DstReg is known to be a register in the LHS interval. If the src is
1188 // from the RHS interval, we can use its value #.
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001189 if (rep(ValSrcReg) != RHS.reg)
1190 continue;
1191
1192 // Figure out the value # from the RHS.
1193 unsigned ValInst = LHS.getInstForValNum(VN);
1194 LHSValsDefinedFromRHS[VN] = RHS.getLiveRangeContaining(ValInst-1)->ValId;
1195 }
1196
Chris Lattner238416c2006-09-01 06:10:18 +00001197 // Loop over the value numbers of the RHS, seeing if any are defined from
1198 // the LHS.
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001199 SmallVector<int, 16> RHSValsDefinedFromLHS;
1200 RHSValsDefinedFromLHS.resize(RHS.getNumValNums(), -1);
1201 for (unsigned VN = 0, e = RHS.getNumValNums(); VN != e; ++VN) {
1202 unsigned ValSrcReg = RHS.getSrcRegForValNum(VN);
1203 if (ValSrcReg == 0) // Src not defined by a copy?
1204 continue;
1205
Chris Lattner238416c2006-09-01 06:10:18 +00001206 // DstReg is known to be a register in the RHS interval. If the src is
1207 // from the LHS interval, we can use its value #.
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001208 if (rep(ValSrcReg) != LHS.reg)
1209 continue;
1210
1211 // Figure out the value # from the LHS.
1212 unsigned ValInst = RHS.getInstForValNum(VN);
1213 RHSValsDefinedFromLHS[VN] = LHS.getLiveRangeContaining(ValInst-1)->ValId;
1214 }
1215
Chris Lattnerf21f0202006-09-02 05:26:59 +00001216 LHSValNoAssignments.resize(LHS.getNumValNums(), -1);
1217 RHSValNoAssignments.resize(RHS.getNumValNums(), -1);
1218 ValueNumberInfo.reserve(LHS.getNumValNums() + RHS.getNumValNums());
1219
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001220 for (unsigned VN = 0, e = LHS.getNumValNums(); VN != e; ++VN) {
Chris Lattner8a67f6e2006-09-01 07:00:23 +00001221 if (LHSValNoAssignments[VN] >= 0 || LHS.getInstForValNum(VN) == ~2U)
1222 continue;
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001223 ComputeUltimateVN(VN, ValueNumberInfo,
1224 LHSValsDefinedFromRHS, RHSValsDefinedFromLHS,
1225 LHSValNoAssignments, RHSValNoAssignments, LHS, RHS);
1226 }
1227 for (unsigned VN = 0, e = RHS.getNumValNums(); VN != e; ++VN) {
Chris Lattner8a67f6e2006-09-01 07:00:23 +00001228 if (RHSValNoAssignments[VN] >= 0 || RHS.getInstForValNum(VN) == ~2U)
1229 continue;
1230 // If this value number isn't a copy from the LHS, it's a new number.
1231 if (RHSValsDefinedFromLHS[VN] == -1) {
1232 ValueNumberInfo.push_back(RHS.getValNumInfo(VN));
1233 RHSValNoAssignments[VN] = ValueNumberInfo.size()-1;
1234 continue;
1235 }
1236
Chris Lattner2ebfa0c2006-08-31 06:48:26 +00001237 ComputeUltimateVN(VN, ValueNumberInfo,
1238 RHSValsDefinedFromLHS, LHSValsDefinedFromRHS,
1239 RHSValNoAssignments, LHSValNoAssignments, RHS, LHS);
1240 }
Chris Lattner6d8fbef2006-08-29 23:18:15 +00001241 }
1242
1243 // Armed with the mappings of LHS/RHS values to ultimate values, walk the
1244 // interval lists to see if these intervals are coallescable.
1245 LiveInterval::const_iterator I = LHS.begin();
1246 LiveInterval::const_iterator IE = LHS.end();
1247 LiveInterval::const_iterator J = RHS.begin();
1248 LiveInterval::const_iterator JE = RHS.end();
1249
1250 // Skip ahead until the first place of potential sharing.
1251 if (I->start < J->start) {
1252 I = std::upper_bound(I, IE, J->start);
1253 if (I != LHS.begin()) --I;
1254 } else if (J->start < I->start) {
1255 J = std::upper_bound(J, JE, I->start);
1256 if (J != RHS.begin()) --J;
1257 }
1258
1259 while (1) {
1260 // Determine if these two live ranges overlap.
1261 bool Overlaps;
1262 if (I->start < J->start) {
1263 Overlaps = I->end > J->start;
1264 } else {
1265 Overlaps = J->end > I->start;
1266 }
1267
1268 // If so, check value # info to determine if they are really different.
1269 if (Overlaps) {
1270 // If the live range overlap will map to the same value number in the
1271 // result liverange, we can still coallesce them. If not, we can't.
1272 if (LHSValNoAssignments[I->ValId] != RHSValNoAssignments[J->ValId])
1273 return false;
1274 }
1275
1276 if (I->end < J->end) {
1277 ++I;
1278 if (I == IE) break;
1279 } else {
1280 ++J;
1281 if (J == JE) break;
1282 }
1283 }
1284
1285 // If we get here, we know that we can coallesce the live ranges. Ask the
1286 // intervals to coallesce themselves now.
1287 LHS.join(RHS, &LHSValNoAssignments[0], &RHSValNoAssignments[0],
Chris Lattner91725b72006-08-31 05:54:43 +00001288 ValueNumberInfo);
Chris Lattner6d8fbef2006-08-29 23:18:15 +00001289 return true;
1290}
Chris Lattnerf7da2c72006-08-24 22:43:55 +00001291
1292
Chris Lattnercc0d1562004-07-19 14:40:29 +00001293namespace {
1294 // DepthMBBCompare - Comparison predicate that sort first based on the loop
1295 // depth of the basic block (the unsigned), and then on the MBB number.
1296 struct DepthMBBCompare {
1297 typedef std::pair<unsigned, MachineBasicBlock*> DepthMBBPair;
1298 bool operator()(const DepthMBBPair &LHS, const DepthMBBPair &RHS) const {
1299 if (LHS.first > RHS.first) return true; // Deeper loops first
Alkis Evlogimenos70651572004-08-04 09:46:56 +00001300 return LHS.first == RHS.first &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001301 LHS.second->getNumber() < RHS.second->getNumber();
Chris Lattnercc0d1562004-07-19 14:40:29 +00001302 }
1303 };
1304}
Chris Lattner1c5c0442004-07-19 14:08:10 +00001305
Chris Lattnerf7da2c72006-08-24 22:43:55 +00001306
Chris Lattner1acb17c2006-09-02 05:32:53 +00001307void LiveIntervals::CopyCoallesceInMBB(MachineBasicBlock *MBB,
1308 std::vector<CopyRec> &TryAgain) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +00001309 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Chris Lattnerf7da2c72006-08-24 22:43:55 +00001310
1311 for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
1312 MII != E;) {
1313 MachineInstr *Inst = MII++;
1314
1315 // If this isn't a copy, we can't join intervals.
1316 unsigned SrcReg, DstReg;
1317 if (!tii_->isMoveInstr(*Inst, SrcReg, DstReg)) continue;
1318
Chris Lattner1acb17c2006-09-02 05:32:53 +00001319 if (!JoinCopy(Inst, SrcReg, DstReg))
1320 TryAgain.push_back(getCopyRec(Inst, SrcReg, DstReg));
Chris Lattnerf7da2c72006-08-24 22:43:55 +00001321 }
1322}
1323
1324
Chris Lattnercc0d1562004-07-19 14:40:29 +00001325void LiveIntervals::joinIntervals() {
Bill Wendlingbdc679d2006-11-29 00:39:47 +00001326 DOUT << "********** JOINING INTERVALS ***********\n";
Chris Lattnercc0d1562004-07-19 14:40:29 +00001327
Chris Lattner1acb17c2006-09-02 05:32:53 +00001328 std::vector<CopyRec> TryAgainList;
1329
Chris Lattnercc0d1562004-07-19 14:40:29 +00001330 const LoopInfo &LI = getAnalysis<LoopInfo>();
1331 if (LI.begin() == LI.end()) {
1332 // If there are no loops in the function, join intervals in function order.
Chris Lattner1c5c0442004-07-19 14:08:10 +00001333 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1334 I != E; ++I)
Chris Lattner1acb17c2006-09-02 05:32:53 +00001335 CopyCoallesceInMBB(I, TryAgainList);
Chris Lattnercc0d1562004-07-19 14:40:29 +00001336 } else {
1337 // Otherwise, join intervals in inner loops before other intervals.
1338 // Unfortunately we can't just iterate over loop hierarchy here because
1339 // there may be more MBB's than BB's. Collect MBB's for sorting.
1340 std::vector<std::pair<unsigned, MachineBasicBlock*> > MBBs;
1341 for (MachineFunction::iterator I = mf_->begin(), E = mf_->end();
1342 I != E; ++I)
1343 MBBs.push_back(std::make_pair(LI.getLoopDepth(I->getBasicBlock()), I));
1344
1345 // Sort by loop depth.
1346 std::sort(MBBs.begin(), MBBs.end(), DepthMBBCompare());
1347
Alkis Evlogimenos70651572004-08-04 09:46:56 +00001348 // Finally, join intervals in loop nest order.
Chris Lattnercc0d1562004-07-19 14:40:29 +00001349 for (unsigned i = 0, e = MBBs.size(); i != e; ++i)
Chris Lattner1acb17c2006-09-02 05:32:53 +00001350 CopyCoallesceInMBB(MBBs[i].second, TryAgainList);
1351 }
1352
1353 // Joining intervals can allow other intervals to be joined. Iteratively join
1354 // until we make no progress.
1355 bool ProgressMade = true;
1356 while (ProgressMade) {
1357 ProgressMade = false;
1358
1359 for (unsigned i = 0, e = TryAgainList.size(); i != e; ++i) {
1360 CopyRec &TheCopy = TryAgainList[i];
1361 if (TheCopy.MI &&
1362 JoinCopy(TheCopy.MI, TheCopy.SrcReg, TheCopy.DstReg)) {
1363 TheCopy.MI = 0; // Mark this one as done.
1364 ProgressMade = true;
1365 }
1366 }
Chris Lattnerf7da2c72006-08-24 22:43:55 +00001367 }
1368
Bill Wendlingbdc679d2006-11-29 00:39:47 +00001369 DOUT << "*** Register mapping ***\n";
1370 for (int i = 0, e = r2rMap_.size(); i != e; ++i)
1371 if (r2rMap_[i]) {
1372 DOUT << " reg " << i << " -> ";
1373 DEBUG(printRegName(r2rMap_[i]));
1374 DOUT << "\n";
1375 }
Chris Lattner1c5c0442004-07-19 14:08:10 +00001376}
1377
Evan Cheng647c15e2006-05-12 06:06:34 +00001378/// Return true if the two specified registers belong to different register
1379/// classes. The registers may be either phys or virt regs.
1380bool LiveIntervals::differingRegisterClasses(unsigned RegA,
1381 unsigned RegB) const {
Alkis Evlogimenos79b0c3f2004-01-23 13:37:51 +00001382
Chris Lattner7ac2d312004-07-24 02:59:07 +00001383 // Get the register classes for the first reg.
Chris Lattnerad3c74f2004-10-26 05:29:18 +00001384 if (MRegisterInfo::isPhysicalRegister(RegA)) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00001385 assert(MRegisterInfo::isVirtualRegister(RegB) &&
Chris Lattnerad3c74f2004-10-26 05:29:18 +00001386 "Shouldn't consider two physregs!");
Evan Cheng647c15e2006-05-12 06:06:34 +00001387 return !mf_->getSSARegMap()->getRegClass(RegB)->contains(RegA);
Chris Lattnerad3c74f2004-10-26 05:29:18 +00001388 }
Chris Lattner7ac2d312004-07-24 02:59:07 +00001389
1390 // Compare against the regclass for the second reg.
Evan Cheng647c15e2006-05-12 06:06:34 +00001391 const TargetRegisterClass *RegClass = mf_->getSSARegMap()->getRegClass(RegA);
1392 if (MRegisterInfo::isVirtualRegister(RegB))
1393 return RegClass != mf_->getSSARegMap()->getRegClass(RegB);
1394 else
1395 return !RegClass->contains(RegB);
Chris Lattner7ac2d312004-07-24 02:59:07 +00001396}
1397
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +00001398LiveInterval LiveIntervals::createInterval(unsigned reg) {
Misha Brukmanedf128a2005-04-21 22:36:52 +00001399 float Weight = MRegisterInfo::isPhysicalRegister(reg) ?
Jim Laskey7902c752006-11-07 12:25:45 +00001400 HUGE_VALF : 0.0F;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +00001401 return LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +00001402}