blob: fba441666625c79d66d607ff8d49cab2685ab430 [file] [log] [blame]
Chris Lattnera3b8b5c2004-07-23 17:56:30 +00001//===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the LiveInterval analysis pass which is used
11// by the Linear Scan Register allocator. This pass linearizes the
12// basic blocks of the function in DFS order and uses the
13// LiveVariables pass to conservatively compute live intervals for
14// each virtual and physical register.
15//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "liveintervals"
Chris Lattner3c3fe462005-09-21 04:19:09 +000019#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Misha Brukman08a6c762004-09-03 18:25:53 +000020#include "VirtRegMap.h"
Chris Lattner015959e2004-05-01 21:24:39 +000021#include "llvm/Value.h"
Dan Gohman6d69ba82008-07-25 00:02:30 +000022#include "llvm/Analysis/AliasAnalysis.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000023#include "llvm/CodeGen/LiveVariables.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000025#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000026#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000027#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000028#include "llvm/CodeGen/Passes.h"
Dan Gohman6d69ba82008-07-25 00:02:30 +000029#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000030#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000031#include "llvm/Target/TargetInstrInfo.h"
32#include "llvm/Target/TargetMachine.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/ADT/Statistic.h"
36#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000037#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000038#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000039using namespace llvm;
40
Dan Gohman844731a2008-05-13 00:00:25 +000041// Hidden options for help debugging.
42static cl::opt<bool> DisableReMat("disable-rematerialization",
43 cl::init(false), cl::Hidden);
Evan Cheng81a03822007-11-17 00:40:40 +000044
Dan Gohman844731a2008-05-13 00:00:25 +000045static cl::opt<bool> SplitAtBB("split-intervals-at-bb",
46 cl::init(true), cl::Hidden);
47static cl::opt<int> SplitLimit("split-limit",
48 cl::init(-1), cl::Hidden);
Evan Chengbc165e42007-08-16 07:24:22 +000049
Dan Gohman4c8f8702008-07-25 15:08:37 +000050static cl::opt<bool> EnableAggressiveRemat("aggressive-remat", cl::Hidden);
51
Chris Lattnercd3245a2006-12-19 22:41:21 +000052STATISTIC(numIntervals, "Number of original intervals");
53STATISTIC(numIntervalsAfter, "Number of intervals after coalescing");
Evan Cheng0cbb1162007-11-29 01:06:25 +000054STATISTIC(numFolds , "Number of loads/stores folded into instructions");
55STATISTIC(numSplits , "Number of intervals split");
Chris Lattnercd3245a2006-12-19 22:41:21 +000056
Devang Patel19974732007-05-03 01:11:54 +000057char LiveIntervals::ID = 0;
Dan Gohman844731a2008-05-13 00:00:25 +000058static RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000059
Chris Lattnerf7da2c72006-08-24 22:43:55 +000060void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman6d69ba82008-07-25 00:02:30 +000061 AU.addRequired<AliasAnalysis>();
62 AU.addPreserved<AliasAnalysis>();
David Greene25133302007-06-08 17:18:56 +000063 AU.addPreserved<LiveVariables>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000064 AU.addRequired<LiveVariables>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000065 AU.addPreservedID(MachineLoopInfoID);
66 AU.addPreservedID(MachineDominatorsID);
Owen Andersonfcc63502008-05-29 18:35:21 +000067 AU.addPreservedID(PHIEliminationID);
68 AU.addRequiredID(PHIEliminationID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000069 AU.addRequiredID(TwoAddressInstructionPassID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000070 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000071}
72
Chris Lattnerf7da2c72006-08-24 22:43:55 +000073void LiveIntervals::releaseMemory() {
Evan Cheng3f32d652008-06-04 09:18:41 +000074 MBB2IdxMap.clear();
Evan Cheng4ca980e2007-10-17 02:10:22 +000075 Idx2MBBMap.clear();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000076 mi2iMap_.clear();
77 i2miMap_.clear();
78 r2iMap_.clear();
Evan Chengdd199d22007-09-06 01:07:24 +000079 // Release VNInfo memroy regions after all VNInfo objects are dtor'd.
80 VNInfoAllocator.Reset();
Evan Cheng1ed99222008-07-19 00:37:25 +000081 while (!ClonedMIs.empty()) {
82 MachineInstr *MI = ClonedMIs.back();
83 ClonedMIs.pop_back();
84 mf_->DeleteMachineInstr(MI);
85 }
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000086}
87
Owen Anderson80b3ce62008-05-28 20:54:50 +000088void LiveIntervals::computeNumbering() {
89 Index2MiMap OldI2MI = i2miMap_;
Owen Anderson7fbad272008-07-23 21:37:49 +000090 std::vector<IdxMBBPair> OldI2MBB = Idx2MBBMap;
Owen Anderson80b3ce62008-05-28 20:54:50 +000091
92 Idx2MBBMap.clear();
93 MBB2IdxMap.clear();
94 mi2iMap_.clear();
95 i2miMap_.clear();
96
Owen Andersona1566f22008-07-22 22:46:49 +000097 FunctionSize = 0;
98
Chris Lattner428b92e2006-09-15 03:57:23 +000099 // Number MachineInstrs and MachineBasicBlocks.
100 // Initialize MBB indexes to a sentinal.
Evan Cheng549f27d32007-08-13 23:45:17 +0000101 MBB2IdxMap.resize(mf_->getNumBlockIDs(), std::make_pair(~0U,~0U));
Chris Lattner428b92e2006-09-15 03:57:23 +0000102
103 unsigned MIIndex = 0;
104 for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
105 MBB != E; ++MBB) {
Evan Cheng549f27d32007-08-13 23:45:17 +0000106 unsigned StartIdx = MIIndex;
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000107
Owen Anderson7fbad272008-07-23 21:37:49 +0000108 // Insert an empty slot at the beginning of each block.
109 MIIndex += InstrSlots::NUM;
110 i2miMap_.push_back(0);
111
Chris Lattner428b92e2006-09-15 03:57:23 +0000112 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
113 I != E; ++I) {
114 bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000115 assert(inserted && "multiple MachineInstr -> index mappings");
Chris Lattner428b92e2006-09-15 03:57:23 +0000116 i2miMap_.push_back(I);
117 MIIndex += InstrSlots::NUM;
Owen Andersona1566f22008-07-22 22:46:49 +0000118 FunctionSize++;
Owen Anderson7fbad272008-07-23 21:37:49 +0000119
120 // Insert an empty slot after every instruction.
Owen Anderson1fbb4542008-06-16 16:58:24 +0000121 MIIndex += InstrSlots::NUM;
122 i2miMap_.push_back(0);
Owen Anderson35578012008-06-16 07:10:49 +0000123 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000124
Owen Anderson1fbb4542008-06-16 16:58:24 +0000125 // Set the MBB2IdxMap entry for this MBB.
126 MBB2IdxMap[MBB->getNumber()] = std::make_pair(StartIdx, MIIndex - 1);
127 Idx2MBBMap.push_back(std::make_pair(StartIdx, MBB));
Chris Lattner428b92e2006-09-15 03:57:23 +0000128 }
Evan Cheng4ca980e2007-10-17 02:10:22 +0000129 std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
Owen Anderson80b3ce62008-05-28 20:54:50 +0000130
131 if (!OldI2MI.empty())
Owen Anderson7fbad272008-07-23 21:37:49 +0000132 for (iterator OI = begin(), OE = end(); OI != OE; ++OI)
133 for (LiveInterval::iterator LI = OI->second.begin(),
134 LE = OI->second.end(); LI != LE; ++LI) {
Owen Anderson4b5b2092008-05-29 18:15:49 +0000135
Owen Anderson7eec0c22008-05-29 23:01:22 +0000136 // Remap the start index of the live range to the corresponding new
137 // number, or our best guess at what it _should_ correspond to if the
138 // original instruction has been erased. This is either the following
139 // instruction or its predecessor.
Owen Anderson7fbad272008-07-23 21:37:49 +0000140 unsigned index = LI->start / InstrSlots::NUM;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000141 unsigned offset = LI->start % InstrSlots::NUM;
Owen Anderson0a7615a2008-07-25 23:06:59 +0000142 if (offset == InstrSlots::LOAD) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000143 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000144 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->start);
Owen Anderson7fbad272008-07-23 21:37:49 +0000145 // Take the pair containing the index
146 std::vector<IdxMBBPair>::const_iterator J =
Owen Andersona0c032f2008-07-29 21:15:44 +0000147 (I == OldI2MBB.end() && OldI2MBB.size()>0) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000148
Owen Anderson7fbad272008-07-23 21:37:49 +0000149 LI->start = getMBBStartIdx(J->second);
150 } else {
151 LI->start = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000152 }
153
154 // Remap the ending index in the same way that we remapped the start,
155 // except for the final step where we always map to the immediately
156 // following instruction.
Owen Andersond7dcbec2008-07-25 19:50:48 +0000157 index = (LI->end - 1) / InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000158 offset = LI->end % InstrSlots::NUM;
Owen Anderson9382b932008-07-30 00:22:56 +0000159 if (offset == InstrSlots::LOAD) {
160 // VReg dies at end of block.
Owen Anderson7fbad272008-07-23 21:37:49 +0000161 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000162 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->end);
Owen Anderson9382b932008-07-30 00:22:56 +0000163 --I;
Owen Anderson7fbad272008-07-23 21:37:49 +0000164
Owen Anderson9382b932008-07-30 00:22:56 +0000165 LI->end = getMBBEndIdx(I->second) + 1;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000166 } else {
Owen Andersond7dcbec2008-07-25 19:50:48 +0000167 unsigned idx = index;
Owen Anderson8d0cc0a2008-07-25 21:07:13 +0000168 while (index < OldI2MI.size() && !OldI2MI[index]) ++index;
169
170 if (index != OldI2MI.size())
171 LI->end = mi2iMap_[OldI2MI[index]] + (idx == index ? offset : 0);
172 else
173 LI->end = InstrSlots::NUM * i2miMap_.size();
Owen Anderson4b5b2092008-05-29 18:15:49 +0000174 }
Owen Anderson745825f42008-05-28 22:40:08 +0000175
Owen Anderson7eec0c22008-05-29 23:01:22 +0000176 // Remap the VNInfo def index, which works the same as the
177 // start indices above.
Owen Anderson745825f42008-05-28 22:40:08 +0000178 VNInfo* vni = LI->valno;
Owen Anderson91292392008-07-30 17:42:47 +0000179
180 // VN's with special sentinel defs don't need to be remapped.
181 if (vni->def != ~0U && vni->def != ~1U) {
182 index = vni->def / InstrSlots::NUM;
183 offset = vni->def % InstrSlots::NUM;
184 if (offset == InstrSlots::LOAD) {
185 std::vector<IdxMBBPair>::const_iterator I =
Owen Anderson0a7615a2008-07-25 23:06:59 +0000186 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->def);
Owen Anderson91292392008-07-30 17:42:47 +0000187 // Take the pair containing the index
188 std::vector<IdxMBBPair>::const_iterator J =
Owen Andersona0c032f2008-07-29 21:15:44 +0000189 (I == OldI2MBB.end() && OldI2MBB.size()>0) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000190
Owen Anderson91292392008-07-30 17:42:47 +0000191 vni->def = getMBBStartIdx(J->second);
192 } else {
193 vni->def = mi2iMap_[OldI2MI[index]] + offset;
194 }
Owen Anderson7eec0c22008-05-29 23:01:22 +0000195 }
Owen Anderson745825f42008-05-28 22:40:08 +0000196
Owen Anderson7eec0c22008-05-29 23:01:22 +0000197 // Remap the VNInfo kill indices, which works the same as
198 // the end indices above.
Owen Anderson4b5b2092008-05-29 18:15:49 +0000199 for (size_t i = 0; i < vni->kills.size(); ++i) {
Owen Anderson9382b932008-07-30 00:22:56 +0000200 // PHI kills don't need to be remapped.
201 if (!vni->kills[i]) continue;
202
Owen Andersond7dcbec2008-07-25 19:50:48 +0000203 index = (vni->kills[i]-1) / InstrSlots::NUM;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000204 offset = vni->kills[i] % InstrSlots::NUM;
Owen Anderson9382b932008-07-30 00:22:56 +0000205 if (offset == InstrSlots::LOAD) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000206 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000207 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->kills[i]);
Owen Anderson9382b932008-07-30 00:22:56 +0000208 --I;
Owen Anderson7fbad272008-07-23 21:37:49 +0000209
Owen Anderson9382b932008-07-30 00:22:56 +0000210 vni->kills[i] = getMBBEndIdx(I->second) + 1;
Owen Anderson7fbad272008-07-23 21:37:49 +0000211 } else {
Owen Andersond7dcbec2008-07-25 19:50:48 +0000212 unsigned idx = index;
Owen Anderson8d0cc0a2008-07-25 21:07:13 +0000213 while (index < OldI2MI.size() && !OldI2MI[index]) ++index;
214
215 if (index != OldI2MI.size())
216 vni->kills[i] = mi2iMap_[OldI2MI[index]] +
217 (idx == index ? offset : 0);
218 else
219 vni->kills[i] = InstrSlots::NUM * i2miMap_.size();
Owen Anderson7eec0c22008-05-29 23:01:22 +0000220 }
Owen Anderson4b5b2092008-05-29 18:15:49 +0000221 }
Owen Anderson80b3ce62008-05-28 20:54:50 +0000222 }
223}
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000224
Owen Anderson80b3ce62008-05-28 20:54:50 +0000225/// runOnMachineFunction - Register allocate the whole function
226///
227bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
228 mf_ = &fn;
229 mri_ = &mf_->getRegInfo();
230 tm_ = &fn.getTarget();
231 tri_ = tm_->getRegisterInfo();
232 tii_ = tm_->getInstrInfo();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000233 aa_ = &getAnalysis<AliasAnalysis>();
Owen Anderson80b3ce62008-05-28 20:54:50 +0000234 lv_ = &getAnalysis<LiveVariables>();
235 allocatableRegs_ = tri_->getAllocatableSet(fn);
236
237 computeNumbering();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000238 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000239
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000240 numIntervals += getNumIntervals();
241
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000242 DOUT << "********** INTERVALS **********\n";
243 for (iterator I = begin(), E = end(); I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000244 I->second.print(DOUT, tri_);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000245 DOUT << "\n";
246 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000247
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000248 numIntervalsAfter += getNumIntervals();
Chris Lattner70ca3582004-09-30 15:59:17 +0000249 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000250 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000251}
252
Chris Lattner70ca3582004-09-30 15:59:17 +0000253/// print - Implement the dump method.
Reid Spencerce9653c2004-12-07 04:03:45 +0000254void LiveIntervals::print(std::ostream &O, const Module* ) const {
Chris Lattner70ca3582004-09-30 15:59:17 +0000255 O << "********** INTERVALS **********\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000256 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Evan Cheng3f32d652008-06-04 09:18:41 +0000257 I->second.print(O, tri_);
258 O << "\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000259 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000260
261 O << "********** MACHINEINSTRS **********\n";
262 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
263 mbbi != mbbe; ++mbbi) {
264 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
265 for (MachineBasicBlock::iterator mii = mbbi->begin(),
266 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner477e4552004-09-30 16:10:45 +0000267 O << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner70ca3582004-09-30 15:59:17 +0000268 }
269 }
270}
271
Evan Chengc92da382007-11-03 07:20:12 +0000272/// conflictsWithPhysRegDef - Returns true if the specified register
273/// is defined during the duration of the specified interval.
274bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
275 VirtRegMap &vrm, unsigned reg) {
276 for (LiveInterval::Ranges::const_iterator
277 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
278 for (unsigned index = getBaseIndex(I->start),
279 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
280 index += InstrSlots::NUM) {
281 // skip deleted instructions
282 while (index != end && !getInstructionFromIndex(index))
283 index += InstrSlots::NUM;
284 if (index == end) break;
285
286 MachineInstr *MI = getInstructionFromIndex(index);
Evan Cheng5d446262007-11-15 08:13:29 +0000287 unsigned SrcReg, DstReg;
288 if (tii_->isMoveInstr(*MI, SrcReg, DstReg))
289 if (SrcReg == li.reg || DstReg == li.reg)
290 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000291 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
292 MachineOperand& mop = MI->getOperand(i);
Evan Cheng5d446262007-11-15 08:13:29 +0000293 if (!mop.isRegister())
Evan Chengc92da382007-11-03 07:20:12 +0000294 continue;
295 unsigned PhysReg = mop.getReg();
Evan Cheng5d446262007-11-15 08:13:29 +0000296 if (PhysReg == 0 || PhysReg == li.reg)
Evan Chengc92da382007-11-03 07:20:12 +0000297 continue;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000298 if (TargetRegisterInfo::isVirtualRegister(PhysReg)) {
Evan Cheng5d446262007-11-15 08:13:29 +0000299 if (!vrm.hasPhys(PhysReg))
300 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000301 PhysReg = vrm.getPhys(PhysReg);
Evan Cheng5d446262007-11-15 08:13:29 +0000302 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000303 if (PhysReg && tri_->regsOverlap(PhysReg, reg))
Evan Chengc92da382007-11-03 07:20:12 +0000304 return true;
305 }
306 }
307 }
308
309 return false;
310}
311
Evan Cheng549f27d32007-08-13 23:45:17 +0000312void LiveIntervals::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000313 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000314 cerr << tri_->getName(reg);
Evan Cheng549f27d32007-08-13 23:45:17 +0000315 else
316 cerr << "%reg" << reg;
317}
318
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000319void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000320 MachineBasicBlock::iterator mi,
Owen Anderson6b098de2008-06-25 23:39:39 +0000321 unsigned MIIdx, MachineOperand& MO,
Evan Chengef0732d2008-07-10 07:35:43 +0000322 unsigned MOIdx,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000323 LiveInterval &interval) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000324 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000325 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000326
Evan Cheng419852c2008-04-03 16:39:43 +0000327 if (mi->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
328 DOUT << "is a implicit_def\n";
329 return;
330 }
331
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000332 // Virtual registers may be defined multiple times (due to phi
333 // elimination and 2-addr elimination). Much of what we do only has to be
334 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000335 // time we see a vreg.
336 if (interval.empty()) {
337 // Get the Idx of the defining instructions.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000338 unsigned defIndex = getDefIndex(MIIdx);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000339 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000340 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000341 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000342 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000343 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000344 tii_->isMoveInstr(*mi, SrcReg, DstReg))
345 CopyMI = mi;
346 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000347
348 assert(ValNo->id == 0 && "First value in interval is not 0?");
Chris Lattner7ac2d312004-07-24 02:59:07 +0000349
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000350 // Loop over all of the blocks that the vreg is defined in. There are
351 // two cases we have to handle here. The most common case is a vreg
352 // whose lifetime is contained within a basic block. In this case there
353 // will be a single kill, in MBB, which comes after the definition.
354 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
355 // FIXME: what about dead vars?
356 unsigned killIdx;
357 if (vi.Kills[0] != mi)
358 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
359 else
360 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000361
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000362 // If the kill happens after the definition, we have an intra-block
363 // live range.
364 if (killIdx > defIndex) {
Evan Cheng61de82d2007-02-15 05:59:24 +0000365 assert(vi.AliveBlocks.none() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000366 "Shouldn't be alive across any blocks!");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000367 LiveRange LR(defIndex, killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000368 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000369 DOUT << " +" << LR << "\n";
Evan Chengf3bb2e62007-09-05 21:46:51 +0000370 interval.addKill(ValNo, killIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000371 return;
372 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000373 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000374
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000375 // The other case we handle is when a virtual register lives to the end
376 // of the defining block, potentially live across some blocks, then is
377 // live into some number of blocks, but gets killed. Start by adding a
378 // range that goes from this definition to the end of the defining block.
Owen Anderson7fbad272008-07-23 21:37:49 +0000379 LiveRange NewLR(defIndex, getMBBEndIdx(mbb)+1, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000380 DOUT << " +" << NewLR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000381 interval.addRange(NewLR);
382
383 // Iterate over all of the blocks that the variable is completely
384 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
385 // live interval.
386 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
387 if (vi.AliveBlocks[i]) {
Owen Anderson31ec8412008-06-16 19:32:40 +0000388 LiveRange LR(getMBBStartIdx(i),
Evan Chengf26e8552008-06-17 20:13:36 +0000389 getMBBEndIdx(i)+1, // MBB ends at -1.
Owen Anderson31ec8412008-06-16 19:32:40 +0000390 ValNo);
391 interval.addRange(LR);
392 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000393 }
394 }
395
396 // Finally, this virtual register is live from the start of any killing
397 // block to the 'use' slot of the killing instruction.
398 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
399 MachineInstr *Kill = vi.Kills[i];
Evan Cheng8df78602007-08-08 03:00:28 +0000400 unsigned killIdx = getUseIndex(getInstructionIndex(Kill))+1;
Chris Lattner428b92e2006-09-15 03:57:23 +0000401 LiveRange LR(getMBBStartIdx(Kill->getParent()),
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000402 killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000403 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000404 interval.addKill(ValNo, killIdx);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000405 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000406 }
407
408 } else {
409 // If this is the second time we see a virtual register definition, it
410 // must be due to phi elimination or two addr elimination. If this is
Evan Chengbf105c82006-11-03 03:04:46 +0000411 // the result of two address elimination, then the vreg is one of the
412 // def-and-use register operand.
Evan Chengef0732d2008-07-10 07:35:43 +0000413 if (mi->isRegReDefinedByTwoAddr(interval.reg, MOIdx)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000414 // If this is a two-address definition, then we have already processed
415 // the live range. The only problem is that we didn't realize there
416 // are actually two values in the live interval. Because of this we
417 // need to take the LiveRegion that defines this register and split it
418 // into two values.
Evan Chenga07cec92008-01-10 08:22:10 +0000419 assert(interval.containsOneValue());
420 unsigned DefIndex = getDefIndex(interval.getValNumInfo(0)->def);
Chris Lattner6b128bd2006-09-03 08:07:11 +0000421 unsigned RedefIndex = getDefIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000422
Evan Cheng4f8ff162007-08-11 00:59:19 +0000423 const LiveRange *OldLR = interval.getLiveRangeContaining(RedefIndex-1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000424 VNInfo *OldValNo = OldLR->valno;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000425
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000426 // Delete the initial value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000427 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000428 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000429
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000430 // Two-address vregs should always only be redefined once. This means
431 // that at this point, there should be exactly one value number in it.
432 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
433
Chris Lattner91725b72006-08-31 05:54:43 +0000434 // The new value number (#1) is defined by the instruction we claimed
435 // defined value #0.
Evan Chengc8d044e2008-02-15 18:24:29 +0000436 VNInfo *ValNo = interval.getNextValue(OldValNo->def, OldValNo->copy,
437 VNInfoAllocator);
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000438
Chris Lattner91725b72006-08-31 05:54:43 +0000439 // Value#0 is now defined by the 2-addr instruction.
Evan Chengc8d044e2008-02-15 18:24:29 +0000440 OldValNo->def = RedefIndex;
441 OldValNo->copy = 0;
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000442
443 // Add the new live interval which replaces the range for the input copy.
444 LiveRange LR(DefIndex, RedefIndex, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000445 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000446 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000447 interval.addKill(ValNo, RedefIndex);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000448
449 // If this redefinition is dead, we need to add a dummy unit live
450 // range covering the def slot.
Owen Anderson6b098de2008-06-25 23:39:39 +0000451 if (MO.isDead())
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000452 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, OldValNo));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000453
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000454 DOUT << " RESULT: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000455 interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000456
457 } else {
458 // Otherwise, this must be because of phi elimination. If this is the
459 // first redefinition of the vreg that we have seen, go back and change
460 // the live range in the PHI block to be a different value number.
461 if (interval.containsOneValue()) {
462 assert(vi.Kills.size() == 1 &&
463 "PHI elimination vreg should have one kill, the PHI itself!");
464
465 // Remove the old range that we now know has an incorrect number.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000466 VNInfo *VNI = interval.getValNumInfo(0);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000467 MachineInstr *Killer = vi.Kills[0];
Chris Lattner428b92e2006-09-15 03:57:23 +0000468 unsigned Start = getMBBStartIdx(Killer->getParent());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000469 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000470 DOUT << " Removing [" << Start << "," << End << "] from: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000471 interval.print(DOUT, tri_); DOUT << "\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000472 interval.removeRange(Start, End);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000473 VNI->hasPHIKill = true;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000474 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000475
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000476 // Replace the interval with one of a NEW value number. Note that this
477 // value number isn't actually defined by an instruction, weird huh? :)
Evan Chengf3bb2e62007-09-05 21:46:51 +0000478 LiveRange LR(Start, End, interval.getNextValue(~0, 0, VNInfoAllocator));
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000479 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000480 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000481 interval.addKill(LR.valno, End);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000482 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000483 }
484
485 // In the case of PHI elimination, each variable definition is only
486 // live until the end of the block. We've already taken care of the
487 // rest of the live range.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000488 unsigned defIndex = getDefIndex(MIIdx);
Chris Lattner91725b72006-08-31 05:54:43 +0000489
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000490 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000491 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000492 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000493 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000494 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000495 tii_->isMoveInstr(*mi, SrcReg, DstReg))
496 CopyMI = mi;
497 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Chris Lattner91725b72006-08-31 05:54:43 +0000498
Owen Anderson7fbad272008-07-23 21:37:49 +0000499 unsigned killIndex = getMBBEndIdx(mbb) + 1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000500 LiveRange LR(defIndex, killIndex, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000501 interval.addRange(LR);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000502 interval.addKill(ValNo, killIndex);
503 ValNo->hasPHIKill = true;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000504 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000505 }
506 }
507
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000508 DOUT << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000509}
510
Chris Lattnerf35fef72004-07-23 21:24:19 +0000511void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000512 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000513 unsigned MIIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000514 MachineOperand& MO,
Chris Lattner91725b72006-08-31 05:54:43 +0000515 LiveInterval &interval,
Evan Chengc8d044e2008-02-15 18:24:29 +0000516 MachineInstr *CopyMI) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000517 // A physical register cannot be live across basic block, so its
518 // lifetime must end somewhere in its defining basic block.
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000519 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000520
Chris Lattner6b128bd2006-09-03 08:07:11 +0000521 unsigned baseIndex = MIIdx;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000522 unsigned start = getDefIndex(baseIndex);
523 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000524
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000525 // If it is not used after definition, it is considered dead at
526 // the instruction defining it. Hence its interval is:
527 // [defSlot(def), defSlot(def)+1)
Owen Anderson6b098de2008-06-25 23:39:39 +0000528 if (MO.isDead()) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000529 DOUT << " dead";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000530 end = getDefIndex(start) + 1;
531 goto exit;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000532 }
533
534 // If it is not dead on definition, it must be killed by a
535 // subsequent instruction. Hence its interval is:
536 // [defSlot(def), useSlot(kill)+1)
Owen Anderson7fbad272008-07-23 21:37:49 +0000537 baseIndex += InstrSlots::NUM;
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000538 while (++mi != MBB->end()) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000539 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
540 getInstructionFromIndex(baseIndex) == 0)
541 baseIndex += InstrSlots::NUM;
Evan Cheng6130f662008-03-05 00:59:57 +0000542 if (mi->killsRegister(interval.reg, tri_)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000543 DOUT << " killed";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000544 end = getUseIndex(baseIndex) + 1;
545 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000546 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Cheng9a1956a2006-11-15 20:54:11 +0000547 // Another instruction redefines the register before it is ever read.
548 // Then the register is essentially dead at the instruction that defines
549 // it. Hence its interval is:
550 // [defSlot(def), defSlot(def)+1)
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000551 DOUT << " dead";
Evan Cheng9a1956a2006-11-15 20:54:11 +0000552 end = getDefIndex(start) + 1;
553 goto exit;
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000554 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000555
556 baseIndex += InstrSlots::NUM;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000557 }
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000558
559 // The only case we should have a dead physreg here without a killing or
560 // instruction where we know it's dead is if it is live-in to the function
561 // and never used.
Evan Chengc8d044e2008-02-15 18:24:29 +0000562 assert(!CopyMI && "physreg was not killed in defining block!");
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000563 end = getDefIndex(start) + 1; // It's dead.
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000564
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000565exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000566 assert(start < end && "did not find end of interval?");
Chris Lattnerf768bba2005-03-09 23:05:19 +0000567
Evan Cheng24a3cc42007-04-25 07:30:23 +0000568 // Already exists? Extend old live interval.
569 LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000570 VNInfo *ValNo = (OldLR != interval.end())
Evan Chengc8d044e2008-02-15 18:24:29 +0000571 ? OldLR->valno : interval.getNextValue(start, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000572 LiveRange LR(start, end, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000573 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000574 interval.addKill(LR.valno, end);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000575 DOUT << " +" << LR << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000576}
577
Chris Lattnerf35fef72004-07-23 21:24:19 +0000578void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
579 MachineBasicBlock::iterator MI,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000580 unsigned MIIdx,
Evan Chengef0732d2008-07-10 07:35:43 +0000581 MachineOperand& MO,
582 unsigned MOIdx) {
Owen Anderson6b098de2008-06-25 23:39:39 +0000583 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Evan Chengef0732d2008-07-10 07:35:43 +0000584 handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000585 getOrCreateInterval(MO.getReg()));
586 else if (allocatableRegs_[MO.getReg()]) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000587 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000588 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000589 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000590 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000591 tii_->isMoveInstr(*MI, SrcReg, DstReg))
592 CopyMI = MI;
Owen Anderson6b098de2008-06-25 23:39:39 +0000593 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
594 getOrCreateInterval(MO.getReg()), CopyMI);
Evan Cheng24a3cc42007-04-25 07:30:23 +0000595 // Def of a register also defines its sub-registers.
Owen Anderson6b098de2008-06-25 23:39:39 +0000596 for (const unsigned* AS = tri_->getSubRegisters(MO.getReg()); *AS; ++AS)
Evan Cheng6130f662008-03-05 00:59:57 +0000597 // If MI also modifies the sub-register explicitly, avoid processing it
598 // more than once. Do not pass in TRI here so it checks for exact match.
599 if (!MI->modifiesRegister(*AS))
Owen Anderson6b098de2008-06-25 23:39:39 +0000600 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
601 getOrCreateInterval(*AS), 0);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000602 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000603}
604
Evan Chengb371f452007-02-19 21:49:54 +0000605void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000606 unsigned MIIdx,
Evan Cheng24a3cc42007-04-25 07:30:23 +0000607 LiveInterval &interval, bool isAlias) {
Evan Chengb371f452007-02-19 21:49:54 +0000608 DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg));
609
610 // Look for kills, if it reaches a def before it's killed, then it shouldn't
611 // be considered a livein.
612 MachineBasicBlock::iterator mi = MBB->begin();
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000613 unsigned baseIndex = MIIdx;
614 unsigned start = baseIndex;
Evan Chengb371f452007-02-19 21:49:54 +0000615 unsigned end = start;
616 while (mi != MBB->end()) {
Evan Cheng6130f662008-03-05 00:59:57 +0000617 if (mi->killsRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000618 DOUT << " killed";
619 end = getUseIndex(baseIndex) + 1;
620 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000621 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000622 // Another instruction redefines the register before it is ever read.
623 // Then the register is essentially dead at the instruction that defines
624 // it. Hence its interval is:
625 // [defSlot(def), defSlot(def)+1)
626 DOUT << " dead";
627 end = getDefIndex(start) + 1;
628 goto exit;
629 }
630
631 baseIndex += InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000632 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
633 getInstructionFromIndex(baseIndex) == 0)
634 baseIndex += InstrSlots::NUM;
Evan Chengb371f452007-02-19 21:49:54 +0000635 ++mi;
636 }
637
638exit:
Evan Cheng75611fb2007-06-27 01:16:36 +0000639 // Live-in register might not be used at all.
640 if (end == MIIdx) {
Evan Cheng292da942007-06-27 18:47:28 +0000641 if (isAlias) {
642 DOUT << " dead";
Evan Cheng75611fb2007-06-27 01:16:36 +0000643 end = getDefIndex(MIIdx) + 1;
Evan Cheng292da942007-06-27 18:47:28 +0000644 } else {
645 DOUT << " live through";
646 end = baseIndex;
647 }
Evan Cheng24a3cc42007-04-25 07:30:23 +0000648 }
649
Evan Chengf3bb2e62007-09-05 21:46:51 +0000650 LiveRange LR(start, end, interval.getNextValue(start, 0, VNInfoAllocator));
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000651 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000652 interval.addKill(LR.valno, end);
Evan Cheng24c2e5c2007-08-08 07:03:29 +0000653 DOUT << " +" << LR << '\n';
Evan Chengb371f452007-02-19 21:49:54 +0000654}
655
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000656/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000657/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000658/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000659/// which a variable is live
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000660void LiveIntervals::computeIntervals() {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000661 DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
662 << "********** Function: "
663 << ((Value*)mf_->getFunction())->getName() << '\n';
Chris Lattner6b128bd2006-09-03 08:07:11 +0000664 // Track the index of the current machine instr.
665 unsigned MIIndex = 0;
Owen Anderson7fbad272008-07-23 21:37:49 +0000666
667 // Skip over empty initial indices.
668 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
669 getInstructionFromIndex(MIIndex) == 0)
670 MIIndex += InstrSlots::NUM;
671
Chris Lattner428b92e2006-09-15 03:57:23 +0000672 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
673 MBBI != E; ++MBBI) {
674 MachineBasicBlock *MBB = MBBI;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000675 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000676
Chris Lattner428b92e2006-09-15 03:57:23 +0000677 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000678
Dan Gohmancb406c22007-10-03 19:26:29 +0000679 // Create intervals for live-ins to this BB first.
680 for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
681 LE = MBB->livein_end(); LI != LE; ++LI) {
682 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
683 // Multiple live-ins can alias the same register.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000684 for (const unsigned* AS = tri_->getSubRegisters(*LI); *AS; ++AS)
Dan Gohmancb406c22007-10-03 19:26:29 +0000685 if (!hasInterval(*AS))
686 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
687 true);
Chris Lattnerdffb2e82006-09-04 18:27:40 +0000688 }
689
Chris Lattner428b92e2006-09-15 03:57:23 +0000690 for (; MI != miEnd; ++MI) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000691 DOUT << MIIndex << "\t" << *MI;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000692
Evan Cheng438f7bc2006-11-10 08:43:01 +0000693 // Handle defs.
Chris Lattner428b92e2006-09-15 03:57:23 +0000694 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
695 MachineOperand &MO = MI->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000696 // handle register defs - build intervals
Chris Lattner428b92e2006-09-15 03:57:23 +0000697 if (MO.isRegister() && MO.getReg() && MO.isDef())
Evan Chengef0732d2008-07-10 07:35:43 +0000698 handleRegisterDef(MBB, MI, MIIndex, MO, i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000699 }
Chris Lattner6b128bd2006-09-03 08:07:11 +0000700
701 MIIndex += InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000702
703 // Skip over empty indices.
704 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
705 getInstructionFromIndex(MIIndex) == 0)
706 MIIndex += InstrSlots::NUM;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000707 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000708 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000709}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000710
Evan Cheng4ca980e2007-10-17 02:10:22 +0000711bool LiveIntervals::findLiveInMBBs(const LiveRange &LR,
Evan Chenga5bfc972007-10-17 06:53:44 +0000712 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
Evan Cheng4ca980e2007-10-17 02:10:22 +0000713 std::vector<IdxMBBPair>::const_iterator I =
714 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), LR.start);
715
716 bool ResVal = false;
717 while (I != Idx2MBBMap.end()) {
718 if (LR.end <= I->first)
719 break;
720 MBBs.push_back(I->second);
721 ResVal = true;
722 ++I;
723 }
724 return ResVal;
725}
726
727
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000728LiveInterval LiveIntervals::createInterval(unsigned reg) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000729 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
Jim Laskey7902c752006-11-07 12:25:45 +0000730 HUGE_VALF : 0.0F;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000731 return LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000732}
Evan Chengf2fbca62007-11-12 06:35:08 +0000733
Evan Chengc8d044e2008-02-15 18:24:29 +0000734/// getVNInfoSourceReg - Helper function that parses the specified VNInfo
735/// copy field and returns the source register that defines it.
736unsigned LiveIntervals::getVNInfoSourceReg(const VNInfo *VNI) const {
737 if (!VNI->copy)
738 return 0;
739
740 if (VNI->copy->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
741 return VNI->copy->getOperand(1).getReg();
Evan Cheng7e073ba2008-04-09 20:57:25 +0000742 if (VNI->copy->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
743 return VNI->copy->getOperand(2).getReg();
Evan Chengc8d044e2008-02-15 18:24:29 +0000744 unsigned SrcReg, DstReg;
745 if (tii_->isMoveInstr(*VNI->copy, SrcReg, DstReg))
746 return SrcReg;
747 assert(0 && "Unrecognized copy instruction!");
748 return 0;
749}
Evan Chengf2fbca62007-11-12 06:35:08 +0000750
751//===----------------------------------------------------------------------===//
752// Register allocator hooks.
753//
754
Evan Chengd70dbb52008-02-22 09:24:50 +0000755/// getReMatImplicitUse - If the remat definition MI has one (for now, we only
756/// allow one) virtual register operand, then its uses are implicitly using
757/// the register. Returns the virtual register.
758unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
759 MachineInstr *MI) const {
760 unsigned RegOp = 0;
761 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
762 MachineOperand &MO = MI->getOperand(i);
763 if (!MO.isRegister() || !MO.isUse())
764 continue;
765 unsigned Reg = MO.getReg();
766 if (Reg == 0 || Reg == li.reg)
767 continue;
768 // FIXME: For now, only remat MI with at most one register operand.
769 assert(!RegOp &&
770 "Can't rematerialize instruction with multiple register operand!");
771 RegOp = MO.getReg();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000772#ifndef NDEBUG
Evan Chengd70dbb52008-02-22 09:24:50 +0000773 break;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000774#endif
Evan Chengd70dbb52008-02-22 09:24:50 +0000775 }
776 return RegOp;
777}
778
779/// isValNoAvailableAt - Return true if the val# of the specified interval
780/// which reaches the given instruction also reaches the specified use index.
781bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
782 unsigned UseIdx) const {
783 unsigned Index = getInstructionIndex(MI);
784 VNInfo *ValNo = li.FindLiveRangeContaining(Index)->valno;
785 LiveInterval::const_iterator UI = li.FindLiveRangeContaining(UseIdx);
786 return UI != li.end() && UI->valno == ValNo;
787}
788
Evan Chengf2fbca62007-11-12 06:35:08 +0000789/// isReMaterializable - Returns true if the definition MI of the specified
790/// val# of the specified interval is re-materializable.
791bool LiveIntervals::isReMaterializable(const LiveInterval &li,
Evan Cheng5ef3a042007-12-06 00:01:56 +0000792 const VNInfo *ValNo, MachineInstr *MI,
793 bool &isLoad) {
Evan Chengf2fbca62007-11-12 06:35:08 +0000794 if (DisableReMat)
795 return false;
796
Evan Cheng20ccded2008-03-15 00:19:36 +0000797 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
Evan Chengd70dbb52008-02-22 09:24:50 +0000798 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000799
800 int FrameIdx = 0;
801 if (tii_->isLoadFromStackSlot(MI, FrameIdx) &&
Evan Cheng249ded32008-02-23 03:38:34 +0000802 mf_->getFrameInfo()->isImmutableObjectIndex(FrameIdx))
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000803 // FIXME: Let target specific isReallyTriviallyReMaterializable determines
804 // this but remember this is not safe to fold into a two-address
805 // instruction.
Evan Cheng249ded32008-02-23 03:38:34 +0000806 // This is a load from fixed stack slot. It can be rematerialized.
Evan Chengdd3465e2008-02-23 01:44:27 +0000807 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000808
Dan Gohman6d69ba82008-07-25 00:02:30 +0000809 // If the target-specific rules don't identify an instruction as
810 // being trivially rematerializable, use some target-independent
811 // rules.
812 if (!MI->getDesc().isRematerializable() ||
813 !tii_->isTriviallyReMaterializable(MI)) {
Dan Gohman4c8f8702008-07-25 15:08:37 +0000814 if (!EnableAggressiveRemat)
815 return false;
Evan Chengd70dbb52008-02-22 09:24:50 +0000816
Dan Gohman0471a792008-07-28 18:43:51 +0000817 // If the instruction accesses memory but the memoperands have been lost,
Dan Gohman6d69ba82008-07-25 00:02:30 +0000818 // we can't analyze it.
819 const TargetInstrDesc &TID = MI->getDesc();
820 if ((TID.mayLoad() || TID.mayStore()) && MI->memoperands_empty())
821 return false;
822
823 // Avoid instructions obviously unsafe for remat.
824 if (TID.hasUnmodeledSideEffects() || TID.isNotDuplicable())
825 return false;
826
827 // If the instruction accesses memory and the memory could be non-constant,
828 // assume the instruction is not rematerializable.
Dan Gohmanfed90b62008-07-28 21:51:04 +0000829 for (std::list<MachineMemOperand>::const_iterator I = MI->memoperands_begin(),
Dan Gohman6d69ba82008-07-25 00:02:30 +0000830 E = MI->memoperands_end(); I != E; ++I) {
831 const MachineMemOperand &MMO = *I;
832 if (MMO.isVolatile() || MMO.isStore())
833 return false;
834 const Value *V = MMO.getValue();
835 if (!V)
836 return false;
837 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
838 if (!PSV->isConstant(mf_->getFrameInfo()))
Evan Chengd70dbb52008-02-22 09:24:50 +0000839 return false;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000840 } else if (!aa_->pointsToConstantMemory(V))
841 return false;
842 }
843
844 // If any of the registers accessed are non-constant, conservatively assume
845 // the instruction is not rematerializable.
846 unsigned ImpUse = 0;
847 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
848 const MachineOperand &MO = MI->getOperand(i);
849 if (MO.isReg()) {
850 unsigned Reg = MO.getReg();
851 if (Reg == 0)
852 continue;
853 if (TargetRegisterInfo::isPhysicalRegister(Reg))
854 return false;
855
856 // Only allow one def, and that in the first operand.
857 if (MO.isDef() != (i == 0))
858 return false;
859
860 // Only allow constant-valued registers.
861 bool IsLiveIn = mri_->isLiveIn(Reg);
862 MachineRegisterInfo::def_iterator I = mri_->def_begin(Reg),
863 E = mri_->def_end();
864
865 // For the def, it should be the only def.
866 if (MO.isDef() && (next(I) != E || IsLiveIn))
867 return false;
868
869 if (MO.isUse()) {
870 // Only allow one use other register use, as that's all the
871 // remat mechanisms support currently.
872 if (Reg != li.reg) {
873 if (ImpUse == 0)
874 ImpUse = Reg;
875 else if (Reg != ImpUse)
876 return false;
877 }
878 // For uses, there should be only one associate def.
879 if (I != E && (next(I) != E || IsLiveIn))
880 return false;
881 }
Evan Chengd70dbb52008-02-22 09:24:50 +0000882 }
883 }
Evan Cheng5ef3a042007-12-06 00:01:56 +0000884 }
Evan Chengf2fbca62007-11-12 06:35:08 +0000885
Dan Gohman6d69ba82008-07-25 00:02:30 +0000886 unsigned ImpUse = getReMatImplicitUse(li, MI);
887 if (ImpUse) {
888 const LiveInterval &ImpLi = getInterval(ImpUse);
889 for (MachineRegisterInfo::use_iterator ri = mri_->use_begin(li.reg),
890 re = mri_->use_end(); ri != re; ++ri) {
891 MachineInstr *UseMI = &*ri;
892 unsigned UseIdx = getInstructionIndex(UseMI);
893 if (li.FindLiveRangeContaining(UseIdx)->valno != ValNo)
894 continue;
895 if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
896 return false;
897 }
898 }
899 return true;
Evan Cheng5ef3a042007-12-06 00:01:56 +0000900}
901
902/// isReMaterializable - Returns true if every definition of MI of every
903/// val# of the specified interval is re-materializable.
904bool LiveIntervals::isReMaterializable(const LiveInterval &li, bool &isLoad) {
905 isLoad = false;
906 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
907 i != e; ++i) {
908 const VNInfo *VNI = *i;
909 unsigned DefIdx = VNI->def;
910 if (DefIdx == ~1U)
911 continue; // Dead val#.
912 // Is the def for the val# rematerializable?
913 if (DefIdx == ~0u)
914 return false;
915 MachineInstr *ReMatDefMI = getInstructionFromIndex(DefIdx);
916 bool DefIsLoad = false;
Evan Chengd70dbb52008-02-22 09:24:50 +0000917 if (!ReMatDefMI ||
918 !isReMaterializable(li, VNI, ReMatDefMI, DefIsLoad))
Evan Cheng5ef3a042007-12-06 00:01:56 +0000919 return false;
920 isLoad |= DefIsLoad;
Evan Chengf2fbca62007-11-12 06:35:08 +0000921 }
922 return true;
923}
924
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000925/// FilterFoldedOps - Filter out two-address use operands. Return
926/// true if it finds any issue with the operands that ought to prevent
927/// folding.
928static bool FilterFoldedOps(MachineInstr *MI,
929 SmallVector<unsigned, 2> &Ops,
930 unsigned &MRInfo,
931 SmallVector<unsigned, 2> &FoldOps) {
Chris Lattner749c6f62008-01-07 07:27:27 +0000932 const TargetInstrDesc &TID = MI->getDesc();
Evan Cheng6e141fd2007-12-12 23:12:09 +0000933
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000934 MRInfo = 0;
Evan Chengaee4af62007-12-02 08:30:39 +0000935 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
936 unsigned OpIdx = Ops[i];
Evan Chengd70dbb52008-02-22 09:24:50 +0000937 MachineOperand &MO = MI->getOperand(OpIdx);
Evan Chengaee4af62007-12-02 08:30:39 +0000938 // FIXME: fold subreg use.
Evan Chengd70dbb52008-02-22 09:24:50 +0000939 if (MO.getSubReg())
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000940 return true;
Evan Chengd70dbb52008-02-22 09:24:50 +0000941 if (MO.isDef())
Evan Chengaee4af62007-12-02 08:30:39 +0000942 MRInfo |= (unsigned)VirtRegMap::isMod;
943 else {
944 // Filter out two-address use operand(s).
Evan Chengd70dbb52008-02-22 09:24:50 +0000945 if (!MO.isImplicit() &&
946 TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1) {
Evan Chengaee4af62007-12-02 08:30:39 +0000947 MRInfo = VirtRegMap::isModRef;
948 continue;
949 }
950 MRInfo |= (unsigned)VirtRegMap::isRef;
951 }
952 FoldOps.push_back(OpIdx);
Evan Chenge62f97c2007-12-01 02:07:52 +0000953 }
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000954 return false;
955}
956
957
958/// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
959/// slot / to reg or any rematerialized load into ith operand of specified
960/// MI. If it is successul, MI is updated with the newly created MI and
961/// returns true.
962bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
963 VirtRegMap &vrm, MachineInstr *DefMI,
964 unsigned InstrIdx,
965 SmallVector<unsigned, 2> &Ops,
966 bool isSS, int Slot, unsigned Reg) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000967 // If it is an implicit def instruction, just delete it.
Evan Cheng20ccded2008-03-15 00:19:36 +0000968 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000969 RemoveMachineInstrFromMaps(MI);
970 vrm.RemoveMachineInstrFromMaps(MI);
971 MI->eraseFromParent();
972 ++numFolds;
973 return true;
974 }
975
976 // Filter the list of operand indexes that are to be folded. Abort if
977 // any operand will prevent folding.
978 unsigned MRInfo = 0;
979 SmallVector<unsigned, 2> FoldOps;
980 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
981 return false;
Evan Chenge62f97c2007-12-01 02:07:52 +0000982
Evan Cheng427f4c12008-03-31 23:19:51 +0000983 // The only time it's safe to fold into a two address instruction is when
984 // it's folding reload and spill from / into a spill stack slot.
985 if (DefMI && (MRInfo & VirtRegMap::isMod))
Evan Cheng249ded32008-02-23 03:38:34 +0000986 return false;
987
Evan Chengf2f8c2a2008-02-08 22:05:27 +0000988 MachineInstr *fmi = isSS ? tii_->foldMemoryOperand(*mf_, MI, FoldOps, Slot)
989 : tii_->foldMemoryOperand(*mf_, MI, FoldOps, DefMI);
Evan Chengf2fbca62007-11-12 06:35:08 +0000990 if (fmi) {
Evan Chengd3653122008-02-27 03:04:06 +0000991 // Remember this instruction uses the spill slot.
992 if (isSS) vrm.addSpillSlotUse(Slot, fmi);
993
Evan Chengf2fbca62007-11-12 06:35:08 +0000994 // Attempt to fold the memory reference into the instruction. If
995 // we can do this, we don't need to insert spill code.
Evan Chengf2fbca62007-11-12 06:35:08 +0000996 MachineBasicBlock &MBB = *MI->getParent();
Evan Cheng84802932008-01-10 08:24:38 +0000997 if (isSS && !mf_->getFrameInfo()->isImmutableObjectIndex(Slot))
Evan Chengaee4af62007-12-02 08:30:39 +0000998 vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
Evan Cheng81a03822007-11-17 00:40:40 +0000999 vrm.transferSpillPts(MI, fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001000 vrm.transferRestorePts(MI, fmi);
Evan Chengc1f53c72008-03-11 21:34:46 +00001001 vrm.transferEmergencySpills(MI, fmi);
Evan Chengf2fbca62007-11-12 06:35:08 +00001002 mi2iMap_.erase(MI);
Evan Chengcddbb832007-11-30 21:23:43 +00001003 i2miMap_[InstrIdx /InstrSlots::NUM] = fmi;
1004 mi2iMap_[fmi] = InstrIdx;
Evan Chengf2fbca62007-11-12 06:35:08 +00001005 MI = MBB.insert(MBB.erase(MI), fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001006 ++numFolds;
Evan Chengf2fbca62007-11-12 06:35:08 +00001007 return true;
1008 }
1009 return false;
1010}
1011
Evan Cheng018f9b02007-12-05 03:22:34 +00001012/// canFoldMemoryOperand - Returns true if the specified load / store
1013/// folding is possible.
1014bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI,
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001015 SmallVector<unsigned, 2> &Ops,
Evan Cheng3c75ba82008-04-01 21:37:32 +00001016 bool ReMat) const {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001017 // Filter the list of operand indexes that are to be folded. Abort if
1018 // any operand will prevent folding.
1019 unsigned MRInfo = 0;
Evan Cheng018f9b02007-12-05 03:22:34 +00001020 SmallVector<unsigned, 2> FoldOps;
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001021 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1022 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001023
Evan Cheng3c75ba82008-04-01 21:37:32 +00001024 // It's only legal to remat for a use, not a def.
1025 if (ReMat && (MRInfo & VirtRegMap::isMod))
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001026 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001027
Evan Chengd70dbb52008-02-22 09:24:50 +00001028 return tii_->canFoldMemoryOperand(MI, FoldOps);
1029}
1030
Evan Cheng81a03822007-11-17 00:40:40 +00001031bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
1032 SmallPtrSet<MachineBasicBlock*, 4> MBBs;
1033 for (LiveInterval::Ranges::const_iterator
1034 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1035 std::vector<IdxMBBPair>::const_iterator II =
1036 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), I->start);
1037 if (II == Idx2MBBMap.end())
1038 continue;
1039 if (I->end > II->first) // crossing a MBB.
1040 return false;
1041 MBBs.insert(II->second);
1042 if (MBBs.size() > 1)
1043 return false;
1044 }
1045 return true;
1046}
1047
Evan Chengd70dbb52008-02-22 09:24:50 +00001048/// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
1049/// interval on to-be re-materialized operands of MI) with new register.
1050void LiveIntervals::rewriteImplicitOps(const LiveInterval &li,
1051 MachineInstr *MI, unsigned NewVReg,
1052 VirtRegMap &vrm) {
1053 // There is an implicit use. That means one of the other operand is
1054 // being remat'ed and the remat'ed instruction has li.reg as an
1055 // use operand. Make sure we rewrite that as well.
1056 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1057 MachineOperand &MO = MI->getOperand(i);
1058 if (!MO.isRegister())
1059 continue;
1060 unsigned Reg = MO.getReg();
1061 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
1062 continue;
1063 if (!vrm.isReMaterialized(Reg))
1064 continue;
1065 MachineInstr *ReMatMI = vrm.getReMaterializedMI(Reg);
Evan Cheng6130f662008-03-05 00:59:57 +00001066 MachineOperand *UseMO = ReMatMI->findRegisterUseOperand(li.reg);
1067 if (UseMO)
1068 UseMO->setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001069 }
1070}
1071
Evan Chengf2fbca62007-11-12 06:35:08 +00001072/// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
1073/// for addIntervalsForSpills to rewrite uses / defs for the given live range.
Evan Cheng018f9b02007-12-05 03:22:34 +00001074bool LiveIntervals::
Evan Chengd70dbb52008-02-22 09:24:50 +00001075rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
1076 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
Evan Cheng81a03822007-11-17 00:40:40 +00001077 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001078 unsigned Slot, int LdSlot,
1079 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001080 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001081 const TargetRegisterClass* rc,
1082 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001083 const MachineLoopInfo *loopInfo,
Evan Cheng313d4b82008-02-23 00:33:04 +00001084 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001085 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001086 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
1087 MachineBasicBlock *MBB = MI->getParent();
1088 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng018f9b02007-12-05 03:22:34 +00001089 bool CanFold = false;
Evan Chengf2fbca62007-11-12 06:35:08 +00001090 RestartInstruction:
1091 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1092 MachineOperand& mop = MI->getOperand(i);
1093 if (!mop.isRegister())
1094 continue;
1095 unsigned Reg = mop.getReg();
1096 unsigned RegI = Reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001097 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
Evan Chengf2fbca62007-11-12 06:35:08 +00001098 continue;
Evan Chengf2fbca62007-11-12 06:35:08 +00001099 if (Reg != li.reg)
1100 continue;
1101
1102 bool TryFold = !DefIsReMat;
Evan Chengcb3c3302007-11-29 23:02:50 +00001103 bool FoldSS = true; // Default behavior unless it's a remat.
Evan Chengf2fbca62007-11-12 06:35:08 +00001104 int FoldSlot = Slot;
1105 if (DefIsReMat) {
1106 // If this is the rematerializable definition MI itself and
1107 // all of its uses are rematerialized, simply delete it.
Evan Cheng81a03822007-11-17 00:40:40 +00001108 if (MI == ReMatOrigDefMI && CanDelete) {
Evan Chengcddbb832007-11-30 21:23:43 +00001109 DOUT << "\t\t\t\tErasing re-materlizable def: ";
1110 DOUT << MI << '\n';
Evan Chengf2fbca62007-11-12 06:35:08 +00001111 RemoveMachineInstrFromMaps(MI);
Evan Chengcada2452007-11-28 01:28:46 +00001112 vrm.RemoveMachineInstrFromMaps(MI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001113 MI->eraseFromParent();
1114 break;
1115 }
1116
1117 // If def for this use can't be rematerialized, then try folding.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001118 // If def is rematerializable and it's a load, also try folding.
Evan Chengcb3c3302007-11-29 23:02:50 +00001119 TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad));
Evan Chengf2fbca62007-11-12 06:35:08 +00001120 if (isLoad) {
1121 // Try fold loads (from stack slot, constant pool, etc.) into uses.
1122 FoldSS = isLoadSS;
1123 FoldSlot = LdSlot;
1124 }
1125 }
1126
Evan Chengf2fbca62007-11-12 06:35:08 +00001127 // Scan all of the operands of this instruction rewriting operands
1128 // to use NewVReg instead of li.reg as appropriate. We do this for
1129 // two reasons:
1130 //
1131 // 1. If the instr reads the same spilled vreg multiple times, we
1132 // want to reuse the NewVReg.
1133 // 2. If the instr is a two-addr instruction, we are required to
1134 // keep the src/dst regs pinned.
1135 //
1136 // Keep track of whether we replace a use and/or def so that we can
1137 // create the spill interval with the appropriate range.
Evan Chengcddbb832007-11-30 21:23:43 +00001138
Evan Cheng81a03822007-11-17 00:40:40 +00001139 HasUse = mop.isUse();
1140 HasDef = mop.isDef();
Evan Chengaee4af62007-12-02 08:30:39 +00001141 SmallVector<unsigned, 2> Ops;
1142 Ops.push_back(i);
Evan Chengf2fbca62007-11-12 06:35:08 +00001143 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
Evan Chengaee4af62007-12-02 08:30:39 +00001144 const MachineOperand &MOj = MI->getOperand(j);
1145 if (!MOj.isRegister())
Evan Chengf2fbca62007-11-12 06:35:08 +00001146 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001147 unsigned RegJ = MOj.getReg();
Dan Gohman6f0d0242008-02-10 18:45:23 +00001148 if (RegJ == 0 || TargetRegisterInfo::isPhysicalRegister(RegJ))
Evan Chengf2fbca62007-11-12 06:35:08 +00001149 continue;
1150 if (RegJ == RegI) {
Evan Chengaee4af62007-12-02 08:30:39 +00001151 Ops.push_back(j);
1152 HasUse |= MOj.isUse();
1153 HasDef |= MOj.isDef();
Evan Chengf2fbca62007-11-12 06:35:08 +00001154 }
1155 }
1156
Evan Cheng79a796c2008-07-12 01:56:02 +00001157 if (HasUse && !li.liveAt(getUseIndex(index)))
1158 // Must be defined by an implicit def. It should not be spilled. Note,
1159 // this is for correctness reason. e.g.
1160 // 8 %reg1024<def> = IMPLICIT_DEF
1161 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1162 // The live range [12, 14) are not part of the r1024 live interval since
1163 // it's defined by an implicit def. It will not conflicts with live
1164 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001165 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001166 // the INSERT_SUBREG and both target registers that would overlap.
1167 HasUse = false;
1168
Evan Cheng9c3c2212008-06-06 07:54:39 +00001169 // Update stack slot spill weight if we are splitting.
Evan Chengc3417602008-06-21 06:45:54 +00001170 float Weight = getSpillWeight(HasDef, HasUse, loopDepth);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001171 if (!TrySplit)
1172 SSWeight += Weight;
1173
1174 if (!TryFold)
1175 CanFold = false;
1176 else {
Evan Cheng018f9b02007-12-05 03:22:34 +00001177 // Do not fold load / store here if we are splitting. We'll find an
1178 // optimal point to insert a load / store later.
1179 if (!TrySplit) {
1180 if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1181 Ops, FoldSS, FoldSlot, Reg)) {
1182 // Folding the load/store can completely change the instruction in
1183 // unpredictable ways, rescan it from the beginning.
1184 HasUse = false;
1185 HasDef = false;
1186 CanFold = false;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001187 if (isRemoved(MI)) {
1188 SSWeight -= Weight;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001189 break;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001190 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001191 goto RestartInstruction;
1192 }
1193 } else {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001194 // We'll try to fold it later if it's profitable.
Evan Cheng3c75ba82008-04-01 21:37:32 +00001195 CanFold = canFoldMemoryOperand(MI, Ops, DefIsReMat);
Evan Cheng018f9b02007-12-05 03:22:34 +00001196 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001197 }
Evan Chengcddbb832007-11-30 21:23:43 +00001198
1199 // Create a new virtual register for the spill interval.
1200 bool CreatedNewVReg = false;
1201 if (NewVReg == 0) {
Evan Chengd70dbb52008-02-22 09:24:50 +00001202 NewVReg = mri_->createVirtualRegister(rc);
Evan Chengcddbb832007-11-30 21:23:43 +00001203 vrm.grow();
1204 CreatedNewVReg = true;
1205 }
1206 mop.setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001207 if (mop.isImplicit())
1208 rewriteImplicitOps(li, MI, NewVReg, vrm);
Evan Chengcddbb832007-11-30 21:23:43 +00001209
1210 // Reuse NewVReg for other reads.
Evan Chengd70dbb52008-02-22 09:24:50 +00001211 for (unsigned j = 0, e = Ops.size(); j != e; ++j) {
1212 MachineOperand &mopj = MI->getOperand(Ops[j]);
1213 mopj.setReg(NewVReg);
1214 if (mopj.isImplicit())
1215 rewriteImplicitOps(li, MI, NewVReg, vrm);
1216 }
Evan Chengcddbb832007-11-30 21:23:43 +00001217
Evan Cheng81a03822007-11-17 00:40:40 +00001218 if (CreatedNewVReg) {
1219 if (DefIsReMat) {
1220 vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI/*, CanDelete*/);
Evan Chengd70dbb52008-02-22 09:24:50 +00001221 if (ReMatIds[VNI->id] == VirtRegMap::MAX_STACK_SLOT) {
Evan Cheng81a03822007-11-17 00:40:40 +00001222 // Each valnum may have its own remat id.
Evan Chengd70dbb52008-02-22 09:24:50 +00001223 ReMatIds[VNI->id] = vrm.assignVirtReMatId(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001224 } else {
Evan Chengd70dbb52008-02-22 09:24:50 +00001225 vrm.assignVirtReMatId(NewVReg, ReMatIds[VNI->id]);
Evan Cheng81a03822007-11-17 00:40:40 +00001226 }
1227 if (!CanDelete || (HasUse && HasDef)) {
1228 // If this is a two-addr instruction then its use operands are
1229 // rematerializable but its def is not. It should be assigned a
1230 // stack slot.
1231 vrm.assignVirt2StackSlot(NewVReg, Slot);
1232 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001233 } else {
Evan Chengf2fbca62007-11-12 06:35:08 +00001234 vrm.assignVirt2StackSlot(NewVReg, Slot);
1235 }
Evan Chengcb3c3302007-11-29 23:02:50 +00001236 } else if (HasUse && HasDef &&
1237 vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) {
1238 // If this interval hasn't been assigned a stack slot (because earlier
1239 // def is a deleted remat def), do it now.
1240 assert(Slot != VirtRegMap::NO_STACK_SLOT);
1241 vrm.assignVirt2StackSlot(NewVReg, Slot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001242 }
1243
Evan Cheng313d4b82008-02-23 00:33:04 +00001244 // Re-matting an instruction with virtual register use. Add the
1245 // register as an implicit use on the use MI.
1246 if (DefIsReMat && ImpUse)
1247 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1248
Evan Chengf2fbca62007-11-12 06:35:08 +00001249 // create a new register interval for this spill / remat.
1250 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001251 if (CreatedNewVReg) {
1252 NewLIs.push_back(&nI);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001253 MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg));
Evan Cheng81a03822007-11-17 00:40:40 +00001254 if (TrySplit)
1255 vrm.setIsSplitFromReg(NewVReg, li.reg);
1256 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001257
1258 if (HasUse) {
Evan Cheng81a03822007-11-17 00:40:40 +00001259 if (CreatedNewVReg) {
1260 LiveRange LR(getLoadIndex(index), getUseIndex(index)+1,
1261 nI.getNextValue(~0U, 0, VNInfoAllocator));
1262 DOUT << " +" << LR;
1263 nI.addRange(LR);
1264 } else {
1265 // Extend the split live interval to this def / use.
1266 unsigned End = getUseIndex(index)+1;
1267 LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
1268 nI.getValNumInfo(nI.getNumValNums()-1));
1269 DOUT << " +" << LR;
1270 nI.addRange(LR);
1271 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001272 }
1273 if (HasDef) {
1274 LiveRange LR(getDefIndex(index), getStoreIndex(index),
1275 nI.getNextValue(~0U, 0, VNInfoAllocator));
1276 DOUT << " +" << LR;
1277 nI.addRange(LR);
1278 }
Evan Cheng81a03822007-11-17 00:40:40 +00001279
Evan Chengf2fbca62007-11-12 06:35:08 +00001280 DOUT << "\t\t\t\tAdded new interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001281 nI.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001282 DOUT << '\n';
1283 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001284 return CanFold;
Evan Chengf2fbca62007-11-12 06:35:08 +00001285}
Evan Cheng81a03822007-11-17 00:40:40 +00001286bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001287 const VNInfo *VNI,
1288 MachineBasicBlock *MBB, unsigned Idx) const {
Evan Cheng81a03822007-11-17 00:40:40 +00001289 unsigned End = getMBBEndIdx(MBB);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001290 for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
1291 unsigned KillIdx = VNI->kills[j];
1292 if (KillIdx > Idx && KillIdx < End)
1293 return true;
Evan Cheng81a03822007-11-17 00:40:40 +00001294 }
1295 return false;
1296}
1297
Evan Cheng063284c2008-02-21 00:34:19 +00001298/// RewriteInfo - Keep track of machine instrs that will be rewritten
1299/// during spilling.
Dan Gohman844731a2008-05-13 00:00:25 +00001300namespace {
1301 struct RewriteInfo {
1302 unsigned Index;
1303 MachineInstr *MI;
1304 bool HasUse;
1305 bool HasDef;
1306 RewriteInfo(unsigned i, MachineInstr *mi, bool u, bool d)
1307 : Index(i), MI(mi), HasUse(u), HasDef(d) {}
1308 };
Evan Cheng063284c2008-02-21 00:34:19 +00001309
Dan Gohman844731a2008-05-13 00:00:25 +00001310 struct RewriteInfoCompare {
1311 bool operator()(const RewriteInfo &LHS, const RewriteInfo &RHS) const {
1312 return LHS.Index < RHS.Index;
1313 }
1314 };
1315}
Evan Cheng063284c2008-02-21 00:34:19 +00001316
Evan Chengf2fbca62007-11-12 06:35:08 +00001317void LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001318rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
Evan Chengf2fbca62007-11-12 06:35:08 +00001319 LiveInterval::Ranges::const_iterator &I,
Evan Cheng81a03822007-11-17 00:40:40 +00001320 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001321 unsigned Slot, int LdSlot,
1322 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001323 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001324 const TargetRegisterClass* rc,
1325 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001326 const MachineLoopInfo *loopInfo,
Evan Cheng81a03822007-11-17 00:40:40 +00001327 BitVector &SpillMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001328 std::map<unsigned, std::vector<SRInfo> > &SpillIdxes,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001329 BitVector &RestoreMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001330 std::map<unsigned, std::vector<SRInfo> > &RestoreIdxes,
1331 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001332 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001333 bool AllCanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001334 unsigned NewVReg = 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001335 unsigned start = getBaseIndex(I->start);
Evan Chengf2fbca62007-11-12 06:35:08 +00001336 unsigned end = getBaseIndex(I->end-1) + InstrSlots::NUM;
Evan Chengf2fbca62007-11-12 06:35:08 +00001337
Evan Cheng063284c2008-02-21 00:34:19 +00001338 // First collect all the def / use in this live range that will be rewritten.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001339 // Make sure they are sorted according to instruction index.
Evan Cheng063284c2008-02-21 00:34:19 +00001340 std::vector<RewriteInfo> RewriteMIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001341 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1342 re = mri_->reg_end(); ri != re; ) {
Evan Cheng419852c2008-04-03 16:39:43 +00001343 MachineInstr *MI = &*ri;
Evan Cheng063284c2008-02-21 00:34:19 +00001344 MachineOperand &O = ri.getOperand();
1345 ++ri;
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001346 assert(!O.isImplicit() && "Spilling register that's used as implicit use?");
Evan Cheng063284c2008-02-21 00:34:19 +00001347 unsigned index = getInstructionIndex(MI);
1348 if (index < start || index >= end)
1349 continue;
Evan Cheng79a796c2008-07-12 01:56:02 +00001350 if (O.isUse() && !li.liveAt(getUseIndex(index)))
1351 // Must be defined by an implicit def. It should not be spilled. Note,
1352 // this is for correctness reason. e.g.
1353 // 8 %reg1024<def> = IMPLICIT_DEF
1354 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1355 // The live range [12, 14) are not part of the r1024 live interval since
1356 // it's defined by an implicit def. It will not conflicts with live
1357 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001358 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001359 // the INSERT_SUBREG and both target registers that would overlap.
1360 continue;
Evan Cheng063284c2008-02-21 00:34:19 +00001361 RewriteMIs.push_back(RewriteInfo(index, MI, O.isUse(), O.isDef()));
1362 }
1363 std::sort(RewriteMIs.begin(), RewriteMIs.end(), RewriteInfoCompare());
1364
Evan Cheng313d4b82008-02-23 00:33:04 +00001365 unsigned ImpUse = DefIsReMat ? getReMatImplicitUse(li, ReMatDefMI) : 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001366 // Now rewrite the defs and uses.
1367 for (unsigned i = 0, e = RewriteMIs.size(); i != e; ) {
1368 RewriteInfo &rwi = RewriteMIs[i];
1369 ++i;
1370 unsigned index = rwi.Index;
1371 bool MIHasUse = rwi.HasUse;
1372 bool MIHasDef = rwi.HasDef;
1373 MachineInstr *MI = rwi.MI;
1374 // If MI def and/or use the same register multiple times, then there
1375 // are multiple entries.
Evan Cheng313d4b82008-02-23 00:33:04 +00001376 unsigned NumUses = MIHasUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001377 while (i != e && RewriteMIs[i].MI == MI) {
1378 assert(RewriteMIs[i].Index == index);
Evan Cheng313d4b82008-02-23 00:33:04 +00001379 bool isUse = RewriteMIs[i].HasUse;
1380 if (isUse) ++NumUses;
1381 MIHasUse |= isUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001382 MIHasDef |= RewriteMIs[i].HasDef;
1383 ++i;
1384 }
Evan Cheng81a03822007-11-17 00:40:40 +00001385 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng313d4b82008-02-23 00:33:04 +00001386
Evan Cheng0a891ed2008-05-23 23:00:04 +00001387 if (ImpUse && MI != ReMatDefMI) {
Evan Cheng313d4b82008-02-23 00:33:04 +00001388 // Re-matting an instruction with virtual register use. Update the
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001389 // register interval's spill weight to HUGE_VALF to prevent it from
1390 // being spilled.
Evan Cheng313d4b82008-02-23 00:33:04 +00001391 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001392 ImpLi.weight = HUGE_VALF;
Evan Cheng313d4b82008-02-23 00:33:04 +00001393 }
1394
Evan Cheng063284c2008-02-21 00:34:19 +00001395 unsigned MBBId = MBB->getNumber();
Evan Cheng018f9b02007-12-05 03:22:34 +00001396 unsigned ThisVReg = 0;
Evan Cheng70306f82007-12-03 09:58:48 +00001397 if (TrySplit) {
Evan Cheng063284c2008-02-21 00:34:19 +00001398 std::map<unsigned,unsigned>::const_iterator NVI = MBBVRegsMap.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001399 if (NVI != MBBVRegsMap.end()) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001400 ThisVReg = NVI->second;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001401 // One common case:
1402 // x = use
1403 // ...
1404 // ...
1405 // def = ...
1406 // = use
1407 // It's better to start a new interval to avoid artifically
1408 // extend the new interval.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001409 if (MIHasDef && !MIHasUse) {
1410 MBBVRegsMap.erase(MBB->getNumber());
Evan Cheng018f9b02007-12-05 03:22:34 +00001411 ThisVReg = 0;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001412 }
1413 }
Evan Chengcada2452007-11-28 01:28:46 +00001414 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001415
1416 bool IsNew = ThisVReg == 0;
1417 if (IsNew) {
1418 // This ends the previous live interval. If all of its def / use
1419 // can be folded, give it a low spill weight.
1420 if (NewVReg && TrySplit && AllCanFold) {
1421 LiveInterval &nI = getOrCreateInterval(NewVReg);
1422 nI.weight /= 10.0F;
1423 }
1424 AllCanFold = true;
1425 }
1426 NewVReg = ThisVReg;
1427
Evan Cheng81a03822007-11-17 00:40:40 +00001428 bool HasDef = false;
1429 bool HasUse = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001430 bool CanFold = rewriteInstructionForSpills(li, I->valno, TrySplit,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001431 index, end, MI, ReMatOrigDefMI, ReMatDefMI,
1432 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
1433 CanDelete, vrm, rc, ReMatIds, loopInfo, NewVReg,
1434 ImpUse, HasDef, HasUse, MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001435 if (!HasDef && !HasUse)
1436 continue;
1437
Evan Cheng018f9b02007-12-05 03:22:34 +00001438 AllCanFold &= CanFold;
1439
Evan Cheng81a03822007-11-17 00:40:40 +00001440 // Update weight of spill interval.
1441 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng70306f82007-12-03 09:58:48 +00001442 if (!TrySplit) {
Evan Cheng81a03822007-11-17 00:40:40 +00001443 // The spill weight is now infinity as it cannot be spilled again.
1444 nI.weight = HUGE_VALF;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001445 continue;
Evan Cheng81a03822007-11-17 00:40:40 +00001446 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001447
1448 // Keep track of the last def and first use in each MBB.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001449 if (HasDef) {
1450 if (MI != ReMatOrigDefMI || !CanDelete) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001451 bool HasKill = false;
1452 if (!HasUse)
1453 HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, getDefIndex(index));
1454 else {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001455 // If this is a two-address code, then this index starts a new VNInfo.
Evan Cheng3f32d652008-06-04 09:18:41 +00001456 const VNInfo *VNI = li.findDefinedVNInfo(getDefIndex(index));
Evan Cheng0cbb1162007-11-29 01:06:25 +00001457 if (VNI)
1458 HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, getDefIndex(index));
1459 }
Evan Chenge3110d02007-12-01 04:42:39 +00001460 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
1461 SpillIdxes.find(MBBId);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001462 if (!HasKill) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001463 if (SII == SpillIdxes.end()) {
1464 std::vector<SRInfo> S;
1465 S.push_back(SRInfo(index, NewVReg, true));
1466 SpillIdxes.insert(std::make_pair(MBBId, S));
1467 } else if (SII->second.back().vreg != NewVReg) {
1468 SII->second.push_back(SRInfo(index, NewVReg, true));
1469 } else if ((int)index > SII->second.back().index) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001470 // If there is an earlier def and this is a two-address
1471 // instruction, then it's not possible to fold the store (which
1472 // would also fold the load).
Evan Cheng1953d0c2007-11-29 10:12:14 +00001473 SRInfo &Info = SII->second.back();
1474 Info.index = index;
1475 Info.canFold = !HasUse;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001476 }
1477 SpillMBBs.set(MBBId);
Evan Chenge3110d02007-12-01 04:42:39 +00001478 } else if (SII != SpillIdxes.end() &&
1479 SII->second.back().vreg == NewVReg &&
1480 (int)index > SII->second.back().index) {
1481 // There is an earlier def that's not killed (must be two-address).
1482 // The spill is no longer needed.
1483 SII->second.pop_back();
1484 if (SII->second.empty()) {
1485 SpillIdxes.erase(MBBId);
1486 SpillMBBs.reset(MBBId);
1487 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001488 }
1489 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001490 }
1491
1492 if (HasUse) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001493 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001494 SpillIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001495 if (SII != SpillIdxes.end() &&
1496 SII->second.back().vreg == NewVReg &&
1497 (int)index > SII->second.back().index)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001498 // Use(s) following the last def, it's not safe to fold the spill.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001499 SII->second.back().canFold = false;
1500 std::map<unsigned, std::vector<SRInfo> >::iterator RII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001501 RestoreIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001502 if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001503 // If we are splitting live intervals, only fold if it's the first
1504 // use and there isn't another use later in the MBB.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001505 RII->second.back().canFold = false;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001506 else if (IsNew) {
1507 // Only need a reload if there isn't an earlier def / use.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001508 if (RII == RestoreIdxes.end()) {
1509 std::vector<SRInfo> Infos;
1510 Infos.push_back(SRInfo(index, NewVReg, true));
1511 RestoreIdxes.insert(std::make_pair(MBBId, Infos));
1512 } else {
1513 RII->second.push_back(SRInfo(index, NewVReg, true));
1514 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001515 RestoreMBBs.set(MBBId);
1516 }
1517 }
1518
1519 // Update spill weight.
Evan Cheng22f07ff2007-12-11 02:09:15 +00001520 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Chengc3417602008-06-21 06:45:54 +00001521 nI.weight += getSpillWeight(HasDef, HasUse, loopDepth);
Evan Chengf2fbca62007-11-12 06:35:08 +00001522 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001523
1524 if (NewVReg && TrySplit && AllCanFold) {
1525 // If all of its def / use can be folded, give it a low spill weight.
1526 LiveInterval &nI = getOrCreateInterval(NewVReg);
1527 nI.weight /= 10.0F;
1528 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001529}
1530
Evan Cheng1953d0c2007-11-29 10:12:14 +00001531bool LiveIntervals::alsoFoldARestore(int Id, int index, unsigned vr,
1532 BitVector &RestoreMBBs,
1533 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1534 if (!RestoreMBBs[Id])
1535 return false;
1536 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1537 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1538 if (Restores[i].index == index &&
1539 Restores[i].vreg == vr &&
1540 Restores[i].canFold)
1541 return true;
1542 return false;
1543}
1544
1545void LiveIntervals::eraseRestoreInfo(int Id, int index, unsigned vr,
1546 BitVector &RestoreMBBs,
1547 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1548 if (!RestoreMBBs[Id])
1549 return;
1550 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1551 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1552 if (Restores[i].index == index && Restores[i].vreg)
1553 Restores[i].index = -1;
1554}
Evan Cheng81a03822007-11-17 00:40:40 +00001555
Evan Cheng4cce6b42008-04-11 17:53:36 +00001556/// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
1557/// spilled and create empty intervals for their uses.
1558void
1559LiveIntervals::handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
1560 const TargetRegisterClass* rc,
1561 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng419852c2008-04-03 16:39:43 +00001562 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1563 re = mri_->reg_end(); ri != re; ) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001564 MachineOperand &O = ri.getOperand();
Evan Cheng419852c2008-04-03 16:39:43 +00001565 MachineInstr *MI = &*ri;
1566 ++ri;
Evan Cheng4cce6b42008-04-11 17:53:36 +00001567 if (O.isDef()) {
1568 assert(MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF &&
1569 "Register def was not rewritten?");
1570 RemoveMachineInstrFromMaps(MI);
1571 vrm.RemoveMachineInstrFromMaps(MI);
1572 MI->eraseFromParent();
1573 } else {
1574 // This must be an use of an implicit_def so it's not part of the live
1575 // interval. Create a new empty live interval for it.
1576 // FIXME: Can we simply erase some of the instructions? e.g. Stores?
1577 unsigned NewVReg = mri_->createVirtualRegister(rc);
1578 vrm.grow();
1579 vrm.setIsImplicitlyDefined(NewVReg);
1580 NewLIs.push_back(&getOrCreateInterval(NewVReg));
1581 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1582 MachineOperand &MO = MI->getOperand(i);
1583 if (MO.isReg() && MO.getReg() == li.reg)
1584 MO.setReg(NewVReg);
1585 }
1586 }
Evan Cheng419852c2008-04-03 16:39:43 +00001587 }
1588}
1589
Evan Cheng81a03822007-11-17 00:40:40 +00001590
Evan Chengf2fbca62007-11-12 06:35:08 +00001591std::vector<LiveInterval*> LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001592addIntervalsForSpills(const LiveInterval &li,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001593 const MachineLoopInfo *loopInfo, VirtRegMap &vrm,
1594 float &SSWeight) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001595 assert(li.weight != HUGE_VALF &&
1596 "attempt to spill already spilled interval!");
1597
1598 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001599 li.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001600 DOUT << '\n';
1601
Evan Cheng9c3c2212008-06-06 07:54:39 +00001602 // Spill slot weight.
1603 SSWeight = 0.0f;
1604
Evan Cheng81a03822007-11-17 00:40:40 +00001605 // Each bit specify whether it a spill is required in the MBB.
1606 BitVector SpillMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001607 std::map<unsigned, std::vector<SRInfo> > SpillIdxes;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001608 BitVector RestoreMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001609 std::map<unsigned, std::vector<SRInfo> > RestoreIdxes;
1610 std::map<unsigned,unsigned> MBBVRegsMap;
Evan Chengf2fbca62007-11-12 06:35:08 +00001611 std::vector<LiveInterval*> NewLIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001612 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
Evan Chengf2fbca62007-11-12 06:35:08 +00001613
1614 unsigned NumValNums = li.getNumValNums();
1615 SmallVector<MachineInstr*, 4> ReMatDefs;
1616 ReMatDefs.resize(NumValNums, NULL);
1617 SmallVector<MachineInstr*, 4> ReMatOrigDefs;
1618 ReMatOrigDefs.resize(NumValNums, NULL);
1619 SmallVector<int, 4> ReMatIds;
1620 ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
1621 BitVector ReMatDelete(NumValNums);
1622 unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
1623
Evan Cheng81a03822007-11-17 00:40:40 +00001624 // Spilling a split live interval. It cannot be split any further. Also,
1625 // it's also guaranteed to be a single val# / range interval.
1626 if (vrm.getPreSplitReg(li.reg)) {
1627 vrm.setIsSplitFromReg(li.reg, 0);
Evan Chengd120ffd2007-12-05 10:24:35 +00001628 // Unset the split kill marker on the last use.
1629 unsigned KillIdx = vrm.getKillPoint(li.reg);
1630 if (KillIdx) {
1631 MachineInstr *KillMI = getInstructionFromIndex(KillIdx);
1632 assert(KillMI && "Last use disappeared?");
1633 int KillOp = KillMI->findRegisterUseOperandIdx(li.reg, true);
1634 assert(KillOp != -1 && "Last use disappeared?");
Chris Lattnerf7382302007-12-30 21:56:09 +00001635 KillMI->getOperand(KillOp).setIsKill(false);
Evan Chengd120ffd2007-12-05 10:24:35 +00001636 }
Evan Chengadf85902007-12-05 09:51:10 +00001637 vrm.removeKillPoint(li.reg);
Evan Cheng81a03822007-11-17 00:40:40 +00001638 bool DefIsReMat = vrm.isReMaterialized(li.reg);
1639 Slot = vrm.getStackSlot(li.reg);
1640 assert(Slot != VirtRegMap::MAX_STACK_SLOT);
1641 MachineInstr *ReMatDefMI = DefIsReMat ?
1642 vrm.getReMaterializedMI(li.reg) : NULL;
1643 int LdSlot = 0;
1644 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1645 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001646 (DefIsReMat && (ReMatDefMI->getDesc().isSimpleLoad()));
Evan Cheng81a03822007-11-17 00:40:40 +00001647 bool IsFirstRange = true;
1648 for (LiveInterval::Ranges::const_iterator
1649 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1650 // If this is a split live interval with multiple ranges, it means there
1651 // are two-address instructions that re-defined the value. Only the
1652 // first def can be rematerialized!
1653 if (IsFirstRange) {
Evan Chengcb3c3302007-11-29 23:02:50 +00001654 // Note ReMatOrigDefMI has already been deleted.
Evan Cheng81a03822007-11-17 00:40:40 +00001655 rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
1656 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001657 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001658 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001659 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001660 } else {
1661 rewriteInstructionsForSpills(li, false, I, NULL, 0,
1662 Slot, 0, false, false, false,
Evan Chengd70dbb52008-02-22 09:24:50 +00001663 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001664 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001665 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001666 }
1667 IsFirstRange = false;
1668 }
Evan Cheng419852c2008-04-03 16:39:43 +00001669
Evan Cheng9c3c2212008-06-06 07:54:39 +00001670 SSWeight = 0.0f; // Already accounted for when split.
Evan Cheng4cce6b42008-04-11 17:53:36 +00001671 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001672 return NewLIs;
1673 }
1674
1675 bool TrySplit = SplitAtBB && !intervalIsInOneMBB(li);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001676 if (SplitLimit != -1 && (int)numSplits >= SplitLimit)
1677 TrySplit = false;
1678 if (TrySplit)
1679 ++numSplits;
Evan Chengf2fbca62007-11-12 06:35:08 +00001680 bool NeedStackSlot = false;
1681 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1682 i != e; ++i) {
1683 const VNInfo *VNI = *i;
1684 unsigned VN = VNI->id;
1685 unsigned DefIdx = VNI->def;
1686 if (DefIdx == ~1U)
1687 continue; // Dead val#.
1688 // Is the def for the val# rematerializable?
Evan Cheng81a03822007-11-17 00:40:40 +00001689 MachineInstr *ReMatDefMI = (DefIdx == ~0u)
1690 ? 0 : getInstructionFromIndex(DefIdx);
Evan Cheng5ef3a042007-12-06 00:01:56 +00001691 bool dummy;
1692 if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, dummy)) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001693 // Remember how to remat the def of this val#.
Evan Cheng81a03822007-11-17 00:40:40 +00001694 ReMatOrigDefs[VN] = ReMatDefMI;
Dan Gohman2c3f7ae2008-07-17 23:49:46 +00001695 // Original def may be modified so we have to make a copy here.
Evan Cheng1ed99222008-07-19 00:37:25 +00001696 MachineInstr *Clone = mf_->CloneMachineInstr(ReMatDefMI);
1697 ClonedMIs.push_back(Clone);
1698 ReMatDefs[VN] = Clone;
Evan Chengf2fbca62007-11-12 06:35:08 +00001699
1700 bool CanDelete = true;
Evan Chengc3fc7d92007-11-29 09:49:23 +00001701 if (VNI->hasPHIKill) {
1702 // A kill is a phi node, not all of its uses can be rematerialized.
Evan Chengf2fbca62007-11-12 06:35:08 +00001703 // It must not be deleted.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001704 CanDelete = false;
1705 // Need a stack slot if there is any live range where uses cannot be
1706 // rematerialized.
1707 NeedStackSlot = true;
Evan Chengf2fbca62007-11-12 06:35:08 +00001708 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001709 if (CanDelete)
1710 ReMatDelete.set(VN);
1711 } else {
1712 // Need a stack slot if there is any live range where uses cannot be
1713 // rematerialized.
1714 NeedStackSlot = true;
1715 }
1716 }
1717
1718 // One stack slot per live interval.
Evan Cheng81a03822007-11-17 00:40:40 +00001719 if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0)
Evan Chengf2fbca62007-11-12 06:35:08 +00001720 Slot = vrm.assignVirt2StackSlot(li.reg);
1721
1722 // Create new intervals and rewrite defs and uses.
1723 for (LiveInterval::Ranges::const_iterator
1724 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Evan Cheng81a03822007-11-17 00:40:40 +00001725 MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id];
1726 MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id];
1727 bool DefIsReMat = ReMatDefMI != NULL;
Evan Chengf2fbca62007-11-12 06:35:08 +00001728 bool CanDelete = ReMatDelete[I->valno->id];
1729 int LdSlot = 0;
Evan Cheng81a03822007-11-17 00:40:40 +00001730 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001731 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001732 (DefIsReMat && ReMatDefMI->getDesc().isSimpleLoad());
Evan Cheng81a03822007-11-17 00:40:40 +00001733 rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001734 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001735 CanDelete, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001736 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001737 MBBVRegsMap, NewLIs, SSWeight);
Evan Chengf2fbca62007-11-12 06:35:08 +00001738 }
1739
Evan Cheng0cbb1162007-11-29 01:06:25 +00001740 // Insert spills / restores if we are splitting.
Evan Cheng419852c2008-04-03 16:39:43 +00001741 if (!TrySplit) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001742 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001743 return NewLIs;
Evan Cheng419852c2008-04-03 16:39:43 +00001744 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001745
Evan Chengb50bb8c2007-12-05 08:16:32 +00001746 SmallPtrSet<LiveInterval*, 4> AddedKill;
Evan Chengaee4af62007-12-02 08:30:39 +00001747 SmallVector<unsigned, 2> Ops;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001748 if (NeedStackSlot) {
1749 int Id = SpillMBBs.find_first();
1750 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001751 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1752 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001753 std::vector<SRInfo> &spills = SpillIdxes[Id];
1754 for (unsigned i = 0, e = spills.size(); i != e; ++i) {
1755 int index = spills[i].index;
1756 unsigned VReg = spills[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001757 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001758 bool isReMat = vrm.isReMaterialized(VReg);
1759 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001760 bool CanFold = false;
1761 bool FoundUse = false;
1762 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001763 if (spills[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001764 CanFold = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001765 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1766 MachineOperand &MO = MI->getOperand(j);
1767 if (!MO.isRegister() || MO.getReg() != VReg)
1768 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001769
1770 Ops.push_back(j);
1771 if (MO.isDef())
Evan Chengcddbb832007-11-30 21:23:43 +00001772 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001773 if (isReMat ||
1774 (!FoundUse && !alsoFoldARestore(Id, index, VReg,
1775 RestoreMBBs, RestoreIdxes))) {
1776 // MI has two-address uses of the same register. If the use
1777 // isn't the first and only use in the BB, then we can't fold
1778 // it. FIXME: Move this to rewriteInstructionsForSpills.
1779 CanFold = false;
Evan Chengcddbb832007-11-30 21:23:43 +00001780 break;
1781 }
Evan Chengaee4af62007-12-02 08:30:39 +00001782 FoundUse = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001783 }
1784 }
1785 // Fold the store into the def if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001786 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001787 if (CanFold && !Ops.empty()) {
1788 if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
Evan Chengcddbb832007-11-30 21:23:43 +00001789 Folded = true;
Evan Chengf38d14f2007-12-05 09:05:34 +00001790 if (FoundUse > 0) {
Evan Chengaee4af62007-12-02 08:30:39 +00001791 // Also folded uses, do not issue a load.
1792 eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
Evan Chengf38d14f2007-12-05 09:05:34 +00001793 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
1794 }
Evan Cheng597d10d2007-12-04 00:32:23 +00001795 nI.removeRange(getDefIndex(index), getStoreIndex(index));
Evan Chengcddbb832007-11-30 21:23:43 +00001796 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001797 }
1798
Evan Cheng7e073ba2008-04-09 20:57:25 +00001799 // Otherwise tell the spiller to issue a spill.
Evan Chengb50bb8c2007-12-05 08:16:32 +00001800 if (!Folded) {
1801 LiveRange *LR = &nI.ranges[nI.ranges.size()-1];
1802 bool isKill = LR->end == getStoreIndex(index);
Evan Chengb0a6f622008-05-20 08:10:37 +00001803 if (!MI->registerDefIsDead(nI.reg))
1804 // No need to spill a dead def.
1805 vrm.addSpillPoint(VReg, isKill, MI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001806 if (isKill)
1807 AddedKill.insert(&nI);
1808 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001809
1810 // Update spill slot weight.
1811 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00001812 SSWeight += getSpillWeight(true, false, loopDepth);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001813 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001814 Id = SpillMBBs.find_next(Id);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001815 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001816 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001817
Evan Cheng1953d0c2007-11-29 10:12:14 +00001818 int Id = RestoreMBBs.find_first();
1819 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001820 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1821 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
1822
Evan Cheng1953d0c2007-11-29 10:12:14 +00001823 std::vector<SRInfo> &restores = RestoreIdxes[Id];
1824 for (unsigned i = 0, e = restores.size(); i != e; ++i) {
1825 int index = restores[i].index;
1826 if (index == -1)
1827 continue;
1828 unsigned VReg = restores[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001829 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001830 bool isReMat = vrm.isReMaterialized(VReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001831 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001832 bool CanFold = false;
1833 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001834 if (restores[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001835 CanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001836 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1837 MachineOperand &MO = MI->getOperand(j);
1838 if (!MO.isRegister() || MO.getReg() != VReg)
1839 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001840
Evan Cheng0cbb1162007-11-29 01:06:25 +00001841 if (MO.isDef()) {
Evan Chengaee4af62007-12-02 08:30:39 +00001842 // If this restore were to be folded, it would have been folded
1843 // already.
1844 CanFold = false;
Evan Cheng81a03822007-11-17 00:40:40 +00001845 break;
1846 }
Evan Chengaee4af62007-12-02 08:30:39 +00001847 Ops.push_back(j);
Evan Cheng81a03822007-11-17 00:40:40 +00001848 }
1849 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001850
1851 // Fold the load into the use if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001852 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001853 if (CanFold && !Ops.empty()) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001854 if (!isReMat)
Evan Chengaee4af62007-12-02 08:30:39 +00001855 Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg);
1856 else {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001857 MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg);
1858 int LdSlot = 0;
1859 bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1860 // If the rematerializable def is a load, also try to fold it.
Chris Lattner749c6f62008-01-07 07:27:27 +00001861 if (isLoadSS || ReMatDefMI->getDesc().isSimpleLoad())
Evan Chengaee4af62007-12-02 08:30:39 +00001862 Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1863 Ops, isLoadSS, LdSlot, VReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001864 unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI);
1865 if (ImpUse) {
1866 // Re-matting an instruction with virtual register use. Add the
1867 // register as an implicit use on the use MI and update the register
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001868 // interval's spill weight to HUGE_VALF to prevent it from being
1869 // spilled.
Evan Chengd70dbb52008-02-22 09:24:50 +00001870 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001871 ImpLi.weight = HUGE_VALF;
Evan Chengd70dbb52008-02-22 09:24:50 +00001872 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1873 }
Evan Chengaee4af62007-12-02 08:30:39 +00001874 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001875 }
1876 // If folding is not possible / failed, then tell the spiller to issue a
1877 // load / rematerialization for us.
Evan Cheng597d10d2007-12-04 00:32:23 +00001878 if (Folded)
1879 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001880 else
Evan Cheng0cbb1162007-11-29 01:06:25 +00001881 vrm.addRestorePoint(VReg, MI);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001882
1883 // Update spill slot weight.
1884 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00001885 SSWeight += getSpillWeight(false, true, loopDepth);
Evan Cheng81a03822007-11-17 00:40:40 +00001886 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001887 Id = RestoreMBBs.find_next(Id);
Evan Cheng81a03822007-11-17 00:40:40 +00001888 }
1889
Evan Chengb50bb8c2007-12-05 08:16:32 +00001890 // Finalize intervals: add kills, finalize spill weights, and filter out
1891 // dead intervals.
Evan Cheng597d10d2007-12-04 00:32:23 +00001892 std::vector<LiveInterval*> RetNewLIs;
1893 for (unsigned i = 0, e = NewLIs.size(); i != e; ++i) {
1894 LiveInterval *LI = NewLIs[i];
1895 if (!LI->empty()) {
Owen Anderson496bac52008-07-23 19:47:27 +00001896 LI->weight /= InstrSlots::NUM * getApproximateInstructionCount(*LI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001897 if (!AddedKill.count(LI)) {
1898 LiveRange *LR = &LI->ranges[LI->ranges.size()-1];
Evan Chengd120ffd2007-12-05 10:24:35 +00001899 unsigned LastUseIdx = getBaseIndex(LR->end);
1900 MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx);
Evan Cheng6130f662008-03-05 00:59:57 +00001901 int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg, false);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001902 assert(UseIdx != -1);
Evan Chengd70dbb52008-02-22 09:24:50 +00001903 if (LastUse->getOperand(UseIdx).isImplicit() ||
1904 LastUse->getDesc().getOperandConstraint(UseIdx,TOI::TIED_TO) == -1){
Evan Chengb50bb8c2007-12-05 08:16:32 +00001905 LastUse->getOperand(UseIdx).setIsKill();
Evan Chengd120ffd2007-12-05 10:24:35 +00001906 vrm.addKillPoint(LI->reg, LastUseIdx);
Evan Chengadf85902007-12-05 09:51:10 +00001907 }
Evan Chengb50bb8c2007-12-05 08:16:32 +00001908 }
Evan Cheng597d10d2007-12-04 00:32:23 +00001909 RetNewLIs.push_back(LI);
1910 }
1911 }
Evan Cheng81a03822007-11-17 00:40:40 +00001912
Evan Cheng4cce6b42008-04-11 17:53:36 +00001913 handleSpilledImpDefs(li, vrm, rc, RetNewLIs);
Evan Cheng597d10d2007-12-04 00:32:23 +00001914 return RetNewLIs;
Evan Chengf2fbca62007-11-12 06:35:08 +00001915}
Evan Cheng676dd7c2008-03-11 07:19:34 +00001916
1917/// hasAllocatableSuperReg - Return true if the specified physical register has
1918/// any super register that's allocatable.
1919bool LiveIntervals::hasAllocatableSuperReg(unsigned Reg) const {
1920 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS)
1921 if (allocatableRegs_[*AS] && hasInterval(*AS))
1922 return true;
1923 return false;
1924}
1925
1926/// getRepresentativeReg - Find the largest super register of the specified
1927/// physical register.
1928unsigned LiveIntervals::getRepresentativeReg(unsigned Reg) const {
1929 // Find the largest super-register that is allocatable.
1930 unsigned BestReg = Reg;
1931 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS) {
1932 unsigned SuperReg = *AS;
1933 if (!hasAllocatableSuperReg(SuperReg) && hasInterval(SuperReg)) {
1934 BestReg = SuperReg;
1935 break;
1936 }
1937 }
1938 return BestReg;
1939}
1940
1941/// getNumConflictsWithPhysReg - Return the number of uses and defs of the
1942/// specified interval that conflicts with the specified physical register.
1943unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li,
1944 unsigned PhysReg) const {
1945 unsigned NumConflicts = 0;
1946 const LiveInterval &pli = getInterval(getRepresentativeReg(PhysReg));
1947 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
1948 E = mri_->reg_end(); I != E; ++I) {
1949 MachineOperand &O = I.getOperand();
1950 MachineInstr *MI = O.getParent();
1951 unsigned Index = getInstructionIndex(MI);
1952 if (pli.liveAt(Index))
1953 ++NumConflicts;
1954 }
1955 return NumConflicts;
1956}
1957
1958/// spillPhysRegAroundRegDefsUses - Spill the specified physical register
1959/// around all defs and uses of the specified interval.
1960void LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
1961 unsigned PhysReg, VirtRegMap &vrm) {
1962 unsigned SpillReg = getRepresentativeReg(PhysReg);
1963
1964 for (const unsigned *AS = tri_->getAliasSet(PhysReg); *AS; ++AS)
1965 // If there are registers which alias PhysReg, but which are not a
1966 // sub-register of the chosen representative super register. Assert
1967 // since we can't handle it yet.
1968 assert(*AS == SpillReg || !allocatableRegs_[*AS] ||
1969 tri_->isSuperRegister(*AS, SpillReg));
1970
1971 LiveInterval &pli = getInterval(SpillReg);
1972 SmallPtrSet<MachineInstr*, 8> SeenMIs;
1973 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
1974 E = mri_->reg_end(); I != E; ++I) {
1975 MachineOperand &O = I.getOperand();
1976 MachineInstr *MI = O.getParent();
1977 if (SeenMIs.count(MI))
1978 continue;
1979 SeenMIs.insert(MI);
1980 unsigned Index = getInstructionIndex(MI);
1981 if (pli.liveAt(Index)) {
1982 vrm.addEmergencySpill(SpillReg, MI);
1983 pli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
1984 for (const unsigned* AS = tri_->getSubRegisters(SpillReg); *AS; ++AS) {
1985 if (!hasInterval(*AS))
1986 continue;
1987 LiveInterval &spli = getInterval(*AS);
1988 if (spli.liveAt(Index))
1989 spli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
1990 }
1991 }
1992 }
1993}
Owen Andersonc4dc1322008-06-05 17:15:43 +00001994
1995LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
1996 MachineInstr* startInst) {
1997 LiveInterval& Interval = getOrCreateInterval(reg);
1998 VNInfo* VN = Interval.getNextValue(
1999 getInstructionIndex(startInst) + InstrSlots::DEF,
2000 startInst, getVNInfoAllocator());
2001 VN->hasPHIKill = true;
2002 VN->kills.push_back(getMBBEndIdx(startInst->getParent()));
2003 LiveRange LR(getInstructionIndex(startInst) + InstrSlots::DEF,
2004 getMBBEndIdx(startInst->getParent()) + 1, VN);
2005 Interval.addRange(LR);
2006
2007 return LR;
2008}