blob: fde27b07a8bf9c533ba078f7f31cd135f99502c0 [file] [log] [blame]
Chris Lattnera3b8b5c2004-07-23 17:56:30 +00001//===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the LiveInterval analysis pass which is used
11// by the Linear Scan Register allocator. This pass linearizes the
12// basic blocks of the function in DFS order and uses the
13// LiveVariables pass to conservatively compute live intervals for
14// each virtual and physical register.
15//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "liveintervals"
Chris Lattner3c3fe462005-09-21 04:19:09 +000019#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Misha Brukman08a6c762004-09-03 18:25:53 +000020#include "VirtRegMap.h"
Chris Lattner015959e2004-05-01 21:24:39 +000021#include "llvm/Value.h"
Dan Gohman6d69ba82008-07-25 00:02:30 +000022#include "llvm/Analysis/AliasAnalysis.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000023#include "llvm/CodeGen/LiveVariables.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000025#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000026#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000027#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000028#include "llvm/CodeGen/Passes.h"
Dan Gohman6d69ba82008-07-25 00:02:30 +000029#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000030#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000031#include "llvm/Target/TargetInstrInfo.h"
32#include "llvm/Target/TargetMachine.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000033#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
35#include "llvm/ADT/Statistic.h"
36#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000037#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000038#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000039using namespace llvm;
40
Dan Gohman844731a2008-05-13 00:00:25 +000041// Hidden options for help debugging.
42static cl::opt<bool> DisableReMat("disable-rematerialization",
43 cl::init(false), cl::Hidden);
Evan Cheng81a03822007-11-17 00:40:40 +000044
Dan Gohman844731a2008-05-13 00:00:25 +000045static cl::opt<bool> SplitAtBB("split-intervals-at-bb",
46 cl::init(true), cl::Hidden);
47static cl::opt<int> SplitLimit("split-limit",
48 cl::init(-1), cl::Hidden);
Evan Chengbc165e42007-08-16 07:24:22 +000049
Dan Gohman4c8f8702008-07-25 15:08:37 +000050static cl::opt<bool> EnableAggressiveRemat("aggressive-remat", cl::Hidden);
51
Chris Lattnercd3245a2006-12-19 22:41:21 +000052STATISTIC(numIntervals, "Number of original intervals");
53STATISTIC(numIntervalsAfter, "Number of intervals after coalescing");
Evan Cheng0cbb1162007-11-29 01:06:25 +000054STATISTIC(numFolds , "Number of loads/stores folded into instructions");
55STATISTIC(numSplits , "Number of intervals split");
Chris Lattnercd3245a2006-12-19 22:41:21 +000056
Devang Patel19974732007-05-03 01:11:54 +000057char LiveIntervals::ID = 0;
Dan Gohman844731a2008-05-13 00:00:25 +000058static RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000059
Chris Lattnerf7da2c72006-08-24 22:43:55 +000060void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman6d69ba82008-07-25 00:02:30 +000061 AU.addRequired<AliasAnalysis>();
62 AU.addPreserved<AliasAnalysis>();
David Greene25133302007-06-08 17:18:56 +000063 AU.addPreserved<LiveVariables>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000064 AU.addRequired<LiveVariables>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000065 AU.addPreservedID(MachineLoopInfoID);
66 AU.addPreservedID(MachineDominatorsID);
Owen Andersonfcc63502008-05-29 18:35:21 +000067 AU.addPreservedID(PHIEliminationID);
68 AU.addRequiredID(PHIEliminationID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000069 AU.addRequiredID(TwoAddressInstructionPassID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000070 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000071}
72
Chris Lattnerf7da2c72006-08-24 22:43:55 +000073void LiveIntervals::releaseMemory() {
Evan Cheng3f32d652008-06-04 09:18:41 +000074 MBB2IdxMap.clear();
Evan Cheng4ca980e2007-10-17 02:10:22 +000075 Idx2MBBMap.clear();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000076 mi2iMap_.clear();
77 i2miMap_.clear();
78 r2iMap_.clear();
Evan Chengdd199d22007-09-06 01:07:24 +000079 // Release VNInfo memroy regions after all VNInfo objects are dtor'd.
80 VNInfoAllocator.Reset();
Evan Cheng1ed99222008-07-19 00:37:25 +000081 while (!ClonedMIs.empty()) {
82 MachineInstr *MI = ClonedMIs.back();
83 ClonedMIs.pop_back();
84 mf_->DeleteMachineInstr(MI);
85 }
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000086}
87
Owen Anderson80b3ce62008-05-28 20:54:50 +000088void LiveIntervals::computeNumbering() {
89 Index2MiMap OldI2MI = i2miMap_;
Owen Anderson7fbad272008-07-23 21:37:49 +000090 std::vector<IdxMBBPair> OldI2MBB = Idx2MBBMap;
Owen Anderson80b3ce62008-05-28 20:54:50 +000091
92 Idx2MBBMap.clear();
93 MBB2IdxMap.clear();
94 mi2iMap_.clear();
95 i2miMap_.clear();
96
Owen Andersona1566f22008-07-22 22:46:49 +000097 FunctionSize = 0;
98
Chris Lattner428b92e2006-09-15 03:57:23 +000099 // Number MachineInstrs and MachineBasicBlocks.
100 // Initialize MBB indexes to a sentinal.
Evan Cheng549f27d32007-08-13 23:45:17 +0000101 MBB2IdxMap.resize(mf_->getNumBlockIDs(), std::make_pair(~0U,~0U));
Chris Lattner428b92e2006-09-15 03:57:23 +0000102
103 unsigned MIIndex = 0;
104 for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
105 MBB != E; ++MBB) {
Evan Cheng549f27d32007-08-13 23:45:17 +0000106 unsigned StartIdx = MIIndex;
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000107
Owen Anderson7fbad272008-07-23 21:37:49 +0000108 // Insert an empty slot at the beginning of each block.
109 MIIndex += InstrSlots::NUM;
110 i2miMap_.push_back(0);
111
Chris Lattner428b92e2006-09-15 03:57:23 +0000112 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
113 I != E; ++I) {
114 bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000115 assert(inserted && "multiple MachineInstr -> index mappings");
Chris Lattner428b92e2006-09-15 03:57:23 +0000116 i2miMap_.push_back(I);
117 MIIndex += InstrSlots::NUM;
Owen Andersona1566f22008-07-22 22:46:49 +0000118 FunctionSize++;
Owen Anderson7fbad272008-07-23 21:37:49 +0000119
120 // Insert an empty slot after every instruction.
Owen Anderson1fbb4542008-06-16 16:58:24 +0000121 MIIndex += InstrSlots::NUM;
122 i2miMap_.push_back(0);
Owen Anderson35578012008-06-16 07:10:49 +0000123 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000124
Owen Anderson1fbb4542008-06-16 16:58:24 +0000125 // Set the MBB2IdxMap entry for this MBB.
126 MBB2IdxMap[MBB->getNumber()] = std::make_pair(StartIdx, MIIndex - 1);
127 Idx2MBBMap.push_back(std::make_pair(StartIdx, MBB));
Chris Lattner428b92e2006-09-15 03:57:23 +0000128 }
Evan Cheng4ca980e2007-10-17 02:10:22 +0000129 std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
Owen Anderson80b3ce62008-05-28 20:54:50 +0000130
131 if (!OldI2MI.empty())
Owen Anderson7fbad272008-07-23 21:37:49 +0000132 for (iterator OI = begin(), OE = end(); OI != OE; ++OI)
133 for (LiveInterval::iterator LI = OI->second.begin(),
134 LE = OI->second.end(); LI != LE; ++LI) {
Owen Anderson4b5b2092008-05-29 18:15:49 +0000135
Owen Anderson7eec0c22008-05-29 23:01:22 +0000136 // Remap the start index of the live range to the corresponding new
137 // number, or our best guess at what it _should_ correspond to if the
138 // original instruction has been erased. This is either the following
139 // instruction or its predecessor.
Owen Anderson7fbad272008-07-23 21:37:49 +0000140 unsigned index = LI->start / InstrSlots::NUM;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000141 unsigned offset = LI->start % InstrSlots::NUM;
Owen Anderson0a7615a2008-07-25 23:06:59 +0000142 if (offset == InstrSlots::LOAD) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000143 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000144 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->start);
Owen Anderson7fbad272008-07-23 21:37:49 +0000145 // Take the pair containing the index
146 std::vector<IdxMBBPair>::const_iterator J =
147 ((I != OldI2MBB.end() && I->first > index) ||
148 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000149
Owen Anderson7fbad272008-07-23 21:37:49 +0000150 LI->start = getMBBStartIdx(J->second);
151 } else {
152 LI->start = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000153 }
154
155 // Remap the ending index in the same way that we remapped the start,
156 // except for the final step where we always map to the immediately
157 // following instruction.
Owen Andersond7dcbec2008-07-25 19:50:48 +0000158 index = (LI->end - 1) / InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000159 offset = LI->end % InstrSlots::NUM;
Owen Anderson0a7615a2008-07-25 23:06:59 +0000160 if (offset == InstrSlots::USE) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000161 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000162 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->end);
Owen Anderson7fbad272008-07-23 21:37:49 +0000163 // Take the pair containing the index
164 std::vector<IdxMBBPair>::const_iterator J =
165 ((I != OldI2MBB.end() && I->first > index) ||
166 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
167
168 LI->end = getMBBEndIdx(J->second) + 1;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000169 } else {
Owen Andersond7dcbec2008-07-25 19:50:48 +0000170 unsigned idx = index;
Owen Anderson8d0cc0a2008-07-25 21:07:13 +0000171 while (index < OldI2MI.size() && !OldI2MI[index]) ++index;
172
173 if (index != OldI2MI.size())
174 LI->end = mi2iMap_[OldI2MI[index]] + (idx == index ? offset : 0);
175 else
176 LI->end = InstrSlots::NUM * i2miMap_.size();
Owen Anderson4b5b2092008-05-29 18:15:49 +0000177 }
Owen Anderson745825f42008-05-28 22:40:08 +0000178
Owen Anderson7eec0c22008-05-29 23:01:22 +0000179 // Remap the VNInfo def index, which works the same as the
180 // start indices above.
Owen Anderson745825f42008-05-28 22:40:08 +0000181 VNInfo* vni = LI->valno;
Owen Anderson0a7615a2008-07-25 23:06:59 +0000182 index = vni->def / InstrSlots::NUM;
183 offset = vni->def % InstrSlots::NUM;
184 if (offset == InstrSlots::LOAD) {
185 std::vector<IdxMBBPair>::const_iterator I =
186 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->def);
187 // 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;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000191
Owen Anderson0a7615a2008-07-25 23:06:59 +0000192 vni->def = getMBBStartIdx(J->second);
Owen Anderson7fbad272008-07-23 21:37:49 +0000193
Owen Anderson0a7615a2008-07-25 23:06:59 +0000194 } else {
195 vni->def = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000196 }
Owen Anderson745825f42008-05-28 22:40:08 +0000197
Owen Anderson7eec0c22008-05-29 23:01:22 +0000198 // Remap the VNInfo kill indices, which works the same as
199 // the end indices above.
Owen Anderson4b5b2092008-05-29 18:15:49 +0000200 for (size_t i = 0; i < vni->kills.size(); ++i) {
Owen Andersond7dcbec2008-07-25 19:50:48 +0000201 index = (vni->kills[i]-1) / InstrSlots::NUM;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000202 offset = vni->kills[i] % InstrSlots::NUM;
Owen Anderson0a7615a2008-07-25 23:06:59 +0000203 if (offset == InstrSlots::USE) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000204 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000205 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->kills[i]);
Owen Anderson7fbad272008-07-23 21:37:49 +0000206 // Take the pair containing the index
207 std::vector<IdxMBBPair>::const_iterator J =
208 ((I != OldI2MBB.end() && I->first > index) ||
209 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
210
211 vni->kills[i] = getMBBEndIdx(J->second) + 1;
212 } else {
Owen Andersond7dcbec2008-07-25 19:50:48 +0000213 unsigned idx = index;
214 while (!OldI2MI[index]) ++index;
Owen Anderson8d0cc0a2008-07-25 21:07:13 +0000215 while (index < OldI2MI.size() && !OldI2MI[index]) ++index;
216
217 if (index != OldI2MI.size())
218 vni->kills[i] = mi2iMap_[OldI2MI[index]] +
219 (idx == index ? offset : 0);
220 else
221 vni->kills[i] = InstrSlots::NUM * i2miMap_.size();
Owen Anderson7eec0c22008-05-29 23:01:22 +0000222 }
Owen Anderson4b5b2092008-05-29 18:15:49 +0000223 }
Owen Anderson80b3ce62008-05-28 20:54:50 +0000224 }
225}
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000226
Owen Anderson80b3ce62008-05-28 20:54:50 +0000227/// runOnMachineFunction - Register allocate the whole function
228///
229bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
230 mf_ = &fn;
231 mri_ = &mf_->getRegInfo();
232 tm_ = &fn.getTarget();
233 tri_ = tm_->getRegisterInfo();
234 tii_ = tm_->getInstrInfo();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000235 aa_ = &getAnalysis<AliasAnalysis>();
Owen Anderson80b3ce62008-05-28 20:54:50 +0000236 lv_ = &getAnalysis<LiveVariables>();
237 allocatableRegs_ = tri_->getAllocatableSet(fn);
238
239 computeNumbering();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000240 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000241
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000242 numIntervals += getNumIntervals();
243
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000244 DOUT << "********** INTERVALS **********\n";
245 for (iterator I = begin(), E = end(); I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000246 I->second.print(DOUT, tri_);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000247 DOUT << "\n";
248 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000249
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000250 numIntervalsAfter += getNumIntervals();
Chris Lattner70ca3582004-09-30 15:59:17 +0000251 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000252 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000253}
254
Chris Lattner70ca3582004-09-30 15:59:17 +0000255/// print - Implement the dump method.
Reid Spencerce9653c2004-12-07 04:03:45 +0000256void LiveIntervals::print(std::ostream &O, const Module* ) const {
Chris Lattner70ca3582004-09-30 15:59:17 +0000257 O << "********** INTERVALS **********\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000258 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Evan Cheng3f32d652008-06-04 09:18:41 +0000259 I->second.print(O, tri_);
260 O << "\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000261 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000262
263 O << "********** MACHINEINSTRS **********\n";
264 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
265 mbbi != mbbe; ++mbbi) {
266 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
267 for (MachineBasicBlock::iterator mii = mbbi->begin(),
268 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner477e4552004-09-30 16:10:45 +0000269 O << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner70ca3582004-09-30 15:59:17 +0000270 }
271 }
272}
273
Evan Chengc92da382007-11-03 07:20:12 +0000274/// conflictsWithPhysRegDef - Returns true if the specified register
275/// is defined during the duration of the specified interval.
276bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
277 VirtRegMap &vrm, unsigned reg) {
278 for (LiveInterval::Ranges::const_iterator
279 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
280 for (unsigned index = getBaseIndex(I->start),
281 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
282 index += InstrSlots::NUM) {
283 // skip deleted instructions
284 while (index != end && !getInstructionFromIndex(index))
285 index += InstrSlots::NUM;
286 if (index == end) break;
287
288 MachineInstr *MI = getInstructionFromIndex(index);
Evan Cheng5d446262007-11-15 08:13:29 +0000289 unsigned SrcReg, DstReg;
290 if (tii_->isMoveInstr(*MI, SrcReg, DstReg))
291 if (SrcReg == li.reg || DstReg == li.reg)
292 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000293 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
294 MachineOperand& mop = MI->getOperand(i);
Evan Cheng5d446262007-11-15 08:13:29 +0000295 if (!mop.isRegister())
Evan Chengc92da382007-11-03 07:20:12 +0000296 continue;
297 unsigned PhysReg = mop.getReg();
Evan Cheng5d446262007-11-15 08:13:29 +0000298 if (PhysReg == 0 || PhysReg == li.reg)
Evan Chengc92da382007-11-03 07:20:12 +0000299 continue;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000300 if (TargetRegisterInfo::isVirtualRegister(PhysReg)) {
Evan Cheng5d446262007-11-15 08:13:29 +0000301 if (!vrm.hasPhys(PhysReg))
302 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000303 PhysReg = vrm.getPhys(PhysReg);
Evan Cheng5d446262007-11-15 08:13:29 +0000304 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000305 if (PhysReg && tri_->regsOverlap(PhysReg, reg))
Evan Chengc92da382007-11-03 07:20:12 +0000306 return true;
307 }
308 }
309 }
310
311 return false;
312}
313
Evan Cheng549f27d32007-08-13 23:45:17 +0000314void LiveIntervals::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000315 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000316 cerr << tri_->getName(reg);
Evan Cheng549f27d32007-08-13 23:45:17 +0000317 else
318 cerr << "%reg" << reg;
319}
320
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000321void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000322 MachineBasicBlock::iterator mi,
Owen Anderson6b098de2008-06-25 23:39:39 +0000323 unsigned MIIdx, MachineOperand& MO,
Evan Chengef0732d2008-07-10 07:35:43 +0000324 unsigned MOIdx,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000325 LiveInterval &interval) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000326 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000327 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000328
Evan Cheng419852c2008-04-03 16:39:43 +0000329 if (mi->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
330 DOUT << "is a implicit_def\n";
331 return;
332 }
333
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000334 // Virtual registers may be defined multiple times (due to phi
335 // elimination and 2-addr elimination). Much of what we do only has to be
336 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000337 // time we see a vreg.
338 if (interval.empty()) {
339 // Get the Idx of the defining instructions.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000340 unsigned defIndex = getDefIndex(MIIdx);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000341 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000342 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000343 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000344 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000345 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000346 tii_->isMoveInstr(*mi, SrcReg, DstReg))
347 CopyMI = mi;
348 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000349
350 assert(ValNo->id == 0 && "First value in interval is not 0?");
Chris Lattner7ac2d312004-07-24 02:59:07 +0000351
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000352 // Loop over all of the blocks that the vreg is defined in. There are
353 // two cases we have to handle here. The most common case is a vreg
354 // whose lifetime is contained within a basic block. In this case there
355 // will be a single kill, in MBB, which comes after the definition.
356 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
357 // FIXME: what about dead vars?
358 unsigned killIdx;
359 if (vi.Kills[0] != mi)
360 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
361 else
362 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000363
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000364 // If the kill happens after the definition, we have an intra-block
365 // live range.
366 if (killIdx > defIndex) {
Evan Cheng61de82d2007-02-15 05:59:24 +0000367 assert(vi.AliveBlocks.none() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000368 "Shouldn't be alive across any blocks!");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000369 LiveRange LR(defIndex, killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000370 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000371 DOUT << " +" << LR << "\n";
Evan Chengf3bb2e62007-09-05 21:46:51 +0000372 interval.addKill(ValNo, killIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000373 return;
374 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000375 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000376
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000377 // The other case we handle is when a virtual register lives to the end
378 // of the defining block, potentially live across some blocks, then is
379 // live into some number of blocks, but gets killed. Start by adding a
380 // range that goes from this definition to the end of the defining block.
Owen Anderson7fbad272008-07-23 21:37:49 +0000381 LiveRange NewLR(defIndex, getMBBEndIdx(mbb)+1, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000382 DOUT << " +" << NewLR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000383 interval.addRange(NewLR);
384
385 // Iterate over all of the blocks that the variable is completely
386 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
387 // live interval.
388 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
389 if (vi.AliveBlocks[i]) {
Owen Anderson31ec8412008-06-16 19:32:40 +0000390 LiveRange LR(getMBBStartIdx(i),
Evan Chengf26e8552008-06-17 20:13:36 +0000391 getMBBEndIdx(i)+1, // MBB ends at -1.
Owen Anderson31ec8412008-06-16 19:32:40 +0000392 ValNo);
393 interval.addRange(LR);
394 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000395 }
396 }
397
398 // Finally, this virtual register is live from the start of any killing
399 // block to the 'use' slot of the killing instruction.
400 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
401 MachineInstr *Kill = vi.Kills[i];
Evan Cheng8df78602007-08-08 03:00:28 +0000402 unsigned killIdx = getUseIndex(getInstructionIndex(Kill))+1;
Chris Lattner428b92e2006-09-15 03:57:23 +0000403 LiveRange LR(getMBBStartIdx(Kill->getParent()),
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000404 killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000405 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000406 interval.addKill(ValNo, killIdx);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000407 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000408 }
409
410 } else {
411 // If this is the second time we see a virtual register definition, it
412 // must be due to phi elimination or two addr elimination. If this is
Evan Chengbf105c82006-11-03 03:04:46 +0000413 // the result of two address elimination, then the vreg is one of the
414 // def-and-use register operand.
Evan Chengef0732d2008-07-10 07:35:43 +0000415 if (mi->isRegReDefinedByTwoAddr(interval.reg, MOIdx)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000416 // If this is a two-address definition, then we have already processed
417 // the live range. The only problem is that we didn't realize there
418 // are actually two values in the live interval. Because of this we
419 // need to take the LiveRegion that defines this register and split it
420 // into two values.
Evan Chenga07cec92008-01-10 08:22:10 +0000421 assert(interval.containsOneValue());
422 unsigned DefIndex = getDefIndex(interval.getValNumInfo(0)->def);
Chris Lattner6b128bd2006-09-03 08:07:11 +0000423 unsigned RedefIndex = getDefIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000424
Evan Cheng4f8ff162007-08-11 00:59:19 +0000425 const LiveRange *OldLR = interval.getLiveRangeContaining(RedefIndex-1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000426 VNInfo *OldValNo = OldLR->valno;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000427
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000428 // Delete the initial value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000429 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000430 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000431
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000432 // Two-address vregs should always only be redefined once. This means
433 // that at this point, there should be exactly one value number in it.
434 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
435
Chris Lattner91725b72006-08-31 05:54:43 +0000436 // The new value number (#1) is defined by the instruction we claimed
437 // defined value #0.
Evan Chengc8d044e2008-02-15 18:24:29 +0000438 VNInfo *ValNo = interval.getNextValue(OldValNo->def, OldValNo->copy,
439 VNInfoAllocator);
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000440
Chris Lattner91725b72006-08-31 05:54:43 +0000441 // Value#0 is now defined by the 2-addr instruction.
Evan Chengc8d044e2008-02-15 18:24:29 +0000442 OldValNo->def = RedefIndex;
443 OldValNo->copy = 0;
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000444
445 // Add the new live interval which replaces the range for the input copy.
446 LiveRange LR(DefIndex, RedefIndex, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000447 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000448 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000449 interval.addKill(ValNo, RedefIndex);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000450
451 // If this redefinition is dead, we need to add a dummy unit live
452 // range covering the def slot.
Owen Anderson6b098de2008-06-25 23:39:39 +0000453 if (MO.isDead())
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000454 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, OldValNo));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000455
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000456 DOUT << " RESULT: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000457 interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000458
459 } else {
460 // Otherwise, this must be because of phi elimination. If this is the
461 // first redefinition of the vreg that we have seen, go back and change
462 // the live range in the PHI block to be a different value number.
463 if (interval.containsOneValue()) {
464 assert(vi.Kills.size() == 1 &&
465 "PHI elimination vreg should have one kill, the PHI itself!");
466
467 // Remove the old range that we now know has an incorrect number.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000468 VNInfo *VNI = interval.getValNumInfo(0);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000469 MachineInstr *Killer = vi.Kills[0];
Chris Lattner428b92e2006-09-15 03:57:23 +0000470 unsigned Start = getMBBStartIdx(Killer->getParent());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000471 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000472 DOUT << " Removing [" << Start << "," << End << "] from: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000473 interval.print(DOUT, tri_); DOUT << "\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000474 interval.removeRange(Start, End);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000475 VNI->hasPHIKill = true;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000476 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000477
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000478 // Replace the interval with one of a NEW value number. Note that this
479 // value number isn't actually defined by an instruction, weird huh? :)
Evan Chengf3bb2e62007-09-05 21:46:51 +0000480 LiveRange LR(Start, End, interval.getNextValue(~0, 0, VNInfoAllocator));
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000481 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000482 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000483 interval.addKill(LR.valno, End);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000484 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000485 }
486
487 // In the case of PHI elimination, each variable definition is only
488 // live until the end of the block. We've already taken care of the
489 // rest of the live range.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000490 unsigned defIndex = getDefIndex(MIIdx);
Chris Lattner91725b72006-08-31 05:54:43 +0000491
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000492 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000493 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000494 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000495 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000496 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000497 tii_->isMoveInstr(*mi, SrcReg, DstReg))
498 CopyMI = mi;
499 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Chris Lattner91725b72006-08-31 05:54:43 +0000500
Owen Anderson7fbad272008-07-23 21:37:49 +0000501 unsigned killIndex = getMBBEndIdx(mbb) + 1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000502 LiveRange LR(defIndex, killIndex, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000503 interval.addRange(LR);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000504 interval.addKill(ValNo, killIndex);
505 ValNo->hasPHIKill = true;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000506 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000507 }
508 }
509
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000510 DOUT << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000511}
512
Chris Lattnerf35fef72004-07-23 21:24:19 +0000513void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000514 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000515 unsigned MIIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000516 MachineOperand& MO,
Chris Lattner91725b72006-08-31 05:54:43 +0000517 LiveInterval &interval,
Evan Chengc8d044e2008-02-15 18:24:29 +0000518 MachineInstr *CopyMI) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000519 // A physical register cannot be live across basic block, so its
520 // lifetime must end somewhere in its defining basic block.
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000521 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000522
Chris Lattner6b128bd2006-09-03 08:07:11 +0000523 unsigned baseIndex = MIIdx;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000524 unsigned start = getDefIndex(baseIndex);
525 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000526
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000527 // If it is not used after definition, it is considered dead at
528 // the instruction defining it. Hence its interval is:
529 // [defSlot(def), defSlot(def)+1)
Owen Anderson6b098de2008-06-25 23:39:39 +0000530 if (MO.isDead()) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000531 DOUT << " dead";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000532 end = getDefIndex(start) + 1;
533 goto exit;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000534 }
535
536 // If it is not dead on definition, it must be killed by a
537 // subsequent instruction. Hence its interval is:
538 // [defSlot(def), useSlot(kill)+1)
Owen Anderson7fbad272008-07-23 21:37:49 +0000539 baseIndex += InstrSlots::NUM;
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000540 while (++mi != MBB->end()) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000541 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
542 getInstructionFromIndex(baseIndex) == 0)
543 baseIndex += InstrSlots::NUM;
Evan Cheng6130f662008-03-05 00:59:57 +0000544 if (mi->killsRegister(interval.reg, tri_)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000545 DOUT << " killed";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000546 end = getUseIndex(baseIndex) + 1;
547 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000548 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Cheng9a1956a2006-11-15 20:54:11 +0000549 // Another instruction redefines the register before it is ever read.
550 // Then the register is essentially dead at the instruction that defines
551 // it. Hence its interval is:
552 // [defSlot(def), defSlot(def)+1)
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000553 DOUT << " dead";
Evan Cheng9a1956a2006-11-15 20:54:11 +0000554 end = getDefIndex(start) + 1;
555 goto exit;
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000556 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000557
558 baseIndex += InstrSlots::NUM;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000559 }
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000560
561 // The only case we should have a dead physreg here without a killing or
562 // instruction where we know it's dead is if it is live-in to the function
563 // and never used.
Evan Chengc8d044e2008-02-15 18:24:29 +0000564 assert(!CopyMI && "physreg was not killed in defining block!");
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000565 end = getDefIndex(start) + 1; // It's dead.
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000566
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000567exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000568 assert(start < end && "did not find end of interval?");
Chris Lattnerf768bba2005-03-09 23:05:19 +0000569
Evan Cheng24a3cc42007-04-25 07:30:23 +0000570 // Already exists? Extend old live interval.
571 LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000572 VNInfo *ValNo = (OldLR != interval.end())
Evan Chengc8d044e2008-02-15 18:24:29 +0000573 ? OldLR->valno : interval.getNextValue(start, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000574 LiveRange LR(start, end, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000575 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000576 interval.addKill(LR.valno, end);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000577 DOUT << " +" << LR << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000578}
579
Chris Lattnerf35fef72004-07-23 21:24:19 +0000580void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
581 MachineBasicBlock::iterator MI,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000582 unsigned MIIdx,
Evan Chengef0732d2008-07-10 07:35:43 +0000583 MachineOperand& MO,
584 unsigned MOIdx) {
Owen Anderson6b098de2008-06-25 23:39:39 +0000585 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Evan Chengef0732d2008-07-10 07:35:43 +0000586 handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000587 getOrCreateInterval(MO.getReg()));
588 else if (allocatableRegs_[MO.getReg()]) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000589 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000590 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000591 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000592 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000593 tii_->isMoveInstr(*MI, SrcReg, DstReg))
594 CopyMI = MI;
Owen Anderson6b098de2008-06-25 23:39:39 +0000595 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
596 getOrCreateInterval(MO.getReg()), CopyMI);
Evan Cheng24a3cc42007-04-25 07:30:23 +0000597 // Def of a register also defines its sub-registers.
Owen Anderson6b098de2008-06-25 23:39:39 +0000598 for (const unsigned* AS = tri_->getSubRegisters(MO.getReg()); *AS; ++AS)
Evan Cheng6130f662008-03-05 00:59:57 +0000599 // If MI also modifies the sub-register explicitly, avoid processing it
600 // more than once. Do not pass in TRI here so it checks for exact match.
601 if (!MI->modifiesRegister(*AS))
Owen Anderson6b098de2008-06-25 23:39:39 +0000602 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
603 getOrCreateInterval(*AS), 0);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000604 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000605}
606
Evan Chengb371f452007-02-19 21:49:54 +0000607void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000608 unsigned MIIdx,
Evan Cheng24a3cc42007-04-25 07:30:23 +0000609 LiveInterval &interval, bool isAlias) {
Evan Chengb371f452007-02-19 21:49:54 +0000610 DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg));
611
612 // Look for kills, if it reaches a def before it's killed, then it shouldn't
613 // be considered a livein.
614 MachineBasicBlock::iterator mi = MBB->begin();
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000615 unsigned baseIndex = MIIdx;
616 unsigned start = baseIndex;
Evan Chengb371f452007-02-19 21:49:54 +0000617 unsigned end = start;
618 while (mi != MBB->end()) {
Evan Cheng6130f662008-03-05 00:59:57 +0000619 if (mi->killsRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000620 DOUT << " killed";
621 end = getUseIndex(baseIndex) + 1;
622 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000623 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000624 // Another instruction redefines the register before it is ever read.
625 // Then the register is essentially dead at the instruction that defines
626 // it. Hence its interval is:
627 // [defSlot(def), defSlot(def)+1)
628 DOUT << " dead";
629 end = getDefIndex(start) + 1;
630 goto exit;
631 }
632
633 baseIndex += InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000634 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
635 getInstructionFromIndex(baseIndex) == 0)
636 baseIndex += InstrSlots::NUM;
Evan Chengb371f452007-02-19 21:49:54 +0000637 ++mi;
638 }
639
640exit:
Evan Cheng75611fb2007-06-27 01:16:36 +0000641 // Live-in register might not be used at all.
642 if (end == MIIdx) {
Evan Cheng292da942007-06-27 18:47:28 +0000643 if (isAlias) {
644 DOUT << " dead";
Evan Cheng75611fb2007-06-27 01:16:36 +0000645 end = getDefIndex(MIIdx) + 1;
Evan Cheng292da942007-06-27 18:47:28 +0000646 } else {
647 DOUT << " live through";
648 end = baseIndex;
649 }
Evan Cheng24a3cc42007-04-25 07:30:23 +0000650 }
651
Evan Chengf3bb2e62007-09-05 21:46:51 +0000652 LiveRange LR(start, end, interval.getNextValue(start, 0, VNInfoAllocator));
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000653 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000654 interval.addKill(LR.valno, end);
Evan Cheng24c2e5c2007-08-08 07:03:29 +0000655 DOUT << " +" << LR << '\n';
Evan Chengb371f452007-02-19 21:49:54 +0000656}
657
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000658/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000659/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000660/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000661/// which a variable is live
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000662void LiveIntervals::computeIntervals() {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000663 DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
664 << "********** Function: "
665 << ((Value*)mf_->getFunction())->getName() << '\n';
Chris Lattner6b128bd2006-09-03 08:07:11 +0000666 // Track the index of the current machine instr.
667 unsigned MIIndex = 0;
Owen Anderson7fbad272008-07-23 21:37:49 +0000668
669 // Skip over empty initial indices.
670 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
671 getInstructionFromIndex(MIIndex) == 0)
672 MIIndex += InstrSlots::NUM;
673
Chris Lattner428b92e2006-09-15 03:57:23 +0000674 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
675 MBBI != E; ++MBBI) {
676 MachineBasicBlock *MBB = MBBI;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000677 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000678
Chris Lattner428b92e2006-09-15 03:57:23 +0000679 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000680
Dan Gohmancb406c22007-10-03 19:26:29 +0000681 // Create intervals for live-ins to this BB first.
682 for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
683 LE = MBB->livein_end(); LI != LE; ++LI) {
684 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
685 // Multiple live-ins can alias the same register.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000686 for (const unsigned* AS = tri_->getSubRegisters(*LI); *AS; ++AS)
Dan Gohmancb406c22007-10-03 19:26:29 +0000687 if (!hasInterval(*AS))
688 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
689 true);
Chris Lattnerdffb2e82006-09-04 18:27:40 +0000690 }
691
Chris Lattner428b92e2006-09-15 03:57:23 +0000692 for (; MI != miEnd; ++MI) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000693 DOUT << MIIndex << "\t" << *MI;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000694
Evan Cheng438f7bc2006-11-10 08:43:01 +0000695 // Handle defs.
Chris Lattner428b92e2006-09-15 03:57:23 +0000696 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
697 MachineOperand &MO = MI->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000698 // handle register defs - build intervals
Chris Lattner428b92e2006-09-15 03:57:23 +0000699 if (MO.isRegister() && MO.getReg() && MO.isDef())
Evan Chengef0732d2008-07-10 07:35:43 +0000700 handleRegisterDef(MBB, MI, MIIndex, MO, i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000701 }
Chris Lattner6b128bd2006-09-03 08:07:11 +0000702
703 MIIndex += InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000704
705 // Skip over empty indices.
706 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
707 getInstructionFromIndex(MIIndex) == 0)
708 MIIndex += InstrSlots::NUM;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000709 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000710 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000711}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000712
Evan Cheng4ca980e2007-10-17 02:10:22 +0000713bool LiveIntervals::findLiveInMBBs(const LiveRange &LR,
Evan Chenga5bfc972007-10-17 06:53:44 +0000714 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
Evan Cheng4ca980e2007-10-17 02:10:22 +0000715 std::vector<IdxMBBPair>::const_iterator I =
716 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), LR.start);
717
718 bool ResVal = false;
719 while (I != Idx2MBBMap.end()) {
720 if (LR.end <= I->first)
721 break;
722 MBBs.push_back(I->second);
723 ResVal = true;
724 ++I;
725 }
726 return ResVal;
727}
728
729
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000730LiveInterval LiveIntervals::createInterval(unsigned reg) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000731 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
Jim Laskey7902c752006-11-07 12:25:45 +0000732 HUGE_VALF : 0.0F;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000733 return LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000734}
Evan Chengf2fbca62007-11-12 06:35:08 +0000735
Evan Chengc8d044e2008-02-15 18:24:29 +0000736/// getVNInfoSourceReg - Helper function that parses the specified VNInfo
737/// copy field and returns the source register that defines it.
738unsigned LiveIntervals::getVNInfoSourceReg(const VNInfo *VNI) const {
739 if (!VNI->copy)
740 return 0;
741
742 if (VNI->copy->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
743 return VNI->copy->getOperand(1).getReg();
Evan Cheng7e073ba2008-04-09 20:57:25 +0000744 if (VNI->copy->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
745 return VNI->copy->getOperand(2).getReg();
Evan Chengc8d044e2008-02-15 18:24:29 +0000746 unsigned SrcReg, DstReg;
747 if (tii_->isMoveInstr(*VNI->copy, SrcReg, DstReg))
748 return SrcReg;
749 assert(0 && "Unrecognized copy instruction!");
750 return 0;
751}
Evan Chengf2fbca62007-11-12 06:35:08 +0000752
753//===----------------------------------------------------------------------===//
754// Register allocator hooks.
755//
756
Evan Chengd70dbb52008-02-22 09:24:50 +0000757/// getReMatImplicitUse - If the remat definition MI has one (for now, we only
758/// allow one) virtual register operand, then its uses are implicitly using
759/// the register. Returns the virtual register.
760unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
761 MachineInstr *MI) const {
762 unsigned RegOp = 0;
763 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
764 MachineOperand &MO = MI->getOperand(i);
765 if (!MO.isRegister() || !MO.isUse())
766 continue;
767 unsigned Reg = MO.getReg();
768 if (Reg == 0 || Reg == li.reg)
769 continue;
770 // FIXME: For now, only remat MI with at most one register operand.
771 assert(!RegOp &&
772 "Can't rematerialize instruction with multiple register operand!");
773 RegOp = MO.getReg();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000774#ifndef NDEBUG
Evan Chengd70dbb52008-02-22 09:24:50 +0000775 break;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000776#endif
Evan Chengd70dbb52008-02-22 09:24:50 +0000777 }
778 return RegOp;
779}
780
781/// isValNoAvailableAt - Return true if the val# of the specified interval
782/// which reaches the given instruction also reaches the specified use index.
783bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
784 unsigned UseIdx) const {
785 unsigned Index = getInstructionIndex(MI);
786 VNInfo *ValNo = li.FindLiveRangeContaining(Index)->valno;
787 LiveInterval::const_iterator UI = li.FindLiveRangeContaining(UseIdx);
788 return UI != li.end() && UI->valno == ValNo;
789}
790
Evan Chengf2fbca62007-11-12 06:35:08 +0000791/// isReMaterializable - Returns true if the definition MI of the specified
792/// val# of the specified interval is re-materializable.
793bool LiveIntervals::isReMaterializable(const LiveInterval &li,
Evan Cheng5ef3a042007-12-06 00:01:56 +0000794 const VNInfo *ValNo, MachineInstr *MI,
795 bool &isLoad) {
Evan Chengf2fbca62007-11-12 06:35:08 +0000796 if (DisableReMat)
797 return false;
798
Evan Cheng20ccded2008-03-15 00:19:36 +0000799 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
Evan Chengd70dbb52008-02-22 09:24:50 +0000800 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000801
802 int FrameIdx = 0;
803 if (tii_->isLoadFromStackSlot(MI, FrameIdx) &&
Evan Cheng249ded32008-02-23 03:38:34 +0000804 mf_->getFrameInfo()->isImmutableObjectIndex(FrameIdx))
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000805 // FIXME: Let target specific isReallyTriviallyReMaterializable determines
806 // this but remember this is not safe to fold into a two-address
807 // instruction.
Evan Cheng249ded32008-02-23 03:38:34 +0000808 // This is a load from fixed stack slot. It can be rematerialized.
Evan Chengdd3465e2008-02-23 01:44:27 +0000809 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000810
Dan Gohman6d69ba82008-07-25 00:02:30 +0000811 // If the target-specific rules don't identify an instruction as
812 // being trivially rematerializable, use some target-independent
813 // rules.
814 if (!MI->getDesc().isRematerializable() ||
815 !tii_->isTriviallyReMaterializable(MI)) {
Dan Gohman4c8f8702008-07-25 15:08:37 +0000816 if (!EnableAggressiveRemat)
817 return false;
Evan Chengd70dbb52008-02-22 09:24:50 +0000818
Dan Gohman0471a792008-07-28 18:43:51 +0000819 // If the instruction accesses memory but the memoperands have been lost,
Dan Gohman6d69ba82008-07-25 00:02:30 +0000820 // we can't analyze it.
821 const TargetInstrDesc &TID = MI->getDesc();
822 if ((TID.mayLoad() || TID.mayStore()) && MI->memoperands_empty())
823 return false;
824
825 // Avoid instructions obviously unsafe for remat.
826 if (TID.hasUnmodeledSideEffects() || TID.isNotDuplicable())
827 return false;
828
829 // If the instruction accesses memory and the memory could be non-constant,
830 // assume the instruction is not rematerializable.
Dan Gohmanfed90b62008-07-28 21:51:04 +0000831 for (std::list<MachineMemOperand>::const_iterator I = MI->memoperands_begin(),
Dan Gohman6d69ba82008-07-25 00:02:30 +0000832 E = MI->memoperands_end(); I != E; ++I) {
833 const MachineMemOperand &MMO = *I;
834 if (MMO.isVolatile() || MMO.isStore())
835 return false;
836 const Value *V = MMO.getValue();
837 if (!V)
838 return false;
839 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
840 if (!PSV->isConstant(mf_->getFrameInfo()))
Evan Chengd70dbb52008-02-22 09:24:50 +0000841 return false;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000842 } else if (!aa_->pointsToConstantMemory(V))
843 return false;
844 }
845
846 // If any of the registers accessed are non-constant, conservatively assume
847 // the instruction is not rematerializable.
848 unsigned ImpUse = 0;
849 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
850 const MachineOperand &MO = MI->getOperand(i);
851 if (MO.isReg()) {
852 unsigned Reg = MO.getReg();
853 if (Reg == 0)
854 continue;
855 if (TargetRegisterInfo::isPhysicalRegister(Reg))
856 return false;
857
858 // Only allow one def, and that in the first operand.
859 if (MO.isDef() != (i == 0))
860 return false;
861
862 // Only allow constant-valued registers.
863 bool IsLiveIn = mri_->isLiveIn(Reg);
864 MachineRegisterInfo::def_iterator I = mri_->def_begin(Reg),
865 E = mri_->def_end();
866
867 // For the def, it should be the only def.
868 if (MO.isDef() && (next(I) != E || IsLiveIn))
869 return false;
870
871 if (MO.isUse()) {
872 // Only allow one use other register use, as that's all the
873 // remat mechanisms support currently.
874 if (Reg != li.reg) {
875 if (ImpUse == 0)
876 ImpUse = Reg;
877 else if (Reg != ImpUse)
878 return false;
879 }
880 // For uses, there should be only one associate def.
881 if (I != E && (next(I) != E || IsLiveIn))
882 return false;
883 }
Evan Chengd70dbb52008-02-22 09:24:50 +0000884 }
885 }
Evan Cheng5ef3a042007-12-06 00:01:56 +0000886 }
Evan Chengf2fbca62007-11-12 06:35:08 +0000887
Dan Gohman6d69ba82008-07-25 00:02:30 +0000888 unsigned ImpUse = getReMatImplicitUse(li, MI);
889 if (ImpUse) {
890 const LiveInterval &ImpLi = getInterval(ImpUse);
891 for (MachineRegisterInfo::use_iterator ri = mri_->use_begin(li.reg),
892 re = mri_->use_end(); ri != re; ++ri) {
893 MachineInstr *UseMI = &*ri;
894 unsigned UseIdx = getInstructionIndex(UseMI);
895 if (li.FindLiveRangeContaining(UseIdx)->valno != ValNo)
896 continue;
897 if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
898 return false;
899 }
900 }
901 return true;
Evan Cheng5ef3a042007-12-06 00:01:56 +0000902}
903
904/// isReMaterializable - Returns true if every definition of MI of every
905/// val# of the specified interval is re-materializable.
906bool LiveIntervals::isReMaterializable(const LiveInterval &li, bool &isLoad) {
907 isLoad = false;
908 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
909 i != e; ++i) {
910 const VNInfo *VNI = *i;
911 unsigned DefIdx = VNI->def;
912 if (DefIdx == ~1U)
913 continue; // Dead val#.
914 // Is the def for the val# rematerializable?
915 if (DefIdx == ~0u)
916 return false;
917 MachineInstr *ReMatDefMI = getInstructionFromIndex(DefIdx);
918 bool DefIsLoad = false;
Evan Chengd70dbb52008-02-22 09:24:50 +0000919 if (!ReMatDefMI ||
920 !isReMaterializable(li, VNI, ReMatDefMI, DefIsLoad))
Evan Cheng5ef3a042007-12-06 00:01:56 +0000921 return false;
922 isLoad |= DefIsLoad;
Evan Chengf2fbca62007-11-12 06:35:08 +0000923 }
924 return true;
925}
926
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000927/// FilterFoldedOps - Filter out two-address use operands. Return
928/// true if it finds any issue with the operands that ought to prevent
929/// folding.
930static bool FilterFoldedOps(MachineInstr *MI,
931 SmallVector<unsigned, 2> &Ops,
932 unsigned &MRInfo,
933 SmallVector<unsigned, 2> &FoldOps) {
Chris Lattner749c6f62008-01-07 07:27:27 +0000934 const TargetInstrDesc &TID = MI->getDesc();
Evan Cheng6e141fd2007-12-12 23:12:09 +0000935
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000936 MRInfo = 0;
Evan Chengaee4af62007-12-02 08:30:39 +0000937 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
938 unsigned OpIdx = Ops[i];
Evan Chengd70dbb52008-02-22 09:24:50 +0000939 MachineOperand &MO = MI->getOperand(OpIdx);
Evan Chengaee4af62007-12-02 08:30:39 +0000940 // FIXME: fold subreg use.
Evan Chengd70dbb52008-02-22 09:24:50 +0000941 if (MO.getSubReg())
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000942 return true;
Evan Chengd70dbb52008-02-22 09:24:50 +0000943 if (MO.isDef())
Evan Chengaee4af62007-12-02 08:30:39 +0000944 MRInfo |= (unsigned)VirtRegMap::isMod;
945 else {
946 // Filter out two-address use operand(s).
Evan Chengd70dbb52008-02-22 09:24:50 +0000947 if (!MO.isImplicit() &&
948 TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1) {
Evan Chengaee4af62007-12-02 08:30:39 +0000949 MRInfo = VirtRegMap::isModRef;
950 continue;
951 }
952 MRInfo |= (unsigned)VirtRegMap::isRef;
953 }
954 FoldOps.push_back(OpIdx);
Evan Chenge62f97c2007-12-01 02:07:52 +0000955 }
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000956 return false;
957}
958
959
960/// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
961/// slot / to reg or any rematerialized load into ith operand of specified
962/// MI. If it is successul, MI is updated with the newly created MI and
963/// returns true.
964bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
965 VirtRegMap &vrm, MachineInstr *DefMI,
966 unsigned InstrIdx,
967 SmallVector<unsigned, 2> &Ops,
968 bool isSS, int Slot, unsigned Reg) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000969 // If it is an implicit def instruction, just delete it.
Evan Cheng20ccded2008-03-15 00:19:36 +0000970 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000971 RemoveMachineInstrFromMaps(MI);
972 vrm.RemoveMachineInstrFromMaps(MI);
973 MI->eraseFromParent();
974 ++numFolds;
975 return true;
976 }
977
978 // Filter the list of operand indexes that are to be folded. Abort if
979 // any operand will prevent folding.
980 unsigned MRInfo = 0;
981 SmallVector<unsigned, 2> FoldOps;
982 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
983 return false;
Evan Chenge62f97c2007-12-01 02:07:52 +0000984
Evan Cheng427f4c12008-03-31 23:19:51 +0000985 // The only time it's safe to fold into a two address instruction is when
986 // it's folding reload and spill from / into a spill stack slot.
987 if (DefMI && (MRInfo & VirtRegMap::isMod))
Evan Cheng249ded32008-02-23 03:38:34 +0000988 return false;
989
Evan Chengf2f8c2a2008-02-08 22:05:27 +0000990 MachineInstr *fmi = isSS ? tii_->foldMemoryOperand(*mf_, MI, FoldOps, Slot)
991 : tii_->foldMemoryOperand(*mf_, MI, FoldOps, DefMI);
Evan Chengf2fbca62007-11-12 06:35:08 +0000992 if (fmi) {
Evan Chengd3653122008-02-27 03:04:06 +0000993 // Remember this instruction uses the spill slot.
994 if (isSS) vrm.addSpillSlotUse(Slot, fmi);
995
Evan Chengf2fbca62007-11-12 06:35:08 +0000996 // Attempt to fold the memory reference into the instruction. If
997 // we can do this, we don't need to insert spill code.
Evan Chengf2fbca62007-11-12 06:35:08 +0000998 MachineBasicBlock &MBB = *MI->getParent();
Evan Cheng84802932008-01-10 08:24:38 +0000999 if (isSS && !mf_->getFrameInfo()->isImmutableObjectIndex(Slot))
Evan Chengaee4af62007-12-02 08:30:39 +00001000 vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
Evan Cheng81a03822007-11-17 00:40:40 +00001001 vrm.transferSpillPts(MI, fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001002 vrm.transferRestorePts(MI, fmi);
Evan Chengc1f53c72008-03-11 21:34:46 +00001003 vrm.transferEmergencySpills(MI, fmi);
Evan Chengf2fbca62007-11-12 06:35:08 +00001004 mi2iMap_.erase(MI);
Evan Chengcddbb832007-11-30 21:23:43 +00001005 i2miMap_[InstrIdx /InstrSlots::NUM] = fmi;
1006 mi2iMap_[fmi] = InstrIdx;
Evan Chengf2fbca62007-11-12 06:35:08 +00001007 MI = MBB.insert(MBB.erase(MI), fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001008 ++numFolds;
Evan Chengf2fbca62007-11-12 06:35:08 +00001009 return true;
1010 }
1011 return false;
1012}
1013
Evan Cheng018f9b02007-12-05 03:22:34 +00001014/// canFoldMemoryOperand - Returns true if the specified load / store
1015/// folding is possible.
1016bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI,
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001017 SmallVector<unsigned, 2> &Ops,
Evan Cheng3c75ba82008-04-01 21:37:32 +00001018 bool ReMat) const {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001019 // Filter the list of operand indexes that are to be folded. Abort if
1020 // any operand will prevent folding.
1021 unsigned MRInfo = 0;
Evan Cheng018f9b02007-12-05 03:22:34 +00001022 SmallVector<unsigned, 2> FoldOps;
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001023 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1024 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001025
Evan Cheng3c75ba82008-04-01 21:37:32 +00001026 // It's only legal to remat for a use, not a def.
1027 if (ReMat && (MRInfo & VirtRegMap::isMod))
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001028 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001029
Evan Chengd70dbb52008-02-22 09:24:50 +00001030 return tii_->canFoldMemoryOperand(MI, FoldOps);
1031}
1032
Evan Cheng81a03822007-11-17 00:40:40 +00001033bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
1034 SmallPtrSet<MachineBasicBlock*, 4> MBBs;
1035 for (LiveInterval::Ranges::const_iterator
1036 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1037 std::vector<IdxMBBPair>::const_iterator II =
1038 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), I->start);
1039 if (II == Idx2MBBMap.end())
1040 continue;
1041 if (I->end > II->first) // crossing a MBB.
1042 return false;
1043 MBBs.insert(II->second);
1044 if (MBBs.size() > 1)
1045 return false;
1046 }
1047 return true;
1048}
1049
Evan Chengd70dbb52008-02-22 09:24:50 +00001050/// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
1051/// interval on to-be re-materialized operands of MI) with new register.
1052void LiveIntervals::rewriteImplicitOps(const LiveInterval &li,
1053 MachineInstr *MI, unsigned NewVReg,
1054 VirtRegMap &vrm) {
1055 // There is an implicit use. That means one of the other operand is
1056 // being remat'ed and the remat'ed instruction has li.reg as an
1057 // use operand. Make sure we rewrite that as well.
1058 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1059 MachineOperand &MO = MI->getOperand(i);
1060 if (!MO.isRegister())
1061 continue;
1062 unsigned Reg = MO.getReg();
1063 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
1064 continue;
1065 if (!vrm.isReMaterialized(Reg))
1066 continue;
1067 MachineInstr *ReMatMI = vrm.getReMaterializedMI(Reg);
Evan Cheng6130f662008-03-05 00:59:57 +00001068 MachineOperand *UseMO = ReMatMI->findRegisterUseOperand(li.reg);
1069 if (UseMO)
1070 UseMO->setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001071 }
1072}
1073
Evan Chengf2fbca62007-11-12 06:35:08 +00001074/// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
1075/// for addIntervalsForSpills to rewrite uses / defs for the given live range.
Evan Cheng018f9b02007-12-05 03:22:34 +00001076bool LiveIntervals::
Evan Chengd70dbb52008-02-22 09:24:50 +00001077rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
1078 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
Evan Cheng81a03822007-11-17 00:40:40 +00001079 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001080 unsigned Slot, int LdSlot,
1081 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001082 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001083 const TargetRegisterClass* rc,
1084 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001085 const MachineLoopInfo *loopInfo,
Evan Cheng313d4b82008-02-23 00:33:04 +00001086 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001087 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001088 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
1089 MachineBasicBlock *MBB = MI->getParent();
1090 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng018f9b02007-12-05 03:22:34 +00001091 bool CanFold = false;
Evan Chengf2fbca62007-11-12 06:35:08 +00001092 RestartInstruction:
1093 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1094 MachineOperand& mop = MI->getOperand(i);
1095 if (!mop.isRegister())
1096 continue;
1097 unsigned Reg = mop.getReg();
1098 unsigned RegI = Reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001099 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
Evan Chengf2fbca62007-11-12 06:35:08 +00001100 continue;
Evan Chengf2fbca62007-11-12 06:35:08 +00001101 if (Reg != li.reg)
1102 continue;
1103
1104 bool TryFold = !DefIsReMat;
Evan Chengcb3c3302007-11-29 23:02:50 +00001105 bool FoldSS = true; // Default behavior unless it's a remat.
Evan Chengf2fbca62007-11-12 06:35:08 +00001106 int FoldSlot = Slot;
1107 if (DefIsReMat) {
1108 // If this is the rematerializable definition MI itself and
1109 // all of its uses are rematerialized, simply delete it.
Evan Cheng81a03822007-11-17 00:40:40 +00001110 if (MI == ReMatOrigDefMI && CanDelete) {
Evan Chengcddbb832007-11-30 21:23:43 +00001111 DOUT << "\t\t\t\tErasing re-materlizable def: ";
1112 DOUT << MI << '\n';
Evan Chengf2fbca62007-11-12 06:35:08 +00001113 RemoveMachineInstrFromMaps(MI);
Evan Chengcada2452007-11-28 01:28:46 +00001114 vrm.RemoveMachineInstrFromMaps(MI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001115 MI->eraseFromParent();
1116 break;
1117 }
1118
1119 // If def for this use can't be rematerialized, then try folding.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001120 // If def is rematerializable and it's a load, also try folding.
Evan Chengcb3c3302007-11-29 23:02:50 +00001121 TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad));
Evan Chengf2fbca62007-11-12 06:35:08 +00001122 if (isLoad) {
1123 // Try fold loads (from stack slot, constant pool, etc.) into uses.
1124 FoldSS = isLoadSS;
1125 FoldSlot = LdSlot;
1126 }
1127 }
1128
Evan Chengf2fbca62007-11-12 06:35:08 +00001129 // Scan all of the operands of this instruction rewriting operands
1130 // to use NewVReg instead of li.reg as appropriate. We do this for
1131 // two reasons:
1132 //
1133 // 1. If the instr reads the same spilled vreg multiple times, we
1134 // want to reuse the NewVReg.
1135 // 2. If the instr is a two-addr instruction, we are required to
1136 // keep the src/dst regs pinned.
1137 //
1138 // Keep track of whether we replace a use and/or def so that we can
1139 // create the spill interval with the appropriate range.
Evan Chengcddbb832007-11-30 21:23:43 +00001140
Evan Cheng81a03822007-11-17 00:40:40 +00001141 HasUse = mop.isUse();
1142 HasDef = mop.isDef();
Evan Chengaee4af62007-12-02 08:30:39 +00001143 SmallVector<unsigned, 2> Ops;
1144 Ops.push_back(i);
Evan Chengf2fbca62007-11-12 06:35:08 +00001145 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
Evan Chengaee4af62007-12-02 08:30:39 +00001146 const MachineOperand &MOj = MI->getOperand(j);
1147 if (!MOj.isRegister())
Evan Chengf2fbca62007-11-12 06:35:08 +00001148 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001149 unsigned RegJ = MOj.getReg();
Dan Gohman6f0d0242008-02-10 18:45:23 +00001150 if (RegJ == 0 || TargetRegisterInfo::isPhysicalRegister(RegJ))
Evan Chengf2fbca62007-11-12 06:35:08 +00001151 continue;
1152 if (RegJ == RegI) {
Evan Chengaee4af62007-12-02 08:30:39 +00001153 Ops.push_back(j);
1154 HasUse |= MOj.isUse();
1155 HasDef |= MOj.isDef();
Evan Chengf2fbca62007-11-12 06:35:08 +00001156 }
1157 }
1158
Evan Cheng79a796c2008-07-12 01:56:02 +00001159 if (HasUse && !li.liveAt(getUseIndex(index)))
1160 // Must be defined by an implicit def. It should not be spilled. Note,
1161 // this is for correctness reason. e.g.
1162 // 8 %reg1024<def> = IMPLICIT_DEF
1163 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1164 // The live range [12, 14) are not part of the r1024 live interval since
1165 // it's defined by an implicit def. It will not conflicts with live
1166 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001167 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001168 // the INSERT_SUBREG and both target registers that would overlap.
1169 HasUse = false;
1170
Evan Cheng9c3c2212008-06-06 07:54:39 +00001171 // Update stack slot spill weight if we are splitting.
Evan Chengc3417602008-06-21 06:45:54 +00001172 float Weight = getSpillWeight(HasDef, HasUse, loopDepth);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001173 if (!TrySplit)
1174 SSWeight += Weight;
1175
1176 if (!TryFold)
1177 CanFold = false;
1178 else {
Evan Cheng018f9b02007-12-05 03:22:34 +00001179 // Do not fold load / store here if we are splitting. We'll find an
1180 // optimal point to insert a load / store later.
1181 if (!TrySplit) {
1182 if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1183 Ops, FoldSS, FoldSlot, Reg)) {
1184 // Folding the load/store can completely change the instruction in
1185 // unpredictable ways, rescan it from the beginning.
1186 HasUse = false;
1187 HasDef = false;
1188 CanFold = false;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001189 if (isRemoved(MI)) {
1190 SSWeight -= Weight;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001191 break;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001192 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001193 goto RestartInstruction;
1194 }
1195 } else {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001196 // We'll try to fold it later if it's profitable.
Evan Cheng3c75ba82008-04-01 21:37:32 +00001197 CanFold = canFoldMemoryOperand(MI, Ops, DefIsReMat);
Evan Cheng018f9b02007-12-05 03:22:34 +00001198 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001199 }
Evan Chengcddbb832007-11-30 21:23:43 +00001200
1201 // Create a new virtual register for the spill interval.
1202 bool CreatedNewVReg = false;
1203 if (NewVReg == 0) {
Evan Chengd70dbb52008-02-22 09:24:50 +00001204 NewVReg = mri_->createVirtualRegister(rc);
Evan Chengcddbb832007-11-30 21:23:43 +00001205 vrm.grow();
1206 CreatedNewVReg = true;
1207 }
1208 mop.setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001209 if (mop.isImplicit())
1210 rewriteImplicitOps(li, MI, NewVReg, vrm);
Evan Chengcddbb832007-11-30 21:23:43 +00001211
1212 // Reuse NewVReg for other reads.
Evan Chengd70dbb52008-02-22 09:24:50 +00001213 for (unsigned j = 0, e = Ops.size(); j != e; ++j) {
1214 MachineOperand &mopj = MI->getOperand(Ops[j]);
1215 mopj.setReg(NewVReg);
1216 if (mopj.isImplicit())
1217 rewriteImplicitOps(li, MI, NewVReg, vrm);
1218 }
Evan Chengcddbb832007-11-30 21:23:43 +00001219
Evan Cheng81a03822007-11-17 00:40:40 +00001220 if (CreatedNewVReg) {
1221 if (DefIsReMat) {
1222 vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI/*, CanDelete*/);
Evan Chengd70dbb52008-02-22 09:24:50 +00001223 if (ReMatIds[VNI->id] == VirtRegMap::MAX_STACK_SLOT) {
Evan Cheng81a03822007-11-17 00:40:40 +00001224 // Each valnum may have its own remat id.
Evan Chengd70dbb52008-02-22 09:24:50 +00001225 ReMatIds[VNI->id] = vrm.assignVirtReMatId(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001226 } else {
Evan Chengd70dbb52008-02-22 09:24:50 +00001227 vrm.assignVirtReMatId(NewVReg, ReMatIds[VNI->id]);
Evan Cheng81a03822007-11-17 00:40:40 +00001228 }
1229 if (!CanDelete || (HasUse && HasDef)) {
1230 // If this is a two-addr instruction then its use operands are
1231 // rematerializable but its def is not. It should be assigned a
1232 // stack slot.
1233 vrm.assignVirt2StackSlot(NewVReg, Slot);
1234 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001235 } else {
Evan Chengf2fbca62007-11-12 06:35:08 +00001236 vrm.assignVirt2StackSlot(NewVReg, Slot);
1237 }
Evan Chengcb3c3302007-11-29 23:02:50 +00001238 } else if (HasUse && HasDef &&
1239 vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) {
1240 // If this interval hasn't been assigned a stack slot (because earlier
1241 // def is a deleted remat def), do it now.
1242 assert(Slot != VirtRegMap::NO_STACK_SLOT);
1243 vrm.assignVirt2StackSlot(NewVReg, Slot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001244 }
1245
Evan Cheng313d4b82008-02-23 00:33:04 +00001246 // Re-matting an instruction with virtual register use. Add the
1247 // register as an implicit use on the use MI.
1248 if (DefIsReMat && ImpUse)
1249 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1250
Evan Chengf2fbca62007-11-12 06:35:08 +00001251 // create a new register interval for this spill / remat.
1252 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001253 if (CreatedNewVReg) {
1254 NewLIs.push_back(&nI);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001255 MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg));
Evan Cheng81a03822007-11-17 00:40:40 +00001256 if (TrySplit)
1257 vrm.setIsSplitFromReg(NewVReg, li.reg);
1258 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001259
1260 if (HasUse) {
Evan Cheng81a03822007-11-17 00:40:40 +00001261 if (CreatedNewVReg) {
1262 LiveRange LR(getLoadIndex(index), getUseIndex(index)+1,
1263 nI.getNextValue(~0U, 0, VNInfoAllocator));
1264 DOUT << " +" << LR;
1265 nI.addRange(LR);
1266 } else {
1267 // Extend the split live interval to this def / use.
1268 unsigned End = getUseIndex(index)+1;
1269 LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
1270 nI.getValNumInfo(nI.getNumValNums()-1));
1271 DOUT << " +" << LR;
1272 nI.addRange(LR);
1273 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001274 }
1275 if (HasDef) {
1276 LiveRange LR(getDefIndex(index), getStoreIndex(index),
1277 nI.getNextValue(~0U, 0, VNInfoAllocator));
1278 DOUT << " +" << LR;
1279 nI.addRange(LR);
1280 }
Evan Cheng81a03822007-11-17 00:40:40 +00001281
Evan Chengf2fbca62007-11-12 06:35:08 +00001282 DOUT << "\t\t\t\tAdded new interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001283 nI.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001284 DOUT << '\n';
1285 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001286 return CanFold;
Evan Chengf2fbca62007-11-12 06:35:08 +00001287}
Evan Cheng81a03822007-11-17 00:40:40 +00001288bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001289 const VNInfo *VNI,
1290 MachineBasicBlock *MBB, unsigned Idx) const {
Evan Cheng81a03822007-11-17 00:40:40 +00001291 unsigned End = getMBBEndIdx(MBB);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001292 for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
1293 unsigned KillIdx = VNI->kills[j];
1294 if (KillIdx > Idx && KillIdx < End)
1295 return true;
Evan Cheng81a03822007-11-17 00:40:40 +00001296 }
1297 return false;
1298}
1299
Evan Cheng063284c2008-02-21 00:34:19 +00001300/// RewriteInfo - Keep track of machine instrs that will be rewritten
1301/// during spilling.
Dan Gohman844731a2008-05-13 00:00:25 +00001302namespace {
1303 struct RewriteInfo {
1304 unsigned Index;
1305 MachineInstr *MI;
1306 bool HasUse;
1307 bool HasDef;
1308 RewriteInfo(unsigned i, MachineInstr *mi, bool u, bool d)
1309 : Index(i), MI(mi), HasUse(u), HasDef(d) {}
1310 };
Evan Cheng063284c2008-02-21 00:34:19 +00001311
Dan Gohman844731a2008-05-13 00:00:25 +00001312 struct RewriteInfoCompare {
1313 bool operator()(const RewriteInfo &LHS, const RewriteInfo &RHS) const {
1314 return LHS.Index < RHS.Index;
1315 }
1316 };
1317}
Evan Cheng063284c2008-02-21 00:34:19 +00001318
Evan Chengf2fbca62007-11-12 06:35:08 +00001319void LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001320rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
Evan Chengf2fbca62007-11-12 06:35:08 +00001321 LiveInterval::Ranges::const_iterator &I,
Evan Cheng81a03822007-11-17 00:40:40 +00001322 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001323 unsigned Slot, int LdSlot,
1324 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001325 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001326 const TargetRegisterClass* rc,
1327 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001328 const MachineLoopInfo *loopInfo,
Evan Cheng81a03822007-11-17 00:40:40 +00001329 BitVector &SpillMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001330 std::map<unsigned, std::vector<SRInfo> > &SpillIdxes,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001331 BitVector &RestoreMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001332 std::map<unsigned, std::vector<SRInfo> > &RestoreIdxes,
1333 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001334 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001335 bool AllCanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001336 unsigned NewVReg = 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001337 unsigned start = getBaseIndex(I->start);
Evan Chengf2fbca62007-11-12 06:35:08 +00001338 unsigned end = getBaseIndex(I->end-1) + InstrSlots::NUM;
Evan Chengf2fbca62007-11-12 06:35:08 +00001339
Evan Cheng063284c2008-02-21 00:34:19 +00001340 // First collect all the def / use in this live range that will be rewritten.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001341 // Make sure they are sorted according to instruction index.
Evan Cheng063284c2008-02-21 00:34:19 +00001342 std::vector<RewriteInfo> RewriteMIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001343 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1344 re = mri_->reg_end(); ri != re; ) {
Evan Cheng419852c2008-04-03 16:39:43 +00001345 MachineInstr *MI = &*ri;
Evan Cheng063284c2008-02-21 00:34:19 +00001346 MachineOperand &O = ri.getOperand();
1347 ++ri;
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001348 assert(!O.isImplicit() && "Spilling register that's used as implicit use?");
Evan Cheng063284c2008-02-21 00:34:19 +00001349 unsigned index = getInstructionIndex(MI);
1350 if (index < start || index >= end)
1351 continue;
Evan Cheng79a796c2008-07-12 01:56:02 +00001352 if (O.isUse() && !li.liveAt(getUseIndex(index)))
1353 // Must be defined by an implicit def. It should not be spilled. Note,
1354 // this is for correctness reason. e.g.
1355 // 8 %reg1024<def> = IMPLICIT_DEF
1356 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1357 // The live range [12, 14) are not part of the r1024 live interval since
1358 // it's defined by an implicit def. It will not conflicts with live
1359 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001360 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001361 // the INSERT_SUBREG and both target registers that would overlap.
1362 continue;
Evan Cheng063284c2008-02-21 00:34:19 +00001363 RewriteMIs.push_back(RewriteInfo(index, MI, O.isUse(), O.isDef()));
1364 }
1365 std::sort(RewriteMIs.begin(), RewriteMIs.end(), RewriteInfoCompare());
1366
Evan Cheng313d4b82008-02-23 00:33:04 +00001367 unsigned ImpUse = DefIsReMat ? getReMatImplicitUse(li, ReMatDefMI) : 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001368 // Now rewrite the defs and uses.
1369 for (unsigned i = 0, e = RewriteMIs.size(); i != e; ) {
1370 RewriteInfo &rwi = RewriteMIs[i];
1371 ++i;
1372 unsigned index = rwi.Index;
1373 bool MIHasUse = rwi.HasUse;
1374 bool MIHasDef = rwi.HasDef;
1375 MachineInstr *MI = rwi.MI;
1376 // If MI def and/or use the same register multiple times, then there
1377 // are multiple entries.
Evan Cheng313d4b82008-02-23 00:33:04 +00001378 unsigned NumUses = MIHasUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001379 while (i != e && RewriteMIs[i].MI == MI) {
1380 assert(RewriteMIs[i].Index == index);
Evan Cheng313d4b82008-02-23 00:33:04 +00001381 bool isUse = RewriteMIs[i].HasUse;
1382 if (isUse) ++NumUses;
1383 MIHasUse |= isUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001384 MIHasDef |= RewriteMIs[i].HasDef;
1385 ++i;
1386 }
Evan Cheng81a03822007-11-17 00:40:40 +00001387 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng313d4b82008-02-23 00:33:04 +00001388
Evan Cheng0a891ed2008-05-23 23:00:04 +00001389 if (ImpUse && MI != ReMatDefMI) {
Evan Cheng313d4b82008-02-23 00:33:04 +00001390 // Re-matting an instruction with virtual register use. Update the
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001391 // register interval's spill weight to HUGE_VALF to prevent it from
1392 // being spilled.
Evan Cheng313d4b82008-02-23 00:33:04 +00001393 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001394 ImpLi.weight = HUGE_VALF;
Evan Cheng313d4b82008-02-23 00:33:04 +00001395 }
1396
Evan Cheng063284c2008-02-21 00:34:19 +00001397 unsigned MBBId = MBB->getNumber();
Evan Cheng018f9b02007-12-05 03:22:34 +00001398 unsigned ThisVReg = 0;
Evan Cheng70306f82007-12-03 09:58:48 +00001399 if (TrySplit) {
Evan Cheng063284c2008-02-21 00:34:19 +00001400 std::map<unsigned,unsigned>::const_iterator NVI = MBBVRegsMap.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001401 if (NVI != MBBVRegsMap.end()) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001402 ThisVReg = NVI->second;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001403 // One common case:
1404 // x = use
1405 // ...
1406 // ...
1407 // def = ...
1408 // = use
1409 // It's better to start a new interval to avoid artifically
1410 // extend the new interval.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001411 if (MIHasDef && !MIHasUse) {
1412 MBBVRegsMap.erase(MBB->getNumber());
Evan Cheng018f9b02007-12-05 03:22:34 +00001413 ThisVReg = 0;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001414 }
1415 }
Evan Chengcada2452007-11-28 01:28:46 +00001416 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001417
1418 bool IsNew = ThisVReg == 0;
1419 if (IsNew) {
1420 // This ends the previous live interval. If all of its def / use
1421 // can be folded, give it a low spill weight.
1422 if (NewVReg && TrySplit && AllCanFold) {
1423 LiveInterval &nI = getOrCreateInterval(NewVReg);
1424 nI.weight /= 10.0F;
1425 }
1426 AllCanFold = true;
1427 }
1428 NewVReg = ThisVReg;
1429
Evan Cheng81a03822007-11-17 00:40:40 +00001430 bool HasDef = false;
1431 bool HasUse = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001432 bool CanFold = rewriteInstructionForSpills(li, I->valno, TrySplit,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001433 index, end, MI, ReMatOrigDefMI, ReMatDefMI,
1434 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
1435 CanDelete, vrm, rc, ReMatIds, loopInfo, NewVReg,
1436 ImpUse, HasDef, HasUse, MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001437 if (!HasDef && !HasUse)
1438 continue;
1439
Evan Cheng018f9b02007-12-05 03:22:34 +00001440 AllCanFold &= CanFold;
1441
Evan Cheng81a03822007-11-17 00:40:40 +00001442 // Update weight of spill interval.
1443 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng70306f82007-12-03 09:58:48 +00001444 if (!TrySplit) {
Evan Cheng81a03822007-11-17 00:40:40 +00001445 // The spill weight is now infinity as it cannot be spilled again.
1446 nI.weight = HUGE_VALF;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001447 continue;
Evan Cheng81a03822007-11-17 00:40:40 +00001448 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001449
1450 // Keep track of the last def and first use in each MBB.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001451 if (HasDef) {
1452 if (MI != ReMatOrigDefMI || !CanDelete) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001453 bool HasKill = false;
1454 if (!HasUse)
1455 HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, getDefIndex(index));
1456 else {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001457 // If this is a two-address code, then this index starts a new VNInfo.
Evan Cheng3f32d652008-06-04 09:18:41 +00001458 const VNInfo *VNI = li.findDefinedVNInfo(getDefIndex(index));
Evan Cheng0cbb1162007-11-29 01:06:25 +00001459 if (VNI)
1460 HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, getDefIndex(index));
1461 }
Evan Chenge3110d02007-12-01 04:42:39 +00001462 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
1463 SpillIdxes.find(MBBId);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001464 if (!HasKill) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001465 if (SII == SpillIdxes.end()) {
1466 std::vector<SRInfo> S;
1467 S.push_back(SRInfo(index, NewVReg, true));
1468 SpillIdxes.insert(std::make_pair(MBBId, S));
1469 } else if (SII->second.back().vreg != NewVReg) {
1470 SII->second.push_back(SRInfo(index, NewVReg, true));
1471 } else if ((int)index > SII->second.back().index) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001472 // If there is an earlier def and this is a two-address
1473 // instruction, then it's not possible to fold the store (which
1474 // would also fold the load).
Evan Cheng1953d0c2007-11-29 10:12:14 +00001475 SRInfo &Info = SII->second.back();
1476 Info.index = index;
1477 Info.canFold = !HasUse;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001478 }
1479 SpillMBBs.set(MBBId);
Evan Chenge3110d02007-12-01 04:42:39 +00001480 } else if (SII != SpillIdxes.end() &&
1481 SII->second.back().vreg == NewVReg &&
1482 (int)index > SII->second.back().index) {
1483 // There is an earlier def that's not killed (must be two-address).
1484 // The spill is no longer needed.
1485 SII->second.pop_back();
1486 if (SII->second.empty()) {
1487 SpillIdxes.erase(MBBId);
1488 SpillMBBs.reset(MBBId);
1489 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001490 }
1491 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001492 }
1493
1494 if (HasUse) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001495 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001496 SpillIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001497 if (SII != SpillIdxes.end() &&
1498 SII->second.back().vreg == NewVReg &&
1499 (int)index > SII->second.back().index)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001500 // Use(s) following the last def, it's not safe to fold the spill.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001501 SII->second.back().canFold = false;
1502 std::map<unsigned, std::vector<SRInfo> >::iterator RII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001503 RestoreIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001504 if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001505 // If we are splitting live intervals, only fold if it's the first
1506 // use and there isn't another use later in the MBB.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001507 RII->second.back().canFold = false;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001508 else if (IsNew) {
1509 // Only need a reload if there isn't an earlier def / use.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001510 if (RII == RestoreIdxes.end()) {
1511 std::vector<SRInfo> Infos;
1512 Infos.push_back(SRInfo(index, NewVReg, true));
1513 RestoreIdxes.insert(std::make_pair(MBBId, Infos));
1514 } else {
1515 RII->second.push_back(SRInfo(index, NewVReg, true));
1516 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001517 RestoreMBBs.set(MBBId);
1518 }
1519 }
1520
1521 // Update spill weight.
Evan Cheng22f07ff2007-12-11 02:09:15 +00001522 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Chengc3417602008-06-21 06:45:54 +00001523 nI.weight += getSpillWeight(HasDef, HasUse, loopDepth);
Evan Chengf2fbca62007-11-12 06:35:08 +00001524 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001525
1526 if (NewVReg && TrySplit && AllCanFold) {
1527 // If all of its def / use can be folded, give it a low spill weight.
1528 LiveInterval &nI = getOrCreateInterval(NewVReg);
1529 nI.weight /= 10.0F;
1530 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001531}
1532
Evan Cheng1953d0c2007-11-29 10:12:14 +00001533bool LiveIntervals::alsoFoldARestore(int Id, int index, unsigned vr,
1534 BitVector &RestoreMBBs,
1535 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1536 if (!RestoreMBBs[Id])
1537 return false;
1538 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1539 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1540 if (Restores[i].index == index &&
1541 Restores[i].vreg == vr &&
1542 Restores[i].canFold)
1543 return true;
1544 return false;
1545}
1546
1547void LiveIntervals::eraseRestoreInfo(int Id, int index, unsigned vr,
1548 BitVector &RestoreMBBs,
1549 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1550 if (!RestoreMBBs[Id])
1551 return;
1552 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1553 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1554 if (Restores[i].index == index && Restores[i].vreg)
1555 Restores[i].index = -1;
1556}
Evan Cheng81a03822007-11-17 00:40:40 +00001557
Evan Cheng4cce6b42008-04-11 17:53:36 +00001558/// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
1559/// spilled and create empty intervals for their uses.
1560void
1561LiveIntervals::handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
1562 const TargetRegisterClass* rc,
1563 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng419852c2008-04-03 16:39:43 +00001564 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1565 re = mri_->reg_end(); ri != re; ) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001566 MachineOperand &O = ri.getOperand();
Evan Cheng419852c2008-04-03 16:39:43 +00001567 MachineInstr *MI = &*ri;
1568 ++ri;
Evan Cheng4cce6b42008-04-11 17:53:36 +00001569 if (O.isDef()) {
1570 assert(MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF &&
1571 "Register def was not rewritten?");
1572 RemoveMachineInstrFromMaps(MI);
1573 vrm.RemoveMachineInstrFromMaps(MI);
1574 MI->eraseFromParent();
1575 } else {
1576 // This must be an use of an implicit_def so it's not part of the live
1577 // interval. Create a new empty live interval for it.
1578 // FIXME: Can we simply erase some of the instructions? e.g. Stores?
1579 unsigned NewVReg = mri_->createVirtualRegister(rc);
1580 vrm.grow();
1581 vrm.setIsImplicitlyDefined(NewVReg);
1582 NewLIs.push_back(&getOrCreateInterval(NewVReg));
1583 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1584 MachineOperand &MO = MI->getOperand(i);
1585 if (MO.isReg() && MO.getReg() == li.reg)
1586 MO.setReg(NewVReg);
1587 }
1588 }
Evan Cheng419852c2008-04-03 16:39:43 +00001589 }
1590}
1591
Evan Cheng81a03822007-11-17 00:40:40 +00001592
Evan Chengf2fbca62007-11-12 06:35:08 +00001593std::vector<LiveInterval*> LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001594addIntervalsForSpills(const LiveInterval &li,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001595 const MachineLoopInfo *loopInfo, VirtRegMap &vrm,
1596 float &SSWeight) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001597 assert(li.weight != HUGE_VALF &&
1598 "attempt to spill already spilled interval!");
1599
1600 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001601 li.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001602 DOUT << '\n';
1603
Evan Cheng9c3c2212008-06-06 07:54:39 +00001604 // Spill slot weight.
1605 SSWeight = 0.0f;
1606
Evan Cheng81a03822007-11-17 00:40:40 +00001607 // Each bit specify whether it a spill is required in the MBB.
1608 BitVector SpillMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001609 std::map<unsigned, std::vector<SRInfo> > SpillIdxes;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001610 BitVector RestoreMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001611 std::map<unsigned, std::vector<SRInfo> > RestoreIdxes;
1612 std::map<unsigned,unsigned> MBBVRegsMap;
Evan Chengf2fbca62007-11-12 06:35:08 +00001613 std::vector<LiveInterval*> NewLIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001614 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
Evan Chengf2fbca62007-11-12 06:35:08 +00001615
1616 unsigned NumValNums = li.getNumValNums();
1617 SmallVector<MachineInstr*, 4> ReMatDefs;
1618 ReMatDefs.resize(NumValNums, NULL);
1619 SmallVector<MachineInstr*, 4> ReMatOrigDefs;
1620 ReMatOrigDefs.resize(NumValNums, NULL);
1621 SmallVector<int, 4> ReMatIds;
1622 ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
1623 BitVector ReMatDelete(NumValNums);
1624 unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
1625
Evan Cheng81a03822007-11-17 00:40:40 +00001626 // Spilling a split live interval. It cannot be split any further. Also,
1627 // it's also guaranteed to be a single val# / range interval.
1628 if (vrm.getPreSplitReg(li.reg)) {
1629 vrm.setIsSplitFromReg(li.reg, 0);
Evan Chengd120ffd2007-12-05 10:24:35 +00001630 // Unset the split kill marker on the last use.
1631 unsigned KillIdx = vrm.getKillPoint(li.reg);
1632 if (KillIdx) {
1633 MachineInstr *KillMI = getInstructionFromIndex(KillIdx);
1634 assert(KillMI && "Last use disappeared?");
1635 int KillOp = KillMI->findRegisterUseOperandIdx(li.reg, true);
1636 assert(KillOp != -1 && "Last use disappeared?");
Chris Lattnerf7382302007-12-30 21:56:09 +00001637 KillMI->getOperand(KillOp).setIsKill(false);
Evan Chengd120ffd2007-12-05 10:24:35 +00001638 }
Evan Chengadf85902007-12-05 09:51:10 +00001639 vrm.removeKillPoint(li.reg);
Evan Cheng81a03822007-11-17 00:40:40 +00001640 bool DefIsReMat = vrm.isReMaterialized(li.reg);
1641 Slot = vrm.getStackSlot(li.reg);
1642 assert(Slot != VirtRegMap::MAX_STACK_SLOT);
1643 MachineInstr *ReMatDefMI = DefIsReMat ?
1644 vrm.getReMaterializedMI(li.reg) : NULL;
1645 int LdSlot = 0;
1646 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1647 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001648 (DefIsReMat && (ReMatDefMI->getDesc().isSimpleLoad()));
Evan Cheng81a03822007-11-17 00:40:40 +00001649 bool IsFirstRange = true;
1650 for (LiveInterval::Ranges::const_iterator
1651 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1652 // If this is a split live interval with multiple ranges, it means there
1653 // are two-address instructions that re-defined the value. Only the
1654 // first def can be rematerialized!
1655 if (IsFirstRange) {
Evan Chengcb3c3302007-11-29 23:02:50 +00001656 // Note ReMatOrigDefMI has already been deleted.
Evan Cheng81a03822007-11-17 00:40:40 +00001657 rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
1658 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001659 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001660 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001661 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001662 } else {
1663 rewriteInstructionsForSpills(li, false, I, NULL, 0,
1664 Slot, 0, false, false, false,
Evan Chengd70dbb52008-02-22 09:24:50 +00001665 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001666 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001667 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001668 }
1669 IsFirstRange = false;
1670 }
Evan Cheng419852c2008-04-03 16:39:43 +00001671
Evan Cheng9c3c2212008-06-06 07:54:39 +00001672 SSWeight = 0.0f; // Already accounted for when split.
Evan Cheng4cce6b42008-04-11 17:53:36 +00001673 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001674 return NewLIs;
1675 }
1676
1677 bool TrySplit = SplitAtBB && !intervalIsInOneMBB(li);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001678 if (SplitLimit != -1 && (int)numSplits >= SplitLimit)
1679 TrySplit = false;
1680 if (TrySplit)
1681 ++numSplits;
Evan Chengf2fbca62007-11-12 06:35:08 +00001682 bool NeedStackSlot = false;
1683 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1684 i != e; ++i) {
1685 const VNInfo *VNI = *i;
1686 unsigned VN = VNI->id;
1687 unsigned DefIdx = VNI->def;
1688 if (DefIdx == ~1U)
1689 continue; // Dead val#.
1690 // Is the def for the val# rematerializable?
Evan Cheng81a03822007-11-17 00:40:40 +00001691 MachineInstr *ReMatDefMI = (DefIdx == ~0u)
1692 ? 0 : getInstructionFromIndex(DefIdx);
Evan Cheng5ef3a042007-12-06 00:01:56 +00001693 bool dummy;
1694 if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, dummy)) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001695 // Remember how to remat the def of this val#.
Evan Cheng81a03822007-11-17 00:40:40 +00001696 ReMatOrigDefs[VN] = ReMatDefMI;
Dan Gohman2c3f7ae2008-07-17 23:49:46 +00001697 // Original def may be modified so we have to make a copy here.
Evan Cheng1ed99222008-07-19 00:37:25 +00001698 MachineInstr *Clone = mf_->CloneMachineInstr(ReMatDefMI);
1699 ClonedMIs.push_back(Clone);
1700 ReMatDefs[VN] = Clone;
Evan Chengf2fbca62007-11-12 06:35:08 +00001701
1702 bool CanDelete = true;
Evan Chengc3fc7d92007-11-29 09:49:23 +00001703 if (VNI->hasPHIKill) {
1704 // A kill is a phi node, not all of its uses can be rematerialized.
Evan Chengf2fbca62007-11-12 06:35:08 +00001705 // It must not be deleted.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001706 CanDelete = false;
1707 // Need a stack slot if there is any live range where uses cannot be
1708 // rematerialized.
1709 NeedStackSlot = true;
Evan Chengf2fbca62007-11-12 06:35:08 +00001710 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001711 if (CanDelete)
1712 ReMatDelete.set(VN);
1713 } else {
1714 // Need a stack slot if there is any live range where uses cannot be
1715 // rematerialized.
1716 NeedStackSlot = true;
1717 }
1718 }
1719
1720 // One stack slot per live interval.
Evan Cheng81a03822007-11-17 00:40:40 +00001721 if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0)
Evan Chengf2fbca62007-11-12 06:35:08 +00001722 Slot = vrm.assignVirt2StackSlot(li.reg);
1723
1724 // Create new intervals and rewrite defs and uses.
1725 for (LiveInterval::Ranges::const_iterator
1726 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Evan Cheng81a03822007-11-17 00:40:40 +00001727 MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id];
1728 MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id];
1729 bool DefIsReMat = ReMatDefMI != NULL;
Evan Chengf2fbca62007-11-12 06:35:08 +00001730 bool CanDelete = ReMatDelete[I->valno->id];
1731 int LdSlot = 0;
Evan Cheng81a03822007-11-17 00:40:40 +00001732 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001733 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001734 (DefIsReMat && ReMatDefMI->getDesc().isSimpleLoad());
Evan Cheng81a03822007-11-17 00:40:40 +00001735 rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001736 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001737 CanDelete, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001738 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001739 MBBVRegsMap, NewLIs, SSWeight);
Evan Chengf2fbca62007-11-12 06:35:08 +00001740 }
1741
Evan Cheng0cbb1162007-11-29 01:06:25 +00001742 // Insert spills / restores if we are splitting.
Evan Cheng419852c2008-04-03 16:39:43 +00001743 if (!TrySplit) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001744 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001745 return NewLIs;
Evan Cheng419852c2008-04-03 16:39:43 +00001746 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001747
Evan Chengb50bb8c2007-12-05 08:16:32 +00001748 SmallPtrSet<LiveInterval*, 4> AddedKill;
Evan Chengaee4af62007-12-02 08:30:39 +00001749 SmallVector<unsigned, 2> Ops;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001750 if (NeedStackSlot) {
1751 int Id = SpillMBBs.find_first();
1752 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001753 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1754 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001755 std::vector<SRInfo> &spills = SpillIdxes[Id];
1756 for (unsigned i = 0, e = spills.size(); i != e; ++i) {
1757 int index = spills[i].index;
1758 unsigned VReg = spills[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001759 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001760 bool isReMat = vrm.isReMaterialized(VReg);
1761 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001762 bool CanFold = false;
1763 bool FoundUse = false;
1764 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001765 if (spills[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001766 CanFold = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001767 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1768 MachineOperand &MO = MI->getOperand(j);
1769 if (!MO.isRegister() || MO.getReg() != VReg)
1770 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001771
1772 Ops.push_back(j);
1773 if (MO.isDef())
Evan Chengcddbb832007-11-30 21:23:43 +00001774 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001775 if (isReMat ||
1776 (!FoundUse && !alsoFoldARestore(Id, index, VReg,
1777 RestoreMBBs, RestoreIdxes))) {
1778 // MI has two-address uses of the same register. If the use
1779 // isn't the first and only use in the BB, then we can't fold
1780 // it. FIXME: Move this to rewriteInstructionsForSpills.
1781 CanFold = false;
Evan Chengcddbb832007-11-30 21:23:43 +00001782 break;
1783 }
Evan Chengaee4af62007-12-02 08:30:39 +00001784 FoundUse = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001785 }
1786 }
1787 // Fold the store into the def if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001788 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001789 if (CanFold && !Ops.empty()) {
1790 if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
Evan Chengcddbb832007-11-30 21:23:43 +00001791 Folded = true;
Evan Chengf38d14f2007-12-05 09:05:34 +00001792 if (FoundUse > 0) {
Evan Chengaee4af62007-12-02 08:30:39 +00001793 // Also folded uses, do not issue a load.
1794 eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
Evan Chengf38d14f2007-12-05 09:05:34 +00001795 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
1796 }
Evan Cheng597d10d2007-12-04 00:32:23 +00001797 nI.removeRange(getDefIndex(index), getStoreIndex(index));
Evan Chengcddbb832007-11-30 21:23:43 +00001798 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001799 }
1800
Evan Cheng7e073ba2008-04-09 20:57:25 +00001801 // Otherwise tell the spiller to issue a spill.
Evan Chengb50bb8c2007-12-05 08:16:32 +00001802 if (!Folded) {
1803 LiveRange *LR = &nI.ranges[nI.ranges.size()-1];
1804 bool isKill = LR->end == getStoreIndex(index);
Evan Chengb0a6f622008-05-20 08:10:37 +00001805 if (!MI->registerDefIsDead(nI.reg))
1806 // No need to spill a dead def.
1807 vrm.addSpillPoint(VReg, isKill, MI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001808 if (isKill)
1809 AddedKill.insert(&nI);
1810 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001811
1812 // Update spill slot weight.
1813 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00001814 SSWeight += getSpillWeight(true, false, loopDepth);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001815 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001816 Id = SpillMBBs.find_next(Id);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001817 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001818 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001819
Evan Cheng1953d0c2007-11-29 10:12:14 +00001820 int Id = RestoreMBBs.find_first();
1821 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001822 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1823 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
1824
Evan Cheng1953d0c2007-11-29 10:12:14 +00001825 std::vector<SRInfo> &restores = RestoreIdxes[Id];
1826 for (unsigned i = 0, e = restores.size(); i != e; ++i) {
1827 int index = restores[i].index;
1828 if (index == -1)
1829 continue;
1830 unsigned VReg = restores[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001831 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001832 bool isReMat = vrm.isReMaterialized(VReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001833 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001834 bool CanFold = false;
1835 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001836 if (restores[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001837 CanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001838 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1839 MachineOperand &MO = MI->getOperand(j);
1840 if (!MO.isRegister() || MO.getReg() != VReg)
1841 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001842
Evan Cheng0cbb1162007-11-29 01:06:25 +00001843 if (MO.isDef()) {
Evan Chengaee4af62007-12-02 08:30:39 +00001844 // If this restore were to be folded, it would have been folded
1845 // already.
1846 CanFold = false;
Evan Cheng81a03822007-11-17 00:40:40 +00001847 break;
1848 }
Evan Chengaee4af62007-12-02 08:30:39 +00001849 Ops.push_back(j);
Evan Cheng81a03822007-11-17 00:40:40 +00001850 }
1851 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001852
1853 // Fold the load into the use if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001854 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001855 if (CanFold && !Ops.empty()) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001856 if (!isReMat)
Evan Chengaee4af62007-12-02 08:30:39 +00001857 Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg);
1858 else {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001859 MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg);
1860 int LdSlot = 0;
1861 bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1862 // If the rematerializable def is a load, also try to fold it.
Chris Lattner749c6f62008-01-07 07:27:27 +00001863 if (isLoadSS || ReMatDefMI->getDesc().isSimpleLoad())
Evan Chengaee4af62007-12-02 08:30:39 +00001864 Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1865 Ops, isLoadSS, LdSlot, VReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001866 unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI);
1867 if (ImpUse) {
1868 // Re-matting an instruction with virtual register use. Add the
1869 // register as an implicit use on the use MI and update the register
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001870 // interval's spill weight to HUGE_VALF to prevent it from being
1871 // spilled.
Evan Chengd70dbb52008-02-22 09:24:50 +00001872 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001873 ImpLi.weight = HUGE_VALF;
Evan Chengd70dbb52008-02-22 09:24:50 +00001874 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1875 }
Evan Chengaee4af62007-12-02 08:30:39 +00001876 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001877 }
1878 // If folding is not possible / failed, then tell the spiller to issue a
1879 // load / rematerialization for us.
Evan Cheng597d10d2007-12-04 00:32:23 +00001880 if (Folded)
1881 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001882 else
Evan Cheng0cbb1162007-11-29 01:06:25 +00001883 vrm.addRestorePoint(VReg, MI);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001884
1885 // Update spill slot weight.
1886 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00001887 SSWeight += getSpillWeight(false, true, loopDepth);
Evan Cheng81a03822007-11-17 00:40:40 +00001888 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001889 Id = RestoreMBBs.find_next(Id);
Evan Cheng81a03822007-11-17 00:40:40 +00001890 }
1891
Evan Chengb50bb8c2007-12-05 08:16:32 +00001892 // Finalize intervals: add kills, finalize spill weights, and filter out
1893 // dead intervals.
Evan Cheng597d10d2007-12-04 00:32:23 +00001894 std::vector<LiveInterval*> RetNewLIs;
1895 for (unsigned i = 0, e = NewLIs.size(); i != e; ++i) {
1896 LiveInterval *LI = NewLIs[i];
1897 if (!LI->empty()) {
Owen Anderson496bac52008-07-23 19:47:27 +00001898 LI->weight /= InstrSlots::NUM * getApproximateInstructionCount(*LI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001899 if (!AddedKill.count(LI)) {
1900 LiveRange *LR = &LI->ranges[LI->ranges.size()-1];
Evan Chengd120ffd2007-12-05 10:24:35 +00001901 unsigned LastUseIdx = getBaseIndex(LR->end);
1902 MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx);
Evan Cheng6130f662008-03-05 00:59:57 +00001903 int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg, false);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001904 assert(UseIdx != -1);
Evan Chengd70dbb52008-02-22 09:24:50 +00001905 if (LastUse->getOperand(UseIdx).isImplicit() ||
1906 LastUse->getDesc().getOperandConstraint(UseIdx,TOI::TIED_TO) == -1){
Evan Chengb50bb8c2007-12-05 08:16:32 +00001907 LastUse->getOperand(UseIdx).setIsKill();
Evan Chengd120ffd2007-12-05 10:24:35 +00001908 vrm.addKillPoint(LI->reg, LastUseIdx);
Evan Chengadf85902007-12-05 09:51:10 +00001909 }
Evan Chengb50bb8c2007-12-05 08:16:32 +00001910 }
Evan Cheng597d10d2007-12-04 00:32:23 +00001911 RetNewLIs.push_back(LI);
1912 }
1913 }
Evan Cheng81a03822007-11-17 00:40:40 +00001914
Evan Cheng4cce6b42008-04-11 17:53:36 +00001915 handleSpilledImpDefs(li, vrm, rc, RetNewLIs);
Evan Cheng597d10d2007-12-04 00:32:23 +00001916 return RetNewLIs;
Evan Chengf2fbca62007-11-12 06:35:08 +00001917}
Evan Cheng676dd7c2008-03-11 07:19:34 +00001918
1919/// hasAllocatableSuperReg - Return true if the specified physical register has
1920/// any super register that's allocatable.
1921bool LiveIntervals::hasAllocatableSuperReg(unsigned Reg) const {
1922 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS)
1923 if (allocatableRegs_[*AS] && hasInterval(*AS))
1924 return true;
1925 return false;
1926}
1927
1928/// getRepresentativeReg - Find the largest super register of the specified
1929/// physical register.
1930unsigned LiveIntervals::getRepresentativeReg(unsigned Reg) const {
1931 // Find the largest super-register that is allocatable.
1932 unsigned BestReg = Reg;
1933 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS) {
1934 unsigned SuperReg = *AS;
1935 if (!hasAllocatableSuperReg(SuperReg) && hasInterval(SuperReg)) {
1936 BestReg = SuperReg;
1937 break;
1938 }
1939 }
1940 return BestReg;
1941}
1942
1943/// getNumConflictsWithPhysReg - Return the number of uses and defs of the
1944/// specified interval that conflicts with the specified physical register.
1945unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li,
1946 unsigned PhysReg) const {
1947 unsigned NumConflicts = 0;
1948 const LiveInterval &pli = getInterval(getRepresentativeReg(PhysReg));
1949 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
1950 E = mri_->reg_end(); I != E; ++I) {
1951 MachineOperand &O = I.getOperand();
1952 MachineInstr *MI = O.getParent();
1953 unsigned Index = getInstructionIndex(MI);
1954 if (pli.liveAt(Index))
1955 ++NumConflicts;
1956 }
1957 return NumConflicts;
1958}
1959
1960/// spillPhysRegAroundRegDefsUses - Spill the specified physical register
1961/// around all defs and uses of the specified interval.
1962void LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
1963 unsigned PhysReg, VirtRegMap &vrm) {
1964 unsigned SpillReg = getRepresentativeReg(PhysReg);
1965
1966 for (const unsigned *AS = tri_->getAliasSet(PhysReg); *AS; ++AS)
1967 // If there are registers which alias PhysReg, but which are not a
1968 // sub-register of the chosen representative super register. Assert
1969 // since we can't handle it yet.
1970 assert(*AS == SpillReg || !allocatableRegs_[*AS] ||
1971 tri_->isSuperRegister(*AS, SpillReg));
1972
1973 LiveInterval &pli = getInterval(SpillReg);
1974 SmallPtrSet<MachineInstr*, 8> SeenMIs;
1975 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
1976 E = mri_->reg_end(); I != E; ++I) {
1977 MachineOperand &O = I.getOperand();
1978 MachineInstr *MI = O.getParent();
1979 if (SeenMIs.count(MI))
1980 continue;
1981 SeenMIs.insert(MI);
1982 unsigned Index = getInstructionIndex(MI);
1983 if (pli.liveAt(Index)) {
1984 vrm.addEmergencySpill(SpillReg, MI);
1985 pli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
1986 for (const unsigned* AS = tri_->getSubRegisters(SpillReg); *AS; ++AS) {
1987 if (!hasInterval(*AS))
1988 continue;
1989 LiveInterval &spli = getInterval(*AS);
1990 if (spli.liveAt(Index))
1991 spli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
1992 }
1993 }
1994 }
1995}
Owen Andersonc4dc1322008-06-05 17:15:43 +00001996
1997LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
1998 MachineInstr* startInst) {
1999 LiveInterval& Interval = getOrCreateInterval(reg);
2000 VNInfo* VN = Interval.getNextValue(
2001 getInstructionIndex(startInst) + InstrSlots::DEF,
2002 startInst, getVNInfoAllocator());
2003 VN->hasPHIKill = true;
2004 VN->kills.push_back(getMBBEndIdx(startInst->getParent()));
2005 LiveRange LR(getInstructionIndex(startInst) + InstrSlots::DEF,
2006 getMBBEndIdx(startInst->getParent()) + 1, VN);
2007 Interval.addRange(LR);
2008
2009 return LR;
2010}