blob: f265e639786c13569ca13674655540bdc5fc00db [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"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000022#include "llvm/CodeGen/LiveVariables.h"
23#include "llvm/CodeGen/MachineFrameInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000024#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000025#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000026#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000027#include "llvm/CodeGen/Passes.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000028#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000029#include "llvm/Target/TargetInstrInfo.h"
30#include "llvm/Target/TargetMachine.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000031#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/ADT/Statistic.h"
34#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000035#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000036#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000037using namespace llvm;
38
Dan Gohman844731a2008-05-13 00:00:25 +000039// Hidden options for help debugging.
40static cl::opt<bool> DisableReMat("disable-rematerialization",
41 cl::init(false), cl::Hidden);
Evan Cheng81a03822007-11-17 00:40:40 +000042
Dan Gohman844731a2008-05-13 00:00:25 +000043static cl::opt<bool> SplitAtBB("split-intervals-at-bb",
44 cl::init(true), cl::Hidden);
45static cl::opt<int> SplitLimit("split-limit",
46 cl::init(-1), cl::Hidden);
Owen Anderson35578012008-06-16 07:10:49 +000047static cl::opt<bool> EmptyBBIndex("empty-bb-index",
48 cl::init(false), cl::Hidden);
Evan Chengbc165e42007-08-16 07:24:22 +000049
Chris Lattnercd3245a2006-12-19 22:41:21 +000050STATISTIC(numIntervals, "Number of original intervals");
51STATISTIC(numIntervalsAfter, "Number of intervals after coalescing");
Evan Cheng0cbb1162007-11-29 01:06:25 +000052STATISTIC(numFolds , "Number of loads/stores folded into instructions");
53STATISTIC(numSplits , "Number of intervals split");
Chris Lattnercd3245a2006-12-19 22:41:21 +000054
Devang Patel19974732007-05-03 01:11:54 +000055char LiveIntervals::ID = 0;
Dan Gohman844731a2008-05-13 00:00:25 +000056static RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000057
Chris Lattnerf7da2c72006-08-24 22:43:55 +000058void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
David Greene25133302007-06-08 17:18:56 +000059 AU.addPreserved<LiveVariables>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000060 AU.addRequired<LiveVariables>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000061 AU.addPreservedID(MachineLoopInfoID);
62 AU.addPreservedID(MachineDominatorsID);
Owen Andersonfcc63502008-05-29 18:35:21 +000063 AU.addPreservedID(PHIEliminationID);
64 AU.addRequiredID(PHIEliminationID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000065 AU.addRequiredID(TwoAddressInstructionPassID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000066 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000067}
68
Chris Lattnerf7da2c72006-08-24 22:43:55 +000069void LiveIntervals::releaseMemory() {
Evan Cheng3f32d652008-06-04 09:18:41 +000070 MBB2IdxMap.clear();
Evan Cheng4ca980e2007-10-17 02:10:22 +000071 Idx2MBBMap.clear();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000072 mi2iMap_.clear();
73 i2miMap_.clear();
74 r2iMap_.clear();
Evan Chengdd199d22007-09-06 01:07:24 +000075 // Release VNInfo memroy regions after all VNInfo objects are dtor'd.
76 VNInfoAllocator.Reset();
Evan Cheng549f27d32007-08-13 23:45:17 +000077 for (unsigned i = 0, e = ClonedMIs.size(); i != e; ++i)
78 delete ClonedMIs[i];
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000079}
80
Owen Anderson80b3ce62008-05-28 20:54:50 +000081void LiveIntervals::computeNumbering() {
82 Index2MiMap OldI2MI = i2miMap_;
83
84 Idx2MBBMap.clear();
85 MBB2IdxMap.clear();
86 mi2iMap_.clear();
87 i2miMap_.clear();
88
Chris Lattner428b92e2006-09-15 03:57:23 +000089 // Number MachineInstrs and MachineBasicBlocks.
90 // Initialize MBB indexes to a sentinal.
Evan Cheng549f27d32007-08-13 23:45:17 +000091 MBB2IdxMap.resize(mf_->getNumBlockIDs(), std::make_pair(~0U,~0U));
Chris Lattner428b92e2006-09-15 03:57:23 +000092
93 unsigned MIIndex = 0;
94 for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
95 MBB != E; ++MBB) {
Evan Cheng549f27d32007-08-13 23:45:17 +000096 unsigned StartIdx = MIIndex;
Evan Cheng0c9f92e2007-02-13 01:30:55 +000097
Chris Lattner428b92e2006-09-15 03:57:23 +000098 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
99 I != E; ++I) {
100 bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000101 assert(inserted && "multiple MachineInstr -> index mappings");
Chris Lattner428b92e2006-09-15 03:57:23 +0000102 i2miMap_.push_back(I);
103 MIIndex += InstrSlots::NUM;
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000104 }
Owen Anderson35578012008-06-16 07:10:49 +0000105
Evan Cheng549f27d32007-08-13 23:45:17 +0000106 // Set the MBB2IdxMap entry for this MBB.
Owen Anderson35578012008-06-16 07:10:49 +0000107 if (!EmptyBBIndex) {
108 MBB2IdxMap[MBB->getNumber()] = (StartIdx == MIIndex)
109 ? std::make_pair(StartIdx, StartIdx) // Empty MBB
110 : std::make_pair(StartIdx, MIIndex - 1);
111 Idx2MBBMap.push_back(std::make_pair(StartIdx, MBB));
112 } else {
113 if (StartIdx == MIIndex) {
114 // Empty MBB
115 MIIndex += InstrSlots::NUM;
116 i2miMap_.push_back(0);
117 }
118
119 MBB2IdxMap[MBB->getNumber()] = std::make_pair(StartIdx, MIIndex - 1);
120 Idx2MBBMap.push_back(std::make_pair(StartIdx, MBB));
121 }
Chris Lattner428b92e2006-09-15 03:57:23 +0000122 }
Evan Cheng4ca980e2007-10-17 02:10:22 +0000123 std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
Owen Anderson80b3ce62008-05-28 20:54:50 +0000124
125 if (!OldI2MI.empty())
126 for (iterator I = begin(), E = end(); I != E; ++I)
127 for (LiveInterval::iterator LI = I->second.begin(), LE = I->second.end();
128 LI != LE; ++LI) {
Owen Anderson4b5b2092008-05-29 18:15:49 +0000129
Owen Anderson7eec0c22008-05-29 23:01:22 +0000130 // Remap the start index of the live range to the corresponding new
131 // number, or our best guess at what it _should_ correspond to if the
132 // original instruction has been erased. This is either the following
133 // instruction or its predecessor.
134 unsigned offset = LI->start % InstrSlots::NUM;
135 if (OldI2MI[LI->start / InstrSlots::NUM])
136 LI->start = mi2iMap_[OldI2MI[LI->start / InstrSlots::NUM]] + offset;
137 else {
138 unsigned i = 0;
139 MachineInstr* newInstr = 0;
140 do {
141 newInstr = OldI2MI[LI->start / InstrSlots::NUM + i];
142 i++;
143 } while (!newInstr);
144
Owen Andersone3abb0a2008-06-02 17:36:36 +0000145 if (mi2iMap_[newInstr] ==
146 MBB2IdxMap[newInstr->getParent()->getNumber()].first)
Owen Anderson7eec0c22008-05-29 23:01:22 +0000147 LI->start = mi2iMap_[newInstr];
Owen Andersone3abb0a2008-06-02 17:36:36 +0000148 else
149 LI->start = mi2iMap_[newInstr] - InstrSlots::NUM + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000150 }
151
152 // Remap the ending index in the same way that we remapped the start,
153 // except for the final step where we always map to the immediately
154 // following instruction.
Owen Anderson4b5b2092008-05-29 18:15:49 +0000155 if (LI->end / InstrSlots::NUM < OldI2MI.size()) {
Owen Anderson4b5b2092008-05-29 18:15:49 +0000156 offset = LI->end % InstrSlots::NUM;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000157 if (OldI2MI[LI->end / InstrSlots::NUM])
158 LI->end = mi2iMap_[OldI2MI[LI->end / InstrSlots::NUM]] + offset;
159 else {
160 unsigned i = 0;
161 MachineInstr* newInstr = 0;
162 do {
163 newInstr = OldI2MI[LI->end / InstrSlots::NUM + i];
164 i++;
165 } while (!newInstr);
166
167 LI->end = mi2iMap_[newInstr];
168 }
Owen Anderson4b5b2092008-05-29 18:15:49 +0000169 } else {
170 LI->end = i2miMap_.size() * InstrSlots::NUM;
171 }
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 Anderson4b5b2092008-05-29 18:15:49 +0000176 offset = vni->def % InstrSlots::NUM;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000177 if (OldI2MI[vni->def / InstrSlots::NUM])
178 vni->def = mi2iMap_[OldI2MI[vni->def / InstrSlots::NUM]] + offset;
179 else {
180 unsigned i = 0;
181 MachineInstr* newInstr = 0;
182 do {
183 newInstr = OldI2MI[vni->def / InstrSlots::NUM + i];
184 i++;
185 } while (!newInstr);
186
Owen Andersone3abb0a2008-06-02 17:36:36 +0000187 if (mi2iMap_[newInstr] ==
188 MBB2IdxMap[newInstr->getParent()->getNumber()].first)
Owen Anderson7eec0c22008-05-29 23:01:22 +0000189 vni->def = mi2iMap_[newInstr];
Owen Andersone3abb0a2008-06-02 17:36:36 +0000190 else
191 vni->def = mi2iMap_[newInstr] - InstrSlots::NUM + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000192 }
Owen Anderson745825f42008-05-28 22:40:08 +0000193
Owen Anderson7eec0c22008-05-29 23:01:22 +0000194 // Remap the VNInfo kill indices, which works the same as
195 // the end indices above.
Owen Anderson4b5b2092008-05-29 18:15:49 +0000196 for (size_t i = 0; i < vni->kills.size(); ++i) {
197 offset = vni->kills[i] % InstrSlots::NUM;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000198 if (OldI2MI[vni->kills[i] / InstrSlots::NUM])
199 vni->kills[i] = mi2iMap_[OldI2MI[vni->kills[i] / InstrSlots::NUM]] +
200 offset;
201 else {
202 unsigned e = 0;
203 MachineInstr* newInstr = 0;
204 do {
205 newInstr = OldI2MI[vni->kills[i] / InstrSlots::NUM + e];
206 e++;
207 } while (!newInstr);
208
209 vni->kills[i] = mi2iMap_[newInstr];
210 }
Owen Anderson4b5b2092008-05-29 18:15:49 +0000211 }
Owen Anderson80b3ce62008-05-28 20:54:50 +0000212 }
213}
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000214
Owen Anderson80b3ce62008-05-28 20:54:50 +0000215/// runOnMachineFunction - Register allocate the whole function
216///
217bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
218 mf_ = &fn;
219 mri_ = &mf_->getRegInfo();
220 tm_ = &fn.getTarget();
221 tri_ = tm_->getRegisterInfo();
222 tii_ = tm_->getInstrInfo();
223 lv_ = &getAnalysis<LiveVariables>();
224 allocatableRegs_ = tri_->getAllocatableSet(fn);
225
226 computeNumbering();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000227 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000228
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000229 numIntervals += getNumIntervals();
230
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000231 DOUT << "********** INTERVALS **********\n";
232 for (iterator I = begin(), E = end(); I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000233 I->second.print(DOUT, tri_);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000234 DOUT << "\n";
235 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000236
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000237 numIntervalsAfter += getNumIntervals();
Chris Lattner70ca3582004-09-30 15:59:17 +0000238 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000239 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000240}
241
Chris Lattner70ca3582004-09-30 15:59:17 +0000242/// print - Implement the dump method.
Reid Spencerce9653c2004-12-07 04:03:45 +0000243void LiveIntervals::print(std::ostream &O, const Module* ) const {
Chris Lattner70ca3582004-09-30 15:59:17 +0000244 O << "********** INTERVALS **********\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000245 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Evan Cheng3f32d652008-06-04 09:18:41 +0000246 I->second.print(O, tri_);
247 O << "\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000248 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000249
250 O << "********** MACHINEINSTRS **********\n";
251 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
252 mbbi != mbbe; ++mbbi) {
253 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
254 for (MachineBasicBlock::iterator mii = mbbi->begin(),
255 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner477e4552004-09-30 16:10:45 +0000256 O << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner70ca3582004-09-30 15:59:17 +0000257 }
258 }
259}
260
Evan Chengc92da382007-11-03 07:20:12 +0000261/// conflictsWithPhysRegDef - Returns true if the specified register
262/// is defined during the duration of the specified interval.
263bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
264 VirtRegMap &vrm, unsigned reg) {
265 for (LiveInterval::Ranges::const_iterator
266 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
267 for (unsigned index = getBaseIndex(I->start),
268 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
269 index += InstrSlots::NUM) {
270 // skip deleted instructions
271 while (index != end && !getInstructionFromIndex(index))
272 index += InstrSlots::NUM;
273 if (index == end) break;
274
275 MachineInstr *MI = getInstructionFromIndex(index);
Evan Cheng5d446262007-11-15 08:13:29 +0000276 unsigned SrcReg, DstReg;
277 if (tii_->isMoveInstr(*MI, SrcReg, DstReg))
278 if (SrcReg == li.reg || DstReg == li.reg)
279 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000280 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
281 MachineOperand& mop = MI->getOperand(i);
Evan Cheng5d446262007-11-15 08:13:29 +0000282 if (!mop.isRegister())
Evan Chengc92da382007-11-03 07:20:12 +0000283 continue;
284 unsigned PhysReg = mop.getReg();
Evan Cheng5d446262007-11-15 08:13:29 +0000285 if (PhysReg == 0 || PhysReg == li.reg)
Evan Chengc92da382007-11-03 07:20:12 +0000286 continue;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000287 if (TargetRegisterInfo::isVirtualRegister(PhysReg)) {
Evan Cheng5d446262007-11-15 08:13:29 +0000288 if (!vrm.hasPhys(PhysReg))
289 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000290 PhysReg = vrm.getPhys(PhysReg);
Evan Cheng5d446262007-11-15 08:13:29 +0000291 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000292 if (PhysReg && tri_->regsOverlap(PhysReg, reg))
Evan Chengc92da382007-11-03 07:20:12 +0000293 return true;
294 }
295 }
296 }
297
298 return false;
299}
300
Evan Cheng549f27d32007-08-13 23:45:17 +0000301void LiveIntervals::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000302 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000303 cerr << tri_->getName(reg);
Evan Cheng549f27d32007-08-13 23:45:17 +0000304 else
305 cerr << "%reg" << reg;
306}
307
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000308void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000309 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000310 unsigned MIIdx,
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.
Alkis Evlogimenosd19e2902004-08-31 17:39:15 +0000367 LiveRange NewLR(defIndex,
368 getInstructionIndex(&mbb->back()) + InstrSlots::NUM,
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000369 ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000370 DOUT << " +" << NewLR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000371 interval.addRange(NewLR);
372
373 // Iterate over all of the blocks that the variable is completely
374 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
375 // live interval.
376 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
377 if (vi.AliveBlocks[i]) {
Chris Lattner428b92e2006-09-15 03:57:23 +0000378 MachineBasicBlock *MBB = mf_->getBlockNumbered(i);
379 if (!MBB->empty()) {
380 LiveRange LR(getMBBStartIdx(i),
381 getInstructionIndex(&MBB->back()) + InstrSlots::NUM,
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000382 ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000383 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000384 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000385 }
386 }
387 }
388
389 // Finally, this virtual register is live from the start of any killing
390 // block to the 'use' slot of the killing instruction.
391 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
392 MachineInstr *Kill = vi.Kills[i];
Evan Cheng8df78602007-08-08 03:00:28 +0000393 unsigned killIdx = getUseIndex(getInstructionIndex(Kill))+1;
Chris Lattner428b92e2006-09-15 03:57:23 +0000394 LiveRange LR(getMBBStartIdx(Kill->getParent()),
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000395 killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000396 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000397 interval.addKill(ValNo, killIdx);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000398 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000399 }
400
401 } else {
402 // If this is the second time we see a virtual register definition, it
403 // must be due to phi elimination or two addr elimination. If this is
Evan Chengbf105c82006-11-03 03:04:46 +0000404 // the result of two address elimination, then the vreg is one of the
405 // def-and-use register operand.
Evan Cheng32dfbea2007-10-12 08:50:34 +0000406 if (mi->isRegReDefinedByTwoAddr(interval.reg)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000407 // If this is a two-address definition, then we have already processed
408 // the live range. The only problem is that we didn't realize there
409 // are actually two values in the live interval. Because of this we
410 // need to take the LiveRegion that defines this register and split it
411 // into two values.
Evan Chenga07cec92008-01-10 08:22:10 +0000412 assert(interval.containsOneValue());
413 unsigned DefIndex = getDefIndex(interval.getValNumInfo(0)->def);
Chris Lattner6b128bd2006-09-03 08:07:11 +0000414 unsigned RedefIndex = getDefIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000415
Evan Cheng4f8ff162007-08-11 00:59:19 +0000416 const LiveRange *OldLR = interval.getLiveRangeContaining(RedefIndex-1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000417 VNInfo *OldValNo = OldLR->valno;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000418
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000419 // Delete the initial value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000420 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000421 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000422
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000423 // Two-address vregs should always only be redefined once. This means
424 // that at this point, there should be exactly one value number in it.
425 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
426
Chris Lattner91725b72006-08-31 05:54:43 +0000427 // The new value number (#1) is defined by the instruction we claimed
428 // defined value #0.
Evan Chengc8d044e2008-02-15 18:24:29 +0000429 VNInfo *ValNo = interval.getNextValue(OldValNo->def, OldValNo->copy,
430 VNInfoAllocator);
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000431
Chris Lattner91725b72006-08-31 05:54:43 +0000432 // Value#0 is now defined by the 2-addr instruction.
Evan Chengc8d044e2008-02-15 18:24:29 +0000433 OldValNo->def = RedefIndex;
434 OldValNo->copy = 0;
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000435
436 // Add the new live interval which replaces the range for the input copy.
437 LiveRange LR(DefIndex, RedefIndex, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000438 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000439 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000440 interval.addKill(ValNo, RedefIndex);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000441
442 // If this redefinition is dead, we need to add a dummy unit live
443 // range covering the def slot.
Evan Cheng6130f662008-03-05 00:59:57 +0000444 if (mi->registerDefIsDead(interval.reg, tri_))
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000445 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, OldValNo));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000446
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000447 DOUT << " RESULT: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000448 interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000449
450 } else {
451 // Otherwise, this must be because of phi elimination. If this is the
452 // first redefinition of the vreg that we have seen, go back and change
453 // the live range in the PHI block to be a different value number.
454 if (interval.containsOneValue()) {
455 assert(vi.Kills.size() == 1 &&
456 "PHI elimination vreg should have one kill, the PHI itself!");
457
458 // Remove the old range that we now know has an incorrect number.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000459 VNInfo *VNI = interval.getValNumInfo(0);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000460 MachineInstr *Killer = vi.Kills[0];
Chris Lattner428b92e2006-09-15 03:57:23 +0000461 unsigned Start = getMBBStartIdx(Killer->getParent());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000462 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000463 DOUT << " Removing [" << Start << "," << End << "] from: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000464 interval.print(DOUT, tri_); DOUT << "\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000465 interval.removeRange(Start, End);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000466 VNI->hasPHIKill = true;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000467 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000468
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000469 // Replace the interval with one of a NEW value number. Note that this
470 // value number isn't actually defined by an instruction, weird huh? :)
Evan Chengf3bb2e62007-09-05 21:46:51 +0000471 LiveRange LR(Start, End, interval.getNextValue(~0, 0, VNInfoAllocator));
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000472 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000473 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000474 interval.addKill(LR.valno, End);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000475 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000476 }
477
478 // In the case of PHI elimination, each variable definition is only
479 // live until the end of the block. We've already taken care of the
480 // rest of the live range.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000481 unsigned defIndex = getDefIndex(MIIdx);
Chris Lattner91725b72006-08-31 05:54:43 +0000482
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000483 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000484 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000485 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000486 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000487 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000488 tii_->isMoveInstr(*mi, SrcReg, DstReg))
489 CopyMI = mi;
490 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Chris Lattner91725b72006-08-31 05:54:43 +0000491
Evan Cheng24c2e5c2007-08-08 07:03:29 +0000492 unsigned killIndex = getInstructionIndex(&mbb->back()) + InstrSlots::NUM;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000493 LiveRange LR(defIndex, killIndex, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000494 interval.addRange(LR);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000495 interval.addKill(ValNo, killIndex);
496 ValNo->hasPHIKill = true;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000497 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000498 }
499 }
500
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000501 DOUT << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000502}
503
Chris Lattnerf35fef72004-07-23 21:24:19 +0000504void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000505 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000506 unsigned MIIdx,
Chris Lattner91725b72006-08-31 05:54:43 +0000507 LiveInterval &interval,
Evan Chengc8d044e2008-02-15 18:24:29 +0000508 MachineInstr *CopyMI) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000509 // A physical register cannot be live across basic block, so its
510 // lifetime must end somewhere in its defining basic block.
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000511 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000512
Chris Lattner6b128bd2006-09-03 08:07:11 +0000513 unsigned baseIndex = MIIdx;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000514 unsigned start = getDefIndex(baseIndex);
515 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000516
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000517 // If it is not used after definition, it is considered dead at
518 // the instruction defining it. Hence its interval is:
519 // [defSlot(def), defSlot(def)+1)
Evan Cheng6130f662008-03-05 00:59:57 +0000520 if (mi->registerDefIsDead(interval.reg, tri_)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000521 DOUT << " dead";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000522 end = getDefIndex(start) + 1;
523 goto exit;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000524 }
525
526 // If it is not dead on definition, it must be killed by a
527 // subsequent instruction. Hence its interval is:
528 // [defSlot(def), useSlot(kill)+1)
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000529 while (++mi != MBB->end()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000530 baseIndex += InstrSlots::NUM;
Evan Cheng6130f662008-03-05 00:59:57 +0000531 if (mi->killsRegister(interval.reg, tri_)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000532 DOUT << " killed";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000533 end = getUseIndex(baseIndex) + 1;
534 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000535 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Cheng9a1956a2006-11-15 20:54:11 +0000536 // Another instruction redefines the register before it is ever read.
537 // Then the register is essentially dead at the instruction that defines
538 // it. Hence its interval is:
539 // [defSlot(def), defSlot(def)+1)
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000540 DOUT << " dead";
Evan Cheng9a1956a2006-11-15 20:54:11 +0000541 end = getDefIndex(start) + 1;
542 goto exit;
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000543 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000544 }
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000545
546 // The only case we should have a dead physreg here without a killing or
547 // instruction where we know it's dead is if it is live-in to the function
548 // and never used.
Evan Chengc8d044e2008-02-15 18:24:29 +0000549 assert(!CopyMI && "physreg was not killed in defining block!");
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000550 end = getDefIndex(start) + 1; // It's dead.
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000551
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000552exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000553 assert(start < end && "did not find end of interval?");
Chris Lattnerf768bba2005-03-09 23:05:19 +0000554
Evan Cheng24a3cc42007-04-25 07:30:23 +0000555 // Already exists? Extend old live interval.
556 LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000557 VNInfo *ValNo = (OldLR != interval.end())
Evan Chengc8d044e2008-02-15 18:24:29 +0000558 ? OldLR->valno : interval.getNextValue(start, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000559 LiveRange LR(start, end, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000560 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000561 interval.addKill(LR.valno, end);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000562 DOUT << " +" << LR << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000563}
564
Chris Lattnerf35fef72004-07-23 21:24:19 +0000565void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
566 MachineBasicBlock::iterator MI,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000567 unsigned MIIdx,
Chris Lattnerf35fef72004-07-23 21:24:19 +0000568 unsigned reg) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000569 if (TargetRegisterInfo::isVirtualRegister(reg))
Chris Lattner6b128bd2006-09-03 08:07:11 +0000570 handleVirtualRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg));
Alkis Evlogimenos53278012004-08-26 22:22:38 +0000571 else if (allocatableRegs_[reg]) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000572 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000573 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000574 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000575 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000576 tii_->isMoveInstr(*MI, SrcReg, DstReg))
577 CopyMI = MI;
578 handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(reg), CopyMI);
Evan Cheng24a3cc42007-04-25 07:30:23 +0000579 // Def of a register also defines its sub-registers.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000580 for (const unsigned* AS = tri_->getSubRegisters(reg); *AS; ++AS)
Evan Cheng6130f662008-03-05 00:59:57 +0000581 // If MI also modifies the sub-register explicitly, avoid processing it
582 // more than once. Do not pass in TRI here so it checks for exact match.
583 if (!MI->modifiesRegister(*AS))
Evan Cheng24a3cc42007-04-25 07:30:23 +0000584 handlePhysicalRegisterDef(MBB, MI, MIIdx, getOrCreateInterval(*AS), 0);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000585 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000586}
587
Evan Chengb371f452007-02-19 21:49:54 +0000588void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000589 unsigned MIIdx,
Evan Cheng24a3cc42007-04-25 07:30:23 +0000590 LiveInterval &interval, bool isAlias) {
Evan Chengb371f452007-02-19 21:49:54 +0000591 DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg));
592
593 // Look for kills, if it reaches a def before it's killed, then it shouldn't
594 // be considered a livein.
595 MachineBasicBlock::iterator mi = MBB->begin();
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000596 unsigned baseIndex = MIIdx;
597 unsigned start = baseIndex;
Evan Chengb371f452007-02-19 21:49:54 +0000598 unsigned end = start;
599 while (mi != MBB->end()) {
Evan Cheng6130f662008-03-05 00:59:57 +0000600 if (mi->killsRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000601 DOUT << " killed";
602 end = getUseIndex(baseIndex) + 1;
603 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000604 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000605 // Another instruction redefines the register before it is ever read.
606 // Then the register is essentially dead at the instruction that defines
607 // it. Hence its interval is:
608 // [defSlot(def), defSlot(def)+1)
609 DOUT << " dead";
610 end = getDefIndex(start) + 1;
611 goto exit;
612 }
613
614 baseIndex += InstrSlots::NUM;
615 ++mi;
616 }
617
618exit:
Evan Cheng75611fb2007-06-27 01:16:36 +0000619 // Live-in register might not be used at all.
620 if (end == MIIdx) {
Evan Cheng292da942007-06-27 18:47:28 +0000621 if (isAlias) {
622 DOUT << " dead";
Evan Cheng75611fb2007-06-27 01:16:36 +0000623 end = getDefIndex(MIIdx) + 1;
Evan Cheng292da942007-06-27 18:47:28 +0000624 } else {
625 DOUT << " live through";
626 end = baseIndex;
627 }
Evan Cheng24a3cc42007-04-25 07:30:23 +0000628 }
629
Evan Chengf3bb2e62007-09-05 21:46:51 +0000630 LiveRange LR(start, end, interval.getNextValue(start, 0, VNInfoAllocator));
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000631 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000632 interval.addKill(LR.valno, end);
Evan Cheng24c2e5c2007-08-08 07:03:29 +0000633 DOUT << " +" << LR << '\n';
Evan Chengb371f452007-02-19 21:49:54 +0000634}
635
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000636/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000637/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000638/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000639/// which a variable is live
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000640void LiveIntervals::computeIntervals() {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000641 DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
642 << "********** Function: "
643 << ((Value*)mf_->getFunction())->getName() << '\n';
Chris Lattner6b128bd2006-09-03 08:07:11 +0000644 // Track the index of the current machine instr.
645 unsigned MIIndex = 0;
Chris Lattner428b92e2006-09-15 03:57:23 +0000646 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
647 MBBI != E; ++MBBI) {
648 MachineBasicBlock *MBB = MBBI;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000649 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000650
Chris Lattner428b92e2006-09-15 03:57:23 +0000651 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000652
Dan Gohmancb406c22007-10-03 19:26:29 +0000653 // Create intervals for live-ins to this BB first.
654 for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
655 LE = MBB->livein_end(); LI != LE; ++LI) {
656 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
657 // Multiple live-ins can alias the same register.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000658 for (const unsigned* AS = tri_->getSubRegisters(*LI); *AS; ++AS)
Dan Gohmancb406c22007-10-03 19:26:29 +0000659 if (!hasInterval(*AS))
660 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
661 true);
Chris Lattnerdffb2e82006-09-04 18:27:40 +0000662 }
663
Chris Lattner428b92e2006-09-15 03:57:23 +0000664 for (; MI != miEnd; ++MI) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000665 DOUT << MIIndex << "\t" << *MI;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000666
Evan Cheng438f7bc2006-11-10 08:43:01 +0000667 // Handle defs.
Chris Lattner428b92e2006-09-15 03:57:23 +0000668 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
669 MachineOperand &MO = MI->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000670 // handle register defs - build intervals
Chris Lattner428b92e2006-09-15 03:57:23 +0000671 if (MO.isRegister() && MO.getReg() && MO.isDef())
672 handleRegisterDef(MBB, MI, MIIndex, MO.getReg());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000673 }
Chris Lattner6b128bd2006-09-03 08:07:11 +0000674
675 MIIndex += InstrSlots::NUM;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000676 }
Owen Anderson8892b6f2008-06-16 06:18:41 +0000677
Owen Anderson35578012008-06-16 07:10:49 +0000678 if (EmptyBBIndex) {
679 if (MBB->begin() == miEnd) MIIndex += InstrSlots::NUM; // Empty MBB
680 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000681 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000682}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000683
Evan Cheng4ca980e2007-10-17 02:10:22 +0000684bool LiveIntervals::findLiveInMBBs(const LiveRange &LR,
Evan Chenga5bfc972007-10-17 06:53:44 +0000685 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
Evan Cheng4ca980e2007-10-17 02:10:22 +0000686 std::vector<IdxMBBPair>::const_iterator I =
687 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), LR.start);
688
689 bool ResVal = false;
690 while (I != Idx2MBBMap.end()) {
691 if (LR.end <= I->first)
692 break;
693 MBBs.push_back(I->second);
694 ResVal = true;
695 ++I;
696 }
697 return ResVal;
698}
699
700
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000701LiveInterval LiveIntervals::createInterval(unsigned reg) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000702 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
Jim Laskey7902c752006-11-07 12:25:45 +0000703 HUGE_VALF : 0.0F;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000704 return LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000705}
Evan Chengf2fbca62007-11-12 06:35:08 +0000706
Evan Chengc8d044e2008-02-15 18:24:29 +0000707/// getVNInfoSourceReg - Helper function that parses the specified VNInfo
708/// copy field and returns the source register that defines it.
709unsigned LiveIntervals::getVNInfoSourceReg(const VNInfo *VNI) const {
710 if (!VNI->copy)
711 return 0;
712
713 if (VNI->copy->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
714 return VNI->copy->getOperand(1).getReg();
Evan Cheng7e073ba2008-04-09 20:57:25 +0000715 if (VNI->copy->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
716 return VNI->copy->getOperand(2).getReg();
Evan Chengc8d044e2008-02-15 18:24:29 +0000717 unsigned SrcReg, DstReg;
718 if (tii_->isMoveInstr(*VNI->copy, SrcReg, DstReg))
719 return SrcReg;
720 assert(0 && "Unrecognized copy instruction!");
721 return 0;
722}
Evan Chengf2fbca62007-11-12 06:35:08 +0000723
724//===----------------------------------------------------------------------===//
725// Register allocator hooks.
726//
727
Evan Chengd70dbb52008-02-22 09:24:50 +0000728/// getReMatImplicitUse - If the remat definition MI has one (for now, we only
729/// allow one) virtual register operand, then its uses are implicitly using
730/// the register. Returns the virtual register.
731unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
732 MachineInstr *MI) const {
733 unsigned RegOp = 0;
734 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
735 MachineOperand &MO = MI->getOperand(i);
736 if (!MO.isRegister() || !MO.isUse())
737 continue;
738 unsigned Reg = MO.getReg();
739 if (Reg == 0 || Reg == li.reg)
740 continue;
741 // FIXME: For now, only remat MI with at most one register operand.
742 assert(!RegOp &&
743 "Can't rematerialize instruction with multiple register operand!");
744 RegOp = MO.getReg();
745 break;
746 }
747 return RegOp;
748}
749
750/// isValNoAvailableAt - Return true if the val# of the specified interval
751/// which reaches the given instruction also reaches the specified use index.
752bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
753 unsigned UseIdx) const {
754 unsigned Index = getInstructionIndex(MI);
755 VNInfo *ValNo = li.FindLiveRangeContaining(Index)->valno;
756 LiveInterval::const_iterator UI = li.FindLiveRangeContaining(UseIdx);
757 return UI != li.end() && UI->valno == ValNo;
758}
759
Evan Chengf2fbca62007-11-12 06:35:08 +0000760/// isReMaterializable - Returns true if the definition MI of the specified
761/// val# of the specified interval is re-materializable.
762bool LiveIntervals::isReMaterializable(const LiveInterval &li,
Evan Cheng5ef3a042007-12-06 00:01:56 +0000763 const VNInfo *ValNo, MachineInstr *MI,
764 bool &isLoad) {
Evan Chengf2fbca62007-11-12 06:35:08 +0000765 if (DisableReMat)
766 return false;
767
Evan Cheng5ef3a042007-12-06 00:01:56 +0000768 isLoad = false;
Evan Cheng20ccded2008-03-15 00:19:36 +0000769 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
Evan Chengd70dbb52008-02-22 09:24:50 +0000770 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000771
772 int FrameIdx = 0;
773 if (tii_->isLoadFromStackSlot(MI, FrameIdx) &&
Evan Cheng249ded32008-02-23 03:38:34 +0000774 mf_->getFrameInfo()->isImmutableObjectIndex(FrameIdx))
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000775 // FIXME: Let target specific isReallyTriviallyReMaterializable determines
776 // this but remember this is not safe to fold into a two-address
777 // instruction.
Evan Cheng249ded32008-02-23 03:38:34 +0000778 // This is a load from fixed stack slot. It can be rematerialized.
Evan Chengdd3465e2008-02-23 01:44:27 +0000779 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000780
Evan Chengd70dbb52008-02-22 09:24:50 +0000781 if (tii_->isTriviallyReMaterializable(MI)) {
Evan Cheng20ccded2008-03-15 00:19:36 +0000782 const TargetInstrDesc &TID = MI->getDesc();
Chris Lattner749c6f62008-01-07 07:27:27 +0000783 isLoad = TID.isSimpleLoad();
Evan Chengd70dbb52008-02-22 09:24:50 +0000784
785 unsigned ImpUse = getReMatImplicitUse(li, MI);
786 if (ImpUse) {
787 const LiveInterval &ImpLi = getInterval(ImpUse);
788 for (MachineRegisterInfo::use_iterator ri = mri_->use_begin(li.reg),
789 re = mri_->use_end(); ri != re; ++ri) {
790 MachineInstr *UseMI = &*ri;
791 unsigned UseIdx = getInstructionIndex(UseMI);
792 if (li.FindLiveRangeContaining(UseIdx)->valno != ValNo)
793 continue;
Evan Cheng298bbe82008-02-23 02:14:42 +0000794 if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
Evan Chengd70dbb52008-02-22 09:24:50 +0000795 return false;
796 }
797 }
Evan Chengf2fbca62007-11-12 06:35:08 +0000798 return true;
Evan Cheng5ef3a042007-12-06 00:01:56 +0000799 }
Evan Chengf2fbca62007-11-12 06:35:08 +0000800
Evan Chengdd3465e2008-02-23 01:44:27 +0000801 return false;
Evan Cheng5ef3a042007-12-06 00:01:56 +0000802}
803
804/// isReMaterializable - Returns true if every definition of MI of every
805/// val# of the specified interval is re-materializable.
806bool LiveIntervals::isReMaterializable(const LiveInterval &li, bool &isLoad) {
807 isLoad = false;
808 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
809 i != e; ++i) {
810 const VNInfo *VNI = *i;
811 unsigned DefIdx = VNI->def;
812 if (DefIdx == ~1U)
813 continue; // Dead val#.
814 // Is the def for the val# rematerializable?
815 if (DefIdx == ~0u)
816 return false;
817 MachineInstr *ReMatDefMI = getInstructionFromIndex(DefIdx);
818 bool DefIsLoad = false;
Evan Chengd70dbb52008-02-22 09:24:50 +0000819 if (!ReMatDefMI ||
820 !isReMaterializable(li, VNI, ReMatDefMI, DefIsLoad))
Evan Cheng5ef3a042007-12-06 00:01:56 +0000821 return false;
822 isLoad |= DefIsLoad;
Evan Chengf2fbca62007-11-12 06:35:08 +0000823 }
824 return true;
825}
826
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000827/// FilterFoldedOps - Filter out two-address use operands. Return
828/// true if it finds any issue with the operands that ought to prevent
829/// folding.
830static bool FilterFoldedOps(MachineInstr *MI,
831 SmallVector<unsigned, 2> &Ops,
832 unsigned &MRInfo,
833 SmallVector<unsigned, 2> &FoldOps) {
Chris Lattner749c6f62008-01-07 07:27:27 +0000834 const TargetInstrDesc &TID = MI->getDesc();
Evan Cheng6e141fd2007-12-12 23:12:09 +0000835
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000836 MRInfo = 0;
Evan Chengaee4af62007-12-02 08:30:39 +0000837 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
838 unsigned OpIdx = Ops[i];
Evan Chengd70dbb52008-02-22 09:24:50 +0000839 MachineOperand &MO = MI->getOperand(OpIdx);
Evan Chengaee4af62007-12-02 08:30:39 +0000840 // FIXME: fold subreg use.
Evan Chengd70dbb52008-02-22 09:24:50 +0000841 if (MO.getSubReg())
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000842 return true;
Evan Chengd70dbb52008-02-22 09:24:50 +0000843 if (MO.isDef())
Evan Chengaee4af62007-12-02 08:30:39 +0000844 MRInfo |= (unsigned)VirtRegMap::isMod;
845 else {
846 // Filter out two-address use operand(s).
Evan Chengd70dbb52008-02-22 09:24:50 +0000847 if (!MO.isImplicit() &&
848 TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1) {
Evan Chengaee4af62007-12-02 08:30:39 +0000849 MRInfo = VirtRegMap::isModRef;
850 continue;
851 }
852 MRInfo |= (unsigned)VirtRegMap::isRef;
853 }
854 FoldOps.push_back(OpIdx);
Evan Chenge62f97c2007-12-01 02:07:52 +0000855 }
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000856 return false;
857}
858
859
860/// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
861/// slot / to reg or any rematerialized load into ith operand of specified
862/// MI. If it is successul, MI is updated with the newly created MI and
863/// returns true.
864bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
865 VirtRegMap &vrm, MachineInstr *DefMI,
866 unsigned InstrIdx,
867 SmallVector<unsigned, 2> &Ops,
868 bool isSS, int Slot, unsigned Reg) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000869 // If it is an implicit def instruction, just delete it.
Evan Cheng20ccded2008-03-15 00:19:36 +0000870 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000871 RemoveMachineInstrFromMaps(MI);
872 vrm.RemoveMachineInstrFromMaps(MI);
873 MI->eraseFromParent();
874 ++numFolds;
875 return true;
876 }
877
878 // Filter the list of operand indexes that are to be folded. Abort if
879 // any operand will prevent folding.
880 unsigned MRInfo = 0;
881 SmallVector<unsigned, 2> FoldOps;
882 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
883 return false;
Evan Chenge62f97c2007-12-01 02:07:52 +0000884
Evan Cheng427f4c12008-03-31 23:19:51 +0000885 // The only time it's safe to fold into a two address instruction is when
886 // it's folding reload and spill from / into a spill stack slot.
887 if (DefMI && (MRInfo & VirtRegMap::isMod))
Evan Cheng249ded32008-02-23 03:38:34 +0000888 return false;
889
Evan Chengf2f8c2a2008-02-08 22:05:27 +0000890 MachineInstr *fmi = isSS ? tii_->foldMemoryOperand(*mf_, MI, FoldOps, Slot)
891 : tii_->foldMemoryOperand(*mf_, MI, FoldOps, DefMI);
Evan Chengf2fbca62007-11-12 06:35:08 +0000892 if (fmi) {
Evan Chengd3653122008-02-27 03:04:06 +0000893 // Remember this instruction uses the spill slot.
894 if (isSS) vrm.addSpillSlotUse(Slot, fmi);
895
Evan Chengf2fbca62007-11-12 06:35:08 +0000896 // Attempt to fold the memory reference into the instruction. If
897 // we can do this, we don't need to insert spill code.
898 if (lv_)
899 lv_->instructionChanged(MI, fmi);
Evan Cheng81a03822007-11-17 00:40:40 +0000900 else
Dan Gohman6f0d0242008-02-10 18:45:23 +0000901 fmi->copyKillDeadInfo(MI, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +0000902 MachineBasicBlock &MBB = *MI->getParent();
Evan Cheng84802932008-01-10 08:24:38 +0000903 if (isSS && !mf_->getFrameInfo()->isImmutableObjectIndex(Slot))
Evan Chengaee4af62007-12-02 08:30:39 +0000904 vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
Evan Cheng81a03822007-11-17 00:40:40 +0000905 vrm.transferSpillPts(MI, fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +0000906 vrm.transferRestorePts(MI, fmi);
Evan Chengc1f53c72008-03-11 21:34:46 +0000907 vrm.transferEmergencySpills(MI, fmi);
Evan Chengf2fbca62007-11-12 06:35:08 +0000908 mi2iMap_.erase(MI);
Evan Chengcddbb832007-11-30 21:23:43 +0000909 i2miMap_[InstrIdx /InstrSlots::NUM] = fmi;
910 mi2iMap_[fmi] = InstrIdx;
Evan Chengf2fbca62007-11-12 06:35:08 +0000911 MI = MBB.insert(MBB.erase(MI), fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +0000912 ++numFolds;
Evan Chengf2fbca62007-11-12 06:35:08 +0000913 return true;
914 }
915 return false;
916}
917
Evan Cheng018f9b02007-12-05 03:22:34 +0000918/// canFoldMemoryOperand - Returns true if the specified load / store
919/// folding is possible.
920bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI,
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000921 SmallVector<unsigned, 2> &Ops,
Evan Cheng3c75ba82008-04-01 21:37:32 +0000922 bool ReMat) const {
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000923 // Filter the list of operand indexes that are to be folded. Abort if
924 // any operand will prevent folding.
925 unsigned MRInfo = 0;
Evan Cheng018f9b02007-12-05 03:22:34 +0000926 SmallVector<unsigned, 2> FoldOps;
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000927 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
928 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +0000929
Evan Cheng3c75ba82008-04-01 21:37:32 +0000930 // It's only legal to remat for a use, not a def.
931 if (ReMat && (MRInfo & VirtRegMap::isMod))
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000932 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +0000933
Evan Chengd70dbb52008-02-22 09:24:50 +0000934 return tii_->canFoldMemoryOperand(MI, FoldOps);
935}
936
Evan Cheng81a03822007-11-17 00:40:40 +0000937bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
938 SmallPtrSet<MachineBasicBlock*, 4> MBBs;
939 for (LiveInterval::Ranges::const_iterator
940 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
941 std::vector<IdxMBBPair>::const_iterator II =
942 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), I->start);
943 if (II == Idx2MBBMap.end())
944 continue;
945 if (I->end > II->first) // crossing a MBB.
946 return false;
947 MBBs.insert(II->second);
948 if (MBBs.size() > 1)
949 return false;
950 }
951 return true;
952}
953
Evan Chengd70dbb52008-02-22 09:24:50 +0000954/// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
955/// interval on to-be re-materialized operands of MI) with new register.
956void LiveIntervals::rewriteImplicitOps(const LiveInterval &li,
957 MachineInstr *MI, unsigned NewVReg,
958 VirtRegMap &vrm) {
959 // There is an implicit use. That means one of the other operand is
960 // being remat'ed and the remat'ed instruction has li.reg as an
961 // use operand. Make sure we rewrite that as well.
962 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
963 MachineOperand &MO = MI->getOperand(i);
964 if (!MO.isRegister())
965 continue;
966 unsigned Reg = MO.getReg();
967 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
968 continue;
969 if (!vrm.isReMaterialized(Reg))
970 continue;
971 MachineInstr *ReMatMI = vrm.getReMaterializedMI(Reg);
Evan Cheng6130f662008-03-05 00:59:57 +0000972 MachineOperand *UseMO = ReMatMI->findRegisterUseOperand(li.reg);
973 if (UseMO)
974 UseMO->setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +0000975 }
976}
977
Evan Chengf2fbca62007-11-12 06:35:08 +0000978/// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
979/// for addIntervalsForSpills to rewrite uses / defs for the given live range.
Evan Cheng018f9b02007-12-05 03:22:34 +0000980bool LiveIntervals::
Evan Chengd70dbb52008-02-22 09:24:50 +0000981rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
982 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
Evan Cheng81a03822007-11-17 00:40:40 +0000983 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +0000984 unsigned Slot, int LdSlot,
985 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +0000986 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +0000987 const TargetRegisterClass* rc,
988 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +0000989 const MachineLoopInfo *loopInfo,
Evan Cheng313d4b82008-02-23 00:33:04 +0000990 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
Evan Cheng1953d0c2007-11-29 10:12:14 +0000991 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +0000992 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
993 MachineBasicBlock *MBB = MI->getParent();
994 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng018f9b02007-12-05 03:22:34 +0000995 bool CanFold = false;
Evan Chengf2fbca62007-11-12 06:35:08 +0000996 RestartInstruction:
997 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
998 MachineOperand& mop = MI->getOperand(i);
999 if (!mop.isRegister())
1000 continue;
1001 unsigned Reg = mop.getReg();
1002 unsigned RegI = Reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001003 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
Evan Chengf2fbca62007-11-12 06:35:08 +00001004 continue;
Evan Chengf2fbca62007-11-12 06:35:08 +00001005 if (Reg != li.reg)
1006 continue;
1007
1008 bool TryFold = !DefIsReMat;
Evan Chengcb3c3302007-11-29 23:02:50 +00001009 bool FoldSS = true; // Default behavior unless it's a remat.
Evan Chengf2fbca62007-11-12 06:35:08 +00001010 int FoldSlot = Slot;
1011 if (DefIsReMat) {
1012 // If this is the rematerializable definition MI itself and
1013 // all of its uses are rematerialized, simply delete it.
Evan Cheng81a03822007-11-17 00:40:40 +00001014 if (MI == ReMatOrigDefMI && CanDelete) {
Evan Chengcddbb832007-11-30 21:23:43 +00001015 DOUT << "\t\t\t\tErasing re-materlizable def: ";
1016 DOUT << MI << '\n';
Evan Chengf2fbca62007-11-12 06:35:08 +00001017 RemoveMachineInstrFromMaps(MI);
Evan Chengcada2452007-11-28 01:28:46 +00001018 vrm.RemoveMachineInstrFromMaps(MI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001019 MI->eraseFromParent();
1020 break;
1021 }
1022
1023 // If def for this use can't be rematerialized, then try folding.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001024 // If def is rematerializable and it's a load, also try folding.
Evan Chengcb3c3302007-11-29 23:02:50 +00001025 TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad));
Evan Chengf2fbca62007-11-12 06:35:08 +00001026 if (isLoad) {
1027 // Try fold loads (from stack slot, constant pool, etc.) into uses.
1028 FoldSS = isLoadSS;
1029 FoldSlot = LdSlot;
1030 }
1031 }
1032
Evan Chengf2fbca62007-11-12 06:35:08 +00001033 // Scan all of the operands of this instruction rewriting operands
1034 // to use NewVReg instead of li.reg as appropriate. We do this for
1035 // two reasons:
1036 //
1037 // 1. If the instr reads the same spilled vreg multiple times, we
1038 // want to reuse the NewVReg.
1039 // 2. If the instr is a two-addr instruction, we are required to
1040 // keep the src/dst regs pinned.
1041 //
1042 // Keep track of whether we replace a use and/or def so that we can
1043 // create the spill interval with the appropriate range.
Evan Chengcddbb832007-11-30 21:23:43 +00001044
Evan Cheng81a03822007-11-17 00:40:40 +00001045 HasUse = mop.isUse();
1046 HasDef = mop.isDef();
Evan Chengaee4af62007-12-02 08:30:39 +00001047 SmallVector<unsigned, 2> Ops;
1048 Ops.push_back(i);
Evan Chengf2fbca62007-11-12 06:35:08 +00001049 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
Evan Chengaee4af62007-12-02 08:30:39 +00001050 const MachineOperand &MOj = MI->getOperand(j);
1051 if (!MOj.isRegister())
Evan Chengf2fbca62007-11-12 06:35:08 +00001052 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001053 unsigned RegJ = MOj.getReg();
Dan Gohman6f0d0242008-02-10 18:45:23 +00001054 if (RegJ == 0 || TargetRegisterInfo::isPhysicalRegister(RegJ))
Evan Chengf2fbca62007-11-12 06:35:08 +00001055 continue;
1056 if (RegJ == RegI) {
Evan Chengaee4af62007-12-02 08:30:39 +00001057 Ops.push_back(j);
1058 HasUse |= MOj.isUse();
1059 HasDef |= MOj.isDef();
Evan Chengf2fbca62007-11-12 06:35:08 +00001060 }
1061 }
1062
Evan Cheng9c3c2212008-06-06 07:54:39 +00001063 // Update stack slot spill weight if we are splitting.
1064 float Weight = getSpillWeight(HasDef, HasUse, loopDepth);
1065 if (!TrySplit)
1066 SSWeight += Weight;
1067
1068 if (!TryFold)
1069 CanFold = false;
1070 else {
Evan Cheng018f9b02007-12-05 03:22:34 +00001071 // Do not fold load / store here if we are splitting. We'll find an
1072 // optimal point to insert a load / store later.
1073 if (!TrySplit) {
1074 if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1075 Ops, FoldSS, FoldSlot, Reg)) {
1076 // Folding the load/store can completely change the instruction in
1077 // unpredictable ways, rescan it from the beginning.
1078 HasUse = false;
1079 HasDef = false;
1080 CanFold = false;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001081 if (isRemoved(MI)) {
1082 SSWeight -= Weight;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001083 break;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001084 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001085 goto RestartInstruction;
1086 }
1087 } else {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001088 // We'll try to fold it later if it's profitable.
Evan Cheng3c75ba82008-04-01 21:37:32 +00001089 CanFold = canFoldMemoryOperand(MI, Ops, DefIsReMat);
Evan Cheng018f9b02007-12-05 03:22:34 +00001090 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001091 }
Evan Chengcddbb832007-11-30 21:23:43 +00001092
1093 // Create a new virtual register for the spill interval.
1094 bool CreatedNewVReg = false;
1095 if (NewVReg == 0) {
Evan Chengd70dbb52008-02-22 09:24:50 +00001096 NewVReg = mri_->createVirtualRegister(rc);
Evan Chengcddbb832007-11-30 21:23:43 +00001097 vrm.grow();
1098 CreatedNewVReg = true;
1099 }
1100 mop.setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001101 if (mop.isImplicit())
1102 rewriteImplicitOps(li, MI, NewVReg, vrm);
Evan Chengcddbb832007-11-30 21:23:43 +00001103
1104 // Reuse NewVReg for other reads.
Evan Chengd70dbb52008-02-22 09:24:50 +00001105 for (unsigned j = 0, e = Ops.size(); j != e; ++j) {
1106 MachineOperand &mopj = MI->getOperand(Ops[j]);
1107 mopj.setReg(NewVReg);
1108 if (mopj.isImplicit())
1109 rewriteImplicitOps(li, MI, NewVReg, vrm);
1110 }
Evan Chengcddbb832007-11-30 21:23:43 +00001111
Evan Cheng81a03822007-11-17 00:40:40 +00001112 if (CreatedNewVReg) {
1113 if (DefIsReMat) {
1114 vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI/*, CanDelete*/);
Evan Chengd70dbb52008-02-22 09:24:50 +00001115 if (ReMatIds[VNI->id] == VirtRegMap::MAX_STACK_SLOT) {
Evan Cheng81a03822007-11-17 00:40:40 +00001116 // Each valnum may have its own remat id.
Evan Chengd70dbb52008-02-22 09:24:50 +00001117 ReMatIds[VNI->id] = vrm.assignVirtReMatId(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001118 } else {
Evan Chengd70dbb52008-02-22 09:24:50 +00001119 vrm.assignVirtReMatId(NewVReg, ReMatIds[VNI->id]);
Evan Cheng81a03822007-11-17 00:40:40 +00001120 }
1121 if (!CanDelete || (HasUse && HasDef)) {
1122 // If this is a two-addr instruction then its use operands are
1123 // rematerializable but its def is not. It should be assigned a
1124 // stack slot.
1125 vrm.assignVirt2StackSlot(NewVReg, Slot);
1126 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001127 } else {
Evan Chengf2fbca62007-11-12 06:35:08 +00001128 vrm.assignVirt2StackSlot(NewVReg, Slot);
1129 }
Evan Chengcb3c3302007-11-29 23:02:50 +00001130 } else if (HasUse && HasDef &&
1131 vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) {
1132 // If this interval hasn't been assigned a stack slot (because earlier
1133 // def is a deleted remat def), do it now.
1134 assert(Slot != VirtRegMap::NO_STACK_SLOT);
1135 vrm.assignVirt2StackSlot(NewVReg, Slot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001136 }
1137
Evan Cheng313d4b82008-02-23 00:33:04 +00001138 // Re-matting an instruction with virtual register use. Add the
1139 // register as an implicit use on the use MI.
1140 if (DefIsReMat && ImpUse)
1141 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1142
Evan Chengf2fbca62007-11-12 06:35:08 +00001143 // create a new register interval for this spill / remat.
1144 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001145 if (CreatedNewVReg) {
1146 NewLIs.push_back(&nI);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001147 MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg));
Evan Cheng81a03822007-11-17 00:40:40 +00001148 if (TrySplit)
1149 vrm.setIsSplitFromReg(NewVReg, li.reg);
1150 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001151
1152 if (HasUse) {
Evan Cheng81a03822007-11-17 00:40:40 +00001153 if (CreatedNewVReg) {
1154 LiveRange LR(getLoadIndex(index), getUseIndex(index)+1,
1155 nI.getNextValue(~0U, 0, VNInfoAllocator));
1156 DOUT << " +" << LR;
1157 nI.addRange(LR);
1158 } else {
1159 // Extend the split live interval to this def / use.
1160 unsigned End = getUseIndex(index)+1;
1161 LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
1162 nI.getValNumInfo(nI.getNumValNums()-1));
1163 DOUT << " +" << LR;
1164 nI.addRange(LR);
1165 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001166 }
1167 if (HasDef) {
1168 LiveRange LR(getDefIndex(index), getStoreIndex(index),
1169 nI.getNextValue(~0U, 0, VNInfoAllocator));
1170 DOUT << " +" << LR;
1171 nI.addRange(LR);
1172 }
Evan Cheng81a03822007-11-17 00:40:40 +00001173
Evan Chengf2fbca62007-11-12 06:35:08 +00001174 DOUT << "\t\t\t\tAdded new interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001175 nI.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001176 DOUT << '\n';
1177 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001178 return CanFold;
Evan Chengf2fbca62007-11-12 06:35:08 +00001179}
Evan Cheng81a03822007-11-17 00:40:40 +00001180bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001181 const VNInfo *VNI,
1182 MachineBasicBlock *MBB, unsigned Idx) const {
Evan Cheng81a03822007-11-17 00:40:40 +00001183 unsigned End = getMBBEndIdx(MBB);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001184 for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
1185 unsigned KillIdx = VNI->kills[j];
1186 if (KillIdx > Idx && KillIdx < End)
1187 return true;
Evan Cheng81a03822007-11-17 00:40:40 +00001188 }
1189 return false;
1190}
1191
Evan Cheng063284c2008-02-21 00:34:19 +00001192/// RewriteInfo - Keep track of machine instrs that will be rewritten
1193/// during spilling.
Dan Gohman844731a2008-05-13 00:00:25 +00001194namespace {
1195 struct RewriteInfo {
1196 unsigned Index;
1197 MachineInstr *MI;
1198 bool HasUse;
1199 bool HasDef;
1200 RewriteInfo(unsigned i, MachineInstr *mi, bool u, bool d)
1201 : Index(i), MI(mi), HasUse(u), HasDef(d) {}
1202 };
Evan Cheng063284c2008-02-21 00:34:19 +00001203
Dan Gohman844731a2008-05-13 00:00:25 +00001204 struct RewriteInfoCompare {
1205 bool operator()(const RewriteInfo &LHS, const RewriteInfo &RHS) const {
1206 return LHS.Index < RHS.Index;
1207 }
1208 };
1209}
Evan Cheng063284c2008-02-21 00:34:19 +00001210
Evan Chengf2fbca62007-11-12 06:35:08 +00001211void LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001212rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
Evan Chengf2fbca62007-11-12 06:35:08 +00001213 LiveInterval::Ranges::const_iterator &I,
Evan Cheng81a03822007-11-17 00:40:40 +00001214 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001215 unsigned Slot, int LdSlot,
1216 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001217 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001218 const TargetRegisterClass* rc,
1219 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001220 const MachineLoopInfo *loopInfo,
Evan Cheng81a03822007-11-17 00:40:40 +00001221 BitVector &SpillMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001222 std::map<unsigned, std::vector<SRInfo> > &SpillIdxes,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001223 BitVector &RestoreMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001224 std::map<unsigned, std::vector<SRInfo> > &RestoreIdxes,
1225 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001226 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001227 bool AllCanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001228 unsigned NewVReg = 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001229 unsigned start = getBaseIndex(I->start);
Evan Chengf2fbca62007-11-12 06:35:08 +00001230 unsigned end = getBaseIndex(I->end-1) + InstrSlots::NUM;
Evan Chengf2fbca62007-11-12 06:35:08 +00001231
Evan Cheng063284c2008-02-21 00:34:19 +00001232 // First collect all the def / use in this live range that will be rewritten.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001233 // Make sure they are sorted according to instruction index.
Evan Cheng063284c2008-02-21 00:34:19 +00001234 std::vector<RewriteInfo> RewriteMIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001235 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1236 re = mri_->reg_end(); ri != re; ) {
Evan Cheng419852c2008-04-03 16:39:43 +00001237 MachineInstr *MI = &*ri;
Evan Cheng063284c2008-02-21 00:34:19 +00001238 MachineOperand &O = ri.getOperand();
1239 ++ri;
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001240 assert(!O.isImplicit() && "Spilling register that's used as implicit use?");
Evan Cheng063284c2008-02-21 00:34:19 +00001241 unsigned index = getInstructionIndex(MI);
1242 if (index < start || index >= end)
1243 continue;
1244 RewriteMIs.push_back(RewriteInfo(index, MI, O.isUse(), O.isDef()));
1245 }
1246 std::sort(RewriteMIs.begin(), RewriteMIs.end(), RewriteInfoCompare());
1247
Evan Cheng313d4b82008-02-23 00:33:04 +00001248 unsigned ImpUse = DefIsReMat ? getReMatImplicitUse(li, ReMatDefMI) : 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001249 // Now rewrite the defs and uses.
1250 for (unsigned i = 0, e = RewriteMIs.size(); i != e; ) {
1251 RewriteInfo &rwi = RewriteMIs[i];
1252 ++i;
1253 unsigned index = rwi.Index;
1254 bool MIHasUse = rwi.HasUse;
1255 bool MIHasDef = rwi.HasDef;
1256 MachineInstr *MI = rwi.MI;
1257 // If MI def and/or use the same register multiple times, then there
1258 // are multiple entries.
Evan Cheng313d4b82008-02-23 00:33:04 +00001259 unsigned NumUses = MIHasUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001260 while (i != e && RewriteMIs[i].MI == MI) {
1261 assert(RewriteMIs[i].Index == index);
Evan Cheng313d4b82008-02-23 00:33:04 +00001262 bool isUse = RewriteMIs[i].HasUse;
1263 if (isUse) ++NumUses;
1264 MIHasUse |= isUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001265 MIHasDef |= RewriteMIs[i].HasDef;
1266 ++i;
1267 }
Evan Cheng81a03822007-11-17 00:40:40 +00001268 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng313d4b82008-02-23 00:33:04 +00001269
Evan Cheng0a891ed2008-05-23 23:00:04 +00001270 if (ImpUse && MI != ReMatDefMI) {
Evan Cheng313d4b82008-02-23 00:33:04 +00001271 // Re-matting an instruction with virtual register use. Update the
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001272 // register interval's spill weight to HUGE_VALF to prevent it from
1273 // being spilled.
Evan Cheng313d4b82008-02-23 00:33:04 +00001274 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001275 ImpLi.weight = HUGE_VALF;
Evan Cheng313d4b82008-02-23 00:33:04 +00001276 }
1277
Evan Cheng063284c2008-02-21 00:34:19 +00001278 unsigned MBBId = MBB->getNumber();
Evan Cheng018f9b02007-12-05 03:22:34 +00001279 unsigned ThisVReg = 0;
Evan Cheng70306f82007-12-03 09:58:48 +00001280 if (TrySplit) {
Evan Cheng063284c2008-02-21 00:34:19 +00001281 std::map<unsigned,unsigned>::const_iterator NVI = MBBVRegsMap.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001282 if (NVI != MBBVRegsMap.end()) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001283 ThisVReg = NVI->second;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001284 // One common case:
1285 // x = use
1286 // ...
1287 // ...
1288 // def = ...
1289 // = use
1290 // It's better to start a new interval to avoid artifically
1291 // extend the new interval.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001292 if (MIHasDef && !MIHasUse) {
1293 MBBVRegsMap.erase(MBB->getNumber());
Evan Cheng018f9b02007-12-05 03:22:34 +00001294 ThisVReg = 0;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001295 }
1296 }
Evan Chengcada2452007-11-28 01:28:46 +00001297 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001298
1299 bool IsNew = ThisVReg == 0;
1300 if (IsNew) {
1301 // This ends the previous live interval. If all of its def / use
1302 // can be folded, give it a low spill weight.
1303 if (NewVReg && TrySplit && AllCanFold) {
1304 LiveInterval &nI = getOrCreateInterval(NewVReg);
1305 nI.weight /= 10.0F;
1306 }
1307 AllCanFold = true;
1308 }
1309 NewVReg = ThisVReg;
1310
Evan Cheng81a03822007-11-17 00:40:40 +00001311 bool HasDef = false;
1312 bool HasUse = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001313 bool CanFold = rewriteInstructionForSpills(li, I->valno, TrySplit,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001314 index, end, MI, ReMatOrigDefMI, ReMatDefMI,
1315 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
1316 CanDelete, vrm, rc, ReMatIds, loopInfo, NewVReg,
1317 ImpUse, HasDef, HasUse, MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001318 if (!HasDef && !HasUse)
1319 continue;
1320
Evan Cheng018f9b02007-12-05 03:22:34 +00001321 AllCanFold &= CanFold;
1322
Evan Cheng81a03822007-11-17 00:40:40 +00001323 // Update weight of spill interval.
1324 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng70306f82007-12-03 09:58:48 +00001325 if (!TrySplit) {
Evan Cheng81a03822007-11-17 00:40:40 +00001326 // The spill weight is now infinity as it cannot be spilled again.
1327 nI.weight = HUGE_VALF;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001328 continue;
Evan Cheng81a03822007-11-17 00:40:40 +00001329 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001330
1331 // Keep track of the last def and first use in each MBB.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001332 if (HasDef) {
1333 if (MI != ReMatOrigDefMI || !CanDelete) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001334 bool HasKill = false;
1335 if (!HasUse)
1336 HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, getDefIndex(index));
1337 else {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001338 // If this is a two-address code, then this index starts a new VNInfo.
Evan Cheng3f32d652008-06-04 09:18:41 +00001339 const VNInfo *VNI = li.findDefinedVNInfo(getDefIndex(index));
Evan Cheng0cbb1162007-11-29 01:06:25 +00001340 if (VNI)
1341 HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, getDefIndex(index));
1342 }
Evan Chenge3110d02007-12-01 04:42:39 +00001343 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
1344 SpillIdxes.find(MBBId);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001345 if (!HasKill) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001346 if (SII == SpillIdxes.end()) {
1347 std::vector<SRInfo> S;
1348 S.push_back(SRInfo(index, NewVReg, true));
1349 SpillIdxes.insert(std::make_pair(MBBId, S));
1350 } else if (SII->second.back().vreg != NewVReg) {
1351 SII->second.push_back(SRInfo(index, NewVReg, true));
1352 } else if ((int)index > SII->second.back().index) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001353 // If there is an earlier def and this is a two-address
1354 // instruction, then it's not possible to fold the store (which
1355 // would also fold the load).
Evan Cheng1953d0c2007-11-29 10:12:14 +00001356 SRInfo &Info = SII->second.back();
1357 Info.index = index;
1358 Info.canFold = !HasUse;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001359 }
1360 SpillMBBs.set(MBBId);
Evan Chenge3110d02007-12-01 04:42:39 +00001361 } else if (SII != SpillIdxes.end() &&
1362 SII->second.back().vreg == NewVReg &&
1363 (int)index > SII->second.back().index) {
1364 // There is an earlier def that's not killed (must be two-address).
1365 // The spill is no longer needed.
1366 SII->second.pop_back();
1367 if (SII->second.empty()) {
1368 SpillIdxes.erase(MBBId);
1369 SpillMBBs.reset(MBBId);
1370 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001371 }
1372 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001373 }
1374
1375 if (HasUse) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001376 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001377 SpillIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001378 if (SII != SpillIdxes.end() &&
1379 SII->second.back().vreg == NewVReg &&
1380 (int)index > SII->second.back().index)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001381 // Use(s) following the last def, it's not safe to fold the spill.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001382 SII->second.back().canFold = false;
1383 std::map<unsigned, std::vector<SRInfo> >::iterator RII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001384 RestoreIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001385 if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001386 // If we are splitting live intervals, only fold if it's the first
1387 // use and there isn't another use later in the MBB.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001388 RII->second.back().canFold = false;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001389 else if (IsNew) {
1390 // Only need a reload if there isn't an earlier def / use.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001391 if (RII == RestoreIdxes.end()) {
1392 std::vector<SRInfo> Infos;
1393 Infos.push_back(SRInfo(index, NewVReg, true));
1394 RestoreIdxes.insert(std::make_pair(MBBId, Infos));
1395 } else {
1396 RII->second.push_back(SRInfo(index, NewVReg, true));
1397 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001398 RestoreMBBs.set(MBBId);
1399 }
1400 }
1401
1402 // Update spill weight.
Evan Cheng22f07ff2007-12-11 02:09:15 +00001403 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001404 nI.weight += getSpillWeight(HasDef, HasUse, loopDepth);
Evan Chengf2fbca62007-11-12 06:35:08 +00001405 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001406
1407 if (NewVReg && TrySplit && AllCanFold) {
1408 // If all of its def / use can be folded, give it a low spill weight.
1409 LiveInterval &nI = getOrCreateInterval(NewVReg);
1410 nI.weight /= 10.0F;
1411 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001412}
1413
Evan Cheng1953d0c2007-11-29 10:12:14 +00001414bool LiveIntervals::alsoFoldARestore(int Id, int index, unsigned vr,
1415 BitVector &RestoreMBBs,
1416 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1417 if (!RestoreMBBs[Id])
1418 return false;
1419 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1420 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1421 if (Restores[i].index == index &&
1422 Restores[i].vreg == vr &&
1423 Restores[i].canFold)
1424 return true;
1425 return false;
1426}
1427
1428void LiveIntervals::eraseRestoreInfo(int Id, int index, unsigned vr,
1429 BitVector &RestoreMBBs,
1430 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1431 if (!RestoreMBBs[Id])
1432 return;
1433 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1434 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1435 if (Restores[i].index == index && Restores[i].vreg)
1436 Restores[i].index = -1;
1437}
Evan Cheng81a03822007-11-17 00:40:40 +00001438
Evan Cheng4cce6b42008-04-11 17:53:36 +00001439/// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
1440/// spilled and create empty intervals for their uses.
1441void
1442LiveIntervals::handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
1443 const TargetRegisterClass* rc,
1444 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng419852c2008-04-03 16:39:43 +00001445 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1446 re = mri_->reg_end(); ri != re; ) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001447 MachineOperand &O = ri.getOperand();
Evan Cheng419852c2008-04-03 16:39:43 +00001448 MachineInstr *MI = &*ri;
1449 ++ri;
Evan Cheng4cce6b42008-04-11 17:53:36 +00001450 if (O.isDef()) {
1451 assert(MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF &&
1452 "Register def was not rewritten?");
1453 RemoveMachineInstrFromMaps(MI);
1454 vrm.RemoveMachineInstrFromMaps(MI);
1455 MI->eraseFromParent();
1456 } else {
1457 // This must be an use of an implicit_def so it's not part of the live
1458 // interval. Create a new empty live interval for it.
1459 // FIXME: Can we simply erase some of the instructions? e.g. Stores?
1460 unsigned NewVReg = mri_->createVirtualRegister(rc);
1461 vrm.grow();
1462 vrm.setIsImplicitlyDefined(NewVReg);
1463 NewLIs.push_back(&getOrCreateInterval(NewVReg));
1464 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1465 MachineOperand &MO = MI->getOperand(i);
1466 if (MO.isReg() && MO.getReg() == li.reg)
1467 MO.setReg(NewVReg);
1468 }
1469 }
Evan Cheng419852c2008-04-03 16:39:43 +00001470 }
1471}
1472
Evan Cheng81a03822007-11-17 00:40:40 +00001473
Evan Chengf2fbca62007-11-12 06:35:08 +00001474std::vector<LiveInterval*> LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001475addIntervalsForSpills(const LiveInterval &li,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001476 const MachineLoopInfo *loopInfo, VirtRegMap &vrm,
1477 float &SSWeight) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001478 // Since this is called after the analysis is done we don't know if
1479 // LiveVariables is available
1480 lv_ = getAnalysisToUpdate<LiveVariables>();
1481
1482 assert(li.weight != HUGE_VALF &&
1483 "attempt to spill already spilled interval!");
1484
1485 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001486 li.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001487 DOUT << '\n';
1488
Evan Cheng9c3c2212008-06-06 07:54:39 +00001489 // Spill slot weight.
1490 SSWeight = 0.0f;
1491
Evan Cheng81a03822007-11-17 00:40:40 +00001492 // Each bit specify whether it a spill is required in the MBB.
1493 BitVector SpillMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001494 std::map<unsigned, std::vector<SRInfo> > SpillIdxes;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001495 BitVector RestoreMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001496 std::map<unsigned, std::vector<SRInfo> > RestoreIdxes;
1497 std::map<unsigned,unsigned> MBBVRegsMap;
Evan Chengf2fbca62007-11-12 06:35:08 +00001498 std::vector<LiveInterval*> NewLIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001499 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
Evan Chengf2fbca62007-11-12 06:35:08 +00001500
1501 unsigned NumValNums = li.getNumValNums();
1502 SmallVector<MachineInstr*, 4> ReMatDefs;
1503 ReMatDefs.resize(NumValNums, NULL);
1504 SmallVector<MachineInstr*, 4> ReMatOrigDefs;
1505 ReMatOrigDefs.resize(NumValNums, NULL);
1506 SmallVector<int, 4> ReMatIds;
1507 ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
1508 BitVector ReMatDelete(NumValNums);
1509 unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
1510
Evan Cheng81a03822007-11-17 00:40:40 +00001511 // Spilling a split live interval. It cannot be split any further. Also,
1512 // it's also guaranteed to be a single val# / range interval.
1513 if (vrm.getPreSplitReg(li.reg)) {
1514 vrm.setIsSplitFromReg(li.reg, 0);
Evan Chengd120ffd2007-12-05 10:24:35 +00001515 // Unset the split kill marker on the last use.
1516 unsigned KillIdx = vrm.getKillPoint(li.reg);
1517 if (KillIdx) {
1518 MachineInstr *KillMI = getInstructionFromIndex(KillIdx);
1519 assert(KillMI && "Last use disappeared?");
1520 int KillOp = KillMI->findRegisterUseOperandIdx(li.reg, true);
1521 assert(KillOp != -1 && "Last use disappeared?");
Chris Lattnerf7382302007-12-30 21:56:09 +00001522 KillMI->getOperand(KillOp).setIsKill(false);
Evan Chengd120ffd2007-12-05 10:24:35 +00001523 }
Evan Chengadf85902007-12-05 09:51:10 +00001524 vrm.removeKillPoint(li.reg);
Evan Cheng81a03822007-11-17 00:40:40 +00001525 bool DefIsReMat = vrm.isReMaterialized(li.reg);
1526 Slot = vrm.getStackSlot(li.reg);
1527 assert(Slot != VirtRegMap::MAX_STACK_SLOT);
1528 MachineInstr *ReMatDefMI = DefIsReMat ?
1529 vrm.getReMaterializedMI(li.reg) : NULL;
1530 int LdSlot = 0;
1531 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1532 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001533 (DefIsReMat && (ReMatDefMI->getDesc().isSimpleLoad()));
Evan Cheng81a03822007-11-17 00:40:40 +00001534 bool IsFirstRange = true;
1535 for (LiveInterval::Ranges::const_iterator
1536 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1537 // If this is a split live interval with multiple ranges, it means there
1538 // are two-address instructions that re-defined the value. Only the
1539 // first def can be rematerialized!
1540 if (IsFirstRange) {
Evan Chengcb3c3302007-11-29 23:02:50 +00001541 // Note ReMatOrigDefMI has already been deleted.
Evan Cheng81a03822007-11-17 00:40:40 +00001542 rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
1543 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001544 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001545 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001546 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001547 } else {
1548 rewriteInstructionsForSpills(li, false, I, NULL, 0,
1549 Slot, 0, false, false, false,
Evan Chengd70dbb52008-02-22 09:24:50 +00001550 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001551 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001552 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001553 }
1554 IsFirstRange = false;
1555 }
Evan Cheng419852c2008-04-03 16:39:43 +00001556
Evan Cheng9c3c2212008-06-06 07:54:39 +00001557 SSWeight = 0.0f; // Already accounted for when split.
Evan Cheng4cce6b42008-04-11 17:53:36 +00001558 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001559 return NewLIs;
1560 }
1561
1562 bool TrySplit = SplitAtBB && !intervalIsInOneMBB(li);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001563 if (SplitLimit != -1 && (int)numSplits >= SplitLimit)
1564 TrySplit = false;
1565 if (TrySplit)
1566 ++numSplits;
Evan Chengf2fbca62007-11-12 06:35:08 +00001567 bool NeedStackSlot = false;
1568 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1569 i != e; ++i) {
1570 const VNInfo *VNI = *i;
1571 unsigned VN = VNI->id;
1572 unsigned DefIdx = VNI->def;
1573 if (DefIdx == ~1U)
1574 continue; // Dead val#.
1575 // Is the def for the val# rematerializable?
Evan Cheng81a03822007-11-17 00:40:40 +00001576 MachineInstr *ReMatDefMI = (DefIdx == ~0u)
1577 ? 0 : getInstructionFromIndex(DefIdx);
Evan Cheng5ef3a042007-12-06 00:01:56 +00001578 bool dummy;
1579 if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, dummy)) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001580 // Remember how to remat the def of this val#.
Evan Cheng81a03822007-11-17 00:40:40 +00001581 ReMatOrigDefs[VN] = ReMatDefMI;
Evan Chengf2fbca62007-11-12 06:35:08 +00001582 // Original def may be modified so we have to make a copy here. vrm must
1583 // delete these!
Evan Cheng81a03822007-11-17 00:40:40 +00001584 ReMatDefs[VN] = ReMatDefMI = ReMatDefMI->clone();
Evan Chengf2fbca62007-11-12 06:35:08 +00001585
1586 bool CanDelete = true;
Evan Chengc3fc7d92007-11-29 09:49:23 +00001587 if (VNI->hasPHIKill) {
1588 // A kill is a phi node, not all of its uses can be rematerialized.
Evan Chengf2fbca62007-11-12 06:35:08 +00001589 // It must not be deleted.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001590 CanDelete = false;
1591 // Need a stack slot if there is any live range where uses cannot be
1592 // rematerialized.
1593 NeedStackSlot = true;
Evan Chengf2fbca62007-11-12 06:35:08 +00001594 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001595 if (CanDelete)
1596 ReMatDelete.set(VN);
1597 } else {
1598 // Need a stack slot if there is any live range where uses cannot be
1599 // rematerialized.
1600 NeedStackSlot = true;
1601 }
1602 }
1603
1604 // One stack slot per live interval.
Evan Cheng81a03822007-11-17 00:40:40 +00001605 if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0)
Evan Chengf2fbca62007-11-12 06:35:08 +00001606 Slot = vrm.assignVirt2StackSlot(li.reg);
1607
1608 // Create new intervals and rewrite defs and uses.
1609 for (LiveInterval::Ranges::const_iterator
1610 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Evan Cheng81a03822007-11-17 00:40:40 +00001611 MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id];
1612 MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id];
1613 bool DefIsReMat = ReMatDefMI != NULL;
Evan Chengf2fbca62007-11-12 06:35:08 +00001614 bool CanDelete = ReMatDelete[I->valno->id];
1615 int LdSlot = 0;
Evan Cheng81a03822007-11-17 00:40:40 +00001616 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001617 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001618 (DefIsReMat && ReMatDefMI->getDesc().isSimpleLoad());
Evan Cheng81a03822007-11-17 00:40:40 +00001619 rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001620 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001621 CanDelete, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001622 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001623 MBBVRegsMap, NewLIs, SSWeight);
Evan Chengf2fbca62007-11-12 06:35:08 +00001624 }
1625
Evan Cheng0cbb1162007-11-29 01:06:25 +00001626 // Insert spills / restores if we are splitting.
Evan Cheng419852c2008-04-03 16:39:43 +00001627 if (!TrySplit) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001628 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001629 return NewLIs;
Evan Cheng419852c2008-04-03 16:39:43 +00001630 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001631
Evan Chengb50bb8c2007-12-05 08:16:32 +00001632 SmallPtrSet<LiveInterval*, 4> AddedKill;
Evan Chengaee4af62007-12-02 08:30:39 +00001633 SmallVector<unsigned, 2> Ops;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001634 if (NeedStackSlot) {
1635 int Id = SpillMBBs.find_first();
1636 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001637 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1638 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001639 std::vector<SRInfo> &spills = SpillIdxes[Id];
1640 for (unsigned i = 0, e = spills.size(); i != e; ++i) {
1641 int index = spills[i].index;
1642 unsigned VReg = spills[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001643 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001644 bool isReMat = vrm.isReMaterialized(VReg);
1645 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001646 bool CanFold = false;
1647 bool FoundUse = false;
1648 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001649 if (spills[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001650 CanFold = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001651 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1652 MachineOperand &MO = MI->getOperand(j);
1653 if (!MO.isRegister() || MO.getReg() != VReg)
1654 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001655
1656 Ops.push_back(j);
1657 if (MO.isDef())
Evan Chengcddbb832007-11-30 21:23:43 +00001658 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001659 if (isReMat ||
1660 (!FoundUse && !alsoFoldARestore(Id, index, VReg,
1661 RestoreMBBs, RestoreIdxes))) {
1662 // MI has two-address uses of the same register. If the use
1663 // isn't the first and only use in the BB, then we can't fold
1664 // it. FIXME: Move this to rewriteInstructionsForSpills.
1665 CanFold = false;
Evan Chengcddbb832007-11-30 21:23:43 +00001666 break;
1667 }
Evan Chengaee4af62007-12-02 08:30:39 +00001668 FoundUse = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001669 }
1670 }
1671 // Fold the store into the def if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001672 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001673 if (CanFold && !Ops.empty()) {
1674 if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
Evan Chengcddbb832007-11-30 21:23:43 +00001675 Folded = true;
Evan Chengf38d14f2007-12-05 09:05:34 +00001676 if (FoundUse > 0) {
Evan Chengaee4af62007-12-02 08:30:39 +00001677 // Also folded uses, do not issue a load.
1678 eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
Evan Chengf38d14f2007-12-05 09:05:34 +00001679 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
1680 }
Evan Cheng597d10d2007-12-04 00:32:23 +00001681 nI.removeRange(getDefIndex(index), getStoreIndex(index));
Evan Chengcddbb832007-11-30 21:23:43 +00001682 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001683 }
1684
Evan Cheng7e073ba2008-04-09 20:57:25 +00001685 // Otherwise tell the spiller to issue a spill.
Evan Chengb50bb8c2007-12-05 08:16:32 +00001686 if (!Folded) {
1687 LiveRange *LR = &nI.ranges[nI.ranges.size()-1];
1688 bool isKill = LR->end == getStoreIndex(index);
Evan Chengb0a6f622008-05-20 08:10:37 +00001689 if (!MI->registerDefIsDead(nI.reg))
1690 // No need to spill a dead def.
1691 vrm.addSpillPoint(VReg, isKill, MI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001692 if (isKill)
1693 AddedKill.insert(&nI);
1694 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001695
1696 // Update spill slot weight.
1697 if (!isReMat)
1698 SSWeight += getSpillWeight(true, false, loopDepth);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001699 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001700 Id = SpillMBBs.find_next(Id);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001701 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001702 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001703
Evan Cheng1953d0c2007-11-29 10:12:14 +00001704 int Id = RestoreMBBs.find_first();
1705 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001706 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1707 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
1708
Evan Cheng1953d0c2007-11-29 10:12:14 +00001709 std::vector<SRInfo> &restores = RestoreIdxes[Id];
1710 for (unsigned i = 0, e = restores.size(); i != e; ++i) {
1711 int index = restores[i].index;
1712 if (index == -1)
1713 continue;
1714 unsigned VReg = restores[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001715 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001716 bool isReMat = vrm.isReMaterialized(VReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001717 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001718 bool CanFold = false;
1719 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001720 if (restores[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001721 CanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001722 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1723 MachineOperand &MO = MI->getOperand(j);
1724 if (!MO.isRegister() || MO.getReg() != VReg)
1725 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001726
Evan Cheng0cbb1162007-11-29 01:06:25 +00001727 if (MO.isDef()) {
Evan Chengaee4af62007-12-02 08:30:39 +00001728 // If this restore were to be folded, it would have been folded
1729 // already.
1730 CanFold = false;
Evan Cheng81a03822007-11-17 00:40:40 +00001731 break;
1732 }
Evan Chengaee4af62007-12-02 08:30:39 +00001733 Ops.push_back(j);
Evan Cheng81a03822007-11-17 00:40:40 +00001734 }
1735 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001736
1737 // Fold the load into the use if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001738 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001739 if (CanFold && !Ops.empty()) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001740 if (!isReMat)
Evan Chengaee4af62007-12-02 08:30:39 +00001741 Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg);
1742 else {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001743 MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg);
1744 int LdSlot = 0;
1745 bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1746 // If the rematerializable def is a load, also try to fold it.
Chris Lattner749c6f62008-01-07 07:27:27 +00001747 if (isLoadSS || ReMatDefMI->getDesc().isSimpleLoad())
Evan Chengaee4af62007-12-02 08:30:39 +00001748 Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1749 Ops, isLoadSS, LdSlot, VReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001750 unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI);
1751 if (ImpUse) {
1752 // Re-matting an instruction with virtual register use. Add the
1753 // register as an implicit use on the use MI and update the register
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001754 // interval's spill weight to HUGE_VALF to prevent it from being
1755 // spilled.
Evan Chengd70dbb52008-02-22 09:24:50 +00001756 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001757 ImpLi.weight = HUGE_VALF;
Evan Chengd70dbb52008-02-22 09:24:50 +00001758 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1759 }
Evan Chengaee4af62007-12-02 08:30:39 +00001760 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001761 }
1762 // If folding is not possible / failed, then tell the spiller to issue a
1763 // load / rematerialization for us.
Evan Cheng597d10d2007-12-04 00:32:23 +00001764 if (Folded)
1765 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001766 else
Evan Cheng0cbb1162007-11-29 01:06:25 +00001767 vrm.addRestorePoint(VReg, MI);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001768
1769 // Update spill slot weight.
1770 if (!isReMat)
1771 SSWeight += getSpillWeight(false, true, loopDepth);
Evan Cheng81a03822007-11-17 00:40:40 +00001772 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001773 Id = RestoreMBBs.find_next(Id);
Evan Cheng81a03822007-11-17 00:40:40 +00001774 }
1775
Evan Chengb50bb8c2007-12-05 08:16:32 +00001776 // Finalize intervals: add kills, finalize spill weights, and filter out
1777 // dead intervals.
Evan Cheng597d10d2007-12-04 00:32:23 +00001778 std::vector<LiveInterval*> RetNewLIs;
1779 for (unsigned i = 0, e = NewLIs.size(); i != e; ++i) {
1780 LiveInterval *LI = NewLIs[i];
1781 if (!LI->empty()) {
1782 LI->weight /= LI->getSize();
Evan Chengb50bb8c2007-12-05 08:16:32 +00001783 if (!AddedKill.count(LI)) {
1784 LiveRange *LR = &LI->ranges[LI->ranges.size()-1];
Evan Chengd120ffd2007-12-05 10:24:35 +00001785 unsigned LastUseIdx = getBaseIndex(LR->end);
1786 MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx);
Evan Cheng6130f662008-03-05 00:59:57 +00001787 int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg, false);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001788 assert(UseIdx != -1);
Evan Chengd70dbb52008-02-22 09:24:50 +00001789 if (LastUse->getOperand(UseIdx).isImplicit() ||
1790 LastUse->getDesc().getOperandConstraint(UseIdx,TOI::TIED_TO) == -1){
Evan Chengb50bb8c2007-12-05 08:16:32 +00001791 LastUse->getOperand(UseIdx).setIsKill();
Evan Chengd120ffd2007-12-05 10:24:35 +00001792 vrm.addKillPoint(LI->reg, LastUseIdx);
Evan Chengadf85902007-12-05 09:51:10 +00001793 }
Evan Chengb50bb8c2007-12-05 08:16:32 +00001794 }
Evan Cheng597d10d2007-12-04 00:32:23 +00001795 RetNewLIs.push_back(LI);
1796 }
1797 }
Evan Cheng81a03822007-11-17 00:40:40 +00001798
Evan Cheng4cce6b42008-04-11 17:53:36 +00001799 handleSpilledImpDefs(li, vrm, rc, RetNewLIs);
Evan Cheng597d10d2007-12-04 00:32:23 +00001800 return RetNewLIs;
Evan Chengf2fbca62007-11-12 06:35:08 +00001801}
Evan Cheng676dd7c2008-03-11 07:19:34 +00001802
1803/// hasAllocatableSuperReg - Return true if the specified physical register has
1804/// any super register that's allocatable.
1805bool LiveIntervals::hasAllocatableSuperReg(unsigned Reg) const {
1806 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS)
1807 if (allocatableRegs_[*AS] && hasInterval(*AS))
1808 return true;
1809 return false;
1810}
1811
1812/// getRepresentativeReg - Find the largest super register of the specified
1813/// physical register.
1814unsigned LiveIntervals::getRepresentativeReg(unsigned Reg) const {
1815 // Find the largest super-register that is allocatable.
1816 unsigned BestReg = Reg;
1817 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS) {
1818 unsigned SuperReg = *AS;
1819 if (!hasAllocatableSuperReg(SuperReg) && hasInterval(SuperReg)) {
1820 BestReg = SuperReg;
1821 break;
1822 }
1823 }
1824 return BestReg;
1825}
1826
1827/// getNumConflictsWithPhysReg - Return the number of uses and defs of the
1828/// specified interval that conflicts with the specified physical register.
1829unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li,
1830 unsigned PhysReg) const {
1831 unsigned NumConflicts = 0;
1832 const LiveInterval &pli = getInterval(getRepresentativeReg(PhysReg));
1833 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
1834 E = mri_->reg_end(); I != E; ++I) {
1835 MachineOperand &O = I.getOperand();
1836 MachineInstr *MI = O.getParent();
1837 unsigned Index = getInstructionIndex(MI);
1838 if (pli.liveAt(Index))
1839 ++NumConflicts;
1840 }
1841 return NumConflicts;
1842}
1843
1844/// spillPhysRegAroundRegDefsUses - Spill the specified physical register
1845/// around all defs and uses of the specified interval.
1846void LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
1847 unsigned PhysReg, VirtRegMap &vrm) {
1848 unsigned SpillReg = getRepresentativeReg(PhysReg);
1849
1850 for (const unsigned *AS = tri_->getAliasSet(PhysReg); *AS; ++AS)
1851 // If there are registers which alias PhysReg, but which are not a
1852 // sub-register of the chosen representative super register. Assert
1853 // since we can't handle it yet.
1854 assert(*AS == SpillReg || !allocatableRegs_[*AS] ||
1855 tri_->isSuperRegister(*AS, SpillReg));
1856
1857 LiveInterval &pli = getInterval(SpillReg);
1858 SmallPtrSet<MachineInstr*, 8> SeenMIs;
1859 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
1860 E = mri_->reg_end(); I != E; ++I) {
1861 MachineOperand &O = I.getOperand();
1862 MachineInstr *MI = O.getParent();
1863 if (SeenMIs.count(MI))
1864 continue;
1865 SeenMIs.insert(MI);
1866 unsigned Index = getInstructionIndex(MI);
1867 if (pli.liveAt(Index)) {
1868 vrm.addEmergencySpill(SpillReg, MI);
1869 pli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
1870 for (const unsigned* AS = tri_->getSubRegisters(SpillReg); *AS; ++AS) {
1871 if (!hasInterval(*AS))
1872 continue;
1873 LiveInterval &spli = getInterval(*AS);
1874 if (spli.liveAt(Index))
1875 spli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
1876 }
1877 }
1878 }
1879}
Owen Andersonc4dc1322008-06-05 17:15:43 +00001880
1881LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
1882 MachineInstr* startInst) {
1883 LiveInterval& Interval = getOrCreateInterval(reg);
1884 VNInfo* VN = Interval.getNextValue(
1885 getInstructionIndex(startInst) + InstrSlots::DEF,
1886 startInst, getVNInfoAllocator());
1887 VN->hasPHIKill = true;
1888 VN->kills.push_back(getMBBEndIdx(startInst->getParent()));
1889 LiveRange LR(getInstructionIndex(startInst) + InstrSlots::DEF,
1890 getMBBEndIdx(startInst->getParent()) + 1, VN);
1891 Interval.addRange(LR);
1892
1893 return LR;
1894}