blob: 21bb5dc0127d0255abfb4a70b7101d383e706437 [file] [log] [blame]
Chris Lattnera3b8b5c2004-07-23 17:56:30 +00001//===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the LiveInterval analysis pass which is used
11// by the Linear Scan Register allocator. This pass linearizes the
12// basic blocks of the function in DFS order and uses the
13// LiveVariables pass to conservatively compute live intervals for
14// each virtual and physical register.
15//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "liveintervals"
Chris Lattner3c3fe462005-09-21 04:19:09 +000019#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Misha Brukman08a6c762004-09-03 18:25:53 +000020#include "VirtRegMap.h"
Chris Lattner015959e2004-05-01 21:24:39 +000021#include "llvm/Value.h"
Dan Gohman6d69ba82008-07-25 00:02:30 +000022#include "llvm/Analysis/AliasAnalysis.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000023#include "llvm/CodeGen/LiveVariables.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000025#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000026#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000027#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000028#include "llvm/CodeGen/Passes.h"
Dan Gohman6d69ba82008-07-25 00:02:30 +000029#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000030#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000031#include "llvm/Target/TargetInstrInfo.h"
32#include "llvm/Target/TargetMachine.h"
Owen Anderson95dad832008-10-07 20:22:28 +000033#include "llvm/Target/TargetOptions.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000034#include "llvm/Support/CommandLine.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/ADT/Statistic.h"
37#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000038#include <algorithm>
Lang Hamesf41538d2009-06-02 16:53:25 +000039#include <limits>
Jeff Cohen97af7512006-12-02 02:22:01 +000040#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000041using namespace llvm;
42
Dan Gohman844731a2008-05-13 00:00:25 +000043// Hidden options for help debugging.
44static cl::opt<bool> DisableReMat("disable-rematerialization",
45 cl::init(false), cl::Hidden);
Evan Cheng81a03822007-11-17 00:40:40 +000046
Dan Gohman844731a2008-05-13 00:00:25 +000047static cl::opt<bool> SplitAtBB("split-intervals-at-bb",
48 cl::init(true), cl::Hidden);
49static cl::opt<int> SplitLimit("split-limit",
50 cl::init(-1), cl::Hidden);
Evan Chengbc165e42007-08-16 07:24:22 +000051
Dan Gohman4c8f8702008-07-25 15:08:37 +000052static cl::opt<bool> EnableAggressiveRemat("aggressive-remat", cl::Hidden);
53
Owen Andersonae339ba2008-08-19 00:17:30 +000054static cl::opt<bool> EnableFastSpilling("fast-spill",
55 cl::init(false), cl::Hidden);
56
Chris Lattnercd3245a2006-12-19 22:41:21 +000057STATISTIC(numIntervals, "Number of original intervals");
Evan Cheng0cbb1162007-11-29 01:06:25 +000058STATISTIC(numFolds , "Number of loads/stores folded into instructions");
59STATISTIC(numSplits , "Number of intervals split");
Chris Lattnercd3245a2006-12-19 22:41:21 +000060
Devang Patel19974732007-05-03 01:11:54 +000061char LiveIntervals::ID = 0;
Dan Gohman844731a2008-05-13 00:00:25 +000062static RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000063
Chris Lattnerf7da2c72006-08-24 22:43:55 +000064void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman6d69ba82008-07-25 00:02:30 +000065 AU.addRequired<AliasAnalysis>();
66 AU.addPreserved<AliasAnalysis>();
David Greene25133302007-06-08 17:18:56 +000067 AU.addPreserved<LiveVariables>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000068 AU.addRequired<LiveVariables>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000069 AU.addPreservedID(MachineLoopInfoID);
70 AU.addPreservedID(MachineDominatorsID);
Owen Anderson95dad832008-10-07 20:22:28 +000071
72 if (!StrongPHIElim) {
73 AU.addPreservedID(PHIEliminationID);
74 AU.addRequiredID(PHIEliminationID);
75 }
76
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000077 AU.addRequiredID(TwoAddressInstructionPassID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000078 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000079}
80
Chris Lattnerf7da2c72006-08-24 22:43:55 +000081void LiveIntervals::releaseMemory() {
Owen Anderson03857b22008-08-13 21:49:13 +000082 // Free the live intervals themselves.
Owen Anderson20e28392008-08-13 22:08:30 +000083 for (DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.begin(),
Owen Anderson03857b22008-08-13 21:49:13 +000084 E = r2iMap_.end(); I != E; ++I)
85 delete I->second;
86
Evan Cheng3f32d652008-06-04 09:18:41 +000087 MBB2IdxMap.clear();
Evan Cheng4ca980e2007-10-17 02:10:22 +000088 Idx2MBBMap.clear();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000089 mi2iMap_.clear();
90 i2miMap_.clear();
91 r2iMap_.clear();
Evan Chengdd199d22007-09-06 01:07:24 +000092 // Release VNInfo memroy regions after all VNInfo objects are dtor'd.
93 VNInfoAllocator.Reset();
Evan Cheng1ed99222008-07-19 00:37:25 +000094 while (!ClonedMIs.empty()) {
95 MachineInstr *MI = ClonedMIs.back();
96 ClonedMIs.pop_back();
97 mf_->DeleteMachineInstr(MI);
98 }
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000099}
100
Owen Anderson80b3ce62008-05-28 20:54:50 +0000101void LiveIntervals::computeNumbering() {
102 Index2MiMap OldI2MI = i2miMap_;
Owen Anderson7fbad272008-07-23 21:37:49 +0000103 std::vector<IdxMBBPair> OldI2MBB = Idx2MBBMap;
Owen Anderson80b3ce62008-05-28 20:54:50 +0000104
105 Idx2MBBMap.clear();
106 MBB2IdxMap.clear();
107 mi2iMap_.clear();
108 i2miMap_.clear();
109
Owen Andersona1566f22008-07-22 22:46:49 +0000110 FunctionSize = 0;
111
Chris Lattner428b92e2006-09-15 03:57:23 +0000112 // Number MachineInstrs and MachineBasicBlocks.
113 // Initialize MBB indexes to a sentinal.
Evan Cheng549f27d32007-08-13 23:45:17 +0000114 MBB2IdxMap.resize(mf_->getNumBlockIDs(), std::make_pair(~0U,~0U));
Chris Lattner428b92e2006-09-15 03:57:23 +0000115
116 unsigned MIIndex = 0;
117 for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
118 MBB != E; ++MBB) {
Evan Cheng549f27d32007-08-13 23:45:17 +0000119 unsigned StartIdx = MIIndex;
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000120
Owen Anderson7fbad272008-07-23 21:37:49 +0000121 // Insert an empty slot at the beginning of each block.
122 MIIndex += InstrSlots::NUM;
123 i2miMap_.push_back(0);
124
Chris Lattner428b92e2006-09-15 03:57:23 +0000125 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
126 I != E; ++I) {
127 bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000128 assert(inserted && "multiple MachineInstr -> index mappings");
Devang Patel59500c82008-11-21 20:00:59 +0000129 inserted = true;
Chris Lattner428b92e2006-09-15 03:57:23 +0000130 i2miMap_.push_back(I);
131 MIIndex += InstrSlots::NUM;
Owen Andersona1566f22008-07-22 22:46:49 +0000132 FunctionSize++;
Owen Anderson7fbad272008-07-23 21:37:49 +0000133
Evan Cheng4ed43292008-10-18 05:21:37 +0000134 // Insert max(1, numdefs) empty slots after every instruction.
Evan Cheng99fe34b2008-10-18 05:18:55 +0000135 unsigned Slots = I->getDesc().getNumDefs();
136 if (Slots == 0)
137 Slots = 1;
138 MIIndex += InstrSlots::NUM * Slots;
139 while (Slots--)
140 i2miMap_.push_back(0);
Owen Anderson35578012008-06-16 07:10:49 +0000141 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000142
Owen Anderson1fbb4542008-06-16 16:58:24 +0000143 // Set the MBB2IdxMap entry for this MBB.
144 MBB2IdxMap[MBB->getNumber()] = std::make_pair(StartIdx, MIIndex - 1);
145 Idx2MBBMap.push_back(std::make_pair(StartIdx, MBB));
Chris Lattner428b92e2006-09-15 03:57:23 +0000146 }
Evan Cheng4ca980e2007-10-17 02:10:22 +0000147 std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
Owen Anderson80b3ce62008-05-28 20:54:50 +0000148
149 if (!OldI2MI.empty())
Owen Anderson788d0412008-08-06 18:35:45 +0000150 for (iterator OI = begin(), OE = end(); OI != OE; ++OI) {
Owen Anderson03857b22008-08-13 21:49:13 +0000151 for (LiveInterval::iterator LI = OI->second->begin(),
152 LE = OI->second->end(); LI != LE; ++LI) {
Owen Anderson4b5b2092008-05-29 18:15:49 +0000153
Owen Anderson7eec0c22008-05-29 23:01:22 +0000154 // Remap the start index of the live range to the corresponding new
155 // number, or our best guess at what it _should_ correspond to if the
156 // original instruction has been erased. This is either the following
157 // instruction or its predecessor.
Owen Anderson7fbad272008-07-23 21:37:49 +0000158 unsigned index = LI->start / InstrSlots::NUM;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000159 unsigned offset = LI->start % InstrSlots::NUM;
Owen Anderson0a7615a2008-07-25 23:06:59 +0000160 if (offset == InstrSlots::LOAD) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000161 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000162 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->start);
Owen Anderson7fbad272008-07-23 21:37:49 +0000163 // Take the pair containing the index
164 std::vector<IdxMBBPair>::const_iterator J =
Owen Andersona0c032f2008-07-29 21:15:44 +0000165 (I == OldI2MBB.end() && OldI2MBB.size()>0) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000166
Owen Anderson7fbad272008-07-23 21:37:49 +0000167 LI->start = getMBBStartIdx(J->second);
168 } else {
169 LI->start = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000170 }
171
172 // Remap the ending index in the same way that we remapped the start,
173 // except for the final step where we always map to the immediately
174 // following instruction.
Owen Andersond7dcbec2008-07-25 19:50:48 +0000175 index = (LI->end - 1) / InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000176 offset = LI->end % InstrSlots::NUM;
Owen Anderson9382b932008-07-30 00:22:56 +0000177 if (offset == InstrSlots::LOAD) {
178 // VReg dies at end of block.
Owen Anderson7fbad272008-07-23 21:37:49 +0000179 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000180 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->end);
Owen Anderson9382b932008-07-30 00:22:56 +0000181 --I;
Owen Anderson7fbad272008-07-23 21:37:49 +0000182
Owen Anderson9382b932008-07-30 00:22:56 +0000183 LI->end = getMBBEndIdx(I->second) + 1;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000184 } else {
Owen Andersond7dcbec2008-07-25 19:50:48 +0000185 unsigned idx = index;
Owen Anderson8d0cc0a2008-07-25 21:07:13 +0000186 while (index < OldI2MI.size() && !OldI2MI[index]) ++index;
187
188 if (index != OldI2MI.size())
189 LI->end = mi2iMap_[OldI2MI[index]] + (idx == index ? offset : 0);
190 else
191 LI->end = InstrSlots::NUM * i2miMap_.size();
Owen Anderson4b5b2092008-05-29 18:15:49 +0000192 }
Owen Anderson788d0412008-08-06 18:35:45 +0000193 }
194
Owen Anderson03857b22008-08-13 21:49:13 +0000195 for (LiveInterval::vni_iterator VNI = OI->second->vni_begin(),
196 VNE = OI->second->vni_end(); VNI != VNE; ++VNI) {
Owen Anderson788d0412008-08-06 18:35:45 +0000197 VNInfo* vni = *VNI;
Owen Anderson745825f42008-05-28 22:40:08 +0000198
Owen Anderson7eec0c22008-05-29 23:01:22 +0000199 // Remap the VNInfo def index, which works the same as the
Owen Anderson788d0412008-08-06 18:35:45 +0000200 // start indices above. VN's with special sentinel defs
201 // don't need to be remapped.
Lang Hames857c4e02009-06-17 21:01:20 +0000202 if (vni->isDefAccurate() && !vni->isUnused()) {
Owen Anderson788d0412008-08-06 18:35:45 +0000203 unsigned index = vni->def / InstrSlots::NUM;
204 unsigned offset = vni->def % InstrSlots::NUM;
Owen Anderson91292392008-07-30 17:42:47 +0000205 if (offset == InstrSlots::LOAD) {
206 std::vector<IdxMBBPair>::const_iterator I =
Owen Anderson0a7615a2008-07-25 23:06:59 +0000207 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->def);
Owen Anderson91292392008-07-30 17:42:47 +0000208 // Take the pair containing the index
209 std::vector<IdxMBBPair>::const_iterator J =
Owen Andersona0c032f2008-07-29 21:15:44 +0000210 (I == OldI2MBB.end() && OldI2MBB.size()>0) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000211
Owen Anderson91292392008-07-30 17:42:47 +0000212 vni->def = getMBBStartIdx(J->second);
213 } else {
214 vni->def = mi2iMap_[OldI2MI[index]] + offset;
215 }
Owen Anderson7eec0c22008-05-29 23:01:22 +0000216 }
Owen Anderson745825f42008-05-28 22:40:08 +0000217
Owen Anderson7eec0c22008-05-29 23:01:22 +0000218 // Remap the VNInfo kill indices, which works the same as
219 // the end indices above.
Owen Anderson4b5b2092008-05-29 18:15:49 +0000220 for (size_t i = 0; i < vni->kills.size(); ++i) {
Owen Anderson9382b932008-07-30 00:22:56 +0000221 // PHI kills don't need to be remapped.
222 if (!vni->kills[i]) continue;
223
Owen Anderson788d0412008-08-06 18:35:45 +0000224 unsigned index = (vni->kills[i]-1) / InstrSlots::NUM;
225 unsigned offset = vni->kills[i] % InstrSlots::NUM;
Owen Anderson309c6162008-09-30 22:51:54 +0000226 if (offset == InstrSlots::LOAD) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000227 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000228 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->kills[i]);
Owen Anderson9382b932008-07-30 00:22:56 +0000229 --I;
Owen Anderson7fbad272008-07-23 21:37:49 +0000230
Owen Anderson788d0412008-08-06 18:35:45 +0000231 vni->kills[i] = getMBBEndIdx(I->second);
Owen Anderson7fbad272008-07-23 21:37:49 +0000232 } else {
Owen Andersond7dcbec2008-07-25 19:50:48 +0000233 unsigned idx = index;
Owen Anderson8d0cc0a2008-07-25 21:07:13 +0000234 while (index < OldI2MI.size() && !OldI2MI[index]) ++index;
235
236 if (index != OldI2MI.size())
237 vni->kills[i] = mi2iMap_[OldI2MI[index]] +
238 (idx == index ? offset : 0);
239 else
240 vni->kills[i] = InstrSlots::NUM * i2miMap_.size();
Owen Anderson7eec0c22008-05-29 23:01:22 +0000241 }
Owen Anderson4b5b2092008-05-29 18:15:49 +0000242 }
Owen Anderson80b3ce62008-05-28 20:54:50 +0000243 }
Owen Anderson788d0412008-08-06 18:35:45 +0000244 }
Owen Anderson80b3ce62008-05-28 20:54:50 +0000245}
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000246
Lang Hamesf41538d2009-06-02 16:53:25 +0000247void LiveIntervals::scaleNumbering(int factor) {
248 // Need to
249 // * scale MBB begin and end points
250 // * scale all ranges.
251 // * Update VNI structures.
252 // * Scale instruction numberings
253
254 // Scale the MBB indices.
255 Idx2MBBMap.clear();
256 for (MachineFunction::iterator MBB = mf_->begin(), MBBE = mf_->end();
257 MBB != MBBE; ++MBB) {
258 std::pair<unsigned, unsigned> &mbbIndices = MBB2IdxMap[MBB->getNumber()];
259 mbbIndices.first = InstrSlots::scale(mbbIndices.first, factor);
260 mbbIndices.second = InstrSlots::scale(mbbIndices.second, factor);
261 Idx2MBBMap.push_back(std::make_pair(mbbIndices.first, MBB));
262 }
263 std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
264
265 // Scale the intervals.
266 for (iterator LI = begin(), LE = end(); LI != LE; ++LI) {
267 LI->second->scaleNumbering(factor);
268 }
269
270 // Scale MachineInstrs.
271 Mi2IndexMap oldmi2iMap = mi2iMap_;
272 unsigned highestSlot = 0;
273 for (Mi2IndexMap::iterator MI = oldmi2iMap.begin(), ME = oldmi2iMap.end();
274 MI != ME; ++MI) {
275 unsigned newSlot = InstrSlots::scale(MI->second, factor);
276 mi2iMap_[MI->first] = newSlot;
277 highestSlot = std::max(highestSlot, newSlot);
278 }
279
280 i2miMap_.clear();
281 i2miMap_.resize(highestSlot + 1);
282 for (Mi2IndexMap::iterator MI = mi2iMap_.begin(), ME = mi2iMap_.end();
283 MI != ME; ++MI) {
284 i2miMap_[MI->second] = MI->first;
285 }
286
287}
288
289
Owen Anderson80b3ce62008-05-28 20:54:50 +0000290/// runOnMachineFunction - Register allocate the whole function
291///
292bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
293 mf_ = &fn;
294 mri_ = &mf_->getRegInfo();
295 tm_ = &fn.getTarget();
296 tri_ = tm_->getRegisterInfo();
297 tii_ = tm_->getInstrInfo();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000298 aa_ = &getAnalysis<AliasAnalysis>();
Owen Anderson80b3ce62008-05-28 20:54:50 +0000299 lv_ = &getAnalysis<LiveVariables>();
300 allocatableRegs_ = tri_->getAllocatableSet(fn);
301
302 computeNumbering();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000303 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000304
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000305 numIntervals += getNumIntervals();
306
Chris Lattner70ca3582004-09-30 15:59:17 +0000307 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000308 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000309}
310
Chris Lattner70ca3582004-09-30 15:59:17 +0000311/// print - Implement the dump method.
Reid Spencerce9653c2004-12-07 04:03:45 +0000312void LiveIntervals::print(std::ostream &O, const Module* ) const {
Chris Lattner70ca3582004-09-30 15:59:17 +0000313 O << "********** INTERVALS **********\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000314 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Owen Anderson03857b22008-08-13 21:49:13 +0000315 I->second->print(O, tri_);
Evan Cheng3f32d652008-06-04 09:18:41 +0000316 O << "\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000317 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000318
319 O << "********** MACHINEINSTRS **********\n";
320 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
321 mbbi != mbbe; ++mbbi) {
322 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
323 for (MachineBasicBlock::iterator mii = mbbi->begin(),
324 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner477e4552004-09-30 16:10:45 +0000325 O << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner70ca3582004-09-30 15:59:17 +0000326 }
327 }
328}
329
Evan Chengc92da382007-11-03 07:20:12 +0000330/// conflictsWithPhysRegDef - Returns true if the specified register
331/// is defined during the duration of the specified interval.
332bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
333 VirtRegMap &vrm, unsigned reg) {
334 for (LiveInterval::Ranges::const_iterator
335 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
336 for (unsigned index = getBaseIndex(I->start),
337 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
338 index += InstrSlots::NUM) {
339 // skip deleted instructions
340 while (index != end && !getInstructionFromIndex(index))
341 index += InstrSlots::NUM;
342 if (index == end) break;
343
344 MachineInstr *MI = getInstructionFromIndex(index);
Evan Cheng04ee5a12009-01-20 19:12:24 +0000345 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
346 if (tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Cheng5d446262007-11-15 08:13:29 +0000347 if (SrcReg == li.reg || DstReg == li.reg)
348 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000349 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
350 MachineOperand& mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000351 if (!mop.isReg())
Evan Chengc92da382007-11-03 07:20:12 +0000352 continue;
353 unsigned PhysReg = mop.getReg();
Evan Cheng5d446262007-11-15 08:13:29 +0000354 if (PhysReg == 0 || PhysReg == li.reg)
Evan Chengc92da382007-11-03 07:20:12 +0000355 continue;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000356 if (TargetRegisterInfo::isVirtualRegister(PhysReg)) {
Evan Cheng5d446262007-11-15 08:13:29 +0000357 if (!vrm.hasPhys(PhysReg))
358 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000359 PhysReg = vrm.getPhys(PhysReg);
Evan Cheng5d446262007-11-15 08:13:29 +0000360 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000361 if (PhysReg && tri_->regsOverlap(PhysReg, reg))
Evan Chengc92da382007-11-03 07:20:12 +0000362 return true;
363 }
364 }
365 }
366
367 return false;
368}
369
Evan Cheng8f90b6e2009-01-07 02:08:57 +0000370/// conflictsWithPhysRegRef - Similar to conflictsWithPhysRegRef except
371/// it can check use as well.
372bool LiveIntervals::conflictsWithPhysRegRef(LiveInterval &li,
373 unsigned Reg, bool CheckUse,
374 SmallPtrSet<MachineInstr*,32> &JoinedCopies) {
375 for (LiveInterval::Ranges::const_iterator
376 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
377 for (unsigned index = getBaseIndex(I->start),
378 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
379 index += InstrSlots::NUM) {
380 // Skip deleted instructions.
381 MachineInstr *MI = 0;
382 while (index != end) {
383 MI = getInstructionFromIndex(index);
384 if (MI)
385 break;
386 index += InstrSlots::NUM;
387 }
388 if (index == end) break;
389
390 if (JoinedCopies.count(MI))
391 continue;
392 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
393 MachineOperand& MO = MI->getOperand(i);
394 if (!MO.isReg())
395 continue;
396 if (MO.isUse() && !CheckUse)
397 continue;
398 unsigned PhysReg = MO.getReg();
399 if (PhysReg == 0 || TargetRegisterInfo::isVirtualRegister(PhysReg))
400 continue;
401 if (tri_->isSubRegister(Reg, PhysReg))
402 return true;
403 }
404 }
405 }
406
407 return false;
408}
409
410
Evan Cheng549f27d32007-08-13 23:45:17 +0000411void LiveIntervals::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000412 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000413 cerr << tri_->getName(reg);
Evan Cheng549f27d32007-08-13 23:45:17 +0000414 else
415 cerr << "%reg" << reg;
416}
417
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000418void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000419 MachineBasicBlock::iterator mi,
Owen Anderson6b098de2008-06-25 23:39:39 +0000420 unsigned MIIdx, MachineOperand& MO,
Evan Chengef0732d2008-07-10 07:35:43 +0000421 unsigned MOIdx,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000422 LiveInterval &interval) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000423 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000424 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000425
Evan Cheng419852c2008-04-03 16:39:43 +0000426 if (mi->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
427 DOUT << "is a implicit_def\n";
428 return;
429 }
430
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000431 // Virtual registers may be defined multiple times (due to phi
432 // elimination and 2-addr elimination). Much of what we do only has to be
433 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000434 // time we see a vreg.
435 if (interval.empty()) {
436 // Get the Idx of the defining instructions.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000437 unsigned defIndex = getDefIndex(MIIdx);
Dale Johannesen86b49f82008-09-24 01:07:17 +0000438 // Earlyclobbers move back one.
439 if (MO.isEarlyClobber())
440 defIndex = getUseIndex(MIIdx);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000441 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000442 MachineInstr *CopyMI = NULL;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000443 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000444 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000445 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Dan Gohman97121ba2009-04-08 00:15:30 +0000446 mi->getOpcode() == TargetInstrInfo::SUBREG_TO_REG ||
Evan Cheng04ee5a12009-01-20 19:12:24 +0000447 tii_->isMoveInstr(*mi, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000448 CopyMI = mi;
Evan Cheng5379f412008-12-19 20:58:01 +0000449 // Earlyclobbers move back one.
Lang Hames857c4e02009-06-17 21:01:20 +0000450 ValNo = interval.getNextValue(defIndex, CopyMI, true, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000451
452 assert(ValNo->id == 0 && "First value in interval is not 0?");
Chris Lattner7ac2d312004-07-24 02:59:07 +0000453
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000454 // Loop over all of the blocks that the vreg is defined in. There are
455 // two cases we have to handle here. The most common case is a vreg
456 // whose lifetime is contained within a basic block. In this case there
457 // will be a single kill, in MBB, which comes after the definition.
458 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
459 // FIXME: what about dead vars?
460 unsigned killIdx;
461 if (vi.Kills[0] != mi)
462 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
463 else
464 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000465
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000466 // If the kill happens after the definition, we have an intra-block
467 // live range.
468 if (killIdx > defIndex) {
Jeffrey Yasskin493a3d02009-05-26 18:27:15 +0000469 assert(vi.AliveBlocks.empty() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000470 "Shouldn't be alive across any blocks!");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000471 LiveRange LR(defIndex, killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000472 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000473 DOUT << " +" << LR << "\n";
Evan Chengf3bb2e62007-09-05 21:46:51 +0000474 interval.addKill(ValNo, killIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000475 return;
476 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000477 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000478
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000479 // The other case we handle is when a virtual register lives to the end
480 // of the defining block, potentially live across some blocks, then is
481 // live into some number of blocks, but gets killed. Start by adding a
482 // range that goes from this definition to the end of the defining block.
Owen Anderson7fbad272008-07-23 21:37:49 +0000483 LiveRange NewLR(defIndex, getMBBEndIdx(mbb)+1, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000484 DOUT << " +" << NewLR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000485 interval.addRange(NewLR);
486
487 // Iterate over all of the blocks that the variable is completely
488 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
489 // live interval.
Jeffrey Yasskin493a3d02009-05-26 18:27:15 +0000490 for (SparseBitVector<>::iterator I = vi.AliveBlocks.begin(),
491 E = vi.AliveBlocks.end(); I != E; ++I) {
492 LiveRange LR(getMBBStartIdx(*I),
493 getMBBEndIdx(*I)+1, // MBB ends at -1.
Dan Gohman4a829ec2008-11-13 16:31:27 +0000494 ValNo);
495 interval.addRange(LR);
496 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000497 }
498
499 // Finally, this virtual register is live from the start of any killing
500 // block to the 'use' slot of the killing instruction.
501 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
502 MachineInstr *Kill = vi.Kills[i];
Evan Cheng8df78602007-08-08 03:00:28 +0000503 unsigned killIdx = getUseIndex(getInstructionIndex(Kill))+1;
Chris Lattner428b92e2006-09-15 03:57:23 +0000504 LiveRange LR(getMBBStartIdx(Kill->getParent()),
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000505 killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000506 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000507 interval.addKill(ValNo, killIdx);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000508 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000509 }
510
511 } else {
512 // If this is the second time we see a virtual register definition, it
513 // must be due to phi elimination or two addr elimination. If this is
Evan Chengbf105c82006-11-03 03:04:46 +0000514 // the result of two address elimination, then the vreg is one of the
515 // def-and-use register operand.
Bob Wilsond9df5012009-04-09 17:16:43 +0000516 if (mi->isRegTiedToUseOperand(MOIdx)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000517 // If this is a two-address definition, then we have already processed
518 // the live range. The only problem is that we didn't realize there
519 // are actually two values in the live interval. Because of this we
520 // need to take the LiveRegion that defines this register and split it
521 // into two values.
Evan Chenga07cec92008-01-10 08:22:10 +0000522 assert(interval.containsOneValue());
523 unsigned DefIndex = getDefIndex(interval.getValNumInfo(0)->def);
Chris Lattner6b128bd2006-09-03 08:07:11 +0000524 unsigned RedefIndex = getDefIndex(MIIdx);
Evan Chengfb112882009-03-23 08:01:15 +0000525 if (MO.isEarlyClobber())
526 RedefIndex = getUseIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000527
Evan Cheng4f8ff162007-08-11 00:59:19 +0000528 const LiveRange *OldLR = interval.getLiveRangeContaining(RedefIndex-1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000529 VNInfo *OldValNo = OldLR->valno;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000530
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000531 // Delete the initial value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000532 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000533 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000534
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000535 // Two-address vregs should always only be redefined once. This means
536 // that at this point, there should be exactly one value number in it.
537 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
538
Chris Lattner91725b72006-08-31 05:54:43 +0000539 // The new value number (#1) is defined by the instruction we claimed
540 // defined value #0.
Evan Chengc8d044e2008-02-15 18:24:29 +0000541 VNInfo *ValNo = interval.getNextValue(OldValNo->def, OldValNo->copy,
Lang Hames857c4e02009-06-17 21:01:20 +0000542 false, // update at *
Evan Chengc8d044e2008-02-15 18:24:29 +0000543 VNInfoAllocator);
Lang Hames857c4e02009-06-17 21:01:20 +0000544 ValNo->setFlags(OldValNo->getFlags()); // * <- updating here
545
Chris Lattner91725b72006-08-31 05:54:43 +0000546 // Value#0 is now defined by the 2-addr instruction.
Evan Chengc8d044e2008-02-15 18:24:29 +0000547 OldValNo->def = RedefIndex;
548 OldValNo->copy = 0;
Evan Chengfb112882009-03-23 08:01:15 +0000549 if (MO.isEarlyClobber())
Lang Hames857c4e02009-06-17 21:01:20 +0000550 OldValNo->setHasRedefByEC(true);
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000551
552 // Add the new live interval which replaces the range for the input copy.
553 LiveRange LR(DefIndex, RedefIndex, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000554 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000555 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000556 interval.addKill(ValNo, RedefIndex);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000557
558 // If this redefinition is dead, we need to add a dummy unit live
559 // range covering the def slot.
Owen Anderson6b098de2008-06-25 23:39:39 +0000560 if (MO.isDead())
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000561 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, OldValNo));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000562
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000563 DOUT << " RESULT: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000564 interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000565
566 } else {
567 // Otherwise, this must be because of phi elimination. If this is the
568 // first redefinition of the vreg that we have seen, go back and change
569 // the live range in the PHI block to be a different value number.
570 if (interval.containsOneValue()) {
571 assert(vi.Kills.size() == 1 &&
572 "PHI elimination vreg should have one kill, the PHI itself!");
573
574 // Remove the old range that we now know has an incorrect number.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000575 VNInfo *VNI = interval.getValNumInfo(0);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000576 MachineInstr *Killer = vi.Kills[0];
Chris Lattner428b92e2006-09-15 03:57:23 +0000577 unsigned Start = getMBBStartIdx(Killer->getParent());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000578 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000579 DOUT << " Removing [" << Start << "," << End << "] from: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000580 interval.print(DOUT, tri_); DOUT << "\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000581 interval.removeRange(Start, End);
Lang Hames857c4e02009-06-17 21:01:20 +0000582 VNI->setHasPHIKill(true);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000583 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000584
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000585 // Replace the interval with one of a NEW value number. Note that this
586 // value number isn't actually defined by an instruction, weird huh? :)
Lang Hames10382fb2009-06-19 02:17:53 +0000587 LiveRange LR(Start, End,
588 interval.getNextValue(mbb->getNumber(), 0, false, VNInfoAllocator));
Lang Hames857c4e02009-06-17 21:01:20 +0000589 LR.valno->setIsPHIDef(true);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000590 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000591 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000592 interval.addKill(LR.valno, End);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000593 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000594 }
595
596 // In the case of PHI elimination, each variable definition is only
597 // live until the end of the block. We've already taken care of the
598 // rest of the live range.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000599 unsigned defIndex = getDefIndex(MIIdx);
Evan Chengfb112882009-03-23 08:01:15 +0000600 if (MO.isEarlyClobber())
601 defIndex = getUseIndex(MIIdx);
Chris Lattner91725b72006-08-31 05:54:43 +0000602
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000603 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000604 MachineInstr *CopyMI = NULL;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000605 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000606 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000607 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Dan Gohman97121ba2009-04-08 00:15:30 +0000608 mi->getOpcode() == TargetInstrInfo::SUBREG_TO_REG ||
Evan Cheng04ee5a12009-01-20 19:12:24 +0000609 tii_->isMoveInstr(*mi, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000610 CopyMI = mi;
Lang Hames857c4e02009-06-17 21:01:20 +0000611 ValNo = interval.getNextValue(defIndex, CopyMI, true, VNInfoAllocator);
Chris Lattner91725b72006-08-31 05:54:43 +0000612
Owen Anderson7fbad272008-07-23 21:37:49 +0000613 unsigned killIndex = getMBBEndIdx(mbb) + 1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000614 LiveRange LR(defIndex, killIndex, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000615 interval.addRange(LR);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000616 interval.addKill(ValNo, killIndex);
Lang Hames857c4e02009-06-17 21:01:20 +0000617 ValNo->setHasPHIKill(true);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000618 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000619 }
620 }
621
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000622 DOUT << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000623}
624
Chris Lattnerf35fef72004-07-23 21:24:19 +0000625void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000626 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000627 unsigned MIIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000628 MachineOperand& MO,
Chris Lattner91725b72006-08-31 05:54:43 +0000629 LiveInterval &interval,
Evan Chengc8d044e2008-02-15 18:24:29 +0000630 MachineInstr *CopyMI) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000631 // A physical register cannot be live across basic block, so its
632 // lifetime must end somewhere in its defining basic block.
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000633 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000634
Chris Lattner6b128bd2006-09-03 08:07:11 +0000635 unsigned baseIndex = MIIdx;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000636 unsigned start = getDefIndex(baseIndex);
Dale Johannesen86b49f82008-09-24 01:07:17 +0000637 // Earlyclobbers move back one.
638 if (MO.isEarlyClobber())
639 start = getUseIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000640 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000641
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000642 // If it is not used after definition, it is considered dead at
643 // the instruction defining it. Hence its interval is:
644 // [defSlot(def), defSlot(def)+1)
Owen Anderson6b098de2008-06-25 23:39:39 +0000645 if (MO.isDead()) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000646 DOUT << " dead";
Dale Johannesen86b49f82008-09-24 01:07:17 +0000647 end = start + 1;
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000648 goto exit;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000649 }
650
651 // If it is not dead on definition, it must be killed by a
652 // subsequent instruction. Hence its interval is:
653 // [defSlot(def), useSlot(kill)+1)
Owen Anderson7fbad272008-07-23 21:37:49 +0000654 baseIndex += InstrSlots::NUM;
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000655 while (++mi != MBB->end()) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000656 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
657 getInstructionFromIndex(baseIndex) == 0)
658 baseIndex += InstrSlots::NUM;
Evan Cheng6130f662008-03-05 00:59:57 +0000659 if (mi->killsRegister(interval.reg, tri_)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000660 DOUT << " killed";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000661 end = getUseIndex(baseIndex) + 1;
662 goto exit;
Evan Chengc45288e2009-04-27 20:42:46 +0000663 } else {
664 int DefIdx = mi->findRegisterDefOperandIdx(interval.reg, false, tri_);
665 if (DefIdx != -1) {
666 if (mi->isRegTiedToUseOperand(DefIdx)) {
667 // Two-address instruction.
668 end = getDefIndex(baseIndex);
669 if (mi->getOperand(DefIdx).isEarlyClobber())
670 end = getUseIndex(baseIndex);
671 } else {
672 // Another instruction redefines the register before it is ever read.
673 // Then the register is essentially dead at the instruction that defines
674 // it. Hence its interval is:
675 // [defSlot(def), defSlot(def)+1)
676 DOUT << " dead";
677 end = start + 1;
678 }
679 goto exit;
680 }
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000681 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000682
683 baseIndex += InstrSlots::NUM;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000684 }
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000685
686 // The only case we should have a dead physreg here without a killing or
687 // instruction where we know it's dead is if it is live-in to the function
Evan Chengd521bc92009-04-27 17:36:47 +0000688 // and never used. Another possible case is the implicit use of the
689 // physical register has been deleted by two-address pass.
Dale Johannesen86b49f82008-09-24 01:07:17 +0000690 end = start + 1;
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000691
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000692exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000693 assert(start < end && "did not find end of interval?");
Chris Lattnerf768bba2005-03-09 23:05:19 +0000694
Evan Cheng24a3cc42007-04-25 07:30:23 +0000695 // Already exists? Extend old live interval.
696 LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
Evan Cheng5379f412008-12-19 20:58:01 +0000697 bool Extend = OldLR != interval.end();
698 VNInfo *ValNo = Extend
Lang Hames857c4e02009-06-17 21:01:20 +0000699 ? OldLR->valno : interval.getNextValue(start, CopyMI, true, VNInfoAllocator);
Evan Cheng5379f412008-12-19 20:58:01 +0000700 if (MO.isEarlyClobber() && Extend)
Lang Hames857c4e02009-06-17 21:01:20 +0000701 ValNo->setHasRedefByEC(true);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000702 LiveRange LR(start, end, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000703 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000704 interval.addKill(LR.valno, end);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000705 DOUT << " +" << LR << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000706}
707
Chris Lattnerf35fef72004-07-23 21:24:19 +0000708void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
709 MachineBasicBlock::iterator MI,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000710 unsigned MIIdx,
Evan Chengef0732d2008-07-10 07:35:43 +0000711 MachineOperand& MO,
712 unsigned MOIdx) {
Owen Anderson6b098de2008-06-25 23:39:39 +0000713 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Evan Chengef0732d2008-07-10 07:35:43 +0000714 handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000715 getOrCreateInterval(MO.getReg()));
716 else if (allocatableRegs_[MO.getReg()]) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000717 MachineInstr *CopyMI = NULL;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000718 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000719 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000720 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Dan Gohman97121ba2009-04-08 00:15:30 +0000721 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG ||
Evan Cheng04ee5a12009-01-20 19:12:24 +0000722 tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000723 CopyMI = MI;
Evan Chengc45288e2009-04-27 20:42:46 +0000724 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
Owen Anderson6b098de2008-06-25 23:39:39 +0000725 getOrCreateInterval(MO.getReg()), CopyMI);
Evan Cheng24a3cc42007-04-25 07:30:23 +0000726 // Def of a register also defines its sub-registers.
Owen Anderson6b098de2008-06-25 23:39:39 +0000727 for (const unsigned* AS = tri_->getSubRegisters(MO.getReg()); *AS; ++AS)
Evan Cheng6130f662008-03-05 00:59:57 +0000728 // If MI also modifies the sub-register explicitly, avoid processing it
729 // more than once. Do not pass in TRI here so it checks for exact match.
730 if (!MI->modifiesRegister(*AS))
Evan Chengc45288e2009-04-27 20:42:46 +0000731 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
Owen Anderson6b098de2008-06-25 23:39:39 +0000732 getOrCreateInterval(*AS), 0);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000733 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000734}
735
Evan Chengb371f452007-02-19 21:49:54 +0000736void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000737 unsigned MIIdx,
Evan Cheng24a3cc42007-04-25 07:30:23 +0000738 LiveInterval &interval, bool isAlias) {
Evan Chengb371f452007-02-19 21:49:54 +0000739 DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg));
740
741 // Look for kills, if it reaches a def before it's killed, then it shouldn't
742 // be considered a livein.
743 MachineBasicBlock::iterator mi = MBB->begin();
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000744 unsigned baseIndex = MIIdx;
745 unsigned start = baseIndex;
Owen Anderson99500ae2008-09-15 22:00:38 +0000746 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
747 getInstructionFromIndex(baseIndex) == 0)
748 baseIndex += InstrSlots::NUM;
749 unsigned end = baseIndex;
Evan Cheng0076c612009-03-05 03:34:26 +0000750 bool SeenDefUse = false;
Owen Anderson99500ae2008-09-15 22:00:38 +0000751
Evan Chengb371f452007-02-19 21:49:54 +0000752 while (mi != MBB->end()) {
Evan Cheng6130f662008-03-05 00:59:57 +0000753 if (mi->killsRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000754 DOUT << " killed";
755 end = getUseIndex(baseIndex) + 1;
Evan Cheng0076c612009-03-05 03:34:26 +0000756 SeenDefUse = true;
Lang Hamesd21c3162009-06-18 22:01:47 +0000757 break;
Evan Cheng6130f662008-03-05 00:59:57 +0000758 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000759 // Another instruction redefines the register before it is ever read.
760 // Then the register is essentially dead at the instruction that defines
761 // it. Hence its interval is:
762 // [defSlot(def), defSlot(def)+1)
763 DOUT << " dead";
764 end = getDefIndex(start) + 1;
Evan Cheng0076c612009-03-05 03:34:26 +0000765 SeenDefUse = true;
Lang Hamesd21c3162009-06-18 22:01:47 +0000766 break;
Evan Chengb371f452007-02-19 21:49:54 +0000767 }
768
769 baseIndex += InstrSlots::NUM;
770 ++mi;
Evan Cheng0076c612009-03-05 03:34:26 +0000771 if (mi != MBB->end()) {
772 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
773 getInstructionFromIndex(baseIndex) == 0)
774 baseIndex += InstrSlots::NUM;
775 }
Evan Chengb371f452007-02-19 21:49:54 +0000776 }
777
Evan Cheng75611fb2007-06-27 01:16:36 +0000778 // Live-in register might not be used at all.
Evan Cheng0076c612009-03-05 03:34:26 +0000779 if (!SeenDefUse) {
Evan Cheng292da942007-06-27 18:47:28 +0000780 if (isAlias) {
781 DOUT << " dead";
Evan Cheng75611fb2007-06-27 01:16:36 +0000782 end = getDefIndex(MIIdx) + 1;
Evan Cheng292da942007-06-27 18:47:28 +0000783 } else {
784 DOUT << " live through";
785 end = baseIndex;
786 }
Evan Cheng24a3cc42007-04-25 07:30:23 +0000787 }
788
Lang Hames10382fb2009-06-19 02:17:53 +0000789 VNInfo *vni =
790 interval.getNextValue(MBB->getNumber(), 0, false, VNInfoAllocator);
Lang Hamesd21c3162009-06-18 22:01:47 +0000791 vni->setIsPHIDef(true);
792 LiveRange LR(start, end, vni);
793
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000794 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000795 interval.addKill(LR.valno, end);
Evan Cheng24c2e5c2007-08-08 07:03:29 +0000796 DOUT << " +" << LR << '\n';
Evan Chengb371f452007-02-19 21:49:54 +0000797}
798
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000799/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000800/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000801/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000802/// which a variable is live
Dale Johannesen91aac102008-09-17 21:13:11 +0000803void LiveIntervals::computeIntervals() {
Dale Johannesen91aac102008-09-17 21:13:11 +0000804
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000805 DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
806 << "********** Function: "
807 << ((Value*)mf_->getFunction())->getName() << '\n';
Owen Anderson7fbad272008-07-23 21:37:49 +0000808
Chris Lattner428b92e2006-09-15 03:57:23 +0000809 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
810 MBBI != E; ++MBBI) {
811 MachineBasicBlock *MBB = MBBI;
Owen Anderson134eb732008-09-21 20:43:24 +0000812 // Track the index of the current machine instr.
813 unsigned MIIndex = getMBBStartIdx(MBB);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000814 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000815
Chris Lattner428b92e2006-09-15 03:57:23 +0000816 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000817
Dan Gohmancb406c22007-10-03 19:26:29 +0000818 // Create intervals for live-ins to this BB first.
819 for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
820 LE = MBB->livein_end(); LI != LE; ++LI) {
821 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
822 // Multiple live-ins can alias the same register.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000823 for (const unsigned* AS = tri_->getSubRegisters(*LI); *AS; ++AS)
Dan Gohmancb406c22007-10-03 19:26:29 +0000824 if (!hasInterval(*AS))
825 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
826 true);
Chris Lattnerdffb2e82006-09-04 18:27:40 +0000827 }
828
Owen Anderson99500ae2008-09-15 22:00:38 +0000829 // Skip over empty initial indices.
830 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
831 getInstructionFromIndex(MIIndex) == 0)
832 MIIndex += InstrSlots::NUM;
833
Chris Lattner428b92e2006-09-15 03:57:23 +0000834 for (; MI != miEnd; ++MI) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000835 DOUT << MIIndex << "\t" << *MI;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000836
Evan Cheng438f7bc2006-11-10 08:43:01 +0000837 // Handle defs.
Chris Lattner428b92e2006-09-15 03:57:23 +0000838 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
839 MachineOperand &MO = MI->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000840 // handle register defs - build intervals
Dan Gohmand735b802008-10-03 15:45:36 +0000841 if (MO.isReg() && MO.getReg() && MO.isDef()) {
Evan Chengef0732d2008-07-10 07:35:43 +0000842 handleRegisterDef(MBB, MI, MIIndex, MO, i);
Dale Johannesen91aac102008-09-17 21:13:11 +0000843 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000844 }
Evan Cheng99fe34b2008-10-18 05:18:55 +0000845
846 // Skip over the empty slots after each instruction.
847 unsigned Slots = MI->getDesc().getNumDefs();
848 if (Slots == 0)
849 Slots = 1;
850 MIIndex += InstrSlots::NUM * Slots;
Owen Anderson7fbad272008-07-23 21:37:49 +0000851
852 // Skip over empty indices.
853 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
854 getInstructionFromIndex(MIIndex) == 0)
855 MIIndex += InstrSlots::NUM;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000856 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000857 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000858}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000859
Evan Chengd0e32c52008-10-29 05:06:14 +0000860bool LiveIntervals::findLiveInMBBs(unsigned Start, unsigned End,
Evan Chenga5bfc972007-10-17 06:53:44 +0000861 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
Evan Cheng4ca980e2007-10-17 02:10:22 +0000862 std::vector<IdxMBBPair>::const_iterator I =
Evan Chengd0e32c52008-10-29 05:06:14 +0000863 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), Start);
Evan Cheng4ca980e2007-10-17 02:10:22 +0000864
865 bool ResVal = false;
866 while (I != Idx2MBBMap.end()) {
Dan Gohman2ad82452008-11-26 05:50:31 +0000867 if (I->first >= End)
Evan Cheng4ca980e2007-10-17 02:10:22 +0000868 break;
869 MBBs.push_back(I->second);
870 ResVal = true;
871 ++I;
872 }
873 return ResVal;
874}
875
Evan Chengd0e32c52008-10-29 05:06:14 +0000876bool LiveIntervals::findReachableMBBs(unsigned Start, unsigned End,
877 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
878 std::vector<IdxMBBPair>::const_iterator I =
879 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), Start);
880
881 bool ResVal = false;
882 while (I != Idx2MBBMap.end()) {
883 if (I->first > End)
884 break;
885 MachineBasicBlock *MBB = I->second;
886 if (getMBBEndIdx(MBB) > End)
887 break;
888 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
889 SE = MBB->succ_end(); SI != SE; ++SI)
890 MBBs.push_back(*SI);
891 ResVal = true;
892 ++I;
893 }
894 return ResVal;
895}
896
Owen Anderson03857b22008-08-13 21:49:13 +0000897LiveInterval* LiveIntervals::createInterval(unsigned reg) {
Evan Cheng0a1fcce2009-02-08 11:04:35 +0000898 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? HUGE_VALF : 0.0F;
Owen Anderson03857b22008-08-13 21:49:13 +0000899 return new LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000900}
Evan Chengf2fbca62007-11-12 06:35:08 +0000901
Evan Cheng0a1fcce2009-02-08 11:04:35 +0000902/// dupInterval - Duplicate a live interval. The caller is responsible for
903/// managing the allocated memory.
904LiveInterval* LiveIntervals::dupInterval(LiveInterval *li) {
905 LiveInterval *NewLI = createInterval(li->reg);
Evan Cheng90f95f82009-06-14 20:22:55 +0000906 NewLI->Copy(*li, mri_, getVNInfoAllocator());
Evan Cheng0a1fcce2009-02-08 11:04:35 +0000907 return NewLI;
908}
909
Evan Chengc8d044e2008-02-15 18:24:29 +0000910/// getVNInfoSourceReg - Helper function that parses the specified VNInfo
911/// copy field and returns the source register that defines it.
912unsigned LiveIntervals::getVNInfoSourceReg(const VNInfo *VNI) const {
913 if (!VNI->copy)
914 return 0;
915
Evan Cheng8f90b6e2009-01-07 02:08:57 +0000916 if (VNI->copy->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
917 // If it's extracting out of a physical register, return the sub-register.
918 unsigned Reg = VNI->copy->getOperand(1).getReg();
919 if (TargetRegisterInfo::isPhysicalRegister(Reg))
920 Reg = tri_->getSubReg(Reg, VNI->copy->getOperand(2).getImm());
921 return Reg;
Dan Gohman97121ba2009-04-08 00:15:30 +0000922 } else if (VNI->copy->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
923 VNI->copy->getOpcode() == TargetInstrInfo::SUBREG_TO_REG)
Evan Cheng7e073ba2008-04-09 20:57:25 +0000924 return VNI->copy->getOperand(2).getReg();
Evan Cheng8f90b6e2009-01-07 02:08:57 +0000925
Evan Cheng04ee5a12009-01-20 19:12:24 +0000926 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
927 if (tii_->isMoveInstr(*VNI->copy, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000928 return SrcReg;
929 assert(0 && "Unrecognized copy instruction!");
930 return 0;
931}
Evan Chengf2fbca62007-11-12 06:35:08 +0000932
933//===----------------------------------------------------------------------===//
934// Register allocator hooks.
935//
936
Evan Chengd70dbb52008-02-22 09:24:50 +0000937/// getReMatImplicitUse - If the remat definition MI has one (for now, we only
938/// allow one) virtual register operand, then its uses are implicitly using
939/// the register. Returns the virtual register.
940unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
941 MachineInstr *MI) const {
942 unsigned RegOp = 0;
943 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
944 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000945 if (!MO.isReg() || !MO.isUse())
Evan Chengd70dbb52008-02-22 09:24:50 +0000946 continue;
947 unsigned Reg = MO.getReg();
948 if (Reg == 0 || Reg == li.reg)
949 continue;
Chris Lattner1873d0c2009-06-27 04:06:41 +0000950
951 if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
952 !allocatableRegs_[Reg])
953 continue;
Evan Chengd70dbb52008-02-22 09:24:50 +0000954 // FIXME: For now, only remat MI with at most one register operand.
955 assert(!RegOp &&
956 "Can't rematerialize instruction with multiple register operand!");
957 RegOp = MO.getReg();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000958#ifndef NDEBUG
Evan Chengd70dbb52008-02-22 09:24:50 +0000959 break;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000960#endif
Evan Chengd70dbb52008-02-22 09:24:50 +0000961 }
962 return RegOp;
963}
964
965/// isValNoAvailableAt - Return true if the val# of the specified interval
966/// which reaches the given instruction also reaches the specified use index.
967bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
968 unsigned UseIdx) const {
969 unsigned Index = getInstructionIndex(MI);
970 VNInfo *ValNo = li.FindLiveRangeContaining(Index)->valno;
971 LiveInterval::const_iterator UI = li.FindLiveRangeContaining(UseIdx);
972 return UI != li.end() && UI->valno == ValNo;
973}
974
Evan Chengf2fbca62007-11-12 06:35:08 +0000975/// isReMaterializable - Returns true if the definition MI of the specified
976/// val# of the specified interval is re-materializable.
977bool LiveIntervals::isReMaterializable(const LiveInterval &li,
Evan Cheng5ef3a042007-12-06 00:01:56 +0000978 const VNInfo *ValNo, MachineInstr *MI,
Evan Chengdc377862008-09-30 15:44:16 +0000979 SmallVectorImpl<LiveInterval*> &SpillIs,
Evan Cheng5ef3a042007-12-06 00:01:56 +0000980 bool &isLoad) {
Evan Chengf2fbca62007-11-12 06:35:08 +0000981 if (DisableReMat)
982 return false;
983
Evan Cheng20ccded2008-03-15 00:19:36 +0000984 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
Evan Chengd70dbb52008-02-22 09:24:50 +0000985 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000986
987 int FrameIdx = 0;
988 if (tii_->isLoadFromStackSlot(MI, FrameIdx) &&
Evan Cheng249ded32008-02-23 03:38:34 +0000989 mf_->getFrameInfo()->isImmutableObjectIndex(FrameIdx))
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000990 // FIXME: Let target specific isReallyTriviallyReMaterializable determines
991 // this but remember this is not safe to fold into a two-address
992 // instruction.
Evan Cheng249ded32008-02-23 03:38:34 +0000993 // This is a load from fixed stack slot. It can be rematerialized.
Evan Chengdd3465e2008-02-23 01:44:27 +0000994 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000995
Dan Gohman6d69ba82008-07-25 00:02:30 +0000996 // If the target-specific rules don't identify an instruction as
997 // being trivially rematerializable, use some target-independent
998 // rules.
999 if (!MI->getDesc().isRematerializable() ||
1000 !tii_->isTriviallyReMaterializable(MI)) {
Dan Gohman4c8f8702008-07-25 15:08:37 +00001001 if (!EnableAggressiveRemat)
1002 return false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001003
Dan Gohman0471a792008-07-28 18:43:51 +00001004 // If the instruction accesses memory but the memoperands have been lost,
Dan Gohman6d69ba82008-07-25 00:02:30 +00001005 // we can't analyze it.
1006 const TargetInstrDesc &TID = MI->getDesc();
1007 if ((TID.mayLoad() || TID.mayStore()) && MI->memoperands_empty())
1008 return false;
1009
1010 // Avoid instructions obviously unsafe for remat.
1011 if (TID.hasUnmodeledSideEffects() || TID.isNotDuplicable())
1012 return false;
1013
1014 // If the instruction accesses memory and the memory could be non-constant,
1015 // assume the instruction is not rematerializable.
Evan Chengdc377862008-09-30 15:44:16 +00001016 for (std::list<MachineMemOperand>::const_iterator
1017 I = MI->memoperands_begin(), E = MI->memoperands_end(); I != E; ++I){
Dan Gohman6d69ba82008-07-25 00:02:30 +00001018 const MachineMemOperand &MMO = *I;
1019 if (MMO.isVolatile() || MMO.isStore())
1020 return false;
1021 const Value *V = MMO.getValue();
1022 if (!V)
1023 return false;
1024 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
1025 if (!PSV->isConstant(mf_->getFrameInfo()))
Evan Chengd70dbb52008-02-22 09:24:50 +00001026 return false;
Dan Gohman6d69ba82008-07-25 00:02:30 +00001027 } else if (!aa_->pointsToConstantMemory(V))
1028 return false;
1029 }
1030
1031 // If any of the registers accessed are non-constant, conservatively assume
1032 // the instruction is not rematerializable.
1033 unsigned ImpUse = 0;
1034 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1035 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001036 if (MO.isReg()) {
Dan Gohman6d69ba82008-07-25 00:02:30 +00001037 unsigned Reg = MO.getReg();
1038 if (Reg == 0)
1039 continue;
1040 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1041 return false;
1042
1043 // Only allow one def, and that in the first operand.
1044 if (MO.isDef() != (i == 0))
1045 return false;
1046
1047 // Only allow constant-valued registers.
1048 bool IsLiveIn = mri_->isLiveIn(Reg);
1049 MachineRegisterInfo::def_iterator I = mri_->def_begin(Reg),
1050 E = mri_->def_end();
1051
Dan Gohmanc93ced5b2008-12-08 04:53:23 +00001052 // For the def, it should be the only def of that register.
Dan Gohman6d69ba82008-07-25 00:02:30 +00001053 if (MO.isDef() && (next(I) != E || IsLiveIn))
1054 return false;
1055
1056 if (MO.isUse()) {
1057 // Only allow one use other register use, as that's all the
1058 // remat mechanisms support currently.
1059 if (Reg != li.reg) {
1060 if (ImpUse == 0)
1061 ImpUse = Reg;
1062 else if (Reg != ImpUse)
1063 return false;
1064 }
Dan Gohmanc93ced5b2008-12-08 04:53:23 +00001065 // For the use, there should be only one associated def.
Dan Gohman6d69ba82008-07-25 00:02:30 +00001066 if (I != E && (next(I) != E || IsLiveIn))
1067 return false;
1068 }
Evan Chengd70dbb52008-02-22 09:24:50 +00001069 }
1070 }
Evan Cheng5ef3a042007-12-06 00:01:56 +00001071 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001072
Dan Gohman6d69ba82008-07-25 00:02:30 +00001073 unsigned ImpUse = getReMatImplicitUse(li, MI);
1074 if (ImpUse) {
1075 const LiveInterval &ImpLi = getInterval(ImpUse);
1076 for (MachineRegisterInfo::use_iterator ri = mri_->use_begin(li.reg),
1077 re = mri_->use_end(); ri != re; ++ri) {
1078 MachineInstr *UseMI = &*ri;
1079 unsigned UseIdx = getInstructionIndex(UseMI);
1080 if (li.FindLiveRangeContaining(UseIdx)->valno != ValNo)
1081 continue;
1082 if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
1083 return false;
1084 }
Evan Chengdc377862008-09-30 15:44:16 +00001085
1086 // If a register operand of the re-materialized instruction is going to
1087 // be spilled next, then it's not legal to re-materialize this instruction.
1088 for (unsigned i = 0, e = SpillIs.size(); i != e; ++i)
1089 if (ImpUse == SpillIs[i]->reg)
1090 return false;
Dan Gohman6d69ba82008-07-25 00:02:30 +00001091 }
1092 return true;
Evan Cheng5ef3a042007-12-06 00:01:56 +00001093}
1094
Evan Cheng06587492008-10-24 02:05:00 +00001095/// isReMaterializable - Returns true if the definition MI of the specified
1096/// val# of the specified interval is re-materializable.
1097bool LiveIntervals::isReMaterializable(const LiveInterval &li,
1098 const VNInfo *ValNo, MachineInstr *MI) {
1099 SmallVector<LiveInterval*, 4> Dummy1;
1100 bool Dummy2;
1101 return isReMaterializable(li, ValNo, MI, Dummy1, Dummy2);
1102}
1103
Evan Cheng5ef3a042007-12-06 00:01:56 +00001104/// isReMaterializable - Returns true if every definition of MI of every
1105/// val# of the specified interval is re-materializable.
Evan Chengdc377862008-09-30 15:44:16 +00001106bool LiveIntervals::isReMaterializable(const LiveInterval &li,
1107 SmallVectorImpl<LiveInterval*> &SpillIs,
1108 bool &isLoad) {
Evan Cheng5ef3a042007-12-06 00:01:56 +00001109 isLoad = false;
1110 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1111 i != e; ++i) {
1112 const VNInfo *VNI = *i;
Lang Hames857c4e02009-06-17 21:01:20 +00001113 if (VNI->isUnused())
Evan Cheng5ef3a042007-12-06 00:01:56 +00001114 continue; // Dead val#.
1115 // Is the def for the val# rematerializable?
Lang Hames857c4e02009-06-17 21:01:20 +00001116 if (!VNI->isDefAccurate())
Evan Cheng5ef3a042007-12-06 00:01:56 +00001117 return false;
Lang Hames857c4e02009-06-17 21:01:20 +00001118 MachineInstr *ReMatDefMI = getInstructionFromIndex(VNI->def);
Evan Cheng5ef3a042007-12-06 00:01:56 +00001119 bool DefIsLoad = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001120 if (!ReMatDefMI ||
Evan Chengdc377862008-09-30 15:44:16 +00001121 !isReMaterializable(li, VNI, ReMatDefMI, SpillIs, DefIsLoad))
Evan Cheng5ef3a042007-12-06 00:01:56 +00001122 return false;
1123 isLoad |= DefIsLoad;
Evan Chengf2fbca62007-11-12 06:35:08 +00001124 }
1125 return true;
1126}
1127
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001128/// FilterFoldedOps - Filter out two-address use operands. Return
1129/// true if it finds any issue with the operands that ought to prevent
1130/// folding.
1131static bool FilterFoldedOps(MachineInstr *MI,
1132 SmallVector<unsigned, 2> &Ops,
1133 unsigned &MRInfo,
1134 SmallVector<unsigned, 2> &FoldOps) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001135 MRInfo = 0;
Evan Chengaee4af62007-12-02 08:30:39 +00001136 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1137 unsigned OpIdx = Ops[i];
Evan Chengd70dbb52008-02-22 09:24:50 +00001138 MachineOperand &MO = MI->getOperand(OpIdx);
Evan Chengaee4af62007-12-02 08:30:39 +00001139 // FIXME: fold subreg use.
Evan Chengd70dbb52008-02-22 09:24:50 +00001140 if (MO.getSubReg())
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001141 return true;
Evan Chengd70dbb52008-02-22 09:24:50 +00001142 if (MO.isDef())
Evan Chengaee4af62007-12-02 08:30:39 +00001143 MRInfo |= (unsigned)VirtRegMap::isMod;
1144 else {
1145 // Filter out two-address use operand(s).
Evan Chenga24752f2009-03-19 20:30:06 +00001146 if (MI->isRegTiedToDefOperand(OpIdx)) {
Evan Chengaee4af62007-12-02 08:30:39 +00001147 MRInfo = VirtRegMap::isModRef;
1148 continue;
1149 }
1150 MRInfo |= (unsigned)VirtRegMap::isRef;
1151 }
1152 FoldOps.push_back(OpIdx);
Evan Chenge62f97c2007-12-01 02:07:52 +00001153 }
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001154 return false;
1155}
1156
1157
1158/// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
1159/// slot / to reg or any rematerialized load into ith operand of specified
1160/// MI. If it is successul, MI is updated with the newly created MI and
1161/// returns true.
1162bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
1163 VirtRegMap &vrm, MachineInstr *DefMI,
1164 unsigned InstrIdx,
1165 SmallVector<unsigned, 2> &Ops,
1166 bool isSS, int Slot, unsigned Reg) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001167 // If it is an implicit def instruction, just delete it.
Evan Cheng20ccded2008-03-15 00:19:36 +00001168 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001169 RemoveMachineInstrFromMaps(MI);
1170 vrm.RemoveMachineInstrFromMaps(MI);
1171 MI->eraseFromParent();
1172 ++numFolds;
1173 return true;
1174 }
1175
1176 // Filter the list of operand indexes that are to be folded. Abort if
1177 // any operand will prevent folding.
1178 unsigned MRInfo = 0;
1179 SmallVector<unsigned, 2> FoldOps;
1180 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1181 return false;
Evan Chenge62f97c2007-12-01 02:07:52 +00001182
Evan Cheng427f4c12008-03-31 23:19:51 +00001183 // The only time it's safe to fold into a two address instruction is when
1184 // it's folding reload and spill from / into a spill stack slot.
1185 if (DefMI && (MRInfo & VirtRegMap::isMod))
Evan Cheng249ded32008-02-23 03:38:34 +00001186 return false;
1187
Evan Chengf2f8c2a2008-02-08 22:05:27 +00001188 MachineInstr *fmi = isSS ? tii_->foldMemoryOperand(*mf_, MI, FoldOps, Slot)
1189 : tii_->foldMemoryOperand(*mf_, MI, FoldOps, DefMI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001190 if (fmi) {
Evan Chengd3653122008-02-27 03:04:06 +00001191 // Remember this instruction uses the spill slot.
1192 if (isSS) vrm.addSpillSlotUse(Slot, fmi);
1193
Evan Chengf2fbca62007-11-12 06:35:08 +00001194 // Attempt to fold the memory reference into the instruction. If
1195 // we can do this, we don't need to insert spill code.
Evan Chengf2fbca62007-11-12 06:35:08 +00001196 MachineBasicBlock &MBB = *MI->getParent();
Evan Cheng84802932008-01-10 08:24:38 +00001197 if (isSS && !mf_->getFrameInfo()->isImmutableObjectIndex(Slot))
Evan Chengaee4af62007-12-02 08:30:39 +00001198 vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
Evan Cheng81a03822007-11-17 00:40:40 +00001199 vrm.transferSpillPts(MI, fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001200 vrm.transferRestorePts(MI, fmi);
Evan Chengc1f53c72008-03-11 21:34:46 +00001201 vrm.transferEmergencySpills(MI, fmi);
Evan Chengf2fbca62007-11-12 06:35:08 +00001202 mi2iMap_.erase(MI);
Evan Chengcddbb832007-11-30 21:23:43 +00001203 i2miMap_[InstrIdx /InstrSlots::NUM] = fmi;
1204 mi2iMap_[fmi] = InstrIdx;
Evan Chengf2fbca62007-11-12 06:35:08 +00001205 MI = MBB.insert(MBB.erase(MI), fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001206 ++numFolds;
Evan Chengf2fbca62007-11-12 06:35:08 +00001207 return true;
1208 }
1209 return false;
1210}
1211
Evan Cheng018f9b02007-12-05 03:22:34 +00001212/// canFoldMemoryOperand - Returns true if the specified load / store
1213/// folding is possible.
1214bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI,
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001215 SmallVector<unsigned, 2> &Ops,
Evan Cheng3c75ba82008-04-01 21:37:32 +00001216 bool ReMat) const {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001217 // Filter the list of operand indexes that are to be folded. Abort if
1218 // any operand will prevent folding.
1219 unsigned MRInfo = 0;
Evan Cheng018f9b02007-12-05 03:22:34 +00001220 SmallVector<unsigned, 2> FoldOps;
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001221 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1222 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001223
Evan Cheng3c75ba82008-04-01 21:37:32 +00001224 // It's only legal to remat for a use, not a def.
1225 if (ReMat && (MRInfo & VirtRegMap::isMod))
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001226 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001227
Evan Chengd70dbb52008-02-22 09:24:50 +00001228 return tii_->canFoldMemoryOperand(MI, FoldOps);
1229}
1230
Evan Cheng81a03822007-11-17 00:40:40 +00001231bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
1232 SmallPtrSet<MachineBasicBlock*, 4> MBBs;
1233 for (LiveInterval::Ranges::const_iterator
1234 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1235 std::vector<IdxMBBPair>::const_iterator II =
1236 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), I->start);
1237 if (II == Idx2MBBMap.end())
1238 continue;
1239 if (I->end > II->first) // crossing a MBB.
1240 return false;
1241 MBBs.insert(II->second);
1242 if (MBBs.size() > 1)
1243 return false;
1244 }
1245 return true;
1246}
1247
Evan Chengd70dbb52008-02-22 09:24:50 +00001248/// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
1249/// interval on to-be re-materialized operands of MI) with new register.
1250void LiveIntervals::rewriteImplicitOps(const LiveInterval &li,
1251 MachineInstr *MI, unsigned NewVReg,
1252 VirtRegMap &vrm) {
1253 // There is an implicit use. That means one of the other operand is
1254 // being remat'ed and the remat'ed instruction has li.reg as an
1255 // use operand. Make sure we rewrite that as well.
1256 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1257 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001258 if (!MO.isReg())
Evan Chengd70dbb52008-02-22 09:24:50 +00001259 continue;
1260 unsigned Reg = MO.getReg();
1261 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
1262 continue;
1263 if (!vrm.isReMaterialized(Reg))
1264 continue;
1265 MachineInstr *ReMatMI = vrm.getReMaterializedMI(Reg);
Evan Cheng6130f662008-03-05 00:59:57 +00001266 MachineOperand *UseMO = ReMatMI->findRegisterUseOperand(li.reg);
1267 if (UseMO)
1268 UseMO->setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001269 }
1270}
1271
Evan Chengf2fbca62007-11-12 06:35:08 +00001272/// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
1273/// for addIntervalsForSpills to rewrite uses / defs for the given live range.
Evan Cheng018f9b02007-12-05 03:22:34 +00001274bool LiveIntervals::
Evan Chengd70dbb52008-02-22 09:24:50 +00001275rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
1276 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
Evan Cheng81a03822007-11-17 00:40:40 +00001277 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001278 unsigned Slot, int LdSlot,
1279 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001280 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001281 const TargetRegisterClass* rc,
1282 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001283 const MachineLoopInfo *loopInfo,
Evan Cheng313d4b82008-02-23 00:33:04 +00001284 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
Owen Anderson28998312008-08-13 22:28:50 +00001285 DenseMap<unsigned,unsigned> &MBBVRegsMap,
Evan Chengc781a242009-05-03 18:32:42 +00001286 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001287 bool CanFold = false;
Evan Chengf2fbca62007-11-12 06:35:08 +00001288 RestartInstruction:
1289 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1290 MachineOperand& mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001291 if (!mop.isReg())
Evan Chengf2fbca62007-11-12 06:35:08 +00001292 continue;
1293 unsigned Reg = mop.getReg();
1294 unsigned RegI = Reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001295 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
Evan Chengf2fbca62007-11-12 06:35:08 +00001296 continue;
Evan Chengf2fbca62007-11-12 06:35:08 +00001297 if (Reg != li.reg)
1298 continue;
1299
1300 bool TryFold = !DefIsReMat;
Evan Chengcb3c3302007-11-29 23:02:50 +00001301 bool FoldSS = true; // Default behavior unless it's a remat.
Evan Chengf2fbca62007-11-12 06:35:08 +00001302 int FoldSlot = Slot;
1303 if (DefIsReMat) {
1304 // If this is the rematerializable definition MI itself and
1305 // all of its uses are rematerialized, simply delete it.
Evan Cheng81a03822007-11-17 00:40:40 +00001306 if (MI == ReMatOrigDefMI && CanDelete) {
Evan Chengcddbb832007-11-30 21:23:43 +00001307 DOUT << "\t\t\t\tErasing re-materlizable def: ";
1308 DOUT << MI << '\n';
Evan Chengf2fbca62007-11-12 06:35:08 +00001309 RemoveMachineInstrFromMaps(MI);
Evan Chengcada2452007-11-28 01:28:46 +00001310 vrm.RemoveMachineInstrFromMaps(MI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001311 MI->eraseFromParent();
1312 break;
1313 }
1314
1315 // If def for this use can't be rematerialized, then try folding.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001316 // If def is rematerializable and it's a load, also try folding.
Evan Chengcb3c3302007-11-29 23:02:50 +00001317 TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad));
Evan Chengf2fbca62007-11-12 06:35:08 +00001318 if (isLoad) {
1319 // Try fold loads (from stack slot, constant pool, etc.) into uses.
1320 FoldSS = isLoadSS;
1321 FoldSlot = LdSlot;
1322 }
1323 }
1324
Evan Chengf2fbca62007-11-12 06:35:08 +00001325 // Scan all of the operands of this instruction rewriting operands
1326 // to use NewVReg instead of li.reg as appropriate. We do this for
1327 // two reasons:
1328 //
1329 // 1. If the instr reads the same spilled vreg multiple times, we
1330 // want to reuse the NewVReg.
1331 // 2. If the instr is a two-addr instruction, we are required to
1332 // keep the src/dst regs pinned.
1333 //
1334 // Keep track of whether we replace a use and/or def so that we can
1335 // create the spill interval with the appropriate range.
Evan Chengcddbb832007-11-30 21:23:43 +00001336
Evan Cheng81a03822007-11-17 00:40:40 +00001337 HasUse = mop.isUse();
1338 HasDef = mop.isDef();
Evan Chengaee4af62007-12-02 08:30:39 +00001339 SmallVector<unsigned, 2> Ops;
1340 Ops.push_back(i);
Evan Chengf2fbca62007-11-12 06:35:08 +00001341 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
Evan Chengaee4af62007-12-02 08:30:39 +00001342 const MachineOperand &MOj = MI->getOperand(j);
Dan Gohmand735b802008-10-03 15:45:36 +00001343 if (!MOj.isReg())
Evan Chengf2fbca62007-11-12 06:35:08 +00001344 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001345 unsigned RegJ = MOj.getReg();
Dan Gohman6f0d0242008-02-10 18:45:23 +00001346 if (RegJ == 0 || TargetRegisterInfo::isPhysicalRegister(RegJ))
Evan Chengf2fbca62007-11-12 06:35:08 +00001347 continue;
1348 if (RegJ == RegI) {
Evan Chengaee4af62007-12-02 08:30:39 +00001349 Ops.push_back(j);
1350 HasUse |= MOj.isUse();
1351 HasDef |= MOj.isDef();
Evan Chengf2fbca62007-11-12 06:35:08 +00001352 }
1353 }
1354
Evan Cheng79a796c2008-07-12 01:56:02 +00001355 if (HasUse && !li.liveAt(getUseIndex(index)))
1356 // Must be defined by an implicit def. It should not be spilled. Note,
1357 // this is for correctness reason. e.g.
1358 // 8 %reg1024<def> = IMPLICIT_DEF
1359 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1360 // The live range [12, 14) are not part of the r1024 live interval since
1361 // it's defined by an implicit def. It will not conflicts with live
1362 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001363 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001364 // the INSERT_SUBREG and both target registers that would overlap.
1365 HasUse = false;
1366
David Greene26b86a02008-10-27 17:38:59 +00001367 // Create a new virtual register for the spill interval.
1368 // Create the new register now so we can map the fold instruction
1369 // to the new register so when it is unfolded we get the correct
1370 // answer.
1371 bool CreatedNewVReg = false;
1372 if (NewVReg == 0) {
1373 NewVReg = mri_->createVirtualRegister(rc);
1374 vrm.grow();
1375 CreatedNewVReg = true;
1376 }
1377
Evan Cheng9c3c2212008-06-06 07:54:39 +00001378 if (!TryFold)
1379 CanFold = false;
1380 else {
Evan Cheng018f9b02007-12-05 03:22:34 +00001381 // Do not fold load / store here if we are splitting. We'll find an
1382 // optimal point to insert a load / store later.
1383 if (!TrySplit) {
1384 if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
David Greene26b86a02008-10-27 17:38:59 +00001385 Ops, FoldSS, FoldSlot, NewVReg)) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001386 // Folding the load/store can completely change the instruction in
1387 // unpredictable ways, rescan it from the beginning.
David Greene26b86a02008-10-27 17:38:59 +00001388
1389 if (FoldSS) {
1390 // We need to give the new vreg the same stack slot as the
1391 // spilled interval.
1392 vrm.assignVirt2StackSlot(NewVReg, FoldSlot);
1393 }
1394
Evan Cheng018f9b02007-12-05 03:22:34 +00001395 HasUse = false;
1396 HasDef = false;
1397 CanFold = false;
Evan Chengc781a242009-05-03 18:32:42 +00001398 if (isNotInMIMap(MI))
Evan Cheng7e073ba2008-04-09 20:57:25 +00001399 break;
Evan Cheng018f9b02007-12-05 03:22:34 +00001400 goto RestartInstruction;
1401 }
1402 } else {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001403 // We'll try to fold it later if it's profitable.
Evan Cheng3c75ba82008-04-01 21:37:32 +00001404 CanFold = canFoldMemoryOperand(MI, Ops, DefIsReMat);
Evan Cheng018f9b02007-12-05 03:22:34 +00001405 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001406 }
Evan Chengcddbb832007-11-30 21:23:43 +00001407
Evan Chengcddbb832007-11-30 21:23:43 +00001408 mop.setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001409 if (mop.isImplicit())
1410 rewriteImplicitOps(li, MI, NewVReg, vrm);
Evan Chengcddbb832007-11-30 21:23:43 +00001411
1412 // Reuse NewVReg for other reads.
Evan Chengd70dbb52008-02-22 09:24:50 +00001413 for (unsigned j = 0, e = Ops.size(); j != e; ++j) {
1414 MachineOperand &mopj = MI->getOperand(Ops[j]);
1415 mopj.setReg(NewVReg);
1416 if (mopj.isImplicit())
1417 rewriteImplicitOps(li, MI, NewVReg, vrm);
1418 }
Evan Chengcddbb832007-11-30 21:23:43 +00001419
Evan Cheng81a03822007-11-17 00:40:40 +00001420 if (CreatedNewVReg) {
1421 if (DefIsReMat) {
1422 vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI/*, CanDelete*/);
Evan Chengd70dbb52008-02-22 09:24:50 +00001423 if (ReMatIds[VNI->id] == VirtRegMap::MAX_STACK_SLOT) {
Evan Cheng81a03822007-11-17 00:40:40 +00001424 // Each valnum may have its own remat id.
Evan Chengd70dbb52008-02-22 09:24:50 +00001425 ReMatIds[VNI->id] = vrm.assignVirtReMatId(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001426 } else {
Evan Chengd70dbb52008-02-22 09:24:50 +00001427 vrm.assignVirtReMatId(NewVReg, ReMatIds[VNI->id]);
Evan Cheng81a03822007-11-17 00:40:40 +00001428 }
1429 if (!CanDelete || (HasUse && HasDef)) {
1430 // If this is a two-addr instruction then its use operands are
1431 // rematerializable but its def is not. It should be assigned a
1432 // stack slot.
1433 vrm.assignVirt2StackSlot(NewVReg, Slot);
1434 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001435 } else {
Evan Chengf2fbca62007-11-12 06:35:08 +00001436 vrm.assignVirt2StackSlot(NewVReg, Slot);
1437 }
Evan Chengcb3c3302007-11-29 23:02:50 +00001438 } else if (HasUse && HasDef &&
1439 vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) {
1440 // If this interval hasn't been assigned a stack slot (because earlier
1441 // def is a deleted remat def), do it now.
1442 assert(Slot != VirtRegMap::NO_STACK_SLOT);
1443 vrm.assignVirt2StackSlot(NewVReg, Slot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001444 }
1445
Evan Cheng313d4b82008-02-23 00:33:04 +00001446 // Re-matting an instruction with virtual register use. Add the
1447 // register as an implicit use on the use MI.
1448 if (DefIsReMat && ImpUse)
1449 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1450
Evan Cheng5b69eba2009-04-21 22:46:52 +00001451 // Create a new register interval for this spill / remat.
Evan Chengf2fbca62007-11-12 06:35:08 +00001452 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001453 if (CreatedNewVReg) {
1454 NewLIs.push_back(&nI);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001455 MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg));
Evan Cheng81a03822007-11-17 00:40:40 +00001456 if (TrySplit)
1457 vrm.setIsSplitFromReg(NewVReg, li.reg);
1458 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001459
1460 if (HasUse) {
Evan Cheng81a03822007-11-17 00:40:40 +00001461 if (CreatedNewVReg) {
1462 LiveRange LR(getLoadIndex(index), getUseIndex(index)+1,
Lang Hames857c4e02009-06-17 21:01:20 +00001463 nI.getNextValue(0, 0, false, VNInfoAllocator));
Evan Cheng81a03822007-11-17 00:40:40 +00001464 DOUT << " +" << LR;
1465 nI.addRange(LR);
1466 } else {
1467 // Extend the split live interval to this def / use.
1468 unsigned End = getUseIndex(index)+1;
1469 LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
1470 nI.getValNumInfo(nI.getNumValNums()-1));
1471 DOUT << " +" << LR;
1472 nI.addRange(LR);
1473 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001474 }
1475 if (HasDef) {
1476 LiveRange LR(getDefIndex(index), getStoreIndex(index),
Lang Hames857c4e02009-06-17 21:01:20 +00001477 nI.getNextValue(0, 0, false, VNInfoAllocator));
Evan Chengf2fbca62007-11-12 06:35:08 +00001478 DOUT << " +" << LR;
1479 nI.addRange(LR);
1480 }
Evan Cheng81a03822007-11-17 00:40:40 +00001481
Evan Chengf2fbca62007-11-12 06:35:08 +00001482 DOUT << "\t\t\t\tAdded new interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001483 nI.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001484 DOUT << '\n';
1485 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001486 return CanFold;
Evan Chengf2fbca62007-11-12 06:35:08 +00001487}
Evan Cheng81a03822007-11-17 00:40:40 +00001488bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001489 const VNInfo *VNI,
1490 MachineBasicBlock *MBB, unsigned Idx) const {
Evan Cheng81a03822007-11-17 00:40:40 +00001491 unsigned End = getMBBEndIdx(MBB);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001492 for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
1493 unsigned KillIdx = VNI->kills[j];
1494 if (KillIdx > Idx && KillIdx < End)
1495 return true;
Evan Cheng81a03822007-11-17 00:40:40 +00001496 }
1497 return false;
1498}
1499
Evan Cheng063284c2008-02-21 00:34:19 +00001500/// RewriteInfo - Keep track of machine instrs that will be rewritten
1501/// during spilling.
Dan Gohman844731a2008-05-13 00:00:25 +00001502namespace {
1503 struct RewriteInfo {
1504 unsigned Index;
1505 MachineInstr *MI;
1506 bool HasUse;
1507 bool HasDef;
1508 RewriteInfo(unsigned i, MachineInstr *mi, bool u, bool d)
1509 : Index(i), MI(mi), HasUse(u), HasDef(d) {}
1510 };
Evan Cheng063284c2008-02-21 00:34:19 +00001511
Dan Gohman844731a2008-05-13 00:00:25 +00001512 struct RewriteInfoCompare {
1513 bool operator()(const RewriteInfo &LHS, const RewriteInfo &RHS) const {
1514 return LHS.Index < RHS.Index;
1515 }
1516 };
1517}
Evan Cheng063284c2008-02-21 00:34:19 +00001518
Evan Chengf2fbca62007-11-12 06:35:08 +00001519void LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001520rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
Evan Chengf2fbca62007-11-12 06:35:08 +00001521 LiveInterval::Ranges::const_iterator &I,
Evan Cheng81a03822007-11-17 00:40:40 +00001522 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001523 unsigned Slot, int LdSlot,
1524 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001525 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001526 const TargetRegisterClass* rc,
1527 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001528 const MachineLoopInfo *loopInfo,
Evan Cheng81a03822007-11-17 00:40:40 +00001529 BitVector &SpillMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001530 DenseMap<unsigned, std::vector<SRInfo> > &SpillIdxes,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001531 BitVector &RestoreMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001532 DenseMap<unsigned, std::vector<SRInfo> > &RestoreIdxes,
1533 DenseMap<unsigned,unsigned> &MBBVRegsMap,
Evan Chengc781a242009-05-03 18:32:42 +00001534 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001535 bool AllCanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001536 unsigned NewVReg = 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001537 unsigned start = getBaseIndex(I->start);
Evan Chengf2fbca62007-11-12 06:35:08 +00001538 unsigned end = getBaseIndex(I->end-1) + InstrSlots::NUM;
Evan Chengf2fbca62007-11-12 06:35:08 +00001539
Evan Cheng063284c2008-02-21 00:34:19 +00001540 // First collect all the def / use in this live range that will be rewritten.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001541 // Make sure they are sorted according to instruction index.
Evan Cheng063284c2008-02-21 00:34:19 +00001542 std::vector<RewriteInfo> RewriteMIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001543 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1544 re = mri_->reg_end(); ri != re; ) {
Evan Cheng419852c2008-04-03 16:39:43 +00001545 MachineInstr *MI = &*ri;
Evan Cheng063284c2008-02-21 00:34:19 +00001546 MachineOperand &O = ri.getOperand();
1547 ++ri;
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001548 assert(!O.isImplicit() && "Spilling register that's used as implicit use?");
Evan Cheng063284c2008-02-21 00:34:19 +00001549 unsigned index = getInstructionIndex(MI);
1550 if (index < start || index >= end)
1551 continue;
Evan Cheng79a796c2008-07-12 01:56:02 +00001552 if (O.isUse() && !li.liveAt(getUseIndex(index)))
1553 // Must be defined by an implicit def. It should not be spilled. Note,
1554 // this is for correctness reason. e.g.
1555 // 8 %reg1024<def> = IMPLICIT_DEF
1556 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1557 // The live range [12, 14) are not part of the r1024 live interval since
1558 // it's defined by an implicit def. It will not conflicts with live
1559 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001560 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001561 // the INSERT_SUBREG and both target registers that would overlap.
1562 continue;
Evan Cheng063284c2008-02-21 00:34:19 +00001563 RewriteMIs.push_back(RewriteInfo(index, MI, O.isUse(), O.isDef()));
1564 }
1565 std::sort(RewriteMIs.begin(), RewriteMIs.end(), RewriteInfoCompare());
1566
Evan Cheng313d4b82008-02-23 00:33:04 +00001567 unsigned ImpUse = DefIsReMat ? getReMatImplicitUse(li, ReMatDefMI) : 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001568 // Now rewrite the defs and uses.
1569 for (unsigned i = 0, e = RewriteMIs.size(); i != e; ) {
1570 RewriteInfo &rwi = RewriteMIs[i];
1571 ++i;
1572 unsigned index = rwi.Index;
1573 bool MIHasUse = rwi.HasUse;
1574 bool MIHasDef = rwi.HasDef;
1575 MachineInstr *MI = rwi.MI;
1576 // If MI def and/or use the same register multiple times, then there
1577 // are multiple entries.
Evan Cheng313d4b82008-02-23 00:33:04 +00001578 unsigned NumUses = MIHasUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001579 while (i != e && RewriteMIs[i].MI == MI) {
1580 assert(RewriteMIs[i].Index == index);
Evan Cheng313d4b82008-02-23 00:33:04 +00001581 bool isUse = RewriteMIs[i].HasUse;
1582 if (isUse) ++NumUses;
1583 MIHasUse |= isUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001584 MIHasDef |= RewriteMIs[i].HasDef;
1585 ++i;
1586 }
Evan Cheng81a03822007-11-17 00:40:40 +00001587 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng313d4b82008-02-23 00:33:04 +00001588
Evan Cheng0a891ed2008-05-23 23:00:04 +00001589 if (ImpUse && MI != ReMatDefMI) {
Evan Cheng313d4b82008-02-23 00:33:04 +00001590 // Re-matting an instruction with virtual register use. Update the
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001591 // register interval's spill weight to HUGE_VALF to prevent it from
1592 // being spilled.
Evan Cheng313d4b82008-02-23 00:33:04 +00001593 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001594 ImpLi.weight = HUGE_VALF;
Evan Cheng313d4b82008-02-23 00:33:04 +00001595 }
1596
Evan Cheng063284c2008-02-21 00:34:19 +00001597 unsigned MBBId = MBB->getNumber();
Evan Cheng018f9b02007-12-05 03:22:34 +00001598 unsigned ThisVReg = 0;
Evan Cheng70306f82007-12-03 09:58:48 +00001599 if (TrySplit) {
Owen Anderson28998312008-08-13 22:28:50 +00001600 DenseMap<unsigned,unsigned>::iterator NVI = MBBVRegsMap.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001601 if (NVI != MBBVRegsMap.end()) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001602 ThisVReg = NVI->second;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001603 // One common case:
1604 // x = use
1605 // ...
1606 // ...
1607 // def = ...
1608 // = use
1609 // It's better to start a new interval to avoid artifically
1610 // extend the new interval.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001611 if (MIHasDef && !MIHasUse) {
1612 MBBVRegsMap.erase(MBB->getNumber());
Evan Cheng018f9b02007-12-05 03:22:34 +00001613 ThisVReg = 0;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001614 }
1615 }
Evan Chengcada2452007-11-28 01:28:46 +00001616 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001617
1618 bool IsNew = ThisVReg == 0;
1619 if (IsNew) {
1620 // This ends the previous live interval. If all of its def / use
1621 // can be folded, give it a low spill weight.
1622 if (NewVReg && TrySplit && AllCanFold) {
1623 LiveInterval &nI = getOrCreateInterval(NewVReg);
1624 nI.weight /= 10.0F;
1625 }
1626 AllCanFold = true;
1627 }
1628 NewVReg = ThisVReg;
1629
Evan Cheng81a03822007-11-17 00:40:40 +00001630 bool HasDef = false;
1631 bool HasUse = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001632 bool CanFold = rewriteInstructionForSpills(li, I->valno, TrySplit,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001633 index, end, MI, ReMatOrigDefMI, ReMatDefMI,
1634 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
1635 CanDelete, vrm, rc, ReMatIds, loopInfo, NewVReg,
Evan Chengc781a242009-05-03 18:32:42 +00001636 ImpUse, HasDef, HasUse, MBBVRegsMap, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001637 if (!HasDef && !HasUse)
1638 continue;
1639
Evan Cheng018f9b02007-12-05 03:22:34 +00001640 AllCanFold &= CanFold;
1641
Evan Cheng81a03822007-11-17 00:40:40 +00001642 // Update weight of spill interval.
1643 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng70306f82007-12-03 09:58:48 +00001644 if (!TrySplit) {
Evan Cheng81a03822007-11-17 00:40:40 +00001645 // The spill weight is now infinity as it cannot be spilled again.
1646 nI.weight = HUGE_VALF;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001647 continue;
Evan Cheng81a03822007-11-17 00:40:40 +00001648 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001649
1650 // Keep track of the last def and first use in each MBB.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001651 if (HasDef) {
1652 if (MI != ReMatOrigDefMI || !CanDelete) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001653 bool HasKill = false;
1654 if (!HasUse)
1655 HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, getDefIndex(index));
1656 else {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001657 // If this is a two-address code, then this index starts a new VNInfo.
Evan Cheng3f32d652008-06-04 09:18:41 +00001658 const VNInfo *VNI = li.findDefinedVNInfo(getDefIndex(index));
Evan Cheng0cbb1162007-11-29 01:06:25 +00001659 if (VNI)
1660 HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, getDefIndex(index));
1661 }
Owen Anderson28998312008-08-13 22:28:50 +00001662 DenseMap<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Chenge3110d02007-12-01 04:42:39 +00001663 SpillIdxes.find(MBBId);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001664 if (!HasKill) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001665 if (SII == SpillIdxes.end()) {
1666 std::vector<SRInfo> S;
1667 S.push_back(SRInfo(index, NewVReg, true));
1668 SpillIdxes.insert(std::make_pair(MBBId, S));
1669 } else if (SII->second.back().vreg != NewVReg) {
1670 SII->second.push_back(SRInfo(index, NewVReg, true));
1671 } else if ((int)index > SII->second.back().index) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001672 // If there is an earlier def and this is a two-address
1673 // instruction, then it's not possible to fold the store (which
1674 // would also fold the load).
Evan Cheng1953d0c2007-11-29 10:12:14 +00001675 SRInfo &Info = SII->second.back();
1676 Info.index = index;
1677 Info.canFold = !HasUse;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001678 }
1679 SpillMBBs.set(MBBId);
Evan Chenge3110d02007-12-01 04:42:39 +00001680 } else if (SII != SpillIdxes.end() &&
1681 SII->second.back().vreg == NewVReg &&
1682 (int)index > SII->second.back().index) {
1683 // There is an earlier def that's not killed (must be two-address).
1684 // The spill is no longer needed.
1685 SII->second.pop_back();
1686 if (SII->second.empty()) {
1687 SpillIdxes.erase(MBBId);
1688 SpillMBBs.reset(MBBId);
1689 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001690 }
1691 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001692 }
1693
1694 if (HasUse) {
Owen Anderson28998312008-08-13 22:28:50 +00001695 DenseMap<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001696 SpillIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001697 if (SII != SpillIdxes.end() &&
1698 SII->second.back().vreg == NewVReg &&
1699 (int)index > SII->second.back().index)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001700 // Use(s) following the last def, it's not safe to fold the spill.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001701 SII->second.back().canFold = false;
Owen Anderson28998312008-08-13 22:28:50 +00001702 DenseMap<unsigned, std::vector<SRInfo> >::iterator RII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001703 RestoreIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001704 if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001705 // If we are splitting live intervals, only fold if it's the first
1706 // use and there isn't another use later in the MBB.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001707 RII->second.back().canFold = false;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001708 else if (IsNew) {
1709 // Only need a reload if there isn't an earlier def / use.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001710 if (RII == RestoreIdxes.end()) {
1711 std::vector<SRInfo> Infos;
1712 Infos.push_back(SRInfo(index, NewVReg, true));
1713 RestoreIdxes.insert(std::make_pair(MBBId, Infos));
1714 } else {
1715 RII->second.push_back(SRInfo(index, NewVReg, true));
1716 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001717 RestoreMBBs.set(MBBId);
1718 }
1719 }
1720
1721 // Update spill weight.
Evan Cheng22f07ff2007-12-11 02:09:15 +00001722 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Chengc3417602008-06-21 06:45:54 +00001723 nI.weight += getSpillWeight(HasDef, HasUse, loopDepth);
Evan Chengf2fbca62007-11-12 06:35:08 +00001724 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001725
1726 if (NewVReg && TrySplit && AllCanFold) {
1727 // If all of its def / use can be folded, give it a low spill weight.
1728 LiveInterval &nI = getOrCreateInterval(NewVReg);
1729 nI.weight /= 10.0F;
1730 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001731}
1732
Evan Cheng1953d0c2007-11-29 10:12:14 +00001733bool LiveIntervals::alsoFoldARestore(int Id, int index, unsigned vr,
1734 BitVector &RestoreMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001735 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001736 if (!RestoreMBBs[Id])
1737 return false;
1738 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1739 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1740 if (Restores[i].index == index &&
1741 Restores[i].vreg == vr &&
1742 Restores[i].canFold)
1743 return true;
1744 return false;
1745}
1746
1747void LiveIntervals::eraseRestoreInfo(int Id, int index, unsigned vr,
1748 BitVector &RestoreMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001749 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001750 if (!RestoreMBBs[Id])
1751 return;
1752 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1753 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1754 if (Restores[i].index == index && Restores[i].vreg)
1755 Restores[i].index = -1;
1756}
Evan Cheng81a03822007-11-17 00:40:40 +00001757
Evan Cheng4cce6b42008-04-11 17:53:36 +00001758/// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
1759/// spilled and create empty intervals for their uses.
1760void
1761LiveIntervals::handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
1762 const TargetRegisterClass* rc,
1763 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng419852c2008-04-03 16:39:43 +00001764 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1765 re = mri_->reg_end(); ri != re; ) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001766 MachineOperand &O = ri.getOperand();
Evan Cheng419852c2008-04-03 16:39:43 +00001767 MachineInstr *MI = &*ri;
1768 ++ri;
Evan Cheng4cce6b42008-04-11 17:53:36 +00001769 if (O.isDef()) {
1770 assert(MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF &&
1771 "Register def was not rewritten?");
1772 RemoveMachineInstrFromMaps(MI);
1773 vrm.RemoveMachineInstrFromMaps(MI);
1774 MI->eraseFromParent();
1775 } else {
1776 // This must be an use of an implicit_def so it's not part of the live
1777 // interval. Create a new empty live interval for it.
1778 // FIXME: Can we simply erase some of the instructions? e.g. Stores?
1779 unsigned NewVReg = mri_->createVirtualRegister(rc);
1780 vrm.grow();
1781 vrm.setIsImplicitlyDefined(NewVReg);
1782 NewLIs.push_back(&getOrCreateInterval(NewVReg));
1783 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1784 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001785 if (MO.isReg() && MO.getReg() == li.reg)
Evan Cheng4cce6b42008-04-11 17:53:36 +00001786 MO.setReg(NewVReg);
1787 }
1788 }
Evan Cheng419852c2008-04-03 16:39:43 +00001789 }
1790}
1791
Evan Chengf2fbca62007-11-12 06:35:08 +00001792std::vector<LiveInterval*> LiveIntervals::
Owen Andersond6664312008-08-18 18:05:32 +00001793addIntervalsForSpillsFast(const LiveInterval &li,
1794 const MachineLoopInfo *loopInfo,
Evan Chengc781a242009-05-03 18:32:42 +00001795 VirtRegMap &vrm) {
Owen Anderson17197312008-08-18 23:41:04 +00001796 unsigned slot = vrm.assignVirt2StackSlot(li.reg);
Owen Andersond6664312008-08-18 18:05:32 +00001797
1798 std::vector<LiveInterval*> added;
1799
1800 assert(li.weight != HUGE_VALF &&
1801 "attempt to spill already spilled interval!");
1802
1803 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
1804 DEBUG(li.dump());
1805 DOUT << '\n';
1806
1807 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
1808
Owen Andersona41e47a2008-08-19 22:12:11 +00001809 MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg);
1810 while (RI != mri_->reg_end()) {
1811 MachineInstr* MI = &*RI;
1812
1813 SmallVector<unsigned, 2> Indices;
1814 bool HasUse = false;
1815 bool HasDef = false;
1816
1817 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1818 MachineOperand& mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001819 if (!mop.isReg() || mop.getReg() != li.reg) continue;
Owen Andersona41e47a2008-08-19 22:12:11 +00001820
1821 HasUse |= MI->getOperand(i).isUse();
1822 HasDef |= MI->getOperand(i).isDef();
1823
1824 Indices.push_back(i);
1825 }
1826
1827 if (!tryFoldMemoryOperand(MI, vrm, NULL, getInstructionIndex(MI),
1828 Indices, true, slot, li.reg)) {
1829 unsigned NewVReg = mri_->createVirtualRegister(rc);
Owen Anderson9a032932008-08-18 21:20:32 +00001830 vrm.grow();
Owen Anderson17197312008-08-18 23:41:04 +00001831 vrm.assignVirt2StackSlot(NewVReg, slot);
1832
Owen Andersona41e47a2008-08-19 22:12:11 +00001833 // create a new register for this spill
1834 LiveInterval &nI = getOrCreateInterval(NewVReg);
Owen Andersond6664312008-08-18 18:05:32 +00001835
Owen Andersona41e47a2008-08-19 22:12:11 +00001836 // the spill weight is now infinity as it
1837 // cannot be spilled again
1838 nI.weight = HUGE_VALF;
1839
1840 // Rewrite register operands to use the new vreg.
1841 for (SmallVectorImpl<unsigned>::iterator I = Indices.begin(),
1842 E = Indices.end(); I != E; ++I) {
1843 MI->getOperand(*I).setReg(NewVReg);
1844
1845 if (MI->getOperand(*I).isUse())
1846 MI->getOperand(*I).setIsKill(true);
1847 }
1848
1849 // Fill in the new live interval.
1850 unsigned index = getInstructionIndex(MI);
1851 if (HasUse) {
1852 LiveRange LR(getLoadIndex(index), getUseIndex(index),
Lang Hames857c4e02009-06-17 21:01:20 +00001853 nI.getNextValue(0, 0, false, getVNInfoAllocator()));
Owen Andersona41e47a2008-08-19 22:12:11 +00001854 DOUT << " +" << LR;
1855 nI.addRange(LR);
1856 vrm.addRestorePoint(NewVReg, MI);
1857 }
1858 if (HasDef) {
1859 LiveRange LR(getDefIndex(index), getStoreIndex(index),
Lang Hames857c4e02009-06-17 21:01:20 +00001860 nI.getNextValue(0, 0, false, getVNInfoAllocator()));
Owen Andersona41e47a2008-08-19 22:12:11 +00001861 DOUT << " +" << LR;
1862 nI.addRange(LR);
1863 vrm.addSpillPoint(NewVReg, true, MI);
1864 }
1865
Owen Anderson17197312008-08-18 23:41:04 +00001866 added.push_back(&nI);
Owen Anderson8dc2cbe2008-08-18 18:38:12 +00001867
Owen Andersona41e47a2008-08-19 22:12:11 +00001868 DOUT << "\t\t\t\tadded new interval: ";
1869 DEBUG(nI.dump());
1870 DOUT << '\n';
Owen Andersona41e47a2008-08-19 22:12:11 +00001871 }
Owen Anderson9a032932008-08-18 21:20:32 +00001872
Owen Anderson9a032932008-08-18 21:20:32 +00001873
Owen Andersona41e47a2008-08-19 22:12:11 +00001874 RI = mri_->reg_begin(li.reg);
Owen Andersond6664312008-08-18 18:05:32 +00001875 }
Owen Andersond6664312008-08-18 18:05:32 +00001876
1877 return added;
1878}
1879
1880std::vector<LiveInterval*> LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001881addIntervalsForSpills(const LiveInterval &li,
Evan Chengdc377862008-09-30 15:44:16 +00001882 SmallVectorImpl<LiveInterval*> &SpillIs,
Evan Chengc781a242009-05-03 18:32:42 +00001883 const MachineLoopInfo *loopInfo, VirtRegMap &vrm) {
Owen Andersonae339ba2008-08-19 00:17:30 +00001884
1885 if (EnableFastSpilling)
Evan Chengc781a242009-05-03 18:32:42 +00001886 return addIntervalsForSpillsFast(li, loopInfo, vrm);
Owen Andersonae339ba2008-08-19 00:17:30 +00001887
Evan Chengf2fbca62007-11-12 06:35:08 +00001888 assert(li.weight != HUGE_VALF &&
1889 "attempt to spill already spilled interval!");
1890
1891 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001892 li.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001893 DOUT << '\n';
1894
Evan Cheng72eeb942008-12-05 17:00:16 +00001895 // Each bit specify whether a spill is required in the MBB.
Evan Cheng81a03822007-11-17 00:40:40 +00001896 BitVector SpillMBBs(mf_->getNumBlockIDs());
Owen Anderson28998312008-08-13 22:28:50 +00001897 DenseMap<unsigned, std::vector<SRInfo> > SpillIdxes;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001898 BitVector RestoreMBBs(mf_->getNumBlockIDs());
Owen Anderson28998312008-08-13 22:28:50 +00001899 DenseMap<unsigned, std::vector<SRInfo> > RestoreIdxes;
1900 DenseMap<unsigned,unsigned> MBBVRegsMap;
Evan Chengf2fbca62007-11-12 06:35:08 +00001901 std::vector<LiveInterval*> NewLIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001902 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
Evan Chengf2fbca62007-11-12 06:35:08 +00001903
1904 unsigned NumValNums = li.getNumValNums();
1905 SmallVector<MachineInstr*, 4> ReMatDefs;
1906 ReMatDefs.resize(NumValNums, NULL);
1907 SmallVector<MachineInstr*, 4> ReMatOrigDefs;
1908 ReMatOrigDefs.resize(NumValNums, NULL);
1909 SmallVector<int, 4> ReMatIds;
1910 ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
1911 BitVector ReMatDelete(NumValNums);
1912 unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
1913
Evan Cheng81a03822007-11-17 00:40:40 +00001914 // Spilling a split live interval. It cannot be split any further. Also,
1915 // it's also guaranteed to be a single val# / range interval.
1916 if (vrm.getPreSplitReg(li.reg)) {
1917 vrm.setIsSplitFromReg(li.reg, 0);
Evan Chengd120ffd2007-12-05 10:24:35 +00001918 // Unset the split kill marker on the last use.
1919 unsigned KillIdx = vrm.getKillPoint(li.reg);
1920 if (KillIdx) {
1921 MachineInstr *KillMI = getInstructionFromIndex(KillIdx);
1922 assert(KillMI && "Last use disappeared?");
1923 int KillOp = KillMI->findRegisterUseOperandIdx(li.reg, true);
1924 assert(KillOp != -1 && "Last use disappeared?");
Chris Lattnerf7382302007-12-30 21:56:09 +00001925 KillMI->getOperand(KillOp).setIsKill(false);
Evan Chengd120ffd2007-12-05 10:24:35 +00001926 }
Evan Chengadf85902007-12-05 09:51:10 +00001927 vrm.removeKillPoint(li.reg);
Evan Cheng81a03822007-11-17 00:40:40 +00001928 bool DefIsReMat = vrm.isReMaterialized(li.reg);
1929 Slot = vrm.getStackSlot(li.reg);
1930 assert(Slot != VirtRegMap::MAX_STACK_SLOT);
1931 MachineInstr *ReMatDefMI = DefIsReMat ?
1932 vrm.getReMaterializedMI(li.reg) : NULL;
1933 int LdSlot = 0;
1934 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1935 bool isLoad = isLoadSS ||
Dan Gohman15511cf2008-12-03 18:15:48 +00001936 (DefIsReMat && (ReMatDefMI->getDesc().canFoldAsLoad()));
Evan Cheng81a03822007-11-17 00:40:40 +00001937 bool IsFirstRange = true;
1938 for (LiveInterval::Ranges::const_iterator
1939 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1940 // If this is a split live interval with multiple ranges, it means there
1941 // are two-address instructions that re-defined the value. Only the
1942 // first def can be rematerialized!
1943 if (IsFirstRange) {
Evan Chengcb3c3302007-11-29 23:02:50 +00001944 // Note ReMatOrigDefMI has already been deleted.
Evan Cheng81a03822007-11-17 00:40:40 +00001945 rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
1946 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001947 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001948 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Chengc781a242009-05-03 18:32:42 +00001949 MBBVRegsMap, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001950 } else {
1951 rewriteInstructionsForSpills(li, false, I, NULL, 0,
1952 Slot, 0, false, false, false,
Evan Chengd70dbb52008-02-22 09:24:50 +00001953 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001954 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Chengc781a242009-05-03 18:32:42 +00001955 MBBVRegsMap, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001956 }
1957 IsFirstRange = false;
1958 }
Evan Cheng419852c2008-04-03 16:39:43 +00001959
Evan Cheng4cce6b42008-04-11 17:53:36 +00001960 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001961 return NewLIs;
1962 }
1963
1964 bool TrySplit = SplitAtBB && !intervalIsInOneMBB(li);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001965 if (SplitLimit != -1 && (int)numSplits >= SplitLimit)
1966 TrySplit = false;
1967 if (TrySplit)
1968 ++numSplits;
Evan Chengf2fbca62007-11-12 06:35:08 +00001969 bool NeedStackSlot = false;
1970 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1971 i != e; ++i) {
1972 const VNInfo *VNI = *i;
1973 unsigned VN = VNI->id;
Lang Hames857c4e02009-06-17 21:01:20 +00001974 if (VNI->isUnused())
Evan Chengf2fbca62007-11-12 06:35:08 +00001975 continue; // Dead val#.
1976 // Is the def for the val# rematerializable?
Lang Hames857c4e02009-06-17 21:01:20 +00001977 MachineInstr *ReMatDefMI = VNI->isDefAccurate()
1978 ? getInstructionFromIndex(VNI->def) : 0;
Evan Cheng5ef3a042007-12-06 00:01:56 +00001979 bool dummy;
Evan Chengdc377862008-09-30 15:44:16 +00001980 if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, SpillIs, dummy)) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001981 // Remember how to remat the def of this val#.
Evan Cheng81a03822007-11-17 00:40:40 +00001982 ReMatOrigDefs[VN] = ReMatDefMI;
Dan Gohman2c3f7ae2008-07-17 23:49:46 +00001983 // Original def may be modified so we have to make a copy here.
Evan Cheng1ed99222008-07-19 00:37:25 +00001984 MachineInstr *Clone = mf_->CloneMachineInstr(ReMatDefMI);
1985 ClonedMIs.push_back(Clone);
1986 ReMatDefs[VN] = Clone;
Evan Chengf2fbca62007-11-12 06:35:08 +00001987
1988 bool CanDelete = true;
Lang Hames857c4e02009-06-17 21:01:20 +00001989 if (VNI->hasPHIKill()) {
Evan Chengc3fc7d92007-11-29 09:49:23 +00001990 // A kill is a phi node, not all of its uses can be rematerialized.
Evan Chengf2fbca62007-11-12 06:35:08 +00001991 // It must not be deleted.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001992 CanDelete = false;
1993 // Need a stack slot if there is any live range where uses cannot be
1994 // rematerialized.
1995 NeedStackSlot = true;
Evan Chengf2fbca62007-11-12 06:35:08 +00001996 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001997 if (CanDelete)
1998 ReMatDelete.set(VN);
1999 } else {
2000 // Need a stack slot if there is any live range where uses cannot be
2001 // rematerialized.
2002 NeedStackSlot = true;
2003 }
2004 }
2005
2006 // One stack slot per live interval.
Owen Andersonb98bbb72009-03-26 18:53:38 +00002007 if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0) {
2008 if (vrm.getStackSlot(li.reg) == VirtRegMap::NO_STACK_SLOT)
2009 Slot = vrm.assignVirt2StackSlot(li.reg);
2010
2011 // This case only occurs when the prealloc splitter has already assigned
2012 // a stack slot to this vreg.
2013 else
2014 Slot = vrm.getStackSlot(li.reg);
2015 }
Evan Chengf2fbca62007-11-12 06:35:08 +00002016
2017 // Create new intervals and rewrite defs and uses.
2018 for (LiveInterval::Ranges::const_iterator
2019 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Evan Cheng81a03822007-11-17 00:40:40 +00002020 MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id];
2021 MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id];
2022 bool DefIsReMat = ReMatDefMI != NULL;
Evan Chengf2fbca62007-11-12 06:35:08 +00002023 bool CanDelete = ReMatDelete[I->valno->id];
2024 int LdSlot = 0;
Evan Cheng81a03822007-11-17 00:40:40 +00002025 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
Evan Chengf2fbca62007-11-12 06:35:08 +00002026 bool isLoad = isLoadSS ||
Dan Gohman15511cf2008-12-03 18:15:48 +00002027 (DefIsReMat && ReMatDefMI->getDesc().canFoldAsLoad());
Evan Cheng81a03822007-11-17 00:40:40 +00002028 rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
Evan Cheng0cbb1162007-11-29 01:06:25 +00002029 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00002030 CanDelete, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00002031 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Chengc781a242009-05-03 18:32:42 +00002032 MBBVRegsMap, NewLIs);
Evan Chengf2fbca62007-11-12 06:35:08 +00002033 }
2034
Evan Cheng0cbb1162007-11-29 01:06:25 +00002035 // Insert spills / restores if we are splitting.
Evan Cheng419852c2008-04-03 16:39:43 +00002036 if (!TrySplit) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00002037 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng1953d0c2007-11-29 10:12:14 +00002038 return NewLIs;
Evan Cheng419852c2008-04-03 16:39:43 +00002039 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002040
Evan Chengb50bb8c2007-12-05 08:16:32 +00002041 SmallPtrSet<LiveInterval*, 4> AddedKill;
Evan Chengaee4af62007-12-02 08:30:39 +00002042 SmallVector<unsigned, 2> Ops;
Evan Cheng1953d0c2007-11-29 10:12:14 +00002043 if (NeedStackSlot) {
2044 int Id = SpillMBBs.find_first();
2045 while (Id != -1) {
2046 std::vector<SRInfo> &spills = SpillIdxes[Id];
2047 for (unsigned i = 0, e = spills.size(); i != e; ++i) {
2048 int index = spills[i].index;
2049 unsigned VReg = spills[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00002050 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng0cbb1162007-11-29 01:06:25 +00002051 bool isReMat = vrm.isReMaterialized(VReg);
2052 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00002053 bool CanFold = false;
2054 bool FoundUse = false;
2055 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00002056 if (spills[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00002057 CanFold = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00002058 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
2059 MachineOperand &MO = MI->getOperand(j);
Dan Gohmand735b802008-10-03 15:45:36 +00002060 if (!MO.isReg() || MO.getReg() != VReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00002061 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00002062
2063 Ops.push_back(j);
2064 if (MO.isDef())
Evan Chengcddbb832007-11-30 21:23:43 +00002065 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00002066 if (isReMat ||
2067 (!FoundUse && !alsoFoldARestore(Id, index, VReg,
2068 RestoreMBBs, RestoreIdxes))) {
2069 // MI has two-address uses of the same register. If the use
2070 // isn't the first and only use in the BB, then we can't fold
2071 // it. FIXME: Move this to rewriteInstructionsForSpills.
2072 CanFold = false;
Evan Chengcddbb832007-11-30 21:23:43 +00002073 break;
2074 }
Evan Chengaee4af62007-12-02 08:30:39 +00002075 FoundUse = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00002076 }
2077 }
2078 // Fold the store into the def if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00002079 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00002080 if (CanFold && !Ops.empty()) {
2081 if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
Evan Chengcddbb832007-11-30 21:23:43 +00002082 Folded = true;
Sebastian Redl48fe6352009-03-19 23:26:52 +00002083 if (FoundUse) {
Evan Chengaee4af62007-12-02 08:30:39 +00002084 // Also folded uses, do not issue a load.
2085 eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
Evan Chengf38d14f2007-12-05 09:05:34 +00002086 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
2087 }
Evan Cheng597d10d2007-12-04 00:32:23 +00002088 nI.removeRange(getDefIndex(index), getStoreIndex(index));
Evan Chengcddbb832007-11-30 21:23:43 +00002089 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002090 }
2091
Evan Cheng7e073ba2008-04-09 20:57:25 +00002092 // Otherwise tell the spiller to issue a spill.
Evan Chengb50bb8c2007-12-05 08:16:32 +00002093 if (!Folded) {
2094 LiveRange *LR = &nI.ranges[nI.ranges.size()-1];
2095 bool isKill = LR->end == getStoreIndex(index);
Evan Chengb0a6f622008-05-20 08:10:37 +00002096 if (!MI->registerDefIsDead(nI.reg))
2097 // No need to spill a dead def.
2098 vrm.addSpillPoint(VReg, isKill, MI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002099 if (isKill)
2100 AddedKill.insert(&nI);
2101 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002102 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002103 Id = SpillMBBs.find_next(Id);
Evan Cheng0cbb1162007-11-29 01:06:25 +00002104 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002105 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002106
Evan Cheng1953d0c2007-11-29 10:12:14 +00002107 int Id = RestoreMBBs.find_first();
2108 while (Id != -1) {
2109 std::vector<SRInfo> &restores = RestoreIdxes[Id];
2110 for (unsigned i = 0, e = restores.size(); i != e; ++i) {
2111 int index = restores[i].index;
2112 if (index == -1)
2113 continue;
2114 unsigned VReg = restores[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00002115 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng9c3c2212008-06-06 07:54:39 +00002116 bool isReMat = vrm.isReMaterialized(VReg);
Evan Cheng81a03822007-11-17 00:40:40 +00002117 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00002118 bool CanFold = false;
2119 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00002120 if (restores[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00002121 CanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00002122 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
2123 MachineOperand &MO = MI->getOperand(j);
Dan Gohmand735b802008-10-03 15:45:36 +00002124 if (!MO.isReg() || MO.getReg() != VReg)
Evan Cheng81a03822007-11-17 00:40:40 +00002125 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00002126
Evan Cheng0cbb1162007-11-29 01:06:25 +00002127 if (MO.isDef()) {
Evan Chengaee4af62007-12-02 08:30:39 +00002128 // If this restore were to be folded, it would have been folded
2129 // already.
2130 CanFold = false;
Evan Cheng81a03822007-11-17 00:40:40 +00002131 break;
2132 }
Evan Chengaee4af62007-12-02 08:30:39 +00002133 Ops.push_back(j);
Evan Cheng81a03822007-11-17 00:40:40 +00002134 }
2135 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002136
2137 // Fold the load into the use if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00002138 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00002139 if (CanFold && !Ops.empty()) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00002140 if (!isReMat)
Evan Chengaee4af62007-12-02 08:30:39 +00002141 Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg);
2142 else {
Evan Cheng0cbb1162007-11-29 01:06:25 +00002143 MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg);
2144 int LdSlot = 0;
2145 bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
2146 // If the rematerializable def is a load, also try to fold it.
Dan Gohman15511cf2008-12-03 18:15:48 +00002147 if (isLoadSS || ReMatDefMI->getDesc().canFoldAsLoad())
Evan Chengaee4af62007-12-02 08:30:39 +00002148 Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
2149 Ops, isLoadSS, LdSlot, VReg);
Evan Cheng650d7f32008-12-05 17:41:31 +00002150 if (!Folded) {
2151 unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI);
2152 if (ImpUse) {
2153 // Re-matting an instruction with virtual register use. Add the
2154 // register as an implicit use on the use MI and update the register
2155 // interval's spill weight to HUGE_VALF to prevent it from being
2156 // spilled.
2157 LiveInterval &ImpLi = getInterval(ImpUse);
2158 ImpLi.weight = HUGE_VALF;
2159 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
2160 }
Evan Chengd70dbb52008-02-22 09:24:50 +00002161 }
Evan Chengaee4af62007-12-02 08:30:39 +00002162 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002163 }
2164 // If folding is not possible / failed, then tell the spiller to issue a
2165 // load / rematerialization for us.
Evan Cheng597d10d2007-12-04 00:32:23 +00002166 if (Folded)
2167 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002168 else
Evan Cheng0cbb1162007-11-29 01:06:25 +00002169 vrm.addRestorePoint(VReg, MI);
Evan Cheng81a03822007-11-17 00:40:40 +00002170 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002171 Id = RestoreMBBs.find_next(Id);
Evan Cheng81a03822007-11-17 00:40:40 +00002172 }
2173
Evan Chengb50bb8c2007-12-05 08:16:32 +00002174 // Finalize intervals: add kills, finalize spill weights, and filter out
2175 // dead intervals.
Evan Cheng597d10d2007-12-04 00:32:23 +00002176 std::vector<LiveInterval*> RetNewLIs;
2177 for (unsigned i = 0, e = NewLIs.size(); i != e; ++i) {
2178 LiveInterval *LI = NewLIs[i];
2179 if (!LI->empty()) {
Owen Anderson496bac52008-07-23 19:47:27 +00002180 LI->weight /= InstrSlots::NUM * getApproximateInstructionCount(*LI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002181 if (!AddedKill.count(LI)) {
2182 LiveRange *LR = &LI->ranges[LI->ranges.size()-1];
Evan Chengd120ffd2007-12-05 10:24:35 +00002183 unsigned LastUseIdx = getBaseIndex(LR->end);
2184 MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx);
Evan Cheng6130f662008-03-05 00:59:57 +00002185 int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg, false);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002186 assert(UseIdx != -1);
Evan Chenga24752f2009-03-19 20:30:06 +00002187 if (!LastUse->isRegTiedToDefOperand(UseIdx)) {
Evan Chengb50bb8c2007-12-05 08:16:32 +00002188 LastUse->getOperand(UseIdx).setIsKill();
Evan Chengd120ffd2007-12-05 10:24:35 +00002189 vrm.addKillPoint(LI->reg, LastUseIdx);
Evan Chengadf85902007-12-05 09:51:10 +00002190 }
Evan Chengb50bb8c2007-12-05 08:16:32 +00002191 }
Evan Cheng597d10d2007-12-04 00:32:23 +00002192 RetNewLIs.push_back(LI);
2193 }
2194 }
Evan Cheng81a03822007-11-17 00:40:40 +00002195
Evan Cheng4cce6b42008-04-11 17:53:36 +00002196 handleSpilledImpDefs(li, vrm, rc, RetNewLIs);
Evan Cheng597d10d2007-12-04 00:32:23 +00002197 return RetNewLIs;
Evan Chengf2fbca62007-11-12 06:35:08 +00002198}
Evan Cheng676dd7c2008-03-11 07:19:34 +00002199
2200/// hasAllocatableSuperReg - Return true if the specified physical register has
2201/// any super register that's allocatable.
2202bool LiveIntervals::hasAllocatableSuperReg(unsigned Reg) const {
2203 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS)
2204 if (allocatableRegs_[*AS] && hasInterval(*AS))
2205 return true;
2206 return false;
2207}
2208
2209/// getRepresentativeReg - Find the largest super register of the specified
2210/// physical register.
2211unsigned LiveIntervals::getRepresentativeReg(unsigned Reg) const {
2212 // Find the largest super-register that is allocatable.
2213 unsigned BestReg = Reg;
2214 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS) {
2215 unsigned SuperReg = *AS;
2216 if (!hasAllocatableSuperReg(SuperReg) && hasInterval(SuperReg)) {
2217 BestReg = SuperReg;
2218 break;
2219 }
2220 }
2221 return BestReg;
2222}
2223
2224/// getNumConflictsWithPhysReg - Return the number of uses and defs of the
2225/// specified interval that conflicts with the specified physical register.
2226unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li,
2227 unsigned PhysReg) const {
2228 unsigned NumConflicts = 0;
2229 const LiveInterval &pli = getInterval(getRepresentativeReg(PhysReg));
2230 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
2231 E = mri_->reg_end(); I != E; ++I) {
2232 MachineOperand &O = I.getOperand();
2233 MachineInstr *MI = O.getParent();
2234 unsigned Index = getInstructionIndex(MI);
2235 if (pli.liveAt(Index))
2236 ++NumConflicts;
2237 }
2238 return NumConflicts;
2239}
2240
2241/// spillPhysRegAroundRegDefsUses - Spill the specified physical register
Evan Cheng2824a652009-03-23 18:24:37 +00002242/// around all defs and uses of the specified interval. Return true if it
2243/// was able to cut its interval.
2244bool LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
Evan Cheng676dd7c2008-03-11 07:19:34 +00002245 unsigned PhysReg, VirtRegMap &vrm) {
2246 unsigned SpillReg = getRepresentativeReg(PhysReg);
2247
2248 for (const unsigned *AS = tri_->getAliasSet(PhysReg); *AS; ++AS)
2249 // If there are registers which alias PhysReg, but which are not a
2250 // sub-register of the chosen representative super register. Assert
2251 // since we can't handle it yet.
Dan Gohman70f2f652009-04-13 15:22:29 +00002252 assert(*AS == SpillReg || !allocatableRegs_[*AS] || !hasInterval(*AS) ||
Evan Cheng676dd7c2008-03-11 07:19:34 +00002253 tri_->isSuperRegister(*AS, SpillReg));
2254
Evan Cheng2824a652009-03-23 18:24:37 +00002255 bool Cut = false;
Evan Cheng676dd7c2008-03-11 07:19:34 +00002256 LiveInterval &pli = getInterval(SpillReg);
2257 SmallPtrSet<MachineInstr*, 8> SeenMIs;
2258 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
2259 E = mri_->reg_end(); I != E; ++I) {
2260 MachineOperand &O = I.getOperand();
2261 MachineInstr *MI = O.getParent();
2262 if (SeenMIs.count(MI))
2263 continue;
2264 SeenMIs.insert(MI);
2265 unsigned Index = getInstructionIndex(MI);
2266 if (pli.liveAt(Index)) {
2267 vrm.addEmergencySpill(SpillReg, MI);
Evan Cheng5a3c6a82009-01-29 02:20:59 +00002268 unsigned StartIdx = getLoadIndex(Index);
2269 unsigned EndIdx = getStoreIndex(Index)+1;
Evan Cheng2824a652009-03-23 18:24:37 +00002270 if (pli.isInOneLiveRange(StartIdx, EndIdx)) {
Evan Cheng5a3c6a82009-01-29 02:20:59 +00002271 pli.removeRange(StartIdx, EndIdx);
Evan Cheng2824a652009-03-23 18:24:37 +00002272 Cut = true;
2273 } else {
Evan Cheng5a3c6a82009-01-29 02:20:59 +00002274 cerr << "Ran out of registers during register allocation!\n";
2275 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
2276 cerr << "Please check your inline asm statement for invalid "
2277 << "constraints:\n";
2278 MI->print(cerr.stream(), tm_);
2279 }
2280 exit(1);
2281 }
Evan Cheng676dd7c2008-03-11 07:19:34 +00002282 for (const unsigned* AS = tri_->getSubRegisters(SpillReg); *AS; ++AS) {
2283 if (!hasInterval(*AS))
2284 continue;
2285 LiveInterval &spli = getInterval(*AS);
2286 if (spli.liveAt(Index))
2287 spli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
2288 }
2289 }
2290 }
Evan Cheng2824a652009-03-23 18:24:37 +00002291 return Cut;
Evan Cheng676dd7c2008-03-11 07:19:34 +00002292}
Owen Andersonc4dc1322008-06-05 17:15:43 +00002293
2294LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
2295 MachineInstr* startInst) {
2296 LiveInterval& Interval = getOrCreateInterval(reg);
2297 VNInfo* VN = Interval.getNextValue(
2298 getInstructionIndex(startInst) + InstrSlots::DEF,
Lang Hames857c4e02009-06-17 21:01:20 +00002299 startInst, true, getVNInfoAllocator());
2300 VN->setHasPHIKill(true);
Owen Andersonc4dc1322008-06-05 17:15:43 +00002301 VN->kills.push_back(getMBBEndIdx(startInst->getParent()));
2302 LiveRange LR(getInstructionIndex(startInst) + InstrSlots::DEF,
2303 getMBBEndIdx(startInst->getParent()) + 1, VN);
2304 Interval.addRange(LR);
2305
2306 return LR;
2307}