blob: adc1e207b50ca137a704e117ec869e586b0283a1 [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
Chris Lattnercd3245a2006-12-19 22:41:21 +000050STATISTIC(numIntervals, "Number of original intervals");
51STATISTIC(numIntervalsAfter, "Number of intervals after coalescing");
Evan Cheng0cbb1162007-11-29 01:06:25 +000052STATISTIC(numFolds , "Number of loads/stores folded into instructions");
53STATISTIC(numSplits , "Number of intervals split");
Chris Lattnercd3245a2006-12-19 22:41:21 +000054
Devang Patel19974732007-05-03 01:11:54 +000055char LiveIntervals::ID = 0;
Dan Gohman844731a2008-05-13 00:00:25 +000056static RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000057
Chris Lattnerf7da2c72006-08-24 22:43:55 +000058void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman6d69ba82008-07-25 00:02:30 +000059 AU.addRequired<AliasAnalysis>();
60 AU.addPreserved<AliasAnalysis>();
David Greene25133302007-06-08 17:18:56 +000061 AU.addPreserved<LiveVariables>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000062 AU.addRequired<LiveVariables>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000063 AU.addPreservedID(MachineLoopInfoID);
64 AU.addPreservedID(MachineDominatorsID);
Owen Andersonfcc63502008-05-29 18:35:21 +000065 AU.addPreservedID(PHIEliminationID);
66 AU.addRequiredID(PHIEliminationID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000067 AU.addRequiredID(TwoAddressInstructionPassID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000068 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000069}
70
Chris Lattnerf7da2c72006-08-24 22:43:55 +000071void LiveIntervals::releaseMemory() {
Evan Cheng3f32d652008-06-04 09:18:41 +000072 MBB2IdxMap.clear();
Evan Cheng4ca980e2007-10-17 02:10:22 +000073 Idx2MBBMap.clear();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000074 mi2iMap_.clear();
75 i2miMap_.clear();
76 r2iMap_.clear();
Evan Chengdd199d22007-09-06 01:07:24 +000077 // Release VNInfo memroy regions after all VNInfo objects are dtor'd.
78 VNInfoAllocator.Reset();
Evan Cheng1ed99222008-07-19 00:37:25 +000079 while (!ClonedMIs.empty()) {
80 MachineInstr *MI = ClonedMIs.back();
81 ClonedMIs.pop_back();
82 mf_->DeleteMachineInstr(MI);
83 }
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000084}
85
Owen Anderson80b3ce62008-05-28 20:54:50 +000086void LiveIntervals::computeNumbering() {
87 Index2MiMap OldI2MI = i2miMap_;
Owen Anderson7fbad272008-07-23 21:37:49 +000088 std::vector<IdxMBBPair> OldI2MBB = Idx2MBBMap;
Owen Anderson80b3ce62008-05-28 20:54:50 +000089
90 Idx2MBBMap.clear();
91 MBB2IdxMap.clear();
92 mi2iMap_.clear();
93 i2miMap_.clear();
94
Owen Andersona1566f22008-07-22 22:46:49 +000095 FunctionSize = 0;
96
Chris Lattner428b92e2006-09-15 03:57:23 +000097 // Number MachineInstrs and MachineBasicBlocks.
98 // Initialize MBB indexes to a sentinal.
Evan Cheng549f27d32007-08-13 23:45:17 +000099 MBB2IdxMap.resize(mf_->getNumBlockIDs(), std::make_pair(~0U,~0U));
Chris Lattner428b92e2006-09-15 03:57:23 +0000100
101 unsigned MIIndex = 0;
102 for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
103 MBB != E; ++MBB) {
Evan Cheng549f27d32007-08-13 23:45:17 +0000104 unsigned StartIdx = MIIndex;
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000105
Owen Anderson7fbad272008-07-23 21:37:49 +0000106 // Insert an empty slot at the beginning of each block.
107 MIIndex += InstrSlots::NUM;
108 i2miMap_.push_back(0);
109
Chris Lattner428b92e2006-09-15 03:57:23 +0000110 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
111 I != E; ++I) {
112 bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000113 assert(inserted && "multiple MachineInstr -> index mappings");
Chris Lattner428b92e2006-09-15 03:57:23 +0000114 i2miMap_.push_back(I);
115 MIIndex += InstrSlots::NUM;
Owen Andersona1566f22008-07-22 22:46:49 +0000116 FunctionSize++;
Owen Anderson7fbad272008-07-23 21:37:49 +0000117
118 // Insert an empty slot after every instruction.
Owen Anderson1fbb4542008-06-16 16:58:24 +0000119 MIIndex += InstrSlots::NUM;
120 i2miMap_.push_back(0);
Owen Anderson35578012008-06-16 07:10:49 +0000121 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000122
Owen Anderson1fbb4542008-06-16 16:58:24 +0000123 // Set the MBB2IdxMap entry for this MBB.
124 MBB2IdxMap[MBB->getNumber()] = std::make_pair(StartIdx, MIIndex - 1);
125 Idx2MBBMap.push_back(std::make_pair(StartIdx, MBB));
Chris Lattner428b92e2006-09-15 03:57:23 +0000126 }
Evan Cheng4ca980e2007-10-17 02:10:22 +0000127 std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
Owen Anderson80b3ce62008-05-28 20:54:50 +0000128
129 if (!OldI2MI.empty())
Owen Anderson7fbad272008-07-23 21:37:49 +0000130 for (iterator OI = begin(), OE = end(); OI != OE; ++OI)
131 for (LiveInterval::iterator LI = OI->second.begin(),
132 LE = OI->second.end(); LI != LE; ++LI) {
Owen Anderson4b5b2092008-05-29 18:15:49 +0000133
Owen Anderson7eec0c22008-05-29 23:01:22 +0000134 // Remap the start index of the live range to the corresponding new
135 // number, or our best guess at what it _should_ correspond to if the
136 // original instruction has been erased. This is either the following
137 // instruction or its predecessor.
Owen Anderson7fbad272008-07-23 21:37:49 +0000138 unsigned index = LI->start / InstrSlots::NUM;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000139 unsigned offset = LI->start % InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000140 if (offset == InstrSlots::LOAD) {
141 std::vector<IdxMBBPair>::const_iterator I =
142 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), index);
143 // Take the pair containing the index
144 std::vector<IdxMBBPair>::const_iterator J =
145 ((I != OldI2MBB.end() && I->first > index) ||
146 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000147
Owen Anderson7fbad272008-07-23 21:37:49 +0000148 LI->start = getMBBStartIdx(J->second);
149 } else {
150 LI->start = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000151 }
152
153 // Remap the ending index in the same way that we remapped the start,
154 // except for the final step where we always map to the immediately
155 // following instruction.
Owen Anderson7fbad272008-07-23 21:37:49 +0000156 index = LI->end / InstrSlots::NUM;
157 offset = LI->end % InstrSlots::NUM;
158 if (offset == InstrSlots::STORE) {
159 std::vector<IdxMBBPair>::const_iterator I =
160 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), index);
161 // Take the pair containing the index
162 std::vector<IdxMBBPair>::const_iterator J =
163 ((I != OldI2MBB.end() && I->first > index) ||
164 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
165
166 LI->end = getMBBEndIdx(J->second) + 1;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000167 } else {
Owen Anderson7fbad272008-07-23 21:37:49 +0000168 LI->end = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000169 }
Owen Anderson745825f42008-05-28 22:40:08 +0000170
Owen Anderson7eec0c22008-05-29 23:01:22 +0000171 // Remap the VNInfo def index, which works the same as the
172 // start indices above.
Owen Anderson745825f42008-05-28 22:40:08 +0000173 VNInfo* vni = LI->valno;
Owen Anderson7fbad272008-07-23 21:37:49 +0000174 index = vni->def / InstrSlots::NUM;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000175 offset = vni->def % InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000176 if (offset == InstrSlots::LOAD) {
177 std::vector<IdxMBBPair>::const_iterator I =
178 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), index);
179 // Take the pair containing the index
180 std::vector<IdxMBBPair>::const_iterator J =
181 ((I != OldI2MBB.end() && I->first > index) ||
182 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000183
Owen Anderson7fbad272008-07-23 21:37:49 +0000184 vni->def = getMBBStartIdx(J->second);
185
186 } else {
187 vni->def = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000188 }
Owen Anderson745825f42008-05-28 22:40:08 +0000189
Owen Anderson7eec0c22008-05-29 23:01:22 +0000190 // Remap the VNInfo kill indices, which works the same as
191 // the end indices above.
Owen Anderson4b5b2092008-05-29 18:15:49 +0000192 for (size_t i = 0; i < vni->kills.size(); ++i) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000193 index = vni->kills[i] / InstrSlots::NUM;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000194 offset = vni->kills[i] % InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000195 if (OldI2MI[vni->kills[i] / InstrSlots::NUM]) {
196 std::vector<IdxMBBPair>::const_iterator I =
197 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), index);
198 // Take the pair containing the index
199 std::vector<IdxMBBPair>::const_iterator J =
200 ((I != OldI2MBB.end() && I->first > index) ||
201 (I == OldI2MBB.end() && OldI2MBB.size()>0)) ? (I-1): I;
202
203 vni->kills[i] = getMBBEndIdx(J->second) + 1;
204 } else {
205 vni->kills[i] = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000206 }
Owen Anderson4b5b2092008-05-29 18:15:49 +0000207 }
Owen Anderson80b3ce62008-05-28 20:54:50 +0000208 }
209}
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000210
Owen Anderson80b3ce62008-05-28 20:54:50 +0000211/// runOnMachineFunction - Register allocate the whole function
212///
213bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
214 mf_ = &fn;
215 mri_ = &mf_->getRegInfo();
216 tm_ = &fn.getTarget();
217 tri_ = tm_->getRegisterInfo();
218 tii_ = tm_->getInstrInfo();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000219 aa_ = &getAnalysis<AliasAnalysis>();
Owen Anderson80b3ce62008-05-28 20:54:50 +0000220 lv_ = &getAnalysis<LiveVariables>();
221 allocatableRegs_ = tri_->getAllocatableSet(fn);
222
223 computeNumbering();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000224 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000225
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000226 numIntervals += getNumIntervals();
227
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000228 DOUT << "********** INTERVALS **********\n";
229 for (iterator I = begin(), E = end(); I != E; ++I) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000230 I->second.print(DOUT, tri_);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000231 DOUT << "\n";
232 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000233
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000234 numIntervalsAfter += getNumIntervals();
Chris Lattner70ca3582004-09-30 15:59:17 +0000235 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000236 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000237}
238
Chris Lattner70ca3582004-09-30 15:59:17 +0000239/// print - Implement the dump method.
Reid Spencerce9653c2004-12-07 04:03:45 +0000240void LiveIntervals::print(std::ostream &O, const Module* ) const {
Chris Lattner70ca3582004-09-30 15:59:17 +0000241 O << "********** INTERVALS **********\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000242 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Evan Cheng3f32d652008-06-04 09:18:41 +0000243 I->second.print(O, tri_);
244 O << "\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000245 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000246
247 O << "********** MACHINEINSTRS **********\n";
248 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
249 mbbi != mbbe; ++mbbi) {
250 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
251 for (MachineBasicBlock::iterator mii = mbbi->begin(),
252 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner477e4552004-09-30 16:10:45 +0000253 O << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner70ca3582004-09-30 15:59:17 +0000254 }
255 }
256}
257
Evan Chengc92da382007-11-03 07:20:12 +0000258/// conflictsWithPhysRegDef - Returns true if the specified register
259/// is defined during the duration of the specified interval.
260bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
261 VirtRegMap &vrm, unsigned reg) {
262 for (LiveInterval::Ranges::const_iterator
263 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
264 for (unsigned index = getBaseIndex(I->start),
265 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
266 index += InstrSlots::NUM) {
267 // skip deleted instructions
268 while (index != end && !getInstructionFromIndex(index))
269 index += InstrSlots::NUM;
270 if (index == end) break;
271
272 MachineInstr *MI = getInstructionFromIndex(index);
Evan Cheng5d446262007-11-15 08:13:29 +0000273 unsigned SrcReg, DstReg;
274 if (tii_->isMoveInstr(*MI, SrcReg, DstReg))
275 if (SrcReg == li.reg || DstReg == li.reg)
276 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000277 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
278 MachineOperand& mop = MI->getOperand(i);
Evan Cheng5d446262007-11-15 08:13:29 +0000279 if (!mop.isRegister())
Evan Chengc92da382007-11-03 07:20:12 +0000280 continue;
281 unsigned PhysReg = mop.getReg();
Evan Cheng5d446262007-11-15 08:13:29 +0000282 if (PhysReg == 0 || PhysReg == li.reg)
Evan Chengc92da382007-11-03 07:20:12 +0000283 continue;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000284 if (TargetRegisterInfo::isVirtualRegister(PhysReg)) {
Evan Cheng5d446262007-11-15 08:13:29 +0000285 if (!vrm.hasPhys(PhysReg))
286 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000287 PhysReg = vrm.getPhys(PhysReg);
Evan Cheng5d446262007-11-15 08:13:29 +0000288 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000289 if (PhysReg && tri_->regsOverlap(PhysReg, reg))
Evan Chengc92da382007-11-03 07:20:12 +0000290 return true;
291 }
292 }
293 }
294
295 return false;
296}
297
Evan Cheng549f27d32007-08-13 23:45:17 +0000298void LiveIntervals::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000299 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000300 cerr << tri_->getName(reg);
Evan Cheng549f27d32007-08-13 23:45:17 +0000301 else
302 cerr << "%reg" << reg;
303}
304
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000305void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000306 MachineBasicBlock::iterator mi,
Owen Anderson6b098de2008-06-25 23:39:39 +0000307 unsigned MIIdx, MachineOperand& MO,
Evan Chengef0732d2008-07-10 07:35:43 +0000308 unsigned MOIdx,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000309 LiveInterval &interval) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000310 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000311 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000312
Evan Cheng419852c2008-04-03 16:39:43 +0000313 if (mi->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
314 DOUT << "is a implicit_def\n";
315 return;
316 }
317
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000318 // Virtual registers may be defined multiple times (due to phi
319 // elimination and 2-addr elimination). Much of what we do only has to be
320 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000321 // time we see a vreg.
322 if (interval.empty()) {
323 // Get the Idx of the defining instructions.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000324 unsigned defIndex = getDefIndex(MIIdx);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000325 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000326 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000327 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000328 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000329 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000330 tii_->isMoveInstr(*mi, SrcReg, DstReg))
331 CopyMI = mi;
332 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000333
334 assert(ValNo->id == 0 && "First value in interval is not 0?");
Chris Lattner7ac2d312004-07-24 02:59:07 +0000335
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000336 // Loop over all of the blocks that the vreg is defined in. There are
337 // two cases we have to handle here. The most common case is a vreg
338 // whose lifetime is contained within a basic block. In this case there
339 // will be a single kill, in MBB, which comes after the definition.
340 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
341 // FIXME: what about dead vars?
342 unsigned killIdx;
343 if (vi.Kills[0] != mi)
344 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
345 else
346 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000347
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000348 // If the kill happens after the definition, we have an intra-block
349 // live range.
350 if (killIdx > defIndex) {
Evan Cheng61de82d2007-02-15 05:59:24 +0000351 assert(vi.AliveBlocks.none() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000352 "Shouldn't be alive across any blocks!");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000353 LiveRange LR(defIndex, killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000354 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000355 DOUT << " +" << LR << "\n";
Evan Chengf3bb2e62007-09-05 21:46:51 +0000356 interval.addKill(ValNo, killIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000357 return;
358 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000359 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000360
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000361 // The other case we handle is when a virtual register lives to the end
362 // of the defining block, potentially live across some blocks, then is
363 // live into some number of blocks, but gets killed. Start by adding a
364 // range that goes from this definition to the end of the defining block.
Owen Anderson7fbad272008-07-23 21:37:49 +0000365 LiveRange NewLR(defIndex, getMBBEndIdx(mbb)+1, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000366 DOUT << " +" << NewLR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000367 interval.addRange(NewLR);
368
369 // Iterate over all of the blocks that the variable is completely
370 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
371 // live interval.
372 for (unsigned i = 0, e = vi.AliveBlocks.size(); i != e; ++i) {
373 if (vi.AliveBlocks[i]) {
Owen Anderson31ec8412008-06-16 19:32:40 +0000374 LiveRange LR(getMBBStartIdx(i),
Evan Chengf26e8552008-06-17 20:13:36 +0000375 getMBBEndIdx(i)+1, // MBB ends at -1.
Owen Anderson31ec8412008-06-16 19:32:40 +0000376 ValNo);
377 interval.addRange(LR);
378 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000379 }
380 }
381
382 // Finally, this virtual register is live from the start of any killing
383 // block to the 'use' slot of the killing instruction.
384 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
385 MachineInstr *Kill = vi.Kills[i];
Evan Cheng8df78602007-08-08 03:00:28 +0000386 unsigned killIdx = getUseIndex(getInstructionIndex(Kill))+1;
Chris Lattner428b92e2006-09-15 03:57:23 +0000387 LiveRange LR(getMBBStartIdx(Kill->getParent()),
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000388 killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000389 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000390 interval.addKill(ValNo, killIdx);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000391 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000392 }
393
394 } else {
395 // If this is the second time we see a virtual register definition, it
396 // must be due to phi elimination or two addr elimination. If this is
Evan Chengbf105c82006-11-03 03:04:46 +0000397 // the result of two address elimination, then the vreg is one of the
398 // def-and-use register operand.
Evan Chengef0732d2008-07-10 07:35:43 +0000399 if (mi->isRegReDefinedByTwoAddr(interval.reg, MOIdx)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000400 // If this is a two-address definition, then we have already processed
401 // the live range. The only problem is that we didn't realize there
402 // are actually two values in the live interval. Because of this we
403 // need to take the LiveRegion that defines this register and split it
404 // into two values.
Evan Chenga07cec92008-01-10 08:22:10 +0000405 assert(interval.containsOneValue());
406 unsigned DefIndex = getDefIndex(interval.getValNumInfo(0)->def);
Chris Lattner6b128bd2006-09-03 08:07:11 +0000407 unsigned RedefIndex = getDefIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000408
Evan Cheng4f8ff162007-08-11 00:59:19 +0000409 const LiveRange *OldLR = interval.getLiveRangeContaining(RedefIndex-1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000410 VNInfo *OldValNo = OldLR->valno;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000411
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000412 // Delete the initial value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000413 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000414 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000415
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000416 // Two-address vregs should always only be redefined once. This means
417 // that at this point, there should be exactly one value number in it.
418 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
419
Chris Lattner91725b72006-08-31 05:54:43 +0000420 // The new value number (#1) is defined by the instruction we claimed
421 // defined value #0.
Evan Chengc8d044e2008-02-15 18:24:29 +0000422 VNInfo *ValNo = interval.getNextValue(OldValNo->def, OldValNo->copy,
423 VNInfoAllocator);
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000424
Chris Lattner91725b72006-08-31 05:54:43 +0000425 // Value#0 is now defined by the 2-addr instruction.
Evan Chengc8d044e2008-02-15 18:24:29 +0000426 OldValNo->def = RedefIndex;
427 OldValNo->copy = 0;
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000428
429 // Add the new live interval which replaces the range for the input copy.
430 LiveRange LR(DefIndex, RedefIndex, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000431 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000432 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000433 interval.addKill(ValNo, RedefIndex);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000434
435 // If this redefinition is dead, we need to add a dummy unit live
436 // range covering the def slot.
Owen Anderson6b098de2008-06-25 23:39:39 +0000437 if (MO.isDead())
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000438 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, OldValNo));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000439
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000440 DOUT << " RESULT: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000441 interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000442
443 } else {
444 // Otherwise, this must be because of phi elimination. If this is the
445 // first redefinition of the vreg that we have seen, go back and change
446 // the live range in the PHI block to be a different value number.
447 if (interval.containsOneValue()) {
448 assert(vi.Kills.size() == 1 &&
449 "PHI elimination vreg should have one kill, the PHI itself!");
450
451 // Remove the old range that we now know has an incorrect number.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000452 VNInfo *VNI = interval.getValNumInfo(0);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000453 MachineInstr *Killer = vi.Kills[0];
Chris Lattner428b92e2006-09-15 03:57:23 +0000454 unsigned Start = getMBBStartIdx(Killer->getParent());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000455 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000456 DOUT << " Removing [" << Start << "," << End << "] from: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000457 interval.print(DOUT, tri_); DOUT << "\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000458 interval.removeRange(Start, End);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000459 VNI->hasPHIKill = true;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000460 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000461
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000462 // Replace the interval with one of a NEW value number. Note that this
463 // value number isn't actually defined by an instruction, weird huh? :)
Evan Chengf3bb2e62007-09-05 21:46:51 +0000464 LiveRange LR(Start, End, interval.getNextValue(~0, 0, VNInfoAllocator));
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000465 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000466 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000467 interval.addKill(LR.valno, End);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000468 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000469 }
470
471 // In the case of PHI elimination, each variable definition is only
472 // live until the end of the block. We've already taken care of the
473 // rest of the live range.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000474 unsigned defIndex = getDefIndex(MIIdx);
Chris Lattner91725b72006-08-31 05:54:43 +0000475
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000476 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000477 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000478 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000479 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000480 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000481 tii_->isMoveInstr(*mi, SrcReg, DstReg))
482 CopyMI = mi;
483 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Chris Lattner91725b72006-08-31 05:54:43 +0000484
Owen Anderson7fbad272008-07-23 21:37:49 +0000485 unsigned killIndex = getMBBEndIdx(mbb) + 1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000486 LiveRange LR(defIndex, killIndex, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000487 interval.addRange(LR);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000488 interval.addKill(ValNo, killIndex);
489 ValNo->hasPHIKill = true;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000490 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000491 }
492 }
493
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000494 DOUT << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000495}
496
Chris Lattnerf35fef72004-07-23 21:24:19 +0000497void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000498 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000499 unsigned MIIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000500 MachineOperand& MO,
Chris Lattner91725b72006-08-31 05:54:43 +0000501 LiveInterval &interval,
Evan Chengc8d044e2008-02-15 18:24:29 +0000502 MachineInstr *CopyMI) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000503 // A physical register cannot be live across basic block, so its
504 // lifetime must end somewhere in its defining basic block.
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000505 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000506
Chris Lattner6b128bd2006-09-03 08:07:11 +0000507 unsigned baseIndex = MIIdx;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000508 unsigned start = getDefIndex(baseIndex);
509 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000510
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000511 // If it is not used after definition, it is considered dead at
512 // the instruction defining it. Hence its interval is:
513 // [defSlot(def), defSlot(def)+1)
Owen Anderson6b098de2008-06-25 23:39:39 +0000514 if (MO.isDead()) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000515 DOUT << " dead";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000516 end = getDefIndex(start) + 1;
517 goto exit;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000518 }
519
520 // If it is not dead on definition, it must be killed by a
521 // subsequent instruction. Hence its interval is:
522 // [defSlot(def), useSlot(kill)+1)
Owen Anderson7fbad272008-07-23 21:37:49 +0000523 baseIndex += InstrSlots::NUM;
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000524 while (++mi != MBB->end()) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000525 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
526 getInstructionFromIndex(baseIndex) == 0)
527 baseIndex += InstrSlots::NUM;
Evan Cheng6130f662008-03-05 00:59:57 +0000528 if (mi->killsRegister(interval.reg, tri_)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000529 DOUT << " killed";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000530 end = getUseIndex(baseIndex) + 1;
531 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000532 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Cheng9a1956a2006-11-15 20:54:11 +0000533 // Another instruction redefines the register before it is ever read.
534 // Then the register is essentially dead at the instruction that defines
535 // it. Hence its interval is:
536 // [defSlot(def), defSlot(def)+1)
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000537 DOUT << " dead";
Evan Cheng9a1956a2006-11-15 20:54:11 +0000538 end = getDefIndex(start) + 1;
539 goto exit;
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000540 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000541
542 baseIndex += InstrSlots::NUM;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000543 }
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000544
545 // The only case we should have a dead physreg here without a killing or
546 // instruction where we know it's dead is if it is live-in to the function
547 // and never used.
Evan Chengc8d044e2008-02-15 18:24:29 +0000548 assert(!CopyMI && "physreg was not killed in defining block!");
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000549 end = getDefIndex(start) + 1; // It's dead.
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000550
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000551exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000552 assert(start < end && "did not find end of interval?");
Chris Lattnerf768bba2005-03-09 23:05:19 +0000553
Evan Cheng24a3cc42007-04-25 07:30:23 +0000554 // Already exists? Extend old live interval.
555 LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000556 VNInfo *ValNo = (OldLR != interval.end())
Evan Chengc8d044e2008-02-15 18:24:29 +0000557 ? OldLR->valno : interval.getNextValue(start, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000558 LiveRange LR(start, end, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000559 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000560 interval.addKill(LR.valno, end);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000561 DOUT << " +" << LR << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000562}
563
Chris Lattnerf35fef72004-07-23 21:24:19 +0000564void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
565 MachineBasicBlock::iterator MI,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000566 unsigned MIIdx,
Evan Chengef0732d2008-07-10 07:35:43 +0000567 MachineOperand& MO,
568 unsigned MOIdx) {
Owen Anderson6b098de2008-06-25 23:39:39 +0000569 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Evan Chengef0732d2008-07-10 07:35:43 +0000570 handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000571 getOrCreateInterval(MO.getReg()));
572 else if (allocatableRegs_[MO.getReg()]) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000573 MachineInstr *CopyMI = NULL;
Chris Lattner91725b72006-08-31 05:54:43 +0000574 unsigned SrcReg, DstReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000575 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000576 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Evan Chengc8d044e2008-02-15 18:24:29 +0000577 tii_->isMoveInstr(*MI, SrcReg, DstReg))
578 CopyMI = MI;
Owen Anderson6b098de2008-06-25 23:39:39 +0000579 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
580 getOrCreateInterval(MO.getReg()), CopyMI);
Evan Cheng24a3cc42007-04-25 07:30:23 +0000581 // Def of a register also defines its sub-registers.
Owen Anderson6b098de2008-06-25 23:39:39 +0000582 for (const unsigned* AS = tri_->getSubRegisters(MO.getReg()); *AS; ++AS)
Evan Cheng6130f662008-03-05 00:59:57 +0000583 // If MI also modifies the sub-register explicitly, avoid processing it
584 // more than once. Do not pass in TRI here so it checks for exact match.
585 if (!MI->modifiesRegister(*AS))
Owen Anderson6b098de2008-06-25 23:39:39 +0000586 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
587 getOrCreateInterval(*AS), 0);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000588 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000589}
590
Evan Chengb371f452007-02-19 21:49:54 +0000591void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000592 unsigned MIIdx,
Evan Cheng24a3cc42007-04-25 07:30:23 +0000593 LiveInterval &interval, bool isAlias) {
Evan Chengb371f452007-02-19 21:49:54 +0000594 DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg));
595
596 // Look for kills, if it reaches a def before it's killed, then it shouldn't
597 // be considered a livein.
598 MachineBasicBlock::iterator mi = MBB->begin();
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000599 unsigned baseIndex = MIIdx;
600 unsigned start = baseIndex;
Evan Chengb371f452007-02-19 21:49:54 +0000601 unsigned end = start;
602 while (mi != MBB->end()) {
Evan Cheng6130f662008-03-05 00:59:57 +0000603 if (mi->killsRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000604 DOUT << " killed";
605 end = getUseIndex(baseIndex) + 1;
606 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000607 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000608 // Another instruction redefines the register before it is ever read.
609 // Then the register is essentially dead at the instruction that defines
610 // it. Hence its interval is:
611 // [defSlot(def), defSlot(def)+1)
612 DOUT << " dead";
613 end = getDefIndex(start) + 1;
614 goto exit;
615 }
616
617 baseIndex += InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000618 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
619 getInstructionFromIndex(baseIndex) == 0)
620 baseIndex += InstrSlots::NUM;
Evan Chengb371f452007-02-19 21:49:54 +0000621 ++mi;
622 }
623
624exit:
Evan Cheng75611fb2007-06-27 01:16:36 +0000625 // Live-in register might not be used at all.
626 if (end == MIIdx) {
Evan Cheng292da942007-06-27 18:47:28 +0000627 if (isAlias) {
628 DOUT << " dead";
Evan Cheng75611fb2007-06-27 01:16:36 +0000629 end = getDefIndex(MIIdx) + 1;
Evan Cheng292da942007-06-27 18:47:28 +0000630 } else {
631 DOUT << " live through";
632 end = baseIndex;
633 }
Evan Cheng24a3cc42007-04-25 07:30:23 +0000634 }
635
Evan Chengf3bb2e62007-09-05 21:46:51 +0000636 LiveRange LR(start, end, interval.getNextValue(start, 0, VNInfoAllocator));
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000637 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000638 interval.addKill(LR.valno, end);
Evan Cheng24c2e5c2007-08-08 07:03:29 +0000639 DOUT << " +" << LR << '\n';
Evan Chengb371f452007-02-19 21:49:54 +0000640}
641
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000642/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000643/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000644/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000645/// which a variable is live
Chris Lattnerf7da2c72006-08-24 22:43:55 +0000646void LiveIntervals::computeIntervals() {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000647 DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
648 << "********** Function: "
649 << ((Value*)mf_->getFunction())->getName() << '\n';
Chris Lattner6b128bd2006-09-03 08:07:11 +0000650 // Track the index of the current machine instr.
651 unsigned MIIndex = 0;
Owen Anderson7fbad272008-07-23 21:37:49 +0000652
653 // Skip over empty initial indices.
654 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
655 getInstructionFromIndex(MIIndex) == 0)
656 MIIndex += InstrSlots::NUM;
657
Chris Lattner428b92e2006-09-15 03:57:23 +0000658 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
659 MBBI != E; ++MBBI) {
660 MachineBasicBlock *MBB = MBBI;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000661 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000662
Chris Lattner428b92e2006-09-15 03:57:23 +0000663 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000664
Dan Gohmancb406c22007-10-03 19:26:29 +0000665 // Create intervals for live-ins to this BB first.
666 for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
667 LE = MBB->livein_end(); LI != LE; ++LI) {
668 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
669 // Multiple live-ins can alias the same register.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000670 for (const unsigned* AS = tri_->getSubRegisters(*LI); *AS; ++AS)
Dan Gohmancb406c22007-10-03 19:26:29 +0000671 if (!hasInterval(*AS))
672 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
673 true);
Chris Lattnerdffb2e82006-09-04 18:27:40 +0000674 }
675
Chris Lattner428b92e2006-09-15 03:57:23 +0000676 for (; MI != miEnd; ++MI) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000677 DOUT << MIIndex << "\t" << *MI;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000678
Evan Cheng438f7bc2006-11-10 08:43:01 +0000679 // Handle defs.
Chris Lattner428b92e2006-09-15 03:57:23 +0000680 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
681 MachineOperand &MO = MI->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000682 // handle register defs - build intervals
Chris Lattner428b92e2006-09-15 03:57:23 +0000683 if (MO.isRegister() && MO.getReg() && MO.isDef())
Evan Chengef0732d2008-07-10 07:35:43 +0000684 handleRegisterDef(MBB, MI, MIIndex, MO, i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000685 }
Chris Lattner6b128bd2006-09-03 08:07:11 +0000686
687 MIIndex += InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000688
689 // Skip over empty indices.
690 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
691 getInstructionFromIndex(MIIndex) == 0)
692 MIIndex += InstrSlots::NUM;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000693 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000694 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000695}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000696
Evan Cheng4ca980e2007-10-17 02:10:22 +0000697bool LiveIntervals::findLiveInMBBs(const LiveRange &LR,
Evan Chenga5bfc972007-10-17 06:53:44 +0000698 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
Evan Cheng4ca980e2007-10-17 02:10:22 +0000699 std::vector<IdxMBBPair>::const_iterator I =
700 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), LR.start);
701
702 bool ResVal = false;
703 while (I != Idx2MBBMap.end()) {
704 if (LR.end <= I->first)
705 break;
706 MBBs.push_back(I->second);
707 ResVal = true;
708 ++I;
709 }
710 return ResVal;
711}
712
713
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000714LiveInterval LiveIntervals::createInterval(unsigned reg) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000715 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ?
Jim Laskey7902c752006-11-07 12:25:45 +0000716 HUGE_VALF : 0.0F;
Alkis Evlogimenosa1613db2004-07-24 11:44:15 +0000717 return LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000718}
Evan Chengf2fbca62007-11-12 06:35:08 +0000719
Evan Chengc8d044e2008-02-15 18:24:29 +0000720/// getVNInfoSourceReg - Helper function that parses the specified VNInfo
721/// copy field and returns the source register that defines it.
722unsigned LiveIntervals::getVNInfoSourceReg(const VNInfo *VNI) const {
723 if (!VNI->copy)
724 return 0;
725
726 if (VNI->copy->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG)
727 return VNI->copy->getOperand(1).getReg();
Evan Cheng7e073ba2008-04-09 20:57:25 +0000728 if (VNI->copy->getOpcode() == TargetInstrInfo::INSERT_SUBREG)
729 return VNI->copy->getOperand(2).getReg();
Evan Chengc8d044e2008-02-15 18:24:29 +0000730 unsigned SrcReg, DstReg;
731 if (tii_->isMoveInstr(*VNI->copy, SrcReg, DstReg))
732 return SrcReg;
733 assert(0 && "Unrecognized copy instruction!");
734 return 0;
735}
Evan Chengf2fbca62007-11-12 06:35:08 +0000736
737//===----------------------------------------------------------------------===//
738// Register allocator hooks.
739//
740
Evan Chengd70dbb52008-02-22 09:24:50 +0000741/// getReMatImplicitUse - If the remat definition MI has one (for now, we only
742/// allow one) virtual register operand, then its uses are implicitly using
743/// the register. Returns the virtual register.
744unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
745 MachineInstr *MI) const {
746 unsigned RegOp = 0;
747 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
748 MachineOperand &MO = MI->getOperand(i);
749 if (!MO.isRegister() || !MO.isUse())
750 continue;
751 unsigned Reg = MO.getReg();
752 if (Reg == 0 || Reg == li.reg)
753 continue;
754 // FIXME: For now, only remat MI with at most one register operand.
755 assert(!RegOp &&
756 "Can't rematerialize instruction with multiple register operand!");
757 RegOp = MO.getReg();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000758#ifndef NDEBUG
Evan Chengd70dbb52008-02-22 09:24:50 +0000759 break;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000760#endif
Evan Chengd70dbb52008-02-22 09:24:50 +0000761 }
762 return RegOp;
763}
764
765/// isValNoAvailableAt - Return true if the val# of the specified interval
766/// which reaches the given instruction also reaches the specified use index.
767bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
768 unsigned UseIdx) const {
769 unsigned Index = getInstructionIndex(MI);
770 VNInfo *ValNo = li.FindLiveRangeContaining(Index)->valno;
771 LiveInterval::const_iterator UI = li.FindLiveRangeContaining(UseIdx);
772 return UI != li.end() && UI->valno == ValNo;
773}
774
Evan Chengf2fbca62007-11-12 06:35:08 +0000775/// isReMaterializable - Returns true if the definition MI of the specified
776/// val# of the specified interval is re-materializable.
777bool LiveIntervals::isReMaterializable(const LiveInterval &li,
Evan Cheng5ef3a042007-12-06 00:01:56 +0000778 const VNInfo *ValNo, MachineInstr *MI,
779 bool &isLoad) {
Evan Chengf2fbca62007-11-12 06:35:08 +0000780 if (DisableReMat)
781 return false;
782
Evan Cheng20ccded2008-03-15 00:19:36 +0000783 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
Evan Chengd70dbb52008-02-22 09:24:50 +0000784 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000785
786 int FrameIdx = 0;
787 if (tii_->isLoadFromStackSlot(MI, FrameIdx) &&
Evan Cheng249ded32008-02-23 03:38:34 +0000788 mf_->getFrameInfo()->isImmutableObjectIndex(FrameIdx))
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000789 // FIXME: Let target specific isReallyTriviallyReMaterializable determines
790 // this but remember this is not safe to fold into a two-address
791 // instruction.
Evan Cheng249ded32008-02-23 03:38:34 +0000792 // This is a load from fixed stack slot. It can be rematerialized.
Evan Chengdd3465e2008-02-23 01:44:27 +0000793 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000794
Dan Gohman6d69ba82008-07-25 00:02:30 +0000795 // If the target-specific rules don't identify an instruction as
796 // being trivially rematerializable, use some target-independent
797 // rules.
798 if (!MI->getDesc().isRematerializable() ||
799 !tii_->isTriviallyReMaterializable(MI)) {
Evan Chengd70dbb52008-02-22 09:24:50 +0000800
Dan Gohman6d69ba82008-07-25 00:02:30 +0000801 // If the instruction access memory but the memoperands have been lost,
802 // we can't analyze it.
803 const TargetInstrDesc &TID = MI->getDesc();
804 if ((TID.mayLoad() || TID.mayStore()) && MI->memoperands_empty())
805 return false;
806
807 // Avoid instructions obviously unsafe for remat.
808 if (TID.hasUnmodeledSideEffects() || TID.isNotDuplicable())
809 return false;
810
811 // If the instruction accesses memory and the memory could be non-constant,
812 // assume the instruction is not rematerializable.
813 for (alist<MachineMemOperand>::const_iterator I = MI->memoperands_begin(),
814 E = MI->memoperands_end(); I != E; ++I) {
815 const MachineMemOperand &MMO = *I;
816 if (MMO.isVolatile() || MMO.isStore())
817 return false;
818 const Value *V = MMO.getValue();
819 if (!V)
820 return false;
821 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
822 if (!PSV->isConstant(mf_->getFrameInfo()))
Evan Chengd70dbb52008-02-22 09:24:50 +0000823 return false;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000824 } else if (!aa_->pointsToConstantMemory(V))
825 return false;
826 }
827
828 // If any of the registers accessed are non-constant, conservatively assume
829 // the instruction is not rematerializable.
830 unsigned ImpUse = 0;
831 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
832 const MachineOperand &MO = MI->getOperand(i);
833 if (MO.isReg()) {
834 unsigned Reg = MO.getReg();
835 if (Reg == 0)
836 continue;
837 if (TargetRegisterInfo::isPhysicalRegister(Reg))
838 return false;
839
840 // Only allow one def, and that in the first operand.
841 if (MO.isDef() != (i == 0))
842 return false;
843
844 // Only allow constant-valued registers.
845 bool IsLiveIn = mri_->isLiveIn(Reg);
846 MachineRegisterInfo::def_iterator I = mri_->def_begin(Reg),
847 E = mri_->def_end();
848
849 // For the def, it should be the only def.
850 if (MO.isDef() && (next(I) != E || IsLiveIn))
851 return false;
852
853 if (MO.isUse()) {
854 // Only allow one use other register use, as that's all the
855 // remat mechanisms support currently.
856 if (Reg != li.reg) {
857 if (ImpUse == 0)
858 ImpUse = Reg;
859 else if (Reg != ImpUse)
860 return false;
861 }
862 // For uses, there should be only one associate def.
863 if (I != E && (next(I) != E || IsLiveIn))
864 return false;
865 }
Evan Chengd70dbb52008-02-22 09:24:50 +0000866 }
867 }
Evan Cheng5ef3a042007-12-06 00:01:56 +0000868 }
Evan Chengf2fbca62007-11-12 06:35:08 +0000869
Dan Gohman6d69ba82008-07-25 00:02:30 +0000870 unsigned ImpUse = getReMatImplicitUse(li, MI);
871 if (ImpUse) {
872 const LiveInterval &ImpLi = getInterval(ImpUse);
873 for (MachineRegisterInfo::use_iterator ri = mri_->use_begin(li.reg),
874 re = mri_->use_end(); ri != re; ++ri) {
875 MachineInstr *UseMI = &*ri;
876 unsigned UseIdx = getInstructionIndex(UseMI);
877 if (li.FindLiveRangeContaining(UseIdx)->valno != ValNo)
878 continue;
879 if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
880 return false;
881 }
882 }
883 return true;
Evan Cheng5ef3a042007-12-06 00:01:56 +0000884}
885
886/// isReMaterializable - Returns true if every definition of MI of every
887/// val# of the specified interval is re-materializable.
888bool LiveIntervals::isReMaterializable(const LiveInterval &li, bool &isLoad) {
889 isLoad = false;
890 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
891 i != e; ++i) {
892 const VNInfo *VNI = *i;
893 unsigned DefIdx = VNI->def;
894 if (DefIdx == ~1U)
895 continue; // Dead val#.
896 // Is the def for the val# rematerializable?
897 if (DefIdx == ~0u)
898 return false;
899 MachineInstr *ReMatDefMI = getInstructionFromIndex(DefIdx);
900 bool DefIsLoad = false;
Evan Chengd70dbb52008-02-22 09:24:50 +0000901 if (!ReMatDefMI ||
902 !isReMaterializable(li, VNI, ReMatDefMI, DefIsLoad))
Evan Cheng5ef3a042007-12-06 00:01:56 +0000903 return false;
904 isLoad |= DefIsLoad;
Evan Chengf2fbca62007-11-12 06:35:08 +0000905 }
906 return true;
907}
908
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000909/// FilterFoldedOps - Filter out two-address use operands. Return
910/// true if it finds any issue with the operands that ought to prevent
911/// folding.
912static bool FilterFoldedOps(MachineInstr *MI,
913 SmallVector<unsigned, 2> &Ops,
914 unsigned &MRInfo,
915 SmallVector<unsigned, 2> &FoldOps) {
Chris Lattner749c6f62008-01-07 07:27:27 +0000916 const TargetInstrDesc &TID = MI->getDesc();
Evan Cheng6e141fd2007-12-12 23:12:09 +0000917
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000918 MRInfo = 0;
Evan Chengaee4af62007-12-02 08:30:39 +0000919 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
920 unsigned OpIdx = Ops[i];
Evan Chengd70dbb52008-02-22 09:24:50 +0000921 MachineOperand &MO = MI->getOperand(OpIdx);
Evan Chengaee4af62007-12-02 08:30:39 +0000922 // FIXME: fold subreg use.
Evan Chengd70dbb52008-02-22 09:24:50 +0000923 if (MO.getSubReg())
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000924 return true;
Evan Chengd70dbb52008-02-22 09:24:50 +0000925 if (MO.isDef())
Evan Chengaee4af62007-12-02 08:30:39 +0000926 MRInfo |= (unsigned)VirtRegMap::isMod;
927 else {
928 // Filter out two-address use operand(s).
Evan Chengd70dbb52008-02-22 09:24:50 +0000929 if (!MO.isImplicit() &&
930 TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1) {
Evan Chengaee4af62007-12-02 08:30:39 +0000931 MRInfo = VirtRegMap::isModRef;
932 continue;
933 }
934 MRInfo |= (unsigned)VirtRegMap::isRef;
935 }
936 FoldOps.push_back(OpIdx);
Evan Chenge62f97c2007-12-01 02:07:52 +0000937 }
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000938 return false;
939}
940
941
942/// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
943/// slot / to reg or any rematerialized load into ith operand of specified
944/// MI. If it is successul, MI is updated with the newly created MI and
945/// returns true.
946bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
947 VirtRegMap &vrm, MachineInstr *DefMI,
948 unsigned InstrIdx,
949 SmallVector<unsigned, 2> &Ops,
950 bool isSS, int Slot, unsigned Reg) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000951 // If it is an implicit def instruction, just delete it.
Evan Cheng20ccded2008-03-15 00:19:36 +0000952 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000953 RemoveMachineInstrFromMaps(MI);
954 vrm.RemoveMachineInstrFromMaps(MI);
955 MI->eraseFromParent();
956 ++numFolds;
957 return true;
958 }
959
960 // Filter the list of operand indexes that are to be folded. Abort if
961 // any operand will prevent folding.
962 unsigned MRInfo = 0;
963 SmallVector<unsigned, 2> FoldOps;
964 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
965 return false;
Evan Chenge62f97c2007-12-01 02:07:52 +0000966
Evan Cheng427f4c12008-03-31 23:19:51 +0000967 // The only time it's safe to fold into a two address instruction is when
968 // it's folding reload and spill from / into a spill stack slot.
969 if (DefMI && (MRInfo & VirtRegMap::isMod))
Evan Cheng249ded32008-02-23 03:38:34 +0000970 return false;
971
Evan Chengf2f8c2a2008-02-08 22:05:27 +0000972 MachineInstr *fmi = isSS ? tii_->foldMemoryOperand(*mf_, MI, FoldOps, Slot)
973 : tii_->foldMemoryOperand(*mf_, MI, FoldOps, DefMI);
Evan Chengf2fbca62007-11-12 06:35:08 +0000974 if (fmi) {
Evan Chengd3653122008-02-27 03:04:06 +0000975 // Remember this instruction uses the spill slot.
976 if (isSS) vrm.addSpillSlotUse(Slot, fmi);
977
Evan Chengf2fbca62007-11-12 06:35:08 +0000978 // Attempt to fold the memory reference into the instruction. If
979 // we can do this, we don't need to insert spill code.
Evan Chengf2fbca62007-11-12 06:35:08 +0000980 MachineBasicBlock &MBB = *MI->getParent();
Evan Cheng84802932008-01-10 08:24:38 +0000981 if (isSS && !mf_->getFrameInfo()->isImmutableObjectIndex(Slot))
Evan Chengaee4af62007-12-02 08:30:39 +0000982 vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
Evan Cheng81a03822007-11-17 00:40:40 +0000983 vrm.transferSpillPts(MI, fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +0000984 vrm.transferRestorePts(MI, fmi);
Evan Chengc1f53c72008-03-11 21:34:46 +0000985 vrm.transferEmergencySpills(MI, fmi);
Evan Chengf2fbca62007-11-12 06:35:08 +0000986 mi2iMap_.erase(MI);
Evan Chengcddbb832007-11-30 21:23:43 +0000987 i2miMap_[InstrIdx /InstrSlots::NUM] = fmi;
988 mi2iMap_[fmi] = InstrIdx;
Evan Chengf2fbca62007-11-12 06:35:08 +0000989 MI = MBB.insert(MBB.erase(MI), fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +0000990 ++numFolds;
Evan Chengf2fbca62007-11-12 06:35:08 +0000991 return true;
992 }
993 return false;
994}
995
Evan Cheng018f9b02007-12-05 03:22:34 +0000996/// canFoldMemoryOperand - Returns true if the specified load / store
997/// folding is possible.
998bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI,
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000999 SmallVector<unsigned, 2> &Ops,
Evan Cheng3c75ba82008-04-01 21:37:32 +00001000 bool ReMat) const {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001001 // Filter the list of operand indexes that are to be folded. Abort if
1002 // any operand will prevent folding.
1003 unsigned MRInfo = 0;
Evan Cheng018f9b02007-12-05 03:22:34 +00001004 SmallVector<unsigned, 2> FoldOps;
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001005 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1006 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001007
Evan Cheng3c75ba82008-04-01 21:37:32 +00001008 // It's only legal to remat for a use, not a def.
1009 if (ReMat && (MRInfo & VirtRegMap::isMod))
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001010 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001011
Evan Chengd70dbb52008-02-22 09:24:50 +00001012 return tii_->canFoldMemoryOperand(MI, FoldOps);
1013}
1014
Evan Cheng81a03822007-11-17 00:40:40 +00001015bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
1016 SmallPtrSet<MachineBasicBlock*, 4> MBBs;
1017 for (LiveInterval::Ranges::const_iterator
1018 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1019 std::vector<IdxMBBPair>::const_iterator II =
1020 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), I->start);
1021 if (II == Idx2MBBMap.end())
1022 continue;
1023 if (I->end > II->first) // crossing a MBB.
1024 return false;
1025 MBBs.insert(II->second);
1026 if (MBBs.size() > 1)
1027 return false;
1028 }
1029 return true;
1030}
1031
Evan Chengd70dbb52008-02-22 09:24:50 +00001032/// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
1033/// interval on to-be re-materialized operands of MI) with new register.
1034void LiveIntervals::rewriteImplicitOps(const LiveInterval &li,
1035 MachineInstr *MI, unsigned NewVReg,
1036 VirtRegMap &vrm) {
1037 // There is an implicit use. That means one of the other operand is
1038 // being remat'ed and the remat'ed instruction has li.reg as an
1039 // use operand. Make sure we rewrite that as well.
1040 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1041 MachineOperand &MO = MI->getOperand(i);
1042 if (!MO.isRegister())
1043 continue;
1044 unsigned Reg = MO.getReg();
1045 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
1046 continue;
1047 if (!vrm.isReMaterialized(Reg))
1048 continue;
1049 MachineInstr *ReMatMI = vrm.getReMaterializedMI(Reg);
Evan Cheng6130f662008-03-05 00:59:57 +00001050 MachineOperand *UseMO = ReMatMI->findRegisterUseOperand(li.reg);
1051 if (UseMO)
1052 UseMO->setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001053 }
1054}
1055
Evan Chengf2fbca62007-11-12 06:35:08 +00001056/// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
1057/// for addIntervalsForSpills to rewrite uses / defs for the given live range.
Evan Cheng018f9b02007-12-05 03:22:34 +00001058bool LiveIntervals::
Evan Chengd70dbb52008-02-22 09:24:50 +00001059rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
1060 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
Evan Cheng81a03822007-11-17 00:40:40 +00001061 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001062 unsigned Slot, int LdSlot,
1063 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001064 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001065 const TargetRegisterClass* rc,
1066 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001067 const MachineLoopInfo *loopInfo,
Evan Cheng313d4b82008-02-23 00:33:04 +00001068 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001069 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001070 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
1071 MachineBasicBlock *MBB = MI->getParent();
1072 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng018f9b02007-12-05 03:22:34 +00001073 bool CanFold = false;
Evan Chengf2fbca62007-11-12 06:35:08 +00001074 RestartInstruction:
1075 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1076 MachineOperand& mop = MI->getOperand(i);
1077 if (!mop.isRegister())
1078 continue;
1079 unsigned Reg = mop.getReg();
1080 unsigned RegI = Reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001081 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
Evan Chengf2fbca62007-11-12 06:35:08 +00001082 continue;
Evan Chengf2fbca62007-11-12 06:35:08 +00001083 if (Reg != li.reg)
1084 continue;
1085
1086 bool TryFold = !DefIsReMat;
Evan Chengcb3c3302007-11-29 23:02:50 +00001087 bool FoldSS = true; // Default behavior unless it's a remat.
Evan Chengf2fbca62007-11-12 06:35:08 +00001088 int FoldSlot = Slot;
1089 if (DefIsReMat) {
1090 // If this is the rematerializable definition MI itself and
1091 // all of its uses are rematerialized, simply delete it.
Evan Cheng81a03822007-11-17 00:40:40 +00001092 if (MI == ReMatOrigDefMI && CanDelete) {
Evan Chengcddbb832007-11-30 21:23:43 +00001093 DOUT << "\t\t\t\tErasing re-materlizable def: ";
1094 DOUT << MI << '\n';
Evan Chengf2fbca62007-11-12 06:35:08 +00001095 RemoveMachineInstrFromMaps(MI);
Evan Chengcada2452007-11-28 01:28:46 +00001096 vrm.RemoveMachineInstrFromMaps(MI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001097 MI->eraseFromParent();
1098 break;
1099 }
1100
1101 // If def for this use can't be rematerialized, then try folding.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001102 // If def is rematerializable and it's a load, also try folding.
Evan Chengcb3c3302007-11-29 23:02:50 +00001103 TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad));
Evan Chengf2fbca62007-11-12 06:35:08 +00001104 if (isLoad) {
1105 // Try fold loads (from stack slot, constant pool, etc.) into uses.
1106 FoldSS = isLoadSS;
1107 FoldSlot = LdSlot;
1108 }
1109 }
1110
Evan Chengf2fbca62007-11-12 06:35:08 +00001111 // Scan all of the operands of this instruction rewriting operands
1112 // to use NewVReg instead of li.reg as appropriate. We do this for
1113 // two reasons:
1114 //
1115 // 1. If the instr reads the same spilled vreg multiple times, we
1116 // want to reuse the NewVReg.
1117 // 2. If the instr is a two-addr instruction, we are required to
1118 // keep the src/dst regs pinned.
1119 //
1120 // Keep track of whether we replace a use and/or def so that we can
1121 // create the spill interval with the appropriate range.
Evan Chengcddbb832007-11-30 21:23:43 +00001122
Evan Cheng81a03822007-11-17 00:40:40 +00001123 HasUse = mop.isUse();
1124 HasDef = mop.isDef();
Evan Chengaee4af62007-12-02 08:30:39 +00001125 SmallVector<unsigned, 2> Ops;
1126 Ops.push_back(i);
Evan Chengf2fbca62007-11-12 06:35:08 +00001127 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
Evan Chengaee4af62007-12-02 08:30:39 +00001128 const MachineOperand &MOj = MI->getOperand(j);
1129 if (!MOj.isRegister())
Evan Chengf2fbca62007-11-12 06:35:08 +00001130 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001131 unsigned RegJ = MOj.getReg();
Dan Gohman6f0d0242008-02-10 18:45:23 +00001132 if (RegJ == 0 || TargetRegisterInfo::isPhysicalRegister(RegJ))
Evan Chengf2fbca62007-11-12 06:35:08 +00001133 continue;
1134 if (RegJ == RegI) {
Evan Chengaee4af62007-12-02 08:30:39 +00001135 Ops.push_back(j);
1136 HasUse |= MOj.isUse();
1137 HasDef |= MOj.isDef();
Evan Chengf2fbca62007-11-12 06:35:08 +00001138 }
1139 }
1140
Evan Cheng79a796c2008-07-12 01:56:02 +00001141 if (HasUse && !li.liveAt(getUseIndex(index)))
1142 // Must be defined by an implicit def. It should not be spilled. Note,
1143 // this is for correctness reason. e.g.
1144 // 8 %reg1024<def> = IMPLICIT_DEF
1145 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1146 // The live range [12, 14) are not part of the r1024 live interval since
1147 // it's defined by an implicit def. It will not conflicts with live
1148 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001149 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001150 // the INSERT_SUBREG and both target registers that would overlap.
1151 HasUse = false;
1152
Evan Cheng9c3c2212008-06-06 07:54:39 +00001153 // Update stack slot spill weight if we are splitting.
Evan Chengc3417602008-06-21 06:45:54 +00001154 float Weight = getSpillWeight(HasDef, HasUse, loopDepth);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001155 if (!TrySplit)
1156 SSWeight += Weight;
1157
1158 if (!TryFold)
1159 CanFold = false;
1160 else {
Evan Cheng018f9b02007-12-05 03:22:34 +00001161 // Do not fold load / store here if we are splitting. We'll find an
1162 // optimal point to insert a load / store later.
1163 if (!TrySplit) {
1164 if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1165 Ops, FoldSS, FoldSlot, Reg)) {
1166 // Folding the load/store can completely change the instruction in
1167 // unpredictable ways, rescan it from the beginning.
1168 HasUse = false;
1169 HasDef = false;
1170 CanFold = false;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001171 if (isRemoved(MI)) {
1172 SSWeight -= Weight;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001173 break;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001174 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001175 goto RestartInstruction;
1176 }
1177 } else {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001178 // We'll try to fold it later if it's profitable.
Evan Cheng3c75ba82008-04-01 21:37:32 +00001179 CanFold = canFoldMemoryOperand(MI, Ops, DefIsReMat);
Evan Cheng018f9b02007-12-05 03:22:34 +00001180 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001181 }
Evan Chengcddbb832007-11-30 21:23:43 +00001182
1183 // Create a new virtual register for the spill interval.
1184 bool CreatedNewVReg = false;
1185 if (NewVReg == 0) {
Evan Chengd70dbb52008-02-22 09:24:50 +00001186 NewVReg = mri_->createVirtualRegister(rc);
Evan Chengcddbb832007-11-30 21:23:43 +00001187 vrm.grow();
1188 CreatedNewVReg = true;
1189 }
1190 mop.setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001191 if (mop.isImplicit())
1192 rewriteImplicitOps(li, MI, NewVReg, vrm);
Evan Chengcddbb832007-11-30 21:23:43 +00001193
1194 // Reuse NewVReg for other reads.
Evan Chengd70dbb52008-02-22 09:24:50 +00001195 for (unsigned j = 0, e = Ops.size(); j != e; ++j) {
1196 MachineOperand &mopj = MI->getOperand(Ops[j]);
1197 mopj.setReg(NewVReg);
1198 if (mopj.isImplicit())
1199 rewriteImplicitOps(li, MI, NewVReg, vrm);
1200 }
Evan Chengcddbb832007-11-30 21:23:43 +00001201
Evan Cheng81a03822007-11-17 00:40:40 +00001202 if (CreatedNewVReg) {
1203 if (DefIsReMat) {
1204 vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI/*, CanDelete*/);
Evan Chengd70dbb52008-02-22 09:24:50 +00001205 if (ReMatIds[VNI->id] == VirtRegMap::MAX_STACK_SLOT) {
Evan Cheng81a03822007-11-17 00:40:40 +00001206 // Each valnum may have its own remat id.
Evan Chengd70dbb52008-02-22 09:24:50 +00001207 ReMatIds[VNI->id] = vrm.assignVirtReMatId(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001208 } else {
Evan Chengd70dbb52008-02-22 09:24:50 +00001209 vrm.assignVirtReMatId(NewVReg, ReMatIds[VNI->id]);
Evan Cheng81a03822007-11-17 00:40:40 +00001210 }
1211 if (!CanDelete || (HasUse && HasDef)) {
1212 // If this is a two-addr instruction then its use operands are
1213 // rematerializable but its def is not. It should be assigned a
1214 // stack slot.
1215 vrm.assignVirt2StackSlot(NewVReg, Slot);
1216 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001217 } else {
Evan Chengf2fbca62007-11-12 06:35:08 +00001218 vrm.assignVirt2StackSlot(NewVReg, Slot);
1219 }
Evan Chengcb3c3302007-11-29 23:02:50 +00001220 } else if (HasUse && HasDef &&
1221 vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) {
1222 // If this interval hasn't been assigned a stack slot (because earlier
1223 // def is a deleted remat def), do it now.
1224 assert(Slot != VirtRegMap::NO_STACK_SLOT);
1225 vrm.assignVirt2StackSlot(NewVReg, Slot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001226 }
1227
Evan Cheng313d4b82008-02-23 00:33:04 +00001228 // Re-matting an instruction with virtual register use. Add the
1229 // register as an implicit use on the use MI.
1230 if (DefIsReMat && ImpUse)
1231 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1232
Evan Chengf2fbca62007-11-12 06:35:08 +00001233 // create a new register interval for this spill / remat.
1234 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001235 if (CreatedNewVReg) {
1236 NewLIs.push_back(&nI);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001237 MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg));
Evan Cheng81a03822007-11-17 00:40:40 +00001238 if (TrySplit)
1239 vrm.setIsSplitFromReg(NewVReg, li.reg);
1240 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001241
1242 if (HasUse) {
Evan Cheng81a03822007-11-17 00:40:40 +00001243 if (CreatedNewVReg) {
1244 LiveRange LR(getLoadIndex(index), getUseIndex(index)+1,
1245 nI.getNextValue(~0U, 0, VNInfoAllocator));
1246 DOUT << " +" << LR;
1247 nI.addRange(LR);
1248 } else {
1249 // Extend the split live interval to this def / use.
1250 unsigned End = getUseIndex(index)+1;
1251 LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
1252 nI.getValNumInfo(nI.getNumValNums()-1));
1253 DOUT << " +" << LR;
1254 nI.addRange(LR);
1255 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001256 }
1257 if (HasDef) {
1258 LiveRange LR(getDefIndex(index), getStoreIndex(index),
1259 nI.getNextValue(~0U, 0, VNInfoAllocator));
1260 DOUT << " +" << LR;
1261 nI.addRange(LR);
1262 }
Evan Cheng81a03822007-11-17 00:40:40 +00001263
Evan Chengf2fbca62007-11-12 06:35:08 +00001264 DOUT << "\t\t\t\tAdded new interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001265 nI.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001266 DOUT << '\n';
1267 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001268 return CanFold;
Evan Chengf2fbca62007-11-12 06:35:08 +00001269}
Evan Cheng81a03822007-11-17 00:40:40 +00001270bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001271 const VNInfo *VNI,
1272 MachineBasicBlock *MBB, unsigned Idx) const {
Evan Cheng81a03822007-11-17 00:40:40 +00001273 unsigned End = getMBBEndIdx(MBB);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001274 for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
1275 unsigned KillIdx = VNI->kills[j];
1276 if (KillIdx > Idx && KillIdx < End)
1277 return true;
Evan Cheng81a03822007-11-17 00:40:40 +00001278 }
1279 return false;
1280}
1281
Evan Cheng063284c2008-02-21 00:34:19 +00001282/// RewriteInfo - Keep track of machine instrs that will be rewritten
1283/// during spilling.
Dan Gohman844731a2008-05-13 00:00:25 +00001284namespace {
1285 struct RewriteInfo {
1286 unsigned Index;
1287 MachineInstr *MI;
1288 bool HasUse;
1289 bool HasDef;
1290 RewriteInfo(unsigned i, MachineInstr *mi, bool u, bool d)
1291 : Index(i), MI(mi), HasUse(u), HasDef(d) {}
1292 };
Evan Cheng063284c2008-02-21 00:34:19 +00001293
Dan Gohman844731a2008-05-13 00:00:25 +00001294 struct RewriteInfoCompare {
1295 bool operator()(const RewriteInfo &LHS, const RewriteInfo &RHS) const {
1296 return LHS.Index < RHS.Index;
1297 }
1298 };
1299}
Evan Cheng063284c2008-02-21 00:34:19 +00001300
Evan Chengf2fbca62007-11-12 06:35:08 +00001301void LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001302rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
Evan Chengf2fbca62007-11-12 06:35:08 +00001303 LiveInterval::Ranges::const_iterator &I,
Evan Cheng81a03822007-11-17 00:40:40 +00001304 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001305 unsigned Slot, int LdSlot,
1306 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001307 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001308 const TargetRegisterClass* rc,
1309 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001310 const MachineLoopInfo *loopInfo,
Evan Cheng81a03822007-11-17 00:40:40 +00001311 BitVector &SpillMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001312 std::map<unsigned, std::vector<SRInfo> > &SpillIdxes,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001313 BitVector &RestoreMBBs,
Evan Cheng1953d0c2007-11-29 10:12:14 +00001314 std::map<unsigned, std::vector<SRInfo> > &RestoreIdxes,
1315 std::map<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001316 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001317 bool AllCanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001318 unsigned NewVReg = 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001319 unsigned start = getBaseIndex(I->start);
Evan Chengf2fbca62007-11-12 06:35:08 +00001320 unsigned end = getBaseIndex(I->end-1) + InstrSlots::NUM;
Evan Chengf2fbca62007-11-12 06:35:08 +00001321
Evan Cheng063284c2008-02-21 00:34:19 +00001322 // First collect all the def / use in this live range that will be rewritten.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001323 // Make sure they are sorted according to instruction index.
Evan Cheng063284c2008-02-21 00:34:19 +00001324 std::vector<RewriteInfo> RewriteMIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001325 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1326 re = mri_->reg_end(); ri != re; ) {
Evan Cheng419852c2008-04-03 16:39:43 +00001327 MachineInstr *MI = &*ri;
Evan Cheng063284c2008-02-21 00:34:19 +00001328 MachineOperand &O = ri.getOperand();
1329 ++ri;
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001330 assert(!O.isImplicit() && "Spilling register that's used as implicit use?");
Evan Cheng063284c2008-02-21 00:34:19 +00001331 unsigned index = getInstructionIndex(MI);
1332 if (index < start || index >= end)
1333 continue;
Evan Cheng79a796c2008-07-12 01:56:02 +00001334 if (O.isUse() && !li.liveAt(getUseIndex(index)))
1335 // Must be defined by an implicit def. It should not be spilled. Note,
1336 // this is for correctness reason. e.g.
1337 // 8 %reg1024<def> = IMPLICIT_DEF
1338 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1339 // The live range [12, 14) are not part of the r1024 live interval since
1340 // it's defined by an implicit def. It will not conflicts with live
1341 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001342 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001343 // the INSERT_SUBREG and both target registers that would overlap.
1344 continue;
Evan Cheng063284c2008-02-21 00:34:19 +00001345 RewriteMIs.push_back(RewriteInfo(index, MI, O.isUse(), O.isDef()));
1346 }
1347 std::sort(RewriteMIs.begin(), RewriteMIs.end(), RewriteInfoCompare());
1348
Evan Cheng313d4b82008-02-23 00:33:04 +00001349 unsigned ImpUse = DefIsReMat ? getReMatImplicitUse(li, ReMatDefMI) : 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001350 // Now rewrite the defs and uses.
1351 for (unsigned i = 0, e = RewriteMIs.size(); i != e; ) {
1352 RewriteInfo &rwi = RewriteMIs[i];
1353 ++i;
1354 unsigned index = rwi.Index;
1355 bool MIHasUse = rwi.HasUse;
1356 bool MIHasDef = rwi.HasDef;
1357 MachineInstr *MI = rwi.MI;
1358 // If MI def and/or use the same register multiple times, then there
1359 // are multiple entries.
Evan Cheng313d4b82008-02-23 00:33:04 +00001360 unsigned NumUses = MIHasUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001361 while (i != e && RewriteMIs[i].MI == MI) {
1362 assert(RewriteMIs[i].Index == index);
Evan Cheng313d4b82008-02-23 00:33:04 +00001363 bool isUse = RewriteMIs[i].HasUse;
1364 if (isUse) ++NumUses;
1365 MIHasUse |= isUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001366 MIHasDef |= RewriteMIs[i].HasDef;
1367 ++i;
1368 }
Evan Cheng81a03822007-11-17 00:40:40 +00001369 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng313d4b82008-02-23 00:33:04 +00001370
Evan Cheng0a891ed2008-05-23 23:00:04 +00001371 if (ImpUse && MI != ReMatDefMI) {
Evan Cheng313d4b82008-02-23 00:33:04 +00001372 // Re-matting an instruction with virtual register use. Update the
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001373 // register interval's spill weight to HUGE_VALF to prevent it from
1374 // being spilled.
Evan Cheng313d4b82008-02-23 00:33:04 +00001375 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001376 ImpLi.weight = HUGE_VALF;
Evan Cheng313d4b82008-02-23 00:33:04 +00001377 }
1378
Evan Cheng063284c2008-02-21 00:34:19 +00001379 unsigned MBBId = MBB->getNumber();
Evan Cheng018f9b02007-12-05 03:22:34 +00001380 unsigned ThisVReg = 0;
Evan Cheng70306f82007-12-03 09:58:48 +00001381 if (TrySplit) {
Evan Cheng063284c2008-02-21 00:34:19 +00001382 std::map<unsigned,unsigned>::const_iterator NVI = MBBVRegsMap.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001383 if (NVI != MBBVRegsMap.end()) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001384 ThisVReg = NVI->second;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001385 // One common case:
1386 // x = use
1387 // ...
1388 // ...
1389 // def = ...
1390 // = use
1391 // It's better to start a new interval to avoid artifically
1392 // extend the new interval.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001393 if (MIHasDef && !MIHasUse) {
1394 MBBVRegsMap.erase(MBB->getNumber());
Evan Cheng018f9b02007-12-05 03:22:34 +00001395 ThisVReg = 0;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001396 }
1397 }
Evan Chengcada2452007-11-28 01:28:46 +00001398 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001399
1400 bool IsNew = ThisVReg == 0;
1401 if (IsNew) {
1402 // This ends the previous live interval. If all of its def / use
1403 // can be folded, give it a low spill weight.
1404 if (NewVReg && TrySplit && AllCanFold) {
1405 LiveInterval &nI = getOrCreateInterval(NewVReg);
1406 nI.weight /= 10.0F;
1407 }
1408 AllCanFold = true;
1409 }
1410 NewVReg = ThisVReg;
1411
Evan Cheng81a03822007-11-17 00:40:40 +00001412 bool HasDef = false;
1413 bool HasUse = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001414 bool CanFold = rewriteInstructionForSpills(li, I->valno, TrySplit,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001415 index, end, MI, ReMatOrigDefMI, ReMatDefMI,
1416 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
1417 CanDelete, vrm, rc, ReMatIds, loopInfo, NewVReg,
1418 ImpUse, HasDef, HasUse, MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001419 if (!HasDef && !HasUse)
1420 continue;
1421
Evan Cheng018f9b02007-12-05 03:22:34 +00001422 AllCanFold &= CanFold;
1423
Evan Cheng81a03822007-11-17 00:40:40 +00001424 // Update weight of spill interval.
1425 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng70306f82007-12-03 09:58:48 +00001426 if (!TrySplit) {
Evan Cheng81a03822007-11-17 00:40:40 +00001427 // The spill weight is now infinity as it cannot be spilled again.
1428 nI.weight = HUGE_VALF;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001429 continue;
Evan Cheng81a03822007-11-17 00:40:40 +00001430 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001431
1432 // Keep track of the last def and first use in each MBB.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001433 if (HasDef) {
1434 if (MI != ReMatOrigDefMI || !CanDelete) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001435 bool HasKill = false;
1436 if (!HasUse)
1437 HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, getDefIndex(index));
1438 else {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001439 // If this is a two-address code, then this index starts a new VNInfo.
Evan Cheng3f32d652008-06-04 09:18:41 +00001440 const VNInfo *VNI = li.findDefinedVNInfo(getDefIndex(index));
Evan Cheng0cbb1162007-11-29 01:06:25 +00001441 if (VNI)
1442 HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, getDefIndex(index));
1443 }
Evan Chenge3110d02007-12-01 04:42:39 +00001444 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
1445 SpillIdxes.find(MBBId);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001446 if (!HasKill) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001447 if (SII == SpillIdxes.end()) {
1448 std::vector<SRInfo> S;
1449 S.push_back(SRInfo(index, NewVReg, true));
1450 SpillIdxes.insert(std::make_pair(MBBId, S));
1451 } else if (SII->second.back().vreg != NewVReg) {
1452 SII->second.push_back(SRInfo(index, NewVReg, true));
1453 } else if ((int)index > SII->second.back().index) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001454 // If there is an earlier def and this is a two-address
1455 // instruction, then it's not possible to fold the store (which
1456 // would also fold the load).
Evan Cheng1953d0c2007-11-29 10:12:14 +00001457 SRInfo &Info = SII->second.back();
1458 Info.index = index;
1459 Info.canFold = !HasUse;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001460 }
1461 SpillMBBs.set(MBBId);
Evan Chenge3110d02007-12-01 04:42:39 +00001462 } else if (SII != SpillIdxes.end() &&
1463 SII->second.back().vreg == NewVReg &&
1464 (int)index > SII->second.back().index) {
1465 // There is an earlier def that's not killed (must be two-address).
1466 // The spill is no longer needed.
1467 SII->second.pop_back();
1468 if (SII->second.empty()) {
1469 SpillIdxes.erase(MBBId);
1470 SpillMBBs.reset(MBBId);
1471 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001472 }
1473 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001474 }
1475
1476 if (HasUse) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001477 std::map<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001478 SpillIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001479 if (SII != SpillIdxes.end() &&
1480 SII->second.back().vreg == NewVReg &&
1481 (int)index > SII->second.back().index)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001482 // Use(s) following the last def, it's not safe to fold the spill.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001483 SII->second.back().canFold = false;
1484 std::map<unsigned, std::vector<SRInfo> >::iterator RII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001485 RestoreIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001486 if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001487 // If we are splitting live intervals, only fold if it's the first
1488 // use and there isn't another use later in the MBB.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001489 RII->second.back().canFold = false;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001490 else if (IsNew) {
1491 // Only need a reload if there isn't an earlier def / use.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001492 if (RII == RestoreIdxes.end()) {
1493 std::vector<SRInfo> Infos;
1494 Infos.push_back(SRInfo(index, NewVReg, true));
1495 RestoreIdxes.insert(std::make_pair(MBBId, Infos));
1496 } else {
1497 RII->second.push_back(SRInfo(index, NewVReg, true));
1498 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001499 RestoreMBBs.set(MBBId);
1500 }
1501 }
1502
1503 // Update spill weight.
Evan Cheng22f07ff2007-12-11 02:09:15 +00001504 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Chengc3417602008-06-21 06:45:54 +00001505 nI.weight += getSpillWeight(HasDef, HasUse, loopDepth);
Evan Chengf2fbca62007-11-12 06:35:08 +00001506 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001507
1508 if (NewVReg && TrySplit && AllCanFold) {
1509 // If all of its def / use can be folded, give it a low spill weight.
1510 LiveInterval &nI = getOrCreateInterval(NewVReg);
1511 nI.weight /= 10.0F;
1512 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001513}
1514
Evan Cheng1953d0c2007-11-29 10:12:14 +00001515bool LiveIntervals::alsoFoldARestore(int Id, int index, unsigned vr,
1516 BitVector &RestoreMBBs,
1517 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1518 if (!RestoreMBBs[Id])
1519 return false;
1520 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1521 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1522 if (Restores[i].index == index &&
1523 Restores[i].vreg == vr &&
1524 Restores[i].canFold)
1525 return true;
1526 return false;
1527}
1528
1529void LiveIntervals::eraseRestoreInfo(int Id, int index, unsigned vr,
1530 BitVector &RestoreMBBs,
1531 std::map<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
1532 if (!RestoreMBBs[Id])
1533 return;
1534 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1535 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1536 if (Restores[i].index == index && Restores[i].vreg)
1537 Restores[i].index = -1;
1538}
Evan Cheng81a03822007-11-17 00:40:40 +00001539
Evan Cheng4cce6b42008-04-11 17:53:36 +00001540/// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
1541/// spilled and create empty intervals for their uses.
1542void
1543LiveIntervals::handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
1544 const TargetRegisterClass* rc,
1545 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng419852c2008-04-03 16:39:43 +00001546 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1547 re = mri_->reg_end(); ri != re; ) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001548 MachineOperand &O = ri.getOperand();
Evan Cheng419852c2008-04-03 16:39:43 +00001549 MachineInstr *MI = &*ri;
1550 ++ri;
Evan Cheng4cce6b42008-04-11 17:53:36 +00001551 if (O.isDef()) {
1552 assert(MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF &&
1553 "Register def was not rewritten?");
1554 RemoveMachineInstrFromMaps(MI);
1555 vrm.RemoveMachineInstrFromMaps(MI);
1556 MI->eraseFromParent();
1557 } else {
1558 // This must be an use of an implicit_def so it's not part of the live
1559 // interval. Create a new empty live interval for it.
1560 // FIXME: Can we simply erase some of the instructions? e.g. Stores?
1561 unsigned NewVReg = mri_->createVirtualRegister(rc);
1562 vrm.grow();
1563 vrm.setIsImplicitlyDefined(NewVReg);
1564 NewLIs.push_back(&getOrCreateInterval(NewVReg));
1565 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1566 MachineOperand &MO = MI->getOperand(i);
1567 if (MO.isReg() && MO.getReg() == li.reg)
1568 MO.setReg(NewVReg);
1569 }
1570 }
Evan Cheng419852c2008-04-03 16:39:43 +00001571 }
1572}
1573
Evan Cheng81a03822007-11-17 00:40:40 +00001574
Evan Chengf2fbca62007-11-12 06:35:08 +00001575std::vector<LiveInterval*> LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001576addIntervalsForSpills(const LiveInterval &li,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001577 const MachineLoopInfo *loopInfo, VirtRegMap &vrm,
1578 float &SSWeight) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001579 assert(li.weight != HUGE_VALF &&
1580 "attempt to spill already spilled interval!");
1581
1582 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001583 li.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001584 DOUT << '\n';
1585
Evan Cheng9c3c2212008-06-06 07:54:39 +00001586 // Spill slot weight.
1587 SSWeight = 0.0f;
1588
Evan Cheng81a03822007-11-17 00:40:40 +00001589 // Each bit specify whether it a spill is required in the MBB.
1590 BitVector SpillMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001591 std::map<unsigned, std::vector<SRInfo> > SpillIdxes;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001592 BitVector RestoreMBBs(mf_->getNumBlockIDs());
Evan Cheng1953d0c2007-11-29 10:12:14 +00001593 std::map<unsigned, std::vector<SRInfo> > RestoreIdxes;
1594 std::map<unsigned,unsigned> MBBVRegsMap;
Evan Chengf2fbca62007-11-12 06:35:08 +00001595 std::vector<LiveInterval*> NewLIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001596 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
Evan Chengf2fbca62007-11-12 06:35:08 +00001597
1598 unsigned NumValNums = li.getNumValNums();
1599 SmallVector<MachineInstr*, 4> ReMatDefs;
1600 ReMatDefs.resize(NumValNums, NULL);
1601 SmallVector<MachineInstr*, 4> ReMatOrigDefs;
1602 ReMatOrigDefs.resize(NumValNums, NULL);
1603 SmallVector<int, 4> ReMatIds;
1604 ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
1605 BitVector ReMatDelete(NumValNums);
1606 unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
1607
Evan Cheng81a03822007-11-17 00:40:40 +00001608 // Spilling a split live interval. It cannot be split any further. Also,
1609 // it's also guaranteed to be a single val# / range interval.
1610 if (vrm.getPreSplitReg(li.reg)) {
1611 vrm.setIsSplitFromReg(li.reg, 0);
Evan Chengd120ffd2007-12-05 10:24:35 +00001612 // Unset the split kill marker on the last use.
1613 unsigned KillIdx = vrm.getKillPoint(li.reg);
1614 if (KillIdx) {
1615 MachineInstr *KillMI = getInstructionFromIndex(KillIdx);
1616 assert(KillMI && "Last use disappeared?");
1617 int KillOp = KillMI->findRegisterUseOperandIdx(li.reg, true);
1618 assert(KillOp != -1 && "Last use disappeared?");
Chris Lattnerf7382302007-12-30 21:56:09 +00001619 KillMI->getOperand(KillOp).setIsKill(false);
Evan Chengd120ffd2007-12-05 10:24:35 +00001620 }
Evan Chengadf85902007-12-05 09:51:10 +00001621 vrm.removeKillPoint(li.reg);
Evan Cheng81a03822007-11-17 00:40:40 +00001622 bool DefIsReMat = vrm.isReMaterialized(li.reg);
1623 Slot = vrm.getStackSlot(li.reg);
1624 assert(Slot != VirtRegMap::MAX_STACK_SLOT);
1625 MachineInstr *ReMatDefMI = DefIsReMat ?
1626 vrm.getReMaterializedMI(li.reg) : NULL;
1627 int LdSlot = 0;
1628 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1629 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001630 (DefIsReMat && (ReMatDefMI->getDesc().isSimpleLoad()));
Evan Cheng81a03822007-11-17 00:40:40 +00001631 bool IsFirstRange = true;
1632 for (LiveInterval::Ranges::const_iterator
1633 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1634 // If this is a split live interval with multiple ranges, it means there
1635 // are two-address instructions that re-defined the value. Only the
1636 // first def can be rematerialized!
1637 if (IsFirstRange) {
Evan Chengcb3c3302007-11-29 23:02:50 +00001638 // Note ReMatOrigDefMI has already been deleted.
Evan Cheng81a03822007-11-17 00:40:40 +00001639 rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
1640 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001641 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001642 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001643 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001644 } else {
1645 rewriteInstructionsForSpills(li, false, I, NULL, 0,
1646 Slot, 0, false, false, false,
Evan Chengd70dbb52008-02-22 09:24:50 +00001647 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001648 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001649 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001650 }
1651 IsFirstRange = false;
1652 }
Evan Cheng419852c2008-04-03 16:39:43 +00001653
Evan Cheng9c3c2212008-06-06 07:54:39 +00001654 SSWeight = 0.0f; // Already accounted for when split.
Evan Cheng4cce6b42008-04-11 17:53:36 +00001655 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001656 return NewLIs;
1657 }
1658
1659 bool TrySplit = SplitAtBB && !intervalIsInOneMBB(li);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001660 if (SplitLimit != -1 && (int)numSplits >= SplitLimit)
1661 TrySplit = false;
1662 if (TrySplit)
1663 ++numSplits;
Evan Chengf2fbca62007-11-12 06:35:08 +00001664 bool NeedStackSlot = false;
1665 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1666 i != e; ++i) {
1667 const VNInfo *VNI = *i;
1668 unsigned VN = VNI->id;
1669 unsigned DefIdx = VNI->def;
1670 if (DefIdx == ~1U)
1671 continue; // Dead val#.
1672 // Is the def for the val# rematerializable?
Evan Cheng81a03822007-11-17 00:40:40 +00001673 MachineInstr *ReMatDefMI = (DefIdx == ~0u)
1674 ? 0 : getInstructionFromIndex(DefIdx);
Evan Cheng5ef3a042007-12-06 00:01:56 +00001675 bool dummy;
1676 if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, dummy)) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001677 // Remember how to remat the def of this val#.
Evan Cheng81a03822007-11-17 00:40:40 +00001678 ReMatOrigDefs[VN] = ReMatDefMI;
Dan Gohman2c3f7ae2008-07-17 23:49:46 +00001679 // Original def may be modified so we have to make a copy here.
Evan Cheng1ed99222008-07-19 00:37:25 +00001680 MachineInstr *Clone = mf_->CloneMachineInstr(ReMatDefMI);
1681 ClonedMIs.push_back(Clone);
1682 ReMatDefs[VN] = Clone;
Evan Chengf2fbca62007-11-12 06:35:08 +00001683
1684 bool CanDelete = true;
Evan Chengc3fc7d92007-11-29 09:49:23 +00001685 if (VNI->hasPHIKill) {
1686 // A kill is a phi node, not all of its uses can be rematerialized.
Evan Chengf2fbca62007-11-12 06:35:08 +00001687 // It must not be deleted.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001688 CanDelete = false;
1689 // Need a stack slot if there is any live range where uses cannot be
1690 // rematerialized.
1691 NeedStackSlot = true;
Evan Chengf2fbca62007-11-12 06:35:08 +00001692 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001693 if (CanDelete)
1694 ReMatDelete.set(VN);
1695 } else {
1696 // Need a stack slot if there is any live range where uses cannot be
1697 // rematerialized.
1698 NeedStackSlot = true;
1699 }
1700 }
1701
1702 // One stack slot per live interval.
Evan Cheng81a03822007-11-17 00:40:40 +00001703 if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0)
Evan Chengf2fbca62007-11-12 06:35:08 +00001704 Slot = vrm.assignVirt2StackSlot(li.reg);
1705
1706 // Create new intervals and rewrite defs and uses.
1707 for (LiveInterval::Ranges::const_iterator
1708 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Evan Cheng81a03822007-11-17 00:40:40 +00001709 MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id];
1710 MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id];
1711 bool DefIsReMat = ReMatDefMI != NULL;
Evan Chengf2fbca62007-11-12 06:35:08 +00001712 bool CanDelete = ReMatDelete[I->valno->id];
1713 int LdSlot = 0;
Evan Cheng81a03822007-11-17 00:40:40 +00001714 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001715 bool isLoad = isLoadSS ||
Chris Lattner749c6f62008-01-07 07:27:27 +00001716 (DefIsReMat && ReMatDefMI->getDesc().isSimpleLoad());
Evan Cheng81a03822007-11-17 00:40:40 +00001717 rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001718 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001719 CanDelete, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001720 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001721 MBBVRegsMap, NewLIs, SSWeight);
Evan Chengf2fbca62007-11-12 06:35:08 +00001722 }
1723
Evan Cheng0cbb1162007-11-29 01:06:25 +00001724 // Insert spills / restores if we are splitting.
Evan Cheng419852c2008-04-03 16:39:43 +00001725 if (!TrySplit) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001726 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001727 return NewLIs;
Evan Cheng419852c2008-04-03 16:39:43 +00001728 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001729
Evan Chengb50bb8c2007-12-05 08:16:32 +00001730 SmallPtrSet<LiveInterval*, 4> AddedKill;
Evan Chengaee4af62007-12-02 08:30:39 +00001731 SmallVector<unsigned, 2> Ops;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001732 if (NeedStackSlot) {
1733 int Id = SpillMBBs.find_first();
1734 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001735 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1736 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001737 std::vector<SRInfo> &spills = SpillIdxes[Id];
1738 for (unsigned i = 0, e = spills.size(); i != e; ++i) {
1739 int index = spills[i].index;
1740 unsigned VReg = spills[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001741 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001742 bool isReMat = vrm.isReMaterialized(VReg);
1743 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001744 bool CanFold = false;
1745 bool FoundUse = false;
1746 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001747 if (spills[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001748 CanFold = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001749 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1750 MachineOperand &MO = MI->getOperand(j);
1751 if (!MO.isRegister() || MO.getReg() != VReg)
1752 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001753
1754 Ops.push_back(j);
1755 if (MO.isDef())
Evan Chengcddbb832007-11-30 21:23:43 +00001756 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001757 if (isReMat ||
1758 (!FoundUse && !alsoFoldARestore(Id, index, VReg,
1759 RestoreMBBs, RestoreIdxes))) {
1760 // MI has two-address uses of the same register. If the use
1761 // isn't the first and only use in the BB, then we can't fold
1762 // it. FIXME: Move this to rewriteInstructionsForSpills.
1763 CanFold = false;
Evan Chengcddbb832007-11-30 21:23:43 +00001764 break;
1765 }
Evan Chengaee4af62007-12-02 08:30:39 +00001766 FoundUse = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001767 }
1768 }
1769 // Fold the store into the def if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001770 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001771 if (CanFold && !Ops.empty()) {
1772 if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
Evan Chengcddbb832007-11-30 21:23:43 +00001773 Folded = true;
Evan Chengf38d14f2007-12-05 09:05:34 +00001774 if (FoundUse > 0) {
Evan Chengaee4af62007-12-02 08:30:39 +00001775 // Also folded uses, do not issue a load.
1776 eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
Evan Chengf38d14f2007-12-05 09:05:34 +00001777 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
1778 }
Evan Cheng597d10d2007-12-04 00:32:23 +00001779 nI.removeRange(getDefIndex(index), getStoreIndex(index));
Evan Chengcddbb832007-11-30 21:23:43 +00001780 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001781 }
1782
Evan Cheng7e073ba2008-04-09 20:57:25 +00001783 // Otherwise tell the spiller to issue a spill.
Evan Chengb50bb8c2007-12-05 08:16:32 +00001784 if (!Folded) {
1785 LiveRange *LR = &nI.ranges[nI.ranges.size()-1];
1786 bool isKill = LR->end == getStoreIndex(index);
Evan Chengb0a6f622008-05-20 08:10:37 +00001787 if (!MI->registerDefIsDead(nI.reg))
1788 // No need to spill a dead def.
1789 vrm.addSpillPoint(VReg, isKill, MI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001790 if (isKill)
1791 AddedKill.insert(&nI);
1792 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001793
1794 // Update spill slot weight.
1795 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00001796 SSWeight += getSpillWeight(true, false, loopDepth);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001797 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001798 Id = SpillMBBs.find_next(Id);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001799 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001800 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001801
Evan Cheng1953d0c2007-11-29 10:12:14 +00001802 int Id = RestoreMBBs.find_first();
1803 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001804 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
1805 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
1806
Evan Cheng1953d0c2007-11-29 10:12:14 +00001807 std::vector<SRInfo> &restores = RestoreIdxes[Id];
1808 for (unsigned i = 0, e = restores.size(); i != e; ++i) {
1809 int index = restores[i].index;
1810 if (index == -1)
1811 continue;
1812 unsigned VReg = restores[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001813 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001814 bool isReMat = vrm.isReMaterialized(VReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001815 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001816 bool CanFold = false;
1817 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001818 if (restores[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001819 CanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001820 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1821 MachineOperand &MO = MI->getOperand(j);
1822 if (!MO.isRegister() || MO.getReg() != VReg)
1823 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001824
Evan Cheng0cbb1162007-11-29 01:06:25 +00001825 if (MO.isDef()) {
Evan Chengaee4af62007-12-02 08:30:39 +00001826 // If this restore were to be folded, it would have been folded
1827 // already.
1828 CanFold = false;
Evan Cheng81a03822007-11-17 00:40:40 +00001829 break;
1830 }
Evan Chengaee4af62007-12-02 08:30:39 +00001831 Ops.push_back(j);
Evan Cheng81a03822007-11-17 00:40:40 +00001832 }
1833 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001834
1835 // Fold the load into the use if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001836 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001837 if (CanFold && !Ops.empty()) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001838 if (!isReMat)
Evan Chengaee4af62007-12-02 08:30:39 +00001839 Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg);
1840 else {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001841 MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg);
1842 int LdSlot = 0;
1843 bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1844 // If the rematerializable def is a load, also try to fold it.
Chris Lattner749c6f62008-01-07 07:27:27 +00001845 if (isLoadSS || ReMatDefMI->getDesc().isSimpleLoad())
Evan Chengaee4af62007-12-02 08:30:39 +00001846 Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
1847 Ops, isLoadSS, LdSlot, VReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001848 unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI);
1849 if (ImpUse) {
1850 // Re-matting an instruction with virtual register use. Add the
1851 // register as an implicit use on the use MI and update the register
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001852 // interval's spill weight to HUGE_VALF to prevent it from being
1853 // spilled.
Evan Chengd70dbb52008-02-22 09:24:50 +00001854 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001855 ImpLi.weight = HUGE_VALF;
Evan Chengd70dbb52008-02-22 09:24:50 +00001856 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1857 }
Evan Chengaee4af62007-12-02 08:30:39 +00001858 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001859 }
1860 // If folding is not possible / failed, then tell the spiller to issue a
1861 // load / rematerialization for us.
Evan Cheng597d10d2007-12-04 00:32:23 +00001862 if (Folded)
1863 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001864 else
Evan Cheng0cbb1162007-11-29 01:06:25 +00001865 vrm.addRestorePoint(VReg, MI);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001866
1867 // Update spill slot weight.
1868 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00001869 SSWeight += getSpillWeight(false, true, loopDepth);
Evan Cheng81a03822007-11-17 00:40:40 +00001870 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001871 Id = RestoreMBBs.find_next(Id);
Evan Cheng81a03822007-11-17 00:40:40 +00001872 }
1873
Evan Chengb50bb8c2007-12-05 08:16:32 +00001874 // Finalize intervals: add kills, finalize spill weights, and filter out
1875 // dead intervals.
Evan Cheng597d10d2007-12-04 00:32:23 +00001876 std::vector<LiveInterval*> RetNewLIs;
1877 for (unsigned i = 0, e = NewLIs.size(); i != e; ++i) {
1878 LiveInterval *LI = NewLIs[i];
1879 if (!LI->empty()) {
Owen Anderson496bac52008-07-23 19:47:27 +00001880 LI->weight /= InstrSlots::NUM * getApproximateInstructionCount(*LI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001881 if (!AddedKill.count(LI)) {
1882 LiveRange *LR = &LI->ranges[LI->ranges.size()-1];
Evan Chengd120ffd2007-12-05 10:24:35 +00001883 unsigned LastUseIdx = getBaseIndex(LR->end);
1884 MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx);
Evan Cheng6130f662008-03-05 00:59:57 +00001885 int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg, false);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001886 assert(UseIdx != -1);
Evan Chengd70dbb52008-02-22 09:24:50 +00001887 if (LastUse->getOperand(UseIdx).isImplicit() ||
1888 LastUse->getDesc().getOperandConstraint(UseIdx,TOI::TIED_TO) == -1){
Evan Chengb50bb8c2007-12-05 08:16:32 +00001889 LastUse->getOperand(UseIdx).setIsKill();
Evan Chengd120ffd2007-12-05 10:24:35 +00001890 vrm.addKillPoint(LI->reg, LastUseIdx);
Evan Chengadf85902007-12-05 09:51:10 +00001891 }
Evan Chengb50bb8c2007-12-05 08:16:32 +00001892 }
Evan Cheng597d10d2007-12-04 00:32:23 +00001893 RetNewLIs.push_back(LI);
1894 }
1895 }
Evan Cheng81a03822007-11-17 00:40:40 +00001896
Evan Cheng4cce6b42008-04-11 17:53:36 +00001897 handleSpilledImpDefs(li, vrm, rc, RetNewLIs);
Evan Cheng597d10d2007-12-04 00:32:23 +00001898 return RetNewLIs;
Evan Chengf2fbca62007-11-12 06:35:08 +00001899}
Evan Cheng676dd7c2008-03-11 07:19:34 +00001900
1901/// hasAllocatableSuperReg - Return true if the specified physical register has
1902/// any super register that's allocatable.
1903bool LiveIntervals::hasAllocatableSuperReg(unsigned Reg) const {
1904 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS)
1905 if (allocatableRegs_[*AS] && hasInterval(*AS))
1906 return true;
1907 return false;
1908}
1909
1910/// getRepresentativeReg - Find the largest super register of the specified
1911/// physical register.
1912unsigned LiveIntervals::getRepresentativeReg(unsigned Reg) const {
1913 // Find the largest super-register that is allocatable.
1914 unsigned BestReg = Reg;
1915 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS) {
1916 unsigned SuperReg = *AS;
1917 if (!hasAllocatableSuperReg(SuperReg) && hasInterval(SuperReg)) {
1918 BestReg = SuperReg;
1919 break;
1920 }
1921 }
1922 return BestReg;
1923}
1924
1925/// getNumConflictsWithPhysReg - Return the number of uses and defs of the
1926/// specified interval that conflicts with the specified physical register.
1927unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li,
1928 unsigned PhysReg) const {
1929 unsigned NumConflicts = 0;
1930 const LiveInterval &pli = getInterval(getRepresentativeReg(PhysReg));
1931 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
1932 E = mri_->reg_end(); I != E; ++I) {
1933 MachineOperand &O = I.getOperand();
1934 MachineInstr *MI = O.getParent();
1935 unsigned Index = getInstructionIndex(MI);
1936 if (pli.liveAt(Index))
1937 ++NumConflicts;
1938 }
1939 return NumConflicts;
1940}
1941
1942/// spillPhysRegAroundRegDefsUses - Spill the specified physical register
1943/// around all defs and uses of the specified interval.
1944void LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
1945 unsigned PhysReg, VirtRegMap &vrm) {
1946 unsigned SpillReg = getRepresentativeReg(PhysReg);
1947
1948 for (const unsigned *AS = tri_->getAliasSet(PhysReg); *AS; ++AS)
1949 // If there are registers which alias PhysReg, but which are not a
1950 // sub-register of the chosen representative super register. Assert
1951 // since we can't handle it yet.
1952 assert(*AS == SpillReg || !allocatableRegs_[*AS] ||
1953 tri_->isSuperRegister(*AS, SpillReg));
1954
1955 LiveInterval &pli = getInterval(SpillReg);
1956 SmallPtrSet<MachineInstr*, 8> SeenMIs;
1957 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
1958 E = mri_->reg_end(); I != E; ++I) {
1959 MachineOperand &O = I.getOperand();
1960 MachineInstr *MI = O.getParent();
1961 if (SeenMIs.count(MI))
1962 continue;
1963 SeenMIs.insert(MI);
1964 unsigned Index = getInstructionIndex(MI);
1965 if (pli.liveAt(Index)) {
1966 vrm.addEmergencySpill(SpillReg, MI);
1967 pli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
1968 for (const unsigned* AS = tri_->getSubRegisters(SpillReg); *AS; ++AS) {
1969 if (!hasInterval(*AS))
1970 continue;
1971 LiveInterval &spli = getInterval(*AS);
1972 if (spli.liveAt(Index))
1973 spli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
1974 }
1975 }
1976 }
1977}
Owen Andersonc4dc1322008-06-05 17:15:43 +00001978
1979LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
1980 MachineInstr* startInst) {
1981 LiveInterval& Interval = getOrCreateInterval(reg);
1982 VNInfo* VN = Interval.getNextValue(
1983 getInstructionIndex(startInst) + InstrSlots::DEF,
1984 startInst, getVNInfoAllocator());
1985 VN->hasPHIKill = true;
1986 VN->kills.push_back(getMBBEndIdx(startInst->getParent()));
1987 LiveRange LR(getInstructionIndex(startInst) + InstrSlots::DEF,
1988 getMBBEndIdx(startInst->getParent()) + 1, VN);
1989 Interval.addRange(LR);
1990
1991 return LR;
1992}