blob: 7ef6abc4b45fcf2a3f5c48e9158a66f334e61e9f [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>
Jeff Cohen97af7512006-12-02 02:22:01 +000039#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000040using namespace llvm;
41
Dan Gohman844731a2008-05-13 00:00:25 +000042// Hidden options for help debugging.
43static cl::opt<bool> DisableReMat("disable-rematerialization",
44 cl::init(false), cl::Hidden);
Evan Cheng81a03822007-11-17 00:40:40 +000045
Dan Gohman844731a2008-05-13 00:00:25 +000046static cl::opt<bool> SplitAtBB("split-intervals-at-bb",
47 cl::init(true), cl::Hidden);
48static cl::opt<int> SplitLimit("split-limit",
49 cl::init(-1), cl::Hidden);
Evan Chengbc165e42007-08-16 07:24:22 +000050
Dan Gohman4c8f8702008-07-25 15:08:37 +000051static cl::opt<bool> EnableAggressiveRemat("aggressive-remat", cl::Hidden);
52
Owen Andersonae339ba2008-08-19 00:17:30 +000053static cl::opt<bool> EnableFastSpilling("fast-spill",
54 cl::init(false), cl::Hidden);
55
Chris Lattnercd3245a2006-12-19 22:41:21 +000056STATISTIC(numIntervals, "Number of original intervals");
Evan Cheng0cbb1162007-11-29 01:06:25 +000057STATISTIC(numFolds , "Number of loads/stores folded into instructions");
58STATISTIC(numSplits , "Number of intervals split");
Chris Lattnercd3245a2006-12-19 22:41:21 +000059
Devang Patel19974732007-05-03 01:11:54 +000060char LiveIntervals::ID = 0;
Dan Gohman844731a2008-05-13 00:00:25 +000061static RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000062
Chris Lattnerf7da2c72006-08-24 22:43:55 +000063void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman6d69ba82008-07-25 00:02:30 +000064 AU.addRequired<AliasAnalysis>();
65 AU.addPreserved<AliasAnalysis>();
David Greene25133302007-06-08 17:18:56 +000066 AU.addPreserved<LiveVariables>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000067 AU.addRequired<LiveVariables>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000068 AU.addPreservedID(MachineLoopInfoID);
69 AU.addPreservedID(MachineDominatorsID);
Owen Anderson95dad832008-10-07 20:22:28 +000070
71 if (!StrongPHIElim) {
72 AU.addPreservedID(PHIEliminationID);
73 AU.addRequiredID(PHIEliminationID);
74 }
75
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000076 AU.addRequiredID(TwoAddressInstructionPassID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000077 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000078}
79
Chris Lattnerf7da2c72006-08-24 22:43:55 +000080void LiveIntervals::releaseMemory() {
Owen Anderson03857b22008-08-13 21:49:13 +000081 // Free the live intervals themselves.
Owen Anderson20e28392008-08-13 22:08:30 +000082 for (DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.begin(),
Owen Anderson03857b22008-08-13 21:49:13 +000083 E = r2iMap_.end(); I != E; ++I)
84 delete I->second;
85
Evan Cheng3f32d652008-06-04 09:18:41 +000086 MBB2IdxMap.clear();
Evan Cheng4ca980e2007-10-17 02:10:22 +000087 Idx2MBBMap.clear();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000088 mi2iMap_.clear();
89 i2miMap_.clear();
90 r2iMap_.clear();
Evan Chengdd199d22007-09-06 01:07:24 +000091 // Release VNInfo memroy regions after all VNInfo objects are dtor'd.
92 VNInfoAllocator.Reset();
Evan Cheng1ed99222008-07-19 00:37:25 +000093 while (!ClonedMIs.empty()) {
94 MachineInstr *MI = ClonedMIs.back();
95 ClonedMIs.pop_back();
96 mf_->DeleteMachineInstr(MI);
97 }
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000098}
99
Owen Anderson80b3ce62008-05-28 20:54:50 +0000100void LiveIntervals::computeNumbering() {
101 Index2MiMap OldI2MI = i2miMap_;
Owen Anderson7fbad272008-07-23 21:37:49 +0000102 std::vector<IdxMBBPair> OldI2MBB = Idx2MBBMap;
Owen Anderson80b3ce62008-05-28 20:54:50 +0000103
104 Idx2MBBMap.clear();
105 MBB2IdxMap.clear();
106 mi2iMap_.clear();
107 i2miMap_.clear();
108
Owen Andersona1566f22008-07-22 22:46:49 +0000109 FunctionSize = 0;
110
Chris Lattner428b92e2006-09-15 03:57:23 +0000111 // Number MachineInstrs and MachineBasicBlocks.
112 // Initialize MBB indexes to a sentinal.
Evan Cheng549f27d32007-08-13 23:45:17 +0000113 MBB2IdxMap.resize(mf_->getNumBlockIDs(), std::make_pair(~0U,~0U));
Chris Lattner428b92e2006-09-15 03:57:23 +0000114
115 unsigned MIIndex = 0;
116 for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
117 MBB != E; ++MBB) {
Evan Cheng549f27d32007-08-13 23:45:17 +0000118 unsigned StartIdx = MIIndex;
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000119
Owen Anderson7fbad272008-07-23 21:37:49 +0000120 // Insert an empty slot at the beginning of each block.
121 MIIndex += InstrSlots::NUM;
122 i2miMap_.push_back(0);
123
Chris Lattner428b92e2006-09-15 03:57:23 +0000124 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
125 I != E; ++I) {
126 bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000127 assert(inserted && "multiple MachineInstr -> index mappings");
Devang Patel59500c82008-11-21 20:00:59 +0000128 inserted = true;
Chris Lattner428b92e2006-09-15 03:57:23 +0000129 i2miMap_.push_back(I);
130 MIIndex += InstrSlots::NUM;
Owen Andersona1566f22008-07-22 22:46:49 +0000131 FunctionSize++;
Owen Anderson7fbad272008-07-23 21:37:49 +0000132
Evan Cheng4ed43292008-10-18 05:21:37 +0000133 // Insert max(1, numdefs) empty slots after every instruction.
Evan Cheng99fe34b2008-10-18 05:18:55 +0000134 unsigned Slots = I->getDesc().getNumDefs();
135 if (Slots == 0)
136 Slots = 1;
137 MIIndex += InstrSlots::NUM * Slots;
138 while (Slots--)
139 i2miMap_.push_back(0);
Owen Anderson35578012008-06-16 07:10:49 +0000140 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000141
Owen Anderson1fbb4542008-06-16 16:58:24 +0000142 // Set the MBB2IdxMap entry for this MBB.
143 MBB2IdxMap[MBB->getNumber()] = std::make_pair(StartIdx, MIIndex - 1);
144 Idx2MBBMap.push_back(std::make_pair(StartIdx, MBB));
Chris Lattner428b92e2006-09-15 03:57:23 +0000145 }
Evan Cheng4ca980e2007-10-17 02:10:22 +0000146 std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
Owen Anderson80b3ce62008-05-28 20:54:50 +0000147
148 if (!OldI2MI.empty())
Owen Anderson788d0412008-08-06 18:35:45 +0000149 for (iterator OI = begin(), OE = end(); OI != OE; ++OI) {
Owen Anderson03857b22008-08-13 21:49:13 +0000150 for (LiveInterval::iterator LI = OI->second->begin(),
151 LE = OI->second->end(); LI != LE; ++LI) {
Owen Anderson4b5b2092008-05-29 18:15:49 +0000152
Owen Anderson7eec0c22008-05-29 23:01:22 +0000153 // Remap the start index of the live range to the corresponding new
154 // number, or our best guess at what it _should_ correspond to if the
155 // original instruction has been erased. This is either the following
156 // instruction or its predecessor.
Owen Anderson7fbad272008-07-23 21:37:49 +0000157 unsigned index = LI->start / InstrSlots::NUM;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000158 unsigned offset = LI->start % InstrSlots::NUM;
Owen Anderson0a7615a2008-07-25 23:06:59 +0000159 if (offset == InstrSlots::LOAD) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000160 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000161 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->start);
Owen Anderson7fbad272008-07-23 21:37:49 +0000162 // Take the pair containing the index
163 std::vector<IdxMBBPair>::const_iterator J =
Owen Andersona0c032f2008-07-29 21:15:44 +0000164 (I == OldI2MBB.end() && OldI2MBB.size()>0) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000165
Owen Anderson7fbad272008-07-23 21:37:49 +0000166 LI->start = getMBBStartIdx(J->second);
167 } else {
168 LI->start = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000169 }
170
171 // Remap the ending index in the same way that we remapped the start,
172 // except for the final step where we always map to the immediately
173 // following instruction.
Owen Andersond7dcbec2008-07-25 19:50:48 +0000174 index = (LI->end - 1) / InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000175 offset = LI->end % InstrSlots::NUM;
Owen Anderson9382b932008-07-30 00:22:56 +0000176 if (offset == InstrSlots::LOAD) {
177 // VReg dies at end of block.
Owen Anderson7fbad272008-07-23 21:37:49 +0000178 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000179 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->end);
Owen Anderson9382b932008-07-30 00:22:56 +0000180 --I;
Owen Anderson7fbad272008-07-23 21:37:49 +0000181
Owen Anderson9382b932008-07-30 00:22:56 +0000182 LI->end = getMBBEndIdx(I->second) + 1;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000183 } else {
Owen Andersond7dcbec2008-07-25 19:50:48 +0000184 unsigned idx = index;
Owen Anderson8d0cc0a2008-07-25 21:07:13 +0000185 while (index < OldI2MI.size() && !OldI2MI[index]) ++index;
186
187 if (index != OldI2MI.size())
188 LI->end = mi2iMap_[OldI2MI[index]] + (idx == index ? offset : 0);
189 else
190 LI->end = InstrSlots::NUM * i2miMap_.size();
Owen Anderson4b5b2092008-05-29 18:15:49 +0000191 }
Owen Anderson788d0412008-08-06 18:35:45 +0000192 }
193
Owen Anderson03857b22008-08-13 21:49:13 +0000194 for (LiveInterval::vni_iterator VNI = OI->second->vni_begin(),
195 VNE = OI->second->vni_end(); VNI != VNE; ++VNI) {
Owen Anderson788d0412008-08-06 18:35:45 +0000196 VNInfo* vni = *VNI;
Owen Anderson745825f42008-05-28 22:40:08 +0000197
Owen Anderson7eec0c22008-05-29 23:01:22 +0000198 // Remap the VNInfo def index, which works the same as the
Owen Anderson788d0412008-08-06 18:35:45 +0000199 // start indices above. VN's with special sentinel defs
200 // don't need to be remapped.
Owen Anderson91292392008-07-30 17:42:47 +0000201 if (vni->def != ~0U && vni->def != ~1U) {
Owen Anderson788d0412008-08-06 18:35:45 +0000202 unsigned index = vni->def / InstrSlots::NUM;
203 unsigned offset = vni->def % InstrSlots::NUM;
Owen Anderson91292392008-07-30 17:42:47 +0000204 if (offset == InstrSlots::LOAD) {
205 std::vector<IdxMBBPair>::const_iterator I =
Owen Anderson0a7615a2008-07-25 23:06:59 +0000206 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->def);
Owen Anderson91292392008-07-30 17:42:47 +0000207 // Take the pair containing the index
208 std::vector<IdxMBBPair>::const_iterator J =
Owen Andersona0c032f2008-07-29 21:15:44 +0000209 (I == OldI2MBB.end() && OldI2MBB.size()>0) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000210
Owen Anderson91292392008-07-30 17:42:47 +0000211 vni->def = getMBBStartIdx(J->second);
212 } else {
213 vni->def = mi2iMap_[OldI2MI[index]] + offset;
214 }
Owen Anderson7eec0c22008-05-29 23:01:22 +0000215 }
Owen Anderson745825f42008-05-28 22:40:08 +0000216
Owen Anderson7eec0c22008-05-29 23:01:22 +0000217 // Remap the VNInfo kill indices, which works the same as
218 // the end indices above.
Owen Anderson4b5b2092008-05-29 18:15:49 +0000219 for (size_t i = 0; i < vni->kills.size(); ++i) {
Owen Anderson9382b932008-07-30 00:22:56 +0000220 // PHI kills don't need to be remapped.
221 if (!vni->kills[i]) continue;
222
Owen Anderson788d0412008-08-06 18:35:45 +0000223 unsigned index = (vni->kills[i]-1) / InstrSlots::NUM;
224 unsigned offset = vni->kills[i] % InstrSlots::NUM;
Owen Anderson309c6162008-09-30 22:51:54 +0000225 if (offset == InstrSlots::LOAD) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000226 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000227 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->kills[i]);
Owen Anderson9382b932008-07-30 00:22:56 +0000228 --I;
Owen Anderson7fbad272008-07-23 21:37:49 +0000229
Owen Anderson788d0412008-08-06 18:35:45 +0000230 vni->kills[i] = getMBBEndIdx(I->second);
Owen Anderson7fbad272008-07-23 21:37:49 +0000231 } else {
Owen Andersond7dcbec2008-07-25 19:50:48 +0000232 unsigned idx = index;
Owen Anderson8d0cc0a2008-07-25 21:07:13 +0000233 while (index < OldI2MI.size() && !OldI2MI[index]) ++index;
234
235 if (index != OldI2MI.size())
236 vni->kills[i] = mi2iMap_[OldI2MI[index]] +
237 (idx == index ? offset : 0);
238 else
239 vni->kills[i] = InstrSlots::NUM * i2miMap_.size();
Owen Anderson7eec0c22008-05-29 23:01:22 +0000240 }
Owen Anderson4b5b2092008-05-29 18:15:49 +0000241 }
Owen Anderson80b3ce62008-05-28 20:54:50 +0000242 }
Owen Anderson788d0412008-08-06 18:35:45 +0000243 }
Owen Anderson80b3ce62008-05-28 20:54:50 +0000244}
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000245
Owen Anderson80b3ce62008-05-28 20:54:50 +0000246/// runOnMachineFunction - Register allocate the whole function
247///
248bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
249 mf_ = &fn;
250 mri_ = &mf_->getRegInfo();
251 tm_ = &fn.getTarget();
252 tri_ = tm_->getRegisterInfo();
253 tii_ = tm_->getInstrInfo();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000254 aa_ = &getAnalysis<AliasAnalysis>();
Owen Anderson80b3ce62008-05-28 20:54:50 +0000255 lv_ = &getAnalysis<LiveVariables>();
256 allocatableRegs_ = tri_->getAllocatableSet(fn);
257
258 computeNumbering();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000259 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000260
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000261 numIntervals += getNumIntervals();
262
Chris Lattner70ca3582004-09-30 15:59:17 +0000263 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000264 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000265}
266
Chris Lattner70ca3582004-09-30 15:59:17 +0000267/// print - Implement the dump method.
Reid Spencerce9653c2004-12-07 04:03:45 +0000268void LiveIntervals::print(std::ostream &O, const Module* ) const {
Chris Lattner70ca3582004-09-30 15:59:17 +0000269 O << "********** INTERVALS **********\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000270 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Owen Anderson03857b22008-08-13 21:49:13 +0000271 I->second->print(O, tri_);
Evan Cheng3f32d652008-06-04 09:18:41 +0000272 O << "\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000273 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000274
275 O << "********** MACHINEINSTRS **********\n";
276 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
277 mbbi != mbbe; ++mbbi) {
278 O << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
279 for (MachineBasicBlock::iterator mii = mbbi->begin(),
280 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner477e4552004-09-30 16:10:45 +0000281 O << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner70ca3582004-09-30 15:59:17 +0000282 }
283 }
284}
285
Evan Chengc92da382007-11-03 07:20:12 +0000286/// conflictsWithPhysRegDef - Returns true if the specified register
287/// is defined during the duration of the specified interval.
288bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
289 VirtRegMap &vrm, unsigned reg) {
290 for (LiveInterval::Ranges::const_iterator
291 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
292 for (unsigned index = getBaseIndex(I->start),
293 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
294 index += InstrSlots::NUM) {
295 // skip deleted instructions
296 while (index != end && !getInstructionFromIndex(index))
297 index += InstrSlots::NUM;
298 if (index == end) break;
299
300 MachineInstr *MI = getInstructionFromIndex(index);
Evan Cheng04ee5a12009-01-20 19:12:24 +0000301 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
302 if (tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Cheng5d446262007-11-15 08:13:29 +0000303 if (SrcReg == li.reg || DstReg == li.reg)
304 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000305 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
306 MachineOperand& mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000307 if (!mop.isReg())
Evan Chengc92da382007-11-03 07:20:12 +0000308 continue;
309 unsigned PhysReg = mop.getReg();
Evan Cheng5d446262007-11-15 08:13:29 +0000310 if (PhysReg == 0 || PhysReg == li.reg)
Evan Chengc92da382007-11-03 07:20:12 +0000311 continue;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000312 if (TargetRegisterInfo::isVirtualRegister(PhysReg)) {
Evan Cheng5d446262007-11-15 08:13:29 +0000313 if (!vrm.hasPhys(PhysReg))
314 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000315 PhysReg = vrm.getPhys(PhysReg);
Evan Cheng5d446262007-11-15 08:13:29 +0000316 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000317 if (PhysReg && tri_->regsOverlap(PhysReg, reg))
Evan Chengc92da382007-11-03 07:20:12 +0000318 return true;
319 }
320 }
321 }
322
323 return false;
324}
325
Evan Cheng8f90b6e2009-01-07 02:08:57 +0000326/// conflictsWithPhysRegRef - Similar to conflictsWithPhysRegRef except
327/// it can check use as well.
328bool LiveIntervals::conflictsWithPhysRegRef(LiveInterval &li,
329 unsigned Reg, bool CheckUse,
330 SmallPtrSet<MachineInstr*,32> &JoinedCopies) {
331 for (LiveInterval::Ranges::const_iterator
332 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
333 for (unsigned index = getBaseIndex(I->start),
334 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
335 index += InstrSlots::NUM) {
336 // Skip deleted instructions.
337 MachineInstr *MI = 0;
338 while (index != end) {
339 MI = getInstructionFromIndex(index);
340 if (MI)
341 break;
342 index += InstrSlots::NUM;
343 }
344 if (index == end) break;
345
346 if (JoinedCopies.count(MI))
347 continue;
348 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
349 MachineOperand& MO = MI->getOperand(i);
350 if (!MO.isReg())
351 continue;
352 if (MO.isUse() && !CheckUse)
353 continue;
354 unsigned PhysReg = MO.getReg();
355 if (PhysReg == 0 || TargetRegisterInfo::isVirtualRegister(PhysReg))
356 continue;
357 if (tri_->isSubRegister(Reg, PhysReg))
358 return true;
359 }
360 }
361 }
362
363 return false;
364}
365
366
Evan Cheng549f27d32007-08-13 23:45:17 +0000367void LiveIntervals::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000368 if (TargetRegisterInfo::isPhysicalRegister(reg))
Bill Wendlinge6d088a2008-02-26 21:47:57 +0000369 cerr << tri_->getName(reg);
Evan Cheng549f27d32007-08-13 23:45:17 +0000370 else
371 cerr << "%reg" << reg;
372}
373
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000374void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000375 MachineBasicBlock::iterator mi,
Owen Anderson6b098de2008-06-25 23:39:39 +0000376 unsigned MIIdx, MachineOperand& MO,
Evan Chengef0732d2008-07-10 07:35:43 +0000377 unsigned MOIdx,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000378 LiveInterval &interval) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000379 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000380 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000381
Evan Cheng419852c2008-04-03 16:39:43 +0000382 if (mi->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
383 DOUT << "is a implicit_def\n";
384 return;
385 }
386
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000387 // Virtual registers may be defined multiple times (due to phi
388 // elimination and 2-addr elimination). Much of what we do only has to be
389 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000390 // time we see a vreg.
391 if (interval.empty()) {
392 // Get the Idx of the defining instructions.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000393 unsigned defIndex = getDefIndex(MIIdx);
Dale Johannesen86b49f82008-09-24 01:07:17 +0000394 // Earlyclobbers move back one.
395 if (MO.isEarlyClobber())
396 defIndex = getUseIndex(MIIdx);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000397 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000398 MachineInstr *CopyMI = NULL;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000399 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000400 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000401 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Dan Gohman97121ba2009-04-08 00:15:30 +0000402 mi->getOpcode() == TargetInstrInfo::SUBREG_TO_REG ||
Evan Cheng04ee5a12009-01-20 19:12:24 +0000403 tii_->isMoveInstr(*mi, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000404 CopyMI = mi;
Evan Cheng5379f412008-12-19 20:58:01 +0000405 // Earlyclobbers move back one.
Evan Chengc8d044e2008-02-15 18:24:29 +0000406 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000407
408 assert(ValNo->id == 0 && "First value in interval is not 0?");
Chris Lattner7ac2d312004-07-24 02:59:07 +0000409
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000410 // Loop over all of the blocks that the vreg is defined in. There are
411 // two cases we have to handle here. The most common case is a vreg
412 // whose lifetime is contained within a basic block. In this case there
413 // will be a single kill, in MBB, which comes after the definition.
414 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
415 // FIXME: what about dead vars?
416 unsigned killIdx;
417 if (vi.Kills[0] != mi)
418 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
419 else
420 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000421
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000422 // If the kill happens after the definition, we have an intra-block
423 // live range.
424 if (killIdx > defIndex) {
Evan Cheng61de82d2007-02-15 05:59:24 +0000425 assert(vi.AliveBlocks.none() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000426 "Shouldn't be alive across any blocks!");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000427 LiveRange LR(defIndex, killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000428 interval.addRange(LR);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000429 DOUT << " +" << LR << "\n";
Evan Chengf3bb2e62007-09-05 21:46:51 +0000430 interval.addKill(ValNo, killIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000431 return;
432 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000433 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000434
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000435 // The other case we handle is when a virtual register lives to the end
436 // of the defining block, potentially live across some blocks, then is
437 // live into some number of blocks, but gets killed. Start by adding a
438 // range that goes from this definition to the end of the defining block.
Owen Anderson7fbad272008-07-23 21:37:49 +0000439 LiveRange NewLR(defIndex, getMBBEndIdx(mbb)+1, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000440 DOUT << " +" << NewLR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000441 interval.addRange(NewLR);
442
443 // Iterate over all of the blocks that the variable is completely
444 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
445 // live interval.
Dan Gohman4a829ec2008-11-13 16:31:27 +0000446 for (int i = vi.AliveBlocks.find_first(); i != -1;
447 i = vi.AliveBlocks.find_next(i)) {
448 LiveRange LR(getMBBStartIdx(i),
449 getMBBEndIdx(i)+1, // MBB ends at -1.
450 ValNo);
451 interval.addRange(LR);
452 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000453 }
454
455 // Finally, this virtual register is live from the start of any killing
456 // block to the 'use' slot of the killing instruction.
457 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
458 MachineInstr *Kill = vi.Kills[i];
Evan Cheng8df78602007-08-08 03:00:28 +0000459 unsigned killIdx = getUseIndex(getInstructionIndex(Kill))+1;
Chris Lattner428b92e2006-09-15 03:57:23 +0000460 LiveRange LR(getMBBStartIdx(Kill->getParent()),
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000461 killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000462 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000463 interval.addKill(ValNo, killIdx);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000464 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000465 }
466
467 } else {
468 // If this is the second time we see a virtual register definition, it
469 // must be due to phi elimination or two addr elimination. If this is
Evan Chengbf105c82006-11-03 03:04:46 +0000470 // the result of two address elimination, then the vreg is one of the
471 // def-and-use register operand.
Bob Wilsond9df5012009-04-09 17:16:43 +0000472 if (mi->isRegTiedToUseOperand(MOIdx)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000473 // If this is a two-address definition, then we have already processed
474 // the live range. The only problem is that we didn't realize there
475 // are actually two values in the live interval. Because of this we
476 // need to take the LiveRegion that defines this register and split it
477 // into two values.
Evan Chenga07cec92008-01-10 08:22:10 +0000478 assert(interval.containsOneValue());
479 unsigned DefIndex = getDefIndex(interval.getValNumInfo(0)->def);
Chris Lattner6b128bd2006-09-03 08:07:11 +0000480 unsigned RedefIndex = getDefIndex(MIIdx);
Evan Chengfb112882009-03-23 08:01:15 +0000481 if (MO.isEarlyClobber())
482 RedefIndex = getUseIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000483
Evan Cheng4f8ff162007-08-11 00:59:19 +0000484 const LiveRange *OldLR = interval.getLiveRangeContaining(RedefIndex-1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000485 VNInfo *OldValNo = OldLR->valno;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000486
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000487 // Delete the initial value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000488 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000489 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000490
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000491 // Two-address vregs should always only be redefined once. This means
492 // that at this point, there should be exactly one value number in it.
493 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
494
Chris Lattner91725b72006-08-31 05:54:43 +0000495 // The new value number (#1) is defined by the instruction we claimed
496 // defined value #0.
Evan Chengc8d044e2008-02-15 18:24:29 +0000497 VNInfo *ValNo = interval.getNextValue(OldValNo->def, OldValNo->copy,
498 VNInfoAllocator);
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000499
Chris Lattner91725b72006-08-31 05:54:43 +0000500 // Value#0 is now defined by the 2-addr instruction.
Evan Chengc8d044e2008-02-15 18:24:29 +0000501 OldValNo->def = RedefIndex;
502 OldValNo->copy = 0;
Evan Chengfb112882009-03-23 08:01:15 +0000503 if (MO.isEarlyClobber())
504 OldValNo->redefByEC = true;
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000505
506 // Add the new live interval which replaces the range for the input copy.
507 LiveRange LR(DefIndex, RedefIndex, ValNo);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000508 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000509 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000510 interval.addKill(ValNo, RedefIndex);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000511
512 // If this redefinition is dead, we need to add a dummy unit live
513 // range covering the def slot.
Owen Anderson6b098de2008-06-25 23:39:39 +0000514 if (MO.isDead())
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000515 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, OldValNo));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000516
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000517 DOUT << " RESULT: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000518 interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000519
520 } else {
521 // Otherwise, this must be because of phi elimination. If this is the
522 // first redefinition of the vreg that we have seen, go back and change
523 // the live range in the PHI block to be a different value number.
524 if (interval.containsOneValue()) {
525 assert(vi.Kills.size() == 1 &&
526 "PHI elimination vreg should have one kill, the PHI itself!");
527
528 // Remove the old range that we now know has an incorrect number.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000529 VNInfo *VNI = interval.getValNumInfo(0);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000530 MachineInstr *Killer = vi.Kills[0];
Chris Lattner428b92e2006-09-15 03:57:23 +0000531 unsigned Start = getMBBStartIdx(Killer->getParent());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000532 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
Evan Cheng56fdd7a2007-03-15 21:19:28 +0000533 DOUT << " Removing [" << Start << "," << End << "] from: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +0000534 interval.print(DOUT, tri_); DOUT << "\n";
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000535 interval.removeRange(Start, End);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000536 VNI->hasPHIKill = true;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000537 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000538
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000539 // Replace the interval with one of a NEW value number. Note that this
540 // value number isn't actually defined by an instruction, weird huh? :)
Evan Chengf3bb2e62007-09-05 21:46:51 +0000541 LiveRange LR(Start, End, interval.getNextValue(~0, 0, VNInfoAllocator));
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000542 DOUT << " replace range with " << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000543 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000544 interval.addKill(LR.valno, End);
Dan Gohman6f0d0242008-02-10 18:45:23 +0000545 DOUT << " RESULT: "; interval.print(DOUT, tri_);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000546 }
547
548 // In the case of PHI elimination, each variable definition is only
549 // live until the end of the block. We've already taken care of the
550 // rest of the live range.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000551 unsigned defIndex = getDefIndex(MIIdx);
Evan Chengfb112882009-03-23 08:01:15 +0000552 if (MO.isEarlyClobber())
553 defIndex = getUseIndex(MIIdx);
Chris Lattner91725b72006-08-31 05:54:43 +0000554
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000555 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000556 MachineInstr *CopyMI = NULL;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000557 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000558 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000559 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Dan Gohman97121ba2009-04-08 00:15:30 +0000560 mi->getOpcode() == TargetInstrInfo::SUBREG_TO_REG ||
Evan Cheng04ee5a12009-01-20 19:12:24 +0000561 tii_->isMoveInstr(*mi, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000562 CopyMI = mi;
563 ValNo = interval.getNextValue(defIndex, CopyMI, VNInfoAllocator);
Chris Lattner91725b72006-08-31 05:54:43 +0000564
Owen Anderson7fbad272008-07-23 21:37:49 +0000565 unsigned killIndex = getMBBEndIdx(mbb) + 1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000566 LiveRange LR(defIndex, killIndex, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000567 interval.addRange(LR);
Evan Chengc3fc7d92007-11-29 09:49:23 +0000568 interval.addKill(ValNo, killIndex);
569 ValNo->hasPHIKill = true;
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000570 DOUT << " +" << LR;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000571 }
572 }
573
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000574 DOUT << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000575}
576
Chris Lattnerf35fef72004-07-23 21:24:19 +0000577void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000578 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000579 unsigned MIIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000580 MachineOperand& MO,
Chris Lattner91725b72006-08-31 05:54:43 +0000581 LiveInterval &interval,
Evan Chengc8d044e2008-02-15 18:24:29 +0000582 MachineInstr *CopyMI) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000583 // A physical register cannot be live across basic block, so its
584 // lifetime must end somewhere in its defining basic block.
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000585 DOUT << "\t\tregister: "; DEBUG(printRegName(interval.reg));
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000586
Chris Lattner6b128bd2006-09-03 08:07:11 +0000587 unsigned baseIndex = MIIdx;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000588 unsigned start = getDefIndex(baseIndex);
Dale Johannesen86b49f82008-09-24 01:07:17 +0000589 // Earlyclobbers move back one.
590 if (MO.isEarlyClobber())
591 start = getUseIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000592 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000593
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000594 // If it is not used after definition, it is considered dead at
595 // the instruction defining it. Hence its interval is:
596 // [defSlot(def), defSlot(def)+1)
Owen Anderson6b098de2008-06-25 23:39:39 +0000597 if (MO.isDead()) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000598 DOUT << " dead";
Dale Johannesen86b49f82008-09-24 01:07:17 +0000599 end = start + 1;
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000600 goto exit;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000601 }
602
603 // If it is not dead on definition, it must be killed by a
604 // subsequent instruction. Hence its interval is:
605 // [defSlot(def), useSlot(kill)+1)
Owen Anderson7fbad272008-07-23 21:37:49 +0000606 baseIndex += InstrSlots::NUM;
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000607 while (++mi != MBB->end()) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000608 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
609 getInstructionFromIndex(baseIndex) == 0)
610 baseIndex += InstrSlots::NUM;
Evan Cheng6130f662008-03-05 00:59:57 +0000611 if (mi->killsRegister(interval.reg, tri_)) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000612 DOUT << " killed";
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000613 end = getUseIndex(baseIndex) + 1;
614 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000615 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Cheng9a1956a2006-11-15 20:54:11 +0000616 // Another instruction redefines the register before it is ever read.
617 // Then the register is essentially dead at the instruction that defines
618 // it. Hence its interval is:
619 // [defSlot(def), defSlot(def)+1)
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000620 DOUT << " dead";
Dale Johannesen86b49f82008-09-24 01:07:17 +0000621 end = start + 1;
Evan Cheng9a1956a2006-11-15 20:54:11 +0000622 goto exit;
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000623 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000624
625 baseIndex += InstrSlots::NUM;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000626 }
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000627
628 // The only case we should have a dead physreg here without a killing or
629 // instruction where we know it's dead is if it is live-in to the function
Evan Chengd521bc92009-04-27 17:36:47 +0000630 // and never used. Another possible case is the implicit use of the
631 // physical register has been deleted by two-address pass.
Dale Johannesen86b49f82008-09-24 01:07:17 +0000632 end = start + 1;
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000633
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000634exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000635 assert(start < end && "did not find end of interval?");
Chris Lattnerf768bba2005-03-09 23:05:19 +0000636
Evan Cheng24a3cc42007-04-25 07:30:23 +0000637 // Already exists? Extend old live interval.
638 LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
Evan Cheng5379f412008-12-19 20:58:01 +0000639 bool Extend = OldLR != interval.end();
640 VNInfo *ValNo = Extend
Evan Chengc8d044e2008-02-15 18:24:29 +0000641 ? OldLR->valno : interval.getNextValue(start, CopyMI, VNInfoAllocator);
Evan Cheng5379f412008-12-19 20:58:01 +0000642 if (MO.isEarlyClobber() && Extend)
643 ValNo->redefByEC = true;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000644 LiveRange LR(start, end, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000645 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000646 interval.addKill(LR.valno, end);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000647 DOUT << " +" << LR << '\n';
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000648}
649
Chris Lattnerf35fef72004-07-23 21:24:19 +0000650void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
651 MachineBasicBlock::iterator MI,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000652 unsigned MIIdx,
Evan Chengef0732d2008-07-10 07:35:43 +0000653 MachineOperand& MO,
654 unsigned MOIdx) {
Owen Anderson6b098de2008-06-25 23:39:39 +0000655 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Evan Chengef0732d2008-07-10 07:35:43 +0000656 handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000657 getOrCreateInterval(MO.getReg()));
658 else if (allocatableRegs_[MO.getReg()]) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000659 MachineInstr *CopyMI = NULL;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000660 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000661 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000662 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Dan Gohman97121ba2009-04-08 00:15:30 +0000663 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG ||
Evan Cheng04ee5a12009-01-20 19:12:24 +0000664 tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000665 CopyMI = MI;
Owen Anderson6b098de2008-06-25 23:39:39 +0000666 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
667 getOrCreateInterval(MO.getReg()), CopyMI);
Evan Cheng24a3cc42007-04-25 07:30:23 +0000668 // Def of a register also defines its sub-registers.
Owen Anderson6b098de2008-06-25 23:39:39 +0000669 for (const unsigned* AS = tri_->getSubRegisters(MO.getReg()); *AS; ++AS)
Evan Cheng6130f662008-03-05 00:59:57 +0000670 // If MI also modifies the sub-register explicitly, avoid processing it
671 // more than once. Do not pass in TRI here so it checks for exact match.
672 if (!MI->modifiesRegister(*AS))
Owen Anderson6b098de2008-06-25 23:39:39 +0000673 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
674 getOrCreateInterval(*AS), 0);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000675 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000676}
677
Evan Chengb371f452007-02-19 21:49:54 +0000678void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000679 unsigned MIIdx,
Evan Cheng24a3cc42007-04-25 07:30:23 +0000680 LiveInterval &interval, bool isAlias) {
Evan Chengb371f452007-02-19 21:49:54 +0000681 DOUT << "\t\tlivein register: "; DEBUG(printRegName(interval.reg));
682
683 // Look for kills, if it reaches a def before it's killed, then it shouldn't
684 // be considered a livein.
685 MachineBasicBlock::iterator mi = MBB->begin();
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000686 unsigned baseIndex = MIIdx;
687 unsigned start = baseIndex;
Owen Anderson99500ae2008-09-15 22:00:38 +0000688 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
689 getInstructionFromIndex(baseIndex) == 0)
690 baseIndex += InstrSlots::NUM;
691 unsigned end = baseIndex;
Evan Cheng0076c612009-03-05 03:34:26 +0000692 bool SeenDefUse = false;
Owen Anderson99500ae2008-09-15 22:00:38 +0000693
Evan Chengb371f452007-02-19 21:49:54 +0000694 while (mi != MBB->end()) {
Evan Cheng6130f662008-03-05 00:59:57 +0000695 if (mi->killsRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000696 DOUT << " killed";
697 end = getUseIndex(baseIndex) + 1;
Evan Cheng0076c612009-03-05 03:34:26 +0000698 SeenDefUse = true;
Evan Chengb371f452007-02-19 21:49:54 +0000699 goto exit;
Evan Cheng6130f662008-03-05 00:59:57 +0000700 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000701 // Another instruction redefines the register before it is ever read.
702 // Then the register is essentially dead at the instruction that defines
703 // it. Hence its interval is:
704 // [defSlot(def), defSlot(def)+1)
705 DOUT << " dead";
706 end = getDefIndex(start) + 1;
Evan Cheng0076c612009-03-05 03:34:26 +0000707 SeenDefUse = true;
Evan Chengb371f452007-02-19 21:49:54 +0000708 goto exit;
709 }
710
711 baseIndex += InstrSlots::NUM;
712 ++mi;
Evan Cheng0076c612009-03-05 03:34:26 +0000713 if (mi != MBB->end()) {
714 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
715 getInstructionFromIndex(baseIndex) == 0)
716 baseIndex += InstrSlots::NUM;
717 }
Evan Chengb371f452007-02-19 21:49:54 +0000718 }
719
720exit:
Evan Cheng75611fb2007-06-27 01:16:36 +0000721 // Live-in register might not be used at all.
Evan Cheng0076c612009-03-05 03:34:26 +0000722 if (!SeenDefUse) {
Evan Cheng292da942007-06-27 18:47:28 +0000723 if (isAlias) {
724 DOUT << " dead";
Evan Cheng75611fb2007-06-27 01:16:36 +0000725 end = getDefIndex(MIIdx) + 1;
Evan Cheng292da942007-06-27 18:47:28 +0000726 } else {
727 DOUT << " live through";
728 end = baseIndex;
729 }
Evan Cheng24a3cc42007-04-25 07:30:23 +0000730 }
731
Owen Anderson99500ae2008-09-15 22:00:38 +0000732 LiveRange LR(start, end, interval.getNextValue(~0U, 0, VNInfoAllocator));
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000733 interval.addRange(LR);
Evan Chengf3bb2e62007-09-05 21:46:51 +0000734 interval.addKill(LR.valno, end);
Evan Cheng24c2e5c2007-08-08 07:03:29 +0000735 DOUT << " +" << LR << '\n';
Evan Chengb371f452007-02-19 21:49:54 +0000736}
737
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000738/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000739/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000740/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000741/// which a variable is live
Dale Johannesen91aac102008-09-17 21:13:11 +0000742void LiveIntervals::computeIntervals() {
Dale Johannesen91aac102008-09-17 21:13:11 +0000743
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000744 DOUT << "********** COMPUTING LIVE INTERVALS **********\n"
745 << "********** Function: "
746 << ((Value*)mf_->getFunction())->getName() << '\n';
Owen Anderson7fbad272008-07-23 21:37:49 +0000747
Chris Lattner428b92e2006-09-15 03:57:23 +0000748 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
749 MBBI != E; ++MBBI) {
750 MachineBasicBlock *MBB = MBBI;
Owen Anderson134eb732008-09-21 20:43:24 +0000751 // Track the index of the current machine instr.
752 unsigned MIIndex = getMBBStartIdx(MBB);
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000753 DOUT << ((Value*)MBB->getBasicBlock())->getName() << ":\n";
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000754
Chris Lattner428b92e2006-09-15 03:57:23 +0000755 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000756
Dan Gohmancb406c22007-10-03 19:26:29 +0000757 // Create intervals for live-ins to this BB first.
758 for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
759 LE = MBB->livein_end(); LI != LE; ++LI) {
760 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
761 // Multiple live-ins can alias the same register.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000762 for (const unsigned* AS = tri_->getSubRegisters(*LI); *AS; ++AS)
Dan Gohmancb406c22007-10-03 19:26:29 +0000763 if (!hasInterval(*AS))
764 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
765 true);
Chris Lattnerdffb2e82006-09-04 18:27:40 +0000766 }
767
Owen Anderson99500ae2008-09-15 22:00:38 +0000768 // Skip over empty initial indices.
769 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
770 getInstructionFromIndex(MIIndex) == 0)
771 MIIndex += InstrSlots::NUM;
772
Chris Lattner428b92e2006-09-15 03:57:23 +0000773 for (; MI != miEnd; ++MI) {
Bill Wendlingbdc679d2006-11-29 00:39:47 +0000774 DOUT << MIIndex << "\t" << *MI;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000775
Evan Cheng438f7bc2006-11-10 08:43:01 +0000776 // Handle defs.
Chris Lattner428b92e2006-09-15 03:57:23 +0000777 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
778 MachineOperand &MO = MI->getOperand(i);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000779 // handle register defs - build intervals
Dan Gohmand735b802008-10-03 15:45:36 +0000780 if (MO.isReg() && MO.getReg() && MO.isDef()) {
Evan Chengef0732d2008-07-10 07:35:43 +0000781 handleRegisterDef(MBB, MI, MIIndex, MO, i);
Dale Johannesen91aac102008-09-17 21:13:11 +0000782 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000783 }
Evan Cheng99fe34b2008-10-18 05:18:55 +0000784
785 // Skip over the empty slots after each instruction.
786 unsigned Slots = MI->getDesc().getNumDefs();
787 if (Slots == 0)
788 Slots = 1;
789 MIIndex += InstrSlots::NUM * Slots;
Owen Anderson7fbad272008-07-23 21:37:49 +0000790
791 // Skip over empty indices.
792 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
793 getInstructionFromIndex(MIIndex) == 0)
794 MIIndex += InstrSlots::NUM;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000795 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000796 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000797}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000798
Evan Chengd0e32c52008-10-29 05:06:14 +0000799bool LiveIntervals::findLiveInMBBs(unsigned Start, unsigned End,
Evan Chenga5bfc972007-10-17 06:53:44 +0000800 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
Evan Cheng4ca980e2007-10-17 02:10:22 +0000801 std::vector<IdxMBBPair>::const_iterator I =
Evan Chengd0e32c52008-10-29 05:06:14 +0000802 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), Start);
Evan Cheng4ca980e2007-10-17 02:10:22 +0000803
804 bool ResVal = false;
805 while (I != Idx2MBBMap.end()) {
Dan Gohman2ad82452008-11-26 05:50:31 +0000806 if (I->first >= End)
Evan Cheng4ca980e2007-10-17 02:10:22 +0000807 break;
808 MBBs.push_back(I->second);
809 ResVal = true;
810 ++I;
811 }
812 return ResVal;
813}
814
Evan Chengd0e32c52008-10-29 05:06:14 +0000815bool LiveIntervals::findReachableMBBs(unsigned Start, unsigned End,
816 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
817 std::vector<IdxMBBPair>::const_iterator I =
818 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), Start);
819
820 bool ResVal = false;
821 while (I != Idx2MBBMap.end()) {
822 if (I->first > End)
823 break;
824 MachineBasicBlock *MBB = I->second;
825 if (getMBBEndIdx(MBB) > End)
826 break;
827 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
828 SE = MBB->succ_end(); SI != SE; ++SI)
829 MBBs.push_back(*SI);
830 ResVal = true;
831 ++I;
832 }
833 return ResVal;
834}
835
Owen Anderson03857b22008-08-13 21:49:13 +0000836LiveInterval* LiveIntervals::createInterval(unsigned reg) {
Evan Cheng0a1fcce2009-02-08 11:04:35 +0000837 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? HUGE_VALF : 0.0F;
Owen Anderson03857b22008-08-13 21:49:13 +0000838 return new LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000839}
Evan Chengf2fbca62007-11-12 06:35:08 +0000840
Evan Cheng0a1fcce2009-02-08 11:04:35 +0000841/// dupInterval - Duplicate a live interval. The caller is responsible for
842/// managing the allocated memory.
843LiveInterval* LiveIntervals::dupInterval(LiveInterval *li) {
844 LiveInterval *NewLI = createInterval(li->reg);
845 NewLI->Copy(*li, getVNInfoAllocator());
846 return NewLI;
847}
848
Evan Chengc8d044e2008-02-15 18:24:29 +0000849/// getVNInfoSourceReg - Helper function that parses the specified VNInfo
850/// copy field and returns the source register that defines it.
851unsigned LiveIntervals::getVNInfoSourceReg(const VNInfo *VNI) const {
852 if (!VNI->copy)
853 return 0;
854
Evan Cheng8f90b6e2009-01-07 02:08:57 +0000855 if (VNI->copy->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
856 // If it's extracting out of a physical register, return the sub-register.
857 unsigned Reg = VNI->copy->getOperand(1).getReg();
858 if (TargetRegisterInfo::isPhysicalRegister(Reg))
859 Reg = tri_->getSubReg(Reg, VNI->copy->getOperand(2).getImm());
860 return Reg;
Dan Gohman97121ba2009-04-08 00:15:30 +0000861 } else if (VNI->copy->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
862 VNI->copy->getOpcode() == TargetInstrInfo::SUBREG_TO_REG)
Evan Cheng7e073ba2008-04-09 20:57:25 +0000863 return VNI->copy->getOperand(2).getReg();
Evan Cheng8f90b6e2009-01-07 02:08:57 +0000864
Evan Cheng04ee5a12009-01-20 19:12:24 +0000865 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
866 if (tii_->isMoveInstr(*VNI->copy, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000867 return SrcReg;
868 assert(0 && "Unrecognized copy instruction!");
869 return 0;
870}
Evan Chengf2fbca62007-11-12 06:35:08 +0000871
872//===----------------------------------------------------------------------===//
873// Register allocator hooks.
874//
875
Evan Chengd70dbb52008-02-22 09:24:50 +0000876/// getReMatImplicitUse - If the remat definition MI has one (for now, we only
877/// allow one) virtual register operand, then its uses are implicitly using
878/// the register. Returns the virtual register.
879unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
880 MachineInstr *MI) const {
881 unsigned RegOp = 0;
882 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
883 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000884 if (!MO.isReg() || !MO.isUse())
Evan Chengd70dbb52008-02-22 09:24:50 +0000885 continue;
886 unsigned Reg = MO.getReg();
887 if (Reg == 0 || Reg == li.reg)
888 continue;
889 // FIXME: For now, only remat MI with at most one register operand.
890 assert(!RegOp &&
891 "Can't rematerialize instruction with multiple register operand!");
892 RegOp = MO.getReg();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000893#ifndef NDEBUG
Evan Chengd70dbb52008-02-22 09:24:50 +0000894 break;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000895#endif
Evan Chengd70dbb52008-02-22 09:24:50 +0000896 }
897 return RegOp;
898}
899
900/// isValNoAvailableAt - Return true if the val# of the specified interval
901/// which reaches the given instruction also reaches the specified use index.
902bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
903 unsigned UseIdx) const {
904 unsigned Index = getInstructionIndex(MI);
905 VNInfo *ValNo = li.FindLiveRangeContaining(Index)->valno;
906 LiveInterval::const_iterator UI = li.FindLiveRangeContaining(UseIdx);
907 return UI != li.end() && UI->valno == ValNo;
908}
909
Evan Chengf2fbca62007-11-12 06:35:08 +0000910/// isReMaterializable - Returns true if the definition MI of the specified
911/// val# of the specified interval is re-materializable.
912bool LiveIntervals::isReMaterializable(const LiveInterval &li,
Evan Cheng5ef3a042007-12-06 00:01:56 +0000913 const VNInfo *ValNo, MachineInstr *MI,
Evan Chengdc377862008-09-30 15:44:16 +0000914 SmallVectorImpl<LiveInterval*> &SpillIs,
Evan Cheng5ef3a042007-12-06 00:01:56 +0000915 bool &isLoad) {
Evan Chengf2fbca62007-11-12 06:35:08 +0000916 if (DisableReMat)
917 return false;
918
Evan Cheng20ccded2008-03-15 00:19:36 +0000919 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
Evan Chengd70dbb52008-02-22 09:24:50 +0000920 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000921
922 int FrameIdx = 0;
923 if (tii_->isLoadFromStackSlot(MI, FrameIdx) &&
Evan Cheng249ded32008-02-23 03:38:34 +0000924 mf_->getFrameInfo()->isImmutableObjectIndex(FrameIdx))
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000925 // FIXME: Let target specific isReallyTriviallyReMaterializable determines
926 // this but remember this is not safe to fold into a two-address
927 // instruction.
Evan Cheng249ded32008-02-23 03:38:34 +0000928 // This is a load from fixed stack slot. It can be rematerialized.
Evan Chengdd3465e2008-02-23 01:44:27 +0000929 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +0000930
Dan Gohman6d69ba82008-07-25 00:02:30 +0000931 // If the target-specific rules don't identify an instruction as
932 // being trivially rematerializable, use some target-independent
933 // rules.
934 if (!MI->getDesc().isRematerializable() ||
935 !tii_->isTriviallyReMaterializable(MI)) {
Dan Gohman4c8f8702008-07-25 15:08:37 +0000936 if (!EnableAggressiveRemat)
937 return false;
Evan Chengd70dbb52008-02-22 09:24:50 +0000938
Dan Gohman0471a792008-07-28 18:43:51 +0000939 // If the instruction accesses memory but the memoperands have been lost,
Dan Gohman6d69ba82008-07-25 00:02:30 +0000940 // we can't analyze it.
941 const TargetInstrDesc &TID = MI->getDesc();
942 if ((TID.mayLoad() || TID.mayStore()) && MI->memoperands_empty())
943 return false;
944
945 // Avoid instructions obviously unsafe for remat.
946 if (TID.hasUnmodeledSideEffects() || TID.isNotDuplicable())
947 return false;
948
949 // If the instruction accesses memory and the memory could be non-constant,
950 // assume the instruction is not rematerializable.
Evan Chengdc377862008-09-30 15:44:16 +0000951 for (std::list<MachineMemOperand>::const_iterator
952 I = MI->memoperands_begin(), E = MI->memoperands_end(); I != E; ++I){
Dan Gohman6d69ba82008-07-25 00:02:30 +0000953 const MachineMemOperand &MMO = *I;
954 if (MMO.isVolatile() || MMO.isStore())
955 return false;
956 const Value *V = MMO.getValue();
957 if (!V)
958 return false;
959 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
960 if (!PSV->isConstant(mf_->getFrameInfo()))
Evan Chengd70dbb52008-02-22 09:24:50 +0000961 return false;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000962 } else if (!aa_->pointsToConstantMemory(V))
963 return false;
964 }
965
966 // If any of the registers accessed are non-constant, conservatively assume
967 // the instruction is not rematerializable.
968 unsigned ImpUse = 0;
969 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
970 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000971 if (MO.isReg()) {
Dan Gohman6d69ba82008-07-25 00:02:30 +0000972 unsigned Reg = MO.getReg();
973 if (Reg == 0)
974 continue;
975 if (TargetRegisterInfo::isPhysicalRegister(Reg))
976 return false;
977
978 // Only allow one def, and that in the first operand.
979 if (MO.isDef() != (i == 0))
980 return false;
981
982 // Only allow constant-valued registers.
983 bool IsLiveIn = mri_->isLiveIn(Reg);
984 MachineRegisterInfo::def_iterator I = mri_->def_begin(Reg),
985 E = mri_->def_end();
986
Dan Gohmanc93ced5b2008-12-08 04:53:23 +0000987 // For the def, it should be the only def of that register.
Dan Gohman6d69ba82008-07-25 00:02:30 +0000988 if (MO.isDef() && (next(I) != E || IsLiveIn))
989 return false;
990
991 if (MO.isUse()) {
992 // Only allow one use other register use, as that's all the
993 // remat mechanisms support currently.
994 if (Reg != li.reg) {
995 if (ImpUse == 0)
996 ImpUse = Reg;
997 else if (Reg != ImpUse)
998 return false;
999 }
Dan Gohmanc93ced5b2008-12-08 04:53:23 +00001000 // For the use, there should be only one associated def.
Dan Gohman6d69ba82008-07-25 00:02:30 +00001001 if (I != E && (next(I) != E || IsLiveIn))
1002 return false;
1003 }
Evan Chengd70dbb52008-02-22 09:24:50 +00001004 }
1005 }
Evan Cheng5ef3a042007-12-06 00:01:56 +00001006 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001007
Dan Gohman6d69ba82008-07-25 00:02:30 +00001008 unsigned ImpUse = getReMatImplicitUse(li, MI);
1009 if (ImpUse) {
1010 const LiveInterval &ImpLi = getInterval(ImpUse);
1011 for (MachineRegisterInfo::use_iterator ri = mri_->use_begin(li.reg),
1012 re = mri_->use_end(); ri != re; ++ri) {
1013 MachineInstr *UseMI = &*ri;
1014 unsigned UseIdx = getInstructionIndex(UseMI);
1015 if (li.FindLiveRangeContaining(UseIdx)->valno != ValNo)
1016 continue;
1017 if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
1018 return false;
1019 }
Evan Chengdc377862008-09-30 15:44:16 +00001020
1021 // If a register operand of the re-materialized instruction is going to
1022 // be spilled next, then it's not legal to re-materialize this instruction.
1023 for (unsigned i = 0, e = SpillIs.size(); i != e; ++i)
1024 if (ImpUse == SpillIs[i]->reg)
1025 return false;
Dan Gohman6d69ba82008-07-25 00:02:30 +00001026 }
1027 return true;
Evan Cheng5ef3a042007-12-06 00:01:56 +00001028}
1029
Evan Cheng06587492008-10-24 02:05:00 +00001030/// isReMaterializable - Returns true if the definition MI of the specified
1031/// val# of the specified interval is re-materializable.
1032bool LiveIntervals::isReMaterializable(const LiveInterval &li,
1033 const VNInfo *ValNo, MachineInstr *MI) {
1034 SmallVector<LiveInterval*, 4> Dummy1;
1035 bool Dummy2;
1036 return isReMaterializable(li, ValNo, MI, Dummy1, Dummy2);
1037}
1038
Evan Cheng5ef3a042007-12-06 00:01:56 +00001039/// isReMaterializable - Returns true if every definition of MI of every
1040/// val# of the specified interval is re-materializable.
Evan Chengdc377862008-09-30 15:44:16 +00001041bool LiveIntervals::isReMaterializable(const LiveInterval &li,
1042 SmallVectorImpl<LiveInterval*> &SpillIs,
1043 bool &isLoad) {
Evan Cheng5ef3a042007-12-06 00:01:56 +00001044 isLoad = false;
1045 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1046 i != e; ++i) {
1047 const VNInfo *VNI = *i;
1048 unsigned DefIdx = VNI->def;
1049 if (DefIdx == ~1U)
1050 continue; // Dead val#.
1051 // Is the def for the val# rematerializable?
1052 if (DefIdx == ~0u)
1053 return false;
1054 MachineInstr *ReMatDefMI = getInstructionFromIndex(DefIdx);
1055 bool DefIsLoad = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001056 if (!ReMatDefMI ||
Evan Chengdc377862008-09-30 15:44:16 +00001057 !isReMaterializable(li, VNI, ReMatDefMI, SpillIs, DefIsLoad))
Evan Cheng5ef3a042007-12-06 00:01:56 +00001058 return false;
1059 isLoad |= DefIsLoad;
Evan Chengf2fbca62007-11-12 06:35:08 +00001060 }
1061 return true;
1062}
1063
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001064/// FilterFoldedOps - Filter out two-address use operands. Return
1065/// true if it finds any issue with the operands that ought to prevent
1066/// folding.
1067static bool FilterFoldedOps(MachineInstr *MI,
1068 SmallVector<unsigned, 2> &Ops,
1069 unsigned &MRInfo,
1070 SmallVector<unsigned, 2> &FoldOps) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001071 MRInfo = 0;
Evan Chengaee4af62007-12-02 08:30:39 +00001072 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1073 unsigned OpIdx = Ops[i];
Evan Chengd70dbb52008-02-22 09:24:50 +00001074 MachineOperand &MO = MI->getOperand(OpIdx);
Evan Chengaee4af62007-12-02 08:30:39 +00001075 // FIXME: fold subreg use.
Evan Chengd70dbb52008-02-22 09:24:50 +00001076 if (MO.getSubReg())
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001077 return true;
Evan Chengd70dbb52008-02-22 09:24:50 +00001078 if (MO.isDef())
Evan Chengaee4af62007-12-02 08:30:39 +00001079 MRInfo |= (unsigned)VirtRegMap::isMod;
1080 else {
1081 // Filter out two-address use operand(s).
Evan Chenga24752f2009-03-19 20:30:06 +00001082 if (MI->isRegTiedToDefOperand(OpIdx)) {
Evan Chengaee4af62007-12-02 08:30:39 +00001083 MRInfo = VirtRegMap::isModRef;
1084 continue;
1085 }
1086 MRInfo |= (unsigned)VirtRegMap::isRef;
1087 }
1088 FoldOps.push_back(OpIdx);
Evan Chenge62f97c2007-12-01 02:07:52 +00001089 }
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001090 return false;
1091}
1092
1093
1094/// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
1095/// slot / to reg or any rematerialized load into ith operand of specified
1096/// MI. If it is successul, MI is updated with the newly created MI and
1097/// returns true.
1098bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
1099 VirtRegMap &vrm, MachineInstr *DefMI,
1100 unsigned InstrIdx,
1101 SmallVector<unsigned, 2> &Ops,
1102 bool isSS, int Slot, unsigned Reg) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001103 // If it is an implicit def instruction, just delete it.
Evan Cheng20ccded2008-03-15 00:19:36 +00001104 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001105 RemoveMachineInstrFromMaps(MI);
1106 vrm.RemoveMachineInstrFromMaps(MI);
1107 MI->eraseFromParent();
1108 ++numFolds;
1109 return true;
1110 }
1111
1112 // Filter the list of operand indexes that are to be folded. Abort if
1113 // any operand will prevent folding.
1114 unsigned MRInfo = 0;
1115 SmallVector<unsigned, 2> FoldOps;
1116 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1117 return false;
Evan Chenge62f97c2007-12-01 02:07:52 +00001118
Evan Cheng427f4c12008-03-31 23:19:51 +00001119 // The only time it's safe to fold into a two address instruction is when
1120 // it's folding reload and spill from / into a spill stack slot.
1121 if (DefMI && (MRInfo & VirtRegMap::isMod))
Evan Cheng249ded32008-02-23 03:38:34 +00001122 return false;
1123
Evan Chengf2f8c2a2008-02-08 22:05:27 +00001124 MachineInstr *fmi = isSS ? tii_->foldMemoryOperand(*mf_, MI, FoldOps, Slot)
1125 : tii_->foldMemoryOperand(*mf_, MI, FoldOps, DefMI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001126 if (fmi) {
Evan Chengd3653122008-02-27 03:04:06 +00001127 // Remember this instruction uses the spill slot.
1128 if (isSS) vrm.addSpillSlotUse(Slot, fmi);
1129
Evan Chengf2fbca62007-11-12 06:35:08 +00001130 // Attempt to fold the memory reference into the instruction. If
1131 // we can do this, we don't need to insert spill code.
Evan Chengf2fbca62007-11-12 06:35:08 +00001132 MachineBasicBlock &MBB = *MI->getParent();
Evan Cheng84802932008-01-10 08:24:38 +00001133 if (isSS && !mf_->getFrameInfo()->isImmutableObjectIndex(Slot))
Evan Chengaee4af62007-12-02 08:30:39 +00001134 vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
Evan Cheng81a03822007-11-17 00:40:40 +00001135 vrm.transferSpillPts(MI, fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001136 vrm.transferRestorePts(MI, fmi);
Evan Chengc1f53c72008-03-11 21:34:46 +00001137 vrm.transferEmergencySpills(MI, fmi);
Evan Chengf2fbca62007-11-12 06:35:08 +00001138 mi2iMap_.erase(MI);
Evan Chengcddbb832007-11-30 21:23:43 +00001139 i2miMap_[InstrIdx /InstrSlots::NUM] = fmi;
1140 mi2iMap_[fmi] = InstrIdx;
Evan Chengf2fbca62007-11-12 06:35:08 +00001141 MI = MBB.insert(MBB.erase(MI), fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001142 ++numFolds;
Evan Chengf2fbca62007-11-12 06:35:08 +00001143 return true;
1144 }
1145 return false;
1146}
1147
Evan Cheng018f9b02007-12-05 03:22:34 +00001148/// canFoldMemoryOperand - Returns true if the specified load / store
1149/// folding is possible.
1150bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI,
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001151 SmallVector<unsigned, 2> &Ops,
Evan Cheng3c75ba82008-04-01 21:37:32 +00001152 bool ReMat) const {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001153 // Filter the list of operand indexes that are to be folded. Abort if
1154 // any operand will prevent folding.
1155 unsigned MRInfo = 0;
Evan Cheng018f9b02007-12-05 03:22:34 +00001156 SmallVector<unsigned, 2> FoldOps;
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001157 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1158 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001159
Evan Cheng3c75ba82008-04-01 21:37:32 +00001160 // It's only legal to remat for a use, not a def.
1161 if (ReMat && (MRInfo & VirtRegMap::isMod))
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001162 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001163
Evan Chengd70dbb52008-02-22 09:24:50 +00001164 return tii_->canFoldMemoryOperand(MI, FoldOps);
1165}
1166
Evan Cheng81a03822007-11-17 00:40:40 +00001167bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
1168 SmallPtrSet<MachineBasicBlock*, 4> MBBs;
1169 for (LiveInterval::Ranges::const_iterator
1170 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1171 std::vector<IdxMBBPair>::const_iterator II =
1172 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), I->start);
1173 if (II == Idx2MBBMap.end())
1174 continue;
1175 if (I->end > II->first) // crossing a MBB.
1176 return false;
1177 MBBs.insert(II->second);
1178 if (MBBs.size() > 1)
1179 return false;
1180 }
1181 return true;
1182}
1183
Evan Chengd70dbb52008-02-22 09:24:50 +00001184/// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
1185/// interval on to-be re-materialized operands of MI) with new register.
1186void LiveIntervals::rewriteImplicitOps(const LiveInterval &li,
1187 MachineInstr *MI, unsigned NewVReg,
1188 VirtRegMap &vrm) {
1189 // There is an implicit use. That means one of the other operand is
1190 // being remat'ed and the remat'ed instruction has li.reg as an
1191 // use operand. Make sure we rewrite that as well.
1192 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1193 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001194 if (!MO.isReg())
Evan Chengd70dbb52008-02-22 09:24:50 +00001195 continue;
1196 unsigned Reg = MO.getReg();
1197 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
1198 continue;
1199 if (!vrm.isReMaterialized(Reg))
1200 continue;
1201 MachineInstr *ReMatMI = vrm.getReMaterializedMI(Reg);
Evan Cheng6130f662008-03-05 00:59:57 +00001202 MachineOperand *UseMO = ReMatMI->findRegisterUseOperand(li.reg);
1203 if (UseMO)
1204 UseMO->setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001205 }
1206}
1207
Evan Chengf2fbca62007-11-12 06:35:08 +00001208/// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
1209/// for addIntervalsForSpills to rewrite uses / defs for the given live range.
Evan Cheng018f9b02007-12-05 03:22:34 +00001210bool LiveIntervals::
Evan Chengd70dbb52008-02-22 09:24:50 +00001211rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
1212 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
Evan Cheng81a03822007-11-17 00:40:40 +00001213 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001214 unsigned Slot, int LdSlot,
1215 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001216 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001217 const TargetRegisterClass* rc,
1218 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001219 const MachineLoopInfo *loopInfo,
Evan Cheng313d4b82008-02-23 00:33:04 +00001220 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
Owen Anderson28998312008-08-13 22:28:50 +00001221 DenseMap<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001222 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
1223 MachineBasicBlock *MBB = MI->getParent();
1224 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng018f9b02007-12-05 03:22:34 +00001225 bool CanFold = false;
Evan Chengf2fbca62007-11-12 06:35:08 +00001226 RestartInstruction:
1227 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1228 MachineOperand& mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001229 if (!mop.isReg())
Evan Chengf2fbca62007-11-12 06:35:08 +00001230 continue;
1231 unsigned Reg = mop.getReg();
1232 unsigned RegI = Reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001233 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
Evan Chengf2fbca62007-11-12 06:35:08 +00001234 continue;
Evan Chengf2fbca62007-11-12 06:35:08 +00001235 if (Reg != li.reg)
1236 continue;
1237
1238 bool TryFold = !DefIsReMat;
Evan Chengcb3c3302007-11-29 23:02:50 +00001239 bool FoldSS = true; // Default behavior unless it's a remat.
Evan Chengf2fbca62007-11-12 06:35:08 +00001240 int FoldSlot = Slot;
1241 if (DefIsReMat) {
1242 // If this is the rematerializable definition MI itself and
1243 // all of its uses are rematerialized, simply delete it.
Evan Cheng81a03822007-11-17 00:40:40 +00001244 if (MI == ReMatOrigDefMI && CanDelete) {
Evan Chengcddbb832007-11-30 21:23:43 +00001245 DOUT << "\t\t\t\tErasing re-materlizable def: ";
1246 DOUT << MI << '\n';
Evan Chengf2fbca62007-11-12 06:35:08 +00001247 RemoveMachineInstrFromMaps(MI);
Evan Chengcada2452007-11-28 01:28:46 +00001248 vrm.RemoveMachineInstrFromMaps(MI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001249 MI->eraseFromParent();
1250 break;
1251 }
1252
1253 // If def for this use can't be rematerialized, then try folding.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001254 // If def is rematerializable and it's a load, also try folding.
Evan Chengcb3c3302007-11-29 23:02:50 +00001255 TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad));
Evan Chengf2fbca62007-11-12 06:35:08 +00001256 if (isLoad) {
1257 // Try fold loads (from stack slot, constant pool, etc.) into uses.
1258 FoldSS = isLoadSS;
1259 FoldSlot = LdSlot;
1260 }
1261 }
1262
Evan Chengf2fbca62007-11-12 06:35:08 +00001263 // Scan all of the operands of this instruction rewriting operands
1264 // to use NewVReg instead of li.reg as appropriate. We do this for
1265 // two reasons:
1266 //
1267 // 1. If the instr reads the same spilled vreg multiple times, we
1268 // want to reuse the NewVReg.
1269 // 2. If the instr is a two-addr instruction, we are required to
1270 // keep the src/dst regs pinned.
1271 //
1272 // Keep track of whether we replace a use and/or def so that we can
1273 // create the spill interval with the appropriate range.
Evan Chengcddbb832007-11-30 21:23:43 +00001274
Evan Cheng81a03822007-11-17 00:40:40 +00001275 HasUse = mop.isUse();
1276 HasDef = mop.isDef();
Evan Chengaee4af62007-12-02 08:30:39 +00001277 SmallVector<unsigned, 2> Ops;
1278 Ops.push_back(i);
Evan Chengf2fbca62007-11-12 06:35:08 +00001279 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
Evan Chengaee4af62007-12-02 08:30:39 +00001280 const MachineOperand &MOj = MI->getOperand(j);
Dan Gohmand735b802008-10-03 15:45:36 +00001281 if (!MOj.isReg())
Evan Chengf2fbca62007-11-12 06:35:08 +00001282 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001283 unsigned RegJ = MOj.getReg();
Dan Gohman6f0d0242008-02-10 18:45:23 +00001284 if (RegJ == 0 || TargetRegisterInfo::isPhysicalRegister(RegJ))
Evan Chengf2fbca62007-11-12 06:35:08 +00001285 continue;
1286 if (RegJ == RegI) {
Evan Chengaee4af62007-12-02 08:30:39 +00001287 Ops.push_back(j);
1288 HasUse |= MOj.isUse();
1289 HasDef |= MOj.isDef();
Evan Chengf2fbca62007-11-12 06:35:08 +00001290 }
1291 }
1292
Evan Cheng79a796c2008-07-12 01:56:02 +00001293 if (HasUse && !li.liveAt(getUseIndex(index)))
1294 // Must be defined by an implicit def. It should not be spilled. Note,
1295 // this is for correctness reason. e.g.
1296 // 8 %reg1024<def> = IMPLICIT_DEF
1297 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1298 // The live range [12, 14) are not part of the r1024 live interval since
1299 // it's defined by an implicit def. It will not conflicts with live
1300 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001301 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001302 // the INSERT_SUBREG and both target registers that would overlap.
1303 HasUse = false;
1304
Evan Cheng9c3c2212008-06-06 07:54:39 +00001305 // Update stack slot spill weight if we are splitting.
Evan Chengc3417602008-06-21 06:45:54 +00001306 float Weight = getSpillWeight(HasDef, HasUse, loopDepth);
Evan Cheng5b69eba2009-04-21 22:46:52 +00001307 if (!TrySplit)
Evan Cheng9c3c2212008-06-06 07:54:39 +00001308 SSWeight += Weight;
1309
David Greene26b86a02008-10-27 17:38:59 +00001310 // Create a new virtual register for the spill interval.
1311 // Create the new register now so we can map the fold instruction
1312 // to the new register so when it is unfolded we get the correct
1313 // answer.
1314 bool CreatedNewVReg = false;
1315 if (NewVReg == 0) {
1316 NewVReg = mri_->createVirtualRegister(rc);
1317 vrm.grow();
1318 CreatedNewVReg = true;
1319 }
1320
Evan Cheng9c3c2212008-06-06 07:54:39 +00001321 if (!TryFold)
1322 CanFold = false;
1323 else {
Evan Cheng018f9b02007-12-05 03:22:34 +00001324 // Do not fold load / store here if we are splitting. We'll find an
1325 // optimal point to insert a load / store later.
1326 if (!TrySplit) {
1327 if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
David Greene26b86a02008-10-27 17:38:59 +00001328 Ops, FoldSS, FoldSlot, NewVReg)) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001329 // Folding the load/store can completely change the instruction in
1330 // unpredictable ways, rescan it from the beginning.
David Greene26b86a02008-10-27 17:38:59 +00001331
1332 if (FoldSS) {
1333 // We need to give the new vreg the same stack slot as the
1334 // spilled interval.
1335 vrm.assignVirt2StackSlot(NewVReg, FoldSlot);
1336 }
1337
Evan Cheng018f9b02007-12-05 03:22:34 +00001338 HasUse = false;
1339 HasDef = false;
1340 CanFold = false;
Evan Cheng5b69eba2009-04-21 22:46:52 +00001341 if (isNotInMIMap(MI)) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001342 SSWeight -= Weight;
Evan Cheng7e073ba2008-04-09 20:57:25 +00001343 break;
Evan Cheng9c3c2212008-06-06 07:54:39 +00001344 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001345 goto RestartInstruction;
1346 }
1347 } else {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001348 // We'll try to fold it later if it's profitable.
Evan Cheng3c75ba82008-04-01 21:37:32 +00001349 CanFold = canFoldMemoryOperand(MI, Ops, DefIsReMat);
Evan Cheng018f9b02007-12-05 03:22:34 +00001350 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001351 }
Evan Chengcddbb832007-11-30 21:23:43 +00001352
Evan Chengcddbb832007-11-30 21:23:43 +00001353 mop.setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001354 if (mop.isImplicit())
1355 rewriteImplicitOps(li, MI, NewVReg, vrm);
Evan Chengcddbb832007-11-30 21:23:43 +00001356
1357 // Reuse NewVReg for other reads.
Evan Chengd70dbb52008-02-22 09:24:50 +00001358 for (unsigned j = 0, e = Ops.size(); j != e; ++j) {
1359 MachineOperand &mopj = MI->getOperand(Ops[j]);
1360 mopj.setReg(NewVReg);
1361 if (mopj.isImplicit())
1362 rewriteImplicitOps(li, MI, NewVReg, vrm);
1363 }
Evan Chengcddbb832007-11-30 21:23:43 +00001364
Evan Cheng81a03822007-11-17 00:40:40 +00001365 if (CreatedNewVReg) {
1366 if (DefIsReMat) {
1367 vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI/*, CanDelete*/);
Evan Chengd70dbb52008-02-22 09:24:50 +00001368 if (ReMatIds[VNI->id] == VirtRegMap::MAX_STACK_SLOT) {
Evan Cheng81a03822007-11-17 00:40:40 +00001369 // Each valnum may have its own remat id.
Evan Chengd70dbb52008-02-22 09:24:50 +00001370 ReMatIds[VNI->id] = vrm.assignVirtReMatId(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001371 } else {
Evan Chengd70dbb52008-02-22 09:24:50 +00001372 vrm.assignVirtReMatId(NewVReg, ReMatIds[VNI->id]);
Evan Cheng81a03822007-11-17 00:40:40 +00001373 }
1374 if (!CanDelete || (HasUse && HasDef)) {
1375 // If this is a two-addr instruction then its use operands are
1376 // rematerializable but its def is not. It should be assigned a
1377 // stack slot.
1378 vrm.assignVirt2StackSlot(NewVReg, Slot);
1379 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001380 } else {
Evan Chengf2fbca62007-11-12 06:35:08 +00001381 vrm.assignVirt2StackSlot(NewVReg, Slot);
1382 }
Evan Chengcb3c3302007-11-29 23:02:50 +00001383 } else if (HasUse && HasDef &&
1384 vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) {
1385 // If this interval hasn't been assigned a stack slot (because earlier
1386 // def is a deleted remat def), do it now.
1387 assert(Slot != VirtRegMap::NO_STACK_SLOT);
1388 vrm.assignVirt2StackSlot(NewVReg, Slot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001389 }
1390
Evan Cheng313d4b82008-02-23 00:33:04 +00001391 // Re-matting an instruction with virtual register use. Add the
1392 // register as an implicit use on the use MI.
1393 if (DefIsReMat && ImpUse)
1394 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1395
Evan Cheng5b69eba2009-04-21 22:46:52 +00001396 // Create a new register interval for this spill / remat.
Evan Chengf2fbca62007-11-12 06:35:08 +00001397 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001398 if (CreatedNewVReg) {
1399 NewLIs.push_back(&nI);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001400 MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg));
Evan Cheng81a03822007-11-17 00:40:40 +00001401 if (TrySplit)
1402 vrm.setIsSplitFromReg(NewVReg, li.reg);
1403 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001404
1405 if (HasUse) {
Evan Cheng81a03822007-11-17 00:40:40 +00001406 if (CreatedNewVReg) {
1407 LiveRange LR(getLoadIndex(index), getUseIndex(index)+1,
1408 nI.getNextValue(~0U, 0, VNInfoAllocator));
1409 DOUT << " +" << LR;
1410 nI.addRange(LR);
1411 } else {
1412 // Extend the split live interval to this def / use.
1413 unsigned End = getUseIndex(index)+1;
1414 LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
1415 nI.getValNumInfo(nI.getNumValNums()-1));
1416 DOUT << " +" << LR;
1417 nI.addRange(LR);
1418 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001419 }
1420 if (HasDef) {
1421 LiveRange LR(getDefIndex(index), getStoreIndex(index),
1422 nI.getNextValue(~0U, 0, VNInfoAllocator));
1423 DOUT << " +" << LR;
1424 nI.addRange(LR);
1425 }
Evan Cheng81a03822007-11-17 00:40:40 +00001426
Evan Chengf2fbca62007-11-12 06:35:08 +00001427 DOUT << "\t\t\t\tAdded new interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001428 nI.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001429 DOUT << '\n';
1430 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001431 return CanFold;
Evan Chengf2fbca62007-11-12 06:35:08 +00001432}
Evan Cheng81a03822007-11-17 00:40:40 +00001433bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001434 const VNInfo *VNI,
1435 MachineBasicBlock *MBB, unsigned Idx) const {
Evan Cheng81a03822007-11-17 00:40:40 +00001436 unsigned End = getMBBEndIdx(MBB);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001437 for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
1438 unsigned KillIdx = VNI->kills[j];
1439 if (KillIdx > Idx && KillIdx < End)
1440 return true;
Evan Cheng81a03822007-11-17 00:40:40 +00001441 }
1442 return false;
1443}
1444
Evan Cheng063284c2008-02-21 00:34:19 +00001445/// RewriteInfo - Keep track of machine instrs that will be rewritten
1446/// during spilling.
Dan Gohman844731a2008-05-13 00:00:25 +00001447namespace {
1448 struct RewriteInfo {
1449 unsigned Index;
1450 MachineInstr *MI;
1451 bool HasUse;
1452 bool HasDef;
1453 RewriteInfo(unsigned i, MachineInstr *mi, bool u, bool d)
1454 : Index(i), MI(mi), HasUse(u), HasDef(d) {}
1455 };
Evan Cheng063284c2008-02-21 00:34:19 +00001456
Dan Gohman844731a2008-05-13 00:00:25 +00001457 struct RewriteInfoCompare {
1458 bool operator()(const RewriteInfo &LHS, const RewriteInfo &RHS) const {
1459 return LHS.Index < RHS.Index;
1460 }
1461 };
1462}
Evan Cheng063284c2008-02-21 00:34:19 +00001463
Evan Chengf2fbca62007-11-12 06:35:08 +00001464void LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001465rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
Evan Chengf2fbca62007-11-12 06:35:08 +00001466 LiveInterval::Ranges::const_iterator &I,
Evan Cheng81a03822007-11-17 00:40:40 +00001467 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001468 unsigned Slot, int LdSlot,
1469 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001470 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001471 const TargetRegisterClass* rc,
1472 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001473 const MachineLoopInfo *loopInfo,
Evan Cheng81a03822007-11-17 00:40:40 +00001474 BitVector &SpillMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001475 DenseMap<unsigned, std::vector<SRInfo> > &SpillIdxes,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001476 BitVector &RestoreMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001477 DenseMap<unsigned, std::vector<SRInfo> > &RestoreIdxes,
1478 DenseMap<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001479 std::vector<LiveInterval*> &NewLIs, float &SSWeight) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001480 bool AllCanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001481 unsigned NewVReg = 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001482 unsigned start = getBaseIndex(I->start);
Evan Chengf2fbca62007-11-12 06:35:08 +00001483 unsigned end = getBaseIndex(I->end-1) + InstrSlots::NUM;
Evan Chengf2fbca62007-11-12 06:35:08 +00001484
Evan Cheng063284c2008-02-21 00:34:19 +00001485 // First collect all the def / use in this live range that will be rewritten.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001486 // Make sure they are sorted according to instruction index.
Evan Cheng063284c2008-02-21 00:34:19 +00001487 std::vector<RewriteInfo> RewriteMIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001488 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1489 re = mri_->reg_end(); ri != re; ) {
Evan Cheng419852c2008-04-03 16:39:43 +00001490 MachineInstr *MI = &*ri;
Evan Cheng063284c2008-02-21 00:34:19 +00001491 MachineOperand &O = ri.getOperand();
1492 ++ri;
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001493 assert(!O.isImplicit() && "Spilling register that's used as implicit use?");
Evan Cheng063284c2008-02-21 00:34:19 +00001494 unsigned index = getInstructionIndex(MI);
1495 if (index < start || index >= end)
1496 continue;
Evan Cheng79a796c2008-07-12 01:56:02 +00001497 if (O.isUse() && !li.liveAt(getUseIndex(index)))
1498 // Must be defined by an implicit def. It should not be spilled. Note,
1499 // this is for correctness reason. e.g.
1500 // 8 %reg1024<def> = IMPLICIT_DEF
1501 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1502 // The live range [12, 14) are not part of the r1024 live interval since
1503 // it's defined by an implicit def. It will not conflicts with live
1504 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001505 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001506 // the INSERT_SUBREG and both target registers that would overlap.
1507 continue;
Evan Cheng063284c2008-02-21 00:34:19 +00001508 RewriteMIs.push_back(RewriteInfo(index, MI, O.isUse(), O.isDef()));
1509 }
1510 std::sort(RewriteMIs.begin(), RewriteMIs.end(), RewriteInfoCompare());
1511
Evan Cheng313d4b82008-02-23 00:33:04 +00001512 unsigned ImpUse = DefIsReMat ? getReMatImplicitUse(li, ReMatDefMI) : 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001513 // Now rewrite the defs and uses.
1514 for (unsigned i = 0, e = RewriteMIs.size(); i != e; ) {
1515 RewriteInfo &rwi = RewriteMIs[i];
1516 ++i;
1517 unsigned index = rwi.Index;
1518 bool MIHasUse = rwi.HasUse;
1519 bool MIHasDef = rwi.HasDef;
1520 MachineInstr *MI = rwi.MI;
1521 // If MI def and/or use the same register multiple times, then there
1522 // are multiple entries.
Evan Cheng313d4b82008-02-23 00:33:04 +00001523 unsigned NumUses = MIHasUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001524 while (i != e && RewriteMIs[i].MI == MI) {
1525 assert(RewriteMIs[i].Index == index);
Evan Cheng313d4b82008-02-23 00:33:04 +00001526 bool isUse = RewriteMIs[i].HasUse;
1527 if (isUse) ++NumUses;
1528 MIHasUse |= isUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001529 MIHasDef |= RewriteMIs[i].HasDef;
1530 ++i;
1531 }
Evan Cheng81a03822007-11-17 00:40:40 +00001532 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng313d4b82008-02-23 00:33:04 +00001533
Evan Cheng0a891ed2008-05-23 23:00:04 +00001534 if (ImpUse && MI != ReMatDefMI) {
Evan Cheng313d4b82008-02-23 00:33:04 +00001535 // Re-matting an instruction with virtual register use. Update the
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001536 // register interval's spill weight to HUGE_VALF to prevent it from
1537 // being spilled.
Evan Cheng313d4b82008-02-23 00:33:04 +00001538 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001539 ImpLi.weight = HUGE_VALF;
Evan Cheng313d4b82008-02-23 00:33:04 +00001540 }
1541
Evan Cheng063284c2008-02-21 00:34:19 +00001542 unsigned MBBId = MBB->getNumber();
Evan Cheng018f9b02007-12-05 03:22:34 +00001543 unsigned ThisVReg = 0;
Evan Cheng70306f82007-12-03 09:58:48 +00001544 if (TrySplit) {
Owen Anderson28998312008-08-13 22:28:50 +00001545 DenseMap<unsigned,unsigned>::iterator NVI = MBBVRegsMap.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001546 if (NVI != MBBVRegsMap.end()) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001547 ThisVReg = NVI->second;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001548 // One common case:
1549 // x = use
1550 // ...
1551 // ...
1552 // def = ...
1553 // = use
1554 // It's better to start a new interval to avoid artifically
1555 // extend the new interval.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001556 if (MIHasDef && !MIHasUse) {
1557 MBBVRegsMap.erase(MBB->getNumber());
Evan Cheng018f9b02007-12-05 03:22:34 +00001558 ThisVReg = 0;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001559 }
1560 }
Evan Chengcada2452007-11-28 01:28:46 +00001561 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001562
1563 bool IsNew = ThisVReg == 0;
1564 if (IsNew) {
1565 // This ends the previous live interval. If all of its def / use
1566 // can be folded, give it a low spill weight.
1567 if (NewVReg && TrySplit && AllCanFold) {
1568 LiveInterval &nI = getOrCreateInterval(NewVReg);
1569 nI.weight /= 10.0F;
1570 }
1571 AllCanFold = true;
1572 }
1573 NewVReg = ThisVReg;
1574
Evan Cheng81a03822007-11-17 00:40:40 +00001575 bool HasDef = false;
1576 bool HasUse = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001577 bool CanFold = rewriteInstructionForSpills(li, I->valno, TrySplit,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001578 index, end, MI, ReMatOrigDefMI, ReMatDefMI,
1579 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
1580 CanDelete, vrm, rc, ReMatIds, loopInfo, NewVReg,
1581 ImpUse, HasDef, HasUse, MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001582 if (!HasDef && !HasUse)
1583 continue;
1584
Evan Cheng018f9b02007-12-05 03:22:34 +00001585 AllCanFold &= CanFold;
1586
Evan Cheng81a03822007-11-17 00:40:40 +00001587 // Update weight of spill interval.
1588 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng70306f82007-12-03 09:58:48 +00001589 if (!TrySplit) {
Evan Cheng81a03822007-11-17 00:40:40 +00001590 // The spill weight is now infinity as it cannot be spilled again.
1591 nI.weight = HUGE_VALF;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001592 continue;
Evan Cheng81a03822007-11-17 00:40:40 +00001593 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001594
1595 // Keep track of the last def and first use in each MBB.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001596 if (HasDef) {
1597 if (MI != ReMatOrigDefMI || !CanDelete) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001598 bool HasKill = false;
1599 if (!HasUse)
1600 HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, getDefIndex(index));
1601 else {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001602 // If this is a two-address code, then this index starts a new VNInfo.
Evan Cheng3f32d652008-06-04 09:18:41 +00001603 const VNInfo *VNI = li.findDefinedVNInfo(getDefIndex(index));
Evan Cheng0cbb1162007-11-29 01:06:25 +00001604 if (VNI)
1605 HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, getDefIndex(index));
1606 }
Owen Anderson28998312008-08-13 22:28:50 +00001607 DenseMap<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Chenge3110d02007-12-01 04:42:39 +00001608 SpillIdxes.find(MBBId);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001609 if (!HasKill) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001610 if (SII == SpillIdxes.end()) {
1611 std::vector<SRInfo> S;
1612 S.push_back(SRInfo(index, NewVReg, true));
1613 SpillIdxes.insert(std::make_pair(MBBId, S));
1614 } else if (SII->second.back().vreg != NewVReg) {
1615 SII->second.push_back(SRInfo(index, NewVReg, true));
1616 } else if ((int)index > SII->second.back().index) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001617 // If there is an earlier def and this is a two-address
1618 // instruction, then it's not possible to fold the store (which
1619 // would also fold the load).
Evan Cheng1953d0c2007-11-29 10:12:14 +00001620 SRInfo &Info = SII->second.back();
1621 Info.index = index;
1622 Info.canFold = !HasUse;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001623 }
1624 SpillMBBs.set(MBBId);
Evan Chenge3110d02007-12-01 04:42:39 +00001625 } else if (SII != SpillIdxes.end() &&
1626 SII->second.back().vreg == NewVReg &&
1627 (int)index > SII->second.back().index) {
1628 // There is an earlier def that's not killed (must be two-address).
1629 // The spill is no longer needed.
1630 SII->second.pop_back();
1631 if (SII->second.empty()) {
1632 SpillIdxes.erase(MBBId);
1633 SpillMBBs.reset(MBBId);
1634 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001635 }
1636 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001637 }
1638
1639 if (HasUse) {
Owen Anderson28998312008-08-13 22:28:50 +00001640 DenseMap<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001641 SpillIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001642 if (SII != SpillIdxes.end() &&
1643 SII->second.back().vreg == NewVReg &&
1644 (int)index > SII->second.back().index)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001645 // Use(s) following the last def, it's not safe to fold the spill.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001646 SII->second.back().canFold = false;
Owen Anderson28998312008-08-13 22:28:50 +00001647 DenseMap<unsigned, std::vector<SRInfo> >::iterator RII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001648 RestoreIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001649 if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001650 // If we are splitting live intervals, only fold if it's the first
1651 // use and there isn't another use later in the MBB.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001652 RII->second.back().canFold = false;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001653 else if (IsNew) {
1654 // Only need a reload if there isn't an earlier def / use.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001655 if (RII == RestoreIdxes.end()) {
1656 std::vector<SRInfo> Infos;
1657 Infos.push_back(SRInfo(index, NewVReg, true));
1658 RestoreIdxes.insert(std::make_pair(MBBId, Infos));
1659 } else {
1660 RII->second.push_back(SRInfo(index, NewVReg, true));
1661 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001662 RestoreMBBs.set(MBBId);
1663 }
1664 }
1665
1666 // Update spill weight.
Evan Cheng22f07ff2007-12-11 02:09:15 +00001667 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Chengc3417602008-06-21 06:45:54 +00001668 nI.weight += getSpillWeight(HasDef, HasUse, loopDepth);
Evan Chengf2fbca62007-11-12 06:35:08 +00001669 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001670
1671 if (NewVReg && TrySplit && AllCanFold) {
1672 // If all of its def / use can be folded, give it a low spill weight.
1673 LiveInterval &nI = getOrCreateInterval(NewVReg);
1674 nI.weight /= 10.0F;
1675 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001676}
1677
Evan Cheng1953d0c2007-11-29 10:12:14 +00001678bool LiveIntervals::alsoFoldARestore(int Id, int index, unsigned vr,
1679 BitVector &RestoreMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001680 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001681 if (!RestoreMBBs[Id])
1682 return false;
1683 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1684 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1685 if (Restores[i].index == index &&
1686 Restores[i].vreg == vr &&
1687 Restores[i].canFold)
1688 return true;
1689 return false;
1690}
1691
1692void LiveIntervals::eraseRestoreInfo(int Id, int index, unsigned vr,
1693 BitVector &RestoreMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001694 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001695 if (!RestoreMBBs[Id])
1696 return;
1697 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1698 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1699 if (Restores[i].index == index && Restores[i].vreg)
1700 Restores[i].index = -1;
1701}
Evan Cheng81a03822007-11-17 00:40:40 +00001702
Evan Cheng4cce6b42008-04-11 17:53:36 +00001703/// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
1704/// spilled and create empty intervals for their uses.
1705void
1706LiveIntervals::handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
1707 const TargetRegisterClass* rc,
1708 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng419852c2008-04-03 16:39:43 +00001709 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1710 re = mri_->reg_end(); ri != re; ) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001711 MachineOperand &O = ri.getOperand();
Evan Cheng419852c2008-04-03 16:39:43 +00001712 MachineInstr *MI = &*ri;
1713 ++ri;
Evan Cheng4cce6b42008-04-11 17:53:36 +00001714 if (O.isDef()) {
1715 assert(MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF &&
1716 "Register def was not rewritten?");
1717 RemoveMachineInstrFromMaps(MI);
1718 vrm.RemoveMachineInstrFromMaps(MI);
1719 MI->eraseFromParent();
1720 } else {
1721 // This must be an use of an implicit_def so it's not part of the live
1722 // interval. Create a new empty live interval for it.
1723 // FIXME: Can we simply erase some of the instructions? e.g. Stores?
1724 unsigned NewVReg = mri_->createVirtualRegister(rc);
1725 vrm.grow();
1726 vrm.setIsImplicitlyDefined(NewVReg);
1727 NewLIs.push_back(&getOrCreateInterval(NewVReg));
1728 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1729 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001730 if (MO.isReg() && MO.getReg() == li.reg)
Evan Cheng4cce6b42008-04-11 17:53:36 +00001731 MO.setReg(NewVReg);
1732 }
1733 }
Evan Cheng419852c2008-04-03 16:39:43 +00001734 }
1735}
1736
Evan Chengf2fbca62007-11-12 06:35:08 +00001737std::vector<LiveInterval*> LiveIntervals::
Owen Andersond6664312008-08-18 18:05:32 +00001738addIntervalsForSpillsFast(const LiveInterval &li,
1739 const MachineLoopInfo *loopInfo,
1740 VirtRegMap &vrm, float& SSWeight) {
Owen Anderson17197312008-08-18 23:41:04 +00001741 unsigned slot = vrm.assignVirt2StackSlot(li.reg);
Owen Andersond6664312008-08-18 18:05:32 +00001742
1743 std::vector<LiveInterval*> added;
1744
1745 assert(li.weight != HUGE_VALF &&
1746 "attempt to spill already spilled interval!");
1747
1748 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
1749 DEBUG(li.dump());
1750 DOUT << '\n';
1751
1752 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
1753
Owen Anderson9a032932008-08-18 21:20:32 +00001754 SSWeight = 0.0f;
1755
Owen Andersona41e47a2008-08-19 22:12:11 +00001756 MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg);
1757 while (RI != mri_->reg_end()) {
1758 MachineInstr* MI = &*RI;
1759
1760 SmallVector<unsigned, 2> Indices;
1761 bool HasUse = false;
1762 bool HasDef = false;
1763
1764 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1765 MachineOperand& mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001766 if (!mop.isReg() || mop.getReg() != li.reg) continue;
Owen Andersona41e47a2008-08-19 22:12:11 +00001767
1768 HasUse |= MI->getOperand(i).isUse();
1769 HasDef |= MI->getOperand(i).isDef();
1770
1771 Indices.push_back(i);
1772 }
1773
1774 if (!tryFoldMemoryOperand(MI, vrm, NULL, getInstructionIndex(MI),
1775 Indices, true, slot, li.reg)) {
1776 unsigned NewVReg = mri_->createVirtualRegister(rc);
Owen Anderson9a032932008-08-18 21:20:32 +00001777 vrm.grow();
Owen Anderson17197312008-08-18 23:41:04 +00001778 vrm.assignVirt2StackSlot(NewVReg, slot);
1779
Owen Andersona41e47a2008-08-19 22:12:11 +00001780 // create a new register for this spill
1781 LiveInterval &nI = getOrCreateInterval(NewVReg);
Owen Andersond6664312008-08-18 18:05:32 +00001782
Owen Andersona41e47a2008-08-19 22:12:11 +00001783 // the spill weight is now infinity as it
1784 // cannot be spilled again
1785 nI.weight = HUGE_VALF;
1786
1787 // Rewrite register operands to use the new vreg.
1788 for (SmallVectorImpl<unsigned>::iterator I = Indices.begin(),
1789 E = Indices.end(); I != E; ++I) {
1790 MI->getOperand(*I).setReg(NewVReg);
1791
1792 if (MI->getOperand(*I).isUse())
1793 MI->getOperand(*I).setIsKill(true);
1794 }
1795
1796 // Fill in the new live interval.
1797 unsigned index = getInstructionIndex(MI);
1798 if (HasUse) {
1799 LiveRange LR(getLoadIndex(index), getUseIndex(index),
1800 nI.getNextValue(~0U, 0, getVNInfoAllocator()));
1801 DOUT << " +" << LR;
1802 nI.addRange(LR);
1803 vrm.addRestorePoint(NewVReg, MI);
1804 }
1805 if (HasDef) {
1806 LiveRange LR(getDefIndex(index), getStoreIndex(index),
1807 nI.getNextValue(~0U, 0, getVNInfoAllocator()));
1808 DOUT << " +" << LR;
1809 nI.addRange(LR);
1810 vrm.addSpillPoint(NewVReg, true, MI);
1811 }
1812
Owen Anderson17197312008-08-18 23:41:04 +00001813 added.push_back(&nI);
Owen Anderson8dc2cbe2008-08-18 18:38:12 +00001814
Owen Andersona41e47a2008-08-19 22:12:11 +00001815 DOUT << "\t\t\t\tadded new interval: ";
1816 DEBUG(nI.dump());
1817 DOUT << '\n';
1818
1819 unsigned loopDepth = loopInfo->getLoopDepth(MI->getParent());
1820 if (HasUse) {
1821 if (HasDef)
1822 SSWeight += getSpillWeight(true, true, loopDepth);
1823 else
1824 SSWeight += getSpillWeight(false, true, loopDepth);
1825 } else
1826 SSWeight += getSpillWeight(true, false, loopDepth);
1827 }
Owen Anderson9a032932008-08-18 21:20:32 +00001828
Owen Anderson9a032932008-08-18 21:20:32 +00001829
Owen Andersona41e47a2008-08-19 22:12:11 +00001830 RI = mri_->reg_begin(li.reg);
Owen Andersond6664312008-08-18 18:05:32 +00001831 }
Owen Andersond6664312008-08-18 18:05:32 +00001832
1833 return added;
1834}
1835
1836std::vector<LiveInterval*> LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001837addIntervalsForSpills(const LiveInterval &li,
Evan Chengdc377862008-09-30 15:44:16 +00001838 SmallVectorImpl<LiveInterval*> &SpillIs,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001839 const MachineLoopInfo *loopInfo, VirtRegMap &vrm,
1840 float &SSWeight) {
Owen Andersonae339ba2008-08-19 00:17:30 +00001841
1842 if (EnableFastSpilling)
1843 return addIntervalsForSpillsFast(li, loopInfo, vrm, SSWeight);
1844
Evan Chengf2fbca62007-11-12 06:35:08 +00001845 assert(li.weight != HUGE_VALF &&
1846 "attempt to spill already spilled interval!");
1847
1848 DOUT << "\t\t\t\tadding intervals for spills for interval: ";
Dan Gohman6f0d0242008-02-10 18:45:23 +00001849 li.print(DOUT, tri_);
Evan Chengf2fbca62007-11-12 06:35:08 +00001850 DOUT << '\n';
1851
Evan Cheng9c3c2212008-06-06 07:54:39 +00001852 // Spill slot weight.
1853 SSWeight = 0.0f;
1854
Evan Cheng72eeb942008-12-05 17:00:16 +00001855 // Each bit specify whether a spill is required in the MBB.
Evan Cheng81a03822007-11-17 00:40:40 +00001856 BitVector SpillMBBs(mf_->getNumBlockIDs());
Owen Anderson28998312008-08-13 22:28:50 +00001857 DenseMap<unsigned, std::vector<SRInfo> > SpillIdxes;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001858 BitVector RestoreMBBs(mf_->getNumBlockIDs());
Owen Anderson28998312008-08-13 22:28:50 +00001859 DenseMap<unsigned, std::vector<SRInfo> > RestoreIdxes;
1860 DenseMap<unsigned,unsigned> MBBVRegsMap;
Evan Chengf2fbca62007-11-12 06:35:08 +00001861 std::vector<LiveInterval*> NewLIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001862 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
Evan Chengf2fbca62007-11-12 06:35:08 +00001863
1864 unsigned NumValNums = li.getNumValNums();
1865 SmallVector<MachineInstr*, 4> ReMatDefs;
1866 ReMatDefs.resize(NumValNums, NULL);
1867 SmallVector<MachineInstr*, 4> ReMatOrigDefs;
1868 ReMatOrigDefs.resize(NumValNums, NULL);
1869 SmallVector<int, 4> ReMatIds;
1870 ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
1871 BitVector ReMatDelete(NumValNums);
1872 unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
1873
Evan Cheng81a03822007-11-17 00:40:40 +00001874 // Spilling a split live interval. It cannot be split any further. Also,
1875 // it's also guaranteed to be a single val# / range interval.
1876 if (vrm.getPreSplitReg(li.reg)) {
1877 vrm.setIsSplitFromReg(li.reg, 0);
Evan Chengd120ffd2007-12-05 10:24:35 +00001878 // Unset the split kill marker on the last use.
1879 unsigned KillIdx = vrm.getKillPoint(li.reg);
1880 if (KillIdx) {
1881 MachineInstr *KillMI = getInstructionFromIndex(KillIdx);
1882 assert(KillMI && "Last use disappeared?");
1883 int KillOp = KillMI->findRegisterUseOperandIdx(li.reg, true);
1884 assert(KillOp != -1 && "Last use disappeared?");
Chris Lattnerf7382302007-12-30 21:56:09 +00001885 KillMI->getOperand(KillOp).setIsKill(false);
Evan Chengd120ffd2007-12-05 10:24:35 +00001886 }
Evan Chengadf85902007-12-05 09:51:10 +00001887 vrm.removeKillPoint(li.reg);
Evan Cheng81a03822007-11-17 00:40:40 +00001888 bool DefIsReMat = vrm.isReMaterialized(li.reg);
1889 Slot = vrm.getStackSlot(li.reg);
1890 assert(Slot != VirtRegMap::MAX_STACK_SLOT);
1891 MachineInstr *ReMatDefMI = DefIsReMat ?
1892 vrm.getReMaterializedMI(li.reg) : NULL;
1893 int LdSlot = 0;
1894 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1895 bool isLoad = isLoadSS ||
Dan Gohman15511cf2008-12-03 18:15:48 +00001896 (DefIsReMat && (ReMatDefMI->getDesc().canFoldAsLoad()));
Evan Cheng81a03822007-11-17 00:40:40 +00001897 bool IsFirstRange = true;
1898 for (LiveInterval::Ranges::const_iterator
1899 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1900 // If this is a split live interval with multiple ranges, it means there
1901 // are two-address instructions that re-defined the value. Only the
1902 // first def can be rematerialized!
1903 if (IsFirstRange) {
Evan Chengcb3c3302007-11-29 23:02:50 +00001904 // Note ReMatOrigDefMI has already been deleted.
Evan Cheng81a03822007-11-17 00:40:40 +00001905 rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
1906 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001907 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001908 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001909 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001910 } else {
1911 rewriteInstructionsForSpills(li, false, I, NULL, 0,
1912 Slot, 0, false, false, false,
Evan Chengd70dbb52008-02-22 09:24:50 +00001913 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001914 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001915 MBBVRegsMap, NewLIs, SSWeight);
Evan Cheng81a03822007-11-17 00:40:40 +00001916 }
1917 IsFirstRange = false;
1918 }
Evan Cheng419852c2008-04-03 16:39:43 +00001919
Evan Cheng9c3c2212008-06-06 07:54:39 +00001920 SSWeight = 0.0f; // Already accounted for when split.
Evan Cheng4cce6b42008-04-11 17:53:36 +00001921 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001922 return NewLIs;
1923 }
1924
1925 bool TrySplit = SplitAtBB && !intervalIsInOneMBB(li);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001926 if (SplitLimit != -1 && (int)numSplits >= SplitLimit)
1927 TrySplit = false;
1928 if (TrySplit)
1929 ++numSplits;
Evan Chengf2fbca62007-11-12 06:35:08 +00001930 bool NeedStackSlot = false;
1931 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1932 i != e; ++i) {
1933 const VNInfo *VNI = *i;
1934 unsigned VN = VNI->id;
1935 unsigned DefIdx = VNI->def;
1936 if (DefIdx == ~1U)
1937 continue; // Dead val#.
1938 // Is the def for the val# rematerializable?
Evan Cheng81a03822007-11-17 00:40:40 +00001939 MachineInstr *ReMatDefMI = (DefIdx == ~0u)
1940 ? 0 : getInstructionFromIndex(DefIdx);
Evan Cheng5ef3a042007-12-06 00:01:56 +00001941 bool dummy;
Evan Chengdc377862008-09-30 15:44:16 +00001942 if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, SpillIs, dummy)) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001943 // Remember how to remat the def of this val#.
Evan Cheng81a03822007-11-17 00:40:40 +00001944 ReMatOrigDefs[VN] = ReMatDefMI;
Dan Gohman2c3f7ae2008-07-17 23:49:46 +00001945 // Original def may be modified so we have to make a copy here.
Evan Cheng1ed99222008-07-19 00:37:25 +00001946 MachineInstr *Clone = mf_->CloneMachineInstr(ReMatDefMI);
1947 ClonedMIs.push_back(Clone);
1948 ReMatDefs[VN] = Clone;
Evan Chengf2fbca62007-11-12 06:35:08 +00001949
1950 bool CanDelete = true;
Evan Chengc3fc7d92007-11-29 09:49:23 +00001951 if (VNI->hasPHIKill) {
1952 // A kill is a phi node, not all of its uses can be rematerialized.
Evan Chengf2fbca62007-11-12 06:35:08 +00001953 // It must not be deleted.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001954 CanDelete = false;
1955 // Need a stack slot if there is any live range where uses cannot be
1956 // rematerialized.
1957 NeedStackSlot = true;
Evan Chengf2fbca62007-11-12 06:35:08 +00001958 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001959 if (CanDelete)
1960 ReMatDelete.set(VN);
1961 } else {
1962 // Need a stack slot if there is any live range where uses cannot be
1963 // rematerialized.
1964 NeedStackSlot = true;
1965 }
1966 }
1967
1968 // One stack slot per live interval.
Owen Andersonb98bbb72009-03-26 18:53:38 +00001969 if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0) {
1970 if (vrm.getStackSlot(li.reg) == VirtRegMap::NO_STACK_SLOT)
1971 Slot = vrm.assignVirt2StackSlot(li.reg);
1972
1973 // This case only occurs when the prealloc splitter has already assigned
1974 // a stack slot to this vreg.
1975 else
1976 Slot = vrm.getStackSlot(li.reg);
1977 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001978
1979 // Create new intervals and rewrite defs and uses.
1980 for (LiveInterval::Ranges::const_iterator
1981 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Evan Cheng81a03822007-11-17 00:40:40 +00001982 MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id];
1983 MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id];
1984 bool DefIsReMat = ReMatDefMI != NULL;
Evan Chengf2fbca62007-11-12 06:35:08 +00001985 bool CanDelete = ReMatDelete[I->valno->id];
1986 int LdSlot = 0;
Evan Cheng81a03822007-11-17 00:40:40 +00001987 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001988 bool isLoad = isLoadSS ||
Dan Gohman15511cf2008-12-03 18:15:48 +00001989 (DefIsReMat && ReMatDefMI->getDesc().canFoldAsLoad());
Evan Cheng81a03822007-11-17 00:40:40 +00001990 rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001991 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001992 CanDelete, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001993 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001994 MBBVRegsMap, NewLIs, SSWeight);
Evan Chengf2fbca62007-11-12 06:35:08 +00001995 }
1996
Evan Cheng0cbb1162007-11-29 01:06:25 +00001997 // Insert spills / restores if we are splitting.
Evan Cheng419852c2008-04-03 16:39:43 +00001998 if (!TrySplit) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001999 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng1953d0c2007-11-29 10:12:14 +00002000 return NewLIs;
Evan Cheng419852c2008-04-03 16:39:43 +00002001 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002002
Evan Chengb50bb8c2007-12-05 08:16:32 +00002003 SmallPtrSet<LiveInterval*, 4> AddedKill;
Evan Chengaee4af62007-12-02 08:30:39 +00002004 SmallVector<unsigned, 2> Ops;
Evan Cheng1953d0c2007-11-29 10:12:14 +00002005 if (NeedStackSlot) {
2006 int Id = SpillMBBs.find_first();
2007 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00002008 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
2009 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Cheng1953d0c2007-11-29 10:12:14 +00002010 std::vector<SRInfo> &spills = SpillIdxes[Id];
2011 for (unsigned i = 0, e = spills.size(); i != e; ++i) {
2012 int index = spills[i].index;
2013 unsigned VReg = spills[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00002014 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng0cbb1162007-11-29 01:06:25 +00002015 bool isReMat = vrm.isReMaterialized(VReg);
2016 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00002017 bool CanFold = false;
2018 bool FoundUse = false;
2019 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00002020 if (spills[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00002021 CanFold = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00002022 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
2023 MachineOperand &MO = MI->getOperand(j);
Dan Gohmand735b802008-10-03 15:45:36 +00002024 if (!MO.isReg() || MO.getReg() != VReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00002025 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00002026
2027 Ops.push_back(j);
2028 if (MO.isDef())
Evan Chengcddbb832007-11-30 21:23:43 +00002029 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00002030 if (isReMat ||
2031 (!FoundUse && !alsoFoldARestore(Id, index, VReg,
2032 RestoreMBBs, RestoreIdxes))) {
2033 // MI has two-address uses of the same register. If the use
2034 // isn't the first and only use in the BB, then we can't fold
2035 // it. FIXME: Move this to rewriteInstructionsForSpills.
2036 CanFold = false;
Evan Chengcddbb832007-11-30 21:23:43 +00002037 break;
2038 }
Evan Chengaee4af62007-12-02 08:30:39 +00002039 FoundUse = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00002040 }
2041 }
2042 // Fold the store into the def if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00002043 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00002044 if (CanFold && !Ops.empty()) {
2045 if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
Evan Chengcddbb832007-11-30 21:23:43 +00002046 Folded = true;
Sebastian Redl48fe6352009-03-19 23:26:52 +00002047 if (FoundUse) {
Evan Chengaee4af62007-12-02 08:30:39 +00002048 // Also folded uses, do not issue a load.
2049 eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
Evan Chengf38d14f2007-12-05 09:05:34 +00002050 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
2051 }
Evan Cheng597d10d2007-12-04 00:32:23 +00002052 nI.removeRange(getDefIndex(index), getStoreIndex(index));
Evan Chengcddbb832007-11-30 21:23:43 +00002053 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002054 }
2055
Evan Cheng7e073ba2008-04-09 20:57:25 +00002056 // Otherwise tell the spiller to issue a spill.
Evan Chengb50bb8c2007-12-05 08:16:32 +00002057 if (!Folded) {
2058 LiveRange *LR = &nI.ranges[nI.ranges.size()-1];
2059 bool isKill = LR->end == getStoreIndex(index);
Evan Chengb0a6f622008-05-20 08:10:37 +00002060 if (!MI->registerDefIsDead(nI.reg))
2061 // No need to spill a dead def.
2062 vrm.addSpillPoint(VReg, isKill, MI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002063 if (isKill)
2064 AddedKill.insert(&nI);
2065 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00002066
2067 // Update spill slot weight.
2068 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00002069 SSWeight += getSpillWeight(true, false, loopDepth);
Evan Cheng0cbb1162007-11-29 01:06:25 +00002070 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002071 Id = SpillMBBs.find_next(Id);
Evan Cheng0cbb1162007-11-29 01:06:25 +00002072 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002073 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002074
Evan Cheng1953d0c2007-11-29 10:12:14 +00002075 int Id = RestoreMBBs.find_first();
2076 while (Id != -1) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00002077 MachineBasicBlock *MBB = mf_->getBlockNumbered(Id);
2078 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
2079
Evan Cheng1953d0c2007-11-29 10:12:14 +00002080 std::vector<SRInfo> &restores = RestoreIdxes[Id];
2081 for (unsigned i = 0, e = restores.size(); i != e; ++i) {
2082 int index = restores[i].index;
2083 if (index == -1)
2084 continue;
2085 unsigned VReg = restores[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00002086 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng9c3c2212008-06-06 07:54:39 +00002087 bool isReMat = vrm.isReMaterialized(VReg);
Evan Cheng81a03822007-11-17 00:40:40 +00002088 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00002089 bool CanFold = false;
2090 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00002091 if (restores[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00002092 CanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00002093 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
2094 MachineOperand &MO = MI->getOperand(j);
Dan Gohmand735b802008-10-03 15:45:36 +00002095 if (!MO.isReg() || MO.getReg() != VReg)
Evan Cheng81a03822007-11-17 00:40:40 +00002096 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00002097
Evan Cheng0cbb1162007-11-29 01:06:25 +00002098 if (MO.isDef()) {
Evan Chengaee4af62007-12-02 08:30:39 +00002099 // If this restore were to be folded, it would have been folded
2100 // already.
2101 CanFold = false;
Evan Cheng81a03822007-11-17 00:40:40 +00002102 break;
2103 }
Evan Chengaee4af62007-12-02 08:30:39 +00002104 Ops.push_back(j);
Evan Cheng81a03822007-11-17 00:40:40 +00002105 }
2106 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002107
2108 // Fold the load into the use if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00002109 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00002110 if (CanFold && !Ops.empty()) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00002111 if (!isReMat)
Evan Chengaee4af62007-12-02 08:30:39 +00002112 Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg);
2113 else {
Evan Cheng0cbb1162007-11-29 01:06:25 +00002114 MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg);
2115 int LdSlot = 0;
2116 bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
2117 // If the rematerializable def is a load, also try to fold it.
Dan Gohman15511cf2008-12-03 18:15:48 +00002118 if (isLoadSS || ReMatDefMI->getDesc().canFoldAsLoad())
Evan Chengaee4af62007-12-02 08:30:39 +00002119 Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
2120 Ops, isLoadSS, LdSlot, VReg);
Evan Cheng650d7f32008-12-05 17:41:31 +00002121 if (!Folded) {
2122 unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI);
2123 if (ImpUse) {
2124 // Re-matting an instruction with virtual register use. Add the
2125 // register as an implicit use on the use MI and update the register
2126 // interval's spill weight to HUGE_VALF to prevent it from being
2127 // spilled.
2128 LiveInterval &ImpLi = getInterval(ImpUse);
2129 ImpLi.weight = HUGE_VALF;
2130 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
2131 }
Evan Chengd70dbb52008-02-22 09:24:50 +00002132 }
Evan Chengaee4af62007-12-02 08:30:39 +00002133 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002134 }
2135 // If folding is not possible / failed, then tell the spiller to issue a
2136 // load / rematerialization for us.
Evan Cheng597d10d2007-12-04 00:32:23 +00002137 if (Folded)
2138 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002139 else
Evan Cheng0cbb1162007-11-29 01:06:25 +00002140 vrm.addRestorePoint(VReg, MI);
Evan Cheng9c3c2212008-06-06 07:54:39 +00002141
2142 // Update spill slot weight.
2143 if (!isReMat)
Evan Chengc3417602008-06-21 06:45:54 +00002144 SSWeight += getSpillWeight(false, true, loopDepth);
Evan Cheng81a03822007-11-17 00:40:40 +00002145 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002146 Id = RestoreMBBs.find_next(Id);
Evan Cheng81a03822007-11-17 00:40:40 +00002147 }
2148
Evan Chengb50bb8c2007-12-05 08:16:32 +00002149 // Finalize intervals: add kills, finalize spill weights, and filter out
2150 // dead intervals.
Evan Cheng597d10d2007-12-04 00:32:23 +00002151 std::vector<LiveInterval*> RetNewLIs;
2152 for (unsigned i = 0, e = NewLIs.size(); i != e; ++i) {
2153 LiveInterval *LI = NewLIs[i];
2154 if (!LI->empty()) {
Owen Anderson496bac52008-07-23 19:47:27 +00002155 LI->weight /= InstrSlots::NUM * getApproximateInstructionCount(*LI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002156 if (!AddedKill.count(LI)) {
2157 LiveRange *LR = &LI->ranges[LI->ranges.size()-1];
Evan Chengd120ffd2007-12-05 10:24:35 +00002158 unsigned LastUseIdx = getBaseIndex(LR->end);
2159 MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx);
Evan Cheng6130f662008-03-05 00:59:57 +00002160 int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg, false);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002161 assert(UseIdx != -1);
Evan Chenga24752f2009-03-19 20:30:06 +00002162 if (!LastUse->isRegTiedToDefOperand(UseIdx)) {
Evan Chengb50bb8c2007-12-05 08:16:32 +00002163 LastUse->getOperand(UseIdx).setIsKill();
Evan Chengd120ffd2007-12-05 10:24:35 +00002164 vrm.addKillPoint(LI->reg, LastUseIdx);
Evan Chengadf85902007-12-05 09:51:10 +00002165 }
Evan Chengb50bb8c2007-12-05 08:16:32 +00002166 }
Evan Cheng597d10d2007-12-04 00:32:23 +00002167 RetNewLIs.push_back(LI);
2168 }
2169 }
Evan Cheng81a03822007-11-17 00:40:40 +00002170
Evan Cheng4cce6b42008-04-11 17:53:36 +00002171 handleSpilledImpDefs(li, vrm, rc, RetNewLIs);
Evan Cheng597d10d2007-12-04 00:32:23 +00002172 return RetNewLIs;
Evan Chengf2fbca62007-11-12 06:35:08 +00002173}
Evan Cheng676dd7c2008-03-11 07:19:34 +00002174
2175/// hasAllocatableSuperReg - Return true if the specified physical register has
2176/// any super register that's allocatable.
2177bool LiveIntervals::hasAllocatableSuperReg(unsigned Reg) const {
2178 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS)
2179 if (allocatableRegs_[*AS] && hasInterval(*AS))
2180 return true;
2181 return false;
2182}
2183
2184/// getRepresentativeReg - Find the largest super register of the specified
2185/// physical register.
2186unsigned LiveIntervals::getRepresentativeReg(unsigned Reg) const {
2187 // Find the largest super-register that is allocatable.
2188 unsigned BestReg = Reg;
2189 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS) {
2190 unsigned SuperReg = *AS;
2191 if (!hasAllocatableSuperReg(SuperReg) && hasInterval(SuperReg)) {
2192 BestReg = SuperReg;
2193 break;
2194 }
2195 }
2196 return BestReg;
2197}
2198
2199/// getNumConflictsWithPhysReg - Return the number of uses and defs of the
2200/// specified interval that conflicts with the specified physical register.
2201unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li,
2202 unsigned PhysReg) const {
2203 unsigned NumConflicts = 0;
2204 const LiveInterval &pli = getInterval(getRepresentativeReg(PhysReg));
2205 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
2206 E = mri_->reg_end(); I != E; ++I) {
2207 MachineOperand &O = I.getOperand();
2208 MachineInstr *MI = O.getParent();
2209 unsigned Index = getInstructionIndex(MI);
2210 if (pli.liveAt(Index))
2211 ++NumConflicts;
2212 }
2213 return NumConflicts;
2214}
2215
2216/// spillPhysRegAroundRegDefsUses - Spill the specified physical register
Evan Cheng2824a652009-03-23 18:24:37 +00002217/// around all defs and uses of the specified interval. Return true if it
2218/// was able to cut its interval.
2219bool LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
Evan Cheng676dd7c2008-03-11 07:19:34 +00002220 unsigned PhysReg, VirtRegMap &vrm) {
2221 unsigned SpillReg = getRepresentativeReg(PhysReg);
2222
2223 for (const unsigned *AS = tri_->getAliasSet(PhysReg); *AS; ++AS)
2224 // If there are registers which alias PhysReg, but which are not a
2225 // sub-register of the chosen representative super register. Assert
2226 // since we can't handle it yet.
Dan Gohman70f2f652009-04-13 15:22:29 +00002227 assert(*AS == SpillReg || !allocatableRegs_[*AS] || !hasInterval(*AS) ||
Evan Cheng676dd7c2008-03-11 07:19:34 +00002228 tri_->isSuperRegister(*AS, SpillReg));
2229
Evan Cheng2824a652009-03-23 18:24:37 +00002230 bool Cut = false;
Evan Cheng676dd7c2008-03-11 07:19:34 +00002231 LiveInterval &pli = getInterval(SpillReg);
2232 SmallPtrSet<MachineInstr*, 8> SeenMIs;
2233 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
2234 E = mri_->reg_end(); I != E; ++I) {
2235 MachineOperand &O = I.getOperand();
2236 MachineInstr *MI = O.getParent();
2237 if (SeenMIs.count(MI))
2238 continue;
2239 SeenMIs.insert(MI);
2240 unsigned Index = getInstructionIndex(MI);
2241 if (pli.liveAt(Index)) {
2242 vrm.addEmergencySpill(SpillReg, MI);
Evan Cheng5a3c6a82009-01-29 02:20:59 +00002243 unsigned StartIdx = getLoadIndex(Index);
2244 unsigned EndIdx = getStoreIndex(Index)+1;
Evan Cheng2824a652009-03-23 18:24:37 +00002245 if (pli.isInOneLiveRange(StartIdx, EndIdx)) {
Evan Cheng5a3c6a82009-01-29 02:20:59 +00002246 pli.removeRange(StartIdx, EndIdx);
Evan Cheng2824a652009-03-23 18:24:37 +00002247 Cut = true;
2248 } else {
Evan Cheng5a3c6a82009-01-29 02:20:59 +00002249 cerr << "Ran out of registers during register allocation!\n";
2250 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
2251 cerr << "Please check your inline asm statement for invalid "
2252 << "constraints:\n";
2253 MI->print(cerr.stream(), tm_);
2254 }
2255 exit(1);
2256 }
Evan Cheng676dd7c2008-03-11 07:19:34 +00002257 for (const unsigned* AS = tri_->getSubRegisters(SpillReg); *AS; ++AS) {
2258 if (!hasInterval(*AS))
2259 continue;
2260 LiveInterval &spli = getInterval(*AS);
2261 if (spli.liveAt(Index))
2262 spli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
2263 }
2264 }
2265 }
Evan Cheng2824a652009-03-23 18:24:37 +00002266 return Cut;
Evan Cheng676dd7c2008-03-11 07:19:34 +00002267}
Owen Andersonc4dc1322008-06-05 17:15:43 +00002268
2269LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
2270 MachineInstr* startInst) {
2271 LiveInterval& Interval = getOrCreateInterval(reg);
2272 VNInfo* VN = Interval.getNextValue(
2273 getInstructionIndex(startInst) + InstrSlots::DEF,
2274 startInst, getVNInfoAllocator());
2275 VN->hasPHIKill = true;
2276 VN->kills.push_back(getMBBEndIdx(startInst->getParent()));
2277 LiveRange LR(getInstructionIndex(startInst) + InstrSlots::DEF,
2278 getMBBEndIdx(startInst->getParent()) + 1, VN);
2279 Interval.addRange(LR);
2280
2281 return LR;
2282}