blob: 169143d63aeacc14d8bcb149982e4c55074c8f38 [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 }
Owen Anderson0c525ca2008-07-25 22:32:01 +0000129
Evan Cheng4ca980e2007-10-17 02:10:22 +0000130 std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
Owen Anderson80b3ce62008-05-28 20:54:50 +0000131
132 if (!OldI2MI.empty())
Owen Anderson7fbad272008-07-23 21:37:49 +0000133 for (iterator OI = begin(), OE = end(); OI != OE; ++OI)
134 for (LiveInterval::iterator LI = OI->second.begin(),
135 LE = OI->second.end(); LI != LE; ++LI) {
Owen Anderson4b5b2092008-05-29 18:15:49 +0000136
Owen Anderson7eec0c22008-05-29 23:01:22 +0000137 // Remap the start index of the live range to the corresponding new
138 // number, or our best guess at what it _should_ correspond to if the
139 // original instruction has been erased. This is either the following
140 // instruction or its predecessor.
Owen Anderson7fbad272008-07-23 21:37:49 +0000141 unsigned index = LI->start / InstrSlots::NUM;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000142 unsigned offset = LI->start % InstrSlots::NUM;
Owen Anderson0c525ca2008-07-25 22:32:01 +0000143 if (offset == InstrSlots::LOAD || LI->valno->def == ~0U) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000144 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000145 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->start);
Owen Anderson7fbad272008-07-23 21:37:49 +0000146 // Take the pair containing the index
147 std::vector<IdxMBBPair>::const_iterator J =
148 ((I != OldI2MBB.end() && I->first > index) ||
149 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000150
Owen Anderson7fbad272008-07-23 21:37:49 +0000151 LI->start = getMBBStartIdx(J->second);
152 } else {
153 LI->start = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000154 }
155
156 // Remap the ending index in the same way that we remapped the start,
157 // except for the final step where we always map to the immediately
158 // following instruction.
Owen Andersond7dcbec2008-07-25 19:50:48 +0000159 index = (LI->end - 1) / InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000160 offset = LI->end % InstrSlots::NUM;
Owen Anderson0c525ca2008-07-25 22:32:01 +0000161 if (LI->valno->hasPHIKill && !OldI2MI[index]) {
162 // Special handling for when this was previously killed by a PHI, but
163 // the PHI has now been removed. We need to trim the live interval
164 // to die at the end of the preceding block.
165 std::vector<IdxMBBPair>::const_iterator I =
166 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->end);
167 // Take the pair containing the index
168 std::vector<IdxMBBPair>::const_iterator J =
169 ((I != OldI2MBB.end() && I->first > index) ||
170 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
171
172 MachineBasicBlock* StartMBB = J->second;
173 MachineBasicBlock* CurrMBB = J->second;
174
175 while (CurrMBB == StartMBB) {
176 while (index > 0 && !OldI2MI[index]) --index;
177 CurrMBB = OldI2MI[index]->getParent();
178 if (!StartMBB) StartMBB = CurrMBB;
179
180 --index;
181 }
182
183 LI->end = getMBBEndIdx(CurrMBB) + 1;
184 } else if (offset == InstrSlots::USE) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000185 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000186 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->end);
Owen Anderson7fbad272008-07-23 21:37:49 +0000187 // Take the pair containing the index
188 std::vector<IdxMBBPair>::const_iterator J =
189 ((I != OldI2MBB.end() && I->first > index) ||
190 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
191
192 LI->end = getMBBEndIdx(J->second) + 1;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000193 } else {
Owen Andersond7dcbec2008-07-25 19:50:48 +0000194 unsigned idx = index;
Owen Anderson8d0cc0a2008-07-25 21:07:13 +0000195 while (index < OldI2MI.size() && !OldI2MI[index]) ++index;
196
197 if (index != OldI2MI.size())
198 LI->end = mi2iMap_[OldI2MI[index]] + (idx == index ? offset : 0);
199 else
200 LI->end = InstrSlots::NUM * i2miMap_.size();
Owen Anderson4b5b2092008-05-29 18:15:49 +0000201 }
Owen Anderson745825f42008-05-28 22:40:08 +0000202
Owen Anderson7eec0c22008-05-29 23:01:22 +0000203 // Remap the VNInfo def index, which works the same as the
204 // start indices above.
Owen Anderson745825f42008-05-28 22:40:08 +0000205 VNInfo* vni = LI->valno;
Owen Anderson0c525ca2008-07-25 22:32:01 +0000206 if (vni->def != ~0U) {
207 index = vni->def / InstrSlots::NUM;
208 offset = vni->def % InstrSlots::NUM;
209 if (offset == InstrSlots::LOAD) {
210 std::vector<IdxMBBPair>::const_iterator I =
211 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(),
212 vni->def);
213 // Take the pair containing the index
214 std::vector<IdxMBBPair>::const_iterator J =
215 ((I != OldI2MBB.end() && I->first > index) ||
216 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000217
Owen Anderson0c525ca2008-07-25 22:32:01 +0000218 vni->def = getMBBStartIdx(J->second);
Owen Anderson7fbad272008-07-23 21:37:49 +0000219
Owen Anderson0c525ca2008-07-25 22:32:01 +0000220 } else {
221 vni->def = mi2iMap_[OldI2MI[index]] + offset;
222 }
Owen Anderson7eec0c22008-05-29 23:01:22 +0000223 }
Owen Anderson745825f42008-05-28 22:40:08 +0000224
Owen Anderson7eec0c22008-05-29 23:01:22 +0000225 // Remap the VNInfo kill indices, which works the same as
226 // the end indices above.
Owen Anderson4b5b2092008-05-29 18:15:49 +0000227 for (size_t i = 0; i < vni->kills.size(); ++i) {
Owen Andersond7dcbec2008-07-25 19:50:48 +0000228 index = (vni->kills[i]-1) / InstrSlots::NUM;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000229 offset = vni->kills[i] % InstrSlots::NUM;
Owen Anderson0c525ca2008-07-25 22:32:01 +0000230
231 if (LI->valno->hasPHIKill && !OldI2MI[index]) {
232 // Special handling for when this was previously killed by a PHI,
233 // but the PHI has now been removed. We need to trim the live
234 // interval to die at the end of the preceding block.
235 std::vector<IdxMBBPair>::const_iterator I =
236 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->end);
237 // Take the pair containing the index
238 std::vector<IdxMBBPair>::const_iterator J =
239 ((I != OldI2MBB.end() && I->first > index) ||
240 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
241
242 MachineBasicBlock* StartMBB = J->second;
243 MachineBasicBlock* CurrMBB = J->second;
244
245 while (CurrMBB == StartMBB) {
246 while (index > 0 && !OldI2MI[index]) --index;
247 CurrMBB = OldI2MI[index]->getParent();
248 if (!StartMBB) StartMBB = CurrMBB;
249
250 --index;
251 }
252
253 vni->kills[i] = getMBBEndIdx(CurrMBB) + 1;
254 } else if (offset == InstrSlots::USE) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000255 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000256 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->kills[i]);
Owen Anderson7fbad272008-07-23 21:37:49 +0000257 // Take the pair containing the index
258 std::vector<IdxMBBPair>::const_iterator J =
259 ((I != OldI2MBB.end() && I->first > index) ||
260 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
261
262 vni->kills[i] = getMBBEndIdx(J->second) + 1;
263 } else {
Owen Andersond7dcbec2008-07-25 19:50:48 +0000264 unsigned idx = index;
265 while (!OldI2MI[index]) ++index;
Owen Anderson8d0cc0a2008-07-25 21:07:13 +0000266 while (index < OldI2MI.size() && !OldI2MI[index]) ++index;
267
268 if (index != OldI2MI.size())
269 vni->kills[i] = mi2iMap_[OldI2MI[index]] +
270 (idx == index ? offset : 0);
271 else
272 vni->kills[i] = InstrSlots::NUM * i2miMap_.size();
Owen Anderson7eec0c22008-05-29 23:01:22 +0000273 }
Owen Anderson4b5b2092008-05-29 18:15:49 +0000274 }
Owen Anderson80b3ce62008-05-28 20:54:50 +0000275 }
276}
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000277
Owen Anderson80b3ce62008-05-28 20:54:50 +0000278/// runOnMachineFunction - Register allocate the whole function
279///
280bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
281 mf_ = &fn;
282 mri_ = &mf_->getRegInfo();
283 tm_ = &fn.getTarget();
284 tri_ = tm_->getRegisterInfo();
285 tii_ = tm_->getInstrInfo();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000286 aa_ = &getAnalysis<AliasAnalysis>();
Owen Anderson80b3ce62008-05-28 20:54:50 +0000287 lv_ = &getAnalysis<LiveVariables>();
288 allocatableRegs_ = tri_->getAllocatableSet(fn);
289
290 computeNumbering();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000291 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000292
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000293 numIntervals += getNumIntervals();
294
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000295 DOUT << "********** INTERVALS **********\n";
296 for (iterator I = begin(), E = end(); I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000297 I->second.print(DOUT, tri_);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000298 DOUT << "\n";
299 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000300
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000301 numIntervalsAfter += getNumIntervals();
Chris Lattner70ca3582004-09-30 15:59:17 +0000302 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000303 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000304}
305
Chris Lattner70ca3582004-09-30 15:59:17 +0000306/// print - Implement the dump method.
Reid Spencerce9653c2004-12-07 04:03:45 +0000307void LiveIntervals::print(std::ostream &O, const Module* ) const {
Chris Lattner70ca3582004-09-30 15:59:17 +0000308 O << "********** INTERVALS **********\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000309 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Evan Cheng3f32d652008-06-04 09:18:41 +0000310 I->second.print(O, tri_);
311 O << "\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000312 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000313
314 O << "********** MACHINEINSTRS **********\n";
315 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
316 mbbi != mbbe; ++mbbi) {
317 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
318 for (MachineBasicBlock::iterator mii = mbbi->begin(),
319 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner477e4552004-09-30 16:10:45 +0000320 O << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner70ca3582004-09-30 15:59:17 +0000321 }
322 }
323}
324
Evan Chengc92da382007-11-03 07:20:12 +0000325/// conflictsWithPhysRegDef - Returns true if the specified register
326/// is defined during the duration of the specified interval.
327bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
328 VirtRegMap &vrm, unsigned reg) {
329 for (LiveInterval::Ranges::const_iterator
330 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
331 for (unsigned index = getBaseIndex(I->start),
332 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
333 index += InstrSlots::NUM) {
334 // skip deleted instructions
335 while (index != end && !getInstructionFromIndex(index))
336 index += InstrSlots::NUM;
337 if (index == end) break;
338
339 MachineInstr *MI = getInstructionFromIndex(index);
Evan Cheng5d446262007-11-15 08:13:29 +0000340 unsigned SrcReg, DstReg;
341 if (tii_->isMoveInstr(*MI, SrcReg, DstReg))
342 if (SrcReg == li.reg || DstReg == li.reg)
343 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000344 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
345 MachineOperand& mop = MI->getOperand(i);
Evan Cheng5d446262007-11-15 08:13:29 +0000346 if (!mop.isRegister())
Evan Chengc92da382007-11-03 07:20:12 +0000347 continue;
348 unsigned PhysReg = mop.getReg();
Evan Cheng5d446262007-11-15 08:13:29 +0000349 if (PhysReg == 0 || PhysReg == li.reg)
Evan Chengc92da382007-11-03 07:20:12 +0000350 continue;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000351 if (TargetRegisterInfo::isVirtualRegister(PhysReg)) {
Evan Cheng5d446262007-11-15 08:13:29 +0000352 if (!vrm.hasPhys(PhysReg))
353 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000354 PhysReg = vrm.getPhys(PhysReg);
Evan Cheng5d446262007-11-15 08:13:29 +0000355 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000356 if (PhysReg && tri_->regsOverlap(PhysReg, reg))
Evan Chengc92da382007-11-03 07:20:12 +0000357 return true;
358 }
359 }
360 }
361
362 return false;
363}
364
Evan Cheng549f27d32007-08-13 23:45:17 +0000365void LiveIntervals::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000366 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000367 cerr << tri_->getName(reg);
Evan Cheng549f27d32007-08-13 23:45:17 +0000368 else
369 cerr << "%reg" << reg;
370}
371
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000372void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000373 MachineBasicBlock::iterator mi,
Owen Anderson6b098de2008-06-25 23:39:39 +0000374 unsigned MIIdx, MachineOperand& MO,
Evan Chengef0732d2008-07-10 07:35:43 +0000375 unsigned MOIdx,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000376 LiveInterval &interval) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000377 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000378 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000379
Evan Cheng419852c2008-04-03 16:39:43 +0000380 if (mi->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
381 DOUT << "is a implicit_def\n";
382 return;
383 }
384
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000385 // Virtual registers may be defined multiple times (due to phi
386 // elimination and 2-addr elimination). Much of what we do only has to be
387 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000388 // time we see a vreg.
389 if (interval.empty()) {
390 // Get the Idx of the defining instructions.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000391 unsigned defIndex = getDefIndex(MIIdx);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000392 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000393 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000394 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000395 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000396 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000397 tii_->isMoveInstr(*mi, SrcReg, DstReg))
398 CopyMI = mi;
399 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000400
401 assert(ValNo->id == 0 && "First value in interval is not 0?");
Chris Lattner7ac2d312004-07-24 02:59:07 +0000402
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000403 // Loop over all of the blocks that the vreg is defined in. There are
404 // two cases we have to handle here. The most common case is a vreg
405 // whose lifetime is contained within a basic block. In this case there
406 // will be a single kill, in MBB, which comes after the definition.
407 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
408 // FIXME: what about dead vars?
409 unsigned killIdx;
410 if (vi.Kills[0] != mi)
411 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
412 else
413 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000414
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000415 // If the kill happens after the definition, we have an intra-block
416 // live range.
417 if (killIdx > defIndex) {
Evan Cheng61de82d2007-02-15 05:59:24 +0000418 assert(vi.AliveBlocks.none() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000419 "Shouldn't be alive across any blocks!");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000420 LiveRange LR(defIndex, killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000421 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000422 DOUT << " +" << LR << "\n";
Evan Chengf3bb2e62007-09-05 21:46:51 +0000423 interval.addKill(ValNo, killIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000424 return;
425 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000426 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000427
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000428 // The other case we handle is when a virtual register lives to the end
429 // of the defining block, potentially live across some blocks, then is
430 // live into some number of blocks, but gets killed. Start by adding a
431 // range that goes from this definition to the end of the defining block.
Owen Anderson7fbad272008-07-23 21:37:49 +0000432 LiveRange NewLR(defIndex, getMBBEndIdx(mbb)+1, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000433 DOUT << " +" << NewLR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000434 interval.addRange(NewLR);
435
436 // Iterate over all of the blocks that the variable is completely
437 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
438 // live interval.
439 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
440 if (vi.AliveBlocks[i]) {
Owen Anderson31ec8412008-06-16 19:32:40 +0000441 LiveRange LR(getMBBStartIdx(i),
Evan Chengf26e8552008-06-17 20:13:36 +0000442 getMBBEndIdx(i)+1, // MBB ends at -1.
Owen Anderson31ec8412008-06-16 19:32:40 +0000443 ValNo);
444 interval.addRange(LR);
445 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000446 }
447 }
448
449 // Finally, this virtual register is live from the start of any killing
450 // block to the 'use' slot of the killing instruction.
451 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
452 MachineInstr *Kill = vi.Kills[i];
Evan Cheng8df78602007-08-08 03:00:28 +0000453 unsigned killIdx = getUseIndex(getInstructionIndex(Kill))+1;
Chris Lattner428b92e2006-09-15 03:57:23 +0000454 LiveRange LR(getMBBStartIdx(Kill->getParent()),
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000455 killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000456 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000457 interval.addKill(ValNo, killIdx);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000458 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000459 }
460
461 } else {
462 // If this is the second time we see a virtual register definition, it
463 // must be due to phi elimination or two addr elimination. If this is
Evan Chengbf105c82006-11-03 03:04:46 +0000464 // the result of two address elimination, then the vreg is one of the
465 // def-and-use register operand.
Evan Chengef0732d2008-07-10 07:35:43 +0000466 if (mi->isRegReDefinedByTwoAddr(interval.reg, MOIdx)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000467 // If this is a two-address definition, then we have already processed
468 // the live range. The only problem is that we didn't realize there
469 // are actually two values in the live interval. Because of this we
470 // need to take the LiveRegion that defines this register and split it
471 // into two values.
Evan Chenga07cec92008-01-10 08:22:10 +0000472 assert(interval.containsOneValue());
473 unsigned DefIndex = getDefIndex(interval.getValNumInfo(0)->def);
Chris Lattner6b128bd2006-09-03 08:07:11 +0000474 unsigned RedefIndex = getDefIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000475
Evan Cheng4f8ff162007-08-11 00:59:19 +0000476 const LiveRange *OldLR = interval.getLiveRangeContaining(RedefIndex-1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000477 VNInfo *OldValNo = OldLR->valno;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000478
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000479 // Delete the initial value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000480 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000481 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000482
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000483 // Two-address vregs should always only be redefined once. This means
484 // that at this point, there should be exactly one value number in it.
485 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
486
Chris Lattner91725b72006-08-31 05:54:43 +0000487 // The new value number (#1) is defined by the instruction we claimed
488 // defined value #0.
Evan Chengc8d044e2008-02-15 18:24:29 +0000489 VNInfo *ValNo = interval.getNextValue(OldValNo->def, OldValNo->copy,
490 VNInfoAllocator);
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000491
Chris Lattner91725b72006-08-31 05:54:43 +0000492 // Value#0 is now defined by the 2-addr instruction.
Evan Chengc8d044e2008-02-15 18:24:29 +0000493 OldValNo->def = RedefIndex;
494 OldValNo->copy = 0;
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000495
496 // Add the new live interval which replaces the range for the input copy.
497 LiveRange LR(DefIndex, RedefIndex, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000498 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000499 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000500 interval.addKill(ValNo, RedefIndex);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000501
502 // If this redefinition is dead, we need to add a dummy unit live
503 // range covering the def slot.
Owen Anderson6b098de2008-06-25 23:39:39 +0000504 if (MO.isDead())
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000505 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, OldValNo));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000506
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000507 DOUT << " RESULT: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000508 interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000509
510 } else {
511 // Otherwise, this must be because of phi elimination. If this is the
512 // first redefinition of the vreg that we have seen, go back and change
513 // the live range in the PHI block to be a different value number.
514 if (interval.containsOneValue()) {
515 assert(vi.Kills.size() == 1 &&
516 "PHI elimination vreg should have one kill, the PHI itself!");
517
518 // Remove the old range that we now know has an incorrect number.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000519 VNInfo *VNI = interval.getValNumInfo(0);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000520 MachineInstr *Killer = vi.Kills[0];
Chris Lattner428b92e2006-09-15 03:57:23 +0000521 unsigned Start = getMBBStartIdx(Killer->getParent());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000522 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000523 DOUT << " Removing [" << Start << "," << End << "] from: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000524 interval.print(DOUT, tri_); DOUT << "\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000525 interval.removeRange(Start, End);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000526 VNI->hasPHIKill = true;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000527 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000528
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000529 // Replace the interval with one of a NEW value number. Note that this
530 // value number isn't actually defined by an instruction, weird huh? :)
Evan Chengf3bb2e62007-09-05 21:46:51 +0000531 LiveRange LR(Start, End, interval.getNextValue(~0, 0, VNInfoAllocator));
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000532 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000533 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000534 interval.addKill(LR.valno, End);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000535 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000536 }
537
538 // In the case of PHI elimination, each variable definition is only
539 // live until the end of the block. We've already taken care of the
540 // rest of the live range.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000541 unsigned defIndex = getDefIndex(MIIdx);
Chris Lattner91725b72006-08-31 05:54:43 +0000542
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000543 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000544 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000545 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000546 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000547 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000548 tii_->isMoveInstr(*mi, SrcReg, DstReg))
549 CopyMI = mi;
550 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Chris Lattner91725b72006-08-31 05:54:43 +0000551
Owen Anderson7fbad272008-07-23 21:37:49 +0000552 unsigned killIndex = getMBBEndIdx(mbb) + 1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000553 LiveRange LR(defIndex, killIndex, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000554 interval.addRange(LR);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000555 interval.addKill(ValNo, killIndex);
556 ValNo->hasPHIKill = true;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000557 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000558 }
559 }
560
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000561 DOUT << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000562}
563
Chris Lattnerf35fef72004-07-23 21:24:19 +0000564void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000565 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000566 unsigned MIIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000567 MachineOperand& MO,
Chris Lattner91725b72006-08-31 05:54:43 +0000568 LiveInterval &interval,
Evan Chengc8d044e2008-02-15 18:24:29 +0000569 MachineInstr *CopyMI) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000570 // A physical register cannot be live across basic block, so its
571 // lifetime must end somewhere in its defining basic block.
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000572 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000573
Chris Lattner6b128bd2006-09-03 08:07:11 +0000574 unsigned baseIndex = MIIdx;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000575 unsigned start = getDefIndex(baseIndex);
576 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000577
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000578 // If it is not used after definition, it is considered dead at
579 // the instruction defining it. Hence its interval is:
580 // [defSlot(def), defSlot(def)+1)
Owen Anderson6b098de2008-06-25 23:39:39 +0000581 if (MO.isDead()) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000582 DOUT << " dead";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000583 end = getDefIndex(start) + 1;
584 goto exit;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000585 }
586
587 // If it is not dead on definition, it must be killed by a
588 // subsequent instruction. Hence its interval is:
589 // [defSlot(def), useSlot(kill)+1)
Owen Anderson7fbad272008-07-23 21:37:49 +0000590 baseIndex += InstrSlots::NUM;
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000591 while (++mi != MBB->end()) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000592 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
593 getInstructionFromIndex(baseIndex) == 0)
594 baseIndex += InstrSlots::NUM;
Evan Cheng6130f662008-03-05 00:59:57 +0000595 if (mi->killsRegister(interval.reg, tri_)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000596 DOUT << " killed";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000597 end = getUseIndex(baseIndex) + 1;
598 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000599 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Cheng9a1956a2006-11-15 20:54:11 +0000600 // Another instruction redefines the register before it is ever read.
601 // Then the register is essentially dead at the instruction that defines
602 // it. Hence its interval is:
603 // [defSlot(def), defSlot(def)+1)
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000604 DOUT << " dead";
Evan Cheng9a1956a2006-11-15 20:54:11 +0000605 end = getDefIndex(start) + 1;
606 goto exit;
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000607 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000608
609 baseIndex += InstrSlots::NUM;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000610 }
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000611
612 // The only case we should have a dead physreg here without a killing or
613 // instruction where we know it's dead is if it is live-in to the function
614 // and never used.
Evan Chengc8d044e2008-02-15 18:24:29 +0000615 assert(!CopyMI && "physreg was not killed in defining block!");
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000616 end = getDefIndex(start) + 1; // It's dead.
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000617
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000618exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000619 assert(start < end && "did not find end of interval?");
Chris Lattnerf768bba2005-03-09 23:05:19 +0000620
Evan Cheng24a3cc42007-04-25 07:30:23 +0000621 // Already exists? Extend old live interval.
622 LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000623 VNInfo *ValNo = (OldLR != interval.end())
Evan Chengc8d044e2008-02-15 18:24:29 +0000624 ? OldLR->valno : interval.getNextValue(start, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000625 LiveRange LR(start, end, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000626 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000627 interval.addKill(LR.valno, end);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000628 DOUT << " +" << LR << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000629}
630
Chris Lattnerf35fef72004-07-23 21:24:19 +0000631void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
632 MachineBasicBlock::iterator MI,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000633 unsigned MIIdx,
Evan Chengef0732d2008-07-10 07:35:43 +0000634 MachineOperand& MO,
635 unsigned MOIdx) {
Owen Anderson6b098de2008-06-25 23:39:39 +0000636 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Evan Chengef0732d2008-07-10 07:35:43 +0000637 handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000638 getOrCreateInterval(MO.getReg()));
639 else if (allocatableRegs_[MO.getReg()]) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000640 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000641 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000642 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000643 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000644 tii_->isMoveInstr(*MI, SrcReg, DstReg))
645 CopyMI = MI;
Owen Anderson6b098de2008-06-25 23:39:39 +0000646 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
647 getOrCreateInterval(MO.getReg()), CopyMI);
Evan Cheng24a3cc42007-04-25 07:30:23 +0000648 // Def of a register also defines its sub-registers.
Owen Anderson6b098de2008-06-25 23:39:39 +0000649 for (const unsigned* AS = tri_->getSubRegisters(MO.getReg()); *AS; ++AS)
Evan Cheng6130f662008-03-05 00:59:57 +0000650 // If MI also modifies the sub-register explicitly, avoid processing it
651 // more than once. Do not pass in TRI here so it checks for exact match.
652 if (!MI->modifiesRegister(*AS))
Owen Anderson6b098de2008-06-25 23:39:39 +0000653 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
654 getOrCreateInterval(*AS), 0);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000655 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000656}
657
Evan Chengb371f452007-02-19 21:49:54 +0000658void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000659 unsigned MIIdx,
Evan Cheng24a3cc42007-04-25 07:30:23 +0000660 LiveInterval &interval, bool isAlias) {
Evan Chengb371f452007-02-19 21:49:54 +0000661 DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg));
662
663 // Look for kills, if it reaches a def before it's killed, then it shouldn't
664 // be considered a livein.
665 MachineBasicBlock::iterator mi = MBB->begin();
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000666 unsigned baseIndex = MIIdx;
667 unsigned start = baseIndex;
Evan Chengb371f452007-02-19 21:49:54 +0000668 unsigned end = start;
669 while (mi != MBB->end()) {
Evan Cheng6130f662008-03-05 00:59:57 +0000670 if (mi->killsRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000671 DOUT << " killed";
672 end = getUseIndex(baseIndex) + 1;
673 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000674 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000675 // Another instruction redefines the register before it is ever read.
676 // Then the register is essentially dead at the instruction that defines
677 // it. Hence its interval is:
678 // [defSlot(def), defSlot(def)+1)
679 DOUT << " dead";
680 end = getDefIndex(start) + 1;
681 goto exit;
682 }
683
684 baseIndex += InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000685 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
686 getInstructionFromIndex(baseIndex) == 0)
687 baseIndex += InstrSlots::NUM;
Evan Chengb371f452007-02-19 21:49:54 +0000688 ++mi;
689 }
690
691exit:
Evan Cheng75611fb2007-06-27 01:16:36 +0000692 // Live-in register might not be used at all.
693 if (end == MIIdx) {
Evan Cheng292da942007-06-27 18:47:28 +0000694 if (isAlias) {
695 DOUT << " dead";
Evan Cheng75611fb2007-06-27 01:16:36 +0000696 end = getDefIndex(MIIdx) + 1;
Evan Cheng292da942007-06-27 18:47:28 +0000697 } else {
698 DOUT << " live through";
699 end = baseIndex;
700 }
Evan Cheng24a3cc42007-04-25 07:30:23 +0000701 }
702
Evan Chengf3bb2e62007-09-05 21:46:51 +0000703 LiveRange LR(start, end, interval.getNextValue(start, 0, VNInfoAllocator));
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000704 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000705 interval.addKill(LR.valno, end);
Evan Cheng24c2e5c2007-08-08 07:03:29 +0000706 DOUT << " +" << LR << '\n';
Evan Chengb371f452007-02-19 21:49:54 +0000707}
708
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000709/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000710/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000711/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000712/// which a variable is live
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000713void LiveIntervals::computeIntervals() {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000714 DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
715 << "********** Function: "
716 << ((Value*)mf_->getFunction())->getName() << '\n';
Chris Lattner6b128bd2006-09-03 08:07:11 +0000717 // Track the index of the current machine instr.
718 unsigned MIIndex = 0;
Owen Anderson7fbad272008-07-23 21:37:49 +0000719
720 // Skip over empty initial indices.
721 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
722 getInstructionFromIndex(MIIndex) == 0)
723 MIIndex += InstrSlots::NUM;
724
Chris Lattner428b92e2006-09-15 03:57:23 +0000725 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
726 MBBI != E; ++MBBI) {
727 MachineBasicBlock *MBB = MBBI;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000728 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000729
Chris Lattner428b92e2006-09-15 03:57:23 +0000730 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000731
Dan Gohmancb406c22007-10-03 19:26:29 +0000732 // Create intervals for live-ins to this BB first.
733 for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
734 LE = MBB->livein_end(); LI != LE; ++LI) {
735 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
736 // Multiple live-ins can alias the same register.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000737 for (const unsigned* AS = tri_->getSubRegisters(*LI); *AS; ++AS)
Dan Gohmancb406c22007-10-03 19:26:29 +0000738 if (!hasInterval(*AS))
739 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
740 true);
Chris Lattnerdffb2e82006-09-04 18:27:40 +0000741 }
742
Chris Lattner428b92e2006-09-15 03:57:23 +0000743 for (; MI != miEnd; ++MI) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000744 DOUT << MIIndex << "\t" << *MI;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000745
Evan Cheng438f7bc2006-11-10 08:43:01 +0000746 // Handle defs.
Chris Lattner428b92e2006-09-15 03:57:23 +0000747 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
748 MachineOperand &MO = MI->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000749 // handle register defs - build intervals
Chris Lattner428b92e2006-09-15 03:57:23 +0000750 if (MO.isRegister() && MO.getReg() && MO.isDef())
Evan Chengef0732d2008-07-10 07:35:43 +0000751 handleRegisterDef(MBB, MI, MIIndex, MO, i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000752 }
Chris Lattner6b128bd2006-09-03 08:07:11 +0000753
754 MIIndex += InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000755
756 // Skip over empty indices.
757 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
758 getInstructionFromIndex(MIIndex) == 0)
759 MIIndex += InstrSlots::NUM;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000760 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000761 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000762}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000763
Evan Cheng4ca980e2007-10-17 02:10:22 +0000764bool LiveIntervals::findLiveInMBBs(const LiveRange &LR,
Evan Chenga5bfc972007-10-17 06:53:44 +0000765 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
Evan Cheng4ca980e2007-10-17 02:10:22 +0000766 std::vector<IdxMBBPair>::const_iterator I =
767 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), LR.start);
768
769 bool ResVal = false;
770 while (I != Idx2MBBMap.end()) {
771 if (LR.end <= I->first)
772 break;
773 MBBs.push_back(I->second);
774 ResVal = true;
775 ++I;
776 }
777 return ResVal;
778}
779
780
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000781LiveInterval LiveIntervals::createInterval(unsigned reg) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000782 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
Jim Laskey7902c752006-11-07 12:25:45 +0000783 HUGE_VALF : 0.0F;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000784 return LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000785}
Evan Chengf2fbca62007-11-12 06:35:08 +0000786
Evan Chengc8d044e2008-02-15 18:24:29 +0000787/// getVNInfoSourceReg - Helper function that parses the specified VNInfo
788/// copy field and returns the source register that defines it.
789unsigned LiveIntervals::getVNInfoSourceReg(const VNInfo *VNI) const {
790 if (!VNI->copy)
791 return 0;
792
793 if (VNI->copy->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
794 return VNI->copy->getOperand(1).getReg();
Evan Cheng7e073ba2008-04-09 20:57:25 +0000795 if (VNI->copy->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
796 return VNI->copy->getOperand(2).getReg();
Evan Chengc8d044e2008-02-15 18:24:29 +0000797 unsigned SrcReg, DstReg;
798 if (tii_->isMoveInstr(*VNI->copy, SrcReg, DstReg))
799 return SrcReg;
800 assert(0 && "Unrecognized copy instruction!");
801 return 0;
802}
Evan Chengf2fbca62007-11-12 06:35:08 +0000803
804//===----------------------------------------------------------------------===//
805// Register allocator hooks.
806//
807
Evan Chengd70dbb52008-02-22 09:24:50 +0000808/// getReMatImplicitUse - If the remat definition MI has one (for now, we only
809/// allow one) virtual register operand, then its uses are implicitly using
810/// the register. Returns the virtual register.
811unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
812 MachineInstr *MI) const {
813 unsigned RegOp = 0;
814 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
815 MachineOperand &MO = MI->getOperand(i);
816 if (!MO.isRegister() || !MO.isUse())
817 continue;
818 unsigned Reg = MO.getReg();
819 if (Reg == 0 || Reg == li.reg)
820 continue;
821 // FIXME: For now, only remat MI with at most one register operand.
822 assert(!RegOp &&
823 "Can't rematerialize instruction with multiple register operand!");
824 RegOp = MO.getReg();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000825#ifndef NDEBUG
Evan Chengd70dbb52008-02-22 09:24:50 +0000826 break;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000827#endif
Evan Chengd70dbb52008-02-22 09:24:50 +0000828 }
829 return RegOp;
830}
831
832/// isValNoAvailableAt - Return true if the val# of the specified interval
833/// which reaches the given instruction also reaches the specified use index.
834bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
835 unsigned UseIdx) const {
836 unsigned Index = getInstructionIndex(MI);
837 VNInfo *ValNo = li.FindLiveRangeContaining(Index)->valno;
838 LiveInterval::const_iterator UI = li.FindLiveRangeContaining(UseIdx);
839 return UI != li.end() && UI->valno == ValNo;
840}
841
Evan Chengf2fbca62007-11-12 06:35:08 +0000842/// isReMaterializable - Returns true if the definition MI of the specified
843/// val# of the specified interval is re-materializable.
844bool LiveIntervals::isReMaterializable(const LiveInterval &li,
Evan Cheng5ef3a042007-12-06 00:01:56 +0000845 const VNInfo *ValNo, MachineInstr *MI,
846 bool &isLoad) {
Evan Chengf2fbca62007-11-12 06:35:08 +0000847 if (DisableReMat)
848 return false;
849
Evan Cheng20ccded2008-03-15 00:19:36 +0000850 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
Evan Chengd70dbb52008-02-22 09:24:50 +0000851 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000852
853 int FrameIdx = 0;
854 if (tii_->isLoadFromStackSlot(MI, FrameIdx) &&
Evan Cheng249ded32008-02-23 03:38:34 +0000855 mf_->getFrameInfo()->isImmutableObjectIndex(FrameIdx))
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000856 // FIXME: Let target specific isReallyTriviallyReMaterializable determines
857 // this but remember this is not safe to fold into a two-address
858 // instruction.
Evan Cheng249ded32008-02-23 03:38:34 +0000859 // This is a load from fixed stack slot. It can be rematerialized.
Evan Chengdd3465e2008-02-23 01:44:27 +0000860 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000861
Dan Gohman6d69ba82008-07-25 00:02:30 +0000862 // If the target-specific rules don't identify an instruction as
863 // being trivially rematerializable, use some target-independent
864 // rules.
865 if (!MI->getDesc().isRematerializable() ||
866 !tii_->isTriviallyReMaterializable(MI)) {
Dan Gohman4c8f8702008-07-25 15:08:37 +0000867 if (!EnableAggressiveRemat)
868 return false;
Evan Chengd70dbb52008-02-22 09:24:50 +0000869
Dan Gohman6d69ba82008-07-25 00:02:30 +0000870 // If the instruction access memory but the memoperands have been lost,
871 // we can't analyze it.
872 const TargetInstrDesc &TID = MI->getDesc();
873 if ((TID.mayLoad() || TID.mayStore()) && MI->memoperands_empty())
874 return false;
875
876 // Avoid instructions obviously unsafe for remat.
877 if (TID.hasUnmodeledSideEffects() || TID.isNotDuplicable())
878 return false;
879
880 // If the instruction accesses memory and the memory could be non-constant,
881 // assume the instruction is not rematerializable.
882 for (alist<MachineMemOperand>::const_iterator I = MI->memoperands_begin(),
883 E = MI->memoperands_end(); I != E; ++I) {
884 const MachineMemOperand &MMO = *I;
885 if (MMO.isVolatile() || MMO.isStore())
886 return false;
887 const Value *V = MMO.getValue();
888 if (!V)
889 return false;
890 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
891 if (!PSV->isConstant(mf_->getFrameInfo()))
Evan Chengd70dbb52008-02-22 09:24:50 +0000892 return false;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000893 } else if (!aa_->pointsToConstantMemory(V))
894 return false;
895 }
896
897 // If any of the registers accessed are non-constant, conservatively assume
898 // the instruction is not rematerializable.
899 unsigned ImpUse = 0;
900 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
901 const MachineOperand &MO = MI->getOperand(i);
902 if (MO.isReg()) {
903 unsigned Reg = MO.getReg();
904 if (Reg == 0)
905 continue;
906 if (TargetRegisterInfo::isPhysicalRegister(Reg))
907 return false;
908
909 // Only allow one def, and that in the first operand.
910 if (MO.isDef() != (i == 0))
911 return false;
912
913 // Only allow constant-valued registers.
914 bool IsLiveIn = mri_->isLiveIn(Reg);
915 MachineRegisterInfo::def_iterator I = mri_->def_begin(Reg),
916 E = mri_->def_end();
917
918 // For the def, it should be the only def.
919 if (MO.isDef() && (next(I) != E || IsLiveIn))
920 return false;
921
922 if (MO.isUse()) {
923 // Only allow one use other register use, as that's all the
924 // remat mechanisms support currently.
925 if (Reg != li.reg) {
926 if (ImpUse == 0)
927 ImpUse = Reg;
928 else if (Reg != ImpUse)
929 return false;
930 }
931 // For uses, there should be only one associate def.
932 if (I != E && (next(I) != E || IsLiveIn))
933 return false;
934 }
Evan Chengd70dbb52008-02-22 09:24:50 +0000935 }
936 }
Evan Cheng5ef3a042007-12-06 00:01:56 +0000937 }
Evan Chengf2fbca62007-11-12 06:35:08 +0000938
Dan Gohman6d69ba82008-07-25 00:02:30 +0000939 unsigned ImpUse = getReMatImplicitUse(li, MI);
940 if (ImpUse) {
941 const LiveInterval &ImpLi = getInterval(ImpUse);
942 for (MachineRegisterInfo::use_iterator ri = mri_->use_begin(li.reg),
943 re = mri_->use_end(); ri != re; ++ri) {
944 MachineInstr *UseMI = &*ri;
945 unsigned UseIdx = getInstructionIndex(UseMI);
946 if (li.FindLiveRangeContaining(UseIdx)->valno != ValNo)
947 continue;
948 if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
949 return false;
950 }
951 }
952 return true;
Evan Cheng5ef3a042007-12-06 00:01:56 +0000953}
954
955/// isReMaterializable - Returns true if every definition of MI of every
956/// val# of the specified interval is re-materializable.
957bool LiveIntervals::isReMaterializable(const LiveInterval &li, bool &isLoad) {
958 isLoad = false;
959 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
960 i != e; ++i) {
961 const VNInfo *VNI = *i;
962 unsigned DefIdx = VNI->def;
963 if (DefIdx == ~1U)
964 continue; // Dead val#.
965 // Is the def for the val# rematerializable?
966 if (DefIdx == ~0u)
967 return false;
968 MachineInstr *ReMatDefMI = getInstructionFromIndex(DefIdx);
969 bool DefIsLoad = false;
Evan Chengd70dbb52008-02-22 09:24:50 +0000970 if (!ReMatDefMI ||
971 !isReMaterializable(li, VNI, ReMatDefMI, DefIsLoad))
Evan Cheng5ef3a042007-12-06 00:01:56 +0000972 return false;
973 isLoad |= DefIsLoad;
Evan Chengf2fbca62007-11-12 06:35:08 +0000974 }
975 return true;
976}
977
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000978/// FilterFoldedOps - Filter out two-address use operands. Return
979/// true if it finds any issue with the operands that ought to prevent
980/// folding.
981static bool FilterFoldedOps(MachineInstr *MI,
982 SmallVector<unsigned, 2> &Ops,
983 unsigned &MRInfo,
984 SmallVector<unsigned, 2> &FoldOps) {
Chris Lattner749c6f62008-01-07 07:27:27 +0000985 const TargetInstrDesc &TID = MI->getDesc();
Evan Cheng6e141fd2007-12-12 23:12:09 +0000986
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000987 MRInfo = 0;
Evan Chengaee4af62007-12-02 08:30:39 +0000988 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
989 unsigned OpIdx = Ops[i];
Evan Chengd70dbb52008-02-22 09:24:50 +0000990 MachineOperand &MO = MI->getOperand(OpIdx);
Evan Chengaee4af62007-12-02 08:30:39 +0000991 // FIXME: fold subreg use.
Evan Chengd70dbb52008-02-22 09:24:50 +0000992 if (MO.getSubReg())
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000993 return true;
Evan Chengd70dbb52008-02-22 09:24:50 +0000994 if (MO.isDef())
Evan Chengaee4af62007-12-02 08:30:39 +0000995 MRInfo |= (unsigned)VirtRegMap::isMod;
996 else {
997 // Filter out two-address use operand(s).
Evan Chengd70dbb52008-02-22 09:24:50 +0000998 if (!MO.isImplicit() &&
999 TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1) {
Evan Chengaee4af62007-12-02 08:30:39 +00001000 MRInfo = VirtRegMap::isModRef;
1001 continue;
1002 }
1003 MRInfo |= (unsigned)VirtRegMap::isRef;
1004 }
1005 FoldOps.push_back(OpIdx);
Evan Chenge62f97c2007-12-01 02:07:52 +00001006 }
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001007 return false;
1008}
1009
1010
1011/// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
1012/// slot / to reg or any rematerialized load into ith operand of specified
1013/// MI. If it is successul, MI is updated with the newly created MI and
1014/// returns true.
1015bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
1016 VirtRegMap &vrm, MachineInstr *DefMI,
1017 unsigned InstrIdx,
1018 SmallVector<unsigned, 2> &Ops,
1019 bool isSS, int Slot, unsigned Reg) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001020 // If it is an implicit def instruction, just delete it.
Evan Cheng20ccded2008-03-15 00:19:36 +00001021 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001022 RemoveMachineInstrFromMaps(MI);
1023 vrm.RemoveMachineInstrFromMaps(MI);
1024 MI->eraseFromParent();
1025 ++numFolds;
1026 return true;
1027 }
1028
1029 // Filter the list of operand indexes that are to be folded. Abort if
1030 // any operand will prevent folding.
1031 unsigned MRInfo = 0;
1032 SmallVector<unsigned, 2> FoldOps;
1033 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1034 return false;
Evan Chenge62f97c2007-12-01 02:07:52 +00001035
Evan Cheng427f4c12008-03-31 23:19:51 +00001036 // The only time it's safe to fold into a two address instruction is when
1037 // it's folding reload and spill from / into a spill stack slot.
1038 if (DefMI && (MRInfo & VirtRegMap::isMod))
Evan Cheng249ded32008-02-23 03:38:34 +00001039 return false;
1040
Evan Chengf2f8c2a2008-02-08 22:05:27 +00001041 MachineInstr *fmi = isSS ? tii_->foldMemoryOperand(*mf_, MI, FoldOps, Slot)
1042 : tii_->foldMemoryOperand(*mf_, MI, FoldOps, DefMI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001043 if (fmi) {
Evan Chengd3653122008-02-27 03:04:06 +00001044 // Remember this instruction uses the spill slot.
1045 if (isSS) vrm.addSpillSlotUse(Slot, fmi);
1046
Evan Chengf2fbca62007-11-12 06:35:08 +00001047 // Attempt to fold the memory reference into the instruction. If
1048 // we can do this, we don't need to insert spill code.
Evan Chengf2fbca62007-11-12 06:35:08 +00001049 MachineBasicBlock &MBB = *MI->getParent();
Evan Cheng84802932008-01-10 08:24:38 +00001050 if (isSS && !mf_->getFrameInfo()->isImmutableObjectIndex(Slot))
Evan Chengaee4af62007-12-02 08:30:39 +00001051 vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
Evan Cheng81a03822007-11-17 00:40:40 +00001052 vrm.transferSpillPts(MI, fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001053 vrm.transferRestorePts(MI, fmi);
Evan Chengc1f53c72008-03-11 21:34:46 +00001054 vrm.transferEmergencySpills(MI, fmi);
Evan Chengf2fbca62007-11-12 06:35:08 +00001055 mi2iMap_.erase(MI);
Evan Chengcddbb832007-11-30 21:23:43 +00001056 i2miMap_[InstrIdx /InstrSlots::NUM] = fmi;
1057 mi2iMap_[fmi] = InstrIdx;
Evan Chengf2fbca62007-11-12 06:35:08 +00001058 MI = MBB.insert(MBB.erase(MI), fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001059 ++numFolds;
Evan Chengf2fbca62007-11-12 06:35:08 +00001060 return true;
1061 }
1062 return false;
1063}
1064
Evan Cheng018f9b02007-12-05 03:22:34 +00001065/// canFoldMemoryOperand - Returns true if the specified load / store
1066/// folding is possible.
1067bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI,
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001068 SmallVector<unsigned, 2> &Ops,
Evan Cheng3c75ba82008-04-01 21:37:32 +00001069 bool ReMat) const {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001070 // Filter the list of operand indexes that are to be folded. Abort if
1071 // any operand will prevent folding.
1072 unsigned MRInfo = 0;
Evan Cheng018f9b02007-12-05 03:22:34 +00001073 SmallVector<unsigned, 2> FoldOps;
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001074 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1075 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001076
Evan Cheng3c75ba82008-04-01 21:37:32 +00001077 // It's only legal to remat for a use, not a def.
1078 if (ReMat && (MRInfo & VirtRegMap::isMod))
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001079 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001080
Evan Chengd70dbb52008-02-22 09:24:50 +00001081 return tii_->canFoldMemoryOperand(MI, FoldOps);
1082}
1083
Evan Cheng81a03822007-11-17 00:40:40 +00001084bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
1085 SmallPtrSet<MachineBasicBlock*, 4> MBBs;
1086 for (LiveInterval::Ranges::const_iterator
1087 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1088 std::vector<IdxMBBPair>::const_iterator II =
1089 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), I->start);
1090 if (II == Idx2MBBMap.end())
1091 continue;
1092 if (I->end > II->first) // crossing a MBB.
1093 return false;
1094 MBBs.insert(II->second);
1095 if (MBBs.size() > 1)
1096 return false;
1097 }
1098 return true;
1099}
1100
Evan Chengd70dbb52008-02-22 09:24:50 +00001101/// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
1102/// interval on to-be re-materialized operands of MI) with new register.
1103void LiveIntervals::rewriteImplicitOps(const LiveInterval &li,
1104 MachineInstr *MI, unsigned NewVReg,
1105 VirtRegMap &vrm) {
1106 // There is an implicit use. That means one of the other operand is
1107 // being remat'ed and the remat'ed instruction has li.reg as an
1108 // use operand. Make sure we rewrite that as well.
1109 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1110 MachineOperand &MO = MI->getOperand(i);
1111 if (!MO.isRegister())
1112 continue;
1113 unsigned Reg = MO.getReg();
1114 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
1115 continue;
1116 if (!vrm.isReMaterialized(Reg))
1117 continue;
1118 MachineInstr *ReMatMI = vrm.getReMaterializedMI(Reg);
Evan Cheng6130f662008-03-05 00:59:57 +00001119 MachineOperand *UseMO = ReMatMI->findRegisterUseOperand(li.reg);
1120 if (UseMO)
1121 UseMO->setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001122 }
1123}
1124
Evan Chengf2fbca62007-11-12 06:35:08 +00001125/// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
1126/// for addIntervalsForSpills to rewrite uses / defs for the given live range.
Evan Cheng018f9b02007-12-05 03:22:34 +00001127bool LiveIntervals::
Evan Chengd70dbb52008-02-22 09:24:50 +00001128rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
1129 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
Evan Cheng81a03822007-11-17 00:40:40 +00001130 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001131 unsigned Slot, int LdSlot,
1132 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001133 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001134 const TargetRegisterClass* rc,
1135 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001136 const MachineLoopInfo *loopInfo,
Evan Cheng313d4b82008-02-23 00:33:04 +00001137 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001138 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001139 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
1140 MachineBasicBlock *MBB = MI->getParent();
1141 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng018f9b02007-12-05 03:22:34 +00001142 bool CanFold = false;
Evan Chengf2fbca62007-11-12 06:35:08 +00001143 RestartInstruction:
1144 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1145 MachineOperand& mop = MI->getOperand(i);
1146 if (!mop.isRegister())
1147 continue;
1148 unsigned Reg = mop.getReg();
1149 unsigned RegI = Reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001150 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
Evan Chengf2fbca62007-11-12 06:35:08 +00001151 continue;
Evan Chengf2fbca62007-11-12 06:35:08 +00001152 if (Reg != li.reg)
1153 continue;
1154
1155 bool TryFold = !DefIsReMat;
Evan Chengcb3c3302007-11-29 23:02:50 +00001156 bool FoldSS = true; // Default behavior unless it's a remat.
Evan Chengf2fbca62007-11-12 06:35:08 +00001157 int FoldSlot = Slot;
1158 if (DefIsReMat) {
1159 // If this is the rematerializable definition MI itself and
1160 // all of its uses are rematerialized, simply delete it.
Evan Cheng81a03822007-11-17 00:40:40 +00001161 if (MI == ReMatOrigDefMI && CanDelete) {
Evan Chengcddbb832007-11-30 21:23:43 +00001162 DOUT << "\t\t\t\tErasing re-materlizable def: ";
1163 DOUT << MI << '\n';
Evan Chengf2fbca62007-11-12 06:35:08 +00001164 RemoveMachineInstrFromMaps(MI);
Evan Chengcada2452007-11-28 01:28:46 +00001165 vrm.RemoveMachineInstrFromMaps(MI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001166 MI->eraseFromParent();
1167 break;
1168 }
1169
1170 // If def for this use can't be rematerialized, then try folding.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001171 // If def is rematerializable and it's a load, also try folding.
Evan Chengcb3c3302007-11-29 23:02:50 +00001172 TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad));
Evan Chengf2fbca62007-11-12 06:35:08 +00001173 if (isLoad) {
1174 // Try fold loads (from stack slot, constant pool, etc.) into uses.
1175 FoldSS = isLoadSS;
1176 FoldSlot = LdSlot;
1177 }
1178 }
1179
Evan Chengf2fbca62007-11-12 06:35:08 +00001180 // Scan all of the operands of this instruction rewriting operands
1181 // to use NewVReg instead of li.reg as appropriate. We do this for
1182 // two reasons:
1183 //
1184 // 1. If the instr reads the same spilled vreg multiple times, we
1185 // want to reuse the NewVReg.
1186 // 2. If the instr is a two-addr instruction, we are required to
1187 // keep the src/dst regs pinned.
1188 //
1189 // Keep track of whether we replace a use and/or def so that we can
1190 // create the spill interval with the appropriate range.
Evan Chengcddbb832007-11-30 21:23:43 +00001191
Evan Cheng81a03822007-11-17 00:40:40 +00001192 HasUse = mop.isUse();
1193 HasDef = mop.isDef();
Evan Chengaee4af62007-12-02 08:30:39 +00001194 SmallVector<unsigned, 2> Ops;
1195 Ops.push_back(i);
Evan Chengf2fbca62007-11-12 06:35:08 +00001196 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
Evan Chengaee4af62007-12-02 08:30:39 +00001197 const MachineOperand &MOj = MI->getOperand(j);
1198 if (!MOj.isRegister())
Evan Chengf2fbca62007-11-12 06:35:08 +00001199 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001200 unsigned RegJ = MOj.getReg();
Dan Gohman6f0d0242008-02-10 18:45:23 +00001201 if (RegJ == 0 || TargetRegisterInfo::isPhysicalRegister(RegJ))
Evan Chengf2fbca62007-11-12 06:35:08 +00001202 continue;
1203 if (RegJ == RegI) {
Evan Chengaee4af62007-12-02 08:30:39 +00001204 Ops.push_back(j);
1205 HasUse |= MOj.isUse();
1206 HasDef |= MOj.isDef();
Evan Chengf2fbca62007-11-12 06:35:08 +00001207 }
1208 }
1209
Evan Cheng79a796c2008-07-12 01:56:02 +00001210 if (HasUse && !li.liveAt(getUseIndex(index)))
1211 // Must be defined by an implicit def. It should not be spilled. Note,
1212 // this is for correctness reason. e.g.
1213 // 8 %reg1024<def> = IMPLICIT_DEF
1214 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1215 // The live range [12, 14) are not part of the r1024 live interval since
1216 // it's defined by an implicit def. It will not conflicts with live
1217 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001218 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001219 // the INSERT_SUBREG and both target registers that would overlap.
1220 HasUse = false;
1221
Evan Cheng9c3c2212008-06-06 07:54:39 +00001222 // Update stack slot spill weight if we are splitting.
Evan Chengc3417602008-06-21 06:45:54 +00001223 float Weight = getSpillWeight(HasDef, HasUse, loopDepth);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001224 if (!TrySplit)
1225 SSWeight += Weight;
1226
1227 if (!TryFold)
1228 CanFold = false;
1229 else {
Evan Cheng018f9b02007-12-05 03:22:34 +00001230 // Do not fold load / store here if we are splitting. We'll find an
1231 // optimal point to insert a load / store later.
1232 if (!TrySplit) {
1233 if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1234 Ops, FoldSS, FoldSlot, Reg)) {
1235 // Folding the load/store can completely change the instruction in
1236 // unpredictable ways, rescan it from the beginning.
1237 HasUse = false;
1238 HasDef = false;
1239 CanFold = false;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001240 if (isRemoved(MI)) {
1241 SSWeight -= Weight;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001242 break;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001243 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001244 goto RestartInstruction;
1245 }
1246 } else {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001247 // We'll try to fold it later if it's profitable.
Evan Cheng3c75ba82008-04-01 21:37:32 +00001248 CanFold = canFoldMemoryOperand(MI, Ops, DefIsReMat);
Evan Cheng018f9b02007-12-05 03:22:34 +00001249 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001250 }
Evan Chengcddbb832007-11-30 21:23:43 +00001251
1252 // Create a new virtual register for the spill interval.
1253 bool CreatedNewVReg = false;
1254 if (NewVReg == 0) {
Evan Chengd70dbb52008-02-22 09:24:50 +00001255 NewVReg = mri_->createVirtualRegister(rc);
Evan Chengcddbb832007-11-30 21:23:43 +00001256 vrm.grow();
1257 CreatedNewVReg = true;
1258 }
1259 mop.setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001260 if (mop.isImplicit())
1261 rewriteImplicitOps(li, MI, NewVReg, vrm);
Evan Chengcddbb832007-11-30 21:23:43 +00001262
1263 // Reuse NewVReg for other reads.
Evan Chengd70dbb52008-02-22 09:24:50 +00001264 for (unsigned j = 0, e = Ops.size(); j != e; ++j) {
1265 MachineOperand &mopj = MI->getOperand(Ops[j]);
1266 mopj.setReg(NewVReg);
1267 if (mopj.isImplicit())
1268 rewriteImplicitOps(li, MI, NewVReg, vrm);
1269 }
Evan Chengcddbb832007-11-30 21:23:43 +00001270
Evan Cheng81a03822007-11-17 00:40:40 +00001271 if (CreatedNewVReg) {
1272 if (DefIsReMat) {
1273 vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI/*, CanDelete*/);
Evan Chengd70dbb52008-02-22 09:24:50 +00001274 if (ReMatIds[VNI->id] == VirtRegMap::MAX_STACK_SLOT) {
Evan Cheng81a03822007-11-17 00:40:40 +00001275 // Each valnum may have its own remat id.
Evan Chengd70dbb52008-02-22 09:24:50 +00001276 ReMatIds[VNI->id] = vrm.assignVirtReMatId(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001277 } else {
Evan Chengd70dbb52008-02-22 09:24:50 +00001278 vrm.assignVirtReMatId(NewVReg, ReMatIds[VNI->id]);
Evan Cheng81a03822007-11-17 00:40:40 +00001279 }
1280 if (!CanDelete || (HasUse && HasDef)) {
1281 // If this is a two-addr instruction then its use operands are
1282 // rematerializable but its def is not. It should be assigned a
1283 // stack slot.
1284 vrm.assignVirt2StackSlot(NewVReg, Slot);
1285 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001286 } else {
Evan Chengf2fbca62007-11-12 06:35:08 +00001287 vrm.assignVirt2StackSlot(NewVReg, Slot);
1288 }
Evan Chengcb3c3302007-11-29 23:02:50 +00001289 } else if (HasUse && HasDef &&
1290 vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) {
1291 // If this interval hasn't been assigned a stack slot (because earlier
1292 // def is a deleted remat def), do it now.
1293 assert(Slot != VirtRegMap::NO_STACK_SLOT);
1294 vrm.assignVirt2StackSlot(NewVReg, Slot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001295 }
1296
Evan Cheng313d4b82008-02-23 00:33:04 +00001297 // Re-matting an instruction with virtual register use. Add the
1298 // register as an implicit use on the use MI.
1299 if (DefIsReMat && ImpUse)
1300 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1301
Evan Chengf2fbca62007-11-12 06:35:08 +00001302 // create a new register interval for this spill / remat.
1303 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001304 if (CreatedNewVReg) {
1305 NewLIs.push_back(&nI);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001306 MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg));
Evan Cheng81a03822007-11-17 00:40:40 +00001307 if (TrySplit)
1308 vrm.setIsSplitFromReg(NewVReg, li.reg);
1309 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001310
1311 if (HasUse) {
Evan Cheng81a03822007-11-17 00:40:40 +00001312 if (CreatedNewVReg) {
1313 LiveRange LR(getLoadIndex(index), getUseIndex(index)+1,
1314 nI.getNextValue(~0U, 0, VNInfoAllocator));
1315 DOUT << " +" << LR;
1316 nI.addRange(LR);
1317 } else {
1318 // Extend the split live interval to this def / use.
1319 unsigned End = getUseIndex(index)+1;
1320 LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
1321 nI.getValNumInfo(nI.getNumValNums()-1));
1322 DOUT << " +" << LR;
1323 nI.addRange(LR);
1324 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001325 }
1326 if (HasDef) {
1327 LiveRange LR(getDefIndex(index), getStoreIndex(index),
1328 nI.getNextValue(~0U, 0, VNInfoAllocator));
1329 DOUT << " +" << LR;
1330 nI.addRange(LR);
1331 }
Evan Cheng81a03822007-11-17 00:40:40 +00001332
Evan Chengf2fbca62007-11-12 06:35:08 +00001333 DOUT << "\t\t\t\tAdded new interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001334 nI.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001335 DOUT << '\n';
1336 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001337 return CanFold;
Evan Chengf2fbca62007-11-12 06:35:08 +00001338}
Evan Cheng81a03822007-11-17 00:40:40 +00001339bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001340 const VNInfo *VNI,
1341 MachineBasicBlock *MBB, unsigned Idx) const {
Evan Cheng81a03822007-11-17 00:40:40 +00001342 unsigned End = getMBBEndIdx(MBB);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001343 for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
1344 unsigned KillIdx = VNI->kills[j];
1345 if (KillIdx > Idx && KillIdx < End)
1346 return true;
Evan Cheng81a03822007-11-17 00:40:40 +00001347 }
1348 return false;
1349}
1350
Evan Cheng063284c2008-02-21 00:34:19 +00001351/// RewriteInfo - Keep track of machine instrs that will be rewritten
1352/// during spilling.
Dan Gohman844731a2008-05-13 00:00:25 +00001353namespace {
1354 struct RewriteInfo {
1355 unsigned Index;
1356 MachineInstr *MI;
1357 bool HasUse;
1358 bool HasDef;
1359 RewriteInfo(unsigned i, MachineInstr *mi, bool u, bool d)
1360 : Index(i), MI(mi), HasUse(u), HasDef(d) {}
1361 };
Evan Cheng063284c2008-02-21 00:34:19 +00001362
Dan Gohman844731a2008-05-13 00:00:25 +00001363 struct RewriteInfoCompare {
1364 bool operator()(const RewriteInfo &LHS, const RewriteInfo &RHS) const {
1365 return LHS.Index < RHS.Index;
1366 }
1367 };
1368}
Evan Cheng063284c2008-02-21 00:34:19 +00001369
Evan Chengf2fbca62007-11-12 06:35:08 +00001370void LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001371rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
Evan Chengf2fbca62007-11-12 06:35:08 +00001372 LiveInterval::Ranges::const_iterator &I,
Evan Cheng81a03822007-11-17 00:40:40 +00001373 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001374 unsigned Slot, int LdSlot,
1375 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001376 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001377 const TargetRegisterClass* rc,
1378 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001379 const MachineLoopInfo *loopInfo,
Evan Cheng81a03822007-11-17 00:40:40 +00001380 BitVector &SpillMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001381 std::map<unsigned, std::vector<SRInfo> > &SpillIdxes,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001382 BitVector &RestoreMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001383 std::map<unsigned, std::vector<SRInfo> > &RestoreIdxes,
1384 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001385 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001386 bool AllCanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001387 unsigned NewVReg = 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001388 unsigned start = getBaseIndex(I->start);
Evan Chengf2fbca62007-11-12 06:35:08 +00001389 unsigned end = getBaseIndex(I->end-1) + InstrSlots::NUM;
Evan Chengf2fbca62007-11-12 06:35:08 +00001390
Evan Cheng063284c2008-02-21 00:34:19 +00001391 // First collect all the def / use in this live range that will be rewritten.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001392 // Make sure they are sorted according to instruction index.
Evan Cheng063284c2008-02-21 00:34:19 +00001393 std::vector<RewriteInfo> RewriteMIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001394 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1395 re = mri_->reg_end(); ri != re; ) {
Evan Cheng419852c2008-04-03 16:39:43 +00001396 MachineInstr *MI = &*ri;
Evan Cheng063284c2008-02-21 00:34:19 +00001397 MachineOperand &O = ri.getOperand();
1398 ++ri;
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001399 assert(!O.isImplicit() && "Spilling register that's used as implicit use?");
Evan Cheng063284c2008-02-21 00:34:19 +00001400 unsigned index = getInstructionIndex(MI);
1401 if (index < start || index >= end)
1402 continue;
Evan Cheng79a796c2008-07-12 01:56:02 +00001403 if (O.isUse() && !li.liveAt(getUseIndex(index)))
1404 // Must be defined by an implicit def. It should not be spilled. Note,
1405 // this is for correctness reason. e.g.
1406 // 8 %reg1024<def> = IMPLICIT_DEF
1407 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1408 // The live range [12, 14) are not part of the r1024 live interval since
1409 // it's defined by an implicit def. It will not conflicts with live
1410 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001411 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001412 // the INSERT_SUBREG and both target registers that would overlap.
1413 continue;
Evan Cheng063284c2008-02-21 00:34:19 +00001414 RewriteMIs.push_back(RewriteInfo(index, MI, O.isUse(), O.isDef()));
1415 }
1416 std::sort(RewriteMIs.begin(), RewriteMIs.end(), RewriteInfoCompare());
1417
Evan Cheng313d4b82008-02-23 00:33:04 +00001418 unsigned ImpUse = DefIsReMat ? getReMatImplicitUse(li, ReMatDefMI) : 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001419 // Now rewrite the defs and uses.
1420 for (unsigned i = 0, e = RewriteMIs.size(); i != e; ) {
1421 RewriteInfo &rwi = RewriteMIs[i];
1422 ++i;
1423 unsigned index = rwi.Index;
1424 bool MIHasUse = rwi.HasUse;
1425 bool MIHasDef = rwi.HasDef;
1426 MachineInstr *MI = rwi.MI;
1427 // If MI def and/or use the same register multiple times, then there
1428 // are multiple entries.
Evan Cheng313d4b82008-02-23 00:33:04 +00001429 unsigned NumUses = MIHasUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001430 while (i != e && RewriteMIs[i].MI == MI) {
1431 assert(RewriteMIs[i].Index == index);
Evan Cheng313d4b82008-02-23 00:33:04 +00001432 bool isUse = RewriteMIs[i].HasUse;
1433 if (isUse) ++NumUses;
1434 MIHasUse |= isUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001435 MIHasDef |= RewriteMIs[i].HasDef;
1436 ++i;
1437 }
Evan Cheng81a03822007-11-17 00:40:40 +00001438 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng313d4b82008-02-23 00:33:04 +00001439
Evan Cheng0a891ed2008-05-23 23:00:04 +00001440 if (ImpUse && MI != ReMatDefMI) {
Evan Cheng313d4b82008-02-23 00:33:04 +00001441 // Re-matting an instruction with virtual register use. Update the
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001442 // register interval's spill weight to HUGE_VALF to prevent it from
1443 // being spilled.
Evan Cheng313d4b82008-02-23 00:33:04 +00001444 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001445 ImpLi.weight = HUGE_VALF;
Evan Cheng313d4b82008-02-23 00:33:04 +00001446 }
1447
Evan Cheng063284c2008-02-21 00:34:19 +00001448 unsigned MBBId = MBB->getNumber();
Evan Cheng018f9b02007-12-05 03:22:34 +00001449 unsigned ThisVReg = 0;
Evan Cheng70306f82007-12-03 09:58:48 +00001450 if (TrySplit) {
Evan Cheng063284c2008-02-21 00:34:19 +00001451 std::map<unsigned,unsigned>::const_iterator NVI = MBBVRegsMap.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001452 if (NVI != MBBVRegsMap.end()) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001453 ThisVReg = NVI->second;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001454 // One common case:
1455 // x = use
1456 // ...
1457 // ...
1458 // def = ...
1459 // = use
1460 // It's better to start a new interval to avoid artifically
1461 // extend the new interval.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001462 if (MIHasDef && !MIHasUse) {
1463 MBBVRegsMap.erase(MBB->getNumber());
Evan Cheng018f9b02007-12-05 03:22:34 +00001464 ThisVReg = 0;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001465 }
1466 }
Evan Chengcada2452007-11-28 01:28:46 +00001467 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001468
1469 bool IsNew = ThisVReg == 0;
1470 if (IsNew) {
1471 // This ends the previous live interval. If all of its def / use
1472 // can be folded, give it a low spill weight.
1473 if (NewVReg && TrySplit && AllCanFold) {
1474 LiveInterval &nI = getOrCreateInterval(NewVReg);
1475 nI.weight /= 10.0F;
1476 }
1477 AllCanFold = true;
1478 }
1479 NewVReg = ThisVReg;
1480
Evan Cheng81a03822007-11-17 00:40:40 +00001481 bool HasDef = false;
1482 bool HasUse = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001483 bool CanFold = rewriteInstructionForSpills(li, I->valno, TrySplit,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001484 index, end, MI, ReMatOrigDefMI, ReMatDefMI,
1485 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
1486 CanDelete, vrm, rc, ReMatIds, loopInfo, NewVReg,
1487 ImpUse, HasDef, HasUse, MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001488 if (!HasDef && !HasUse)
1489 continue;
1490
Evan Cheng018f9b02007-12-05 03:22:34 +00001491 AllCanFold &= CanFold;
1492
Evan Cheng81a03822007-11-17 00:40:40 +00001493 // Update weight of spill interval.
1494 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng70306f82007-12-03 09:58:48 +00001495 if (!TrySplit) {
Evan Cheng81a03822007-11-17 00:40:40 +00001496 // The spill weight is now infinity as it cannot be spilled again.
1497 nI.weight = HUGE_VALF;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001498 continue;
Evan Cheng81a03822007-11-17 00:40:40 +00001499 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001500
1501 // Keep track of the last def and first use in each MBB.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001502 if (HasDef) {
1503 if (MI != ReMatOrigDefMI || !CanDelete) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001504 bool HasKill = false;
1505 if (!HasUse)
1506 HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, getDefIndex(index));
1507 else {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001508 // If this is a two-address code, then this index starts a new VNInfo.
Evan Cheng3f32d652008-06-04 09:18:41 +00001509 const VNInfo *VNI = li.findDefinedVNInfo(getDefIndex(index));
Evan Cheng0cbb1162007-11-29 01:06:25 +00001510 if (VNI)
1511 HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, getDefIndex(index));
1512 }
Evan Chenge3110d02007-12-01 04:42:39 +00001513 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
1514 SpillIdxes.find(MBBId);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001515 if (!HasKill) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001516 if (SII == SpillIdxes.end()) {
1517 std::vector<SRInfo> S;
1518 S.push_back(SRInfo(index, NewVReg, true));
1519 SpillIdxes.insert(std::make_pair(MBBId, S));
1520 } else if (SII->second.back().vreg != NewVReg) {
1521 SII->second.push_back(SRInfo(index, NewVReg, true));
1522 } else if ((int)index > SII->second.back().index) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001523 // If there is an earlier def and this is a two-address
1524 // instruction, then it's not possible to fold the store (which
1525 // would also fold the load).
Evan Cheng1953d0c2007-11-29 10:12:14 +00001526 SRInfo &Info = SII->second.back();
1527 Info.index = index;
1528 Info.canFold = !HasUse;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001529 }
1530 SpillMBBs.set(MBBId);
Evan Chenge3110d02007-12-01 04:42:39 +00001531 } else if (SII != SpillIdxes.end() &&
1532 SII->second.back().vreg == NewVReg &&
1533 (int)index > SII->second.back().index) {
1534 // There is an earlier def that's not killed (must be two-address).
1535 // The spill is no longer needed.
1536 SII->second.pop_back();
1537 if (SII->second.empty()) {
1538 SpillIdxes.erase(MBBId);
1539 SpillMBBs.reset(MBBId);
1540 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001541 }
1542 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001543 }
1544
1545 if (HasUse) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001546 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001547 SpillIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001548 if (SII != SpillIdxes.end() &&
1549 SII->second.back().vreg == NewVReg &&
1550 (int)index > SII->second.back().index)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001551 // Use(s) following the last def, it's not safe to fold the spill.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001552 SII->second.back().canFold = false;
1553 std::map<unsigned, std::vector<SRInfo> >::iterator RII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001554 RestoreIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001555 if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001556 // If we are splitting live intervals, only fold if it's the first
1557 // use and there isn't another use later in the MBB.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001558 RII->second.back().canFold = false;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001559 else if (IsNew) {
1560 // Only need a reload if there isn't an earlier def / use.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001561 if (RII == RestoreIdxes.end()) {
1562 std::vector<SRInfo> Infos;
1563 Infos.push_back(SRInfo(index, NewVReg, true));
1564 RestoreIdxes.insert(std::make_pair(MBBId, Infos));
1565 } else {
1566 RII->second.push_back(SRInfo(index, NewVReg, true));
1567 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001568 RestoreMBBs.set(MBBId);
1569 }
1570 }
1571
1572 // Update spill weight.
Evan Cheng22f07ff2007-12-11 02:09:15 +00001573 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Chengc3417602008-06-21 06:45:54 +00001574 nI.weight += getSpillWeight(HasDef, HasUse, loopDepth);
Evan Chengf2fbca62007-11-12 06:35:08 +00001575 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001576
1577 if (NewVReg && TrySplit && AllCanFold) {
1578 // If all of its def / use can be folded, give it a low spill weight.
1579 LiveInterval &nI = getOrCreateInterval(NewVReg);
1580 nI.weight /= 10.0F;
1581 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001582}
1583
Evan Cheng1953d0c2007-11-29 10:12:14 +00001584bool LiveIntervals::alsoFoldARestore(int Id, int index, unsigned vr,
1585 BitVector &RestoreMBBs,
1586 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1587 if (!RestoreMBBs[Id])
1588 return false;
1589 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1590 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1591 if (Restores[i].index == index &&
1592 Restores[i].vreg == vr &&
1593 Restores[i].canFold)
1594 return true;
1595 return false;
1596}
1597
1598void LiveIntervals::eraseRestoreInfo(int Id, int index, unsigned vr,
1599 BitVector &RestoreMBBs,
1600 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1601 if (!RestoreMBBs[Id])
1602 return;
1603 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1604 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1605 if (Restores[i].index == index && Restores[i].vreg)
1606 Restores[i].index = -1;
1607}
Evan Cheng81a03822007-11-17 00:40:40 +00001608
Evan Cheng4cce6b42008-04-11 17:53:36 +00001609/// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
1610/// spilled and create empty intervals for their uses.
1611void
1612LiveIntervals::handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
1613 const TargetRegisterClass* rc,
1614 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng419852c2008-04-03 16:39:43 +00001615 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1616 re = mri_->reg_end(); ri != re; ) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001617 MachineOperand &O = ri.getOperand();
Evan Cheng419852c2008-04-03 16:39:43 +00001618 MachineInstr *MI = &*ri;
1619 ++ri;
Evan Cheng4cce6b42008-04-11 17:53:36 +00001620 if (O.isDef()) {
1621 assert(MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF &&
1622 "Register def was not rewritten?");
1623 RemoveMachineInstrFromMaps(MI);
1624 vrm.RemoveMachineInstrFromMaps(MI);
1625 MI->eraseFromParent();
1626 } else {
1627 // This must be an use of an implicit_def so it's not part of the live
1628 // interval. Create a new empty live interval for it.
1629 // FIXME: Can we simply erase some of the instructions? e.g. Stores?
1630 unsigned NewVReg = mri_->createVirtualRegister(rc);
1631 vrm.grow();
1632 vrm.setIsImplicitlyDefined(NewVReg);
1633 NewLIs.push_back(&getOrCreateInterval(NewVReg));
1634 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1635 MachineOperand &MO = MI->getOperand(i);
1636 if (MO.isReg() && MO.getReg() == li.reg)
1637 MO.setReg(NewVReg);
1638 }
1639 }
Evan Cheng419852c2008-04-03 16:39:43 +00001640 }
1641}
1642
Evan Cheng81a03822007-11-17 00:40:40 +00001643
Evan Chengf2fbca62007-11-12 06:35:08 +00001644std::vector<LiveInterval*> LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001645addIntervalsForSpills(const LiveInterval &li,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001646 const MachineLoopInfo *loopInfo, VirtRegMap &vrm,
1647 float &SSWeight) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001648 assert(li.weight != HUGE_VALF &&
1649 "attempt to spill already spilled interval!");
1650
1651 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001652 li.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001653 DOUT << '\n';
1654
Evan Cheng9c3c2212008-06-06 07:54:39 +00001655 // Spill slot weight.
1656 SSWeight = 0.0f;
1657
Evan Cheng81a03822007-11-17 00:40:40 +00001658 // Each bit specify whether it a spill is required in the MBB.
1659 BitVector SpillMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001660 std::map<unsigned, std::vector<SRInfo> > SpillIdxes;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001661 BitVector RestoreMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001662 std::map<unsigned, std::vector<SRInfo> > RestoreIdxes;
1663 std::map<unsigned,unsigned> MBBVRegsMap;
Evan Chengf2fbca62007-11-12 06:35:08 +00001664 std::vector<LiveInterval*> NewLIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001665 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
Evan Chengf2fbca62007-11-12 06:35:08 +00001666
1667 unsigned NumValNums = li.getNumValNums();
1668 SmallVector<MachineInstr*, 4> ReMatDefs;
1669 ReMatDefs.resize(NumValNums, NULL);
1670 SmallVector<MachineInstr*, 4> ReMatOrigDefs;
1671 ReMatOrigDefs.resize(NumValNums, NULL);
1672 SmallVector<int, 4> ReMatIds;
1673 ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
1674 BitVector ReMatDelete(NumValNums);
1675 unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
1676
Evan Cheng81a03822007-11-17 00:40:40 +00001677 // Spilling a split live interval. It cannot be split any further. Also,
1678 // it's also guaranteed to be a single val# / range interval.
1679 if (vrm.getPreSplitReg(li.reg)) {
1680 vrm.setIsSplitFromReg(li.reg, 0);
Evan Chengd120ffd2007-12-05 10:24:35 +00001681 // Unset the split kill marker on the last use.
1682 unsigned KillIdx = vrm.getKillPoint(li.reg);
1683 if (KillIdx) {
1684 MachineInstr *KillMI = getInstructionFromIndex(KillIdx);
1685 assert(KillMI && "Last use disappeared?");
1686 int KillOp = KillMI->findRegisterUseOperandIdx(li.reg, true);
1687 assert(KillOp != -1 && "Last use disappeared?");
Chris Lattnerf7382302007-12-30 21:56:09 +00001688 KillMI->getOperand(KillOp).setIsKill(false);
Evan Chengd120ffd2007-12-05 10:24:35 +00001689 }
Evan Chengadf85902007-12-05 09:51:10 +00001690 vrm.removeKillPoint(li.reg);
Evan Cheng81a03822007-11-17 00:40:40 +00001691 bool DefIsReMat = vrm.isReMaterialized(li.reg);
1692 Slot = vrm.getStackSlot(li.reg);
1693 assert(Slot != VirtRegMap::MAX_STACK_SLOT);
1694 MachineInstr *ReMatDefMI = DefIsReMat ?
1695 vrm.getReMaterializedMI(li.reg) : NULL;
1696 int LdSlot = 0;
1697 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1698 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001699 (DefIsReMat && (ReMatDefMI->getDesc().isSimpleLoad()));
Evan Cheng81a03822007-11-17 00:40:40 +00001700 bool IsFirstRange = true;
1701 for (LiveInterval::Ranges::const_iterator
1702 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1703 // If this is a split live interval with multiple ranges, it means there
1704 // are two-address instructions that re-defined the value. Only the
1705 // first def can be rematerialized!
1706 if (IsFirstRange) {
Evan Chengcb3c3302007-11-29 23:02:50 +00001707 // Note ReMatOrigDefMI has already been deleted.
Evan Cheng81a03822007-11-17 00:40:40 +00001708 rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
1709 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001710 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001711 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001712 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001713 } else {
1714 rewriteInstructionsForSpills(li, false, I, NULL, 0,
1715 Slot, 0, false, false, false,
Evan Chengd70dbb52008-02-22 09:24:50 +00001716 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001717 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001718 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001719 }
1720 IsFirstRange = false;
1721 }
Evan Cheng419852c2008-04-03 16:39:43 +00001722
Evan Cheng9c3c2212008-06-06 07:54:39 +00001723 SSWeight = 0.0f; // Already accounted for when split.
Evan Cheng4cce6b42008-04-11 17:53:36 +00001724 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001725 return NewLIs;
1726 }
1727
1728 bool TrySplit = SplitAtBB && !intervalIsInOneMBB(li);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001729 if (SplitLimit != -1 && (int)numSplits >= SplitLimit)
1730 TrySplit = false;
1731 if (TrySplit)
1732 ++numSplits;
Evan Chengf2fbca62007-11-12 06:35:08 +00001733 bool NeedStackSlot = false;
1734 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1735 i != e; ++i) {
1736 const VNInfo *VNI = *i;
1737 unsigned VN = VNI->id;
1738 unsigned DefIdx = VNI->def;
1739 if (DefIdx == ~1U)
1740 continue; // Dead val#.
1741 // Is the def for the val# rematerializable?
Evan Cheng81a03822007-11-17 00:40:40 +00001742 MachineInstr *ReMatDefMI = (DefIdx == ~0u)
1743 ? 0 : getInstructionFromIndex(DefIdx);
Evan Cheng5ef3a042007-12-06 00:01:56 +00001744 bool dummy;
1745 if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, dummy)) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001746 // Remember how to remat the def of this val#.
Evan Cheng81a03822007-11-17 00:40:40 +00001747 ReMatOrigDefs[VN] = ReMatDefMI;
Dan Gohman2c3f7ae2008-07-17 23:49:46 +00001748 // Original def may be modified so we have to make a copy here.
Evan Cheng1ed99222008-07-19 00:37:25 +00001749 MachineInstr *Clone = mf_->CloneMachineInstr(ReMatDefMI);
1750 ClonedMIs.push_back(Clone);
1751 ReMatDefs[VN] = Clone;
Evan Chengf2fbca62007-11-12 06:35:08 +00001752
1753 bool CanDelete = true;
Evan Chengc3fc7d92007-11-29 09:49:23 +00001754 if (VNI->hasPHIKill) {
1755 // A kill is a phi node, not all of its uses can be rematerialized.
Evan Chengf2fbca62007-11-12 06:35:08 +00001756 // It must not be deleted.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001757 CanDelete = false;
1758 // Need a stack slot if there is any live range where uses cannot be
1759 // rematerialized.
1760 NeedStackSlot = true;
Evan Chengf2fbca62007-11-12 06:35:08 +00001761 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001762 if (CanDelete)
1763 ReMatDelete.set(VN);
1764 } else {
1765 // Need a stack slot if there is any live range where uses cannot be
1766 // rematerialized.
1767 NeedStackSlot = true;
1768 }
1769 }
1770
1771 // One stack slot per live interval.
Evan Cheng81a03822007-11-17 00:40:40 +00001772 if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0)
Evan Chengf2fbca62007-11-12 06:35:08 +00001773 Slot = vrm.assignVirt2StackSlot(li.reg);
1774
1775 // Create new intervals and rewrite defs and uses.
1776 for (LiveInterval::Ranges::const_iterator
1777 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Evan Cheng81a03822007-11-17 00:40:40 +00001778 MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id];
1779 MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id];
1780 bool DefIsReMat = ReMatDefMI != NULL;
Evan Chengf2fbca62007-11-12 06:35:08 +00001781 bool CanDelete = ReMatDelete[I->valno->id];
1782 int LdSlot = 0;
Evan Cheng81a03822007-11-17 00:40:40 +00001783 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001784 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001785 (DefIsReMat && ReMatDefMI->getDesc().isSimpleLoad());
Evan Cheng81a03822007-11-17 00:40:40 +00001786 rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001787 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001788 CanDelete, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001789 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001790 MBBVRegsMap, NewLIs, SSWeight);
Evan Chengf2fbca62007-11-12 06:35:08 +00001791 }
1792
Evan Cheng0cbb1162007-11-29 01:06:25 +00001793 // Insert spills / restores if we are splitting.
Evan Cheng419852c2008-04-03 16:39:43 +00001794 if (!TrySplit) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001795 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001796 return NewLIs;
Evan Cheng419852c2008-04-03 16:39:43 +00001797 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001798
Evan Chengb50bb8c2007-12-05 08:16:32 +00001799 SmallPtrSet<LiveInterval*, 4> AddedKill;
Evan Chengaee4af62007-12-02 08:30:39 +00001800 SmallVector<unsigned, 2> Ops;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001801 if (NeedStackSlot) {
1802 int Id = SpillMBBs.find_first();
1803 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001804 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1805 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001806 std::vector<SRInfo> &spills = SpillIdxes[Id];
1807 for (unsigned i = 0, e = spills.size(); i != e; ++i) {
1808 int index = spills[i].index;
1809 unsigned VReg = spills[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001810 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001811 bool isReMat = vrm.isReMaterialized(VReg);
1812 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001813 bool CanFold = false;
1814 bool FoundUse = false;
1815 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001816 if (spills[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001817 CanFold = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001818 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1819 MachineOperand &MO = MI->getOperand(j);
1820 if (!MO.isRegister() || MO.getReg() != VReg)
1821 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001822
1823 Ops.push_back(j);
1824 if (MO.isDef())
Evan Chengcddbb832007-11-30 21:23:43 +00001825 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001826 if (isReMat ||
1827 (!FoundUse && !alsoFoldARestore(Id, index, VReg,
1828 RestoreMBBs, RestoreIdxes))) {
1829 // MI has two-address uses of the same register. If the use
1830 // isn't the first and only use in the BB, then we can't fold
1831 // it. FIXME: Move this to rewriteInstructionsForSpills.
1832 CanFold = false;
Evan Chengcddbb832007-11-30 21:23:43 +00001833 break;
1834 }
Evan Chengaee4af62007-12-02 08:30:39 +00001835 FoundUse = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001836 }
1837 }
1838 // Fold the store into the def if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001839 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001840 if (CanFold && !Ops.empty()) {
1841 if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
Evan Chengcddbb832007-11-30 21:23:43 +00001842 Folded = true;
Evan Chengf38d14f2007-12-05 09:05:34 +00001843 if (FoundUse > 0) {
Evan Chengaee4af62007-12-02 08:30:39 +00001844 // Also folded uses, do not issue a load.
1845 eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
Evan Chengf38d14f2007-12-05 09:05:34 +00001846 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
1847 }
Evan Cheng597d10d2007-12-04 00:32:23 +00001848 nI.removeRange(getDefIndex(index), getStoreIndex(index));
Evan Chengcddbb832007-11-30 21:23:43 +00001849 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001850 }
1851
Evan Cheng7e073ba2008-04-09 20:57:25 +00001852 // Otherwise tell the spiller to issue a spill.
Evan Chengb50bb8c2007-12-05 08:16:32 +00001853 if (!Folded) {
1854 LiveRange *LR = &nI.ranges[nI.ranges.size()-1];
1855 bool isKill = LR->end == getStoreIndex(index);
Evan Chengb0a6f622008-05-20 08:10:37 +00001856 if (!MI->registerDefIsDead(nI.reg))
1857 // No need to spill a dead def.
1858 vrm.addSpillPoint(VReg, isKill, MI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001859 if (isKill)
1860 AddedKill.insert(&nI);
1861 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001862
1863 // Update spill slot weight.
1864 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00001865 SSWeight += getSpillWeight(true, false, loopDepth);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001866 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001867 Id = SpillMBBs.find_next(Id);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001868 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001869 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001870
Evan Cheng1953d0c2007-11-29 10:12:14 +00001871 int Id = RestoreMBBs.find_first();
1872 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001873 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1874 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
1875
Evan Cheng1953d0c2007-11-29 10:12:14 +00001876 std::vector<SRInfo> &restores = RestoreIdxes[Id];
1877 for (unsigned i = 0, e = restores.size(); i != e; ++i) {
1878 int index = restores[i].index;
1879 if (index == -1)
1880 continue;
1881 unsigned VReg = restores[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001882 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001883 bool isReMat = vrm.isReMaterialized(VReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001884 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001885 bool CanFold = false;
1886 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001887 if (restores[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001888 CanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001889 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1890 MachineOperand &MO = MI->getOperand(j);
1891 if (!MO.isRegister() || MO.getReg() != VReg)
1892 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001893
Evan Cheng0cbb1162007-11-29 01:06:25 +00001894 if (MO.isDef()) {
Evan Chengaee4af62007-12-02 08:30:39 +00001895 // If this restore were to be folded, it would have been folded
1896 // already.
1897 CanFold = false;
Evan Cheng81a03822007-11-17 00:40:40 +00001898 break;
1899 }
Evan Chengaee4af62007-12-02 08:30:39 +00001900 Ops.push_back(j);
Evan Cheng81a03822007-11-17 00:40:40 +00001901 }
1902 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001903
1904 // Fold the load into the use if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001905 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001906 if (CanFold && !Ops.empty()) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001907 if (!isReMat)
Evan Chengaee4af62007-12-02 08:30:39 +00001908 Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg);
1909 else {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001910 MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg);
1911 int LdSlot = 0;
1912 bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1913 // If the rematerializable def is a load, also try to fold it.
Chris Lattner749c6f62008-01-07 07:27:27 +00001914 if (isLoadSS || ReMatDefMI->getDesc().isSimpleLoad())
Evan Chengaee4af62007-12-02 08:30:39 +00001915 Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1916 Ops, isLoadSS, LdSlot, VReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001917 unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI);
1918 if (ImpUse) {
1919 // Re-matting an instruction with virtual register use. Add the
1920 // register as an implicit use on the use MI and update the register
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001921 // interval's spill weight to HUGE_VALF to prevent it from being
1922 // spilled.
Evan Chengd70dbb52008-02-22 09:24:50 +00001923 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001924 ImpLi.weight = HUGE_VALF;
Evan Chengd70dbb52008-02-22 09:24:50 +00001925 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1926 }
Evan Chengaee4af62007-12-02 08:30:39 +00001927 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001928 }
1929 // If folding is not possible / failed, then tell the spiller to issue a
1930 // load / rematerialization for us.
Evan Cheng597d10d2007-12-04 00:32:23 +00001931 if (Folded)
1932 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001933 else
Evan Cheng0cbb1162007-11-29 01:06:25 +00001934 vrm.addRestorePoint(VReg, MI);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001935
1936 // Update spill slot weight.
1937 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00001938 SSWeight += getSpillWeight(false, true, loopDepth);
Evan Cheng81a03822007-11-17 00:40:40 +00001939 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001940 Id = RestoreMBBs.find_next(Id);
Evan Cheng81a03822007-11-17 00:40:40 +00001941 }
1942
Evan Chengb50bb8c2007-12-05 08:16:32 +00001943 // Finalize intervals: add kills, finalize spill weights, and filter out
1944 // dead intervals.
Evan Cheng597d10d2007-12-04 00:32:23 +00001945 std::vector<LiveInterval*> RetNewLIs;
1946 for (unsigned i = 0, e = NewLIs.size(); i != e; ++i) {
1947 LiveInterval *LI = NewLIs[i];
1948 if (!LI->empty()) {
Owen Anderson496bac52008-07-23 19:47:27 +00001949 LI->weight /= InstrSlots::NUM * getApproximateInstructionCount(*LI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001950 if (!AddedKill.count(LI)) {
1951 LiveRange *LR = &LI->ranges[LI->ranges.size()-1];
Evan Chengd120ffd2007-12-05 10:24:35 +00001952 unsigned LastUseIdx = getBaseIndex(LR->end);
1953 MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx);
Evan Cheng6130f662008-03-05 00:59:57 +00001954 int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg, false);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001955 assert(UseIdx != -1);
Evan Chengd70dbb52008-02-22 09:24:50 +00001956 if (LastUse->getOperand(UseIdx).isImplicit() ||
1957 LastUse->getDesc().getOperandConstraint(UseIdx,TOI::TIED_TO) == -1){
Evan Chengb50bb8c2007-12-05 08:16:32 +00001958 LastUse->getOperand(UseIdx).setIsKill();
Evan Chengd120ffd2007-12-05 10:24:35 +00001959 vrm.addKillPoint(LI->reg, LastUseIdx);
Evan Chengadf85902007-12-05 09:51:10 +00001960 }
Evan Chengb50bb8c2007-12-05 08:16:32 +00001961 }
Evan Cheng597d10d2007-12-04 00:32:23 +00001962 RetNewLIs.push_back(LI);
1963 }
1964 }
Evan Cheng81a03822007-11-17 00:40:40 +00001965
Evan Cheng4cce6b42008-04-11 17:53:36 +00001966 handleSpilledImpDefs(li, vrm, rc, RetNewLIs);
Evan Cheng597d10d2007-12-04 00:32:23 +00001967 return RetNewLIs;
Evan Chengf2fbca62007-11-12 06:35:08 +00001968}
Evan Cheng676dd7c2008-03-11 07:19:34 +00001969
1970/// hasAllocatableSuperReg - Return true if the specified physical register has
1971/// any super register that's allocatable.
1972bool LiveIntervals::hasAllocatableSuperReg(unsigned Reg) const {
1973 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS)
1974 if (allocatableRegs_[*AS] && hasInterval(*AS))
1975 return true;
1976 return false;
1977}
1978
1979/// getRepresentativeReg - Find the largest super register of the specified
1980/// physical register.
1981unsigned LiveIntervals::getRepresentativeReg(unsigned Reg) const {
1982 // Find the largest super-register that is allocatable.
1983 unsigned BestReg = Reg;
1984 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS) {
1985 unsigned SuperReg = *AS;
1986 if (!hasAllocatableSuperReg(SuperReg) && hasInterval(SuperReg)) {
1987 BestReg = SuperReg;
1988 break;
1989 }
1990 }
1991 return BestReg;
1992}
1993
1994/// getNumConflictsWithPhysReg - Return the number of uses and defs of the
1995/// specified interval that conflicts with the specified physical register.
1996unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li,
1997 unsigned PhysReg) const {
1998 unsigned NumConflicts = 0;
1999 const LiveInterval &pli = getInterval(getRepresentativeReg(PhysReg));
2000 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
2001 E = mri_->reg_end(); I != E; ++I) {
2002 MachineOperand &O = I.getOperand();
2003 MachineInstr *MI = O.getParent();
2004 unsigned Index = getInstructionIndex(MI);
2005 if (pli.liveAt(Index))
2006 ++NumConflicts;
2007 }
2008 return NumConflicts;
2009}
2010
2011/// spillPhysRegAroundRegDefsUses - Spill the specified physical register
2012/// around all defs and uses of the specified interval.
2013void LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
2014 unsigned PhysReg, VirtRegMap &vrm) {
2015 unsigned SpillReg = getRepresentativeReg(PhysReg);
2016
2017 for (const unsigned *AS = tri_->getAliasSet(PhysReg); *AS; ++AS)
2018 // If there are registers which alias PhysReg, but which are not a
2019 // sub-register of the chosen representative super register. Assert
2020 // since we can't handle it yet.
2021 assert(*AS == SpillReg || !allocatableRegs_[*AS] ||
2022 tri_->isSuperRegister(*AS, SpillReg));
2023
2024 LiveInterval &pli = getInterval(SpillReg);
2025 SmallPtrSet<MachineInstr*, 8> SeenMIs;
2026 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
2027 E = mri_->reg_end(); I != E; ++I) {
2028 MachineOperand &O = I.getOperand();
2029 MachineInstr *MI = O.getParent();
2030 if (SeenMIs.count(MI))
2031 continue;
2032 SeenMIs.insert(MI);
2033 unsigned Index = getInstructionIndex(MI);
2034 if (pli.liveAt(Index)) {
2035 vrm.addEmergencySpill(SpillReg, MI);
2036 pli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
2037 for (const unsigned* AS = tri_->getSubRegisters(SpillReg); *AS; ++AS) {
2038 if (!hasInterval(*AS))
2039 continue;
2040 LiveInterval &spli = getInterval(*AS);
2041 if (spli.liveAt(Index))
2042 spli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
2043 }
2044 }
2045 }
2046}
Owen Andersonc4dc1322008-06-05 17:15:43 +00002047
2048LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
2049 MachineInstr* startInst) {
2050 LiveInterval& Interval = getOrCreateInterval(reg);
2051 VNInfo* VN = Interval.getNextValue(
2052 getInstructionIndex(startInst) + InstrSlots::DEF,
2053 startInst, getVNInfoAllocator());
2054 VN->hasPHIKill = true;
2055 VN->kills.push_back(getMBBEndIdx(startInst->getParent()));
2056 LiveRange LR(getInstructionIndex(startInst) + InstrSlots::DEF,
2057 getMBBEndIdx(startInst->getParent()) + 1, VN);
2058 Interval.addRange(LR);
2059
2060 return LR;
2061}