blob: 09557851be4bcd90b8adb22866ef74bd0791713d [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//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00007//
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"
Dan Gohman6d69ba82008-07-25 00:02:30 +000022#include "llvm/Analysis/AliasAnalysis.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"
Evan Cheng22f07ff2007-12-11 02:09:15 +000026#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000027#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000028#include "llvm/CodeGen/Passes.h"
Dan Gohman6d69ba82008-07-25 00:02:30 +000029#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000030#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000031#include "llvm/Target/TargetInstrInfo.h"
32#include "llvm/Target/TargetMachine.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/ADT/Statistic.h"
36#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000037#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000038#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000039using namespace llvm;
40
Dan Gohman844731a2008-05-13 00:00:25 +000041// Hidden options for help debugging.
42static cl::opt<bool> DisableReMat("disable-rematerialization",
43 cl::init(false), cl::Hidden);
Evan Cheng81a03822007-11-17 00:40:40 +000044
Dan Gohman844731a2008-05-13 00:00:25 +000045static cl::opt<bool> SplitAtBB("split-intervals-at-bb",
46 cl::init(true), cl::Hidden);
47static cl::opt<int> SplitLimit("split-limit",
48 cl::init(-1), cl::Hidden);
Evan Chengbc165e42007-08-16 07:24:22 +000049
Dan Gohman4c8f8702008-07-25 15:08:37 +000050static cl::opt<bool> EnableAggressiveRemat("aggressive-remat", cl::Hidden);
51
Chris Lattnercd3245a2006-12-19 22:41:21 +000052STATISTIC(numIntervals, "Number of original intervals");
53STATISTIC(numIntervalsAfter, "Number of intervals after coalescing");
Evan Cheng0cbb1162007-11-29 01:06:25 +000054STATISTIC(numFolds , "Number of loads/stores folded into instructions");
55STATISTIC(numSplits , "Number of intervals split");
Chris Lattnercd3245a2006-12-19 22:41:21 +000056
Devang Patel19974732007-05-03 01:11:54 +000057char LiveIntervals::ID = 0;
Dan Gohman844731a2008-05-13 00:00:25 +000058static RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000059
Chris Lattnerf7da2c72006-08-24 22:43:55 +000060void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman6d69ba82008-07-25 00:02:30 +000061 AU.addRequired<AliasAnalysis>();
62 AU.addPreserved<AliasAnalysis>();
David Greene25133302007-06-08 17:18:56 +000063 AU.addPreserved<LiveVariables>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000064 AU.addRequired<LiveVariables>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000065 AU.addPreservedID(MachineLoopInfoID);
66 AU.addPreservedID(MachineDominatorsID);
Owen Andersonfcc63502008-05-29 18:35:21 +000067 AU.addPreservedID(PHIEliminationID);
68 AU.addRequiredID(PHIEliminationID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000069 AU.addRequiredID(TwoAddressInstructionPassID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000070 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000071}
72
Chris Lattnerf7da2c72006-08-24 22:43:55 +000073void LiveIntervals::releaseMemory() {
Evan Cheng3f32d652008-06-04 09:18:41 +000074 MBB2IdxMap.clear();
Evan Cheng4ca980e2007-10-17 02:10:22 +000075 Idx2MBBMap.clear();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000076 mi2iMap_.clear();
77 i2miMap_.clear();
78 r2iMap_.clear();
Evan Chengdd199d22007-09-06 01:07:24 +000079 // Release VNInfo memroy regions after all VNInfo objects are dtor'd.
80 VNInfoAllocator.Reset();
Evan Cheng1ed99222008-07-19 00:37:25 +000081 while (!ClonedMIs.empty()) {
82 MachineInstr *MI = ClonedMIs.back();
83 ClonedMIs.pop_back();
84 mf_->DeleteMachineInstr(MI);
85 }
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000086}
87
Owen Anderson80b3ce62008-05-28 20:54:50 +000088void LiveIntervals::computeNumbering() {
89 Index2MiMap OldI2MI = i2miMap_;
Owen Anderson7fbad272008-07-23 21:37:49 +000090 std::vector<IdxMBBPair> OldI2MBB = Idx2MBBMap;
Owen Anderson80b3ce62008-05-28 20:54:50 +000091
92 Idx2MBBMap.clear();
93 MBB2IdxMap.clear();
94 mi2iMap_.clear();
95 i2miMap_.clear();
96
Owen Andersona1566f22008-07-22 22:46:49 +000097 FunctionSize = 0;
98
Chris Lattner428b92e2006-09-15 03:57:23 +000099 // Number MachineInstrs and MachineBasicBlocks.
100 // Initialize MBB indexes to a sentinal.
Evan Cheng549f27d32007-08-13 23:45:17 +0000101 MBB2IdxMap.resize(mf_->getNumBlockIDs(), std::make_pair(~0U,~0U));
Chris Lattner428b92e2006-09-15 03:57:23 +0000102
103 unsigned MIIndex = 0;
104 for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
105 MBB != E; ++MBB) {
Evan Cheng549f27d32007-08-13 23:45:17 +0000106 unsigned StartIdx = MIIndex;
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000107
Owen Anderson7fbad272008-07-23 21:37:49 +0000108 // Insert an empty slot at the beginning of each block.
109 MIIndex += InstrSlots::NUM;
110 i2miMap_.push_back(0);
111
Chris Lattner428b92e2006-09-15 03:57:23 +0000112 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
113 I != E; ++I) {
114 bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000115 assert(inserted && "multiple MachineInstr -> index mappings");
Chris Lattner428b92e2006-09-15 03:57:23 +0000116 i2miMap_.push_back(I);
117 MIIndex += InstrSlots::NUM;
Owen Andersona1566f22008-07-22 22:46:49 +0000118 FunctionSize++;
Owen Anderson7fbad272008-07-23 21:37:49 +0000119
120 // Insert an empty slot after every instruction.
Owen Anderson1fbb4542008-06-16 16:58:24 +0000121 MIIndex += InstrSlots::NUM;
122 i2miMap_.push_back(0);
Owen Anderson35578012008-06-16 07:10:49 +0000123 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000124
Owen Anderson1fbb4542008-06-16 16:58:24 +0000125 // Set the MBB2IdxMap entry for this MBB.
126 MBB2IdxMap[MBB->getNumber()] = std::make_pair(StartIdx, MIIndex - 1);
127 Idx2MBBMap.push_back(std::make_pair(StartIdx, MBB));
Chris Lattner428b92e2006-09-15 03:57:23 +0000128 }
Evan Cheng4ca980e2007-10-17 02:10:22 +0000129 std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
Owen Anderson80b3ce62008-05-28 20:54:50 +0000130
131 if (!OldI2MI.empty())
Owen Anderson7fbad272008-07-23 21:37:49 +0000132 for (iterator OI = begin(), OE = end(); OI != OE; ++OI)
133 for (LiveInterval::iterator LI = OI->second.begin(),
134 LE = OI->second.end(); LI != LE; ++LI) {
Owen Anderson4b5b2092008-05-29 18:15:49 +0000135
Owen Anderson7eec0c22008-05-29 23:01:22 +0000136 // Remap the start index of the live range to the corresponding new
137 // number, or our best guess at what it _should_ correspond to if the
138 // original instruction has been erased. This is either the following
139 // instruction or its predecessor.
Owen Anderson7fbad272008-07-23 21:37:49 +0000140 unsigned index = LI->start / InstrSlots::NUM;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000141 unsigned offset = LI->start % InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000142 if (offset == InstrSlots::LOAD) {
143 std::vector<IdxMBBPair>::const_iterator I =
144 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), index);
145 // Take the pair containing the index
146 std::vector<IdxMBBPair>::const_iterator J =
147 ((I != OldI2MBB.end() && I->first > index) ||
148 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000149
Owen Anderson7fbad272008-07-23 21:37:49 +0000150 LI->start = getMBBStartIdx(J->second);
151 } else {
152 LI->start = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000153 }
154
155 // Remap the ending index in the same way that we remapped the start,
156 // except for the final step where we always map to the immediately
157 // following instruction.
Owen Anderson7fbad272008-07-23 21:37:49 +0000158 index = LI->end / InstrSlots::NUM;
159 offset = LI->end % InstrSlots::NUM;
160 if (offset == InstrSlots::STORE) {
161 std::vector<IdxMBBPair>::const_iterator I =
162 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), index);
163 // Take the pair containing the index
164 std::vector<IdxMBBPair>::const_iterator J =
165 ((I != OldI2MBB.end() && I->first > index) ||
166 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
167
168 LI->end = getMBBEndIdx(J->second) + 1;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000169 } else {
Owen Anderson7fbad272008-07-23 21:37:49 +0000170 LI->end = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000171 }
Owen Anderson745825f42008-05-28 22:40:08 +0000172
Owen Anderson7eec0c22008-05-29 23:01:22 +0000173 // Remap the VNInfo def index, which works the same as the
174 // start indices above.
Owen Anderson745825f42008-05-28 22:40:08 +0000175 VNInfo* vni = LI->valno;
Owen Anderson7fbad272008-07-23 21:37:49 +0000176 index = vni->def / InstrSlots::NUM;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000177 offset = vni->def % InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000178 if (offset == InstrSlots::LOAD) {
179 std::vector<IdxMBBPair>::const_iterator I =
180 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), index);
181 // Take the pair containing the index
182 std::vector<IdxMBBPair>::const_iterator J =
183 ((I != OldI2MBB.end() && I->first > index) ||
184 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000185
Owen Anderson7fbad272008-07-23 21:37:49 +0000186 vni->def = getMBBStartIdx(J->second);
187
188 } else {
189 vni->def = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000190 }
Owen Anderson745825f42008-05-28 22:40:08 +0000191
Owen Anderson7eec0c22008-05-29 23:01:22 +0000192 // Remap the VNInfo kill indices, which works the same as
193 // the end indices above.
Owen Anderson4b5b2092008-05-29 18:15:49 +0000194 for (size_t i = 0; i < vni->kills.size(); ++i) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000195 index = vni->kills[i] / InstrSlots::NUM;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000196 offset = vni->kills[i] % InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000197 if (OldI2MI[vni->kills[i] / InstrSlots::NUM]) {
198 std::vector<IdxMBBPair>::const_iterator I =
199 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), index);
200 // Take the pair containing the index
201 std::vector<IdxMBBPair>::const_iterator J =
202 ((I != OldI2MBB.end() && I->first > index) ||
203 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
204
205 vni->kills[i] = getMBBEndIdx(J->second) + 1;
206 } else {
207 vni->kills[i] = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000208 }
Owen Anderson4b5b2092008-05-29 18:15:49 +0000209 }
Owen Anderson80b3ce62008-05-28 20:54:50 +0000210 }
211}
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000212
Owen Anderson80b3ce62008-05-28 20:54:50 +0000213/// runOnMachineFunction - Register allocate the whole function
214///
215bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
216 mf_ = &fn;
217 mri_ = &mf_->getRegInfo();
218 tm_ = &fn.getTarget();
219 tri_ = tm_->getRegisterInfo();
220 tii_ = tm_->getInstrInfo();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000221 aa_ = &getAnalysis<AliasAnalysis>();
Owen Anderson80b3ce62008-05-28 20:54:50 +0000222 lv_ = &getAnalysis<LiveVariables>();
223 allocatableRegs_ = tri_->getAllocatableSet(fn);
224
225 computeNumbering();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000226 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000227
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000228 numIntervals += getNumIntervals();
229
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000230 DOUT << "********** INTERVALS **********\n";
231 for (iterator I = begin(), E = end(); I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000232 I->second.print(DOUT, tri_);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000233 DOUT << "\n";
234 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000235
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000236 numIntervalsAfter += getNumIntervals();
Chris Lattner70ca3582004-09-30 15:59:17 +0000237 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000238 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000239}
240
Chris Lattner70ca3582004-09-30 15:59:17 +0000241/// print - Implement the dump method.
Reid Spencerce9653c2004-12-07 04:03:45 +0000242void LiveIntervals::print(std::ostream &O, const Module* ) const {
Chris Lattner70ca3582004-09-30 15:59:17 +0000243 O << "********** INTERVALS **********\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000244 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Evan Cheng3f32d652008-06-04 09:18:41 +0000245 I->second.print(O, tri_);
246 O << "\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000247 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000248
249 O << "********** MACHINEINSTRS **********\n";
250 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
251 mbbi != mbbe; ++mbbi) {
252 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
253 for (MachineBasicBlock::iterator mii = mbbi->begin(),
254 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner477e4552004-09-30 16:10:45 +0000255 O << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner70ca3582004-09-30 15:59:17 +0000256 }
257 }
258}
259
Evan Chengc92da382007-11-03 07:20:12 +0000260/// conflictsWithPhysRegDef - Returns true if the specified register
261/// is defined during the duration of the specified interval.
262bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
263 VirtRegMap &vrm, unsigned reg) {
264 for (LiveInterval::Ranges::const_iterator
265 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
266 for (unsigned index = getBaseIndex(I->start),
267 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
268 index += InstrSlots::NUM) {
269 // skip deleted instructions
270 while (index != end && !getInstructionFromIndex(index))
271 index += InstrSlots::NUM;
272 if (index == end) break;
273
274 MachineInstr *MI = getInstructionFromIndex(index);
Evan Cheng5d446262007-11-15 08:13:29 +0000275 unsigned SrcReg, DstReg;
276 if (tii_->isMoveInstr(*MI, SrcReg, DstReg))
277 if (SrcReg == li.reg || DstReg == li.reg)
278 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000279 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
280 MachineOperand& mop = MI->getOperand(i);
Evan Cheng5d446262007-11-15 08:13:29 +0000281 if (!mop.isRegister())
Evan Chengc92da382007-11-03 07:20:12 +0000282 continue;
283 unsigned PhysReg = mop.getReg();
Evan Cheng5d446262007-11-15 08:13:29 +0000284 if (PhysReg == 0 || PhysReg == li.reg)
Evan Chengc92da382007-11-03 07:20:12 +0000285 continue;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000286 if (TargetRegisterInfo::isVirtualRegister(PhysReg)) {
Evan Cheng5d446262007-11-15 08:13:29 +0000287 if (!vrm.hasPhys(PhysReg))
288 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000289 PhysReg = vrm.getPhys(PhysReg);
Evan Cheng5d446262007-11-15 08:13:29 +0000290 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000291 if (PhysReg && tri_->regsOverlap(PhysReg, reg))
Evan Chengc92da382007-11-03 07:20:12 +0000292 return true;
293 }
294 }
295 }
296
297 return false;
298}
299
Evan Cheng549f27d32007-08-13 23:45:17 +0000300void LiveIntervals::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000301 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000302 cerr << tri_->getName(reg);
Evan Cheng549f27d32007-08-13 23:45:17 +0000303 else
304 cerr << "%reg" << reg;
305}
306
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000307void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000308 MachineBasicBlock::iterator mi,
Owen Anderson6b098de2008-06-25 23:39:39 +0000309 unsigned MIIdx, MachineOperand& MO,
Evan Chengef0732d2008-07-10 07:35:43 +0000310 unsigned MOIdx,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000311 LiveInterval &interval) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000312 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000313 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000314
Evan Cheng419852c2008-04-03 16:39:43 +0000315 if (mi->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
316 DOUT << "is a implicit_def\n";
317 return;
318 }
319
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000320 // Virtual registers may be defined multiple times (due to phi
321 // elimination and 2-addr elimination). Much of what we do only has to be
322 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000323 // time we see a vreg.
324 if (interval.empty()) {
325 // Get the Idx of the defining instructions.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000326 unsigned defIndex = getDefIndex(MIIdx);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000327 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000328 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000329 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000330 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000331 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000332 tii_->isMoveInstr(*mi, SrcReg, DstReg))
333 CopyMI = mi;
334 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000335
336 assert(ValNo->id == 0 && "First value in interval is not 0?");
Chris Lattner7ac2d312004-07-24 02:59:07 +0000337
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000338 // Loop over all of the blocks that the vreg is defined in. There are
339 // two cases we have to handle here. The most common case is a vreg
340 // whose lifetime is contained within a basic block. In this case there
341 // will be a single kill, in MBB, which comes after the definition.
342 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
343 // FIXME: what about dead vars?
344 unsigned killIdx;
345 if (vi.Kills[0] != mi)
346 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
347 else
348 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000349
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000350 // If the kill happens after the definition, we have an intra-block
351 // live range.
352 if (killIdx > defIndex) {
Evan Cheng61de82d2007-02-15 05:59:24 +0000353 assert(vi.AliveBlocks.none() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000354 "Shouldn't be alive across any blocks!");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000355 LiveRange LR(defIndex, killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000356 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000357 DOUT << " +" << LR << "\n";
Evan Chengf3bb2e62007-09-05 21:46:51 +0000358 interval.addKill(ValNo, killIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000359 return;
360 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000361 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000362
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000363 // The other case we handle is when a virtual register lives to the end
364 // of the defining block, potentially live across some blocks, then is
365 // live into some number of blocks, but gets killed. Start by adding a
366 // range that goes from this definition to the end of the defining block.
Owen Anderson7fbad272008-07-23 21:37:49 +0000367 LiveRange NewLR(defIndex, getMBBEndIdx(mbb)+1, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000368 DOUT << " +" << NewLR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000369 interval.addRange(NewLR);
370
371 // Iterate over all of the blocks that the variable is completely
372 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
373 // live interval.
374 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
375 if (vi.AliveBlocks[i]) {
Owen Anderson31ec8412008-06-16 19:32:40 +0000376 LiveRange LR(getMBBStartIdx(i),
Evan Chengf26e8552008-06-17 20:13:36 +0000377 getMBBEndIdx(i)+1, // MBB ends at -1.
Owen Anderson31ec8412008-06-16 19:32:40 +0000378 ValNo);
379 interval.addRange(LR);
380 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000381 }
382 }
383
384 // Finally, this virtual register is live from the start of any killing
385 // block to the 'use' slot of the killing instruction.
386 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
387 MachineInstr *Kill = vi.Kills[i];
Evan Cheng8df78602007-08-08 03:00:28 +0000388 unsigned killIdx = getUseIndex(getInstructionIndex(Kill))+1;
Chris Lattner428b92e2006-09-15 03:57:23 +0000389 LiveRange LR(getMBBStartIdx(Kill->getParent()),
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000390 killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000391 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000392 interval.addKill(ValNo, killIdx);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000393 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000394 }
395
396 } else {
397 // If this is the second time we see a virtual register definition, it
398 // must be due to phi elimination or two addr elimination. If this is
Evan Chengbf105c82006-11-03 03:04:46 +0000399 // the result of two address elimination, then the vreg is one of the
400 // def-and-use register operand.
Evan Chengef0732d2008-07-10 07:35:43 +0000401 if (mi->isRegReDefinedByTwoAddr(interval.reg, MOIdx)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000402 // If this is a two-address definition, then we have already processed
403 // the live range. The only problem is that we didn't realize there
404 // are actually two values in the live interval. Because of this we
405 // need to take the LiveRegion that defines this register and split it
406 // into two values.
Evan Chenga07cec92008-01-10 08:22:10 +0000407 assert(interval.containsOneValue());
408 unsigned DefIndex = getDefIndex(interval.getValNumInfo(0)->def);
Chris Lattner6b128bd2006-09-03 08:07:11 +0000409 unsigned RedefIndex = getDefIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000410
Evan Cheng4f8ff162007-08-11 00:59:19 +0000411 const LiveRange *OldLR = interval.getLiveRangeContaining(RedefIndex-1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000412 VNInfo *OldValNo = OldLR->valno;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000413
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000414 // Delete the initial value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000415 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000416 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000417
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000418 // Two-address vregs should always only be redefined once. This means
419 // that at this point, there should be exactly one value number in it.
420 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
421
Chris Lattner91725b72006-08-31 05:54:43 +0000422 // The new value number (#1) is defined by the instruction we claimed
423 // defined value #0.
Evan Chengc8d044e2008-02-15 18:24:29 +0000424 VNInfo *ValNo = interval.getNextValue(OldValNo->def, OldValNo->copy,
425 VNInfoAllocator);
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000426
Chris Lattner91725b72006-08-31 05:54:43 +0000427 // Value#0 is now defined by the 2-addr instruction.
Evan Chengc8d044e2008-02-15 18:24:29 +0000428 OldValNo->def = RedefIndex;
429 OldValNo->copy = 0;
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000430
431 // Add the new live interval which replaces the range for the input copy.
432 LiveRange LR(DefIndex, RedefIndex, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000433 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000434 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000435 interval.addKill(ValNo, RedefIndex);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000436
437 // If this redefinition is dead, we need to add a dummy unit live
438 // range covering the def slot.
Owen Anderson6b098de2008-06-25 23:39:39 +0000439 if (MO.isDead())
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000440 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, OldValNo));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000441
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000442 DOUT << " RESULT: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000443 interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000444
445 } else {
446 // Otherwise, this must be because of phi elimination. If this is the
447 // first redefinition of the vreg that we have seen, go back and change
448 // the live range in the PHI block to be a different value number.
449 if (interval.containsOneValue()) {
450 assert(vi.Kills.size() == 1 &&
451 "PHI elimination vreg should have one kill, the PHI itself!");
452
453 // Remove the old range that we now know has an incorrect number.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000454 VNInfo *VNI = interval.getValNumInfo(0);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000455 MachineInstr *Killer = vi.Kills[0];
Chris Lattner428b92e2006-09-15 03:57:23 +0000456 unsigned Start = getMBBStartIdx(Killer->getParent());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000457 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000458 DOUT << " Removing [" << Start << "," << End << "] from: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000459 interval.print(DOUT, tri_); DOUT << "\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000460 interval.removeRange(Start, End);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000461 VNI->hasPHIKill = true;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000462 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000463
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000464 // Replace the interval with one of a NEW value number. Note that this
465 // value number isn't actually defined by an instruction, weird huh? :)
Evan Chengf3bb2e62007-09-05 21:46:51 +0000466 LiveRange LR(Start, End, interval.getNextValue(~0, 0, VNInfoAllocator));
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000467 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000468 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000469 interval.addKill(LR.valno, End);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000470 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000471 }
472
473 // In the case of PHI elimination, each variable definition is only
474 // live until the end of the block. We've already taken care of the
475 // rest of the live range.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000476 unsigned defIndex = getDefIndex(MIIdx);
Chris Lattner91725b72006-08-31 05:54:43 +0000477
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000478 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000479 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000480 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000481 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000482 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000483 tii_->isMoveInstr(*mi, SrcReg, DstReg))
484 CopyMI = mi;
485 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Chris Lattner91725b72006-08-31 05:54:43 +0000486
Owen Anderson7fbad272008-07-23 21:37:49 +0000487 unsigned killIndex = getMBBEndIdx(mbb) + 1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000488 LiveRange LR(defIndex, killIndex, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000489 interval.addRange(LR);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000490 interval.addKill(ValNo, killIndex);
491 ValNo->hasPHIKill = true;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000492 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000493 }
494 }
495
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000496 DOUT << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000497}
498
Chris Lattnerf35fef72004-07-23 21:24:19 +0000499void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000500 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000501 unsigned MIIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000502 MachineOperand& MO,
Chris Lattner91725b72006-08-31 05:54:43 +0000503 LiveInterval &interval,
Evan Chengc8d044e2008-02-15 18:24:29 +0000504 MachineInstr *CopyMI) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000505 // A physical register cannot be live across basic block, so its
506 // lifetime must end somewhere in its defining basic block.
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000507 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000508
Chris Lattner6b128bd2006-09-03 08:07:11 +0000509 unsigned baseIndex = MIIdx;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000510 unsigned start = getDefIndex(baseIndex);
511 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000512
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000513 // If it is not used after definition, it is considered dead at
514 // the instruction defining it. Hence its interval is:
515 // [defSlot(def), defSlot(def)+1)
Owen Anderson6b098de2008-06-25 23:39:39 +0000516 if (MO.isDead()) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000517 DOUT << " dead";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000518 end = getDefIndex(start) + 1;
519 goto exit;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000520 }
521
522 // If it is not dead on definition, it must be killed by a
523 // subsequent instruction. Hence its interval is:
524 // [defSlot(def), useSlot(kill)+1)
Owen Anderson7fbad272008-07-23 21:37:49 +0000525 baseIndex += InstrSlots::NUM;
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000526 while (++mi != MBB->end()) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000527 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
528 getInstructionFromIndex(baseIndex) == 0)
529 baseIndex += InstrSlots::NUM;
Evan Cheng6130f662008-03-05 00:59:57 +0000530 if (mi->killsRegister(interval.reg, tri_)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000531 DOUT << " killed";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000532 end = getUseIndex(baseIndex) + 1;
533 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000534 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Cheng9a1956a2006-11-15 20:54:11 +0000535 // Another instruction redefines the register before it is ever read.
536 // Then the register is essentially dead at the instruction that defines
537 // it. Hence its interval is:
538 // [defSlot(def), defSlot(def)+1)
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000539 DOUT << " dead";
Evan Cheng9a1956a2006-11-15 20:54:11 +0000540 end = getDefIndex(start) + 1;
541 goto exit;
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000542 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000543
544 baseIndex += InstrSlots::NUM;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000545 }
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000546
547 // The only case we should have a dead physreg here without a killing or
548 // instruction where we know it's dead is if it is live-in to the function
549 // and never used.
Evan Chengc8d044e2008-02-15 18:24:29 +0000550 assert(!CopyMI && "physreg was not killed in defining block!");
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000551 end = getDefIndex(start) + 1; // It's dead.
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000552
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000553exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000554 assert(start < end && "did not find end of interval?");
Chris Lattnerf768bba2005-03-09 23:05:19 +0000555
Evan Cheng24a3cc42007-04-25 07:30:23 +0000556 // Already exists? Extend old live interval.
557 LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000558 VNInfo *ValNo = (OldLR != interval.end())
Evan Chengc8d044e2008-02-15 18:24:29 +0000559 ? OldLR->valno : interval.getNextValue(start, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000560 LiveRange LR(start, end, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000561 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000562 interval.addKill(LR.valno, end);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000563 DOUT << " +" << LR << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000564}
565
Chris Lattnerf35fef72004-07-23 21:24:19 +0000566void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
567 MachineBasicBlock::iterator MI,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000568 unsigned MIIdx,
Evan Chengef0732d2008-07-10 07:35:43 +0000569 MachineOperand& MO,
570 unsigned MOIdx) {
Owen Anderson6b098de2008-06-25 23:39:39 +0000571 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Evan Chengef0732d2008-07-10 07:35:43 +0000572 handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000573 getOrCreateInterval(MO.getReg()));
574 else if (allocatableRegs_[MO.getReg()]) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000575 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000576 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000577 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000578 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000579 tii_->isMoveInstr(*MI, SrcReg, DstReg))
580 CopyMI = MI;
Owen Anderson6b098de2008-06-25 23:39:39 +0000581 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
582 getOrCreateInterval(MO.getReg()), CopyMI);
Evan Cheng24a3cc42007-04-25 07:30:23 +0000583 // Def of a register also defines its sub-registers.
Owen Anderson6b098de2008-06-25 23:39:39 +0000584 for (const unsigned* AS = tri_->getSubRegisters(MO.getReg()); *AS; ++AS)
Evan Cheng6130f662008-03-05 00:59:57 +0000585 // If MI also modifies the sub-register explicitly, avoid processing it
586 // more than once. Do not pass in TRI here so it checks for exact match.
587 if (!MI->modifiesRegister(*AS))
Owen Anderson6b098de2008-06-25 23:39:39 +0000588 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
589 getOrCreateInterval(*AS), 0);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000590 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000591}
592
Evan Chengb371f452007-02-19 21:49:54 +0000593void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000594 unsigned MIIdx,
Evan Cheng24a3cc42007-04-25 07:30:23 +0000595 LiveInterval &interval, bool isAlias) {
Evan Chengb371f452007-02-19 21:49:54 +0000596 DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg));
597
598 // Look for kills, if it reaches a def before it's killed, then it shouldn't
599 // be considered a livein.
600 MachineBasicBlock::iterator mi = MBB->begin();
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000601 unsigned baseIndex = MIIdx;
602 unsigned start = baseIndex;
Evan Chengb371f452007-02-19 21:49:54 +0000603 unsigned end = start;
604 while (mi != MBB->end()) {
Evan Cheng6130f662008-03-05 00:59:57 +0000605 if (mi->killsRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000606 DOUT << " killed";
607 end = getUseIndex(baseIndex) + 1;
608 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000609 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000610 // Another instruction redefines the register before it is ever read.
611 // Then the register is essentially dead at the instruction that defines
612 // it. Hence its interval is:
613 // [defSlot(def), defSlot(def)+1)
614 DOUT << " dead";
615 end = getDefIndex(start) + 1;
616 goto exit;
617 }
618
619 baseIndex += InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000620 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
621 getInstructionFromIndex(baseIndex) == 0)
622 baseIndex += InstrSlots::NUM;
Evan Chengb371f452007-02-19 21:49:54 +0000623 ++mi;
624 }
625
626exit:
Evan Cheng75611fb2007-06-27 01:16:36 +0000627 // Live-in register might not be used at all.
628 if (end == MIIdx) {
Evan Cheng292da942007-06-27 18:47:28 +0000629 if (isAlias) {
630 DOUT << " dead";
Evan Cheng75611fb2007-06-27 01:16:36 +0000631 end = getDefIndex(MIIdx) + 1;
Evan Cheng292da942007-06-27 18:47:28 +0000632 } else {
633 DOUT << " live through";
634 end = baseIndex;
635 }
Evan Cheng24a3cc42007-04-25 07:30:23 +0000636 }
637
Evan Chengf3bb2e62007-09-05 21:46:51 +0000638 LiveRange LR(start, end, interval.getNextValue(start, 0, VNInfoAllocator));
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000639 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000640 interval.addKill(LR.valno, end);
Evan Cheng24c2e5c2007-08-08 07:03:29 +0000641 DOUT << " +" << LR << '\n';
Evan Chengb371f452007-02-19 21:49:54 +0000642}
643
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000644/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000645/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000646/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000647/// which a variable is live
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000648void LiveIntervals::computeIntervals() {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000649 DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
650 << "********** Function: "
651 << ((Value*)mf_->getFunction())->getName() << '\n';
Chris Lattner6b128bd2006-09-03 08:07:11 +0000652 // Track the index of the current machine instr.
653 unsigned MIIndex = 0;
Owen Anderson7fbad272008-07-23 21:37:49 +0000654
655 // Skip over empty initial indices.
656 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
657 getInstructionFromIndex(MIIndex) == 0)
658 MIIndex += InstrSlots::NUM;
659
Chris Lattner428b92e2006-09-15 03:57:23 +0000660 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
661 MBBI != E; ++MBBI) {
662 MachineBasicBlock *MBB = MBBI;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000663 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000664
Chris Lattner428b92e2006-09-15 03:57:23 +0000665 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000666
Dan Gohmancb406c22007-10-03 19:26:29 +0000667 // Create intervals for live-ins to this BB first.
668 for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
669 LE = MBB->livein_end(); LI != LE; ++LI) {
670 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
671 // Multiple live-ins can alias the same register.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000672 for (const unsigned* AS = tri_->getSubRegisters(*LI); *AS; ++AS)
Dan Gohmancb406c22007-10-03 19:26:29 +0000673 if (!hasInterval(*AS))
674 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
675 true);
Chris Lattnerdffb2e82006-09-04 18:27:40 +0000676 }
677
Chris Lattner428b92e2006-09-15 03:57:23 +0000678 for (; MI != miEnd; ++MI) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000679 DOUT << MIIndex << "\t" << *MI;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000680
Evan Cheng438f7bc2006-11-10 08:43:01 +0000681 // Handle defs.
Chris Lattner428b92e2006-09-15 03:57:23 +0000682 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
683 MachineOperand &MO = MI->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000684 // handle register defs - build intervals
Chris Lattner428b92e2006-09-15 03:57:23 +0000685 if (MO.isRegister() && MO.getReg() && MO.isDef())
Evan Chengef0732d2008-07-10 07:35:43 +0000686 handleRegisterDef(MBB, MI, MIIndex, MO, i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000687 }
Chris Lattner6b128bd2006-09-03 08:07:11 +0000688
689 MIIndex += InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000690
691 // Skip over empty indices.
692 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
693 getInstructionFromIndex(MIIndex) == 0)
694 MIIndex += InstrSlots::NUM;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000695 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000696 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000697}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000698
Evan Cheng4ca980e2007-10-17 02:10:22 +0000699bool LiveIntervals::findLiveInMBBs(const LiveRange &LR,
Evan Chenga5bfc972007-10-17 06:53:44 +0000700 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
Evan Cheng4ca980e2007-10-17 02:10:22 +0000701 std::vector<IdxMBBPair>::const_iterator I =
702 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), LR.start);
703
704 bool ResVal = false;
705 while (I != Idx2MBBMap.end()) {
706 if (LR.end <= I->first)
707 break;
708 MBBs.push_back(I->second);
709 ResVal = true;
710 ++I;
711 }
712 return ResVal;
713}
714
715
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000716LiveInterval LiveIntervals::createInterval(unsigned reg) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000717 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
Jim Laskey7902c752006-11-07 12:25:45 +0000718 HUGE_VALF : 0.0F;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000719 return LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000720}
Evan Chengf2fbca62007-11-12 06:35:08 +0000721
Evan Chengc8d044e2008-02-15 18:24:29 +0000722/// getVNInfoSourceReg - Helper function that parses the specified VNInfo
723/// copy field and returns the source register that defines it.
724unsigned LiveIntervals::getVNInfoSourceReg(const VNInfo *VNI) const {
725 if (!VNI->copy)
726 return 0;
727
728 if (VNI->copy->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
729 return VNI->copy->getOperand(1).getReg();
Evan Cheng7e073ba2008-04-09 20:57:25 +0000730 if (VNI->copy->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
731 return VNI->copy->getOperand(2).getReg();
Evan Chengc8d044e2008-02-15 18:24:29 +0000732 unsigned SrcReg, DstReg;
733 if (tii_->isMoveInstr(*VNI->copy, SrcReg, DstReg))
734 return SrcReg;
735 assert(0 && "Unrecognized copy instruction!");
736 return 0;
737}
Evan Chengf2fbca62007-11-12 06:35:08 +0000738
739//===----------------------------------------------------------------------===//
740// Register allocator hooks.
741//
742
Evan Chengd70dbb52008-02-22 09:24:50 +0000743/// getReMatImplicitUse - If the remat definition MI has one (for now, we only
744/// allow one) virtual register operand, then its uses are implicitly using
745/// the register. Returns the virtual register.
746unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
747 MachineInstr *MI) const {
748 unsigned RegOp = 0;
749 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
750 MachineOperand &MO = MI->getOperand(i);
751 if (!MO.isRegister() || !MO.isUse())
752 continue;
753 unsigned Reg = MO.getReg();
754 if (Reg == 0 || Reg == li.reg)
755 continue;
756 // FIXME: For now, only remat MI with at most one register operand.
757 assert(!RegOp &&
758 "Can't rematerialize instruction with multiple register operand!");
759 RegOp = MO.getReg();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000760#ifndef NDEBUG
Evan Chengd70dbb52008-02-22 09:24:50 +0000761 break;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000762#endif
Evan Chengd70dbb52008-02-22 09:24:50 +0000763 }
764 return RegOp;
765}
766
767/// isValNoAvailableAt - Return true if the val# of the specified interval
768/// which reaches the given instruction also reaches the specified use index.
769bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
770 unsigned UseIdx) const {
771 unsigned Index = getInstructionIndex(MI);
772 VNInfo *ValNo = li.FindLiveRangeContaining(Index)->valno;
773 LiveInterval::const_iterator UI = li.FindLiveRangeContaining(UseIdx);
774 return UI != li.end() && UI->valno == ValNo;
775}
776
Evan Chengf2fbca62007-11-12 06:35:08 +0000777/// isReMaterializable - Returns true if the definition MI of the specified
778/// val# of the specified interval is re-materializable.
779bool LiveIntervals::isReMaterializable(const LiveInterval &li,
Evan Cheng5ef3a042007-12-06 00:01:56 +0000780 const VNInfo *ValNo, MachineInstr *MI,
781 bool &isLoad) {
Evan Chengf2fbca62007-11-12 06:35:08 +0000782 if (DisableReMat)
783 return false;
784
Evan Cheng20ccded2008-03-15 00:19:36 +0000785 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
Evan Chengd70dbb52008-02-22 09:24:50 +0000786 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000787
788 int FrameIdx = 0;
789 if (tii_->isLoadFromStackSlot(MI, FrameIdx) &&
Evan Cheng249ded32008-02-23 03:38:34 +0000790 mf_->getFrameInfo()->isImmutableObjectIndex(FrameIdx))
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000791 // FIXME: Let target specific isReallyTriviallyReMaterializable determines
792 // this but remember this is not safe to fold into a two-address
793 // instruction.
Evan Cheng249ded32008-02-23 03:38:34 +0000794 // This is a load from fixed stack slot. It can be rematerialized.
Evan Chengdd3465e2008-02-23 01:44:27 +0000795 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000796
Dan Gohman6d69ba82008-07-25 00:02:30 +0000797 // If the target-specific rules don't identify an instruction as
798 // being trivially rematerializable, use some target-independent
799 // rules.
800 if (!MI->getDesc().isRematerializable() ||
801 !tii_->isTriviallyReMaterializable(MI)) {
Dan Gohman4c8f8702008-07-25 15:08:37 +0000802 if (!EnableAggressiveRemat)
803 return false;
Evan Chengd70dbb52008-02-22 09:24:50 +0000804
Dan Gohman6d69ba82008-07-25 00:02:30 +0000805 // If the instruction access memory but the memoperands have been lost,
806 // we can't analyze it.
807 const TargetInstrDesc &TID = MI->getDesc();
808 if ((TID.mayLoad() || TID.mayStore()) && MI->memoperands_empty())
809 return false;
810
811 // Avoid instructions obviously unsafe for remat.
812 if (TID.hasUnmodeledSideEffects() || TID.isNotDuplicable())
813 return false;
814
815 // If the instruction accesses memory and the memory could be non-constant,
816 // assume the instruction is not rematerializable.
817 for (alist<MachineMemOperand>::const_iterator I = MI->memoperands_begin(),
818 E = MI->memoperands_end(); I != E; ++I) {
819 const MachineMemOperand &MMO = *I;
820 if (MMO.isVolatile() || MMO.isStore())
821 return false;
822 const Value *V = MMO.getValue();
823 if (!V)
824 return false;
825 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
826 if (!PSV->isConstant(mf_->getFrameInfo()))
Evan Chengd70dbb52008-02-22 09:24:50 +0000827 return false;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000828 } else if (!aa_->pointsToConstantMemory(V))
829 return false;
830 }
831
832 // If any of the registers accessed are non-constant, conservatively assume
833 // the instruction is not rematerializable.
834 unsigned ImpUse = 0;
835 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
836 const MachineOperand &MO = MI->getOperand(i);
837 if (MO.isReg()) {
838 unsigned Reg = MO.getReg();
839 if (Reg == 0)
840 continue;
841 if (TargetRegisterInfo::isPhysicalRegister(Reg))
842 return false;
843
844 // Only allow one def, and that in the first operand.
845 if (MO.isDef() != (i == 0))
846 return false;
847
848 // Only allow constant-valued registers.
849 bool IsLiveIn = mri_->isLiveIn(Reg);
850 MachineRegisterInfo::def_iterator I = mri_->def_begin(Reg),
851 E = mri_->def_end();
852
853 // For the def, it should be the only def.
854 if (MO.isDef() && (next(I) != E || IsLiveIn))
855 return false;
856
857 if (MO.isUse()) {
858 // Only allow one use other register use, as that's all the
859 // remat mechanisms support currently.
860 if (Reg != li.reg) {
861 if (ImpUse == 0)
862 ImpUse = Reg;
863 else if (Reg != ImpUse)
864 return false;
865 }
866 // For uses, there should be only one associate def.
867 if (I != E && (next(I) != E || IsLiveIn))
868 return false;
869 }
Evan Chengd70dbb52008-02-22 09:24:50 +0000870 }
871 }
Evan Cheng5ef3a042007-12-06 00:01:56 +0000872 }
Evan Chengf2fbca62007-11-12 06:35:08 +0000873
Dan Gohman6d69ba82008-07-25 00:02:30 +0000874 unsigned ImpUse = getReMatImplicitUse(li, MI);
875 if (ImpUse) {
876 const LiveInterval &ImpLi = getInterval(ImpUse);
877 for (MachineRegisterInfo::use_iterator ri = mri_->use_begin(li.reg),
878 re = mri_->use_end(); ri != re; ++ri) {
879 MachineInstr *UseMI = &*ri;
880 unsigned UseIdx = getInstructionIndex(UseMI);
881 if (li.FindLiveRangeContaining(UseIdx)->valno != ValNo)
882 continue;
883 if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
884 return false;
885 }
886 }
887 return true;
Evan Cheng5ef3a042007-12-06 00:01:56 +0000888}
889
890/// isReMaterializable - Returns true if every definition of MI of every
891/// val# of the specified interval is re-materializable.
892bool LiveIntervals::isReMaterializable(const LiveInterval &li, bool &isLoad) {
893 isLoad = false;
894 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
895 i != e; ++i) {
896 const VNInfo *VNI = *i;
897 unsigned DefIdx = VNI->def;
898 if (DefIdx == ~1U)
899 continue; // Dead val#.
900 // Is the def for the val# rematerializable?
901 if (DefIdx == ~0u)
902 return false;
903 MachineInstr *ReMatDefMI = getInstructionFromIndex(DefIdx);
904 bool DefIsLoad = false;
Evan Chengd70dbb52008-02-22 09:24:50 +0000905 if (!ReMatDefMI ||
906 !isReMaterializable(li, VNI, ReMatDefMI, DefIsLoad))
Evan Cheng5ef3a042007-12-06 00:01:56 +0000907 return false;
908 isLoad |= DefIsLoad;
Evan Chengf2fbca62007-11-12 06:35:08 +0000909 }
910 return true;
911}
912
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000913/// FilterFoldedOps - Filter out two-address use operands. Return
914/// true if it finds any issue with the operands that ought to prevent
915/// folding.
916static bool FilterFoldedOps(MachineInstr *MI,
917 SmallVector<unsigned, 2> &Ops,
918 unsigned &MRInfo,
919 SmallVector<unsigned, 2> &FoldOps) {
Chris Lattner749c6f62008-01-07 07:27:27 +0000920 const TargetInstrDesc &TID = MI->getDesc();
Evan Cheng6e141fd2007-12-12 23:12:09 +0000921
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000922 MRInfo = 0;
Evan Chengaee4af62007-12-02 08:30:39 +0000923 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
924 unsigned OpIdx = Ops[i];
Evan Chengd70dbb52008-02-22 09:24:50 +0000925 MachineOperand &MO = MI->getOperand(OpIdx);
Evan Chengaee4af62007-12-02 08:30:39 +0000926 // FIXME: fold subreg use.
Evan Chengd70dbb52008-02-22 09:24:50 +0000927 if (MO.getSubReg())
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000928 return true;
Evan Chengd70dbb52008-02-22 09:24:50 +0000929 if (MO.isDef())
Evan Chengaee4af62007-12-02 08:30:39 +0000930 MRInfo |= (unsigned)VirtRegMap::isMod;
931 else {
932 // Filter out two-address use operand(s).
Evan Chengd70dbb52008-02-22 09:24:50 +0000933 if (!MO.isImplicit() &&
934 TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1) {
Evan Chengaee4af62007-12-02 08:30:39 +0000935 MRInfo = VirtRegMap::isModRef;
936 continue;
937 }
938 MRInfo |= (unsigned)VirtRegMap::isRef;
939 }
940 FoldOps.push_back(OpIdx);
Evan Chenge62f97c2007-12-01 02:07:52 +0000941 }
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000942 return false;
943}
944
945
946/// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
947/// slot / to reg or any rematerialized load into ith operand of specified
948/// MI. If it is successul, MI is updated with the newly created MI and
949/// returns true.
950bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
951 VirtRegMap &vrm, MachineInstr *DefMI,
952 unsigned InstrIdx,
953 SmallVector<unsigned, 2> &Ops,
954 bool isSS, int Slot, unsigned Reg) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000955 // If it is an implicit def instruction, just delete it.
Evan Cheng20ccded2008-03-15 00:19:36 +0000956 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000957 RemoveMachineInstrFromMaps(MI);
958 vrm.RemoveMachineInstrFromMaps(MI);
959 MI->eraseFromParent();
960 ++numFolds;
961 return true;
962 }
963
964 // Filter the list of operand indexes that are to be folded. Abort if
965 // any operand will prevent folding.
966 unsigned MRInfo = 0;
967 SmallVector<unsigned, 2> FoldOps;
968 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
969 return false;
Evan Chenge62f97c2007-12-01 02:07:52 +0000970
Evan Cheng427f4c12008-03-31 23:19:51 +0000971 // The only time it's safe to fold into a two address instruction is when
972 // it's folding reload and spill from / into a spill stack slot.
973 if (DefMI && (MRInfo & VirtRegMap::isMod))
Evan Cheng249ded32008-02-23 03:38:34 +0000974 return false;
975
Evan Chengf2f8c2a2008-02-08 22:05:27 +0000976 MachineInstr *fmi = isSS ? tii_->foldMemoryOperand(*mf_, MI, FoldOps, Slot)
977 : tii_->foldMemoryOperand(*mf_, MI, FoldOps, DefMI);
Evan Chengf2fbca62007-11-12 06:35:08 +0000978 if (fmi) {
Evan Chengd3653122008-02-27 03:04:06 +0000979 // Remember this instruction uses the spill slot.
980 if (isSS) vrm.addSpillSlotUse(Slot, fmi);
981
Evan Chengf2fbca62007-11-12 06:35:08 +0000982 // Attempt to fold the memory reference into the instruction. If
983 // we can do this, we don't need to insert spill code.
Evan Chengf2fbca62007-11-12 06:35:08 +0000984 MachineBasicBlock &MBB = *MI->getParent();
Evan Cheng84802932008-01-10 08:24:38 +0000985 if (isSS && !mf_->getFrameInfo()->isImmutableObjectIndex(Slot))
Evan Chengaee4af62007-12-02 08:30:39 +0000986 vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
Evan Cheng81a03822007-11-17 00:40:40 +0000987 vrm.transferSpillPts(MI, fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +0000988 vrm.transferRestorePts(MI, fmi);
Evan Chengc1f53c72008-03-11 21:34:46 +0000989 vrm.transferEmergencySpills(MI, fmi);
Evan Chengf2fbca62007-11-12 06:35:08 +0000990 mi2iMap_.erase(MI);
Evan Chengcddbb832007-11-30 21:23:43 +0000991 i2miMap_[InstrIdx /InstrSlots::NUM] = fmi;
992 mi2iMap_[fmi] = InstrIdx;
Evan Chengf2fbca62007-11-12 06:35:08 +0000993 MI = MBB.insert(MBB.erase(MI), fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +0000994 ++numFolds;
Evan Chengf2fbca62007-11-12 06:35:08 +0000995 return true;
996 }
997 return false;
998}
999
Evan Cheng018f9b02007-12-05 03:22:34 +00001000/// canFoldMemoryOperand - Returns true if the specified load / store
1001/// folding is possible.
1002bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI,
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001003 SmallVector<unsigned, 2> &Ops,
Evan Cheng3c75ba82008-04-01 21:37:32 +00001004 bool ReMat) const {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001005 // Filter the list of operand indexes that are to be folded. Abort if
1006 // any operand will prevent folding.
1007 unsigned MRInfo = 0;
Evan Cheng018f9b02007-12-05 03:22:34 +00001008 SmallVector<unsigned, 2> FoldOps;
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001009 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1010 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001011
Evan Cheng3c75ba82008-04-01 21:37:32 +00001012 // It's only legal to remat for a use, not a def.
1013 if (ReMat && (MRInfo & VirtRegMap::isMod))
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001014 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001015
Evan Chengd70dbb52008-02-22 09:24:50 +00001016 return tii_->canFoldMemoryOperand(MI, FoldOps);
1017}
1018
Evan Cheng81a03822007-11-17 00:40:40 +00001019bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
1020 SmallPtrSet<MachineBasicBlock*, 4> MBBs;
1021 for (LiveInterval::Ranges::const_iterator
1022 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1023 std::vector<IdxMBBPair>::const_iterator II =
1024 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), I->start);
1025 if (II == Idx2MBBMap.end())
1026 continue;
1027 if (I->end > II->first) // crossing a MBB.
1028 return false;
1029 MBBs.insert(II->second);
1030 if (MBBs.size() > 1)
1031 return false;
1032 }
1033 return true;
1034}
1035
Evan Chengd70dbb52008-02-22 09:24:50 +00001036/// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
1037/// interval on to-be re-materialized operands of MI) with new register.
1038void LiveIntervals::rewriteImplicitOps(const LiveInterval &li,
1039 MachineInstr *MI, unsigned NewVReg,
1040 VirtRegMap &vrm) {
1041 // There is an implicit use. That means one of the other operand is
1042 // being remat'ed and the remat'ed instruction has li.reg as an
1043 // use operand. Make sure we rewrite that as well.
1044 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1045 MachineOperand &MO = MI->getOperand(i);
1046 if (!MO.isRegister())
1047 continue;
1048 unsigned Reg = MO.getReg();
1049 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
1050 continue;
1051 if (!vrm.isReMaterialized(Reg))
1052 continue;
1053 MachineInstr *ReMatMI = vrm.getReMaterializedMI(Reg);
Evan Cheng6130f662008-03-05 00:59:57 +00001054 MachineOperand *UseMO = ReMatMI->findRegisterUseOperand(li.reg);
1055 if (UseMO)
1056 UseMO->setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001057 }
1058}
1059
Evan Chengf2fbca62007-11-12 06:35:08 +00001060/// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
1061/// for addIntervalsForSpills to rewrite uses / defs for the given live range.
Evan Cheng018f9b02007-12-05 03:22:34 +00001062bool LiveIntervals::
Evan Chengd70dbb52008-02-22 09:24:50 +00001063rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
1064 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
Evan Cheng81a03822007-11-17 00:40:40 +00001065 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001066 unsigned Slot, int LdSlot,
1067 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001068 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001069 const TargetRegisterClass* rc,
1070 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001071 const MachineLoopInfo *loopInfo,
Evan Cheng313d4b82008-02-23 00:33:04 +00001072 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001073 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001074 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
1075 MachineBasicBlock *MBB = MI->getParent();
1076 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng018f9b02007-12-05 03:22:34 +00001077 bool CanFold = false;
Evan Chengf2fbca62007-11-12 06:35:08 +00001078 RestartInstruction:
1079 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1080 MachineOperand& mop = MI->getOperand(i);
1081 if (!mop.isRegister())
1082 continue;
1083 unsigned Reg = mop.getReg();
1084 unsigned RegI = Reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001085 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
Evan Chengf2fbca62007-11-12 06:35:08 +00001086 continue;
Evan Chengf2fbca62007-11-12 06:35:08 +00001087 if (Reg != li.reg)
1088 continue;
1089
1090 bool TryFold = !DefIsReMat;
Evan Chengcb3c3302007-11-29 23:02:50 +00001091 bool FoldSS = true; // Default behavior unless it's a remat.
Evan Chengf2fbca62007-11-12 06:35:08 +00001092 int FoldSlot = Slot;
1093 if (DefIsReMat) {
1094 // If this is the rematerializable definition MI itself and
1095 // all of its uses are rematerialized, simply delete it.
Evan Cheng81a03822007-11-17 00:40:40 +00001096 if (MI == ReMatOrigDefMI && CanDelete) {
Evan Chengcddbb832007-11-30 21:23:43 +00001097 DOUT << "\t\t\t\tErasing re-materlizable def: ";
1098 DOUT << MI << '\n';
Evan Chengf2fbca62007-11-12 06:35:08 +00001099 RemoveMachineInstrFromMaps(MI);
Evan Chengcada2452007-11-28 01:28:46 +00001100 vrm.RemoveMachineInstrFromMaps(MI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001101 MI->eraseFromParent();
1102 break;
1103 }
1104
1105 // If def for this use can't be rematerialized, then try folding.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001106 // If def is rematerializable and it's a load, also try folding.
Evan Chengcb3c3302007-11-29 23:02:50 +00001107 TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad));
Evan Chengf2fbca62007-11-12 06:35:08 +00001108 if (isLoad) {
1109 // Try fold loads (from stack slot, constant pool, etc.) into uses.
1110 FoldSS = isLoadSS;
1111 FoldSlot = LdSlot;
1112 }
1113 }
1114
Evan Chengf2fbca62007-11-12 06:35:08 +00001115 // Scan all of the operands of this instruction rewriting operands
1116 // to use NewVReg instead of li.reg as appropriate. We do this for
1117 // two reasons:
1118 //
1119 // 1. If the instr reads the same spilled vreg multiple times, we
1120 // want to reuse the NewVReg.
1121 // 2. If the instr is a two-addr instruction, we are required to
1122 // keep the src/dst regs pinned.
1123 //
1124 // Keep track of whether we replace a use and/or def so that we can
1125 // create the spill interval with the appropriate range.
Evan Chengcddbb832007-11-30 21:23:43 +00001126
Evan Cheng81a03822007-11-17 00:40:40 +00001127 HasUse = mop.isUse();
1128 HasDef = mop.isDef();
Evan Chengaee4af62007-12-02 08:30:39 +00001129 SmallVector<unsigned, 2> Ops;
1130 Ops.push_back(i);
Evan Chengf2fbca62007-11-12 06:35:08 +00001131 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
Evan Chengaee4af62007-12-02 08:30:39 +00001132 const MachineOperand &MOj = MI->getOperand(j);
1133 if (!MOj.isRegister())
Evan Chengf2fbca62007-11-12 06:35:08 +00001134 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001135 unsigned RegJ = MOj.getReg();
Dan Gohman6f0d0242008-02-10 18:45:23 +00001136 if (RegJ == 0 || TargetRegisterInfo::isPhysicalRegister(RegJ))
Evan Chengf2fbca62007-11-12 06:35:08 +00001137 continue;
1138 if (RegJ == RegI) {
Evan Chengaee4af62007-12-02 08:30:39 +00001139 Ops.push_back(j);
1140 HasUse |= MOj.isUse();
1141 HasDef |= MOj.isDef();
Evan Chengf2fbca62007-11-12 06:35:08 +00001142 }
1143 }
1144
Evan Cheng79a796c2008-07-12 01:56:02 +00001145 if (HasUse && !li.liveAt(getUseIndex(index)))
1146 // Must be defined by an implicit def. It should not be spilled. Note,
1147 // this is for correctness reason. e.g.
1148 // 8 %reg1024<def> = IMPLICIT_DEF
1149 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1150 // The live range [12, 14) are not part of the r1024 live interval since
1151 // it's defined by an implicit def. It will not conflicts with live
1152 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001153 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001154 // the INSERT_SUBREG and both target registers that would overlap.
1155 HasUse = false;
1156
Evan Cheng9c3c2212008-06-06 07:54:39 +00001157 // Update stack slot spill weight if we are splitting.
Evan Chengc3417602008-06-21 06:45:54 +00001158 float Weight = getSpillWeight(HasDef, HasUse, loopDepth);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001159 if (!TrySplit)
1160 SSWeight += Weight;
1161
1162 if (!TryFold)
1163 CanFold = false;
1164 else {
Evan Cheng018f9b02007-12-05 03:22:34 +00001165 // Do not fold load / store here if we are splitting. We'll find an
1166 // optimal point to insert a load / store later.
1167 if (!TrySplit) {
1168 if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1169 Ops, FoldSS, FoldSlot, Reg)) {
1170 // Folding the load/store can completely change the instruction in
1171 // unpredictable ways, rescan it from the beginning.
1172 HasUse = false;
1173 HasDef = false;
1174 CanFold = false;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001175 if (isRemoved(MI)) {
1176 SSWeight -= Weight;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001177 break;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001178 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001179 goto RestartInstruction;
1180 }
1181 } else {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001182 // We'll try to fold it later if it's profitable.
Evan Cheng3c75ba82008-04-01 21:37:32 +00001183 CanFold = canFoldMemoryOperand(MI, Ops, DefIsReMat);
Evan Cheng018f9b02007-12-05 03:22:34 +00001184 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001185 }
Evan Chengcddbb832007-11-30 21:23:43 +00001186
1187 // Create a new virtual register for the spill interval.
1188 bool CreatedNewVReg = false;
1189 if (NewVReg == 0) {
Evan Chengd70dbb52008-02-22 09:24:50 +00001190 NewVReg = mri_->createVirtualRegister(rc);
Evan Chengcddbb832007-11-30 21:23:43 +00001191 vrm.grow();
1192 CreatedNewVReg = true;
1193 }
1194 mop.setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001195 if (mop.isImplicit())
1196 rewriteImplicitOps(li, MI, NewVReg, vrm);
Evan Chengcddbb832007-11-30 21:23:43 +00001197
1198 // Reuse NewVReg for other reads.
Evan Chengd70dbb52008-02-22 09:24:50 +00001199 for (unsigned j = 0, e = Ops.size(); j != e; ++j) {
1200 MachineOperand &mopj = MI->getOperand(Ops[j]);
1201 mopj.setReg(NewVReg);
1202 if (mopj.isImplicit())
1203 rewriteImplicitOps(li, MI, NewVReg, vrm);
1204 }
Evan Chengcddbb832007-11-30 21:23:43 +00001205
Evan Cheng81a03822007-11-17 00:40:40 +00001206 if (CreatedNewVReg) {
1207 if (DefIsReMat) {
1208 vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI/*, CanDelete*/);
Evan Chengd70dbb52008-02-22 09:24:50 +00001209 if (ReMatIds[VNI->id] == VirtRegMap::MAX_STACK_SLOT) {
Evan Cheng81a03822007-11-17 00:40:40 +00001210 // Each valnum may have its own remat id.
Evan Chengd70dbb52008-02-22 09:24:50 +00001211 ReMatIds[VNI->id] = vrm.assignVirtReMatId(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001212 } else {
Evan Chengd70dbb52008-02-22 09:24:50 +00001213 vrm.assignVirtReMatId(NewVReg, ReMatIds[VNI->id]);
Evan Cheng81a03822007-11-17 00:40:40 +00001214 }
1215 if (!CanDelete || (HasUse && HasDef)) {
1216 // If this is a two-addr instruction then its use operands are
1217 // rematerializable but its def is not. It should be assigned a
1218 // stack slot.
1219 vrm.assignVirt2StackSlot(NewVReg, Slot);
1220 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001221 } else {
Evan Chengf2fbca62007-11-12 06:35:08 +00001222 vrm.assignVirt2StackSlot(NewVReg, Slot);
1223 }
Evan Chengcb3c3302007-11-29 23:02:50 +00001224 } else if (HasUse && HasDef &&
1225 vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) {
1226 // If this interval hasn't been assigned a stack slot (because earlier
1227 // def is a deleted remat def), do it now.
1228 assert(Slot != VirtRegMap::NO_STACK_SLOT);
1229 vrm.assignVirt2StackSlot(NewVReg, Slot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001230 }
1231
Evan Cheng313d4b82008-02-23 00:33:04 +00001232 // Re-matting an instruction with virtual register use. Add the
1233 // register as an implicit use on the use MI.
1234 if (DefIsReMat && ImpUse)
1235 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1236
Evan Chengf2fbca62007-11-12 06:35:08 +00001237 // create a new register interval for this spill / remat.
1238 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001239 if (CreatedNewVReg) {
1240 NewLIs.push_back(&nI);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001241 MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg));
Evan Cheng81a03822007-11-17 00:40:40 +00001242 if (TrySplit)
1243 vrm.setIsSplitFromReg(NewVReg, li.reg);
1244 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001245
1246 if (HasUse) {
Evan Cheng81a03822007-11-17 00:40:40 +00001247 if (CreatedNewVReg) {
1248 LiveRange LR(getLoadIndex(index), getUseIndex(index)+1,
1249 nI.getNextValue(~0U, 0, VNInfoAllocator));
1250 DOUT << " +" << LR;
1251 nI.addRange(LR);
1252 } else {
1253 // Extend the split live interval to this def / use.
1254 unsigned End = getUseIndex(index)+1;
1255 LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
1256 nI.getValNumInfo(nI.getNumValNums()-1));
1257 DOUT << " +" << LR;
1258 nI.addRange(LR);
1259 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001260 }
1261 if (HasDef) {
1262 LiveRange LR(getDefIndex(index), getStoreIndex(index),
1263 nI.getNextValue(~0U, 0, VNInfoAllocator));
1264 DOUT << " +" << LR;
1265 nI.addRange(LR);
1266 }
Evan Cheng81a03822007-11-17 00:40:40 +00001267
Evan Chengf2fbca62007-11-12 06:35:08 +00001268 DOUT << "\t\t\t\tAdded new interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001269 nI.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001270 DOUT << '\n';
1271 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001272 return CanFold;
Evan Chengf2fbca62007-11-12 06:35:08 +00001273}
Evan Cheng81a03822007-11-17 00:40:40 +00001274bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001275 const VNInfo *VNI,
1276 MachineBasicBlock *MBB, unsigned Idx) const {
Evan Cheng81a03822007-11-17 00:40:40 +00001277 unsigned End = getMBBEndIdx(MBB);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001278 for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
1279 unsigned KillIdx = VNI->kills[j];
1280 if (KillIdx > Idx && KillIdx < End)
1281 return true;
Evan Cheng81a03822007-11-17 00:40:40 +00001282 }
1283 return false;
1284}
1285
Evan Cheng063284c2008-02-21 00:34:19 +00001286/// RewriteInfo - Keep track of machine instrs that will be rewritten
1287/// during spilling.
Dan Gohman844731a2008-05-13 00:00:25 +00001288namespace {
1289 struct RewriteInfo {
1290 unsigned Index;
1291 MachineInstr *MI;
1292 bool HasUse;
1293 bool HasDef;
1294 RewriteInfo(unsigned i, MachineInstr *mi, bool u, bool d)
1295 : Index(i), MI(mi), HasUse(u), HasDef(d) {}
1296 };
Evan Cheng063284c2008-02-21 00:34:19 +00001297
Dan Gohman844731a2008-05-13 00:00:25 +00001298 struct RewriteInfoCompare {
1299 bool operator()(const RewriteInfo &LHS, const RewriteInfo &RHS) const {
1300 return LHS.Index < RHS.Index;
1301 }
1302 };
1303}
Evan Cheng063284c2008-02-21 00:34:19 +00001304
Evan Chengf2fbca62007-11-12 06:35:08 +00001305void LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001306rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
Evan Chengf2fbca62007-11-12 06:35:08 +00001307 LiveInterval::Ranges::const_iterator &I,
Evan Cheng81a03822007-11-17 00:40:40 +00001308 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001309 unsigned Slot, int LdSlot,
1310 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001311 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001312 const TargetRegisterClass* rc,
1313 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001314 const MachineLoopInfo *loopInfo,
Evan Cheng81a03822007-11-17 00:40:40 +00001315 BitVector &SpillMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001316 std::map<unsigned, std::vector<SRInfo> > &SpillIdxes,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001317 BitVector &RestoreMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001318 std::map<unsigned, std::vector<SRInfo> > &RestoreIdxes,
1319 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001320 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001321 bool AllCanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001322 unsigned NewVReg = 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001323 unsigned start = getBaseIndex(I->start);
Evan Chengf2fbca62007-11-12 06:35:08 +00001324 unsigned end = getBaseIndex(I->end-1) + InstrSlots::NUM;
Evan Chengf2fbca62007-11-12 06:35:08 +00001325
Evan Cheng063284c2008-02-21 00:34:19 +00001326 // First collect all the def / use in this live range that will be rewritten.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001327 // Make sure they are sorted according to instruction index.
Evan Cheng063284c2008-02-21 00:34:19 +00001328 std::vector<RewriteInfo> RewriteMIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001329 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1330 re = mri_->reg_end(); ri != re; ) {
Evan Cheng419852c2008-04-03 16:39:43 +00001331 MachineInstr *MI = &*ri;
Evan Cheng063284c2008-02-21 00:34:19 +00001332 MachineOperand &O = ri.getOperand();
1333 ++ri;
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001334 assert(!O.isImplicit() && "Spilling register that's used as implicit use?");
Evan Cheng063284c2008-02-21 00:34:19 +00001335 unsigned index = getInstructionIndex(MI);
1336 if (index < start || index >= end)
1337 continue;
Evan Cheng79a796c2008-07-12 01:56:02 +00001338 if (O.isUse() && !li.liveAt(getUseIndex(index)))
1339 // Must be defined by an implicit def. It should not be spilled. Note,
1340 // this is for correctness reason. e.g.
1341 // 8 %reg1024<def> = IMPLICIT_DEF
1342 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1343 // The live range [12, 14) are not part of the r1024 live interval since
1344 // it's defined by an implicit def. It will not conflicts with live
1345 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001346 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001347 // the INSERT_SUBREG and both target registers that would overlap.
1348 continue;
Evan Cheng063284c2008-02-21 00:34:19 +00001349 RewriteMIs.push_back(RewriteInfo(index, MI, O.isUse(), O.isDef()));
1350 }
1351 std::sort(RewriteMIs.begin(), RewriteMIs.end(), RewriteInfoCompare());
1352
Evan Cheng313d4b82008-02-23 00:33:04 +00001353 unsigned ImpUse = DefIsReMat ? getReMatImplicitUse(li, ReMatDefMI) : 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001354 // Now rewrite the defs and uses.
1355 for (unsigned i = 0, e = RewriteMIs.size(); i != e; ) {
1356 RewriteInfo &rwi = RewriteMIs[i];
1357 ++i;
1358 unsigned index = rwi.Index;
1359 bool MIHasUse = rwi.HasUse;
1360 bool MIHasDef = rwi.HasDef;
1361 MachineInstr *MI = rwi.MI;
1362 // If MI def and/or use the same register multiple times, then there
1363 // are multiple entries.
Evan Cheng313d4b82008-02-23 00:33:04 +00001364 unsigned NumUses = MIHasUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001365 while (i != e && RewriteMIs[i].MI == MI) {
1366 assert(RewriteMIs[i].Index == index);
Evan Cheng313d4b82008-02-23 00:33:04 +00001367 bool isUse = RewriteMIs[i].HasUse;
1368 if (isUse) ++NumUses;
1369 MIHasUse |= isUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001370 MIHasDef |= RewriteMIs[i].HasDef;
1371 ++i;
1372 }
Evan Cheng81a03822007-11-17 00:40:40 +00001373 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng313d4b82008-02-23 00:33:04 +00001374
Evan Cheng0a891ed2008-05-23 23:00:04 +00001375 if (ImpUse && MI != ReMatDefMI) {
Evan Cheng313d4b82008-02-23 00:33:04 +00001376 // Re-matting an instruction with virtual register use. Update the
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001377 // register interval's spill weight to HUGE_VALF to prevent it from
1378 // being spilled.
Evan Cheng313d4b82008-02-23 00:33:04 +00001379 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001380 ImpLi.weight = HUGE_VALF;
Evan Cheng313d4b82008-02-23 00:33:04 +00001381 }
1382
Evan Cheng063284c2008-02-21 00:34:19 +00001383 unsigned MBBId = MBB->getNumber();
Evan Cheng018f9b02007-12-05 03:22:34 +00001384 unsigned ThisVReg = 0;
Evan Cheng70306f82007-12-03 09:58:48 +00001385 if (TrySplit) {
Evan Cheng063284c2008-02-21 00:34:19 +00001386 std::map<unsigned,unsigned>::const_iterator NVI = MBBVRegsMap.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001387 if (NVI != MBBVRegsMap.end()) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001388 ThisVReg = NVI->second;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001389 // One common case:
1390 // x = use
1391 // ...
1392 // ...
1393 // def = ...
1394 // = use
1395 // It's better to start a new interval to avoid artifically
1396 // extend the new interval.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001397 if (MIHasDef && !MIHasUse) {
1398 MBBVRegsMap.erase(MBB->getNumber());
Evan Cheng018f9b02007-12-05 03:22:34 +00001399 ThisVReg = 0;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001400 }
1401 }
Evan Chengcada2452007-11-28 01:28:46 +00001402 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001403
1404 bool IsNew = ThisVReg == 0;
1405 if (IsNew) {
1406 // This ends the previous live interval. If all of its def / use
1407 // can be folded, give it a low spill weight.
1408 if (NewVReg && TrySplit && AllCanFold) {
1409 LiveInterval &nI = getOrCreateInterval(NewVReg);
1410 nI.weight /= 10.0F;
1411 }
1412 AllCanFold = true;
1413 }
1414 NewVReg = ThisVReg;
1415
Evan Cheng81a03822007-11-17 00:40:40 +00001416 bool HasDef = false;
1417 bool HasUse = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001418 bool CanFold = rewriteInstructionForSpills(li, I->valno, TrySplit,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001419 index, end, MI, ReMatOrigDefMI, ReMatDefMI,
1420 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
1421 CanDelete, vrm, rc, ReMatIds, loopInfo, NewVReg,
1422 ImpUse, HasDef, HasUse, MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001423 if (!HasDef && !HasUse)
1424 continue;
1425
Evan Cheng018f9b02007-12-05 03:22:34 +00001426 AllCanFold &= CanFold;
1427
Evan Cheng81a03822007-11-17 00:40:40 +00001428 // Update weight of spill interval.
1429 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng70306f82007-12-03 09:58:48 +00001430 if (!TrySplit) {
Evan Cheng81a03822007-11-17 00:40:40 +00001431 // The spill weight is now infinity as it cannot be spilled again.
1432 nI.weight = HUGE_VALF;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001433 continue;
Evan Cheng81a03822007-11-17 00:40:40 +00001434 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001435
1436 // Keep track of the last def and first use in each MBB.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001437 if (HasDef) {
1438 if (MI != ReMatOrigDefMI || !CanDelete) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001439 bool HasKill = false;
1440 if (!HasUse)
1441 HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, getDefIndex(index));
1442 else {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001443 // If this is a two-address code, then this index starts a new VNInfo.
Evan Cheng3f32d652008-06-04 09:18:41 +00001444 const VNInfo *VNI = li.findDefinedVNInfo(getDefIndex(index));
Evan Cheng0cbb1162007-11-29 01:06:25 +00001445 if (VNI)
1446 HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, getDefIndex(index));
1447 }
Evan Chenge3110d02007-12-01 04:42:39 +00001448 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
1449 SpillIdxes.find(MBBId);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001450 if (!HasKill) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001451 if (SII == SpillIdxes.end()) {
1452 std::vector<SRInfo> S;
1453 S.push_back(SRInfo(index, NewVReg, true));
1454 SpillIdxes.insert(std::make_pair(MBBId, S));
1455 } else if (SII->second.back().vreg != NewVReg) {
1456 SII->second.push_back(SRInfo(index, NewVReg, true));
1457 } else if ((int)index > SII->second.back().index) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001458 // If there is an earlier def and this is a two-address
1459 // instruction, then it's not possible to fold the store (which
1460 // would also fold the load).
Evan Cheng1953d0c2007-11-29 10:12:14 +00001461 SRInfo &Info = SII->second.back();
1462 Info.index = index;
1463 Info.canFold = !HasUse;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001464 }
1465 SpillMBBs.set(MBBId);
Evan Chenge3110d02007-12-01 04:42:39 +00001466 } else if (SII != SpillIdxes.end() &&
1467 SII->second.back().vreg == NewVReg &&
1468 (int)index > SII->second.back().index) {
1469 // There is an earlier def that's not killed (must be two-address).
1470 // The spill is no longer needed.
1471 SII->second.pop_back();
1472 if (SII->second.empty()) {
1473 SpillIdxes.erase(MBBId);
1474 SpillMBBs.reset(MBBId);
1475 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001476 }
1477 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001478 }
1479
1480 if (HasUse) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001481 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001482 SpillIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001483 if (SII != SpillIdxes.end() &&
1484 SII->second.back().vreg == NewVReg &&
1485 (int)index > SII->second.back().index)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001486 // Use(s) following the last def, it's not safe to fold the spill.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001487 SII->second.back().canFold = false;
1488 std::map<unsigned, std::vector<SRInfo> >::iterator RII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001489 RestoreIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001490 if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001491 // If we are splitting live intervals, only fold if it's the first
1492 // use and there isn't another use later in the MBB.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001493 RII->second.back().canFold = false;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001494 else if (IsNew) {
1495 // Only need a reload if there isn't an earlier def / use.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001496 if (RII == RestoreIdxes.end()) {
1497 std::vector<SRInfo> Infos;
1498 Infos.push_back(SRInfo(index, NewVReg, true));
1499 RestoreIdxes.insert(std::make_pair(MBBId, Infos));
1500 } else {
1501 RII->second.push_back(SRInfo(index, NewVReg, true));
1502 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001503 RestoreMBBs.set(MBBId);
1504 }
1505 }
1506
1507 // Update spill weight.
Evan Cheng22f07ff2007-12-11 02:09:15 +00001508 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Chengc3417602008-06-21 06:45:54 +00001509 nI.weight += getSpillWeight(HasDef, HasUse, loopDepth);
Evan Chengf2fbca62007-11-12 06:35:08 +00001510 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001511
1512 if (NewVReg && TrySplit && AllCanFold) {
1513 // If all of its def / use can be folded, give it a low spill weight.
1514 LiveInterval &nI = getOrCreateInterval(NewVReg);
1515 nI.weight /= 10.0F;
1516 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001517}
1518
Evan Cheng1953d0c2007-11-29 10:12:14 +00001519bool LiveIntervals::alsoFoldARestore(int Id, int index, unsigned vr,
1520 BitVector &RestoreMBBs,
1521 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1522 if (!RestoreMBBs[Id])
1523 return false;
1524 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1525 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1526 if (Restores[i].index == index &&
1527 Restores[i].vreg == vr &&
1528 Restores[i].canFold)
1529 return true;
1530 return false;
1531}
1532
1533void LiveIntervals::eraseRestoreInfo(int Id, int index, unsigned vr,
1534 BitVector &RestoreMBBs,
1535 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1536 if (!RestoreMBBs[Id])
1537 return;
1538 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1539 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1540 if (Restores[i].index == index && Restores[i].vreg)
1541 Restores[i].index = -1;
1542}
Evan Cheng81a03822007-11-17 00:40:40 +00001543
Evan Cheng4cce6b42008-04-11 17:53:36 +00001544/// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
1545/// spilled and create empty intervals for their uses.
1546void
1547LiveIntervals::handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
1548 const TargetRegisterClass* rc,
1549 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng419852c2008-04-03 16:39:43 +00001550 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1551 re = mri_->reg_end(); ri != re; ) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001552 MachineOperand &O = ri.getOperand();
Evan Cheng419852c2008-04-03 16:39:43 +00001553 MachineInstr *MI = &*ri;
1554 ++ri;
Evan Cheng4cce6b42008-04-11 17:53:36 +00001555 if (O.isDef()) {
1556 assert(MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF &&
1557 "Register def was not rewritten?");
1558 RemoveMachineInstrFromMaps(MI);
1559 vrm.RemoveMachineInstrFromMaps(MI);
1560 MI->eraseFromParent();
1561 } else {
1562 // This must be an use of an implicit_def so it's not part of the live
1563 // interval. Create a new empty live interval for it.
1564 // FIXME: Can we simply erase some of the instructions? e.g. Stores?
1565 unsigned NewVReg = mri_->createVirtualRegister(rc);
1566 vrm.grow();
1567 vrm.setIsImplicitlyDefined(NewVReg);
1568 NewLIs.push_back(&getOrCreateInterval(NewVReg));
1569 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1570 MachineOperand &MO = MI->getOperand(i);
1571 if (MO.isReg() && MO.getReg() == li.reg)
1572 MO.setReg(NewVReg);
1573 }
1574 }
Evan Cheng419852c2008-04-03 16:39:43 +00001575 }
1576}
1577
Evan Cheng81a03822007-11-17 00:40:40 +00001578
Evan Chengf2fbca62007-11-12 06:35:08 +00001579std::vector<LiveInterval*> LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001580addIntervalsForSpills(const LiveInterval &li,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001581 const MachineLoopInfo *loopInfo, VirtRegMap &vrm,
1582 float &SSWeight) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001583 assert(li.weight != HUGE_VALF &&
1584 "attempt to spill already spilled interval!");
1585
1586 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001587 li.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001588 DOUT << '\n';
1589
Evan Cheng9c3c2212008-06-06 07:54:39 +00001590 // Spill slot weight.
1591 SSWeight = 0.0f;
1592
Evan Cheng81a03822007-11-17 00:40:40 +00001593 // Each bit specify whether it a spill is required in the MBB.
1594 BitVector SpillMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001595 std::map<unsigned, std::vector<SRInfo> > SpillIdxes;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001596 BitVector RestoreMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001597 std::map<unsigned, std::vector<SRInfo> > RestoreIdxes;
1598 std::map<unsigned,unsigned> MBBVRegsMap;
Evan Chengf2fbca62007-11-12 06:35:08 +00001599 std::vector<LiveInterval*> NewLIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001600 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
Evan Chengf2fbca62007-11-12 06:35:08 +00001601
1602 unsigned NumValNums = li.getNumValNums();
1603 SmallVector<MachineInstr*, 4> ReMatDefs;
1604 ReMatDefs.resize(NumValNums, NULL);
1605 SmallVector<MachineInstr*, 4> ReMatOrigDefs;
1606 ReMatOrigDefs.resize(NumValNums, NULL);
1607 SmallVector<int, 4> ReMatIds;
1608 ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
1609 BitVector ReMatDelete(NumValNums);
1610 unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
1611
Evan Cheng81a03822007-11-17 00:40:40 +00001612 // Spilling a split live interval. It cannot be split any further. Also,
1613 // it's also guaranteed to be a single val# / range interval.
1614 if (vrm.getPreSplitReg(li.reg)) {
1615 vrm.setIsSplitFromReg(li.reg, 0);
Evan Chengd120ffd2007-12-05 10:24:35 +00001616 // Unset the split kill marker on the last use.
1617 unsigned KillIdx = vrm.getKillPoint(li.reg);
1618 if (KillIdx) {
1619 MachineInstr *KillMI = getInstructionFromIndex(KillIdx);
1620 assert(KillMI && "Last use disappeared?");
1621 int KillOp = KillMI->findRegisterUseOperandIdx(li.reg, true);
1622 assert(KillOp != -1 && "Last use disappeared?");
Chris Lattnerf7382302007-12-30 21:56:09 +00001623 KillMI->getOperand(KillOp).setIsKill(false);
Evan Chengd120ffd2007-12-05 10:24:35 +00001624 }
Evan Chengadf85902007-12-05 09:51:10 +00001625 vrm.removeKillPoint(li.reg);
Evan Cheng81a03822007-11-17 00:40:40 +00001626 bool DefIsReMat = vrm.isReMaterialized(li.reg);
1627 Slot = vrm.getStackSlot(li.reg);
1628 assert(Slot != VirtRegMap::MAX_STACK_SLOT);
1629 MachineInstr *ReMatDefMI = DefIsReMat ?
1630 vrm.getReMaterializedMI(li.reg) : NULL;
1631 int LdSlot = 0;
1632 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1633 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001634 (DefIsReMat && (ReMatDefMI->getDesc().isSimpleLoad()));
Evan Cheng81a03822007-11-17 00:40:40 +00001635 bool IsFirstRange = true;
1636 for (LiveInterval::Ranges::const_iterator
1637 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1638 // If this is a split live interval with multiple ranges, it means there
1639 // are two-address instructions that re-defined the value. Only the
1640 // first def can be rematerialized!
1641 if (IsFirstRange) {
Evan Chengcb3c3302007-11-29 23:02:50 +00001642 // Note ReMatOrigDefMI has already been deleted.
Evan Cheng81a03822007-11-17 00:40:40 +00001643 rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
1644 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001645 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001646 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001647 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001648 } else {
1649 rewriteInstructionsForSpills(li, false, I, NULL, 0,
1650 Slot, 0, false, false, false,
Evan Chengd70dbb52008-02-22 09:24:50 +00001651 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001652 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001653 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001654 }
1655 IsFirstRange = false;
1656 }
Evan Cheng419852c2008-04-03 16:39:43 +00001657
Evan Cheng9c3c2212008-06-06 07:54:39 +00001658 SSWeight = 0.0f; // Already accounted for when split.
Evan Cheng4cce6b42008-04-11 17:53:36 +00001659 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001660 return NewLIs;
1661 }
1662
1663 bool TrySplit = SplitAtBB && !intervalIsInOneMBB(li);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001664 if (SplitLimit != -1 && (int)numSplits >= SplitLimit)
1665 TrySplit = false;
1666 if (TrySplit)
1667 ++numSplits;
Evan Chengf2fbca62007-11-12 06:35:08 +00001668 bool NeedStackSlot = false;
1669 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1670 i != e; ++i) {
1671 const VNInfo *VNI = *i;
1672 unsigned VN = VNI->id;
1673 unsigned DefIdx = VNI->def;
1674 if (DefIdx == ~1U)
1675 continue; // Dead val#.
1676 // Is the def for the val# rematerializable?
Evan Cheng81a03822007-11-17 00:40:40 +00001677 MachineInstr *ReMatDefMI = (DefIdx == ~0u)
1678 ? 0 : getInstructionFromIndex(DefIdx);
Evan Cheng5ef3a042007-12-06 00:01:56 +00001679 bool dummy;
1680 if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, dummy)) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001681 // Remember how to remat the def of this val#.
Evan Cheng81a03822007-11-17 00:40:40 +00001682 ReMatOrigDefs[VN] = ReMatDefMI;
Dan Gohman2c3f7ae2008-07-17 23:49:46 +00001683 // Original def may be modified so we have to make a copy here.
Evan Cheng1ed99222008-07-19 00:37:25 +00001684 MachineInstr *Clone = mf_->CloneMachineInstr(ReMatDefMI);
1685 ClonedMIs.push_back(Clone);
1686 ReMatDefs[VN] = Clone;
Evan Chengf2fbca62007-11-12 06:35:08 +00001687
1688 bool CanDelete = true;
Evan Chengc3fc7d92007-11-29 09:49:23 +00001689 if (VNI->hasPHIKill) {
1690 // A kill is a phi node, not all of its uses can be rematerialized.
Evan Chengf2fbca62007-11-12 06:35:08 +00001691 // It must not be deleted.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001692 CanDelete = false;
1693 // Need a stack slot if there is any live range where uses cannot be
1694 // rematerialized.
1695 NeedStackSlot = true;
Evan Chengf2fbca62007-11-12 06:35:08 +00001696 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001697 if (CanDelete)
1698 ReMatDelete.set(VN);
1699 } else {
1700 // Need a stack slot if there is any live range where uses cannot be
1701 // rematerialized.
1702 NeedStackSlot = true;
1703 }
1704 }
1705
1706 // One stack slot per live interval.
Evan Cheng81a03822007-11-17 00:40:40 +00001707 if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0)
Evan Chengf2fbca62007-11-12 06:35:08 +00001708 Slot = vrm.assignVirt2StackSlot(li.reg);
1709
1710 // Create new intervals and rewrite defs and uses.
1711 for (LiveInterval::Ranges::const_iterator
1712 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Evan Cheng81a03822007-11-17 00:40:40 +00001713 MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id];
1714 MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id];
1715 bool DefIsReMat = ReMatDefMI != NULL;
Evan Chengf2fbca62007-11-12 06:35:08 +00001716 bool CanDelete = ReMatDelete[I->valno->id];
1717 int LdSlot = 0;
Evan Cheng81a03822007-11-17 00:40:40 +00001718 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001719 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001720 (DefIsReMat && ReMatDefMI->getDesc().isSimpleLoad());
Evan Cheng81a03822007-11-17 00:40:40 +00001721 rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001722 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001723 CanDelete, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001724 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001725 MBBVRegsMap, NewLIs, SSWeight);
Evan Chengf2fbca62007-11-12 06:35:08 +00001726 }
1727
Evan Cheng0cbb1162007-11-29 01:06:25 +00001728 // Insert spills / restores if we are splitting.
Evan Cheng419852c2008-04-03 16:39:43 +00001729 if (!TrySplit) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001730 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001731 return NewLIs;
Evan Cheng419852c2008-04-03 16:39:43 +00001732 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001733
Evan Chengb50bb8c2007-12-05 08:16:32 +00001734 SmallPtrSet<LiveInterval*, 4> AddedKill;
Evan Chengaee4af62007-12-02 08:30:39 +00001735 SmallVector<unsigned, 2> Ops;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001736 if (NeedStackSlot) {
1737 int Id = SpillMBBs.find_first();
1738 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001739 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1740 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001741 std::vector<SRInfo> &spills = SpillIdxes[Id];
1742 for (unsigned i = 0, e = spills.size(); i != e; ++i) {
1743 int index = spills[i].index;
1744 unsigned VReg = spills[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001745 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001746 bool isReMat = vrm.isReMaterialized(VReg);
1747 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001748 bool CanFold = false;
1749 bool FoundUse = false;
1750 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001751 if (spills[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001752 CanFold = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001753 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1754 MachineOperand &MO = MI->getOperand(j);
1755 if (!MO.isRegister() || MO.getReg() != VReg)
1756 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001757
1758 Ops.push_back(j);
1759 if (MO.isDef())
Evan Chengcddbb832007-11-30 21:23:43 +00001760 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001761 if (isReMat ||
1762 (!FoundUse && !alsoFoldARestore(Id, index, VReg,
1763 RestoreMBBs, RestoreIdxes))) {
1764 // MI has two-address uses of the same register. If the use
1765 // isn't the first and only use in the BB, then we can't fold
1766 // it. FIXME: Move this to rewriteInstructionsForSpills.
1767 CanFold = false;
Evan Chengcddbb832007-11-30 21:23:43 +00001768 break;
1769 }
Evan Chengaee4af62007-12-02 08:30:39 +00001770 FoundUse = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001771 }
1772 }
1773 // Fold the store into the def if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001774 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001775 if (CanFold && !Ops.empty()) {
1776 if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
Evan Chengcddbb832007-11-30 21:23:43 +00001777 Folded = true;
Evan Chengf38d14f2007-12-05 09:05:34 +00001778 if (FoundUse > 0) {
Evan Chengaee4af62007-12-02 08:30:39 +00001779 // Also folded uses, do not issue a load.
1780 eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
Evan Chengf38d14f2007-12-05 09:05:34 +00001781 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
1782 }
Evan Cheng597d10d2007-12-04 00:32:23 +00001783 nI.removeRange(getDefIndex(index), getStoreIndex(index));
Evan Chengcddbb832007-11-30 21:23:43 +00001784 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001785 }
1786
Evan Cheng7e073ba2008-04-09 20:57:25 +00001787 // Otherwise tell the spiller to issue a spill.
Evan Chengb50bb8c2007-12-05 08:16:32 +00001788 if (!Folded) {
1789 LiveRange *LR = &nI.ranges[nI.ranges.size()-1];
1790 bool isKill = LR->end == getStoreIndex(index);
Evan Chengb0a6f622008-05-20 08:10:37 +00001791 if (!MI->registerDefIsDead(nI.reg))
1792 // No need to spill a dead def.
1793 vrm.addSpillPoint(VReg, isKill, MI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001794 if (isKill)
1795 AddedKill.insert(&nI);
1796 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001797
1798 // Update spill slot weight.
1799 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00001800 SSWeight += getSpillWeight(true, false, loopDepth);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001801 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001802 Id = SpillMBBs.find_next(Id);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001803 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001804 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001805
Evan Cheng1953d0c2007-11-29 10:12:14 +00001806 int Id = RestoreMBBs.find_first();
1807 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001808 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1809 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
1810
Evan Cheng1953d0c2007-11-29 10:12:14 +00001811 std::vector<SRInfo> &restores = RestoreIdxes[Id];
1812 for (unsigned i = 0, e = restores.size(); i != e; ++i) {
1813 int index = restores[i].index;
1814 if (index == -1)
1815 continue;
1816 unsigned VReg = restores[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001817 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001818 bool isReMat = vrm.isReMaterialized(VReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001819 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001820 bool CanFold = false;
1821 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001822 if (restores[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001823 CanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001824 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1825 MachineOperand &MO = MI->getOperand(j);
1826 if (!MO.isRegister() || MO.getReg() != VReg)
1827 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001828
Evan Cheng0cbb1162007-11-29 01:06:25 +00001829 if (MO.isDef()) {
Evan Chengaee4af62007-12-02 08:30:39 +00001830 // If this restore were to be folded, it would have been folded
1831 // already.
1832 CanFold = false;
Evan Cheng81a03822007-11-17 00:40:40 +00001833 break;
1834 }
Evan Chengaee4af62007-12-02 08:30:39 +00001835 Ops.push_back(j);
Evan Cheng81a03822007-11-17 00:40:40 +00001836 }
1837 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001838
1839 // Fold the load into the use if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001840 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001841 if (CanFold && !Ops.empty()) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001842 if (!isReMat)
Evan Chengaee4af62007-12-02 08:30:39 +00001843 Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg);
1844 else {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001845 MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg);
1846 int LdSlot = 0;
1847 bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1848 // If the rematerializable def is a load, also try to fold it.
Chris Lattner749c6f62008-01-07 07:27:27 +00001849 if (isLoadSS || ReMatDefMI->getDesc().isSimpleLoad())
Evan Chengaee4af62007-12-02 08:30:39 +00001850 Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1851 Ops, isLoadSS, LdSlot, VReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001852 unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI);
1853 if (ImpUse) {
1854 // Re-matting an instruction with virtual register use. Add the
1855 // register as an implicit use on the use MI and update the register
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001856 // interval's spill weight to HUGE_VALF to prevent it from being
1857 // spilled.
Evan Chengd70dbb52008-02-22 09:24:50 +00001858 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001859 ImpLi.weight = HUGE_VALF;
Evan Chengd70dbb52008-02-22 09:24:50 +00001860 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1861 }
Evan Chengaee4af62007-12-02 08:30:39 +00001862 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001863 }
1864 // If folding is not possible / failed, then tell the spiller to issue a
1865 // load / rematerialization for us.
Evan Cheng597d10d2007-12-04 00:32:23 +00001866 if (Folded)
1867 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001868 else
Evan Cheng0cbb1162007-11-29 01:06:25 +00001869 vrm.addRestorePoint(VReg, MI);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001870
1871 // Update spill slot weight.
1872 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00001873 SSWeight += getSpillWeight(false, true, loopDepth);
Evan Cheng81a03822007-11-17 00:40:40 +00001874 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001875 Id = RestoreMBBs.find_next(Id);
Evan Cheng81a03822007-11-17 00:40:40 +00001876 }
1877
Evan Chengb50bb8c2007-12-05 08:16:32 +00001878 // Finalize intervals: add kills, finalize spill weights, and filter out
1879 // dead intervals.
Evan Cheng597d10d2007-12-04 00:32:23 +00001880 std::vector<LiveInterval*> RetNewLIs;
1881 for (unsigned i = 0, e = NewLIs.size(); i != e; ++i) {
1882 LiveInterval *LI = NewLIs[i];
1883 if (!LI->empty()) {
Owen Anderson496bac52008-07-23 19:47:27 +00001884 LI->weight /= InstrSlots::NUM * getApproximateInstructionCount(*LI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001885 if (!AddedKill.count(LI)) {
1886 LiveRange *LR = &LI->ranges[LI->ranges.size()-1];
Evan Chengd120ffd2007-12-05 10:24:35 +00001887 unsigned LastUseIdx = getBaseIndex(LR->end);
1888 MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx);
Evan Cheng6130f662008-03-05 00:59:57 +00001889 int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg, false);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001890 assert(UseIdx != -1);
Evan Chengd70dbb52008-02-22 09:24:50 +00001891 if (LastUse->getOperand(UseIdx).isImplicit() ||
1892 LastUse->getDesc().getOperandConstraint(UseIdx,TOI::TIED_TO) == -1){
Evan Chengb50bb8c2007-12-05 08:16:32 +00001893 LastUse->getOperand(UseIdx).setIsKill();
Evan Chengd120ffd2007-12-05 10:24:35 +00001894 vrm.addKillPoint(LI->reg, LastUseIdx);
Evan Chengadf85902007-12-05 09:51:10 +00001895 }
Evan Chengb50bb8c2007-12-05 08:16:32 +00001896 }
Evan Cheng597d10d2007-12-04 00:32:23 +00001897 RetNewLIs.push_back(LI);
1898 }
1899 }
Evan Cheng81a03822007-11-17 00:40:40 +00001900
Evan Cheng4cce6b42008-04-11 17:53:36 +00001901 handleSpilledImpDefs(li, vrm, rc, RetNewLIs);
Evan Cheng597d10d2007-12-04 00:32:23 +00001902 return RetNewLIs;
Evan Chengf2fbca62007-11-12 06:35:08 +00001903}
Evan Cheng676dd7c2008-03-11 07:19:34 +00001904
1905/// hasAllocatableSuperReg - Return true if the specified physical register has
1906/// any super register that's allocatable.
1907bool LiveIntervals::hasAllocatableSuperReg(unsigned Reg) const {
1908 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS)
1909 if (allocatableRegs_[*AS] && hasInterval(*AS))
1910 return true;
1911 return false;
1912}
1913
1914/// getRepresentativeReg - Find the largest super register of the specified
1915/// physical register.
1916unsigned LiveIntervals::getRepresentativeReg(unsigned Reg) const {
1917 // Find the largest super-register that is allocatable.
1918 unsigned BestReg = Reg;
1919 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS) {
1920 unsigned SuperReg = *AS;
1921 if (!hasAllocatableSuperReg(SuperReg) && hasInterval(SuperReg)) {
1922 BestReg = SuperReg;
1923 break;
1924 }
1925 }
1926 return BestReg;
1927}
1928
1929/// getNumConflictsWithPhysReg - Return the number of uses and defs of the
1930/// specified interval that conflicts with the specified physical register.
1931unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li,
1932 unsigned PhysReg) const {
1933 unsigned NumConflicts = 0;
1934 const LiveInterval &pli = getInterval(getRepresentativeReg(PhysReg));
1935 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
1936 E = mri_->reg_end(); I != E; ++I) {
1937 MachineOperand &O = I.getOperand();
1938 MachineInstr *MI = O.getParent();
1939 unsigned Index = getInstructionIndex(MI);
1940 if (pli.liveAt(Index))
1941 ++NumConflicts;
1942 }
1943 return NumConflicts;
1944}
1945
1946/// spillPhysRegAroundRegDefsUses - Spill the specified physical register
1947/// around all defs and uses of the specified interval.
1948void LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
1949 unsigned PhysReg, VirtRegMap &vrm) {
1950 unsigned SpillReg = getRepresentativeReg(PhysReg);
1951
1952 for (const unsigned *AS = tri_->getAliasSet(PhysReg); *AS; ++AS)
1953 // If there are registers which alias PhysReg, but which are not a
1954 // sub-register of the chosen representative super register. Assert
1955 // since we can't handle it yet.
1956 assert(*AS == SpillReg || !allocatableRegs_[*AS] ||
1957 tri_->isSuperRegister(*AS, SpillReg));
1958
1959 LiveInterval &pli = getInterval(SpillReg);
1960 SmallPtrSet<MachineInstr*, 8> SeenMIs;
1961 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
1962 E = mri_->reg_end(); I != E; ++I) {
1963 MachineOperand &O = I.getOperand();
1964 MachineInstr *MI = O.getParent();
1965 if (SeenMIs.count(MI))
1966 continue;
1967 SeenMIs.insert(MI);
1968 unsigned Index = getInstructionIndex(MI);
1969 if (pli.liveAt(Index)) {
1970 vrm.addEmergencySpill(SpillReg, MI);
1971 pli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
1972 for (const unsigned* AS = tri_->getSubRegisters(SpillReg); *AS; ++AS) {
1973 if (!hasInterval(*AS))
1974 continue;
1975 LiveInterval &spli = getInterval(*AS);
1976 if (spli.liveAt(Index))
1977 spli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
1978 }
1979 }
1980 }
1981}
Owen Andersonc4dc1322008-06-05 17:15:43 +00001982
1983LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
1984 MachineInstr* startInst) {
1985 LiveInterval& Interval = getOrCreateInterval(reg);
1986 VNInfo* VN = Interval.getNextValue(
1987 getInstructionIndex(startInst) + InstrSlots::DEF,
1988 startInst, getVNInfoAllocator());
1989 VN->hasPHIKill = true;
1990 VN->kills.push_back(getMBBEndIdx(startInst->getParent()));
1991 LiveRange LR(getInstructionIndex(startInst) + InstrSlots::DEF,
1992 getMBBEndIdx(startInst->getParent()) + 1, VN);
1993 Interval.addRange(LR);
1994
1995 return LR;
1996}