blob: edd9536e2c374e3925f90cd4c4c4d01dbb217fa3 [file] [log] [blame]
Chris Lattnera3b8b5c2004-07-23 17:56:30 +00001//===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the LiveInterval analysis pass which is used
11// by the Linear Scan Register allocator. This pass linearizes the
12// basic blocks of the function in DFS order and uses the
13// LiveVariables pass to conservatively compute live intervals for
14// each virtual and physical register.
15//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "liveintervals"
Chris Lattner3c3fe462005-09-21 04:19:09 +000019#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Misha Brukman08a6c762004-09-03 18:25:53 +000020#include "VirtRegMap.h"
Chris Lattner015959e2004-05-01 21:24:39 +000021#include "llvm/Value.h"
Dan Gohman6d69ba82008-07-25 00:02:30 +000022#include "llvm/Analysis/AliasAnalysis.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000023#include "llvm/CodeGen/LiveVariables.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000025#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng2578ba22009-07-01 01:59:31 +000026#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000027#include "llvm/CodeGen/MachineLoopInfo.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000028#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000029#include "llvm/CodeGen/Passes.h"
Dan Gohman6d69ba82008-07-25 00:02:30 +000030#include "llvm/CodeGen/PseudoSourceValue.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000031#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000032#include "llvm/Target/TargetInstrInfo.h"
33#include "llvm/Target/TargetMachine.h"
Owen Anderson95dad832008-10-07 20:22:28 +000034#include "llvm/Target/TargetOptions.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000035#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000037#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/raw_ostream.h"
Evan Cheng2578ba22009-07-01 01:59:31 +000039#include "llvm/ADT/DepthFirstIterator.h"
40#include "llvm/ADT/SmallSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000041#include "llvm/ADT/Statistic.h"
42#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000043#include <algorithm>
Lang Hamesf41538d2009-06-02 16:53:25 +000044#include <limits>
Jeff Cohen97af7512006-12-02 02:22:01 +000045#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000046using namespace llvm;
47
Dan Gohman844731a2008-05-13 00:00:25 +000048// Hidden options for help debugging.
49static cl::opt<bool> DisableReMat("disable-rematerialization",
50 cl::init(false), cl::Hidden);
Evan Cheng81a03822007-11-17 00:40:40 +000051
Dan Gohman844731a2008-05-13 00:00:25 +000052static cl::opt<bool> SplitAtBB("split-intervals-at-bb",
53 cl::init(true), cl::Hidden);
54static cl::opt<int> SplitLimit("split-limit",
55 cl::init(-1), cl::Hidden);
Evan Chengbc165e42007-08-16 07:24:22 +000056
Dan Gohman4c8f8702008-07-25 15:08:37 +000057static cl::opt<bool> EnableAggressiveRemat("aggressive-remat", cl::Hidden);
58
Owen Andersonae339ba2008-08-19 00:17:30 +000059static cl::opt<bool> EnableFastSpilling("fast-spill",
60 cl::init(false), cl::Hidden);
61
Chris Lattnercd3245a2006-12-19 22:41:21 +000062STATISTIC(numIntervals, "Number of original intervals");
Evan Cheng0cbb1162007-11-29 01:06:25 +000063STATISTIC(numFolds , "Number of loads/stores folded into instructions");
64STATISTIC(numSplits , "Number of intervals split");
Chris Lattnercd3245a2006-12-19 22:41:21 +000065
Devang Patel19974732007-05-03 01:11:54 +000066char LiveIntervals::ID = 0;
Dan Gohman844731a2008-05-13 00:00:25 +000067static RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000068
Chris Lattnerf7da2c72006-08-24 22:43:55 +000069void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000070 AU.setPreservesCFG();
Dan Gohman6d69ba82008-07-25 00:02:30 +000071 AU.addRequired<AliasAnalysis>();
72 AU.addPreserved<AliasAnalysis>();
David Greene25133302007-06-08 17:18:56 +000073 AU.addPreserved<LiveVariables>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000074 AU.addRequired<LiveVariables>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000075 AU.addPreservedID(MachineLoopInfoID);
76 AU.addPreservedID(MachineDominatorsID);
Owen Anderson95dad832008-10-07 20:22:28 +000077
78 if (!StrongPHIElim) {
79 AU.addPreservedID(PHIEliminationID);
80 AU.addRequiredID(PHIEliminationID);
81 }
82
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000083 AU.addRequiredID(TwoAddressInstructionPassID);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000084 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000085}
86
Chris Lattnerf7da2c72006-08-24 22:43:55 +000087void LiveIntervals::releaseMemory() {
Owen Anderson03857b22008-08-13 21:49:13 +000088 // Free the live intervals themselves.
Owen Anderson20e28392008-08-13 22:08:30 +000089 for (DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.begin(),
Owen Anderson03857b22008-08-13 21:49:13 +000090 E = r2iMap_.end(); I != E; ++I)
91 delete I->second;
92
Evan Cheng3f32d652008-06-04 09:18:41 +000093 MBB2IdxMap.clear();
Evan Cheng4ca980e2007-10-17 02:10:22 +000094 Idx2MBBMap.clear();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000095 mi2iMap_.clear();
96 i2miMap_.clear();
97 r2iMap_.clear();
Lang Hamesffd13262009-07-09 03:57:02 +000098 terminatorGaps.clear();
99
Evan Chengdd199d22007-09-06 01:07:24 +0000100 // Release VNInfo memroy regions after all VNInfo objects are dtor'd.
101 VNInfoAllocator.Reset();
Evan Cheng1ed99222008-07-19 00:37:25 +0000102 while (!ClonedMIs.empty()) {
103 MachineInstr *MI = ClonedMIs.back();
104 ClonedMIs.pop_back();
105 mf_->DeleteMachineInstr(MI);
106 }
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000107}
108
Evan Cheng6ade93b2009-08-05 03:53:14 +0000109static bool CanTurnIntoImplicitDef(MachineInstr *MI, unsigned Reg,
110 const TargetInstrInfo *tii_) {
111 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
112 if (tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg) &&
113 Reg == SrcReg)
114 return true;
115
116 if ((MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
117 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) &&
118 MI->getOperand(2).getReg() == Reg)
119 return true;
120 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG &&
121 MI->getOperand(1).getReg() == Reg)
122 return true;
123 return false;
124}
125
Evan Cheng2578ba22009-07-01 01:59:31 +0000126/// processImplicitDefs - Process IMPLICIT_DEF instructions and make sure
127/// there is one implicit_def for each use. Add isUndef marker to
128/// implicit_def defs and their uses.
129void LiveIntervals::processImplicitDefs() {
130 SmallSet<unsigned, 8> ImpDefRegs;
131 SmallVector<MachineInstr*, 8> ImpDefMIs;
132 MachineBasicBlock *Entry = mf_->begin();
133 SmallPtrSet<MachineBasicBlock*,16> Visited;
134 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
135 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
136 DFI != E; ++DFI) {
137 MachineBasicBlock *MBB = *DFI;
138 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
139 I != E; ) {
140 MachineInstr *MI = &*I;
141 ++I;
142 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
143 unsigned Reg = MI->getOperand(0).getReg();
Evan Cheng2578ba22009-07-01 01:59:31 +0000144 ImpDefRegs.insert(Reg);
145 ImpDefMIs.push_back(MI);
146 continue;
147 }
Evan Cheng459a7c62009-07-01 08:19:36 +0000148
149 bool ChangedToImpDef = false;
150 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
Evan Cheng2578ba22009-07-01 01:59:31 +0000151 MachineOperand& MO = MI->getOperand(i);
Evan Cheng6ade93b2009-08-05 03:53:14 +0000152 if (!MO.isReg() || !MO.isUse() || MO.isUndef())
Evan Cheng2578ba22009-07-01 01:59:31 +0000153 continue;
154 unsigned Reg = MO.getReg();
155 if (!Reg)
156 continue;
157 if (!ImpDefRegs.count(Reg))
158 continue;
Evan Cheng459a7c62009-07-01 08:19:36 +0000159 // Use is a copy, just turn it into an implicit_def.
Evan Cheng6ade93b2009-08-05 03:53:14 +0000160 if (CanTurnIntoImplicitDef(MI, Reg, tii_)) {
Evan Cheng459a7c62009-07-01 08:19:36 +0000161 bool isKill = MO.isKill();
162 MI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF));
163 for (int j = MI->getNumOperands() - 1, ee = 0; j > ee; --j)
164 MI->RemoveOperand(j);
165 if (isKill)
166 ImpDefRegs.erase(Reg);
167 ChangedToImpDef = true;
168 break;
169 }
170
Evan Cheng2578ba22009-07-01 01:59:31 +0000171 MO.setIsUndef();
Evan Cheng6ade93b2009-08-05 03:53:14 +0000172 if (MO.isKill() || MI->isRegTiedToDefOperand(i)) {
173 // Make sure other uses of
174 for (unsigned j = i+1; j != e; ++j) {
175 MachineOperand &MOJ = MI->getOperand(j);
176 if (MOJ.isReg() && MOJ.isUse() && MOJ.getReg() == Reg)
177 MOJ.setIsUndef();
178 }
Evan Cheng2578ba22009-07-01 01:59:31 +0000179 ImpDefRegs.erase(Reg);
Evan Cheng6ade93b2009-08-05 03:53:14 +0000180 }
Evan Cheng2578ba22009-07-01 01:59:31 +0000181 }
182
Evan Cheng459a7c62009-07-01 08:19:36 +0000183 if (ChangedToImpDef) {
184 // Backtrack to process this new implicit_def.
185 --I;
186 } else {
187 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
188 MachineOperand& MO = MI->getOperand(i);
189 if (!MO.isReg() || !MO.isDef())
190 continue;
191 ImpDefRegs.erase(MO.getReg());
192 }
Evan Cheng2578ba22009-07-01 01:59:31 +0000193 }
194 }
195
196 // Any outstanding liveout implicit_def's?
197 for (unsigned i = 0, e = ImpDefMIs.size(); i != e; ++i) {
198 MachineInstr *MI = ImpDefMIs[i];
199 unsigned Reg = MI->getOperand(0).getReg();
Evan Chengd129d732009-07-17 19:43:40 +0000200 if (TargetRegisterInfo::isPhysicalRegister(Reg) ||
201 !ImpDefRegs.count(Reg)) {
202 // Delete all "local" implicit_def's. That include those which define
203 // physical registers since they cannot be liveout.
204 MI->eraseFromParent();
Evan Cheng2578ba22009-07-01 01:59:31 +0000205 continue;
Evan Chengd129d732009-07-17 19:43:40 +0000206 }
Evan Cheng459a7c62009-07-01 08:19:36 +0000207
208 // If there are multiple defs of the same register and at least one
209 // is not an implicit_def, do not insert implicit_def's before the
210 // uses.
211 bool Skip = false;
212 for (MachineRegisterInfo::def_iterator DI = mri_->def_begin(Reg),
213 DE = mri_->def_end(); DI != DE; ++DI) {
214 if (DI->getOpcode() != TargetInstrInfo::IMPLICIT_DEF) {
215 Skip = true;
216 break;
Evan Cheng2578ba22009-07-01 01:59:31 +0000217 }
Evan Cheng459a7c62009-07-01 08:19:36 +0000218 }
219 if (Skip)
220 continue;
221
Evan Chengd129d732009-07-17 19:43:40 +0000222 // The only implicit_def which we want to keep are those that are live
223 // out of its block.
224 MI->eraseFromParent();
225
Evan Cheng459a7c62009-07-01 08:19:36 +0000226 for (MachineRegisterInfo::use_iterator UI = mri_->use_begin(Reg),
227 UE = mri_->use_end(); UI != UE; ) {
228 MachineOperand &RMO = UI.getOperand();
229 MachineInstr *RMI = &*UI;
230 ++UI;
Evan Cheng2578ba22009-07-01 01:59:31 +0000231 MachineBasicBlock *RMBB = RMI->getParent();
Evan Cheng459a7c62009-07-01 08:19:36 +0000232 if (RMBB == MBB)
Evan Cheng2578ba22009-07-01 01:59:31 +0000233 continue;
Evan Chengd129d732009-07-17 19:43:40 +0000234
235 // Turn a copy use into an implicit_def.
236 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
237 if (tii_->isMoveInstr(*RMI, SrcReg, DstReg, SrcSubReg, DstSubReg) &&
238 Reg == SrcReg) {
239 RMI->setDesc(tii_->get(TargetInstrInfo::IMPLICIT_DEF));
240 for (int j = RMI->getNumOperands() - 1, ee = 0; j > ee; --j)
241 RMI->RemoveOperand(j);
242 continue;
243 }
244
Evan Cheng2578ba22009-07-01 01:59:31 +0000245 const TargetRegisterClass* RC = mri_->getRegClass(Reg);
246 unsigned NewVReg = mri_->createVirtualRegister(RC);
Evan Cheng2578ba22009-07-01 01:59:31 +0000247 RMO.setReg(NewVReg);
248 RMO.setIsUndef();
249 RMO.setIsKill();
250 }
Evan Cheng2578ba22009-07-01 01:59:31 +0000251 }
252 ImpDefRegs.clear();
253 ImpDefMIs.clear();
254 }
255}
256
Owen Anderson80b3ce62008-05-28 20:54:50 +0000257void LiveIntervals::computeNumbering() {
258 Index2MiMap OldI2MI = i2miMap_;
Owen Anderson7fbad272008-07-23 21:37:49 +0000259 std::vector<IdxMBBPair> OldI2MBB = Idx2MBBMap;
Owen Anderson80b3ce62008-05-28 20:54:50 +0000260
261 Idx2MBBMap.clear();
262 MBB2IdxMap.clear();
263 mi2iMap_.clear();
264 i2miMap_.clear();
Lang Hamesffd13262009-07-09 03:57:02 +0000265 terminatorGaps.clear();
Owen Anderson80b3ce62008-05-28 20:54:50 +0000266
Owen Andersona1566f22008-07-22 22:46:49 +0000267 FunctionSize = 0;
268
Chris Lattner428b92e2006-09-15 03:57:23 +0000269 // Number MachineInstrs and MachineBasicBlocks.
270 // Initialize MBB indexes to a sentinal.
Evan Cheng549f27d32007-08-13 23:45:17 +0000271 MBB2IdxMap.resize(mf_->getNumBlockIDs(), std::make_pair(~0U,~0U));
Chris Lattner428b92e2006-09-15 03:57:23 +0000272
273 unsigned MIIndex = 0;
274 for (MachineFunction::iterator MBB = mf_->begin(), E = mf_->end();
275 MBB != E; ++MBB) {
Evan Cheng549f27d32007-08-13 23:45:17 +0000276 unsigned StartIdx = MIIndex;
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000277
Owen Anderson7fbad272008-07-23 21:37:49 +0000278 // Insert an empty slot at the beginning of each block.
279 MIIndex += InstrSlots::NUM;
280 i2miMap_.push_back(0);
281
Chris Lattner428b92e2006-09-15 03:57:23 +0000282 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
283 I != E; ++I) {
Lang Hamesffd13262009-07-09 03:57:02 +0000284
285 if (I == MBB->getFirstTerminator()) {
286 // Leave a gap for before terminators, this is where we will point
287 // PHI kills.
288 bool inserted =
289 terminatorGaps.insert(std::make_pair(&*MBB, MIIndex)).second;
290 assert(inserted &&
291 "Multiple 'first' terminators encountered during numbering.");
Duncan Sands413a15e2009-07-10 20:07:07 +0000292 inserted = inserted; // Avoid compiler warning if assertions turned off.
Lang Hamesffd13262009-07-09 03:57:02 +0000293 i2miMap_.push_back(0);
294
295 MIIndex += InstrSlots::NUM;
296 }
297
Chris Lattner428b92e2006-09-15 03:57:23 +0000298 bool inserted = mi2iMap_.insert(std::make_pair(I, MIIndex)).second;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000299 assert(inserted && "multiple MachineInstr -> index mappings");
Devang Patel59500c82008-11-21 20:00:59 +0000300 inserted = true;
Chris Lattner428b92e2006-09-15 03:57:23 +0000301 i2miMap_.push_back(I);
302 MIIndex += InstrSlots::NUM;
Owen Andersona1566f22008-07-22 22:46:49 +0000303 FunctionSize++;
Owen Anderson7fbad272008-07-23 21:37:49 +0000304
Evan Cheng4ed43292008-10-18 05:21:37 +0000305 // Insert max(1, numdefs) empty slots after every instruction.
Evan Cheng99fe34b2008-10-18 05:18:55 +0000306 unsigned Slots = I->getDesc().getNumDefs();
307 if (Slots == 0)
308 Slots = 1;
309 MIIndex += InstrSlots::NUM * Slots;
310 while (Slots--)
311 i2miMap_.push_back(0);
Owen Anderson35578012008-06-16 07:10:49 +0000312 }
Lang Hamesffd13262009-07-09 03:57:02 +0000313
314 if (MBB->getFirstTerminator() == MBB->end()) {
315 // Leave a gap for before terminators, this is where we will point
316 // PHI kills.
317 bool inserted =
318 terminatorGaps.insert(std::make_pair(&*MBB, MIIndex)).second;
319 assert(inserted &&
320 "Multiple 'first' terminators encountered during numbering.");
Duncan Sands413a15e2009-07-10 20:07:07 +0000321 inserted = inserted; // Avoid compiler warning if assertions turned off.
Lang Hamesffd13262009-07-09 03:57:02 +0000322 i2miMap_.push_back(0);
323
324 MIIndex += InstrSlots::NUM;
325 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000326
Owen Anderson1fbb4542008-06-16 16:58:24 +0000327 // Set the MBB2IdxMap entry for this MBB.
328 MBB2IdxMap[MBB->getNumber()] = std::make_pair(StartIdx, MIIndex - 1);
329 Idx2MBBMap.push_back(std::make_pair(StartIdx, MBB));
Chris Lattner428b92e2006-09-15 03:57:23 +0000330 }
Lang Hamesffd13262009-07-09 03:57:02 +0000331
Evan Cheng4ca980e2007-10-17 02:10:22 +0000332 std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
Owen Anderson80b3ce62008-05-28 20:54:50 +0000333
334 if (!OldI2MI.empty())
Owen Anderson788d0412008-08-06 18:35:45 +0000335 for (iterator OI = begin(), OE = end(); OI != OE; ++OI) {
Owen Anderson03857b22008-08-13 21:49:13 +0000336 for (LiveInterval::iterator LI = OI->second->begin(),
337 LE = OI->second->end(); LI != LE; ++LI) {
Owen Anderson4b5b2092008-05-29 18:15:49 +0000338
Owen Anderson7eec0c22008-05-29 23:01:22 +0000339 // Remap the start index of the live range to the corresponding new
340 // number, or our best guess at what it _should_ correspond to if the
341 // original instruction has been erased. This is either the following
342 // instruction or its predecessor.
Owen Anderson7fbad272008-07-23 21:37:49 +0000343 unsigned index = LI->start / InstrSlots::NUM;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000344 unsigned offset = LI->start % InstrSlots::NUM;
Owen Anderson0a7615a2008-07-25 23:06:59 +0000345 if (offset == InstrSlots::LOAD) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000346 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000347 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->start);
Owen Anderson7fbad272008-07-23 21:37:49 +0000348 // Take the pair containing the index
349 std::vector<IdxMBBPair>::const_iterator J =
Owen Andersona0c032f2008-07-29 21:15:44 +0000350 (I == OldI2MBB.end() && OldI2MBB.size()>0) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000351
Owen Anderson7fbad272008-07-23 21:37:49 +0000352 LI->start = getMBBStartIdx(J->second);
353 } else {
354 LI->start = mi2iMap_[OldI2MI[index]] + offset;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000355 }
356
357 // Remap the ending index in the same way that we remapped the start,
358 // except for the final step where we always map to the immediately
359 // following instruction.
Owen Andersond7dcbec2008-07-25 19:50:48 +0000360 index = (LI->end - 1) / InstrSlots::NUM;
Owen Anderson7fbad272008-07-23 21:37:49 +0000361 offset = LI->end % InstrSlots::NUM;
Owen Anderson9382b932008-07-30 00:22:56 +0000362 if (offset == InstrSlots::LOAD) {
363 // VReg dies at end of block.
Owen Anderson7fbad272008-07-23 21:37:49 +0000364 std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000365 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), LI->end);
Owen Anderson9382b932008-07-30 00:22:56 +0000366 --I;
Owen Anderson7fbad272008-07-23 21:37:49 +0000367
Owen Anderson9382b932008-07-30 00:22:56 +0000368 LI->end = getMBBEndIdx(I->second) + 1;
Owen Anderson4b5b2092008-05-29 18:15:49 +0000369 } else {
Owen Andersond7dcbec2008-07-25 19:50:48 +0000370 unsigned idx = index;
Owen Anderson8d0cc0a2008-07-25 21:07:13 +0000371 while (index < OldI2MI.size() && !OldI2MI[index]) ++index;
372
373 if (index != OldI2MI.size())
374 LI->end = mi2iMap_[OldI2MI[index]] + (idx == index ? offset : 0);
375 else
376 LI->end = InstrSlots::NUM * i2miMap_.size();
Owen Anderson4b5b2092008-05-29 18:15:49 +0000377 }
Owen Anderson788d0412008-08-06 18:35:45 +0000378 }
379
Owen Anderson03857b22008-08-13 21:49:13 +0000380 for (LiveInterval::vni_iterator VNI = OI->second->vni_begin(),
381 VNE = OI->second->vni_end(); VNI != VNE; ++VNI) {
Owen Anderson788d0412008-08-06 18:35:45 +0000382 VNInfo* vni = *VNI;
Owen Anderson745825f42008-05-28 22:40:08 +0000383
Owen Anderson7eec0c22008-05-29 23:01:22 +0000384 // Remap the VNInfo def index, which works the same as the
Owen Anderson788d0412008-08-06 18:35:45 +0000385 // start indices above. VN's with special sentinel defs
386 // don't need to be remapped.
Lang Hames857c4e02009-06-17 21:01:20 +0000387 if (vni->isDefAccurate() && !vni->isUnused()) {
Owen Anderson788d0412008-08-06 18:35:45 +0000388 unsigned index = vni->def / InstrSlots::NUM;
389 unsigned offset = vni->def % InstrSlots::NUM;
Owen Anderson91292392008-07-30 17:42:47 +0000390 if (offset == InstrSlots::LOAD) {
391 std::vector<IdxMBBPair>::const_iterator I =
Owen Anderson0a7615a2008-07-25 23:06:59 +0000392 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->def);
Owen Anderson91292392008-07-30 17:42:47 +0000393 // Take the pair containing the index
394 std::vector<IdxMBBPair>::const_iterator J =
Owen Andersona0c032f2008-07-29 21:15:44 +0000395 (I == OldI2MBB.end() && OldI2MBB.size()>0) ? (I-1): I;
Owen Anderson7eec0c22008-05-29 23:01:22 +0000396
Owen Anderson91292392008-07-30 17:42:47 +0000397 vni->def = getMBBStartIdx(J->second);
398 } else {
399 vni->def = mi2iMap_[OldI2MI[index]] + offset;
400 }
Owen Anderson7eec0c22008-05-29 23:01:22 +0000401 }
Owen Anderson745825f42008-05-28 22:40:08 +0000402
Owen Anderson7eec0c22008-05-29 23:01:22 +0000403 // Remap the VNInfo kill indices, which works the same as
404 // the end indices above.
Owen Anderson4b5b2092008-05-29 18:15:49 +0000405 for (size_t i = 0; i < vni->kills.size(); ++i) {
Lang Hamesffd13262009-07-09 03:57:02 +0000406 unsigned killIdx = vni->kills[i].killIdx;
407
408 unsigned index = (killIdx - 1) / InstrSlots::NUM;
409 unsigned offset = killIdx % InstrSlots::NUM;
410
Owen Anderson309c6162008-09-30 22:51:54 +0000411 if (offset == InstrSlots::LOAD) {
Lang Hamesffd13262009-07-09 03:57:02 +0000412 assert("Value killed at a load slot.");
413 /*std::vector<IdxMBBPair>::const_iterator I =
Owen Andersond7dcbec2008-07-25 19:50:48 +0000414 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), vni->kills[i]);
Owen Anderson9382b932008-07-30 00:22:56 +0000415 --I;
Owen Anderson7fbad272008-07-23 21:37:49 +0000416
Lang Hamesffd13262009-07-09 03:57:02 +0000417 vni->kills[i] = getMBBEndIdx(I->second);*/
Owen Anderson7fbad272008-07-23 21:37:49 +0000418 } else {
Lang Hamesffd13262009-07-09 03:57:02 +0000419 if (vni->kills[i].isPHIKill) {
420 std::vector<IdxMBBPair>::const_iterator I =
421 std::lower_bound(OldI2MBB.begin(), OldI2MBB.end(), index);
422 --I;
423 vni->kills[i].killIdx = terminatorGaps[I->second];
424 } else {
425 assert(OldI2MI[index] != 0 &&
426 "Kill refers to instruction not present in index maps.");
427 vni->kills[i].killIdx = mi2iMap_[OldI2MI[index]] + offset;
428 }
429
430 /*
Owen Andersond7dcbec2008-07-25 19:50:48 +0000431 unsigned idx = index;
Owen Anderson8d0cc0a2008-07-25 21:07:13 +0000432 while (index < OldI2MI.size() && !OldI2MI[index]) ++index;
433
434 if (index != OldI2MI.size())
435 vni->kills[i] = mi2iMap_[OldI2MI[index]] +
436 (idx == index ? offset : 0);
437 else
438 vni->kills[i] = InstrSlots::NUM * i2miMap_.size();
Lang Hamesffd13262009-07-09 03:57:02 +0000439 */
Owen Anderson7eec0c22008-05-29 23:01:22 +0000440 }
Owen Anderson4b5b2092008-05-29 18:15:49 +0000441 }
Owen Anderson80b3ce62008-05-28 20:54:50 +0000442 }
Owen Anderson788d0412008-08-06 18:35:45 +0000443 }
Owen Anderson80b3ce62008-05-28 20:54:50 +0000444}
Alkis Evlogimenosd6e40a62004-01-14 10:44:29 +0000445
Lang Hamesf41538d2009-06-02 16:53:25 +0000446void LiveIntervals::scaleNumbering(int factor) {
447 // Need to
448 // * scale MBB begin and end points
449 // * scale all ranges.
450 // * Update VNI structures.
451 // * Scale instruction numberings
452
453 // Scale the MBB indices.
454 Idx2MBBMap.clear();
455 for (MachineFunction::iterator MBB = mf_->begin(), MBBE = mf_->end();
456 MBB != MBBE; ++MBB) {
457 std::pair<unsigned, unsigned> &mbbIndices = MBB2IdxMap[MBB->getNumber()];
458 mbbIndices.first = InstrSlots::scale(mbbIndices.first, factor);
459 mbbIndices.second = InstrSlots::scale(mbbIndices.second, factor);
460 Idx2MBBMap.push_back(std::make_pair(mbbIndices.first, MBB));
461 }
462 std::sort(Idx2MBBMap.begin(), Idx2MBBMap.end(), Idx2MBBCompare());
463
Lang Hamesffd13262009-07-09 03:57:02 +0000464 // Scale terminator gaps.
465 for (DenseMap<MachineBasicBlock*, unsigned>::iterator
466 TGI = terminatorGaps.begin(), TGE = terminatorGaps.end();
467 TGI != TGE; ++TGI) {
468 terminatorGaps[TGI->first] = InstrSlots::scale(TGI->second, factor);
469 }
470
Lang Hamesf41538d2009-06-02 16:53:25 +0000471 // Scale the intervals.
472 for (iterator LI = begin(), LE = end(); LI != LE; ++LI) {
473 LI->second->scaleNumbering(factor);
474 }
475
476 // Scale MachineInstrs.
477 Mi2IndexMap oldmi2iMap = mi2iMap_;
478 unsigned highestSlot = 0;
479 for (Mi2IndexMap::iterator MI = oldmi2iMap.begin(), ME = oldmi2iMap.end();
480 MI != ME; ++MI) {
481 unsigned newSlot = InstrSlots::scale(MI->second, factor);
482 mi2iMap_[MI->first] = newSlot;
483 highestSlot = std::max(highestSlot, newSlot);
484 }
485
486 i2miMap_.clear();
487 i2miMap_.resize(highestSlot + 1);
488 for (Mi2IndexMap::iterator MI = mi2iMap_.begin(), ME = mi2iMap_.end();
489 MI != ME; ++MI) {
David Greene340482d2009-07-22 21:56:14 +0000490 i2miMap_[MI->second] = const_cast<MachineInstr *>(MI->first);
Lang Hamesf41538d2009-06-02 16:53:25 +0000491 }
492
493}
494
495
Owen Anderson80b3ce62008-05-28 20:54:50 +0000496/// runOnMachineFunction - Register allocate the whole function
497///
498bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
499 mf_ = &fn;
500 mri_ = &mf_->getRegInfo();
501 tm_ = &fn.getTarget();
502 tri_ = tm_->getRegisterInfo();
503 tii_ = tm_->getInstrInfo();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000504 aa_ = &getAnalysis<AliasAnalysis>();
Owen Anderson80b3ce62008-05-28 20:54:50 +0000505 lv_ = &getAnalysis<LiveVariables>();
506 allocatableRegs_ = tri_->getAllocatableSet(fn);
507
Evan Cheng2578ba22009-07-01 01:59:31 +0000508 processImplicitDefs();
Owen Anderson80b3ce62008-05-28 20:54:50 +0000509 computeNumbering();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000510 computeIntervals();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000511
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000512 numIntervals += getNumIntervals();
513
Chris Lattner70ca3582004-09-30 15:59:17 +0000514 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000515 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000516}
517
Chris Lattner70ca3582004-09-30 15:59:17 +0000518/// print - Implement the dump method.
Reid Spencerce9653c2004-12-07 04:03:45 +0000519void LiveIntervals::print(std::ostream &O, const Module* ) const {
Chris Lattner705e07f2009-08-23 03:41:05 +0000520 raw_os_ostream OS(O);
521 OS << "********** INTERVALS **********\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000522 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Chris Lattner705e07f2009-08-23 03:41:05 +0000523 I->second->print(OS, tri_);
524 OS << "\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000525 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000526
Chris Lattner705e07f2009-08-23 03:41:05 +0000527 OS << "********** MACHINEINSTRS **********\n";
528
Chris Lattner3380d5c2009-07-21 21:12:58 +0000529 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
530 mbbi != mbbe; ++mbbi) {
Chris Lattner705e07f2009-08-23 03:41:05 +0000531 OS << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
Chris Lattner3380d5c2009-07-21 21:12:58 +0000532 for (MachineBasicBlock::iterator mii = mbbi->begin(),
533 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner705e07f2009-08-23 03:41:05 +0000534 OS << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner3380d5c2009-07-21 21:12:58 +0000535 }
536 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000537}
538
Evan Chengc92da382007-11-03 07:20:12 +0000539/// conflictsWithPhysRegDef - Returns true if the specified register
540/// is defined during the duration of the specified interval.
541bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
542 VirtRegMap &vrm, unsigned reg) {
543 for (LiveInterval::Ranges::const_iterator
544 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
545 for (unsigned index = getBaseIndex(I->start),
546 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
547 index += InstrSlots::NUM) {
548 // skip deleted instructions
549 while (index != end && !getInstructionFromIndex(index))
550 index += InstrSlots::NUM;
551 if (index == end) break;
552
553 MachineInstr *MI = getInstructionFromIndex(index);
Evan Cheng04ee5a12009-01-20 19:12:24 +0000554 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
555 if (tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Cheng5d446262007-11-15 08:13:29 +0000556 if (SrcReg == li.reg || DstReg == li.reg)
557 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000558 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
559 MachineOperand& mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000560 if (!mop.isReg())
Evan Chengc92da382007-11-03 07:20:12 +0000561 continue;
562 unsigned PhysReg = mop.getReg();
Evan Cheng5d446262007-11-15 08:13:29 +0000563 if (PhysReg == 0 || PhysReg == li.reg)
Evan Chengc92da382007-11-03 07:20:12 +0000564 continue;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000565 if (TargetRegisterInfo::isVirtualRegister(PhysReg)) {
Evan Cheng5d446262007-11-15 08:13:29 +0000566 if (!vrm.hasPhys(PhysReg))
567 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000568 PhysReg = vrm.getPhys(PhysReg);
Evan Cheng5d446262007-11-15 08:13:29 +0000569 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000570 if (PhysReg && tri_->regsOverlap(PhysReg, reg))
Evan Chengc92da382007-11-03 07:20:12 +0000571 return true;
572 }
573 }
574 }
575
576 return false;
577}
578
Evan Cheng8f90b6e2009-01-07 02:08:57 +0000579/// conflictsWithPhysRegRef - Similar to conflictsWithPhysRegRef except
580/// it can check use as well.
581bool LiveIntervals::conflictsWithPhysRegRef(LiveInterval &li,
582 unsigned Reg, bool CheckUse,
583 SmallPtrSet<MachineInstr*,32> &JoinedCopies) {
584 for (LiveInterval::Ranges::const_iterator
585 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
586 for (unsigned index = getBaseIndex(I->start),
587 end = getBaseIndex(I->end-1) + InstrSlots::NUM; index != end;
588 index += InstrSlots::NUM) {
589 // Skip deleted instructions.
590 MachineInstr *MI = 0;
591 while (index != end) {
592 MI = getInstructionFromIndex(index);
593 if (MI)
594 break;
595 index += InstrSlots::NUM;
596 }
597 if (index == end) break;
598
599 if (JoinedCopies.count(MI))
600 continue;
601 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
602 MachineOperand& MO = MI->getOperand(i);
603 if (!MO.isReg())
604 continue;
605 if (MO.isUse() && !CheckUse)
606 continue;
607 unsigned PhysReg = MO.getReg();
608 if (PhysReg == 0 || TargetRegisterInfo::isVirtualRegister(PhysReg))
609 continue;
610 if (tri_->isSubRegister(Reg, PhysReg))
611 return true;
612 }
613 }
614 }
615
616 return false;
617}
618
619
Evan Cheng549f27d32007-08-13 23:45:17 +0000620void LiveIntervals::printRegName(unsigned reg) const {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000621 if (TargetRegisterInfo::isPhysicalRegister(reg))
Daniel Dunbar3f0e8302009-07-24 09:53:24 +0000622 errs() << tri_->getName(reg);
Evan Cheng549f27d32007-08-13 23:45:17 +0000623 else
Daniel Dunbar3f0e8302009-07-24 09:53:24 +0000624 errs() << "%reg" << reg;
Evan Cheng549f27d32007-08-13 23:45:17 +0000625}
626
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000627void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000628 MachineBasicBlock::iterator mi,
Owen Anderson6b098de2008-06-25 23:39:39 +0000629 unsigned MIIdx, MachineOperand& MO,
Evan Chengef0732d2008-07-10 07:35:43 +0000630 unsigned MOIdx,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000631 LiveInterval &interval) {
Bill Wendling8e6179f2009-08-22 20:18:03 +0000632 DEBUG({
633 errs() << "\t\tregister: ";
634 printRegName(interval.reg);
635 });
Evan Cheng419852c2008-04-03 16:39:43 +0000636
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000637 // Virtual registers may be defined multiple times (due to phi
638 // elimination and 2-addr elimination). Much of what we do only has to be
639 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000640 // time we see a vreg.
Evan Chengd129d732009-07-17 19:43:40 +0000641 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000642 if (interval.empty()) {
643 // Get the Idx of the defining instructions.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000644 unsigned defIndex = getDefIndex(MIIdx);
Dale Johannesen86b49f82008-09-24 01:07:17 +0000645 // Earlyclobbers move back one.
646 if (MO.isEarlyClobber())
647 defIndex = getUseIndex(MIIdx);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000648 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000649 MachineInstr *CopyMI = NULL;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000650 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000651 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000652 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Dan Gohman97121ba2009-04-08 00:15:30 +0000653 mi->getOpcode() == TargetInstrInfo::SUBREG_TO_REG ||
Evan Cheng04ee5a12009-01-20 19:12:24 +0000654 tii_->isMoveInstr(*mi, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000655 CopyMI = mi;
Evan Cheng5379f412008-12-19 20:58:01 +0000656 // Earlyclobbers move back one.
Lang Hames857c4e02009-06-17 21:01:20 +0000657 ValNo = interval.getNextValue(defIndex, CopyMI, true, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000658
659 assert(ValNo->id == 0 && "First value in interval is not 0?");
Chris Lattner7ac2d312004-07-24 02:59:07 +0000660
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000661 // Loop over all of the blocks that the vreg is defined in. There are
662 // two cases we have to handle here. The most common case is a vreg
663 // whose lifetime is contained within a basic block. In this case there
664 // will be a single kill, in MBB, which comes after the definition.
665 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
666 // FIXME: what about dead vars?
667 unsigned killIdx;
668 if (vi.Kills[0] != mi)
669 killIdx = getUseIndex(getInstructionIndex(vi.Kills[0]))+1;
670 else
671 killIdx = defIndex+1;
Chris Lattner6097d132004-07-19 02:15:56 +0000672
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000673 // If the kill happens after the definition, we have an intra-block
674 // live range.
675 if (killIdx > defIndex) {
Jeffrey Yasskin493a3d02009-05-26 18:27:15 +0000676 assert(vi.AliveBlocks.empty() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000677 "Shouldn't be alive across any blocks!");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000678 LiveRange LR(defIndex, killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000679 interval.addRange(LR);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000680 DEBUG(errs() << " +" << LR << "\n");
Lang Hamesffd13262009-07-09 03:57:02 +0000681 interval.addKill(ValNo, killIdx, false);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000682 return;
683 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000684 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000685
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000686 // The other case we handle is when a virtual register lives to the end
687 // of the defining block, potentially live across some blocks, then is
688 // live into some number of blocks, but gets killed. Start by adding a
689 // range that goes from this definition to the end of the defining block.
Owen Anderson7fbad272008-07-23 21:37:49 +0000690 LiveRange NewLR(defIndex, getMBBEndIdx(mbb)+1, ValNo);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000691 DEBUG(errs() << " +" << NewLR);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000692 interval.addRange(NewLR);
693
694 // Iterate over all of the blocks that the variable is completely
695 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
696 // live interval.
Jeffrey Yasskin493a3d02009-05-26 18:27:15 +0000697 for (SparseBitVector<>::iterator I = vi.AliveBlocks.begin(),
698 E = vi.AliveBlocks.end(); I != E; ++I) {
699 LiveRange LR(getMBBStartIdx(*I),
700 getMBBEndIdx(*I)+1, // MBB ends at -1.
Dan Gohman4a829ec2008-11-13 16:31:27 +0000701 ValNo);
702 interval.addRange(LR);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000703 DEBUG(errs() << " +" << LR);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000704 }
705
706 // Finally, this virtual register is live from the start of any killing
707 // block to the 'use' slot of the killing instruction.
708 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
709 MachineInstr *Kill = vi.Kills[i];
Evan Cheng8df78602007-08-08 03:00:28 +0000710 unsigned killIdx = getUseIndex(getInstructionIndex(Kill))+1;
Chris Lattner428b92e2006-09-15 03:57:23 +0000711 LiveRange LR(getMBBStartIdx(Kill->getParent()),
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000712 killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000713 interval.addRange(LR);
Lang Hamesffd13262009-07-09 03:57:02 +0000714 interval.addKill(ValNo, killIdx, false);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000715 DEBUG(errs() << " +" << LR);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000716 }
717
718 } else {
719 // If this is the second time we see a virtual register definition, it
720 // must be due to phi elimination or two addr elimination. If this is
Evan Chengbf105c82006-11-03 03:04:46 +0000721 // the result of two address elimination, then the vreg is one of the
722 // def-and-use register operand.
Bob Wilsond9df5012009-04-09 17:16:43 +0000723 if (mi->isRegTiedToUseOperand(MOIdx)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000724 // If this is a two-address definition, then we have already processed
725 // the live range. The only problem is that we didn't realize there
726 // are actually two values in the live interval. Because of this we
727 // need to take the LiveRegion that defines this register and split it
728 // into two values.
Evan Chenga07cec92008-01-10 08:22:10 +0000729 assert(interval.containsOneValue());
730 unsigned DefIndex = getDefIndex(interval.getValNumInfo(0)->def);
Chris Lattner6b128bd2006-09-03 08:07:11 +0000731 unsigned RedefIndex = getDefIndex(MIIdx);
Evan Chengfb112882009-03-23 08:01:15 +0000732 if (MO.isEarlyClobber())
733 RedefIndex = getUseIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000734
Evan Cheng4f8ff162007-08-11 00:59:19 +0000735 const LiveRange *OldLR = interval.getLiveRangeContaining(RedefIndex-1);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000736 VNInfo *OldValNo = OldLR->valno;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000737
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000738 // Delete the initial value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000739 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000740 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000741
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000742 // Two-address vregs should always only be redefined once. This means
743 // that at this point, there should be exactly one value number in it.
744 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
745
Chris Lattner91725b72006-08-31 05:54:43 +0000746 // The new value number (#1) is defined by the instruction we claimed
747 // defined value #0.
Lang Hames52c1afc2009-08-10 23:43:28 +0000748 VNInfo *ValNo = interval.getNextValue(OldValNo->def, OldValNo->getCopy(),
Lang Hames857c4e02009-06-17 21:01:20 +0000749 false, // update at *
Evan Chengc8d044e2008-02-15 18:24:29 +0000750 VNInfoAllocator);
Lang Hames857c4e02009-06-17 21:01:20 +0000751 ValNo->setFlags(OldValNo->getFlags()); // * <- updating here
752
Chris Lattner91725b72006-08-31 05:54:43 +0000753 // Value#0 is now defined by the 2-addr instruction.
Evan Chengc8d044e2008-02-15 18:24:29 +0000754 OldValNo->def = RedefIndex;
Lang Hames52c1afc2009-08-10 23:43:28 +0000755 OldValNo->setCopy(0);
Evan Chengfb112882009-03-23 08:01:15 +0000756 if (MO.isEarlyClobber())
Lang Hames857c4e02009-06-17 21:01:20 +0000757 OldValNo->setHasRedefByEC(true);
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000758
759 // Add the new live interval which replaces the range for the input copy.
760 LiveRange LR(DefIndex, RedefIndex, ValNo);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000761 DEBUG(errs() << " replace range with " << LR);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000762 interval.addRange(LR);
Lang Hamesffd13262009-07-09 03:57:02 +0000763 interval.addKill(ValNo, RedefIndex, false);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000764
765 // If this redefinition is dead, we need to add a dummy unit live
766 // range covering the def slot.
Owen Anderson6b098de2008-06-25 23:39:39 +0000767 if (MO.isDead())
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000768 interval.addRange(LiveRange(RedefIndex, RedefIndex+1, OldValNo));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000769
Bill Wendling8e6179f2009-08-22 20:18:03 +0000770 DEBUG({
771 errs() << " RESULT: ";
772 interval.print(errs(), tri_);
773 });
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000774 } else {
775 // Otherwise, this must be because of phi elimination. If this is the
776 // first redefinition of the vreg that we have seen, go back and change
777 // the live range in the PHI block to be a different value number.
778 if (interval.containsOneValue()) {
779 assert(vi.Kills.size() == 1 &&
780 "PHI elimination vreg should have one kill, the PHI itself!");
781
782 // Remove the old range that we now know has an incorrect number.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000783 VNInfo *VNI = interval.getValNumInfo(0);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000784 MachineInstr *Killer = vi.Kills[0];
Chris Lattner428b92e2006-09-15 03:57:23 +0000785 unsigned Start = getMBBStartIdx(Killer->getParent());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000786 unsigned End = getUseIndex(getInstructionIndex(Killer))+1;
Bill Wendling8e6179f2009-08-22 20:18:03 +0000787 DEBUG({
788 errs() << " Removing [" << Start << "," << End << "] from: ";
789 interval.print(errs(), tri_);
790 errs() << "\n";
791 });
Lang Hamesffd13262009-07-09 03:57:02 +0000792 interval.removeRange(Start, End);
793 assert(interval.ranges.size() == 1 &&
794 "newly discovered PHI interval has >1 ranges.");
795 MachineBasicBlock *killMBB = getMBBFromIndex(interval.endNumber());
796 interval.addKill(VNI, terminatorGaps[killMBB], true);
Lang Hames857c4e02009-06-17 21:01:20 +0000797 VNI->setHasPHIKill(true);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000798 DEBUG({
799 errs() << " RESULT: ";
800 interval.print(errs(), tri_);
801 });
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000802
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000803 // Replace the interval with one of a NEW value number. Note that this
804 // value number isn't actually defined by an instruction, weird huh? :)
Lang Hames10382fb2009-06-19 02:17:53 +0000805 LiveRange LR(Start, End,
806 interval.getNextValue(mbb->getNumber(), 0, false, VNInfoAllocator));
Lang Hames857c4e02009-06-17 21:01:20 +0000807 LR.valno->setIsPHIDef(true);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000808 DEBUG(errs() << " replace range with " << LR);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000809 interval.addRange(LR);
Lang Hamesffd13262009-07-09 03:57:02 +0000810 interval.addKill(LR.valno, End, false);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000811 DEBUG({
812 errs() << " RESULT: ";
813 interval.print(errs(), tri_);
814 });
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000815 }
816
817 // In the case of PHI elimination, each variable definition is only
818 // live until the end of the block. We've already taken care of the
819 // rest of the live range.
Chris Lattner6b128bd2006-09-03 08:07:11 +0000820 unsigned defIndex = getDefIndex(MIIdx);
Evan Chengfb112882009-03-23 08:01:15 +0000821 if (MO.isEarlyClobber())
822 defIndex = getUseIndex(MIIdx);
Chris Lattner91725b72006-08-31 05:54:43 +0000823
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000824 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000825 MachineInstr *CopyMI = NULL;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000826 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000827 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000828 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Dan Gohman97121ba2009-04-08 00:15:30 +0000829 mi->getOpcode() == TargetInstrInfo::SUBREG_TO_REG ||
Evan Cheng04ee5a12009-01-20 19:12:24 +0000830 tii_->isMoveInstr(*mi, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000831 CopyMI = mi;
Lang Hames857c4e02009-06-17 21:01:20 +0000832 ValNo = interval.getNextValue(defIndex, CopyMI, true, VNInfoAllocator);
Chris Lattner91725b72006-08-31 05:54:43 +0000833
Owen Anderson7fbad272008-07-23 21:37:49 +0000834 unsigned killIndex = getMBBEndIdx(mbb) + 1;
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000835 LiveRange LR(defIndex, killIndex, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000836 interval.addRange(LR);
Lang Hamesffd13262009-07-09 03:57:02 +0000837 interval.addKill(ValNo, terminatorGaps[mbb], true);
Lang Hames857c4e02009-06-17 21:01:20 +0000838 ValNo->setHasPHIKill(true);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000839 DEBUG(errs() << " +" << LR);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000840 }
841 }
842
Bill Wendling8e6179f2009-08-22 20:18:03 +0000843 DEBUG(errs() << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000844}
845
Chris Lattnerf35fef72004-07-23 21:24:19 +0000846void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000847 MachineBasicBlock::iterator mi,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000848 unsigned MIIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000849 MachineOperand& MO,
Chris Lattner91725b72006-08-31 05:54:43 +0000850 LiveInterval &interval,
Evan Chengc8d044e2008-02-15 18:24:29 +0000851 MachineInstr *CopyMI) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000852 // A physical register cannot be live across basic block, so its
853 // lifetime must end somewhere in its defining basic block.
Bill Wendling8e6179f2009-08-22 20:18:03 +0000854 DEBUG({
855 errs() << "\t\tregister: ";
856 printRegName(interval.reg);
857 });
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000858
Chris Lattner6b128bd2006-09-03 08:07:11 +0000859 unsigned baseIndex = MIIdx;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000860 unsigned start = getDefIndex(baseIndex);
Dale Johannesen86b49f82008-09-24 01:07:17 +0000861 // Earlyclobbers move back one.
862 if (MO.isEarlyClobber())
863 start = getUseIndex(MIIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000864 unsigned end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000865
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000866 // If it is not used after definition, it is considered dead at
867 // the instruction defining it. Hence its interval is:
868 // [defSlot(def), defSlot(def)+1)
Owen Anderson6b098de2008-06-25 23:39:39 +0000869 if (MO.isDead()) {
Bill Wendling8e6179f2009-08-22 20:18:03 +0000870 DEBUG(errs() << " dead");
Dale Johannesen86b49f82008-09-24 01:07:17 +0000871 end = start + 1;
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000872 goto exit;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000873 }
874
875 // If it is not dead on definition, it must be killed by a
876 // subsequent instruction. Hence its interval is:
877 // [defSlot(def), useSlot(kill)+1)
Owen Anderson7fbad272008-07-23 21:37:49 +0000878 baseIndex += InstrSlots::NUM;
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000879 while (++mi != MBB->end()) {
Owen Anderson7fbad272008-07-23 21:37:49 +0000880 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
881 getInstructionFromIndex(baseIndex) == 0)
882 baseIndex += InstrSlots::NUM;
Evan Cheng6130f662008-03-05 00:59:57 +0000883 if (mi->killsRegister(interval.reg, tri_)) {
Bill Wendling8e6179f2009-08-22 20:18:03 +0000884 DEBUG(errs() << " killed");
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000885 end = getUseIndex(baseIndex) + 1;
886 goto exit;
Evan Chengc45288e2009-04-27 20:42:46 +0000887 } else {
888 int DefIdx = mi->findRegisterDefOperandIdx(interval.reg, false, tri_);
889 if (DefIdx != -1) {
890 if (mi->isRegTiedToUseOperand(DefIdx)) {
891 // Two-address instruction.
892 end = getDefIndex(baseIndex);
893 if (mi->getOperand(DefIdx).isEarlyClobber())
894 end = getUseIndex(baseIndex);
895 } else {
896 // Another instruction redefines the register before it is ever read.
897 // Then the register is essentially dead at the instruction that defines
898 // it. Hence its interval is:
899 // [defSlot(def), defSlot(def)+1)
Bill Wendling8e6179f2009-08-22 20:18:03 +0000900 DEBUG(errs() << " dead");
Evan Chengc45288e2009-04-27 20:42:46 +0000901 end = start + 1;
902 }
903 goto exit;
904 }
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000905 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000906
907 baseIndex += InstrSlots::NUM;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000908 }
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000909
910 // The only case we should have a dead physreg here without a killing or
911 // instruction where we know it's dead is if it is live-in to the function
Evan Chengd521bc92009-04-27 17:36:47 +0000912 // and never used. Another possible case is the implicit use of the
913 // physical register has been deleted by two-address pass.
Dale Johannesen86b49f82008-09-24 01:07:17 +0000914 end = start + 1;
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000915
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000916exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000917 assert(start < end && "did not find end of interval?");
Chris Lattnerf768bba2005-03-09 23:05:19 +0000918
Evan Cheng24a3cc42007-04-25 07:30:23 +0000919 // Already exists? Extend old live interval.
920 LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
Evan Cheng5379f412008-12-19 20:58:01 +0000921 bool Extend = OldLR != interval.end();
922 VNInfo *ValNo = Extend
Lang Hames857c4e02009-06-17 21:01:20 +0000923 ? OldLR->valno : interval.getNextValue(start, CopyMI, true, VNInfoAllocator);
Evan Cheng5379f412008-12-19 20:58:01 +0000924 if (MO.isEarlyClobber() && Extend)
Lang Hames857c4e02009-06-17 21:01:20 +0000925 ValNo->setHasRedefByEC(true);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000926 LiveRange LR(start, end, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000927 interval.addRange(LR);
Lang Hamesffd13262009-07-09 03:57:02 +0000928 interval.addKill(LR.valno, end, false);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000929 DEBUG(errs() << " +" << LR << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000930}
931
Chris Lattnerf35fef72004-07-23 21:24:19 +0000932void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
933 MachineBasicBlock::iterator MI,
Chris Lattner6b128bd2006-09-03 08:07:11 +0000934 unsigned MIIdx,
Evan Chengef0732d2008-07-10 07:35:43 +0000935 MachineOperand& MO,
936 unsigned MOIdx) {
Owen Anderson6b098de2008-06-25 23:39:39 +0000937 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Evan Chengef0732d2008-07-10 07:35:43 +0000938 handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000939 getOrCreateInterval(MO.getReg()));
940 else if (allocatableRegs_[MO.getReg()]) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000941 MachineInstr *CopyMI = NULL;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000942 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000943 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000944 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Dan Gohman97121ba2009-04-08 00:15:30 +0000945 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG ||
Evan Cheng04ee5a12009-01-20 19:12:24 +0000946 tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000947 CopyMI = MI;
Evan Chengc45288e2009-04-27 20:42:46 +0000948 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
Owen Anderson6b098de2008-06-25 23:39:39 +0000949 getOrCreateInterval(MO.getReg()), CopyMI);
Evan Cheng24a3cc42007-04-25 07:30:23 +0000950 // Def of a register also defines its sub-registers.
Owen Anderson6b098de2008-06-25 23:39:39 +0000951 for (const unsigned* AS = tri_->getSubRegisters(MO.getReg()); *AS; ++AS)
Evan Cheng6130f662008-03-05 00:59:57 +0000952 // If MI also modifies the sub-register explicitly, avoid processing it
953 // more than once. Do not pass in TRI here so it checks for exact match.
954 if (!MI->modifiesRegister(*AS))
Evan Chengc45288e2009-04-27 20:42:46 +0000955 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
Owen Anderson6b098de2008-06-25 23:39:39 +0000956 getOrCreateInterval(*AS), 0);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000957 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000958}
959
Evan Chengb371f452007-02-19 21:49:54 +0000960void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000961 unsigned MIIdx,
Evan Cheng24a3cc42007-04-25 07:30:23 +0000962 LiveInterval &interval, bool isAlias) {
Bill Wendling8e6179f2009-08-22 20:18:03 +0000963 DEBUG({
964 errs() << "\t\tlivein register: ";
965 printRegName(interval.reg);
966 });
Evan Chengb371f452007-02-19 21:49:54 +0000967
968 // Look for kills, if it reaches a def before it's killed, then it shouldn't
969 // be considered a livein.
970 MachineBasicBlock::iterator mi = MBB->begin();
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000971 unsigned baseIndex = MIIdx;
972 unsigned start = baseIndex;
Owen Anderson99500ae2008-09-15 22:00:38 +0000973 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
974 getInstructionFromIndex(baseIndex) == 0)
975 baseIndex += InstrSlots::NUM;
976 unsigned end = baseIndex;
Evan Cheng0076c612009-03-05 03:34:26 +0000977 bool SeenDefUse = false;
Owen Anderson99500ae2008-09-15 22:00:38 +0000978
Evan Chengb371f452007-02-19 21:49:54 +0000979 while (mi != MBB->end()) {
Evan Cheng6130f662008-03-05 00:59:57 +0000980 if (mi->killsRegister(interval.reg, tri_)) {
Bill Wendling8e6179f2009-08-22 20:18:03 +0000981 DEBUG(errs() << " killed");
Evan Chengb371f452007-02-19 21:49:54 +0000982 end = getUseIndex(baseIndex) + 1;
Evan Cheng0076c612009-03-05 03:34:26 +0000983 SeenDefUse = true;
Lang Hamesd21c3162009-06-18 22:01:47 +0000984 break;
Evan Cheng6130f662008-03-05 00:59:57 +0000985 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000986 // Another instruction redefines the register before it is ever read.
987 // Then the register is essentially dead at the instruction that defines
988 // it. Hence its interval is:
989 // [defSlot(def), defSlot(def)+1)
Bill Wendling8e6179f2009-08-22 20:18:03 +0000990 DEBUG(errs() << " dead");
Evan Chengb371f452007-02-19 21:49:54 +0000991 end = getDefIndex(start) + 1;
Evan Cheng0076c612009-03-05 03:34:26 +0000992 SeenDefUse = true;
Lang Hamesd21c3162009-06-18 22:01:47 +0000993 break;
Evan Chengb371f452007-02-19 21:49:54 +0000994 }
995
996 baseIndex += InstrSlots::NUM;
997 ++mi;
Evan Cheng0076c612009-03-05 03:34:26 +0000998 if (mi != MBB->end()) {
999 while (baseIndex / InstrSlots::NUM < i2miMap_.size() &&
1000 getInstructionFromIndex(baseIndex) == 0)
1001 baseIndex += InstrSlots::NUM;
1002 }
Evan Chengb371f452007-02-19 21:49:54 +00001003 }
1004
Evan Cheng75611fb2007-06-27 01:16:36 +00001005 // Live-in register might not be used at all.
Evan Cheng0076c612009-03-05 03:34:26 +00001006 if (!SeenDefUse) {
Evan Cheng292da942007-06-27 18:47:28 +00001007 if (isAlias) {
Bill Wendling8e6179f2009-08-22 20:18:03 +00001008 DEBUG(errs() << " dead");
Evan Cheng75611fb2007-06-27 01:16:36 +00001009 end = getDefIndex(MIIdx) + 1;
Evan Cheng292da942007-06-27 18:47:28 +00001010 } else {
Bill Wendling8e6179f2009-08-22 20:18:03 +00001011 DEBUG(errs() << " live through");
Evan Cheng292da942007-06-27 18:47:28 +00001012 end = baseIndex;
1013 }
Evan Cheng24a3cc42007-04-25 07:30:23 +00001014 }
1015
Lang Hames10382fb2009-06-19 02:17:53 +00001016 VNInfo *vni =
1017 interval.getNextValue(MBB->getNumber(), 0, false, VNInfoAllocator);
Lang Hamesd21c3162009-06-18 22:01:47 +00001018 vni->setIsPHIDef(true);
1019 LiveRange LR(start, end, vni);
1020
Jim Laskey9b25b8c2007-02-21 22:41:17 +00001021 interval.addRange(LR);
Lang Hamesffd13262009-07-09 03:57:02 +00001022 interval.addKill(LR.valno, end, false);
Bill Wendling8e6179f2009-08-22 20:18:03 +00001023 DEBUG(errs() << " +" << LR << '\n');
Evan Chengb371f452007-02-19 21:49:54 +00001024}
1025
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001026/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +00001027/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +00001028/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001029/// which a variable is live
Dale Johannesen91aac102008-09-17 21:13:11 +00001030void LiveIntervals::computeIntervals() {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001031 DEBUG(errs() << "********** COMPUTING LIVE INTERVALS **********\n"
Bill Wendling8e6179f2009-08-22 20:18:03 +00001032 << "********** Function: "
1033 << ((Value*)mf_->getFunction())->getName() << '\n');
Evan Chengd129d732009-07-17 19:43:40 +00001034
1035 SmallVector<unsigned, 8> UndefUses;
Chris Lattner428b92e2006-09-15 03:57:23 +00001036 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
1037 MBBI != E; ++MBBI) {
1038 MachineBasicBlock *MBB = MBBI;
Owen Anderson134eb732008-09-21 20:43:24 +00001039 // Track the index of the current machine instr.
1040 unsigned MIIndex = getMBBStartIdx(MBB);
Daniel Dunbarce63ffb2009-07-25 00:23:56 +00001041 DEBUG(errs() << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +00001042
Chris Lattner428b92e2006-09-15 03:57:23 +00001043 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
Evan Cheng0c9f92e2007-02-13 01:30:55 +00001044
Dan Gohmancb406c22007-10-03 19:26:29 +00001045 // Create intervals for live-ins to this BB first.
1046 for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
1047 LE = MBB->livein_end(); LI != LE; ++LI) {
1048 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
1049 // Multiple live-ins can alias the same register.
Dan Gohman6f0d0242008-02-10 18:45:23 +00001050 for (const unsigned* AS = tri_->getSubRegisters(*LI); *AS; ++AS)
Dan Gohmancb406c22007-10-03 19:26:29 +00001051 if (!hasInterval(*AS))
1052 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
1053 true);
Chris Lattnerdffb2e82006-09-04 18:27:40 +00001054 }
1055
Owen Anderson99500ae2008-09-15 22:00:38 +00001056 // Skip over empty initial indices.
1057 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
1058 getInstructionFromIndex(MIIndex) == 0)
1059 MIIndex += InstrSlots::NUM;
1060
Chris Lattner428b92e2006-09-15 03:57:23 +00001061 for (; MI != miEnd; ++MI) {
Bill Wendling8e6179f2009-08-22 20:18:03 +00001062 DEBUG(errs() << MIIndex << "\t" << *MI);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001063
Evan Cheng438f7bc2006-11-10 08:43:01 +00001064 // Handle defs.
Chris Lattner428b92e2006-09-15 03:57:23 +00001065 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
1066 MachineOperand &MO = MI->getOperand(i);
Evan Chengd129d732009-07-17 19:43:40 +00001067 if (!MO.isReg() || !MO.getReg())
1068 continue;
1069
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001070 // handle register defs - build intervals
Evan Chengd129d732009-07-17 19:43:40 +00001071 if (MO.isDef())
Evan Chengef0732d2008-07-10 07:35:43 +00001072 handleRegisterDef(MBB, MI, MIIndex, MO, i);
Evan Chengd129d732009-07-17 19:43:40 +00001073 else if (MO.isUndef())
1074 UndefUses.push_back(MO.getReg());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001075 }
Evan Cheng99fe34b2008-10-18 05:18:55 +00001076
1077 // Skip over the empty slots after each instruction.
1078 unsigned Slots = MI->getDesc().getNumDefs();
1079 if (Slots == 0)
1080 Slots = 1;
1081 MIIndex += InstrSlots::NUM * Slots;
Owen Anderson7fbad272008-07-23 21:37:49 +00001082
1083 // Skip over empty indices.
1084 while (MIIndex / InstrSlots::NUM < i2miMap_.size() &&
1085 getInstructionFromIndex(MIIndex) == 0)
1086 MIIndex += InstrSlots::NUM;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001087 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +00001088 }
Evan Chengd129d732009-07-17 19:43:40 +00001089
1090 // Create empty intervals for registers defined by implicit_def's (except
1091 // for those implicit_def that define values which are liveout of their
1092 // blocks.
1093 for (unsigned i = 0, e = UndefUses.size(); i != e; ++i) {
1094 unsigned UndefReg = UndefUses[i];
1095 (void)getOrCreateInterval(UndefReg);
1096 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00001097}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +00001098
Evan Chengd0e32c52008-10-29 05:06:14 +00001099bool LiveIntervals::findLiveInMBBs(unsigned Start, unsigned End,
Evan Chenga5bfc972007-10-17 06:53:44 +00001100 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
Evan Cheng4ca980e2007-10-17 02:10:22 +00001101 std::vector<IdxMBBPair>::const_iterator I =
Evan Chengd0e32c52008-10-29 05:06:14 +00001102 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), Start);
Evan Cheng4ca980e2007-10-17 02:10:22 +00001103
1104 bool ResVal = false;
1105 while (I != Idx2MBBMap.end()) {
Dan Gohman2ad82452008-11-26 05:50:31 +00001106 if (I->first >= End)
Evan Cheng4ca980e2007-10-17 02:10:22 +00001107 break;
1108 MBBs.push_back(I->second);
1109 ResVal = true;
1110 ++I;
1111 }
1112 return ResVal;
1113}
1114
Evan Chengd0e32c52008-10-29 05:06:14 +00001115bool LiveIntervals::findReachableMBBs(unsigned Start, unsigned End,
1116 SmallVectorImpl<MachineBasicBlock*> &MBBs) const {
1117 std::vector<IdxMBBPair>::const_iterator I =
1118 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), Start);
1119
1120 bool ResVal = false;
1121 while (I != Idx2MBBMap.end()) {
1122 if (I->first > End)
1123 break;
1124 MachineBasicBlock *MBB = I->second;
1125 if (getMBBEndIdx(MBB) > End)
1126 break;
1127 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1128 SE = MBB->succ_end(); SI != SE; ++SI)
1129 MBBs.push_back(*SI);
1130 ResVal = true;
1131 ++I;
1132 }
1133 return ResVal;
1134}
1135
Owen Anderson03857b22008-08-13 21:49:13 +00001136LiveInterval* LiveIntervals::createInterval(unsigned reg) {
Evan Cheng0a1fcce2009-02-08 11:04:35 +00001137 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? HUGE_VALF : 0.0F;
Owen Anderson03857b22008-08-13 21:49:13 +00001138 return new LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +00001139}
Evan Chengf2fbca62007-11-12 06:35:08 +00001140
Evan Cheng0a1fcce2009-02-08 11:04:35 +00001141/// dupInterval - Duplicate a live interval. The caller is responsible for
1142/// managing the allocated memory.
1143LiveInterval* LiveIntervals::dupInterval(LiveInterval *li) {
1144 LiveInterval *NewLI = createInterval(li->reg);
Evan Cheng90f95f82009-06-14 20:22:55 +00001145 NewLI->Copy(*li, mri_, getVNInfoAllocator());
Evan Cheng0a1fcce2009-02-08 11:04:35 +00001146 return NewLI;
1147}
1148
Evan Chengc8d044e2008-02-15 18:24:29 +00001149/// getVNInfoSourceReg - Helper function that parses the specified VNInfo
1150/// copy field and returns the source register that defines it.
1151unsigned LiveIntervals::getVNInfoSourceReg(const VNInfo *VNI) const {
Lang Hames52c1afc2009-08-10 23:43:28 +00001152 if (!VNI->getCopy())
Evan Chengc8d044e2008-02-15 18:24:29 +00001153 return 0;
1154
Lang Hames52c1afc2009-08-10 23:43:28 +00001155 if (VNI->getCopy()->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001156 // If it's extracting out of a physical register, return the sub-register.
Lang Hames52c1afc2009-08-10 23:43:28 +00001157 unsigned Reg = VNI->getCopy()->getOperand(1).getReg();
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001158 if (TargetRegisterInfo::isPhysicalRegister(Reg))
Lang Hames52c1afc2009-08-10 23:43:28 +00001159 Reg = tri_->getSubReg(Reg, VNI->getCopy()->getOperand(2).getImm());
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001160 return Reg;
Lang Hames52c1afc2009-08-10 23:43:28 +00001161 } else if (VNI->getCopy()->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
1162 VNI->getCopy()->getOpcode() == TargetInstrInfo::SUBREG_TO_REG)
1163 return VNI->getCopy()->getOperand(2).getReg();
Evan Cheng8f90b6e2009-01-07 02:08:57 +00001164
Evan Cheng04ee5a12009-01-20 19:12:24 +00001165 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Lang Hames52c1afc2009-08-10 23:43:28 +00001166 if (tii_->isMoveInstr(*VNI->getCopy(), SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +00001167 return SrcReg;
Torok Edwinc23197a2009-07-14 16:55:14 +00001168 llvm_unreachable("Unrecognized copy instruction!");
Evan Chengc8d044e2008-02-15 18:24:29 +00001169 return 0;
1170}
Evan Chengf2fbca62007-11-12 06:35:08 +00001171
1172//===----------------------------------------------------------------------===//
1173// Register allocator hooks.
1174//
1175
Evan Chengd70dbb52008-02-22 09:24:50 +00001176/// getReMatImplicitUse - If the remat definition MI has one (for now, we only
1177/// allow one) virtual register operand, then its uses are implicitly using
1178/// the register. Returns the virtual register.
1179unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
1180 MachineInstr *MI) const {
1181 unsigned RegOp = 0;
1182 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1183 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001184 if (!MO.isReg() || !MO.isUse())
Evan Chengd70dbb52008-02-22 09:24:50 +00001185 continue;
1186 unsigned Reg = MO.getReg();
1187 if (Reg == 0 || Reg == li.reg)
1188 continue;
Chris Lattner1873d0c2009-06-27 04:06:41 +00001189
1190 if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
1191 !allocatableRegs_[Reg])
1192 continue;
Evan Chengd70dbb52008-02-22 09:24:50 +00001193 // FIXME: For now, only remat MI with at most one register operand.
1194 assert(!RegOp &&
1195 "Can't rematerialize instruction with multiple register operand!");
1196 RegOp = MO.getReg();
Dan Gohman6d69ba82008-07-25 00:02:30 +00001197#ifndef NDEBUG
Evan Chengd70dbb52008-02-22 09:24:50 +00001198 break;
Dan Gohman6d69ba82008-07-25 00:02:30 +00001199#endif
Evan Chengd70dbb52008-02-22 09:24:50 +00001200 }
1201 return RegOp;
1202}
1203
1204/// isValNoAvailableAt - Return true if the val# of the specified interval
1205/// which reaches the given instruction also reaches the specified use index.
1206bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
1207 unsigned UseIdx) const {
1208 unsigned Index = getInstructionIndex(MI);
1209 VNInfo *ValNo = li.FindLiveRangeContaining(Index)->valno;
1210 LiveInterval::const_iterator UI = li.FindLiveRangeContaining(UseIdx);
1211 return UI != li.end() && UI->valno == ValNo;
1212}
1213
Evan Chengf2fbca62007-11-12 06:35:08 +00001214/// isReMaterializable - Returns true if the definition MI of the specified
1215/// val# of the specified interval is re-materializable.
1216bool LiveIntervals::isReMaterializable(const LiveInterval &li,
Evan Cheng5ef3a042007-12-06 00:01:56 +00001217 const VNInfo *ValNo, MachineInstr *MI,
Evan Chengdc377862008-09-30 15:44:16 +00001218 SmallVectorImpl<LiveInterval*> &SpillIs,
Evan Cheng5ef3a042007-12-06 00:01:56 +00001219 bool &isLoad) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001220 if (DisableReMat)
1221 return false;
1222
Evan Cheng20ccded2008-03-15 00:19:36 +00001223 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF)
Evan Chengd70dbb52008-02-22 09:24:50 +00001224 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +00001225
1226 int FrameIdx = 0;
1227 if (tii_->isLoadFromStackSlot(MI, FrameIdx) &&
Evan Cheng249ded32008-02-23 03:38:34 +00001228 mf_->getFrameInfo()->isImmutableObjectIndex(FrameIdx))
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001229 // FIXME: Let target specific isReallyTriviallyReMaterializable determines
1230 // this but remember this is not safe to fold into a two-address
1231 // instruction.
Evan Cheng249ded32008-02-23 03:38:34 +00001232 // This is a load from fixed stack slot. It can be rematerialized.
Evan Chengdd3465e2008-02-23 01:44:27 +00001233 return true;
Evan Chengdd3465e2008-02-23 01:44:27 +00001234
Dan Gohman6d69ba82008-07-25 00:02:30 +00001235 // If the target-specific rules don't identify an instruction as
1236 // being trivially rematerializable, use some target-independent
1237 // rules.
1238 if (!MI->getDesc().isRematerializable() ||
1239 !tii_->isTriviallyReMaterializable(MI)) {
Dan Gohman4c8f8702008-07-25 15:08:37 +00001240 if (!EnableAggressiveRemat)
1241 return false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001242
Dan Gohman0471a792008-07-28 18:43:51 +00001243 // If the instruction accesses memory but the memoperands have been lost,
Dan Gohman6d69ba82008-07-25 00:02:30 +00001244 // we can't analyze it.
1245 const TargetInstrDesc &TID = MI->getDesc();
1246 if ((TID.mayLoad() || TID.mayStore()) && MI->memoperands_empty())
1247 return false;
1248
1249 // Avoid instructions obviously unsafe for remat.
1250 if (TID.hasUnmodeledSideEffects() || TID.isNotDuplicable())
1251 return false;
1252
1253 // If the instruction accesses memory and the memory could be non-constant,
1254 // assume the instruction is not rematerializable.
Evan Chengdc377862008-09-30 15:44:16 +00001255 for (std::list<MachineMemOperand>::const_iterator
1256 I = MI->memoperands_begin(), E = MI->memoperands_end(); I != E; ++I){
Dan Gohman6d69ba82008-07-25 00:02:30 +00001257 const MachineMemOperand &MMO = *I;
1258 if (MMO.isVolatile() || MMO.isStore())
1259 return false;
1260 const Value *V = MMO.getValue();
1261 if (!V)
1262 return false;
1263 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
1264 if (!PSV->isConstant(mf_->getFrameInfo()))
Evan Chengd70dbb52008-02-22 09:24:50 +00001265 return false;
Dan Gohman6d69ba82008-07-25 00:02:30 +00001266 } else if (!aa_->pointsToConstantMemory(V))
1267 return false;
1268 }
1269
1270 // If any of the registers accessed are non-constant, conservatively assume
1271 // the instruction is not rematerializable.
1272 unsigned ImpUse = 0;
1273 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1274 const MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001275 if (MO.isReg()) {
Dan Gohman6d69ba82008-07-25 00:02:30 +00001276 unsigned Reg = MO.getReg();
1277 if (Reg == 0)
1278 continue;
1279 if (TargetRegisterInfo::isPhysicalRegister(Reg))
1280 return false;
1281
1282 // Only allow one def, and that in the first operand.
1283 if (MO.isDef() != (i == 0))
1284 return false;
1285
1286 // Only allow constant-valued registers.
1287 bool IsLiveIn = mri_->isLiveIn(Reg);
1288 MachineRegisterInfo::def_iterator I = mri_->def_begin(Reg),
1289 E = mri_->def_end();
1290
Dan Gohmanc93ced5b2008-12-08 04:53:23 +00001291 // For the def, it should be the only def of that register.
Dan Gohman6d69ba82008-07-25 00:02:30 +00001292 if (MO.isDef() && (next(I) != E || IsLiveIn))
1293 return false;
1294
1295 if (MO.isUse()) {
1296 // Only allow one use other register use, as that's all the
1297 // remat mechanisms support currently.
1298 if (Reg != li.reg) {
1299 if (ImpUse == 0)
1300 ImpUse = Reg;
1301 else if (Reg != ImpUse)
1302 return false;
1303 }
Dan Gohmanc93ced5b2008-12-08 04:53:23 +00001304 // For the use, there should be only one associated def.
Dan Gohman6d69ba82008-07-25 00:02:30 +00001305 if (I != E && (next(I) != E || IsLiveIn))
1306 return false;
1307 }
Evan Chengd70dbb52008-02-22 09:24:50 +00001308 }
1309 }
Evan Cheng5ef3a042007-12-06 00:01:56 +00001310 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001311
Dan Gohman6d69ba82008-07-25 00:02:30 +00001312 unsigned ImpUse = getReMatImplicitUse(li, MI);
1313 if (ImpUse) {
1314 const LiveInterval &ImpLi = getInterval(ImpUse);
1315 for (MachineRegisterInfo::use_iterator ri = mri_->use_begin(li.reg),
1316 re = mri_->use_end(); ri != re; ++ri) {
1317 MachineInstr *UseMI = &*ri;
1318 unsigned UseIdx = getInstructionIndex(UseMI);
1319 if (li.FindLiveRangeContaining(UseIdx)->valno != ValNo)
1320 continue;
1321 if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
1322 return false;
1323 }
Evan Chengdc377862008-09-30 15:44:16 +00001324
1325 // If a register operand of the re-materialized instruction is going to
1326 // be spilled next, then it's not legal to re-materialize this instruction.
1327 for (unsigned i = 0, e = SpillIs.size(); i != e; ++i)
1328 if (ImpUse == SpillIs[i]->reg)
1329 return false;
Dan Gohman6d69ba82008-07-25 00:02:30 +00001330 }
1331 return true;
Evan Cheng5ef3a042007-12-06 00:01:56 +00001332}
1333
Evan Cheng06587492008-10-24 02:05:00 +00001334/// isReMaterializable - Returns true if the definition MI of the specified
1335/// val# of the specified interval is re-materializable.
1336bool LiveIntervals::isReMaterializable(const LiveInterval &li,
1337 const VNInfo *ValNo, MachineInstr *MI) {
1338 SmallVector<LiveInterval*, 4> Dummy1;
1339 bool Dummy2;
1340 return isReMaterializable(li, ValNo, MI, Dummy1, Dummy2);
1341}
1342
Evan Cheng5ef3a042007-12-06 00:01:56 +00001343/// isReMaterializable - Returns true if every definition of MI of every
1344/// val# of the specified interval is re-materializable.
Evan Chengdc377862008-09-30 15:44:16 +00001345bool LiveIntervals::isReMaterializable(const LiveInterval &li,
1346 SmallVectorImpl<LiveInterval*> &SpillIs,
1347 bool &isLoad) {
Evan Cheng5ef3a042007-12-06 00:01:56 +00001348 isLoad = false;
1349 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1350 i != e; ++i) {
1351 const VNInfo *VNI = *i;
Lang Hames857c4e02009-06-17 21:01:20 +00001352 if (VNI->isUnused())
Evan Cheng5ef3a042007-12-06 00:01:56 +00001353 continue; // Dead val#.
1354 // Is the def for the val# rematerializable?
Lang Hames857c4e02009-06-17 21:01:20 +00001355 if (!VNI->isDefAccurate())
Evan Cheng5ef3a042007-12-06 00:01:56 +00001356 return false;
Lang Hames857c4e02009-06-17 21:01:20 +00001357 MachineInstr *ReMatDefMI = getInstructionFromIndex(VNI->def);
Evan Cheng5ef3a042007-12-06 00:01:56 +00001358 bool DefIsLoad = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001359 if (!ReMatDefMI ||
Evan Chengdc377862008-09-30 15:44:16 +00001360 !isReMaterializable(li, VNI, ReMatDefMI, SpillIs, DefIsLoad))
Evan Cheng5ef3a042007-12-06 00:01:56 +00001361 return false;
1362 isLoad |= DefIsLoad;
Evan Chengf2fbca62007-11-12 06:35:08 +00001363 }
1364 return true;
1365}
1366
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001367/// FilterFoldedOps - Filter out two-address use operands. Return
1368/// true if it finds any issue with the operands that ought to prevent
1369/// folding.
1370static bool FilterFoldedOps(MachineInstr *MI,
1371 SmallVector<unsigned, 2> &Ops,
1372 unsigned &MRInfo,
1373 SmallVector<unsigned, 2> &FoldOps) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001374 MRInfo = 0;
Evan Chengaee4af62007-12-02 08:30:39 +00001375 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1376 unsigned OpIdx = Ops[i];
Evan Chengd70dbb52008-02-22 09:24:50 +00001377 MachineOperand &MO = MI->getOperand(OpIdx);
Evan Chengaee4af62007-12-02 08:30:39 +00001378 // FIXME: fold subreg use.
Evan Chengd70dbb52008-02-22 09:24:50 +00001379 if (MO.getSubReg())
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001380 return true;
Evan Chengd70dbb52008-02-22 09:24:50 +00001381 if (MO.isDef())
Evan Chengaee4af62007-12-02 08:30:39 +00001382 MRInfo |= (unsigned)VirtRegMap::isMod;
1383 else {
1384 // Filter out two-address use operand(s).
Evan Chenga24752f2009-03-19 20:30:06 +00001385 if (MI->isRegTiedToDefOperand(OpIdx)) {
Evan Chengaee4af62007-12-02 08:30:39 +00001386 MRInfo = VirtRegMap::isModRef;
1387 continue;
1388 }
1389 MRInfo |= (unsigned)VirtRegMap::isRef;
1390 }
1391 FoldOps.push_back(OpIdx);
Evan Chenge62f97c2007-12-01 02:07:52 +00001392 }
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001393 return false;
1394}
1395
1396
1397/// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
1398/// slot / to reg or any rematerialized load into ith operand of specified
1399/// MI. If it is successul, MI is updated with the newly created MI and
1400/// returns true.
1401bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
1402 VirtRegMap &vrm, MachineInstr *DefMI,
1403 unsigned InstrIdx,
1404 SmallVector<unsigned, 2> &Ops,
1405 bool isSS, int Slot, unsigned Reg) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001406 // If it is an implicit def instruction, just delete it.
Evan Cheng20ccded2008-03-15 00:19:36 +00001407 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001408 RemoveMachineInstrFromMaps(MI);
1409 vrm.RemoveMachineInstrFromMaps(MI);
1410 MI->eraseFromParent();
1411 ++numFolds;
1412 return true;
1413 }
1414
1415 // Filter the list of operand indexes that are to be folded. Abort if
1416 // any operand will prevent folding.
1417 unsigned MRInfo = 0;
1418 SmallVector<unsigned, 2> FoldOps;
1419 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1420 return false;
Evan Chenge62f97c2007-12-01 02:07:52 +00001421
Evan Cheng427f4c12008-03-31 23:19:51 +00001422 // The only time it's safe to fold into a two address instruction is when
1423 // it's folding reload and spill from / into a spill stack slot.
1424 if (DefMI && (MRInfo & VirtRegMap::isMod))
Evan Cheng249ded32008-02-23 03:38:34 +00001425 return false;
1426
Evan Chengf2f8c2a2008-02-08 22:05:27 +00001427 MachineInstr *fmi = isSS ? tii_->foldMemoryOperand(*mf_, MI, FoldOps, Slot)
1428 : tii_->foldMemoryOperand(*mf_, MI, FoldOps, DefMI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001429 if (fmi) {
Evan Chengd3653122008-02-27 03:04:06 +00001430 // Remember this instruction uses the spill slot.
1431 if (isSS) vrm.addSpillSlotUse(Slot, fmi);
1432
Evan Chengf2fbca62007-11-12 06:35:08 +00001433 // Attempt to fold the memory reference into the instruction. If
1434 // we can do this, we don't need to insert spill code.
Evan Chengf2fbca62007-11-12 06:35:08 +00001435 MachineBasicBlock &MBB = *MI->getParent();
Evan Cheng84802932008-01-10 08:24:38 +00001436 if (isSS && !mf_->getFrameInfo()->isImmutableObjectIndex(Slot))
Evan Chengaee4af62007-12-02 08:30:39 +00001437 vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
Evan Cheng81a03822007-11-17 00:40:40 +00001438 vrm.transferSpillPts(MI, fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001439 vrm.transferRestorePts(MI, fmi);
Evan Chengc1f53c72008-03-11 21:34:46 +00001440 vrm.transferEmergencySpills(MI, fmi);
Evan Chengf2fbca62007-11-12 06:35:08 +00001441 mi2iMap_.erase(MI);
Evan Chengcddbb832007-11-30 21:23:43 +00001442 i2miMap_[InstrIdx /InstrSlots::NUM] = fmi;
1443 mi2iMap_[fmi] = InstrIdx;
Evan Chengf2fbca62007-11-12 06:35:08 +00001444 MI = MBB.insert(MBB.erase(MI), fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001445 ++numFolds;
Evan Chengf2fbca62007-11-12 06:35:08 +00001446 return true;
1447 }
1448 return false;
1449}
1450
Evan Cheng018f9b02007-12-05 03:22:34 +00001451/// canFoldMemoryOperand - Returns true if the specified load / store
1452/// folding is possible.
1453bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI,
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001454 SmallVector<unsigned, 2> &Ops,
Evan Cheng3c75ba82008-04-01 21:37:32 +00001455 bool ReMat) const {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001456 // Filter the list of operand indexes that are to be folded. Abort if
1457 // any operand will prevent folding.
1458 unsigned MRInfo = 0;
Evan Cheng018f9b02007-12-05 03:22:34 +00001459 SmallVector<unsigned, 2> FoldOps;
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001460 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1461 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001462
Evan Cheng3c75ba82008-04-01 21:37:32 +00001463 // It's only legal to remat for a use, not a def.
1464 if (ReMat && (MRInfo & VirtRegMap::isMod))
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001465 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001466
Evan Chengd70dbb52008-02-22 09:24:50 +00001467 return tii_->canFoldMemoryOperand(MI, FoldOps);
1468}
1469
Evan Cheng81a03822007-11-17 00:40:40 +00001470bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
1471 SmallPtrSet<MachineBasicBlock*, 4> MBBs;
1472 for (LiveInterval::Ranges::const_iterator
1473 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1474 std::vector<IdxMBBPair>::const_iterator II =
1475 std::lower_bound(Idx2MBBMap.begin(), Idx2MBBMap.end(), I->start);
1476 if (II == Idx2MBBMap.end())
1477 continue;
1478 if (I->end > II->first) // crossing a MBB.
1479 return false;
1480 MBBs.insert(II->second);
1481 if (MBBs.size() > 1)
1482 return false;
1483 }
1484 return true;
1485}
1486
Evan Chengd70dbb52008-02-22 09:24:50 +00001487/// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
1488/// interval on to-be re-materialized operands of MI) with new register.
1489void LiveIntervals::rewriteImplicitOps(const LiveInterval &li,
1490 MachineInstr *MI, unsigned NewVReg,
1491 VirtRegMap &vrm) {
1492 // There is an implicit use. That means one of the other operand is
1493 // being remat'ed and the remat'ed instruction has li.reg as an
1494 // use operand. Make sure we rewrite that as well.
1495 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1496 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001497 if (!MO.isReg())
Evan Chengd70dbb52008-02-22 09:24:50 +00001498 continue;
1499 unsigned Reg = MO.getReg();
1500 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
1501 continue;
1502 if (!vrm.isReMaterialized(Reg))
1503 continue;
1504 MachineInstr *ReMatMI = vrm.getReMaterializedMI(Reg);
Evan Cheng6130f662008-03-05 00:59:57 +00001505 MachineOperand *UseMO = ReMatMI->findRegisterUseOperand(li.reg);
1506 if (UseMO)
1507 UseMO->setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001508 }
1509}
1510
Evan Chengf2fbca62007-11-12 06:35:08 +00001511/// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
1512/// for addIntervalsForSpills to rewrite uses / defs for the given live range.
Evan Cheng018f9b02007-12-05 03:22:34 +00001513bool LiveIntervals::
Evan Chengd70dbb52008-02-22 09:24:50 +00001514rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
1515 bool TrySplit, unsigned index, unsigned end, MachineInstr *MI,
Evan Cheng81a03822007-11-17 00:40:40 +00001516 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001517 unsigned Slot, int LdSlot,
1518 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001519 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001520 const TargetRegisterClass* rc,
1521 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001522 const MachineLoopInfo *loopInfo,
Evan Cheng313d4b82008-02-23 00:33:04 +00001523 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
Owen Anderson28998312008-08-13 22:28:50 +00001524 DenseMap<unsigned,unsigned> &MBBVRegsMap,
Evan Chengc781a242009-05-03 18:32:42 +00001525 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001526 bool CanFold = false;
Evan Chengf2fbca62007-11-12 06:35:08 +00001527 RestartInstruction:
1528 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1529 MachineOperand& mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001530 if (!mop.isReg())
Evan Chengf2fbca62007-11-12 06:35:08 +00001531 continue;
1532 unsigned Reg = mop.getReg();
1533 unsigned RegI = Reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001534 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
Evan Chengf2fbca62007-11-12 06:35:08 +00001535 continue;
Evan Chengf2fbca62007-11-12 06:35:08 +00001536 if (Reg != li.reg)
1537 continue;
1538
1539 bool TryFold = !DefIsReMat;
Evan Chengcb3c3302007-11-29 23:02:50 +00001540 bool FoldSS = true; // Default behavior unless it's a remat.
Evan Chengf2fbca62007-11-12 06:35:08 +00001541 int FoldSlot = Slot;
1542 if (DefIsReMat) {
1543 // If this is the rematerializable definition MI itself and
1544 // all of its uses are rematerialized, simply delete it.
Evan Cheng81a03822007-11-17 00:40:40 +00001545 if (MI == ReMatOrigDefMI && CanDelete) {
Bill Wendling8e6179f2009-08-22 20:18:03 +00001546 DEBUG(errs() << "\t\t\t\tErasing re-materlizable def: "
1547 << MI << '\n');
Evan Chengf2fbca62007-11-12 06:35:08 +00001548 RemoveMachineInstrFromMaps(MI);
Evan Chengcada2452007-11-28 01:28:46 +00001549 vrm.RemoveMachineInstrFromMaps(MI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001550 MI->eraseFromParent();
1551 break;
1552 }
1553
1554 // If def for this use can't be rematerialized, then try folding.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001555 // If def is rematerializable and it's a load, also try folding.
Evan Chengcb3c3302007-11-29 23:02:50 +00001556 TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad));
Evan Chengf2fbca62007-11-12 06:35:08 +00001557 if (isLoad) {
1558 // Try fold loads (from stack slot, constant pool, etc.) into uses.
1559 FoldSS = isLoadSS;
1560 FoldSlot = LdSlot;
1561 }
1562 }
1563
Evan Chengf2fbca62007-11-12 06:35:08 +00001564 // Scan all of the operands of this instruction rewriting operands
1565 // to use NewVReg instead of li.reg as appropriate. We do this for
1566 // two reasons:
1567 //
1568 // 1. If the instr reads the same spilled vreg multiple times, we
1569 // want to reuse the NewVReg.
1570 // 2. If the instr is a two-addr instruction, we are required to
1571 // keep the src/dst regs pinned.
1572 //
1573 // Keep track of whether we replace a use and/or def so that we can
1574 // create the spill interval with the appropriate range.
Evan Chengcddbb832007-11-30 21:23:43 +00001575
Evan Cheng81a03822007-11-17 00:40:40 +00001576 HasUse = mop.isUse();
1577 HasDef = mop.isDef();
Evan Chengaee4af62007-12-02 08:30:39 +00001578 SmallVector<unsigned, 2> Ops;
1579 Ops.push_back(i);
Evan Chengf2fbca62007-11-12 06:35:08 +00001580 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
Evan Chengaee4af62007-12-02 08:30:39 +00001581 const MachineOperand &MOj = MI->getOperand(j);
Dan Gohmand735b802008-10-03 15:45:36 +00001582 if (!MOj.isReg())
Evan Chengf2fbca62007-11-12 06:35:08 +00001583 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001584 unsigned RegJ = MOj.getReg();
Dan Gohman6f0d0242008-02-10 18:45:23 +00001585 if (RegJ == 0 || TargetRegisterInfo::isPhysicalRegister(RegJ))
Evan Chengf2fbca62007-11-12 06:35:08 +00001586 continue;
1587 if (RegJ == RegI) {
Evan Chengaee4af62007-12-02 08:30:39 +00001588 Ops.push_back(j);
Evan Chengd129d732009-07-17 19:43:40 +00001589 if (!MOj.isUndef()) {
1590 HasUse |= MOj.isUse();
1591 HasDef |= MOj.isDef();
1592 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001593 }
1594 }
1595
David Greene26b86a02008-10-27 17:38:59 +00001596 // Create a new virtual register for the spill interval.
1597 // Create the new register now so we can map the fold instruction
1598 // to the new register so when it is unfolded we get the correct
1599 // answer.
1600 bool CreatedNewVReg = false;
1601 if (NewVReg == 0) {
1602 NewVReg = mri_->createVirtualRegister(rc);
1603 vrm.grow();
1604 CreatedNewVReg = true;
1605 }
1606
Evan Cheng9c3c2212008-06-06 07:54:39 +00001607 if (!TryFold)
1608 CanFold = false;
1609 else {
Evan Cheng018f9b02007-12-05 03:22:34 +00001610 // Do not fold load / store here if we are splitting. We'll find an
1611 // optimal point to insert a load / store later.
1612 if (!TrySplit) {
1613 if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
David Greene26b86a02008-10-27 17:38:59 +00001614 Ops, FoldSS, FoldSlot, NewVReg)) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001615 // Folding the load/store can completely change the instruction in
1616 // unpredictable ways, rescan it from the beginning.
David Greene26b86a02008-10-27 17:38:59 +00001617
1618 if (FoldSS) {
1619 // We need to give the new vreg the same stack slot as the
1620 // spilled interval.
1621 vrm.assignVirt2StackSlot(NewVReg, FoldSlot);
1622 }
1623
Evan Cheng018f9b02007-12-05 03:22:34 +00001624 HasUse = false;
1625 HasDef = false;
1626 CanFold = false;
Evan Chengc781a242009-05-03 18:32:42 +00001627 if (isNotInMIMap(MI))
Evan Cheng7e073ba2008-04-09 20:57:25 +00001628 break;
Evan Cheng018f9b02007-12-05 03:22:34 +00001629 goto RestartInstruction;
1630 }
1631 } else {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001632 // We'll try to fold it later if it's profitable.
Evan Cheng3c75ba82008-04-01 21:37:32 +00001633 CanFold = canFoldMemoryOperand(MI, Ops, DefIsReMat);
Evan Cheng018f9b02007-12-05 03:22:34 +00001634 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001635 }
Evan Chengcddbb832007-11-30 21:23:43 +00001636
Evan Chengcddbb832007-11-30 21:23:43 +00001637 mop.setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001638 if (mop.isImplicit())
1639 rewriteImplicitOps(li, MI, NewVReg, vrm);
Evan Chengcddbb832007-11-30 21:23:43 +00001640
1641 // Reuse NewVReg for other reads.
Evan Chengd70dbb52008-02-22 09:24:50 +00001642 for (unsigned j = 0, e = Ops.size(); j != e; ++j) {
1643 MachineOperand &mopj = MI->getOperand(Ops[j]);
1644 mopj.setReg(NewVReg);
1645 if (mopj.isImplicit())
1646 rewriteImplicitOps(li, MI, NewVReg, vrm);
1647 }
Evan Chengcddbb832007-11-30 21:23:43 +00001648
Evan Cheng81a03822007-11-17 00:40:40 +00001649 if (CreatedNewVReg) {
1650 if (DefIsReMat) {
Evan Cheng37844532009-07-16 09:20:10 +00001651 vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI);
Evan Chengd70dbb52008-02-22 09:24:50 +00001652 if (ReMatIds[VNI->id] == VirtRegMap::MAX_STACK_SLOT) {
Evan Cheng81a03822007-11-17 00:40:40 +00001653 // Each valnum may have its own remat id.
Evan Chengd70dbb52008-02-22 09:24:50 +00001654 ReMatIds[VNI->id] = vrm.assignVirtReMatId(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001655 } else {
Evan Chengd70dbb52008-02-22 09:24:50 +00001656 vrm.assignVirtReMatId(NewVReg, ReMatIds[VNI->id]);
Evan Cheng81a03822007-11-17 00:40:40 +00001657 }
1658 if (!CanDelete || (HasUse && HasDef)) {
1659 // If this is a two-addr instruction then its use operands are
1660 // rematerializable but its def is not. It should be assigned a
1661 // stack slot.
1662 vrm.assignVirt2StackSlot(NewVReg, Slot);
1663 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001664 } else {
Evan Chengf2fbca62007-11-12 06:35:08 +00001665 vrm.assignVirt2StackSlot(NewVReg, Slot);
1666 }
Evan Chengcb3c3302007-11-29 23:02:50 +00001667 } else if (HasUse && HasDef &&
1668 vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) {
1669 // If this interval hasn't been assigned a stack slot (because earlier
1670 // def is a deleted remat def), do it now.
1671 assert(Slot != VirtRegMap::NO_STACK_SLOT);
1672 vrm.assignVirt2StackSlot(NewVReg, Slot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001673 }
1674
Evan Cheng313d4b82008-02-23 00:33:04 +00001675 // Re-matting an instruction with virtual register use. Add the
1676 // register as an implicit use on the use MI.
1677 if (DefIsReMat && ImpUse)
1678 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1679
Evan Cheng5b69eba2009-04-21 22:46:52 +00001680 // Create a new register interval for this spill / remat.
Evan Chengf2fbca62007-11-12 06:35:08 +00001681 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001682 if (CreatedNewVReg) {
1683 NewLIs.push_back(&nI);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001684 MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg));
Evan Cheng81a03822007-11-17 00:40:40 +00001685 if (TrySplit)
1686 vrm.setIsSplitFromReg(NewVReg, li.reg);
1687 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001688
1689 if (HasUse) {
Evan Cheng81a03822007-11-17 00:40:40 +00001690 if (CreatedNewVReg) {
1691 LiveRange LR(getLoadIndex(index), getUseIndex(index)+1,
Lang Hames857c4e02009-06-17 21:01:20 +00001692 nI.getNextValue(0, 0, false, VNInfoAllocator));
Bill Wendling8e6179f2009-08-22 20:18:03 +00001693 DEBUG(errs() << " +" << LR);
Evan Cheng81a03822007-11-17 00:40:40 +00001694 nI.addRange(LR);
1695 } else {
1696 // Extend the split live interval to this def / use.
1697 unsigned End = getUseIndex(index)+1;
1698 LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
1699 nI.getValNumInfo(nI.getNumValNums()-1));
Bill Wendling8e6179f2009-08-22 20:18:03 +00001700 DEBUG(errs() << " +" << LR);
Evan Cheng81a03822007-11-17 00:40:40 +00001701 nI.addRange(LR);
1702 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001703 }
1704 if (HasDef) {
1705 LiveRange LR(getDefIndex(index), getStoreIndex(index),
Lang Hames857c4e02009-06-17 21:01:20 +00001706 nI.getNextValue(0, 0, false, VNInfoAllocator));
Bill Wendling8e6179f2009-08-22 20:18:03 +00001707 DEBUG(errs() << " +" << LR);
Evan Chengf2fbca62007-11-12 06:35:08 +00001708 nI.addRange(LR);
1709 }
Evan Cheng81a03822007-11-17 00:40:40 +00001710
Bill Wendling8e6179f2009-08-22 20:18:03 +00001711 DEBUG({
1712 errs() << "\t\t\t\tAdded new interval: ";
1713 nI.print(errs(), tri_);
1714 errs() << '\n';
1715 });
Evan Chengf2fbca62007-11-12 06:35:08 +00001716 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001717 return CanFold;
Evan Chengf2fbca62007-11-12 06:35:08 +00001718}
Evan Cheng81a03822007-11-17 00:40:40 +00001719bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001720 const VNInfo *VNI,
1721 MachineBasicBlock *MBB, unsigned Idx) const {
Evan Cheng81a03822007-11-17 00:40:40 +00001722 unsigned End = getMBBEndIdx(MBB);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001723 for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
Lang Hamesffd13262009-07-09 03:57:02 +00001724 if (VNI->kills[j].isPHIKill)
1725 continue;
1726
1727 unsigned KillIdx = VNI->kills[j].killIdx;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001728 if (KillIdx > Idx && KillIdx < End)
1729 return true;
Evan Cheng81a03822007-11-17 00:40:40 +00001730 }
1731 return false;
1732}
1733
Evan Cheng063284c2008-02-21 00:34:19 +00001734/// RewriteInfo - Keep track of machine instrs that will be rewritten
1735/// during spilling.
Dan Gohman844731a2008-05-13 00:00:25 +00001736namespace {
1737 struct RewriteInfo {
1738 unsigned Index;
1739 MachineInstr *MI;
1740 bool HasUse;
1741 bool HasDef;
1742 RewriteInfo(unsigned i, MachineInstr *mi, bool u, bool d)
1743 : Index(i), MI(mi), HasUse(u), HasDef(d) {}
1744 };
Evan Cheng063284c2008-02-21 00:34:19 +00001745
Dan Gohman844731a2008-05-13 00:00:25 +00001746 struct RewriteInfoCompare {
1747 bool operator()(const RewriteInfo &LHS, const RewriteInfo &RHS) const {
1748 return LHS.Index < RHS.Index;
1749 }
1750 };
1751}
Evan Cheng063284c2008-02-21 00:34:19 +00001752
Evan Chengf2fbca62007-11-12 06:35:08 +00001753void LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001754rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
Evan Chengf2fbca62007-11-12 06:35:08 +00001755 LiveInterval::Ranges::const_iterator &I,
Evan Cheng81a03822007-11-17 00:40:40 +00001756 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001757 unsigned Slot, int LdSlot,
1758 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001759 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001760 const TargetRegisterClass* rc,
1761 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001762 const MachineLoopInfo *loopInfo,
Evan Cheng81a03822007-11-17 00:40:40 +00001763 BitVector &SpillMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001764 DenseMap<unsigned, std::vector<SRInfo> > &SpillIdxes,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001765 BitVector &RestoreMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001766 DenseMap<unsigned, std::vector<SRInfo> > &RestoreIdxes,
1767 DenseMap<unsigned,unsigned> &MBBVRegsMap,
Evan Chengc781a242009-05-03 18:32:42 +00001768 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001769 bool AllCanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001770 unsigned NewVReg = 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001771 unsigned start = getBaseIndex(I->start);
Evan Chengf2fbca62007-11-12 06:35:08 +00001772 unsigned end = getBaseIndex(I->end-1) + InstrSlots::NUM;
Evan Chengf2fbca62007-11-12 06:35:08 +00001773
Evan Cheng063284c2008-02-21 00:34:19 +00001774 // First collect all the def / use in this live range that will be rewritten.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001775 // Make sure they are sorted according to instruction index.
Evan Cheng063284c2008-02-21 00:34:19 +00001776 std::vector<RewriteInfo> RewriteMIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001777 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1778 re = mri_->reg_end(); ri != re; ) {
Evan Cheng419852c2008-04-03 16:39:43 +00001779 MachineInstr *MI = &*ri;
Evan Cheng063284c2008-02-21 00:34:19 +00001780 MachineOperand &O = ri.getOperand();
1781 ++ri;
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001782 assert(!O.isImplicit() && "Spilling register that's used as implicit use?");
Evan Cheng063284c2008-02-21 00:34:19 +00001783 unsigned index = getInstructionIndex(MI);
1784 if (index < start || index >= end)
1785 continue;
Evan Chengd129d732009-07-17 19:43:40 +00001786
1787 if (O.isUndef())
Evan Cheng79a796c2008-07-12 01:56:02 +00001788 // Must be defined by an implicit def. It should not be spilled. Note,
1789 // this is for correctness reason. e.g.
1790 // 8 %reg1024<def> = IMPLICIT_DEF
1791 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1792 // The live range [12, 14) are not part of the r1024 live interval since
1793 // it's defined by an implicit def. It will not conflicts with live
1794 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001795 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001796 // the INSERT_SUBREG and both target registers that would overlap.
1797 continue;
Evan Cheng063284c2008-02-21 00:34:19 +00001798 RewriteMIs.push_back(RewriteInfo(index, MI, O.isUse(), O.isDef()));
1799 }
1800 std::sort(RewriteMIs.begin(), RewriteMIs.end(), RewriteInfoCompare());
1801
Evan Cheng313d4b82008-02-23 00:33:04 +00001802 unsigned ImpUse = DefIsReMat ? getReMatImplicitUse(li, ReMatDefMI) : 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001803 // Now rewrite the defs and uses.
1804 for (unsigned i = 0, e = RewriteMIs.size(); i != e; ) {
1805 RewriteInfo &rwi = RewriteMIs[i];
1806 ++i;
1807 unsigned index = rwi.Index;
1808 bool MIHasUse = rwi.HasUse;
1809 bool MIHasDef = rwi.HasDef;
1810 MachineInstr *MI = rwi.MI;
1811 // If MI def and/or use the same register multiple times, then there
1812 // are multiple entries.
Evan Cheng313d4b82008-02-23 00:33:04 +00001813 unsigned NumUses = MIHasUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001814 while (i != e && RewriteMIs[i].MI == MI) {
1815 assert(RewriteMIs[i].Index == index);
Evan Cheng313d4b82008-02-23 00:33:04 +00001816 bool isUse = RewriteMIs[i].HasUse;
1817 if (isUse) ++NumUses;
1818 MIHasUse |= isUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001819 MIHasDef |= RewriteMIs[i].HasDef;
1820 ++i;
1821 }
Evan Cheng81a03822007-11-17 00:40:40 +00001822 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng313d4b82008-02-23 00:33:04 +00001823
Evan Cheng0a891ed2008-05-23 23:00:04 +00001824 if (ImpUse && MI != ReMatDefMI) {
Evan Cheng313d4b82008-02-23 00:33:04 +00001825 // Re-matting an instruction with virtual register use. Update the
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001826 // register interval's spill weight to HUGE_VALF to prevent it from
1827 // being spilled.
Evan Cheng313d4b82008-02-23 00:33:04 +00001828 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001829 ImpLi.weight = HUGE_VALF;
Evan Cheng313d4b82008-02-23 00:33:04 +00001830 }
1831
Evan Cheng063284c2008-02-21 00:34:19 +00001832 unsigned MBBId = MBB->getNumber();
Evan Cheng018f9b02007-12-05 03:22:34 +00001833 unsigned ThisVReg = 0;
Evan Cheng70306f82007-12-03 09:58:48 +00001834 if (TrySplit) {
Owen Anderson28998312008-08-13 22:28:50 +00001835 DenseMap<unsigned,unsigned>::iterator NVI = MBBVRegsMap.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001836 if (NVI != MBBVRegsMap.end()) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001837 ThisVReg = NVI->second;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001838 // One common case:
1839 // x = use
1840 // ...
1841 // ...
1842 // def = ...
1843 // = use
1844 // It's better to start a new interval to avoid artifically
1845 // extend the new interval.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001846 if (MIHasDef && !MIHasUse) {
1847 MBBVRegsMap.erase(MBB->getNumber());
Evan Cheng018f9b02007-12-05 03:22:34 +00001848 ThisVReg = 0;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001849 }
1850 }
Evan Chengcada2452007-11-28 01:28:46 +00001851 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001852
1853 bool IsNew = ThisVReg == 0;
1854 if (IsNew) {
1855 // This ends the previous live interval. If all of its def / use
1856 // can be folded, give it a low spill weight.
1857 if (NewVReg && TrySplit && AllCanFold) {
1858 LiveInterval &nI = getOrCreateInterval(NewVReg);
1859 nI.weight /= 10.0F;
1860 }
1861 AllCanFold = true;
1862 }
1863 NewVReg = ThisVReg;
1864
Evan Cheng81a03822007-11-17 00:40:40 +00001865 bool HasDef = false;
1866 bool HasUse = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001867 bool CanFold = rewriteInstructionForSpills(li, I->valno, TrySplit,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001868 index, end, MI, ReMatOrigDefMI, ReMatDefMI,
1869 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
1870 CanDelete, vrm, rc, ReMatIds, loopInfo, NewVReg,
Evan Chengc781a242009-05-03 18:32:42 +00001871 ImpUse, HasDef, HasUse, MBBVRegsMap, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001872 if (!HasDef && !HasUse)
1873 continue;
1874
Evan Cheng018f9b02007-12-05 03:22:34 +00001875 AllCanFold &= CanFold;
1876
Evan Cheng81a03822007-11-17 00:40:40 +00001877 // Update weight of spill interval.
1878 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng70306f82007-12-03 09:58:48 +00001879 if (!TrySplit) {
Evan Cheng81a03822007-11-17 00:40:40 +00001880 // The spill weight is now infinity as it cannot be spilled again.
1881 nI.weight = HUGE_VALF;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001882 continue;
Evan Cheng81a03822007-11-17 00:40:40 +00001883 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001884
1885 // Keep track of the last def and first use in each MBB.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001886 if (HasDef) {
1887 if (MI != ReMatOrigDefMI || !CanDelete) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001888 bool HasKill = false;
1889 if (!HasUse)
1890 HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, getDefIndex(index));
1891 else {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001892 // If this is a two-address code, then this index starts a new VNInfo.
Evan Cheng3f32d652008-06-04 09:18:41 +00001893 const VNInfo *VNI = li.findDefinedVNInfo(getDefIndex(index));
Evan Cheng0cbb1162007-11-29 01:06:25 +00001894 if (VNI)
1895 HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, getDefIndex(index));
1896 }
Owen Anderson28998312008-08-13 22:28:50 +00001897 DenseMap<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Chenge3110d02007-12-01 04:42:39 +00001898 SpillIdxes.find(MBBId);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001899 if (!HasKill) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001900 if (SII == SpillIdxes.end()) {
1901 std::vector<SRInfo> S;
1902 S.push_back(SRInfo(index, NewVReg, true));
1903 SpillIdxes.insert(std::make_pair(MBBId, S));
1904 } else if (SII->second.back().vreg != NewVReg) {
1905 SII->second.push_back(SRInfo(index, NewVReg, true));
1906 } else if ((int)index > SII->second.back().index) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001907 // If there is an earlier def and this is a two-address
1908 // instruction, then it's not possible to fold the store (which
1909 // would also fold the load).
Evan Cheng1953d0c2007-11-29 10:12:14 +00001910 SRInfo &Info = SII->second.back();
1911 Info.index = index;
1912 Info.canFold = !HasUse;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001913 }
1914 SpillMBBs.set(MBBId);
Evan Chenge3110d02007-12-01 04:42:39 +00001915 } else if (SII != SpillIdxes.end() &&
1916 SII->second.back().vreg == NewVReg &&
1917 (int)index > SII->second.back().index) {
1918 // There is an earlier def that's not killed (must be two-address).
1919 // The spill is no longer needed.
1920 SII->second.pop_back();
1921 if (SII->second.empty()) {
1922 SpillIdxes.erase(MBBId);
1923 SpillMBBs.reset(MBBId);
1924 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001925 }
1926 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001927 }
1928
1929 if (HasUse) {
Owen Anderson28998312008-08-13 22:28:50 +00001930 DenseMap<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001931 SpillIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001932 if (SII != SpillIdxes.end() &&
1933 SII->second.back().vreg == NewVReg &&
1934 (int)index > SII->second.back().index)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001935 // Use(s) following the last def, it's not safe to fold the spill.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001936 SII->second.back().canFold = false;
Owen Anderson28998312008-08-13 22:28:50 +00001937 DenseMap<unsigned, std::vector<SRInfo> >::iterator RII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001938 RestoreIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001939 if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001940 // If we are splitting live intervals, only fold if it's the first
1941 // use and there isn't another use later in the MBB.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001942 RII->second.back().canFold = false;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001943 else if (IsNew) {
1944 // Only need a reload if there isn't an earlier def / use.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001945 if (RII == RestoreIdxes.end()) {
1946 std::vector<SRInfo> Infos;
1947 Infos.push_back(SRInfo(index, NewVReg, true));
1948 RestoreIdxes.insert(std::make_pair(MBBId, Infos));
1949 } else {
1950 RII->second.push_back(SRInfo(index, NewVReg, true));
1951 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001952 RestoreMBBs.set(MBBId);
1953 }
1954 }
1955
1956 // Update spill weight.
Evan Cheng22f07ff2007-12-11 02:09:15 +00001957 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Chengc3417602008-06-21 06:45:54 +00001958 nI.weight += getSpillWeight(HasDef, HasUse, loopDepth);
Evan Chengf2fbca62007-11-12 06:35:08 +00001959 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001960
1961 if (NewVReg && TrySplit && AllCanFold) {
1962 // If all of its def / use can be folded, give it a low spill weight.
1963 LiveInterval &nI = getOrCreateInterval(NewVReg);
1964 nI.weight /= 10.0F;
1965 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001966}
1967
Evan Cheng1953d0c2007-11-29 10:12:14 +00001968bool LiveIntervals::alsoFoldARestore(int Id, int index, unsigned vr,
1969 BitVector &RestoreMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001970 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001971 if (!RestoreMBBs[Id])
1972 return false;
1973 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1974 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1975 if (Restores[i].index == index &&
1976 Restores[i].vreg == vr &&
1977 Restores[i].canFold)
1978 return true;
1979 return false;
1980}
1981
1982void LiveIntervals::eraseRestoreInfo(int Id, int index, unsigned vr,
1983 BitVector &RestoreMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001984 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001985 if (!RestoreMBBs[Id])
1986 return;
1987 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1988 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1989 if (Restores[i].index == index && Restores[i].vreg)
1990 Restores[i].index = -1;
1991}
Evan Cheng81a03822007-11-17 00:40:40 +00001992
Evan Cheng4cce6b42008-04-11 17:53:36 +00001993/// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
1994/// spilled and create empty intervals for their uses.
1995void
1996LiveIntervals::handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
1997 const TargetRegisterClass* rc,
1998 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng419852c2008-04-03 16:39:43 +00001999 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
2000 re = mri_->reg_end(); ri != re; ) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00002001 MachineOperand &O = ri.getOperand();
Evan Cheng419852c2008-04-03 16:39:43 +00002002 MachineInstr *MI = &*ri;
2003 ++ri;
Evan Cheng4cce6b42008-04-11 17:53:36 +00002004 if (O.isDef()) {
2005 assert(MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF &&
2006 "Register def was not rewritten?");
2007 RemoveMachineInstrFromMaps(MI);
2008 vrm.RemoveMachineInstrFromMaps(MI);
2009 MI->eraseFromParent();
2010 } else {
2011 // This must be an use of an implicit_def so it's not part of the live
2012 // interval. Create a new empty live interval for it.
2013 // FIXME: Can we simply erase some of the instructions? e.g. Stores?
2014 unsigned NewVReg = mri_->createVirtualRegister(rc);
2015 vrm.grow();
2016 vrm.setIsImplicitlyDefined(NewVReg);
2017 NewLIs.push_back(&getOrCreateInterval(NewVReg));
2018 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
2019 MachineOperand &MO = MI->getOperand(i);
Evan Cheng4784f1f2009-06-30 08:49:04 +00002020 if (MO.isReg() && MO.getReg() == li.reg) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00002021 MO.setReg(NewVReg);
Evan Cheng4784f1f2009-06-30 08:49:04 +00002022 MO.setIsUndef();
Evan Cheng4784f1f2009-06-30 08:49:04 +00002023 }
Evan Cheng4cce6b42008-04-11 17:53:36 +00002024 }
2025 }
Evan Cheng419852c2008-04-03 16:39:43 +00002026 }
2027}
2028
Evan Chengf2fbca62007-11-12 06:35:08 +00002029std::vector<LiveInterval*> LiveIntervals::
Owen Andersond6664312008-08-18 18:05:32 +00002030addIntervalsForSpillsFast(const LiveInterval &li,
2031 const MachineLoopInfo *loopInfo,
Evan Chengc781a242009-05-03 18:32:42 +00002032 VirtRegMap &vrm) {
Owen Anderson17197312008-08-18 23:41:04 +00002033 unsigned slot = vrm.assignVirt2StackSlot(li.reg);
Owen Andersond6664312008-08-18 18:05:32 +00002034
2035 std::vector<LiveInterval*> added;
2036
2037 assert(li.weight != HUGE_VALF &&
2038 "attempt to spill already spilled interval!");
2039
Bill Wendling8e6179f2009-08-22 20:18:03 +00002040 DEBUG({
2041 errs() << "\t\t\t\tadding intervals for spills for interval: ";
2042 li.dump();
2043 errs() << '\n';
2044 });
Owen Andersond6664312008-08-18 18:05:32 +00002045
2046 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
2047
Owen Andersona41e47a2008-08-19 22:12:11 +00002048 MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg);
2049 while (RI != mri_->reg_end()) {
2050 MachineInstr* MI = &*RI;
2051
2052 SmallVector<unsigned, 2> Indices;
2053 bool HasUse = false;
2054 bool HasDef = false;
2055
2056 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
2057 MachineOperand& mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00002058 if (!mop.isReg() || mop.getReg() != li.reg) continue;
Owen Andersona41e47a2008-08-19 22:12:11 +00002059
2060 HasUse |= MI->getOperand(i).isUse();
2061 HasDef |= MI->getOperand(i).isDef();
2062
2063 Indices.push_back(i);
2064 }
2065
2066 if (!tryFoldMemoryOperand(MI, vrm, NULL, getInstructionIndex(MI),
2067 Indices, true, slot, li.reg)) {
2068 unsigned NewVReg = mri_->createVirtualRegister(rc);
Owen Anderson9a032932008-08-18 21:20:32 +00002069 vrm.grow();
Owen Anderson17197312008-08-18 23:41:04 +00002070 vrm.assignVirt2StackSlot(NewVReg, slot);
2071
Owen Andersona41e47a2008-08-19 22:12:11 +00002072 // create a new register for this spill
2073 LiveInterval &nI = getOrCreateInterval(NewVReg);
Owen Andersond6664312008-08-18 18:05:32 +00002074
Owen Andersona41e47a2008-08-19 22:12:11 +00002075 // the spill weight is now infinity as it
2076 // cannot be spilled again
2077 nI.weight = HUGE_VALF;
2078
2079 // Rewrite register operands to use the new vreg.
2080 for (SmallVectorImpl<unsigned>::iterator I = Indices.begin(),
2081 E = Indices.end(); I != E; ++I) {
2082 MI->getOperand(*I).setReg(NewVReg);
2083
2084 if (MI->getOperand(*I).isUse())
2085 MI->getOperand(*I).setIsKill(true);
2086 }
2087
2088 // Fill in the new live interval.
2089 unsigned index = getInstructionIndex(MI);
2090 if (HasUse) {
2091 LiveRange LR(getLoadIndex(index), getUseIndex(index),
Lang Hames857c4e02009-06-17 21:01:20 +00002092 nI.getNextValue(0, 0, false, getVNInfoAllocator()));
Bill Wendling8e6179f2009-08-22 20:18:03 +00002093 DEBUG(errs() << " +" << LR);
Owen Andersona41e47a2008-08-19 22:12:11 +00002094 nI.addRange(LR);
2095 vrm.addRestorePoint(NewVReg, MI);
2096 }
2097 if (HasDef) {
2098 LiveRange LR(getDefIndex(index), getStoreIndex(index),
Lang Hames857c4e02009-06-17 21:01:20 +00002099 nI.getNextValue(0, 0, false, getVNInfoAllocator()));
Bill Wendling8e6179f2009-08-22 20:18:03 +00002100 DEBUG(errs() << " +" << LR);
Owen Andersona41e47a2008-08-19 22:12:11 +00002101 nI.addRange(LR);
2102 vrm.addSpillPoint(NewVReg, true, MI);
2103 }
2104
Owen Anderson17197312008-08-18 23:41:04 +00002105 added.push_back(&nI);
Owen Anderson8dc2cbe2008-08-18 18:38:12 +00002106
Bill Wendling8e6179f2009-08-22 20:18:03 +00002107 DEBUG({
2108 errs() << "\t\t\t\tadded new interval: ";
2109 nI.dump();
2110 errs() << '\n';
2111 });
Owen Andersona41e47a2008-08-19 22:12:11 +00002112 }
Owen Anderson9a032932008-08-18 21:20:32 +00002113
Owen Anderson9a032932008-08-18 21:20:32 +00002114
Owen Andersona41e47a2008-08-19 22:12:11 +00002115 RI = mri_->reg_begin(li.reg);
Owen Andersond6664312008-08-18 18:05:32 +00002116 }
Owen Andersond6664312008-08-18 18:05:32 +00002117
2118 return added;
2119}
2120
2121std::vector<LiveInterval*> LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00002122addIntervalsForSpills(const LiveInterval &li,
Evan Chengdc377862008-09-30 15:44:16 +00002123 SmallVectorImpl<LiveInterval*> &SpillIs,
Evan Chengc781a242009-05-03 18:32:42 +00002124 const MachineLoopInfo *loopInfo, VirtRegMap &vrm) {
Owen Andersonae339ba2008-08-19 00:17:30 +00002125
2126 if (EnableFastSpilling)
Evan Chengc781a242009-05-03 18:32:42 +00002127 return addIntervalsForSpillsFast(li, loopInfo, vrm);
Owen Andersonae339ba2008-08-19 00:17:30 +00002128
Evan Chengf2fbca62007-11-12 06:35:08 +00002129 assert(li.weight != HUGE_VALF &&
2130 "attempt to spill already spilled interval!");
2131
Bill Wendling8e6179f2009-08-22 20:18:03 +00002132 DEBUG({
2133 errs() << "\t\t\t\tadding intervals for spills for interval: ";
2134 li.print(errs(), tri_);
2135 errs() << '\n';
2136 });
Evan Chengf2fbca62007-11-12 06:35:08 +00002137
Evan Cheng72eeb942008-12-05 17:00:16 +00002138 // Each bit specify whether a spill is required in the MBB.
Evan Cheng81a03822007-11-17 00:40:40 +00002139 BitVector SpillMBBs(mf_->getNumBlockIDs());
Owen Anderson28998312008-08-13 22:28:50 +00002140 DenseMap<unsigned, std::vector<SRInfo> > SpillIdxes;
Evan Cheng0cbb1162007-11-29 01:06:25 +00002141 BitVector RestoreMBBs(mf_->getNumBlockIDs());
Owen Anderson28998312008-08-13 22:28:50 +00002142 DenseMap<unsigned, std::vector<SRInfo> > RestoreIdxes;
2143 DenseMap<unsigned,unsigned> MBBVRegsMap;
Evan Chengf2fbca62007-11-12 06:35:08 +00002144 std::vector<LiveInterval*> NewLIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00002145 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
Evan Chengf2fbca62007-11-12 06:35:08 +00002146
2147 unsigned NumValNums = li.getNumValNums();
2148 SmallVector<MachineInstr*, 4> ReMatDefs;
2149 ReMatDefs.resize(NumValNums, NULL);
2150 SmallVector<MachineInstr*, 4> ReMatOrigDefs;
2151 ReMatOrigDefs.resize(NumValNums, NULL);
2152 SmallVector<int, 4> ReMatIds;
2153 ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
2154 BitVector ReMatDelete(NumValNums);
2155 unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
2156
Evan Cheng81a03822007-11-17 00:40:40 +00002157 // Spilling a split live interval. It cannot be split any further. Also,
2158 // it's also guaranteed to be a single val# / range interval.
2159 if (vrm.getPreSplitReg(li.reg)) {
2160 vrm.setIsSplitFromReg(li.reg, 0);
Evan Chengd120ffd2007-12-05 10:24:35 +00002161 // Unset the split kill marker on the last use.
2162 unsigned KillIdx = vrm.getKillPoint(li.reg);
2163 if (KillIdx) {
2164 MachineInstr *KillMI = getInstructionFromIndex(KillIdx);
2165 assert(KillMI && "Last use disappeared?");
2166 int KillOp = KillMI->findRegisterUseOperandIdx(li.reg, true);
2167 assert(KillOp != -1 && "Last use disappeared?");
Chris Lattnerf7382302007-12-30 21:56:09 +00002168 KillMI->getOperand(KillOp).setIsKill(false);
Evan Chengd120ffd2007-12-05 10:24:35 +00002169 }
Evan Chengadf85902007-12-05 09:51:10 +00002170 vrm.removeKillPoint(li.reg);
Evan Cheng81a03822007-11-17 00:40:40 +00002171 bool DefIsReMat = vrm.isReMaterialized(li.reg);
2172 Slot = vrm.getStackSlot(li.reg);
2173 assert(Slot != VirtRegMap::MAX_STACK_SLOT);
2174 MachineInstr *ReMatDefMI = DefIsReMat ?
2175 vrm.getReMaterializedMI(li.reg) : NULL;
2176 int LdSlot = 0;
2177 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
2178 bool isLoad = isLoadSS ||
Dan Gohman15511cf2008-12-03 18:15:48 +00002179 (DefIsReMat && (ReMatDefMI->getDesc().canFoldAsLoad()));
Evan Cheng81a03822007-11-17 00:40:40 +00002180 bool IsFirstRange = true;
2181 for (LiveInterval::Ranges::const_iterator
2182 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
2183 // If this is a split live interval with multiple ranges, it means there
2184 // are two-address instructions that re-defined the value. Only the
2185 // first def can be rematerialized!
2186 if (IsFirstRange) {
Evan Chengcb3c3302007-11-29 23:02:50 +00002187 // Note ReMatOrigDefMI has already been deleted.
Evan Cheng81a03822007-11-17 00:40:40 +00002188 rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
2189 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00002190 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00002191 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Chengc781a242009-05-03 18:32:42 +00002192 MBBVRegsMap, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00002193 } else {
2194 rewriteInstructionsForSpills(li, false, I, NULL, 0,
2195 Slot, 0, false, false, false,
Evan Chengd70dbb52008-02-22 09:24:50 +00002196 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00002197 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Chengc781a242009-05-03 18:32:42 +00002198 MBBVRegsMap, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00002199 }
2200 IsFirstRange = false;
2201 }
Evan Cheng419852c2008-04-03 16:39:43 +00002202
Evan Cheng4cce6b42008-04-11 17:53:36 +00002203 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00002204 return NewLIs;
2205 }
2206
2207 bool TrySplit = SplitAtBB && !intervalIsInOneMBB(li);
Evan Cheng0cbb1162007-11-29 01:06:25 +00002208 if (SplitLimit != -1 && (int)numSplits >= SplitLimit)
2209 TrySplit = false;
2210 if (TrySplit)
2211 ++numSplits;
Evan Chengf2fbca62007-11-12 06:35:08 +00002212 bool NeedStackSlot = false;
2213 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
2214 i != e; ++i) {
2215 const VNInfo *VNI = *i;
2216 unsigned VN = VNI->id;
Lang Hames857c4e02009-06-17 21:01:20 +00002217 if (VNI->isUnused())
Evan Chengf2fbca62007-11-12 06:35:08 +00002218 continue; // Dead val#.
2219 // Is the def for the val# rematerializable?
Lang Hames857c4e02009-06-17 21:01:20 +00002220 MachineInstr *ReMatDefMI = VNI->isDefAccurate()
2221 ? getInstructionFromIndex(VNI->def) : 0;
Evan Cheng5ef3a042007-12-06 00:01:56 +00002222 bool dummy;
Evan Chengdc377862008-09-30 15:44:16 +00002223 if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, SpillIs, dummy)) {
Evan Chengf2fbca62007-11-12 06:35:08 +00002224 // Remember how to remat the def of this val#.
Evan Cheng81a03822007-11-17 00:40:40 +00002225 ReMatOrigDefs[VN] = ReMatDefMI;
Dan Gohman2c3f7ae2008-07-17 23:49:46 +00002226 // Original def may be modified so we have to make a copy here.
Evan Cheng1ed99222008-07-19 00:37:25 +00002227 MachineInstr *Clone = mf_->CloneMachineInstr(ReMatDefMI);
2228 ClonedMIs.push_back(Clone);
2229 ReMatDefs[VN] = Clone;
Evan Chengf2fbca62007-11-12 06:35:08 +00002230
2231 bool CanDelete = true;
Lang Hames857c4e02009-06-17 21:01:20 +00002232 if (VNI->hasPHIKill()) {
Evan Chengc3fc7d92007-11-29 09:49:23 +00002233 // A kill is a phi node, not all of its uses can be rematerialized.
Evan Chengf2fbca62007-11-12 06:35:08 +00002234 // It must not be deleted.
Evan Chengc3fc7d92007-11-29 09:49:23 +00002235 CanDelete = false;
2236 // Need a stack slot if there is any live range where uses cannot be
2237 // rematerialized.
2238 NeedStackSlot = true;
Evan Chengf2fbca62007-11-12 06:35:08 +00002239 }
Evan Chengf2fbca62007-11-12 06:35:08 +00002240 if (CanDelete)
2241 ReMatDelete.set(VN);
2242 } else {
2243 // Need a stack slot if there is any live range where uses cannot be
2244 // rematerialized.
2245 NeedStackSlot = true;
2246 }
2247 }
2248
2249 // One stack slot per live interval.
Owen Andersonb98bbb72009-03-26 18:53:38 +00002250 if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0) {
2251 if (vrm.getStackSlot(li.reg) == VirtRegMap::NO_STACK_SLOT)
2252 Slot = vrm.assignVirt2StackSlot(li.reg);
2253
2254 // This case only occurs when the prealloc splitter has already assigned
2255 // a stack slot to this vreg.
2256 else
2257 Slot = vrm.getStackSlot(li.reg);
2258 }
Evan Chengf2fbca62007-11-12 06:35:08 +00002259
2260 // Create new intervals and rewrite defs and uses.
2261 for (LiveInterval::Ranges::const_iterator
2262 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Evan Cheng81a03822007-11-17 00:40:40 +00002263 MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id];
2264 MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id];
2265 bool DefIsReMat = ReMatDefMI != NULL;
Evan Chengf2fbca62007-11-12 06:35:08 +00002266 bool CanDelete = ReMatDelete[I->valno->id];
2267 int LdSlot = 0;
Evan Cheng81a03822007-11-17 00:40:40 +00002268 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
Evan Chengf2fbca62007-11-12 06:35:08 +00002269 bool isLoad = isLoadSS ||
Dan Gohman15511cf2008-12-03 18:15:48 +00002270 (DefIsReMat && ReMatDefMI->getDesc().canFoldAsLoad());
Evan Cheng81a03822007-11-17 00:40:40 +00002271 rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
Evan Cheng0cbb1162007-11-29 01:06:25 +00002272 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00002273 CanDelete, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00002274 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Chengc781a242009-05-03 18:32:42 +00002275 MBBVRegsMap, NewLIs);
Evan Chengf2fbca62007-11-12 06:35:08 +00002276 }
2277
Evan Cheng0cbb1162007-11-29 01:06:25 +00002278 // Insert spills / restores if we are splitting.
Evan Cheng419852c2008-04-03 16:39:43 +00002279 if (!TrySplit) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00002280 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng1953d0c2007-11-29 10:12:14 +00002281 return NewLIs;
Evan Cheng419852c2008-04-03 16:39:43 +00002282 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002283
Evan Chengb50bb8c2007-12-05 08:16:32 +00002284 SmallPtrSet<LiveInterval*, 4> AddedKill;
Evan Chengaee4af62007-12-02 08:30:39 +00002285 SmallVector<unsigned, 2> Ops;
Evan Cheng1953d0c2007-11-29 10:12:14 +00002286 if (NeedStackSlot) {
2287 int Id = SpillMBBs.find_first();
2288 while (Id != -1) {
2289 std::vector<SRInfo> &spills = SpillIdxes[Id];
2290 for (unsigned i = 0, e = spills.size(); i != e; ++i) {
2291 int index = spills[i].index;
2292 unsigned VReg = spills[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00002293 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng0cbb1162007-11-29 01:06:25 +00002294 bool isReMat = vrm.isReMaterialized(VReg);
2295 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00002296 bool CanFold = false;
2297 bool FoundUse = false;
2298 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00002299 if (spills[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00002300 CanFold = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00002301 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
2302 MachineOperand &MO = MI->getOperand(j);
Dan Gohmand735b802008-10-03 15:45:36 +00002303 if (!MO.isReg() || MO.getReg() != VReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00002304 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00002305
2306 Ops.push_back(j);
2307 if (MO.isDef())
Evan Chengcddbb832007-11-30 21:23:43 +00002308 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00002309 if (isReMat ||
2310 (!FoundUse && !alsoFoldARestore(Id, index, VReg,
2311 RestoreMBBs, RestoreIdxes))) {
2312 // MI has two-address uses of the same register. If the use
2313 // isn't the first and only use in the BB, then we can't fold
2314 // it. FIXME: Move this to rewriteInstructionsForSpills.
2315 CanFold = false;
Evan Chengcddbb832007-11-30 21:23:43 +00002316 break;
2317 }
Evan Chengaee4af62007-12-02 08:30:39 +00002318 FoundUse = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00002319 }
2320 }
2321 // Fold the store into the def if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00002322 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00002323 if (CanFold && !Ops.empty()) {
2324 if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
Evan Chengcddbb832007-11-30 21:23:43 +00002325 Folded = true;
Sebastian Redl48fe6352009-03-19 23:26:52 +00002326 if (FoundUse) {
Evan Chengaee4af62007-12-02 08:30:39 +00002327 // Also folded uses, do not issue a load.
2328 eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
Evan Chengf38d14f2007-12-05 09:05:34 +00002329 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
2330 }
Evan Cheng597d10d2007-12-04 00:32:23 +00002331 nI.removeRange(getDefIndex(index), getStoreIndex(index));
Evan Chengcddbb832007-11-30 21:23:43 +00002332 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002333 }
2334
Evan Cheng7e073ba2008-04-09 20:57:25 +00002335 // Otherwise tell the spiller to issue a spill.
Evan Chengb50bb8c2007-12-05 08:16:32 +00002336 if (!Folded) {
2337 LiveRange *LR = &nI.ranges[nI.ranges.size()-1];
2338 bool isKill = LR->end == getStoreIndex(index);
Evan Chengb0a6f622008-05-20 08:10:37 +00002339 if (!MI->registerDefIsDead(nI.reg))
2340 // No need to spill a dead def.
2341 vrm.addSpillPoint(VReg, isKill, MI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002342 if (isKill)
2343 AddedKill.insert(&nI);
2344 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002345 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002346 Id = SpillMBBs.find_next(Id);
Evan Cheng0cbb1162007-11-29 01:06:25 +00002347 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002348 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002349
Evan Cheng1953d0c2007-11-29 10:12:14 +00002350 int Id = RestoreMBBs.find_first();
2351 while (Id != -1) {
2352 std::vector<SRInfo> &restores = RestoreIdxes[Id];
2353 for (unsigned i = 0, e = restores.size(); i != e; ++i) {
2354 int index = restores[i].index;
2355 if (index == -1)
2356 continue;
2357 unsigned VReg = restores[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00002358 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng9c3c2212008-06-06 07:54:39 +00002359 bool isReMat = vrm.isReMaterialized(VReg);
Evan Cheng81a03822007-11-17 00:40:40 +00002360 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00002361 bool CanFold = false;
2362 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00002363 if (restores[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00002364 CanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00002365 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
2366 MachineOperand &MO = MI->getOperand(j);
Dan Gohmand735b802008-10-03 15:45:36 +00002367 if (!MO.isReg() || MO.getReg() != VReg)
Evan Cheng81a03822007-11-17 00:40:40 +00002368 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00002369
Evan Cheng0cbb1162007-11-29 01:06:25 +00002370 if (MO.isDef()) {
Evan Chengaee4af62007-12-02 08:30:39 +00002371 // If this restore were to be folded, it would have been folded
2372 // already.
2373 CanFold = false;
Evan Cheng81a03822007-11-17 00:40:40 +00002374 break;
2375 }
Evan Chengaee4af62007-12-02 08:30:39 +00002376 Ops.push_back(j);
Evan Cheng81a03822007-11-17 00:40:40 +00002377 }
2378 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002379
2380 // Fold the load into the use if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00002381 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00002382 if (CanFold && !Ops.empty()) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00002383 if (!isReMat)
Evan Chengaee4af62007-12-02 08:30:39 +00002384 Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg);
2385 else {
Evan Cheng0cbb1162007-11-29 01:06:25 +00002386 MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg);
2387 int LdSlot = 0;
2388 bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
2389 // If the rematerializable def is a load, also try to fold it.
Dan Gohman15511cf2008-12-03 18:15:48 +00002390 if (isLoadSS || ReMatDefMI->getDesc().canFoldAsLoad())
Evan Chengaee4af62007-12-02 08:30:39 +00002391 Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
2392 Ops, isLoadSS, LdSlot, VReg);
Evan Cheng650d7f32008-12-05 17:41:31 +00002393 if (!Folded) {
2394 unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI);
2395 if (ImpUse) {
2396 // Re-matting an instruction with virtual register use. Add the
2397 // register as an implicit use on the use MI and update the register
2398 // interval's spill weight to HUGE_VALF to prevent it from being
2399 // spilled.
2400 LiveInterval &ImpLi = getInterval(ImpUse);
2401 ImpLi.weight = HUGE_VALF;
2402 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
2403 }
Evan Chengd70dbb52008-02-22 09:24:50 +00002404 }
Evan Chengaee4af62007-12-02 08:30:39 +00002405 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002406 }
2407 // If folding is not possible / failed, then tell the spiller to issue a
2408 // load / rematerialization for us.
Evan Cheng597d10d2007-12-04 00:32:23 +00002409 if (Folded)
2410 nI.removeRange(getLoadIndex(index), getUseIndex(index)+1);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002411 else
Evan Cheng0cbb1162007-11-29 01:06:25 +00002412 vrm.addRestorePoint(VReg, MI);
Evan Cheng81a03822007-11-17 00:40:40 +00002413 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002414 Id = RestoreMBBs.find_next(Id);
Evan Cheng81a03822007-11-17 00:40:40 +00002415 }
2416
Evan Chengb50bb8c2007-12-05 08:16:32 +00002417 // Finalize intervals: add kills, finalize spill weights, and filter out
2418 // dead intervals.
Evan Cheng597d10d2007-12-04 00:32:23 +00002419 std::vector<LiveInterval*> RetNewLIs;
2420 for (unsigned i = 0, e = NewLIs.size(); i != e; ++i) {
2421 LiveInterval *LI = NewLIs[i];
2422 if (!LI->empty()) {
Owen Anderson496bac52008-07-23 19:47:27 +00002423 LI->weight /= InstrSlots::NUM * getApproximateInstructionCount(*LI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002424 if (!AddedKill.count(LI)) {
2425 LiveRange *LR = &LI->ranges[LI->ranges.size()-1];
Evan Chengd120ffd2007-12-05 10:24:35 +00002426 unsigned LastUseIdx = getBaseIndex(LR->end);
2427 MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx);
Evan Cheng6130f662008-03-05 00:59:57 +00002428 int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg, false);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002429 assert(UseIdx != -1);
Evan Chenga24752f2009-03-19 20:30:06 +00002430 if (!LastUse->isRegTiedToDefOperand(UseIdx)) {
Evan Chengb50bb8c2007-12-05 08:16:32 +00002431 LastUse->getOperand(UseIdx).setIsKill();
Evan Chengd120ffd2007-12-05 10:24:35 +00002432 vrm.addKillPoint(LI->reg, LastUseIdx);
Evan Chengadf85902007-12-05 09:51:10 +00002433 }
Evan Chengb50bb8c2007-12-05 08:16:32 +00002434 }
Evan Cheng597d10d2007-12-04 00:32:23 +00002435 RetNewLIs.push_back(LI);
2436 }
2437 }
Evan Cheng81a03822007-11-17 00:40:40 +00002438
Evan Cheng4cce6b42008-04-11 17:53:36 +00002439 handleSpilledImpDefs(li, vrm, rc, RetNewLIs);
Evan Cheng597d10d2007-12-04 00:32:23 +00002440 return RetNewLIs;
Evan Chengf2fbca62007-11-12 06:35:08 +00002441}
Evan Cheng676dd7c2008-03-11 07:19:34 +00002442
2443/// hasAllocatableSuperReg - Return true if the specified physical register has
2444/// any super register that's allocatable.
2445bool LiveIntervals::hasAllocatableSuperReg(unsigned Reg) const {
2446 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS)
2447 if (allocatableRegs_[*AS] && hasInterval(*AS))
2448 return true;
2449 return false;
2450}
2451
2452/// getRepresentativeReg - Find the largest super register of the specified
2453/// physical register.
2454unsigned LiveIntervals::getRepresentativeReg(unsigned Reg) const {
2455 // Find the largest super-register that is allocatable.
2456 unsigned BestReg = Reg;
2457 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS) {
2458 unsigned SuperReg = *AS;
2459 if (!hasAllocatableSuperReg(SuperReg) && hasInterval(SuperReg)) {
2460 BestReg = SuperReg;
2461 break;
2462 }
2463 }
2464 return BestReg;
2465}
2466
2467/// getNumConflictsWithPhysReg - Return the number of uses and defs of the
2468/// specified interval that conflicts with the specified physical register.
2469unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li,
2470 unsigned PhysReg) const {
2471 unsigned NumConflicts = 0;
2472 const LiveInterval &pli = getInterval(getRepresentativeReg(PhysReg));
2473 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
2474 E = mri_->reg_end(); I != E; ++I) {
2475 MachineOperand &O = I.getOperand();
2476 MachineInstr *MI = O.getParent();
2477 unsigned Index = getInstructionIndex(MI);
2478 if (pli.liveAt(Index))
2479 ++NumConflicts;
2480 }
2481 return NumConflicts;
2482}
2483
2484/// spillPhysRegAroundRegDefsUses - Spill the specified physical register
Evan Cheng2824a652009-03-23 18:24:37 +00002485/// around all defs and uses of the specified interval. Return true if it
2486/// was able to cut its interval.
2487bool LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
Evan Cheng676dd7c2008-03-11 07:19:34 +00002488 unsigned PhysReg, VirtRegMap &vrm) {
2489 unsigned SpillReg = getRepresentativeReg(PhysReg);
2490
2491 for (const unsigned *AS = tri_->getAliasSet(PhysReg); *AS; ++AS)
2492 // If there are registers which alias PhysReg, but which are not a
2493 // sub-register of the chosen representative super register. Assert
2494 // since we can't handle it yet.
Dan Gohman70f2f652009-04-13 15:22:29 +00002495 assert(*AS == SpillReg || !allocatableRegs_[*AS] || !hasInterval(*AS) ||
Evan Cheng676dd7c2008-03-11 07:19:34 +00002496 tri_->isSuperRegister(*AS, SpillReg));
2497
Evan Cheng2824a652009-03-23 18:24:37 +00002498 bool Cut = false;
Evan Cheng676dd7c2008-03-11 07:19:34 +00002499 LiveInterval &pli = getInterval(SpillReg);
2500 SmallPtrSet<MachineInstr*, 8> SeenMIs;
2501 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
2502 E = mri_->reg_end(); I != E; ++I) {
2503 MachineOperand &O = I.getOperand();
2504 MachineInstr *MI = O.getParent();
2505 if (SeenMIs.count(MI))
2506 continue;
2507 SeenMIs.insert(MI);
2508 unsigned Index = getInstructionIndex(MI);
2509 if (pli.liveAt(Index)) {
2510 vrm.addEmergencySpill(SpillReg, MI);
Evan Cheng5a3c6a82009-01-29 02:20:59 +00002511 unsigned StartIdx = getLoadIndex(Index);
2512 unsigned EndIdx = getStoreIndex(Index)+1;
Evan Cheng2824a652009-03-23 18:24:37 +00002513 if (pli.isInOneLiveRange(StartIdx, EndIdx)) {
Evan Cheng5a3c6a82009-01-29 02:20:59 +00002514 pli.removeRange(StartIdx, EndIdx);
Evan Cheng2824a652009-03-23 18:24:37 +00002515 Cut = true;
2516 } else {
Torok Edwin7d696d82009-07-11 13:10:19 +00002517 std::string msg;
2518 raw_string_ostream Msg(msg);
2519 Msg << "Ran out of registers during register allocation!";
Evan Cheng5a3c6a82009-01-29 02:20:59 +00002520 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
Torok Edwin7d696d82009-07-11 13:10:19 +00002521 Msg << "\nPlease check your inline asm statement for invalid "
Evan Cheng5a3c6a82009-01-29 02:20:59 +00002522 << "constraints:\n";
Torok Edwin7d696d82009-07-11 13:10:19 +00002523 MI->print(Msg, tm_);
Evan Cheng5a3c6a82009-01-29 02:20:59 +00002524 }
Torok Edwin7d696d82009-07-11 13:10:19 +00002525 llvm_report_error(Msg.str());
Evan Cheng5a3c6a82009-01-29 02:20:59 +00002526 }
Evan Cheng676dd7c2008-03-11 07:19:34 +00002527 for (const unsigned* AS = tri_->getSubRegisters(SpillReg); *AS; ++AS) {
2528 if (!hasInterval(*AS))
2529 continue;
2530 LiveInterval &spli = getInterval(*AS);
2531 if (spli.liveAt(Index))
2532 spli.removeRange(getLoadIndex(Index), getStoreIndex(Index)+1);
2533 }
2534 }
2535 }
Evan Cheng2824a652009-03-23 18:24:37 +00002536 return Cut;
Evan Cheng676dd7c2008-03-11 07:19:34 +00002537}
Owen Andersonc4dc1322008-06-05 17:15:43 +00002538
2539LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
Lang Hamesffd13262009-07-09 03:57:02 +00002540 MachineInstr* startInst) {
Owen Andersonc4dc1322008-06-05 17:15:43 +00002541 LiveInterval& Interval = getOrCreateInterval(reg);
2542 VNInfo* VN = Interval.getNextValue(
2543 getInstructionIndex(startInst) + InstrSlots::DEF,
Lang Hames857c4e02009-06-17 21:01:20 +00002544 startInst, true, getVNInfoAllocator());
2545 VN->setHasPHIKill(true);
Lang Hamesffd13262009-07-09 03:57:02 +00002546 VN->kills.push_back(
2547 VNInfo::KillInfo(terminatorGaps[startInst->getParent()], true));
Owen Andersonc4dc1322008-06-05 17:15:43 +00002548 LiveRange LR(getInstructionIndex(startInst) + InstrSlots::DEF,
2549 getMBBEndIdx(startInst->getParent()) + 1, VN);
2550 Interval.addRange(LR);
2551
2552 return LR;
2553}
David Greeneb5257662009-08-03 21:55:09 +00002554