blob: 9339c951a81588db1f55ad60dc3c8e353fc743c3 [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 Cheng2578ba22009-07-01 01:59:31 +000026#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000027#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000028#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000029#include "llvm/CodeGen/Passes.h"
Dan Gohman6d69ba82008-07-25 00:02:30 +000030#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000031#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000032#include "llvm/Target/TargetInstrInfo.h"
33#include "llvm/Target/TargetMachine.h"
Owen Anderson95dad832008-10-07 20:22:28 +000034#include "llvm/Target/TargetOptions.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000035#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
Evan Cheng2578ba22009-07-01 01:59:31 +000037#include "llvm/ADT/DepthFirstIterator.h"
38#include "llvm/ADT/SmallSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000039#include "llvm/ADT/Statistic.h"
40#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000041#include <algorithm>
Lang Hamesf41538d2009-06-02 16:53:25 +000042#include <limits>
Jeff Cohen97af7512006-12-02 02:22:01 +000043#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000044using namespace llvm;
45
Dan Gohman844731a2008-05-13 00:00:25 +000046// Hidden options for help debugging.
47static cl::opt<bool> DisableReMat("disable-rematerialization",
48 cl::init(false), cl::Hidden);
Evan Cheng81a03822007-11-17 00:40:40 +000049
Dan Gohman844731a2008-05-13 00:00:25 +000050static cl::opt<bool> SplitAtBB("split-intervals-at-bb",
51 cl::init(true), cl::Hidden);
52static cl::opt<int> SplitLimit("split-limit",
53 cl::init(-1), cl::Hidden);
Evan Chengbc165e42007-08-16 07:24:22 +000054
Dan Gohman4c8f8702008-07-25 15:08:37 +000055static cl::opt<bool> EnableAggressiveRemat("aggressive-remat", cl::Hidden);
56
Owen Andersonae339ba2008-08-19 00:17:30 +000057static cl::opt<bool> EnableFastSpilling("fast-spill",
58 cl::init(false), cl::Hidden);
59
Chris Lattnercd3245a2006-12-19 22:41:21 +000060STATISTIC(numIntervals, "Number of original intervals");
Evan Cheng0cbb1162007-11-29 01:06:25 +000061STATISTIC(numFolds , "Number of loads/stores folded into instructions");
62STATISTIC(numSplits , "Number of intervals split");
Chris Lattnercd3245a2006-12-19 22:41:21 +000063
Devang Patel19974732007-05-03 01:11:54 +000064char LiveIntervals::ID = 0;
Dan Gohman844731a2008-05-13 00:00:25 +000065static RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000066
Chris Lattnerf7da2c72006-08-24 22:43:55 +000067void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman6d69ba82008-07-25 00:02:30 +000068 AU.addRequired<AliasAnalysis>();
69 AU.addPreserved<AliasAnalysis>();
David Greene25133302007-06-08 17:18:56 +000070 AU.addPreserved<LiveVariables>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000071 AU.addRequired<LiveVariables>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000072 AU.addPreservedID(MachineLoopInfoID);
73 AU.addPreservedID(MachineDominatorsID);
Owen Anderson95dad832008-10-07 20:22:28 +000074
75 if (!StrongPHIElim) {
76 AU.addPreservedID(PHIEliminationID);
77 AU.addRequiredID(PHIEliminationID);
78 }
79
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000080 AU.addRequiredID(TwoAddressInstructionPassID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000081 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000082}
83
Chris Lattnerf7da2c72006-08-24 22:43:55 +000084void LiveIntervals::releaseMemory() {
Owen Anderson03857b22008-08-13 21:49:13 +000085 // Free the live intervals themselves.
Owen Anderson20e28392008-08-13 22:08:30 +000086 for (DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.begin(),
Owen Anderson03857b22008-08-13 21:49:13 +000087 E = r2iMap_.end(); I != E; ++I)
88 delete I->second;
89
Evan Cheng3f32d652008-06-04 09:18:41 +000090 MBB2IdxMap.clear();
Evan Cheng4ca980e2007-10-17 02:10:22 +000091 Idx2MBBMap.clear();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000092 mi2iMap_.clear();
93 i2miMap_.clear();
94 r2iMap_.clear();
Evan Chengdd199d22007-09-06 01:07:24 +000095 // Release VNInfo memroy regions after all VNInfo objects are dtor'd.
96 VNInfoAllocator.Reset();
Evan Cheng1ed99222008-07-19 00:37:25 +000097 while (!ClonedMIs.empty()) {
98 MachineInstr *MI = ClonedMIs.back();
99 ClonedMIs.pop_back();
100 mf_->DeleteMachineInstr(MI);
101 }
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000102}
103
Evan Cheng2578ba22009-07-01 01:59:31 +0000104/// processImplicitDefs - Process IMPLICIT_DEF instructions and make sure
105/// there is one implicit_def for each use. Add isUndef marker to
106/// implicit_def defs and their uses.
107void LiveIntervals::processImplicitDefs() {
108 SmallSet<unsigned, 8> ImpDefRegs;
109 SmallVector<MachineInstr*, 8> ImpDefMIs;
110 MachineBasicBlock *Entry = mf_->begin();
111 SmallPtrSet<MachineBasicBlock*,16> Visited;
112 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
113 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
114 DFI != E; ++DFI) {
115 MachineBasicBlock *MBB = *DFI;
116 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
117 I != E; ) {
118 MachineInstr *MI = &*I;
119 ++I;
120 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
121 unsigned Reg = MI->getOperand(0).getReg();
122 MI->getOperand(0).setIsUndef();
123 ImpDefRegs.insert(Reg);
124 ImpDefMIs.push_back(MI);
125 continue;
126 }
127 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
128 MachineOperand& MO = MI->getOperand(i);
129 if (!MO.isReg() || !MO.isUse())
130 continue;
131 unsigned Reg = MO.getReg();
132 if (!Reg)
133 continue;
134 if (!ImpDefRegs.count(Reg))
135 continue;
136 MO.setIsUndef();
137 if (MO.isKill() || MI->isRegTiedToDefOperand(i))
138 ImpDefRegs.erase(Reg);
139 }
140
141 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
142 MachineOperand& MO = MI->getOperand(i);
143 if (!MO.isReg() || !MO.isDef())
144 continue;
145 ImpDefRegs.erase(MO.getReg());
146 }
147 }
148
149 // Any outstanding liveout implicit_def's?
150 for (unsigned i = 0, e = ImpDefMIs.size(); i != e; ++i) {
151 MachineInstr *MI = ImpDefMIs[i];
152 unsigned Reg = MI->getOperand(0).getReg();
153 if (TargetRegisterInfo::isPhysicalRegister(Reg))
154 // Physical registers are not liveout (yet).
155 continue;
156 if (!ImpDefRegs.count(Reg))
157 continue;
158 bool HasLocalUse = false;
159 for (MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(Reg),
160 RE = mri_->reg_end(); RI != RE; ) {
161 MachineOperand &RMO = RI.getOperand();
162 MachineInstr *RMI = &*RI;
163 ++RI;
164 if (RMO.isDef()) {
165 // Don't expect another def of the same register.
166 assert(RMI == MI &&
167 "Register with multiple defs including an implicit_def?");
168 continue;
169 }
170 MachineBasicBlock *RMBB = RMI->getParent();
171 if (RMBB == MBB) {
172 HasLocalUse = true;
173 continue;
174 }
175 const TargetRegisterClass* RC = mri_->getRegClass(Reg);
176 unsigned NewVReg = mri_->createVirtualRegister(RC);
177 BuildMI(*RMBB, RMI, RMI->getDebugLoc(),
178 tii_->get(TargetInstrInfo::IMPLICIT_DEF), NewVReg);
179 RMO.setReg(NewVReg);
180 RMO.setIsUndef();
181 RMO.setIsKill();
182 }
183 if (!HasLocalUse)
184 MI->eraseFromParent();
185 }
186 ImpDefRegs.clear();
187 ImpDefMIs.clear();
188 }
189}
190
Owen Anderson80b3ce62008-05-28 20:54:50 +0000191void LiveIntervals::computeNumbering() {
192 Index2MiMap OldI2MI = i2miMap_;
Owen Anderson7fbad272008-07-23 21:37:49 +0000193 std::vector<IdxMBBPair> OldI2MBB = Idx2MBBMap;
Owen Anderson80b3ce62008-05-28 20:54:50 +0000194
195 Idx2MBBMap.clear();
196 MBB2IdxMap.clear();
197 mi2iMap_.clear();
198 i2miMap_.clear();
199
Owen Andersona1566f22008-07-22 22:46:49 +0000200 FunctionSize = 0;
201
Chris Lattner428b92e2006-09-15 03:57:23 +0000202 // Number MachineInstrs and MachineBasicBlocks.
203 // Initialize MBB indexes to a sentinal.
Evan Cheng549f27d32007-08-13 23:45:17 +0000204 MBB2IdxMap.resize(mf_->getNumBlockIDs(), std::make_pair(~0U,~0U));
Chris Lattner428b92e2006-09-15 03:57:23 +0000205
206 unsigned MIIndex = 0;
207 for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
208 MBB != E; ++MBB) {
Evan Cheng549f27d32007-08-13 23:45:17 +0000209 unsigned StartIdx = MIIndex;
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000210
Owen Anderson7fbad272008-07-23 21:37:49 +0000211 // Insert an empty slot at the beginning of each block.
212 MIIndex += InstrSlots::NUM;
213 i2miMap_.push_back(0);
214
Chris Lattner428b92e2006-09-15 03:57:23 +0000215 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
216 I != E; ++I) {
217 bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000218 assert(inserted && "multiple MachineInstr -> index mappings");
Devang Patel59500c82008-11-21 20:00:59 +0000219 inserted = true;
Chris Lattner428b92e2006-09-15 03:57:23 +0000220 i2miMap_.push_back(I);
221 MIIndex += InstrSlots::NUM;
Owen Andersona1566f22008-07-22 22:46:49 +0000222 FunctionSize++;
Owen Anderson7fbad272008-07-23 21:37:49 +0000223
Evan Cheng4ed43292008-10-18 05:21:37 +0000224 // Insert max(1, numdefs) empty slots after every instruction.
Evan Cheng99fe34b2008-10-18 05:18:55 +0000225 unsigned Slots = I->getDesc().getNumDefs();
226 if (Slots == 0)
227 Slots = 1;
228 MIIndex += InstrSlots::NUM * Slots;
229 while (Slots--)
230 i2miMap_.push_back(0);
Owen Anderson35578012008-06-16 07:10:49 +0000231 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000232
Owen Anderson1fbb4542008-06-16 16:58:24 +0000233 // Set the MBB2IdxMap entry for this MBB.
234 MBB2IdxMap[MBB->getNumber()] = std::make_pair(StartIdx, MIIndex - 1);
235 Idx2MBBMap.push_back(std::make_pair(StartIdx, MBB));
Chris Lattner428b92e2006-09-15 03:57:23 +0000236 }
Evan Cheng4ca980e2007-10-17 02:10:22 +0000237 std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
Owen Anderson80b3ce62008-05-28 20:54:50 +0000238
239 if (!OldI2MI.empty())
Owen Anderson788d0412008-08-06 18:35:45 +0000240 for (iterator OI = begin(), OE = end(); OI != OE; ++OI) {
Owen Anderson03857b22008-08-13 21:49:13 +0000241 for (LiveInterval::iterator LI = OI->second->begin(),
242 LE = OI->second->end(); LI != LE; ++LI) {
Owen Anderson4b5b2092008-05-29 18:15:49 +0000243
Owen Anderson7eec0c22008-05-29 23:01:22 +0000244 // Remap the start index of the live range to the corresponding new
245 // number, or our best guess at what it _should_ correspond to if the
246 // original instruction has been erased. This is either the following
247 // instruction or its predecessor.
Owen Anderson7fbad272008-07-23 21:37:49 +0000248 unsigned index = LI->start / InstrSlots::NUM;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000249 unsigned offset = LI->start % InstrSlots::NUM;
Owen Anderson0a7615a2008-07-25 23:06:59 +0000250 if (offset == InstrSlots::LOAD) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000251 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000252 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->start);
Owen Anderson7fbad272008-07-23 21:37:49 +0000253 // Take the pair containing the index
254 std::vector<IdxMBBPair>::const_iterator J =
Owen Andersona0c032f2008-07-29 21:15:44 +0000255 (I == OldI2MBB.end() && OldI2MBB.size()>0) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000256
Owen Anderson7fbad272008-07-23 21:37:49 +0000257 LI->start = getMBBStartIdx(J->second);
258 } else {
259 LI->start = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000260 }
261
262 // Remap the ending index in the same way that we remapped the start,
263 // except for the final step where we always map to the immediately
264 // following instruction.
Owen Andersond7dcbec2008-07-25 19:50:48 +0000265 index = (LI->end - 1) / InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000266 offset = LI->end % InstrSlots::NUM;
Owen Anderson9382b932008-07-30 00:22:56 +0000267 if (offset == InstrSlots::LOAD) {
268 // VReg dies at end of block.
Owen Anderson7fbad272008-07-23 21:37:49 +0000269 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000270 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->end);
Owen Anderson9382b932008-07-30 00:22:56 +0000271 --I;
Owen Anderson7fbad272008-07-23 21:37:49 +0000272
Owen Anderson9382b932008-07-30 00:22:56 +0000273 LI->end = getMBBEndIdx(I->second) + 1;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000274 } else {
Owen Andersond7dcbec2008-07-25 19:50:48 +0000275 unsigned idx = index;
Owen Anderson8d0cc0a2008-07-25 21:07:13 +0000276 while (index < OldI2MI.size() && !OldI2MI[index]) ++index;
277
278 if (index != OldI2MI.size())
279 LI->end = mi2iMap_[OldI2MI[index]] + (idx == index ? offset : 0);
280 else
281 LI->end = InstrSlots::NUM * i2miMap_.size();
Owen Anderson4b5b2092008-05-29 18:15:49 +0000282 }
Owen Anderson788d0412008-08-06 18:35:45 +0000283 }
284
Owen Anderson03857b22008-08-13 21:49:13 +0000285 for (LiveInterval::vni_iterator VNI = OI->second->vni_begin(),
286 VNE = OI->second->vni_end(); VNI != VNE; ++VNI) {
Owen Anderson788d0412008-08-06 18:35:45 +0000287 VNInfo* vni = *VNI;
Owen Anderson745825f42008-05-28 22:40:08 +0000288
Owen Anderson7eec0c22008-05-29 23:01:22 +0000289 // Remap the VNInfo def index, which works the same as the
Owen Anderson788d0412008-08-06 18:35:45 +0000290 // start indices above. VN's with special sentinel defs
291 // don't need to be remapped.
Lang Hames857c4e02009-06-17 21:01:20 +0000292 if (vni->isDefAccurate() && !vni->isUnused()) {
Owen Anderson788d0412008-08-06 18:35:45 +0000293 unsigned index = vni->def / InstrSlots::NUM;
294 unsigned offset = vni->def % InstrSlots::NUM;
Owen Anderson91292392008-07-30 17:42:47 +0000295 if (offset == InstrSlots::LOAD) {
296 std::vector<IdxMBBPair>::const_iterator I =
Owen Anderson0a7615a2008-07-25 23:06:59 +0000297 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->def);
Owen Anderson91292392008-07-30 17:42:47 +0000298 // Take the pair containing the index
299 std::vector<IdxMBBPair>::const_iterator J =
Owen Andersona0c032f2008-07-29 21:15:44 +0000300 (I == OldI2MBB.end() && OldI2MBB.size()>0) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000301
Owen Anderson91292392008-07-30 17:42:47 +0000302 vni->def = getMBBStartIdx(J->second);
303 } else {
304 vni->def = mi2iMap_[OldI2MI[index]] + offset;
305 }
Owen Anderson7eec0c22008-05-29 23:01:22 +0000306 }
Owen Anderson745825f42008-05-28 22:40:08 +0000307
Owen Anderson7eec0c22008-05-29 23:01:22 +0000308 // Remap the VNInfo kill indices, which works the same as
309 // the end indices above.
Owen Anderson4b5b2092008-05-29 18:15:49 +0000310 for (size_t i = 0; i < vni->kills.size(); ++i) {
Owen Anderson9382b932008-07-30 00:22:56 +0000311 // PHI kills don't need to be remapped.
312 if (!vni->kills[i]) continue;
313
Owen Anderson788d0412008-08-06 18:35:45 +0000314 unsigned index = (vni->kills[i]-1) / InstrSlots::NUM;
315 unsigned offset = vni->kills[i] % InstrSlots::NUM;
Owen Anderson309c6162008-09-30 22:51:54 +0000316 if (offset == InstrSlots::LOAD) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000317 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000318 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->kills[i]);
Owen Anderson9382b932008-07-30 00:22:56 +0000319 --I;
Owen Anderson7fbad272008-07-23 21:37:49 +0000320
Owen Anderson788d0412008-08-06 18:35:45 +0000321 vni->kills[i] = getMBBEndIdx(I->second);
Owen Anderson7fbad272008-07-23 21:37:49 +0000322 } else {
Owen Andersond7dcbec2008-07-25 19:50:48 +0000323 unsigned idx = index;
Owen Anderson8d0cc0a2008-07-25 21:07:13 +0000324 while (index < OldI2MI.size() && !OldI2MI[index]) ++index;
325
326 if (index != OldI2MI.size())
327 vni->kills[i] = mi2iMap_[OldI2MI[index]] +
328 (idx == index ? offset : 0);
329 else
330 vni->kills[i] = InstrSlots::NUM * i2miMap_.size();
Owen Anderson7eec0c22008-05-29 23:01:22 +0000331 }
Owen Anderson4b5b2092008-05-29 18:15:49 +0000332 }
Owen Anderson80b3ce62008-05-28 20:54:50 +0000333 }
Owen Anderson788d0412008-08-06 18:35:45 +0000334 }
Owen Anderson80b3ce62008-05-28 20:54:50 +0000335}
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000336
Lang Hamesf41538d2009-06-02 16:53:25 +0000337void LiveIntervals::scaleNumbering(int factor) {
338 // Need to
339 // * scale MBB begin and end points
340 // * scale all ranges.
341 // * Update VNI structures.
342 // * Scale instruction numberings
343
344 // Scale the MBB indices.
345 Idx2MBBMap.clear();
346 for (MachineFunction::iterator MBB = mf_->begin(), MBBE = mf_->end();
347 MBB != MBBE; ++MBB) {
348 std::pair<unsigned, unsigned> &mbbIndices = MBB2IdxMap[MBB->getNumber()];
349 mbbIndices.first = InstrSlots::scale(mbbIndices.first, factor);
350 mbbIndices.second = InstrSlots::scale(mbbIndices.second, factor);
351 Idx2MBBMap.push_back(std::make_pair(mbbIndices.first, MBB));
352 }
353 std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
354
355 // Scale the intervals.
356 for (iterator LI = begin(), LE = end(); LI != LE; ++LI) {
357 LI->second->scaleNumbering(factor);
358 }
359
360 // Scale MachineInstrs.
361 Mi2IndexMap oldmi2iMap = mi2iMap_;
362 unsigned highestSlot = 0;
363 for (Mi2IndexMap::iterator MI = oldmi2iMap.begin(), ME = oldmi2iMap.end();
364 MI != ME; ++MI) {
365 unsigned newSlot = InstrSlots::scale(MI->second, factor);
366 mi2iMap_[MI->first] = newSlot;
367 highestSlot = std::max(highestSlot, newSlot);
368 }
369
370 i2miMap_.clear();
371 i2miMap_.resize(highestSlot + 1);
372 for (Mi2IndexMap::iterator MI = mi2iMap_.begin(), ME = mi2iMap_.end();
373 MI != ME; ++MI) {
374 i2miMap_[MI->second] = MI->first;
375 }
376
377}
378
379
Owen Anderson80b3ce62008-05-28 20:54:50 +0000380/// runOnMachineFunction - Register allocate the whole function
381///
382bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
383 mf_ = &fn;
384 mri_ = &mf_->getRegInfo();
385 tm_ = &fn.getTarget();
386 tri_ = tm_->getRegisterInfo();
387 tii_ = tm_->getInstrInfo();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000388 aa_ = &getAnalysis<AliasAnalysis>();
Owen Anderson80b3ce62008-05-28 20:54:50 +0000389 lv_ = &getAnalysis<LiveVariables>();
390 allocatableRegs_ = tri_->getAllocatableSet(fn);
391
Evan Cheng2578ba22009-07-01 01:59:31 +0000392 processImplicitDefs();
Owen Anderson80b3ce62008-05-28 20:54:50 +0000393 computeNumbering();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000394 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000395
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000396 numIntervals += getNumIntervals();
397
Chris Lattner70ca3582004-09-30 15:59:17 +0000398 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000399 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000400}
401
Chris Lattner70ca3582004-09-30 15:59:17 +0000402/// print - Implement the dump method.
Reid Spencerce9653c2004-12-07 04:03:45 +0000403void LiveIntervals::print(std::ostream &O, const Module* ) const {
Chris Lattner70ca3582004-09-30 15:59:17 +0000404 O << "********** INTERVALS **********\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000405 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Owen Anderson03857b22008-08-13 21:49:13 +0000406 I->second->print(O, tri_);
Evan Cheng3f32d652008-06-04 09:18:41 +0000407 O << "\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000408 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000409
410 O << "********** MACHINEINSTRS **********\n";
411 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
412 mbbi != mbbe; ++mbbi) {
413 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
414 for (MachineBasicBlock::iterator mii = mbbi->begin(),
415 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner477e4552004-09-30 16:10:45 +0000416 O << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner70ca3582004-09-30 15:59:17 +0000417 }
418 }
419}
420
Evan Chengc92da382007-11-03 07:20:12 +0000421/// conflictsWithPhysRegDef - Returns true if the specified register
422/// is defined during the duration of the specified interval.
423bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
424 VirtRegMap &vrm, unsigned reg) {
425 for (LiveInterval::Ranges::const_iterator
426 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
427 for (unsigned index = getBaseIndex(I->start),
428 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
429 index += InstrSlots::NUM) {
430 // skip deleted instructions
431 while (index != end && !getInstructionFromIndex(index))
432 index += InstrSlots::NUM;
433 if (index == end) break;
434
435 MachineInstr *MI = getInstructionFromIndex(index);
Evan Cheng04ee5a12009-01-20 19:12:24 +0000436 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
437 if (tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Cheng5d446262007-11-15 08:13:29 +0000438 if (SrcReg == li.reg || DstReg == li.reg)
439 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000440 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
441 MachineOperand& mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000442 if (!mop.isReg())
Evan Chengc92da382007-11-03 07:20:12 +0000443 continue;
444 unsigned PhysReg = mop.getReg();
Evan Cheng5d446262007-11-15 08:13:29 +0000445 if (PhysReg == 0 || PhysReg == li.reg)
Evan Chengc92da382007-11-03 07:20:12 +0000446 continue;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000447 if (TargetRegisterInfo::isVirtualRegister(PhysReg)) {
Evan Cheng5d446262007-11-15 08:13:29 +0000448 if (!vrm.hasPhys(PhysReg))
449 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000450 PhysReg = vrm.getPhys(PhysReg);
Evan Cheng5d446262007-11-15 08:13:29 +0000451 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000452 if (PhysReg && tri_->regsOverlap(PhysReg, reg))
Evan Chengc92da382007-11-03 07:20:12 +0000453 return true;
454 }
455 }
456 }
457
458 return false;
459}
460
Evan Cheng8f90b6e2009-01-07 02:08:57 +0000461/// conflictsWithPhysRegRef - Similar to conflictsWithPhysRegRef except
462/// it can check use as well.
463bool LiveIntervals::conflictsWithPhysRegRef(LiveInterval &li,
464 unsigned Reg, bool CheckUse,
465 SmallPtrSet<MachineInstr*,32> &JoinedCopies) {
466 for (LiveInterval::Ranges::const_iterator
467 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
468 for (unsigned index = getBaseIndex(I->start),
469 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
470 index += InstrSlots::NUM) {
471 // Skip deleted instructions.
472 MachineInstr *MI = 0;
473 while (index != end) {
474 MI = getInstructionFromIndex(index);
475 if (MI)
476 break;
477 index += InstrSlots::NUM;
478 }
479 if (index == end) break;
480
481 if (JoinedCopies.count(MI))
482 continue;
483 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
484 MachineOperand& MO = MI->getOperand(i);
485 if (!MO.isReg())
486 continue;
487 if (MO.isUse() && !CheckUse)
488 continue;
489 unsigned PhysReg = MO.getReg();
490 if (PhysReg == 0 || TargetRegisterInfo::isVirtualRegister(PhysReg))
491 continue;
492 if (tri_->isSubRegister(Reg, PhysReg))
493 return true;
494 }
495 }
496 }
497
498 return false;
499}
500
501
Evan Cheng549f27d32007-08-13 23:45:17 +0000502void LiveIntervals::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000503 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000504 cerr << tri_->getName(reg);
Evan Cheng549f27d32007-08-13 23:45:17 +0000505 else
506 cerr << "%reg" << reg;
507}
508
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000509void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000510 MachineBasicBlock::iterator mi,
Owen Anderson6b098de2008-06-25 23:39:39 +0000511 unsigned MIIdx, MachineOperand& MO,
Evan Chengef0732d2008-07-10 07:35:43 +0000512 unsigned MOIdx,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000513 LiveInterval &interval) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000514 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000515 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000516
Evan Cheng419852c2008-04-03 16:39:43 +0000517 if (mi->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
518 DOUT << "is a implicit_def\n";
519 return;
520 }
521
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000522 // Virtual registers may be defined multiple times (due to phi
523 // elimination and 2-addr elimination). Much of what we do only has to be
524 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000525 // time we see a vreg.
526 if (interval.empty()) {
527 // Get the Idx of the defining instructions.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000528 unsigned defIndex = getDefIndex(MIIdx);
Dale Johannesen86b49f82008-09-24 01:07:17 +0000529 // Earlyclobbers move back one.
530 if (MO.isEarlyClobber())
531 defIndex = getUseIndex(MIIdx);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000532 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000533 MachineInstr *CopyMI = NULL;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000534 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000535 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000536 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Dan Gohman97121ba2009-04-08 00:15:30 +0000537 mi->getOpcode() == TargetInstrInfo::SUBREG_TO_REG ||
Evan Cheng04ee5a12009-01-20 19:12:24 +0000538 tii_->isMoveInstr(*mi, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000539 CopyMI = mi;
Evan Cheng5379f412008-12-19 20:58:01 +0000540 // Earlyclobbers move back one.
Lang Hames857c4e02009-06-17 21:01:20 +0000541 ValNo = interval.getNextValue(defIndex, CopyMI, true, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000542
543 assert(ValNo->id == 0 && "First value in interval is not 0?");
Chris Lattner7ac2d312004-07-24 02:59:07 +0000544
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000545 // Loop over all of the blocks that the vreg is defined in. There are
546 // two cases we have to handle here. The most common case is a vreg
547 // whose lifetime is contained within a basic block. In this case there
548 // will be a single kill, in MBB, which comes after the definition.
549 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
550 // FIXME: what about dead vars?
551 unsigned killIdx;
552 if (vi.Kills[0] != mi)
553 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
554 else
555 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000556
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000557 // If the kill happens after the definition, we have an intra-block
558 // live range.
559 if (killIdx > defIndex) {
Jeffrey Yasskin493a3d02009-05-26 18:27:15 +0000560 assert(vi.AliveBlocks.empty() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000561 "Shouldn't be alive across any blocks!");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000562 LiveRange LR(defIndex, killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000563 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000564 DOUT << " +" << LR << "\n";
Evan Chengf3bb2e62007-09-05 21:46:51 +0000565 interval.addKill(ValNo, killIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000566 return;
567 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000568 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000569
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000570 // The other case we handle is when a virtual register lives to the end
571 // of the defining block, potentially live across some blocks, then is
572 // live into some number of blocks, but gets killed. Start by adding a
573 // range that goes from this definition to the end of the defining block.
Owen Anderson7fbad272008-07-23 21:37:49 +0000574 LiveRange NewLR(defIndex, getMBBEndIdx(mbb)+1, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000575 DOUT << " +" << NewLR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000576 interval.addRange(NewLR);
577
578 // Iterate over all of the blocks that the variable is completely
579 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
580 // live interval.
Jeffrey Yasskin493a3d02009-05-26 18:27:15 +0000581 for (SparseBitVector<>::iterator I = vi.AliveBlocks.begin(),
582 E = vi.AliveBlocks.end(); I != E; ++I) {
583 LiveRange LR(getMBBStartIdx(*I),
584 getMBBEndIdx(*I)+1, // MBB ends at -1.
Dan Gohman4a829ec2008-11-13 16:31:27 +0000585 ValNo);
586 interval.addRange(LR);
587 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000588 }
589
590 // Finally, this virtual register is live from the start of any killing
591 // block to the 'use' slot of the killing instruction.
592 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
593 MachineInstr *Kill = vi.Kills[i];
Evan Cheng8df78602007-08-08 03:00:28 +0000594 unsigned killIdx = getUseIndex(getInstructionIndex(Kill))+1;
Chris Lattner428b92e2006-09-15 03:57:23 +0000595 LiveRange LR(getMBBStartIdx(Kill->getParent()),
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000596 killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000597 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000598 interval.addKill(ValNo, killIdx);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000599 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000600 }
601
602 } else {
603 // If this is the second time we see a virtual register definition, it
604 // must be due to phi elimination or two addr elimination. If this is
Evan Chengbf105c82006-11-03 03:04:46 +0000605 // the result of two address elimination, then the vreg is one of the
606 // def-and-use register operand.
Bob Wilsond9df5012009-04-09 17:16:43 +0000607 if (mi->isRegTiedToUseOperand(MOIdx)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000608 // If this is a two-address definition, then we have already processed
609 // the live range. The only problem is that we didn't realize there
610 // are actually two values in the live interval. Because of this we
611 // need to take the LiveRegion that defines this register and split it
612 // into two values.
Evan Chenga07cec92008-01-10 08:22:10 +0000613 assert(interval.containsOneValue());
614 unsigned DefIndex = getDefIndex(interval.getValNumInfo(0)->def);
Chris Lattner6b128bd2006-09-03 08:07:11 +0000615 unsigned RedefIndex = getDefIndex(MIIdx);
Evan Chengfb112882009-03-23 08:01:15 +0000616 if (MO.isEarlyClobber())
617 RedefIndex = getUseIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000618
Evan Cheng4f8ff162007-08-11 00:59:19 +0000619 const LiveRange *OldLR = interval.getLiveRangeContaining(RedefIndex-1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000620 VNInfo *OldValNo = OldLR->valno;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000621
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000622 // Delete the initial value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000623 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000624 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000625
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000626 // Two-address vregs should always only be redefined once. This means
627 // that at this point, there should be exactly one value number in it.
628 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
629
Chris Lattner91725b72006-08-31 05:54:43 +0000630 // The new value number (#1) is defined by the instruction we claimed
631 // defined value #0.
Evan Chengc8d044e2008-02-15 18:24:29 +0000632 VNInfo *ValNo = interval.getNextValue(OldValNo->def, OldValNo->copy,
Lang Hames857c4e02009-06-17 21:01:20 +0000633 false, // update at *
Evan Chengc8d044e2008-02-15 18:24:29 +0000634 VNInfoAllocator);
Lang Hames857c4e02009-06-17 21:01:20 +0000635 ValNo->setFlags(OldValNo->getFlags()); // * <- updating here
636
Chris Lattner91725b72006-08-31 05:54:43 +0000637 // Value#0 is now defined by the 2-addr instruction.
Evan Chengc8d044e2008-02-15 18:24:29 +0000638 OldValNo->def = RedefIndex;
639 OldValNo->copy = 0;
Evan Chengfb112882009-03-23 08:01:15 +0000640 if (MO.isEarlyClobber())
Lang Hames857c4e02009-06-17 21:01:20 +0000641 OldValNo->setHasRedefByEC(true);
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000642
643 // Add the new live interval which replaces the range for the input copy.
644 LiveRange LR(DefIndex, RedefIndex, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000645 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000646 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000647 interval.addKill(ValNo, RedefIndex);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000648
649 // If this redefinition is dead, we need to add a dummy unit live
650 // range covering the def slot.
Owen Anderson6b098de2008-06-25 23:39:39 +0000651 if (MO.isDead())
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000652 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, OldValNo));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000653
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000654 DOUT << " RESULT: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000655 interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000656
657 } else {
658 // Otherwise, this must be because of phi elimination. If this is the
659 // first redefinition of the vreg that we have seen, go back and change
660 // the live range in the PHI block to be a different value number.
661 if (interval.containsOneValue()) {
662 assert(vi.Kills.size() == 1 &&
663 "PHI elimination vreg should have one kill, the PHI itself!");
664
665 // Remove the old range that we now know has an incorrect number.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000666 VNInfo *VNI = interval.getValNumInfo(0);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000667 MachineInstr *Killer = vi.Kills[0];
Chris Lattner428b92e2006-09-15 03:57:23 +0000668 unsigned Start = getMBBStartIdx(Killer->getParent());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000669 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000670 DOUT << " Removing [" << Start << "," << End << "] from: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000671 interval.print(DOUT, tri_); DOUT << "\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000672 interval.removeRange(Start, End);
Lang Hames857c4e02009-06-17 21:01:20 +0000673 VNI->setHasPHIKill(true);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000674 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000675
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000676 // Replace the interval with one of a NEW value number. Note that this
677 // value number isn't actually defined by an instruction, weird huh? :)
Lang Hames10382fb2009-06-19 02:17:53 +0000678 LiveRange LR(Start, End,
679 interval.getNextValue(mbb->getNumber(), 0, false, VNInfoAllocator));
Lang Hames857c4e02009-06-17 21:01:20 +0000680 LR.valno->setIsPHIDef(true);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000681 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000682 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000683 interval.addKill(LR.valno, End);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000684 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000685 }
686
687 // In the case of PHI elimination, each variable definition is only
688 // live until the end of the block. We've already taken care of the
689 // rest of the live range.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000690 unsigned defIndex = getDefIndex(MIIdx);
Evan Chengfb112882009-03-23 08:01:15 +0000691 if (MO.isEarlyClobber())
692 defIndex = getUseIndex(MIIdx);
Chris Lattner91725b72006-08-31 05:54:43 +0000693
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000694 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000695 MachineInstr *CopyMI = NULL;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000696 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000697 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000698 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Dan Gohman97121ba2009-04-08 00:15:30 +0000699 mi->getOpcode() == TargetInstrInfo::SUBREG_TO_REG ||
Evan Cheng04ee5a12009-01-20 19:12:24 +0000700 tii_->isMoveInstr(*mi, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000701 CopyMI = mi;
Lang Hames857c4e02009-06-17 21:01:20 +0000702 ValNo = interval.getNextValue(defIndex, CopyMI, true, VNInfoAllocator);
Chris Lattner91725b72006-08-31 05:54:43 +0000703
Owen Anderson7fbad272008-07-23 21:37:49 +0000704 unsigned killIndex = getMBBEndIdx(mbb) + 1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000705 LiveRange LR(defIndex, killIndex, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000706 interval.addRange(LR);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000707 interval.addKill(ValNo, killIndex);
Lang Hames857c4e02009-06-17 21:01:20 +0000708 ValNo->setHasPHIKill(true);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000709 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000710 }
711 }
712
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000713 DOUT << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000714}
715
Chris Lattnerf35fef72004-07-23 21:24:19 +0000716void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000717 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000718 unsigned MIIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000719 MachineOperand& MO,
Chris Lattner91725b72006-08-31 05:54:43 +0000720 LiveInterval &interval,
Evan Chengc8d044e2008-02-15 18:24:29 +0000721 MachineInstr *CopyMI) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000722 // A physical register cannot be live across basic block, so its
723 // lifetime must end somewhere in its defining basic block.
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000724 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000725
Chris Lattner6b128bd2006-09-03 08:07:11 +0000726 unsigned baseIndex = MIIdx;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000727 unsigned start = getDefIndex(baseIndex);
Dale Johannesen86b49f82008-09-24 01:07:17 +0000728 // Earlyclobbers move back one.
729 if (MO.isEarlyClobber())
730 start = getUseIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000731 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000732
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000733 // If it is not used after definition, it is considered dead at
734 // the instruction defining it. Hence its interval is:
735 // [defSlot(def), defSlot(def)+1)
Owen Anderson6b098de2008-06-25 23:39:39 +0000736 if (MO.isDead()) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000737 DOUT << " dead";
Dale Johannesen86b49f82008-09-24 01:07:17 +0000738 end = start + 1;
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000739 goto exit;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000740 }
741
742 // If it is not dead on definition, it must be killed by a
743 // subsequent instruction. Hence its interval is:
744 // [defSlot(def), useSlot(kill)+1)
Owen Anderson7fbad272008-07-23 21:37:49 +0000745 baseIndex += InstrSlots::NUM;
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000746 while (++mi != MBB->end()) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000747 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
748 getInstructionFromIndex(baseIndex) == 0)
749 baseIndex += InstrSlots::NUM;
Evan Cheng6130f662008-03-05 00:59:57 +0000750 if (mi->killsRegister(interval.reg, tri_)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000751 DOUT << " killed";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000752 end = getUseIndex(baseIndex) + 1;
753 goto exit;
Evan Chengc45288e2009-04-27 20:42:46 +0000754 } else {
755 int DefIdx = mi->findRegisterDefOperandIdx(interval.reg, false, tri_);
756 if (DefIdx != -1) {
757 if (mi->isRegTiedToUseOperand(DefIdx)) {
758 // Two-address instruction.
759 end = getDefIndex(baseIndex);
760 if (mi->getOperand(DefIdx).isEarlyClobber())
761 end = getUseIndex(baseIndex);
762 } else {
763 // Another instruction redefines the register before it is ever read.
764 // Then the register is essentially dead at the instruction that defines
765 // it. Hence its interval is:
766 // [defSlot(def), defSlot(def)+1)
767 DOUT << " dead";
768 end = start + 1;
769 }
770 goto exit;
771 }
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000772 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000773
774 baseIndex += InstrSlots::NUM;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000775 }
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000776
777 // The only case we should have a dead physreg here without a killing or
778 // instruction where we know it's dead is if it is live-in to the function
Evan Chengd521bc92009-04-27 17:36:47 +0000779 // and never used. Another possible case is the implicit use of the
780 // physical register has been deleted by two-address pass.
Dale Johannesen86b49f82008-09-24 01:07:17 +0000781 end = start + 1;
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000782
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000783exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000784 assert(start < end && "did not find end of interval?");
Chris Lattnerf768bba2005-03-09 23:05:19 +0000785
Evan Cheng24a3cc42007-04-25 07:30:23 +0000786 // Already exists? Extend old live interval.
787 LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
Evan Cheng5379f412008-12-19 20:58:01 +0000788 bool Extend = OldLR != interval.end();
789 VNInfo *ValNo = Extend
Lang Hames857c4e02009-06-17 21:01:20 +0000790 ? OldLR->valno : interval.getNextValue(start, CopyMI, true, VNInfoAllocator);
Evan Cheng5379f412008-12-19 20:58:01 +0000791 if (MO.isEarlyClobber() && Extend)
Lang Hames857c4e02009-06-17 21:01:20 +0000792 ValNo->setHasRedefByEC(true);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000793 LiveRange LR(start, end, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000794 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000795 interval.addKill(LR.valno, end);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000796 DOUT << " +" << LR << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000797}
798
Chris Lattnerf35fef72004-07-23 21:24:19 +0000799void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
800 MachineBasicBlock::iterator MI,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000801 unsigned MIIdx,
Evan Chengef0732d2008-07-10 07:35:43 +0000802 MachineOperand& MO,
803 unsigned MOIdx) {
Owen Anderson6b098de2008-06-25 23:39:39 +0000804 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Evan Chengef0732d2008-07-10 07:35:43 +0000805 handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000806 getOrCreateInterval(MO.getReg()));
807 else if (allocatableRegs_[MO.getReg()]) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000808 MachineInstr *CopyMI = NULL;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000809 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000810 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000811 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Dan Gohman97121ba2009-04-08 00:15:30 +0000812 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG ||
Evan Cheng04ee5a12009-01-20 19:12:24 +0000813 tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000814 CopyMI = MI;
Evan Chengc45288e2009-04-27 20:42:46 +0000815 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
Owen Anderson6b098de2008-06-25 23:39:39 +0000816 getOrCreateInterval(MO.getReg()), CopyMI);
Evan Cheng24a3cc42007-04-25 07:30:23 +0000817 // Def of a register also defines its sub-registers.
Owen Anderson6b098de2008-06-25 23:39:39 +0000818 for (const unsigned* AS = tri_->getSubRegisters(MO.getReg()); *AS; ++AS)
Evan Cheng6130f662008-03-05 00:59:57 +0000819 // If MI also modifies the sub-register explicitly, avoid processing it
820 // more than once. Do not pass in TRI here so it checks for exact match.
821 if (!MI->modifiesRegister(*AS))
Evan Chengc45288e2009-04-27 20:42:46 +0000822 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
Owen Anderson6b098de2008-06-25 23:39:39 +0000823 getOrCreateInterval(*AS), 0);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000824 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000825}
826
Evan Chengb371f452007-02-19 21:49:54 +0000827void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000828 unsigned MIIdx,
Evan Cheng24a3cc42007-04-25 07:30:23 +0000829 LiveInterval &interval, bool isAlias) {
Evan Chengb371f452007-02-19 21:49:54 +0000830 DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg));
831
832 // Look for kills, if it reaches a def before it's killed, then it shouldn't
833 // be considered a livein.
834 MachineBasicBlock::iterator mi = MBB->begin();
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000835 unsigned baseIndex = MIIdx;
836 unsigned start = baseIndex;
Owen Anderson99500ae2008-09-15 22:00:38 +0000837 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
838 getInstructionFromIndex(baseIndex) == 0)
839 baseIndex += InstrSlots::NUM;
840 unsigned end = baseIndex;
Evan Cheng0076c612009-03-05 03:34:26 +0000841 bool SeenDefUse = false;
Owen Anderson99500ae2008-09-15 22:00:38 +0000842
Evan Chengb371f452007-02-19 21:49:54 +0000843 while (mi != MBB->end()) {
Evan Cheng6130f662008-03-05 00:59:57 +0000844 if (mi->killsRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000845 DOUT << " killed";
846 end = getUseIndex(baseIndex) + 1;
Evan Cheng0076c612009-03-05 03:34:26 +0000847 SeenDefUse = true;
Lang Hamesd21c3162009-06-18 22:01:47 +0000848 break;
Evan Cheng6130f662008-03-05 00:59:57 +0000849 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000850 // Another instruction redefines the register before it is ever read.
851 // Then the register is essentially dead at the instruction that defines
852 // it. Hence its interval is:
853 // [defSlot(def), defSlot(def)+1)
854 DOUT << " dead";
855 end = getDefIndex(start) + 1;
Evan Cheng0076c612009-03-05 03:34:26 +0000856 SeenDefUse = true;
Lang Hamesd21c3162009-06-18 22:01:47 +0000857 break;
Evan Chengb371f452007-02-19 21:49:54 +0000858 }
859
860 baseIndex += InstrSlots::NUM;
861 ++mi;
Evan Cheng0076c612009-03-05 03:34:26 +0000862 if (mi != MBB->end()) {
863 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
864 getInstructionFromIndex(baseIndex) == 0)
865 baseIndex += InstrSlots::NUM;
866 }
Evan Chengb371f452007-02-19 21:49:54 +0000867 }
868
Evan Cheng75611fb2007-06-27 01:16:36 +0000869 // Live-in register might not be used at all.
Evan Cheng0076c612009-03-05 03:34:26 +0000870 if (!SeenDefUse) {
Evan Cheng292da942007-06-27 18:47:28 +0000871 if (isAlias) {
872 DOUT << " dead";
Evan Cheng75611fb2007-06-27 01:16:36 +0000873 end = getDefIndex(MIIdx) + 1;
Evan Cheng292da942007-06-27 18:47:28 +0000874 } else {
875 DOUT << " live through";
876 end = baseIndex;
877 }
Evan Cheng24a3cc42007-04-25 07:30:23 +0000878 }
879
Lang Hames10382fb2009-06-19 02:17:53 +0000880 VNInfo *vni =
881 interval.getNextValue(MBB->getNumber(), 0, false, VNInfoAllocator);
Lang Hamesd21c3162009-06-18 22:01:47 +0000882 vni->setIsPHIDef(true);
883 LiveRange LR(start, end, vni);
884
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000885 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000886 interval.addKill(LR.valno, end);
Evan Cheng24c2e5c2007-08-08 07:03:29 +0000887 DOUT << " +" << LR << '\n';
Evan Chengb371f452007-02-19 21:49:54 +0000888}
889
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000890/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000891/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000892/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000893/// which a variable is live
Dale Johannesen91aac102008-09-17 21:13:11 +0000894void LiveIntervals::computeIntervals() {
Dale Johannesen91aac102008-09-17 21:13:11 +0000895
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000896 DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
897 << "********** Function: "
898 << ((Value*)mf_->getFunction())->getName() << '\n';
Owen Anderson7fbad272008-07-23 21:37:49 +0000899
Chris Lattner428b92e2006-09-15 03:57:23 +0000900 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
901 MBBI != E; ++MBBI) {
902 MachineBasicBlock *MBB = MBBI;
Owen Anderson134eb732008-09-21 20:43:24 +0000903 // Track the index of the current machine instr.
904 unsigned MIIndex = getMBBStartIdx(MBB);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000905 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000906
Chris Lattner428b92e2006-09-15 03:57:23 +0000907 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000908
Dan Gohmancb406c22007-10-03 19:26:29 +0000909 // Create intervals for live-ins to this BB first.
910 for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
911 LE = MBB->livein_end(); LI != LE; ++LI) {
912 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
913 // Multiple live-ins can alias the same register.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000914 for (const unsigned* AS = tri_->getSubRegisters(*LI); *AS; ++AS)
Dan Gohmancb406c22007-10-03 19:26:29 +0000915 if (!hasInterval(*AS))
916 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
917 true);
Chris Lattnerdffb2e82006-09-04 18:27:40 +0000918 }
919
Owen Anderson99500ae2008-09-15 22:00:38 +0000920 // Skip over empty initial indices.
921 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
922 getInstructionFromIndex(MIIndex) == 0)
923 MIIndex += InstrSlots::NUM;
924
Chris Lattner428b92e2006-09-15 03:57:23 +0000925 for (; MI != miEnd; ++MI) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000926 DOUT << MIIndex << "\t" << *MI;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000927
Evan Cheng438f7bc2006-11-10 08:43:01 +0000928 // Handle defs.
Chris Lattner428b92e2006-09-15 03:57:23 +0000929 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
930 MachineOperand &MO = MI->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000931 // handle register defs - build intervals
Dan Gohmand735b802008-10-03 15:45:36 +0000932 if (MO.isReg() && MO.getReg() && MO.isDef()) {
Evan Chengef0732d2008-07-10 07:35:43 +0000933 handleRegisterDef(MBB, MI, MIIndex, MO, i);
Dale Johannesen91aac102008-09-17 21:13:11 +0000934 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000935 }
Evan Cheng99fe34b2008-10-18 05:18:55 +0000936
937 // Skip over the empty slots after each instruction.
938 unsigned Slots = MI->getDesc().getNumDefs();
939 if (Slots == 0)
940 Slots = 1;
941 MIIndex += InstrSlots::NUM * Slots;
Owen Anderson7fbad272008-07-23 21:37:49 +0000942
943 // Skip over empty indices.
944 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
945 getInstructionFromIndex(MIIndex) == 0)
946 MIIndex += InstrSlots::NUM;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000947 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000948 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000949}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000950
Evan Chengd0e32c52008-10-29 05:06:14 +0000951bool LiveIntervals::findLiveInMBBs(unsigned Start, unsigned End,
Evan Chenga5bfc972007-10-17 06:53:44 +0000952 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
Evan Cheng4ca980e2007-10-17 02:10:22 +0000953 std::vector<IdxMBBPair>::const_iterator I =
Evan Chengd0e32c52008-10-29 05:06:14 +0000954 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), Start);
Evan Cheng4ca980e2007-10-17 02:10:22 +0000955
956 bool ResVal = false;
957 while (I != Idx2MBBMap.end()) {
Dan Gohman2ad82452008-11-26 05:50:31 +0000958 if (I->first >= End)
Evan Cheng4ca980e2007-10-17 02:10:22 +0000959 break;
960 MBBs.push_back(I->second);
961 ResVal = true;
962 ++I;
963 }
964 return ResVal;
965}
966
Evan Chengd0e32c52008-10-29 05:06:14 +0000967bool LiveIntervals::findReachableMBBs(unsigned Start, unsigned End,
968 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
969 std::vector<IdxMBBPair>::const_iterator I =
970 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), Start);
971
972 bool ResVal = false;
973 while (I != Idx2MBBMap.end()) {
974 if (I->first > End)
975 break;
976 MachineBasicBlock *MBB = I->second;
977 if (getMBBEndIdx(MBB) > End)
978 break;
979 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
980 SE = MBB->succ_end(); SI != SE; ++SI)
981 MBBs.push_back(*SI);
982 ResVal = true;
983 ++I;
984 }
985 return ResVal;
986}
987
Owen Anderson03857b22008-08-13 21:49:13 +0000988LiveInterval* LiveIntervals::createInterval(unsigned reg) {
Evan Cheng0a1fcce2009-02-08 11:04:35 +0000989 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? HUGE_VALF : 0.0F;
Owen Anderson03857b22008-08-13 21:49:13 +0000990 return new LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000991}
Evan Chengf2fbca62007-11-12 06:35:08 +0000992
Evan Cheng0a1fcce2009-02-08 11:04:35 +0000993/// dupInterval - Duplicate a live interval. The caller is responsible for
994/// managing the allocated memory.
995LiveInterval* LiveIntervals::dupInterval(LiveInterval *li) {
996 LiveInterval *NewLI = createInterval(li->reg);
Evan Cheng90f95f82009-06-14 20:22:55 +0000997 NewLI->Copy(*li, mri_, getVNInfoAllocator());
Evan Cheng0a1fcce2009-02-08 11:04:35 +0000998 return NewLI;
999}
1000
Evan Chengc8d044e2008-02-15 18:24:29 +00001001/// getVNInfoSourceReg - Helper function that parses the specified VNInfo
1002/// copy field and returns the source register that defines it.
1003unsigned LiveIntervals::getVNInfoSourceReg(const VNInfo *VNI) const {
1004 if (!VNI->copy)
1005 return 0;
1006
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001007 if (VNI->copy->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
1008 // If it's extracting out of a physical register, return the sub-register.
1009 unsigned Reg = VNI->copy->getOperand(1).getReg();
1010 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1011 Reg = tri_->getSubReg(Reg, VNI->copy->getOperand(2).getImm());
1012 return Reg;
Dan Gohman97121ba2009-04-08 00:15:30 +00001013 } else if (VNI->copy->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
1014 VNI->copy->getOpcode() == TargetInstrInfo::SUBREG_TO_REG)
Evan Cheng7e073ba2008-04-09 20:57:25 +00001015 return VNI->copy->getOperand(2).getReg();
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001016
Evan Cheng04ee5a12009-01-20 19:12:24 +00001017 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
1018 if (tii_->isMoveInstr(*VNI->copy, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +00001019 return SrcReg;
1020 assert(0 && "Unrecognized copy instruction!");
1021 return 0;
1022}
Evan Chengf2fbca62007-11-12 06:35:08 +00001023
1024//===----------------------------------------------------------------------===//
1025// Register allocator hooks.
1026//
1027
Evan Chengd70dbb52008-02-22 09:24:50 +00001028/// getReMatImplicitUse - If the remat definition MI has one (for now, we only
1029/// allow one) virtual register operand, then its uses are implicitly using
1030/// the register. Returns the virtual register.
1031unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
1032 MachineInstr *MI) const {
1033 unsigned RegOp = 0;
1034 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1035 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001036 if (!MO.isReg() || !MO.isUse())
Evan Chengd70dbb52008-02-22 09:24:50 +00001037 continue;
1038 unsigned Reg = MO.getReg();
1039 if (Reg == 0 || Reg == li.reg)
1040 continue;
Chris Lattner1873d0c2009-06-27 04:06:41 +00001041
1042 if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
1043 !allocatableRegs_[Reg])
1044 continue;
Evan Chengd70dbb52008-02-22 09:24:50 +00001045 // FIXME: For now, only remat MI with at most one register operand.
1046 assert(!RegOp &&
1047 "Can't rematerialize instruction with multiple register operand!");
1048 RegOp = MO.getReg();
Dan Gohman6d69ba82008-07-25 00:02:30 +00001049#ifndef NDEBUG
Evan Chengd70dbb52008-02-22 09:24:50 +00001050 break;
Dan Gohman6d69ba82008-07-25 00:02:30 +00001051#endif
Evan Chengd70dbb52008-02-22 09:24:50 +00001052 }
1053 return RegOp;
1054}
1055
1056/// isValNoAvailableAt - Return true if the val# of the specified interval
1057/// which reaches the given instruction also reaches the specified use index.
1058bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
1059 unsigned UseIdx) const {
1060 unsigned Index = getInstructionIndex(MI);
1061 VNInfo *ValNo = li.FindLiveRangeContaining(Index)->valno;
1062 LiveInterval::const_iterator UI = li.FindLiveRangeContaining(UseIdx);
1063 return UI != li.end() && UI->valno == ValNo;
1064}
1065
Evan Chengf2fbca62007-11-12 06:35:08 +00001066/// isReMaterializable - Returns true if the definition MI of the specified
1067/// val# of the specified interval is re-materializable.
1068bool LiveIntervals::isReMaterializable(const LiveInterval &li,
Evan Cheng5ef3a042007-12-06 00:01:56 +00001069 const VNInfo *ValNo, MachineInstr *MI,
Evan Chengdc377862008-09-30 15:44:16 +00001070 SmallVectorImpl<LiveInterval*> &SpillIs,
Evan Cheng5ef3a042007-12-06 00:01:56 +00001071 bool &isLoad) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001072 if (DisableReMat)
1073 return false;
1074
Evan Cheng20ccded2008-03-15 00:19:36 +00001075 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
Evan Chengd70dbb52008-02-22 09:24:50 +00001076 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +00001077
1078 int FrameIdx = 0;
1079 if (tii_->isLoadFromStackSlot(MI, FrameIdx) &&
Evan Cheng249ded32008-02-23 03:38:34 +00001080 mf_->getFrameInfo()->isImmutableObjectIndex(FrameIdx))
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001081 // FIXME: Let target specific isReallyTriviallyReMaterializable determines
1082 // this but remember this is not safe to fold into a two-address
1083 // instruction.
Evan Cheng249ded32008-02-23 03:38:34 +00001084 // This is a load from fixed stack slot. It can be rematerialized.
Evan Chengdd3465e2008-02-23 01:44:27 +00001085 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +00001086
Dan Gohman6d69ba82008-07-25 00:02:30 +00001087 // If the target-specific rules don't identify an instruction as
1088 // being trivially rematerializable, use some target-independent
1089 // rules.
1090 if (!MI->getDesc().isRematerializable() ||
1091 !tii_->isTriviallyReMaterializable(MI)) {
Dan Gohman4c8f8702008-07-25 15:08:37 +00001092 if (!EnableAggressiveRemat)
1093 return false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001094
Dan Gohman0471a792008-07-28 18:43:51 +00001095 // If the instruction accesses memory but the memoperands have been lost,
Dan Gohman6d69ba82008-07-25 00:02:30 +00001096 // we can't analyze it.
1097 const TargetInstrDesc &TID = MI->getDesc();
1098 if ((TID.mayLoad() || TID.mayStore()) && MI->memoperands_empty())
1099 return false;
1100
1101 // Avoid instructions obviously unsafe for remat.
1102 if (TID.hasUnmodeledSideEffects() || TID.isNotDuplicable())
1103 return false;
1104
1105 // If the instruction accesses memory and the memory could be non-constant,
1106 // assume the instruction is not rematerializable.
Evan Chengdc377862008-09-30 15:44:16 +00001107 for (std::list<MachineMemOperand>::const_iterator
1108 I = MI->memoperands_begin(), E = MI->memoperands_end(); I != E; ++I){
Dan Gohman6d69ba82008-07-25 00:02:30 +00001109 const MachineMemOperand &MMO = *I;
1110 if (MMO.isVolatile() || MMO.isStore())
1111 return false;
1112 const Value *V = MMO.getValue();
1113 if (!V)
1114 return false;
1115 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
1116 if (!PSV->isConstant(mf_->getFrameInfo()))
Evan Chengd70dbb52008-02-22 09:24:50 +00001117 return false;
Dan Gohman6d69ba82008-07-25 00:02:30 +00001118 } else if (!aa_->pointsToConstantMemory(V))
1119 return false;
1120 }
1121
1122 // If any of the registers accessed are non-constant, conservatively assume
1123 // the instruction is not rematerializable.
1124 unsigned ImpUse = 0;
1125 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1126 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001127 if (MO.isReg()) {
Dan Gohman6d69ba82008-07-25 00:02:30 +00001128 unsigned Reg = MO.getReg();
1129 if (Reg == 0)
1130 continue;
1131 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1132 return false;
1133
1134 // Only allow one def, and that in the first operand.
1135 if (MO.isDef() != (i == 0))
1136 return false;
1137
1138 // Only allow constant-valued registers.
1139 bool IsLiveIn = mri_->isLiveIn(Reg);
1140 MachineRegisterInfo::def_iterator I = mri_->def_begin(Reg),
1141 E = mri_->def_end();
1142
Dan Gohmanc93ced5b2008-12-08 04:53:23 +00001143 // For the def, it should be the only def of that register.
Dan Gohman6d69ba82008-07-25 00:02:30 +00001144 if (MO.isDef() && (next(I) != E || IsLiveIn))
1145 return false;
1146
1147 if (MO.isUse()) {
1148 // Only allow one use other register use, as that's all the
1149 // remat mechanisms support currently.
1150 if (Reg != li.reg) {
1151 if (ImpUse == 0)
1152 ImpUse = Reg;
1153 else if (Reg != ImpUse)
1154 return false;
1155 }
Dan Gohmanc93ced5b2008-12-08 04:53:23 +00001156 // For the use, there should be only one associated def.
Dan Gohman6d69ba82008-07-25 00:02:30 +00001157 if (I != E && (next(I) != E || IsLiveIn))
1158 return false;
1159 }
Evan Chengd70dbb52008-02-22 09:24:50 +00001160 }
1161 }
Evan Cheng5ef3a042007-12-06 00:01:56 +00001162 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001163
Dan Gohman6d69ba82008-07-25 00:02:30 +00001164 unsigned ImpUse = getReMatImplicitUse(li, MI);
1165 if (ImpUse) {
1166 const LiveInterval &ImpLi = getInterval(ImpUse);
1167 for (MachineRegisterInfo::use_iterator ri = mri_->use_begin(li.reg),
1168 re = mri_->use_end(); ri != re; ++ri) {
1169 MachineInstr *UseMI = &*ri;
1170 unsigned UseIdx = getInstructionIndex(UseMI);
1171 if (li.FindLiveRangeContaining(UseIdx)->valno != ValNo)
1172 continue;
1173 if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
1174 return false;
1175 }
Evan Chengdc377862008-09-30 15:44:16 +00001176
1177 // If a register operand of the re-materialized instruction is going to
1178 // be spilled next, then it's not legal to re-materialize this instruction.
1179 for (unsigned i = 0, e = SpillIs.size(); i != e; ++i)
1180 if (ImpUse == SpillIs[i]->reg)
1181 return false;
Dan Gohman6d69ba82008-07-25 00:02:30 +00001182 }
1183 return true;
Evan Cheng5ef3a042007-12-06 00:01:56 +00001184}
1185
Evan Cheng06587492008-10-24 02:05:00 +00001186/// isReMaterializable - Returns true if the definition MI of the specified
1187/// val# of the specified interval is re-materializable.
1188bool LiveIntervals::isReMaterializable(const LiveInterval &li,
1189 const VNInfo *ValNo, MachineInstr *MI) {
1190 SmallVector<LiveInterval*, 4> Dummy1;
1191 bool Dummy2;
1192 return isReMaterializable(li, ValNo, MI, Dummy1, Dummy2);
1193}
1194
Evan Cheng5ef3a042007-12-06 00:01:56 +00001195/// isReMaterializable - Returns true if every definition of MI of every
1196/// val# of the specified interval is re-materializable.
Evan Chengdc377862008-09-30 15:44:16 +00001197bool LiveIntervals::isReMaterializable(const LiveInterval &li,
1198 SmallVectorImpl<LiveInterval*> &SpillIs,
1199 bool &isLoad) {
Evan Cheng5ef3a042007-12-06 00:01:56 +00001200 isLoad = false;
1201 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1202 i != e; ++i) {
1203 const VNInfo *VNI = *i;
Lang Hames857c4e02009-06-17 21:01:20 +00001204 if (VNI->isUnused())
Evan Cheng5ef3a042007-12-06 00:01:56 +00001205 continue; // Dead val#.
1206 // Is the def for the val# rematerializable?
Lang Hames857c4e02009-06-17 21:01:20 +00001207 if (!VNI->isDefAccurate())
Evan Cheng5ef3a042007-12-06 00:01:56 +00001208 return false;
Lang Hames857c4e02009-06-17 21:01:20 +00001209 MachineInstr *ReMatDefMI = getInstructionFromIndex(VNI->def);
Evan Cheng5ef3a042007-12-06 00:01:56 +00001210 bool DefIsLoad = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001211 if (!ReMatDefMI ||
Evan Chengdc377862008-09-30 15:44:16 +00001212 !isReMaterializable(li, VNI, ReMatDefMI, SpillIs, DefIsLoad))
Evan Cheng5ef3a042007-12-06 00:01:56 +00001213 return false;
1214 isLoad |= DefIsLoad;
Evan Chengf2fbca62007-11-12 06:35:08 +00001215 }
1216 return true;
1217}
1218
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001219/// FilterFoldedOps - Filter out two-address use operands. Return
1220/// true if it finds any issue with the operands that ought to prevent
1221/// folding.
1222static bool FilterFoldedOps(MachineInstr *MI,
1223 SmallVector<unsigned, 2> &Ops,
1224 unsigned &MRInfo,
1225 SmallVector<unsigned, 2> &FoldOps) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001226 MRInfo = 0;
Evan Chengaee4af62007-12-02 08:30:39 +00001227 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1228 unsigned OpIdx = Ops[i];
Evan Chengd70dbb52008-02-22 09:24:50 +00001229 MachineOperand &MO = MI->getOperand(OpIdx);
Evan Chengaee4af62007-12-02 08:30:39 +00001230 // FIXME: fold subreg use.
Evan Chengd70dbb52008-02-22 09:24:50 +00001231 if (MO.getSubReg())
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001232 return true;
Evan Chengd70dbb52008-02-22 09:24:50 +00001233 if (MO.isDef())
Evan Chengaee4af62007-12-02 08:30:39 +00001234 MRInfo |= (unsigned)VirtRegMap::isMod;
1235 else {
1236 // Filter out two-address use operand(s).
Evan Chenga24752f2009-03-19 20:30:06 +00001237 if (MI->isRegTiedToDefOperand(OpIdx)) {
Evan Chengaee4af62007-12-02 08:30:39 +00001238 MRInfo = VirtRegMap::isModRef;
1239 continue;
1240 }
1241 MRInfo |= (unsigned)VirtRegMap::isRef;
1242 }
1243 FoldOps.push_back(OpIdx);
Evan Chenge62f97c2007-12-01 02:07:52 +00001244 }
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001245 return false;
1246}
1247
1248
1249/// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
1250/// slot / to reg or any rematerialized load into ith operand of specified
1251/// MI. If it is successul, MI is updated with the newly created MI and
1252/// returns true.
1253bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
1254 VirtRegMap &vrm, MachineInstr *DefMI,
1255 unsigned InstrIdx,
1256 SmallVector<unsigned, 2> &Ops,
1257 bool isSS, int Slot, unsigned Reg) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001258 // If it is an implicit def instruction, just delete it.
Evan Cheng20ccded2008-03-15 00:19:36 +00001259 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001260 RemoveMachineInstrFromMaps(MI);
1261 vrm.RemoveMachineInstrFromMaps(MI);
1262 MI->eraseFromParent();
1263 ++numFolds;
1264 return true;
1265 }
1266
1267 // Filter the list of operand indexes that are to be folded. Abort if
1268 // any operand will prevent folding.
1269 unsigned MRInfo = 0;
1270 SmallVector<unsigned, 2> FoldOps;
1271 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1272 return false;
Evan Chenge62f97c2007-12-01 02:07:52 +00001273
Evan Cheng427f4c12008-03-31 23:19:51 +00001274 // The only time it's safe to fold into a two address instruction is when
1275 // it's folding reload and spill from / into a spill stack slot.
1276 if (DefMI && (MRInfo & VirtRegMap::isMod))
Evan Cheng249ded32008-02-23 03:38:34 +00001277 return false;
1278
Evan Chengf2f8c2a2008-02-08 22:05:27 +00001279 MachineInstr *fmi = isSS ? tii_->foldMemoryOperand(*mf_, MI, FoldOps, Slot)
1280 : tii_->foldMemoryOperand(*mf_, MI, FoldOps, DefMI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001281 if (fmi) {
Evan Chengd3653122008-02-27 03:04:06 +00001282 // Remember this instruction uses the spill slot.
1283 if (isSS) vrm.addSpillSlotUse(Slot, fmi);
1284
Evan Chengf2fbca62007-11-12 06:35:08 +00001285 // Attempt to fold the memory reference into the instruction. If
1286 // we can do this, we don't need to insert spill code.
Evan Chengf2fbca62007-11-12 06:35:08 +00001287 MachineBasicBlock &MBB = *MI->getParent();
Evan Cheng84802932008-01-10 08:24:38 +00001288 if (isSS && !mf_->getFrameInfo()->isImmutableObjectIndex(Slot))
Evan Chengaee4af62007-12-02 08:30:39 +00001289 vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
Evan Cheng81a03822007-11-17 00:40:40 +00001290 vrm.transferSpillPts(MI, fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001291 vrm.transferRestorePts(MI, fmi);
Evan Chengc1f53c72008-03-11 21:34:46 +00001292 vrm.transferEmergencySpills(MI, fmi);
Evan Chengf2fbca62007-11-12 06:35:08 +00001293 mi2iMap_.erase(MI);
Evan Chengcddbb832007-11-30 21:23:43 +00001294 i2miMap_[InstrIdx /InstrSlots::NUM] = fmi;
1295 mi2iMap_[fmi] = InstrIdx;
Evan Chengf2fbca62007-11-12 06:35:08 +00001296 MI = MBB.insert(MBB.erase(MI), fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001297 ++numFolds;
Evan Chengf2fbca62007-11-12 06:35:08 +00001298 return true;
1299 }
1300 return false;
1301}
1302
Evan Cheng018f9b02007-12-05 03:22:34 +00001303/// canFoldMemoryOperand - Returns true if the specified load / store
1304/// folding is possible.
1305bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI,
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001306 SmallVector<unsigned, 2> &Ops,
Evan Cheng3c75ba82008-04-01 21:37:32 +00001307 bool ReMat) const {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001308 // Filter the list of operand indexes that are to be folded. Abort if
1309 // any operand will prevent folding.
1310 unsigned MRInfo = 0;
Evan Cheng018f9b02007-12-05 03:22:34 +00001311 SmallVector<unsigned, 2> FoldOps;
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001312 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1313 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001314
Evan Cheng3c75ba82008-04-01 21:37:32 +00001315 // It's only legal to remat for a use, not a def.
1316 if (ReMat && (MRInfo & VirtRegMap::isMod))
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001317 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001318
Evan Chengd70dbb52008-02-22 09:24:50 +00001319 return tii_->canFoldMemoryOperand(MI, FoldOps);
1320}
1321
Evan Cheng81a03822007-11-17 00:40:40 +00001322bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
1323 SmallPtrSet<MachineBasicBlock*, 4> MBBs;
1324 for (LiveInterval::Ranges::const_iterator
1325 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1326 std::vector<IdxMBBPair>::const_iterator II =
1327 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), I->start);
1328 if (II == Idx2MBBMap.end())
1329 continue;
1330 if (I->end > II->first) // crossing a MBB.
1331 return false;
1332 MBBs.insert(II->second);
1333 if (MBBs.size() > 1)
1334 return false;
1335 }
1336 return true;
1337}
1338
Evan Chengd70dbb52008-02-22 09:24:50 +00001339/// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
1340/// interval on to-be re-materialized operands of MI) with new register.
1341void LiveIntervals::rewriteImplicitOps(const LiveInterval &li,
1342 MachineInstr *MI, unsigned NewVReg,
1343 VirtRegMap &vrm) {
1344 // There is an implicit use. That means one of the other operand is
1345 // being remat'ed and the remat'ed instruction has li.reg as an
1346 // use operand. Make sure we rewrite that as well.
1347 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1348 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001349 if (!MO.isReg())
Evan Chengd70dbb52008-02-22 09:24:50 +00001350 continue;
1351 unsigned Reg = MO.getReg();
1352 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
1353 continue;
1354 if (!vrm.isReMaterialized(Reg))
1355 continue;
1356 MachineInstr *ReMatMI = vrm.getReMaterializedMI(Reg);
Evan Cheng6130f662008-03-05 00:59:57 +00001357 MachineOperand *UseMO = ReMatMI->findRegisterUseOperand(li.reg);
1358 if (UseMO)
1359 UseMO->setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001360 }
1361}
1362
Evan Chengf2fbca62007-11-12 06:35:08 +00001363/// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
1364/// for addIntervalsForSpills to rewrite uses / defs for the given live range.
Evan Cheng018f9b02007-12-05 03:22:34 +00001365bool LiveIntervals::
Evan Chengd70dbb52008-02-22 09:24:50 +00001366rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
1367 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
Evan Cheng81a03822007-11-17 00:40:40 +00001368 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001369 unsigned Slot, int LdSlot,
1370 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001371 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001372 const TargetRegisterClass* rc,
1373 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001374 const MachineLoopInfo *loopInfo,
Evan Cheng313d4b82008-02-23 00:33:04 +00001375 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
Owen Anderson28998312008-08-13 22:28:50 +00001376 DenseMap<unsigned,unsigned> &MBBVRegsMap,
Evan Chengc781a242009-05-03 18:32:42 +00001377 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001378 bool CanFold = false;
Evan Chengf2fbca62007-11-12 06:35:08 +00001379 RestartInstruction:
1380 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1381 MachineOperand& mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001382 if (!mop.isReg())
Evan Chengf2fbca62007-11-12 06:35:08 +00001383 continue;
1384 unsigned Reg = mop.getReg();
1385 unsigned RegI = Reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001386 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
Evan Chengf2fbca62007-11-12 06:35:08 +00001387 continue;
Evan Chengf2fbca62007-11-12 06:35:08 +00001388 if (Reg != li.reg)
1389 continue;
1390
1391 bool TryFold = !DefIsReMat;
Evan Chengcb3c3302007-11-29 23:02:50 +00001392 bool FoldSS = true; // Default behavior unless it's a remat.
Evan Chengf2fbca62007-11-12 06:35:08 +00001393 int FoldSlot = Slot;
1394 if (DefIsReMat) {
1395 // If this is the rematerializable definition MI itself and
1396 // all of its uses are rematerialized, simply delete it.
Evan Cheng81a03822007-11-17 00:40:40 +00001397 if (MI == ReMatOrigDefMI && CanDelete) {
Evan Chengcddbb832007-11-30 21:23:43 +00001398 DOUT << "\t\t\t\tErasing re-materlizable def: ";
1399 DOUT << MI << '\n';
Evan Chengf2fbca62007-11-12 06:35:08 +00001400 RemoveMachineInstrFromMaps(MI);
Evan Chengcada2452007-11-28 01:28:46 +00001401 vrm.RemoveMachineInstrFromMaps(MI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001402 MI->eraseFromParent();
1403 break;
1404 }
1405
1406 // If def for this use can't be rematerialized, then try folding.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001407 // If def is rematerializable and it's a load, also try folding.
Evan Chengcb3c3302007-11-29 23:02:50 +00001408 TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad));
Evan Chengf2fbca62007-11-12 06:35:08 +00001409 if (isLoad) {
1410 // Try fold loads (from stack slot, constant pool, etc.) into uses.
1411 FoldSS = isLoadSS;
1412 FoldSlot = LdSlot;
1413 }
1414 }
1415
Evan Chengf2fbca62007-11-12 06:35:08 +00001416 // Scan all of the operands of this instruction rewriting operands
1417 // to use NewVReg instead of li.reg as appropriate. We do this for
1418 // two reasons:
1419 //
1420 // 1. If the instr reads the same spilled vreg multiple times, we
1421 // want to reuse the NewVReg.
1422 // 2. If the instr is a two-addr instruction, we are required to
1423 // keep the src/dst regs pinned.
1424 //
1425 // Keep track of whether we replace a use and/or def so that we can
1426 // create the spill interval with the appropriate range.
Evan Chengcddbb832007-11-30 21:23:43 +00001427
Evan Cheng81a03822007-11-17 00:40:40 +00001428 HasUse = mop.isUse();
1429 HasDef = mop.isDef();
Evan Chengaee4af62007-12-02 08:30:39 +00001430 SmallVector<unsigned, 2> Ops;
1431 Ops.push_back(i);
Evan Chengf2fbca62007-11-12 06:35:08 +00001432 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
Evan Chengaee4af62007-12-02 08:30:39 +00001433 const MachineOperand &MOj = MI->getOperand(j);
Dan Gohmand735b802008-10-03 15:45:36 +00001434 if (!MOj.isReg())
Evan Chengf2fbca62007-11-12 06:35:08 +00001435 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001436 unsigned RegJ = MOj.getReg();
Dan Gohman6f0d0242008-02-10 18:45:23 +00001437 if (RegJ == 0 || TargetRegisterInfo::isPhysicalRegister(RegJ))
Evan Chengf2fbca62007-11-12 06:35:08 +00001438 continue;
1439 if (RegJ == RegI) {
Evan Chengaee4af62007-12-02 08:30:39 +00001440 Ops.push_back(j);
1441 HasUse |= MOj.isUse();
1442 HasDef |= MOj.isDef();
Evan Chengf2fbca62007-11-12 06:35:08 +00001443 }
1444 }
1445
Evan Cheng79a796c2008-07-12 01:56:02 +00001446 if (HasUse && !li.liveAt(getUseIndex(index)))
1447 // Must be defined by an implicit def. It should not be spilled. Note,
1448 // this is for correctness reason. e.g.
1449 // 8 %reg1024<def> = IMPLICIT_DEF
1450 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1451 // The live range [12, 14) are not part of the r1024 live interval since
1452 // it's defined by an implicit def. It will not conflicts with live
1453 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001454 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001455 // the INSERT_SUBREG and both target registers that would overlap.
1456 HasUse = false;
1457
David Greene26b86a02008-10-27 17:38:59 +00001458 // Create a new virtual register for the spill interval.
1459 // Create the new register now so we can map the fold instruction
1460 // to the new register so when it is unfolded we get the correct
1461 // answer.
1462 bool CreatedNewVReg = false;
1463 if (NewVReg == 0) {
1464 NewVReg = mri_->createVirtualRegister(rc);
1465 vrm.grow();
1466 CreatedNewVReg = true;
1467 }
1468
Evan Cheng9c3c2212008-06-06 07:54:39 +00001469 if (!TryFold)
1470 CanFold = false;
1471 else {
Evan Cheng018f9b02007-12-05 03:22:34 +00001472 // Do not fold load / store here if we are splitting. We'll find an
1473 // optimal point to insert a load / store later.
1474 if (!TrySplit) {
1475 if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
David Greene26b86a02008-10-27 17:38:59 +00001476 Ops, FoldSS, FoldSlot, NewVReg)) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001477 // Folding the load/store can completely change the instruction in
1478 // unpredictable ways, rescan it from the beginning.
David Greene26b86a02008-10-27 17:38:59 +00001479
1480 if (FoldSS) {
1481 // We need to give the new vreg the same stack slot as the
1482 // spilled interval.
1483 vrm.assignVirt2StackSlot(NewVReg, FoldSlot);
1484 }
1485
Evan Cheng018f9b02007-12-05 03:22:34 +00001486 HasUse = false;
1487 HasDef = false;
1488 CanFold = false;
Evan Chengc781a242009-05-03 18:32:42 +00001489 if (isNotInMIMap(MI))
Evan Cheng7e073ba2008-04-09 20:57:25 +00001490 break;
Evan Cheng018f9b02007-12-05 03:22:34 +00001491 goto RestartInstruction;
1492 }
1493 } else {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001494 // We'll try to fold it later if it's profitable.
Evan Cheng3c75ba82008-04-01 21:37:32 +00001495 CanFold = canFoldMemoryOperand(MI, Ops, DefIsReMat);
Evan Cheng018f9b02007-12-05 03:22:34 +00001496 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001497 }
Evan Chengcddbb832007-11-30 21:23:43 +00001498
Evan Chengcddbb832007-11-30 21:23:43 +00001499 mop.setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001500 if (mop.isImplicit())
1501 rewriteImplicitOps(li, MI, NewVReg, vrm);
Evan Chengcddbb832007-11-30 21:23:43 +00001502
1503 // Reuse NewVReg for other reads.
Evan Chengd70dbb52008-02-22 09:24:50 +00001504 for (unsigned j = 0, e = Ops.size(); j != e; ++j) {
1505 MachineOperand &mopj = MI->getOperand(Ops[j]);
1506 mopj.setReg(NewVReg);
1507 if (mopj.isImplicit())
1508 rewriteImplicitOps(li, MI, NewVReg, vrm);
1509 }
Evan Chengcddbb832007-11-30 21:23:43 +00001510
Evan Cheng81a03822007-11-17 00:40:40 +00001511 if (CreatedNewVReg) {
1512 if (DefIsReMat) {
1513 vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI/*, CanDelete*/);
Evan Chengd70dbb52008-02-22 09:24:50 +00001514 if (ReMatIds[VNI->id] == VirtRegMap::MAX_STACK_SLOT) {
Evan Cheng81a03822007-11-17 00:40:40 +00001515 // Each valnum may have its own remat id.
Evan Chengd70dbb52008-02-22 09:24:50 +00001516 ReMatIds[VNI->id] = vrm.assignVirtReMatId(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001517 } else {
Evan Chengd70dbb52008-02-22 09:24:50 +00001518 vrm.assignVirtReMatId(NewVReg, ReMatIds[VNI->id]);
Evan Cheng81a03822007-11-17 00:40:40 +00001519 }
1520 if (!CanDelete || (HasUse && HasDef)) {
1521 // If this is a two-addr instruction then its use operands are
1522 // rematerializable but its def is not. It should be assigned a
1523 // stack slot.
1524 vrm.assignVirt2StackSlot(NewVReg, Slot);
1525 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001526 } else {
Evan Chengf2fbca62007-11-12 06:35:08 +00001527 vrm.assignVirt2StackSlot(NewVReg, Slot);
1528 }
Evan Chengcb3c3302007-11-29 23:02:50 +00001529 } else if (HasUse && HasDef &&
1530 vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) {
1531 // If this interval hasn't been assigned a stack slot (because earlier
1532 // def is a deleted remat def), do it now.
1533 assert(Slot != VirtRegMap::NO_STACK_SLOT);
1534 vrm.assignVirt2StackSlot(NewVReg, Slot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001535 }
1536
Evan Cheng313d4b82008-02-23 00:33:04 +00001537 // Re-matting an instruction with virtual register use. Add the
1538 // register as an implicit use on the use MI.
1539 if (DefIsReMat && ImpUse)
1540 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1541
Evan Cheng5b69eba2009-04-21 22:46:52 +00001542 // Create a new register interval for this spill / remat.
Evan Chengf2fbca62007-11-12 06:35:08 +00001543 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001544 if (CreatedNewVReg) {
1545 NewLIs.push_back(&nI);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001546 MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg));
Evan Cheng81a03822007-11-17 00:40:40 +00001547 if (TrySplit)
1548 vrm.setIsSplitFromReg(NewVReg, li.reg);
1549 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001550
1551 if (HasUse) {
Evan Cheng81a03822007-11-17 00:40:40 +00001552 if (CreatedNewVReg) {
1553 LiveRange LR(getLoadIndex(index), getUseIndex(index)+1,
Lang Hames857c4e02009-06-17 21:01:20 +00001554 nI.getNextValue(0, 0, false, VNInfoAllocator));
Evan Cheng81a03822007-11-17 00:40:40 +00001555 DOUT << " +" << LR;
1556 nI.addRange(LR);
1557 } else {
1558 // Extend the split live interval to this def / use.
1559 unsigned End = getUseIndex(index)+1;
1560 LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
1561 nI.getValNumInfo(nI.getNumValNums()-1));
1562 DOUT << " +" << LR;
1563 nI.addRange(LR);
1564 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001565 }
1566 if (HasDef) {
1567 LiveRange LR(getDefIndex(index), getStoreIndex(index),
Lang Hames857c4e02009-06-17 21:01:20 +00001568 nI.getNextValue(0, 0, false, VNInfoAllocator));
Evan Chengf2fbca62007-11-12 06:35:08 +00001569 DOUT << " +" << LR;
1570 nI.addRange(LR);
1571 }
Evan Cheng81a03822007-11-17 00:40:40 +00001572
Evan Chengf2fbca62007-11-12 06:35:08 +00001573 DOUT << "\t\t\t\tAdded new interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001574 nI.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001575 DOUT << '\n';
1576 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001577 return CanFold;
Evan Chengf2fbca62007-11-12 06:35:08 +00001578}
Evan Cheng81a03822007-11-17 00:40:40 +00001579bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001580 const VNInfo *VNI,
1581 MachineBasicBlock *MBB, unsigned Idx) const {
Evan Cheng81a03822007-11-17 00:40:40 +00001582 unsigned End = getMBBEndIdx(MBB);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001583 for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
1584 unsigned KillIdx = VNI->kills[j];
1585 if (KillIdx > Idx && KillIdx < End)
1586 return true;
Evan Cheng81a03822007-11-17 00:40:40 +00001587 }
1588 return false;
1589}
1590
Evan Cheng063284c2008-02-21 00:34:19 +00001591/// RewriteInfo - Keep track of machine instrs that will be rewritten
1592/// during spilling.
Dan Gohman844731a2008-05-13 00:00:25 +00001593namespace {
1594 struct RewriteInfo {
1595 unsigned Index;
1596 MachineInstr *MI;
1597 bool HasUse;
1598 bool HasDef;
1599 RewriteInfo(unsigned i, MachineInstr *mi, bool u, bool d)
1600 : Index(i), MI(mi), HasUse(u), HasDef(d) {}
1601 };
Evan Cheng063284c2008-02-21 00:34:19 +00001602
Dan Gohman844731a2008-05-13 00:00:25 +00001603 struct RewriteInfoCompare {
1604 bool operator()(const RewriteInfo &LHS, const RewriteInfo &RHS) const {
1605 return LHS.Index < RHS.Index;
1606 }
1607 };
1608}
Evan Cheng063284c2008-02-21 00:34:19 +00001609
Evan Chengf2fbca62007-11-12 06:35:08 +00001610void LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001611rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
Evan Chengf2fbca62007-11-12 06:35:08 +00001612 LiveInterval::Ranges::const_iterator &I,
Evan Cheng81a03822007-11-17 00:40:40 +00001613 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001614 unsigned Slot, int LdSlot,
1615 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001616 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001617 const TargetRegisterClass* rc,
1618 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001619 const MachineLoopInfo *loopInfo,
Evan Cheng81a03822007-11-17 00:40:40 +00001620 BitVector &SpillMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001621 DenseMap<unsigned, std::vector<SRInfo> > &SpillIdxes,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001622 BitVector &RestoreMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001623 DenseMap<unsigned, std::vector<SRInfo> > &RestoreIdxes,
1624 DenseMap<unsigned,unsigned> &MBBVRegsMap,
Evan Chengc781a242009-05-03 18:32:42 +00001625 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001626 bool AllCanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001627 unsigned NewVReg = 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001628 unsigned start = getBaseIndex(I->start);
Evan Chengf2fbca62007-11-12 06:35:08 +00001629 unsigned end = getBaseIndex(I->end-1) + InstrSlots::NUM;
Evan Chengf2fbca62007-11-12 06:35:08 +00001630
Evan Cheng063284c2008-02-21 00:34:19 +00001631 // First collect all the def / use in this live range that will be rewritten.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001632 // Make sure they are sorted according to instruction index.
Evan Cheng063284c2008-02-21 00:34:19 +00001633 std::vector<RewriteInfo> RewriteMIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001634 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1635 re = mri_->reg_end(); ri != re; ) {
Evan Cheng419852c2008-04-03 16:39:43 +00001636 MachineInstr *MI = &*ri;
Evan Cheng063284c2008-02-21 00:34:19 +00001637 MachineOperand &O = ri.getOperand();
1638 ++ri;
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001639 assert(!O.isImplicit() && "Spilling register that's used as implicit use?");
Evan Cheng063284c2008-02-21 00:34:19 +00001640 unsigned index = getInstructionIndex(MI);
1641 if (index < start || index >= end)
1642 continue;
Evan Cheng79a796c2008-07-12 01:56:02 +00001643 if (O.isUse() && !li.liveAt(getUseIndex(index)))
1644 // Must be defined by an implicit def. It should not be spilled. Note,
1645 // this is for correctness reason. e.g.
1646 // 8 %reg1024<def> = IMPLICIT_DEF
1647 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1648 // The live range [12, 14) are not part of the r1024 live interval since
1649 // it's defined by an implicit def. It will not conflicts with live
1650 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001651 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001652 // the INSERT_SUBREG and both target registers that would overlap.
1653 continue;
Evan Cheng063284c2008-02-21 00:34:19 +00001654 RewriteMIs.push_back(RewriteInfo(index, MI, O.isUse(), O.isDef()));
1655 }
1656 std::sort(RewriteMIs.begin(), RewriteMIs.end(), RewriteInfoCompare());
1657
Evan Cheng313d4b82008-02-23 00:33:04 +00001658 unsigned ImpUse = DefIsReMat ? getReMatImplicitUse(li, ReMatDefMI) : 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001659 // Now rewrite the defs and uses.
1660 for (unsigned i = 0, e = RewriteMIs.size(); i != e; ) {
1661 RewriteInfo &rwi = RewriteMIs[i];
1662 ++i;
1663 unsigned index = rwi.Index;
1664 bool MIHasUse = rwi.HasUse;
1665 bool MIHasDef = rwi.HasDef;
1666 MachineInstr *MI = rwi.MI;
1667 // If MI def and/or use the same register multiple times, then there
1668 // are multiple entries.
Evan Cheng313d4b82008-02-23 00:33:04 +00001669 unsigned NumUses = MIHasUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001670 while (i != e && RewriteMIs[i].MI == MI) {
1671 assert(RewriteMIs[i].Index == index);
Evan Cheng313d4b82008-02-23 00:33:04 +00001672 bool isUse = RewriteMIs[i].HasUse;
1673 if (isUse) ++NumUses;
1674 MIHasUse |= isUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001675 MIHasDef |= RewriteMIs[i].HasDef;
1676 ++i;
1677 }
Evan Cheng81a03822007-11-17 00:40:40 +00001678 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng313d4b82008-02-23 00:33:04 +00001679
Evan Cheng0a891ed2008-05-23 23:00:04 +00001680 if (ImpUse && MI != ReMatDefMI) {
Evan Cheng313d4b82008-02-23 00:33:04 +00001681 // Re-matting an instruction with virtual register use. Update the
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001682 // register interval's spill weight to HUGE_VALF to prevent it from
1683 // being spilled.
Evan Cheng313d4b82008-02-23 00:33:04 +00001684 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001685 ImpLi.weight = HUGE_VALF;
Evan Cheng313d4b82008-02-23 00:33:04 +00001686 }
1687
Evan Cheng063284c2008-02-21 00:34:19 +00001688 unsigned MBBId = MBB->getNumber();
Evan Cheng018f9b02007-12-05 03:22:34 +00001689 unsigned ThisVReg = 0;
Evan Cheng70306f82007-12-03 09:58:48 +00001690 if (TrySplit) {
Owen Anderson28998312008-08-13 22:28:50 +00001691 DenseMap<unsigned,unsigned>::iterator NVI = MBBVRegsMap.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001692 if (NVI != MBBVRegsMap.end()) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001693 ThisVReg = NVI->second;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001694 // One common case:
1695 // x = use
1696 // ...
1697 // ...
1698 // def = ...
1699 // = use
1700 // It's better to start a new interval to avoid artifically
1701 // extend the new interval.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001702 if (MIHasDef && !MIHasUse) {
1703 MBBVRegsMap.erase(MBB->getNumber());
Evan Cheng018f9b02007-12-05 03:22:34 +00001704 ThisVReg = 0;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001705 }
1706 }
Evan Chengcada2452007-11-28 01:28:46 +00001707 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001708
1709 bool IsNew = ThisVReg == 0;
1710 if (IsNew) {
1711 // This ends the previous live interval. If all of its def / use
1712 // can be folded, give it a low spill weight.
1713 if (NewVReg && TrySplit && AllCanFold) {
1714 LiveInterval &nI = getOrCreateInterval(NewVReg);
1715 nI.weight /= 10.0F;
1716 }
1717 AllCanFold = true;
1718 }
1719 NewVReg = ThisVReg;
1720
Evan Cheng81a03822007-11-17 00:40:40 +00001721 bool HasDef = false;
1722 bool HasUse = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001723 bool CanFold = rewriteInstructionForSpills(li, I->valno, TrySplit,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001724 index, end, MI, ReMatOrigDefMI, ReMatDefMI,
1725 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
1726 CanDelete, vrm, rc, ReMatIds, loopInfo, NewVReg,
Evan Chengc781a242009-05-03 18:32:42 +00001727 ImpUse, HasDef, HasUse, MBBVRegsMap, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001728 if (!HasDef && !HasUse)
1729 continue;
1730
Evan Cheng018f9b02007-12-05 03:22:34 +00001731 AllCanFold &= CanFold;
1732
Evan Cheng81a03822007-11-17 00:40:40 +00001733 // Update weight of spill interval.
1734 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng70306f82007-12-03 09:58:48 +00001735 if (!TrySplit) {
Evan Cheng81a03822007-11-17 00:40:40 +00001736 // The spill weight is now infinity as it cannot be spilled again.
1737 nI.weight = HUGE_VALF;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001738 continue;
Evan Cheng81a03822007-11-17 00:40:40 +00001739 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001740
1741 // Keep track of the last def and first use in each MBB.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001742 if (HasDef) {
1743 if (MI != ReMatOrigDefMI || !CanDelete) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001744 bool HasKill = false;
1745 if (!HasUse)
1746 HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, getDefIndex(index));
1747 else {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001748 // If this is a two-address code, then this index starts a new VNInfo.
Evan Cheng3f32d652008-06-04 09:18:41 +00001749 const VNInfo *VNI = li.findDefinedVNInfo(getDefIndex(index));
Evan Cheng0cbb1162007-11-29 01:06:25 +00001750 if (VNI)
1751 HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, getDefIndex(index));
1752 }
Owen Anderson28998312008-08-13 22:28:50 +00001753 DenseMap<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Chenge3110d02007-12-01 04:42:39 +00001754 SpillIdxes.find(MBBId);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001755 if (!HasKill) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001756 if (SII == SpillIdxes.end()) {
1757 std::vector<SRInfo> S;
1758 S.push_back(SRInfo(index, NewVReg, true));
1759 SpillIdxes.insert(std::make_pair(MBBId, S));
1760 } else if (SII->second.back().vreg != NewVReg) {
1761 SII->second.push_back(SRInfo(index, NewVReg, true));
1762 } else if ((int)index > SII->second.back().index) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001763 // If there is an earlier def and this is a two-address
1764 // instruction, then it's not possible to fold the store (which
1765 // would also fold the load).
Evan Cheng1953d0c2007-11-29 10:12:14 +00001766 SRInfo &Info = SII->second.back();
1767 Info.index = index;
1768 Info.canFold = !HasUse;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001769 }
1770 SpillMBBs.set(MBBId);
Evan Chenge3110d02007-12-01 04:42:39 +00001771 } else if (SII != SpillIdxes.end() &&
1772 SII->second.back().vreg == NewVReg &&
1773 (int)index > SII->second.back().index) {
1774 // There is an earlier def that's not killed (must be two-address).
1775 // The spill is no longer needed.
1776 SII->second.pop_back();
1777 if (SII->second.empty()) {
1778 SpillIdxes.erase(MBBId);
1779 SpillMBBs.reset(MBBId);
1780 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001781 }
1782 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001783 }
1784
1785 if (HasUse) {
Owen Anderson28998312008-08-13 22:28:50 +00001786 DenseMap<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001787 SpillIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001788 if (SII != SpillIdxes.end() &&
1789 SII->second.back().vreg == NewVReg &&
1790 (int)index > SII->second.back().index)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001791 // Use(s) following the last def, it's not safe to fold the spill.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001792 SII->second.back().canFold = false;
Owen Anderson28998312008-08-13 22:28:50 +00001793 DenseMap<unsigned, std::vector<SRInfo> >::iterator RII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001794 RestoreIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001795 if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001796 // If we are splitting live intervals, only fold if it's the first
1797 // use and there isn't another use later in the MBB.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001798 RII->second.back().canFold = false;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001799 else if (IsNew) {
1800 // Only need a reload if there isn't an earlier def / use.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001801 if (RII == RestoreIdxes.end()) {
1802 std::vector<SRInfo> Infos;
1803 Infos.push_back(SRInfo(index, NewVReg, true));
1804 RestoreIdxes.insert(std::make_pair(MBBId, Infos));
1805 } else {
1806 RII->second.push_back(SRInfo(index, NewVReg, true));
1807 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001808 RestoreMBBs.set(MBBId);
1809 }
1810 }
1811
1812 // Update spill weight.
Evan Cheng22f07ff2007-12-11 02:09:15 +00001813 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Chengc3417602008-06-21 06:45:54 +00001814 nI.weight += getSpillWeight(HasDef, HasUse, loopDepth);
Evan Chengf2fbca62007-11-12 06:35:08 +00001815 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001816
1817 if (NewVReg && TrySplit && AllCanFold) {
1818 // If all of its def / use can be folded, give it a low spill weight.
1819 LiveInterval &nI = getOrCreateInterval(NewVReg);
1820 nI.weight /= 10.0F;
1821 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001822}
1823
Evan Cheng1953d0c2007-11-29 10:12:14 +00001824bool LiveIntervals::alsoFoldARestore(int Id, int index, unsigned vr,
1825 BitVector &RestoreMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001826 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001827 if (!RestoreMBBs[Id])
1828 return false;
1829 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1830 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1831 if (Restores[i].index == index &&
1832 Restores[i].vreg == vr &&
1833 Restores[i].canFold)
1834 return true;
1835 return false;
1836}
1837
1838void LiveIntervals::eraseRestoreInfo(int Id, int index, unsigned vr,
1839 BitVector &RestoreMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001840 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001841 if (!RestoreMBBs[Id])
1842 return;
1843 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1844 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1845 if (Restores[i].index == index && Restores[i].vreg)
1846 Restores[i].index = -1;
1847}
Evan Cheng81a03822007-11-17 00:40:40 +00001848
Evan Cheng4cce6b42008-04-11 17:53:36 +00001849/// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
1850/// spilled and create empty intervals for their uses.
1851void
1852LiveIntervals::handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
1853 const TargetRegisterClass* rc,
1854 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng419852c2008-04-03 16:39:43 +00001855 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1856 re = mri_->reg_end(); ri != re; ) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001857 MachineOperand &O = ri.getOperand();
Evan Cheng419852c2008-04-03 16:39:43 +00001858 MachineInstr *MI = &*ri;
1859 ++ri;
Evan Cheng4cce6b42008-04-11 17:53:36 +00001860 if (O.isDef()) {
1861 assert(MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF &&
1862 "Register def was not rewritten?");
1863 RemoveMachineInstrFromMaps(MI);
1864 vrm.RemoveMachineInstrFromMaps(MI);
1865 MI->eraseFromParent();
1866 } else {
1867 // This must be an use of an implicit_def so it's not part of the live
1868 // interval. Create a new empty live interval for it.
1869 // FIXME: Can we simply erase some of the instructions? e.g. Stores?
1870 unsigned NewVReg = mri_->createVirtualRegister(rc);
1871 vrm.grow();
1872 vrm.setIsImplicitlyDefined(NewVReg);
1873 NewLIs.push_back(&getOrCreateInterval(NewVReg));
1874 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1875 MachineOperand &MO = MI->getOperand(i);
Evan Cheng4784f1f2009-06-30 08:49:04 +00001876 if (MO.isReg() && MO.getReg() == li.reg) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001877 MO.setReg(NewVReg);
Evan Cheng4784f1f2009-06-30 08:49:04 +00001878 MO.setIsUndef();
Evan Cheng4784f1f2009-06-30 08:49:04 +00001879 }
Evan Cheng4cce6b42008-04-11 17:53:36 +00001880 }
1881 }
Evan Cheng419852c2008-04-03 16:39:43 +00001882 }
1883}
1884
Evan Chengf2fbca62007-11-12 06:35:08 +00001885std::vector<LiveInterval*> LiveIntervals::
Owen Andersond6664312008-08-18 18:05:32 +00001886addIntervalsForSpillsFast(const LiveInterval &li,
1887 const MachineLoopInfo *loopInfo,
Evan Chengc781a242009-05-03 18:32:42 +00001888 VirtRegMap &vrm) {
Owen Anderson17197312008-08-18 23:41:04 +00001889 unsigned slot = vrm.assignVirt2StackSlot(li.reg);
Owen Andersond6664312008-08-18 18:05:32 +00001890
1891 std::vector<LiveInterval*> added;
1892
1893 assert(li.weight != HUGE_VALF &&
1894 "attempt to spill already spilled interval!");
1895
1896 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
1897 DEBUG(li.dump());
1898 DOUT << '\n';
1899
1900 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
1901
Owen Andersona41e47a2008-08-19 22:12:11 +00001902 MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg);
1903 while (RI != mri_->reg_end()) {
1904 MachineInstr* MI = &*RI;
1905
1906 SmallVector<unsigned, 2> Indices;
1907 bool HasUse = false;
1908 bool HasDef = false;
1909
1910 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1911 MachineOperand& mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001912 if (!mop.isReg() || mop.getReg() != li.reg) continue;
Owen Andersona41e47a2008-08-19 22:12:11 +00001913
1914 HasUse |= MI->getOperand(i).isUse();
1915 HasDef |= MI->getOperand(i).isDef();
1916
1917 Indices.push_back(i);
1918 }
1919
1920 if (!tryFoldMemoryOperand(MI, vrm, NULL, getInstructionIndex(MI),
1921 Indices, true, slot, li.reg)) {
1922 unsigned NewVReg = mri_->createVirtualRegister(rc);
Owen Anderson9a032932008-08-18 21:20:32 +00001923 vrm.grow();
Owen Anderson17197312008-08-18 23:41:04 +00001924 vrm.assignVirt2StackSlot(NewVReg, slot);
1925
Owen Andersona41e47a2008-08-19 22:12:11 +00001926 // create a new register for this spill
1927 LiveInterval &nI = getOrCreateInterval(NewVReg);
Owen Andersond6664312008-08-18 18:05:32 +00001928
Owen Andersona41e47a2008-08-19 22:12:11 +00001929 // the spill weight is now infinity as it
1930 // cannot be spilled again
1931 nI.weight = HUGE_VALF;
1932
1933 // Rewrite register operands to use the new vreg.
1934 for (SmallVectorImpl<unsigned>::iterator I = Indices.begin(),
1935 E = Indices.end(); I != E; ++I) {
1936 MI->getOperand(*I).setReg(NewVReg);
1937
1938 if (MI->getOperand(*I).isUse())
1939 MI->getOperand(*I).setIsKill(true);
1940 }
1941
1942 // Fill in the new live interval.
1943 unsigned index = getInstructionIndex(MI);
1944 if (HasUse) {
1945 LiveRange LR(getLoadIndex(index), getUseIndex(index),
Lang Hames857c4e02009-06-17 21:01:20 +00001946 nI.getNextValue(0, 0, false, getVNInfoAllocator()));
Owen Andersona41e47a2008-08-19 22:12:11 +00001947 DOUT << " +" << LR;
1948 nI.addRange(LR);
1949 vrm.addRestorePoint(NewVReg, MI);
1950 }
1951 if (HasDef) {
1952 LiveRange LR(getDefIndex(index), getStoreIndex(index),
Lang Hames857c4e02009-06-17 21:01:20 +00001953 nI.getNextValue(0, 0, false, getVNInfoAllocator()));
Owen Andersona41e47a2008-08-19 22:12:11 +00001954 DOUT << " +" << LR;
1955 nI.addRange(LR);
1956 vrm.addSpillPoint(NewVReg, true, MI);
1957 }
1958
Owen Anderson17197312008-08-18 23:41:04 +00001959 added.push_back(&nI);
Owen Anderson8dc2cbe2008-08-18 18:38:12 +00001960
Owen Andersona41e47a2008-08-19 22:12:11 +00001961 DOUT << "\t\t\t\tadded new interval: ";
1962 DEBUG(nI.dump());
1963 DOUT << '\n';
Owen Andersona41e47a2008-08-19 22:12:11 +00001964 }
Owen Anderson9a032932008-08-18 21:20:32 +00001965
Owen Anderson9a032932008-08-18 21:20:32 +00001966
Owen Andersona41e47a2008-08-19 22:12:11 +00001967 RI = mri_->reg_begin(li.reg);
Owen Andersond6664312008-08-18 18:05:32 +00001968 }
Owen Andersond6664312008-08-18 18:05:32 +00001969
1970 return added;
1971}
1972
1973std::vector<LiveInterval*> LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001974addIntervalsForSpills(const LiveInterval &li,
Evan Chengdc377862008-09-30 15:44:16 +00001975 SmallVectorImpl<LiveInterval*> &SpillIs,
Evan Chengc781a242009-05-03 18:32:42 +00001976 const MachineLoopInfo *loopInfo, VirtRegMap &vrm) {
Owen Andersonae339ba2008-08-19 00:17:30 +00001977
1978 if (EnableFastSpilling)
Evan Chengc781a242009-05-03 18:32:42 +00001979 return addIntervalsForSpillsFast(li, loopInfo, vrm);
Owen Andersonae339ba2008-08-19 00:17:30 +00001980
Evan Chengf2fbca62007-11-12 06:35:08 +00001981 assert(li.weight != HUGE_VALF &&
1982 "attempt to spill already spilled interval!");
1983
1984 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001985 li.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001986 DOUT << '\n';
1987
Evan Cheng72eeb942008-12-05 17:00:16 +00001988 // Each bit specify whether a spill is required in the MBB.
Evan Cheng81a03822007-11-17 00:40:40 +00001989 BitVector SpillMBBs(mf_->getNumBlockIDs());
Owen Anderson28998312008-08-13 22:28:50 +00001990 DenseMap<unsigned, std::vector<SRInfo> > SpillIdxes;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001991 BitVector RestoreMBBs(mf_->getNumBlockIDs());
Owen Anderson28998312008-08-13 22:28:50 +00001992 DenseMap<unsigned, std::vector<SRInfo> > RestoreIdxes;
1993 DenseMap<unsigned,unsigned> MBBVRegsMap;
Evan Chengf2fbca62007-11-12 06:35:08 +00001994 std::vector<LiveInterval*> NewLIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001995 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
Evan Chengf2fbca62007-11-12 06:35:08 +00001996
1997 unsigned NumValNums = li.getNumValNums();
1998 SmallVector<MachineInstr*, 4> ReMatDefs;
1999 ReMatDefs.resize(NumValNums, NULL);
2000 SmallVector<MachineInstr*, 4> ReMatOrigDefs;
2001 ReMatOrigDefs.resize(NumValNums, NULL);
2002 SmallVector<int, 4> ReMatIds;
2003 ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
2004 BitVector ReMatDelete(NumValNums);
2005 unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
2006
Evan Cheng81a03822007-11-17 00:40:40 +00002007 // Spilling a split live interval. It cannot be split any further. Also,
2008 // it's also guaranteed to be a single val# / range interval.
2009 if (vrm.getPreSplitReg(li.reg)) {
2010 vrm.setIsSplitFromReg(li.reg, 0);
Evan Chengd120ffd2007-12-05 10:24:35 +00002011 // Unset the split kill marker on the last use.
2012 unsigned KillIdx = vrm.getKillPoint(li.reg);
2013 if (KillIdx) {
2014 MachineInstr *KillMI = getInstructionFromIndex(KillIdx);
2015 assert(KillMI && "Last use disappeared?");
2016 int KillOp = KillMI->findRegisterUseOperandIdx(li.reg, true);
2017 assert(KillOp != -1 && "Last use disappeared?");
Chris Lattnerf7382302007-12-30 21:56:09 +00002018 KillMI->getOperand(KillOp).setIsKill(false);
Evan Chengd120ffd2007-12-05 10:24:35 +00002019 }
Evan Chengadf85902007-12-05 09:51:10 +00002020 vrm.removeKillPoint(li.reg);
Evan Cheng81a03822007-11-17 00:40:40 +00002021 bool DefIsReMat = vrm.isReMaterialized(li.reg);
2022 Slot = vrm.getStackSlot(li.reg);
2023 assert(Slot != VirtRegMap::MAX_STACK_SLOT);
2024 MachineInstr *ReMatDefMI = DefIsReMat ?
2025 vrm.getReMaterializedMI(li.reg) : NULL;
2026 int LdSlot = 0;
2027 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
2028 bool isLoad = isLoadSS ||
Dan Gohman15511cf2008-12-03 18:15:48 +00002029 (DefIsReMat && (ReMatDefMI->getDesc().canFoldAsLoad()));
Evan Cheng81a03822007-11-17 00:40:40 +00002030 bool IsFirstRange = true;
2031 for (LiveInterval::Ranges::const_iterator
2032 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
2033 // If this is a split live interval with multiple ranges, it means there
2034 // are two-address instructions that re-defined the value. Only the
2035 // first def can be rematerialized!
2036 if (IsFirstRange) {
Evan Chengcb3c3302007-11-29 23:02:50 +00002037 // Note ReMatOrigDefMI has already been deleted.
Evan Cheng81a03822007-11-17 00:40:40 +00002038 rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
2039 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00002040 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00002041 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Chengc781a242009-05-03 18:32:42 +00002042 MBBVRegsMap, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00002043 } else {
2044 rewriteInstructionsForSpills(li, false, I, NULL, 0,
2045 Slot, 0, false, false, false,
Evan Chengd70dbb52008-02-22 09:24:50 +00002046 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00002047 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Chengc781a242009-05-03 18:32:42 +00002048 MBBVRegsMap, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00002049 }
2050 IsFirstRange = false;
2051 }
Evan Cheng419852c2008-04-03 16:39:43 +00002052
Evan Cheng4cce6b42008-04-11 17:53:36 +00002053 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00002054 return NewLIs;
2055 }
2056
2057 bool TrySplit = SplitAtBB && !intervalIsInOneMBB(li);
Evan Cheng0cbb1162007-11-29 01:06:25 +00002058 if (SplitLimit != -1 && (int)numSplits >= SplitLimit)
2059 TrySplit = false;
2060 if (TrySplit)
2061 ++numSplits;
Evan Chengf2fbca62007-11-12 06:35:08 +00002062 bool NeedStackSlot = false;
2063 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
2064 i != e; ++i) {
2065 const VNInfo *VNI = *i;
2066 unsigned VN = VNI->id;
Lang Hames857c4e02009-06-17 21:01:20 +00002067 if (VNI->isUnused())
Evan Chengf2fbca62007-11-12 06:35:08 +00002068 continue; // Dead val#.
2069 // Is the def for the val# rematerializable?
Lang Hames857c4e02009-06-17 21:01:20 +00002070 MachineInstr *ReMatDefMI = VNI->isDefAccurate()
2071 ? getInstructionFromIndex(VNI->def) : 0;
Evan Cheng5ef3a042007-12-06 00:01:56 +00002072 bool dummy;
Evan Chengdc377862008-09-30 15:44:16 +00002073 if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, SpillIs, dummy)) {
Evan Chengf2fbca62007-11-12 06:35:08 +00002074 // Remember how to remat the def of this val#.
Evan Cheng81a03822007-11-17 00:40:40 +00002075 ReMatOrigDefs[VN] = ReMatDefMI;
Dan Gohman2c3f7ae2008-07-17 23:49:46 +00002076 // Original def may be modified so we have to make a copy here.
Evan Cheng1ed99222008-07-19 00:37:25 +00002077 MachineInstr *Clone = mf_->CloneMachineInstr(ReMatDefMI);
2078 ClonedMIs.push_back(Clone);
2079 ReMatDefs[VN] = Clone;
Evan Chengf2fbca62007-11-12 06:35:08 +00002080
2081 bool CanDelete = true;
Lang Hames857c4e02009-06-17 21:01:20 +00002082 if (VNI->hasPHIKill()) {
Evan Chengc3fc7d92007-11-29 09:49:23 +00002083 // A kill is a phi node, not all of its uses can be rematerialized.
Evan Chengf2fbca62007-11-12 06:35:08 +00002084 // It must not be deleted.
Evan Chengc3fc7d92007-11-29 09:49:23 +00002085 CanDelete = false;
2086 // Need a stack slot if there is any live range where uses cannot be
2087 // rematerialized.
2088 NeedStackSlot = true;
Evan Chengf2fbca62007-11-12 06:35:08 +00002089 }
Evan Chengf2fbca62007-11-12 06:35:08 +00002090 if (CanDelete)
2091 ReMatDelete.set(VN);
2092 } else {
2093 // Need a stack slot if there is any live range where uses cannot be
2094 // rematerialized.
2095 NeedStackSlot = true;
2096 }
2097 }
2098
2099 // One stack slot per live interval.
Owen Andersonb98bbb72009-03-26 18:53:38 +00002100 if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0) {
2101 if (vrm.getStackSlot(li.reg) == VirtRegMap::NO_STACK_SLOT)
2102 Slot = vrm.assignVirt2StackSlot(li.reg);
2103
2104 // This case only occurs when the prealloc splitter has already assigned
2105 // a stack slot to this vreg.
2106 else
2107 Slot = vrm.getStackSlot(li.reg);
2108 }
Evan Chengf2fbca62007-11-12 06:35:08 +00002109
2110 // Create new intervals and rewrite defs and uses.
2111 for (LiveInterval::Ranges::const_iterator
2112 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Evan Cheng81a03822007-11-17 00:40:40 +00002113 MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id];
2114 MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id];
2115 bool DefIsReMat = ReMatDefMI != NULL;
Evan Chengf2fbca62007-11-12 06:35:08 +00002116 bool CanDelete = ReMatDelete[I->valno->id];
2117 int LdSlot = 0;
Evan Cheng81a03822007-11-17 00:40:40 +00002118 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
Evan Chengf2fbca62007-11-12 06:35:08 +00002119 bool isLoad = isLoadSS ||
Dan Gohman15511cf2008-12-03 18:15:48 +00002120 (DefIsReMat && ReMatDefMI->getDesc().canFoldAsLoad());
Evan Cheng81a03822007-11-17 00:40:40 +00002121 rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
Evan Cheng0cbb1162007-11-29 01:06:25 +00002122 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00002123 CanDelete, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00002124 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Chengc781a242009-05-03 18:32:42 +00002125 MBBVRegsMap, NewLIs);
Evan Chengf2fbca62007-11-12 06:35:08 +00002126 }
2127
Evan Cheng0cbb1162007-11-29 01:06:25 +00002128 // Insert spills / restores if we are splitting.
Evan Cheng419852c2008-04-03 16:39:43 +00002129 if (!TrySplit) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00002130 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng1953d0c2007-11-29 10:12:14 +00002131 return NewLIs;
Evan Cheng419852c2008-04-03 16:39:43 +00002132 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002133
Evan Chengb50bb8c2007-12-05 08:16:32 +00002134 SmallPtrSet<LiveInterval*, 4> AddedKill;
Evan Chengaee4af62007-12-02 08:30:39 +00002135 SmallVector<unsigned, 2> Ops;
Evan Cheng1953d0c2007-11-29 10:12:14 +00002136 if (NeedStackSlot) {
2137 int Id = SpillMBBs.find_first();
2138 while (Id != -1) {
2139 std::vector<SRInfo> &spills = SpillIdxes[Id];
2140 for (unsigned i = 0, e = spills.size(); i != e; ++i) {
2141 int index = spills[i].index;
2142 unsigned VReg = spills[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00002143 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng0cbb1162007-11-29 01:06:25 +00002144 bool isReMat = vrm.isReMaterialized(VReg);
2145 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00002146 bool CanFold = false;
2147 bool FoundUse = false;
2148 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00002149 if (spills[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00002150 CanFold = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00002151 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
2152 MachineOperand &MO = MI->getOperand(j);
Dan Gohmand735b802008-10-03 15:45:36 +00002153 if (!MO.isReg() || MO.getReg() != VReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00002154 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00002155
2156 Ops.push_back(j);
2157 if (MO.isDef())
Evan Chengcddbb832007-11-30 21:23:43 +00002158 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00002159 if (isReMat ||
2160 (!FoundUse && !alsoFoldARestore(Id, index, VReg,
2161 RestoreMBBs, RestoreIdxes))) {
2162 // MI has two-address uses of the same register. If the use
2163 // isn't the first and only use in the BB, then we can't fold
2164 // it. FIXME: Move this to rewriteInstructionsForSpills.
2165 CanFold = false;
Evan Chengcddbb832007-11-30 21:23:43 +00002166 break;
2167 }
Evan Chengaee4af62007-12-02 08:30:39 +00002168 FoundUse = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00002169 }
2170 }
2171 // Fold the store into the def if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00002172 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00002173 if (CanFold && !Ops.empty()) {
2174 if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
Evan Chengcddbb832007-11-30 21:23:43 +00002175 Folded = true;
Sebastian Redl48fe6352009-03-19 23:26:52 +00002176 if (FoundUse) {
Evan Chengaee4af62007-12-02 08:30:39 +00002177 // Also folded uses, do not issue a load.
2178 eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
Evan Chengf38d14f2007-12-05 09:05:34 +00002179 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
2180 }
Evan Cheng597d10d2007-12-04 00:32:23 +00002181 nI.removeRange(getDefIndex(index), getStoreIndex(index));
Evan Chengcddbb832007-11-30 21:23:43 +00002182 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002183 }
2184
Evan Cheng7e073ba2008-04-09 20:57:25 +00002185 // Otherwise tell the spiller to issue a spill.
Evan Chengb50bb8c2007-12-05 08:16:32 +00002186 if (!Folded) {
2187 LiveRange *LR = &nI.ranges[nI.ranges.size()-1];
2188 bool isKill = LR->end == getStoreIndex(index);
Evan Chengb0a6f622008-05-20 08:10:37 +00002189 if (!MI->registerDefIsDead(nI.reg))
2190 // No need to spill a dead def.
2191 vrm.addSpillPoint(VReg, isKill, MI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002192 if (isKill)
2193 AddedKill.insert(&nI);
2194 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002195 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002196 Id = SpillMBBs.find_next(Id);
Evan Cheng0cbb1162007-11-29 01:06:25 +00002197 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002198 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002199
Evan Cheng1953d0c2007-11-29 10:12:14 +00002200 int Id = RestoreMBBs.find_first();
2201 while (Id != -1) {
2202 std::vector<SRInfo> &restores = RestoreIdxes[Id];
2203 for (unsigned i = 0, e = restores.size(); i != e; ++i) {
2204 int index = restores[i].index;
2205 if (index == -1)
2206 continue;
2207 unsigned VReg = restores[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00002208 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng9c3c2212008-06-06 07:54:39 +00002209 bool isReMat = vrm.isReMaterialized(VReg);
Evan Cheng81a03822007-11-17 00:40:40 +00002210 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00002211 bool CanFold = false;
2212 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00002213 if (restores[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00002214 CanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00002215 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
2216 MachineOperand &MO = MI->getOperand(j);
Dan Gohmand735b802008-10-03 15:45:36 +00002217 if (!MO.isReg() || MO.getReg() != VReg)
Evan Cheng81a03822007-11-17 00:40:40 +00002218 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00002219
Evan Cheng0cbb1162007-11-29 01:06:25 +00002220 if (MO.isDef()) {
Evan Chengaee4af62007-12-02 08:30:39 +00002221 // If this restore were to be folded, it would have been folded
2222 // already.
2223 CanFold = false;
Evan Cheng81a03822007-11-17 00:40:40 +00002224 break;
2225 }
Evan Chengaee4af62007-12-02 08:30:39 +00002226 Ops.push_back(j);
Evan Cheng81a03822007-11-17 00:40:40 +00002227 }
2228 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002229
2230 // Fold the load into the use if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00002231 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00002232 if (CanFold && !Ops.empty()) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00002233 if (!isReMat)
Evan Chengaee4af62007-12-02 08:30:39 +00002234 Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg);
2235 else {
Evan Cheng0cbb1162007-11-29 01:06:25 +00002236 MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg);
2237 int LdSlot = 0;
2238 bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
2239 // If the rematerializable def is a load, also try to fold it.
Dan Gohman15511cf2008-12-03 18:15:48 +00002240 if (isLoadSS || ReMatDefMI->getDesc().canFoldAsLoad())
Evan Chengaee4af62007-12-02 08:30:39 +00002241 Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
2242 Ops, isLoadSS, LdSlot, VReg);
Evan Cheng650d7f32008-12-05 17:41:31 +00002243 if (!Folded) {
2244 unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI);
2245 if (ImpUse) {
2246 // Re-matting an instruction with virtual register use. Add the
2247 // register as an implicit use on the use MI and update the register
2248 // interval's spill weight to HUGE_VALF to prevent it from being
2249 // spilled.
2250 LiveInterval &ImpLi = getInterval(ImpUse);
2251 ImpLi.weight = HUGE_VALF;
2252 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
2253 }
Evan Chengd70dbb52008-02-22 09:24:50 +00002254 }
Evan Chengaee4af62007-12-02 08:30:39 +00002255 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002256 }
2257 // If folding is not possible / failed, then tell the spiller to issue a
2258 // load / rematerialization for us.
Evan Cheng597d10d2007-12-04 00:32:23 +00002259 if (Folded)
2260 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002261 else
Evan Cheng0cbb1162007-11-29 01:06:25 +00002262 vrm.addRestorePoint(VReg, MI);
Evan Cheng81a03822007-11-17 00:40:40 +00002263 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002264 Id = RestoreMBBs.find_next(Id);
Evan Cheng81a03822007-11-17 00:40:40 +00002265 }
2266
Evan Chengb50bb8c2007-12-05 08:16:32 +00002267 // Finalize intervals: add kills, finalize spill weights, and filter out
2268 // dead intervals.
Evan Cheng597d10d2007-12-04 00:32:23 +00002269 std::vector<LiveInterval*> RetNewLIs;
2270 for (unsigned i = 0, e = NewLIs.size(); i != e; ++i) {
2271 LiveInterval *LI = NewLIs[i];
2272 if (!LI->empty()) {
Owen Anderson496bac52008-07-23 19:47:27 +00002273 LI->weight /= InstrSlots::NUM * getApproximateInstructionCount(*LI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002274 if (!AddedKill.count(LI)) {
2275 LiveRange *LR = &LI->ranges[LI->ranges.size()-1];
Evan Chengd120ffd2007-12-05 10:24:35 +00002276 unsigned LastUseIdx = getBaseIndex(LR->end);
2277 MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx);
Evan Cheng6130f662008-03-05 00:59:57 +00002278 int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg, false);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002279 assert(UseIdx != -1);
Evan Chenga24752f2009-03-19 20:30:06 +00002280 if (!LastUse->isRegTiedToDefOperand(UseIdx)) {
Evan Chengb50bb8c2007-12-05 08:16:32 +00002281 LastUse->getOperand(UseIdx).setIsKill();
Evan Chengd120ffd2007-12-05 10:24:35 +00002282 vrm.addKillPoint(LI->reg, LastUseIdx);
Evan Chengadf85902007-12-05 09:51:10 +00002283 }
Evan Chengb50bb8c2007-12-05 08:16:32 +00002284 }
Evan Cheng597d10d2007-12-04 00:32:23 +00002285 RetNewLIs.push_back(LI);
2286 }
2287 }
Evan Cheng81a03822007-11-17 00:40:40 +00002288
Evan Cheng4cce6b42008-04-11 17:53:36 +00002289 handleSpilledImpDefs(li, vrm, rc, RetNewLIs);
Evan Cheng597d10d2007-12-04 00:32:23 +00002290 return RetNewLIs;
Evan Chengf2fbca62007-11-12 06:35:08 +00002291}
Evan Cheng676dd7c2008-03-11 07:19:34 +00002292
2293/// hasAllocatableSuperReg - Return true if the specified physical register has
2294/// any super register that's allocatable.
2295bool LiveIntervals::hasAllocatableSuperReg(unsigned Reg) const {
2296 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS)
2297 if (allocatableRegs_[*AS] && hasInterval(*AS))
2298 return true;
2299 return false;
2300}
2301
2302/// getRepresentativeReg - Find the largest super register of the specified
2303/// physical register.
2304unsigned LiveIntervals::getRepresentativeReg(unsigned Reg) const {
2305 // Find the largest super-register that is allocatable.
2306 unsigned BestReg = Reg;
2307 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS) {
2308 unsigned SuperReg = *AS;
2309 if (!hasAllocatableSuperReg(SuperReg) && hasInterval(SuperReg)) {
2310 BestReg = SuperReg;
2311 break;
2312 }
2313 }
2314 return BestReg;
2315}
2316
2317/// getNumConflictsWithPhysReg - Return the number of uses and defs of the
2318/// specified interval that conflicts with the specified physical register.
2319unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li,
2320 unsigned PhysReg) const {
2321 unsigned NumConflicts = 0;
2322 const LiveInterval &pli = getInterval(getRepresentativeReg(PhysReg));
2323 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
2324 E = mri_->reg_end(); I != E; ++I) {
2325 MachineOperand &O = I.getOperand();
2326 MachineInstr *MI = O.getParent();
2327 unsigned Index = getInstructionIndex(MI);
2328 if (pli.liveAt(Index))
2329 ++NumConflicts;
2330 }
2331 return NumConflicts;
2332}
2333
2334/// spillPhysRegAroundRegDefsUses - Spill the specified physical register
Evan Cheng2824a652009-03-23 18:24:37 +00002335/// around all defs and uses of the specified interval. Return true if it
2336/// was able to cut its interval.
2337bool LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
Evan Cheng676dd7c2008-03-11 07:19:34 +00002338 unsigned PhysReg, VirtRegMap &vrm) {
2339 unsigned SpillReg = getRepresentativeReg(PhysReg);
2340
2341 for (const unsigned *AS = tri_->getAliasSet(PhysReg); *AS; ++AS)
2342 // If there are registers which alias PhysReg, but which are not a
2343 // sub-register of the chosen representative super register. Assert
2344 // since we can't handle it yet.
Dan Gohman70f2f652009-04-13 15:22:29 +00002345 assert(*AS == SpillReg || !allocatableRegs_[*AS] || !hasInterval(*AS) ||
Evan Cheng676dd7c2008-03-11 07:19:34 +00002346 tri_->isSuperRegister(*AS, SpillReg));
2347
Evan Cheng2824a652009-03-23 18:24:37 +00002348 bool Cut = false;
Evan Cheng676dd7c2008-03-11 07:19:34 +00002349 LiveInterval &pli = getInterval(SpillReg);
2350 SmallPtrSet<MachineInstr*, 8> SeenMIs;
2351 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
2352 E = mri_->reg_end(); I != E; ++I) {
2353 MachineOperand &O = I.getOperand();
2354 MachineInstr *MI = O.getParent();
2355 if (SeenMIs.count(MI))
2356 continue;
2357 SeenMIs.insert(MI);
2358 unsigned Index = getInstructionIndex(MI);
2359 if (pli.liveAt(Index)) {
2360 vrm.addEmergencySpill(SpillReg, MI);
Evan Cheng5a3c6a82009-01-29 02:20:59 +00002361 unsigned StartIdx = getLoadIndex(Index);
2362 unsigned EndIdx = getStoreIndex(Index)+1;
Evan Cheng2824a652009-03-23 18:24:37 +00002363 if (pli.isInOneLiveRange(StartIdx, EndIdx)) {
Evan Cheng5a3c6a82009-01-29 02:20:59 +00002364 pli.removeRange(StartIdx, EndIdx);
Evan Cheng2824a652009-03-23 18:24:37 +00002365 Cut = true;
2366 } else {
Evan Cheng5a3c6a82009-01-29 02:20:59 +00002367 cerr << "Ran out of registers during register allocation!\n";
2368 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
2369 cerr << "Please check your inline asm statement for invalid "
2370 << "constraints:\n";
2371 MI->print(cerr.stream(), tm_);
2372 }
2373 exit(1);
2374 }
Evan Cheng676dd7c2008-03-11 07:19:34 +00002375 for (const unsigned* AS = tri_->getSubRegisters(SpillReg); *AS; ++AS) {
2376 if (!hasInterval(*AS))
2377 continue;
2378 LiveInterval &spli = getInterval(*AS);
2379 if (spli.liveAt(Index))
2380 spli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
2381 }
2382 }
2383 }
Evan Cheng2824a652009-03-23 18:24:37 +00002384 return Cut;
Evan Cheng676dd7c2008-03-11 07:19:34 +00002385}
Owen Andersonc4dc1322008-06-05 17:15:43 +00002386
2387LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
2388 MachineInstr* startInst) {
2389 LiveInterval& Interval = getOrCreateInterval(reg);
2390 VNInfo* VN = Interval.getNextValue(
2391 getInstructionIndex(startInst) + InstrSlots::DEF,
Lang Hames857c4e02009-06-17 21:01:20 +00002392 startInst, true, getVNInfoAllocator());
2393 VN->setHasPHIKill(true);
Owen Andersonc4dc1322008-06-05 17:15:43 +00002394 VN->kills.push_back(getMBBEndIdx(startInst->getParent()));
2395 LiveRange LR(getInstructionIndex(startInst) + InstrSlots::DEF,
2396 getMBBEndIdx(startInst->getParent()) + 1, VN);
2397 Interval.addRange(LR);
2398
2399 return LR;
2400}