blob: a60d34f58a918fb3fe74865cc29f3efb54e4a49a [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +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"
19#include "llvm/CodeGen/LiveIntervalAnalysis.h"
20#include "VirtRegMap.h"
21#include "llvm/Value.h"
Dan Gohmane3427532008-07-25 00:02:30 +000022#include "llvm/Analysis/AliasAnalysis.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000023#include "llvm/CodeGen/LiveVariables.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
25#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng65219822009-07-01 01:59:31 +000026#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Cheng26d17df2007-12-11 02:09:15 +000027#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohman4e3bb1b2009-09-25 20:36:54 +000028#include "llvm/CodeGen/MachineMemOperand.h"
Chris Lattner1b989192007-12-31 04:13:23 +000029#include "llvm/CodeGen/MachineRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030#include "llvm/CodeGen/Passes.h"
Lang Hamesd6a717c2009-11-03 23:52:08 +000031#include "llvm/CodeGen/ProcessImplicitDefs.h"
Dan Gohman1e57df32008-02-10 18:45:23 +000032#include "llvm/Target/TargetRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#include "llvm/Target/TargetInstrInfo.h"
34#include "llvm/Target/TargetMachine.h"
Owen Andersonbac9ae22008-10-07 20:22:28 +000035#include "llvm/Target/TargetOptions.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000036#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000038#include "llvm/Support/ErrorHandling.h"
39#include "llvm/Support/raw_ostream.h"
Evan Cheng65219822009-07-01 01:59:31 +000040#include "llvm/ADT/DepthFirstIterator.h"
41#include "llvm/ADT/SmallSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000042#include "llvm/ADT/Statistic.h"
43#include "llvm/ADT/STLExtras.h"
44#include <algorithm>
Lang Hames86f6afb2009-06-02 16:53:25 +000045#include <limits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046#include <cmath>
47using namespace llvm;
48
Dan Gohman089efff2008-05-13 00:00:25 +000049// Hidden options for help debugging.
50static cl::opt<bool> DisableReMat("disable-rematerialization",
51 cl::init(false), cl::Hidden);
Evan Chengcecc8222007-11-17 00:40:40 +000052
Owen Andersona9205692008-08-19 00:17:30 +000053static cl::opt<bool> EnableFastSpilling("fast-spill",
54 cl::init(false), cl::Hidden);
55
Evan Cheng48ac7b92009-11-09 06:49:37 +000056static cl::opt<bool> EarlyCoalescing("early-coalescing",
57 cl::init(false), cl::Hidden);
Evan Cheng95320812009-09-14 21:33:42 +000058
59static cl::opt<int> CoalescingLimit("early-coalescing-limit",
60 cl::init(-1), cl::Hidden);
61
62STATISTIC(numIntervals , "Number of original intervals");
63STATISTIC(numFolds , "Number of loads/stores folded into instructions");
64STATISTIC(numSplits , "Number of intervals split");
65STATISTIC(numCoalescing, "Number of early coalescing performed");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000066
67char LiveIntervals::ID = 0;
Dan Gohman089efff2008-05-13 00:00:25 +000068static RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000069
70void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohmanecb436f2009-07-31 23:37:33 +000071 AU.setPreservesCFG();
Dan Gohmane3427532008-07-25 00:02:30 +000072 AU.addRequired<AliasAnalysis>();
73 AU.addPreserved<AliasAnalysis>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000074 AU.addPreserved<LiveVariables>();
75 AU.addRequired<LiveVariables>();
Bill Wendling62264362008-01-04 20:54:55 +000076 AU.addPreservedID(MachineLoopInfoID);
77 AU.addPreservedID(MachineDominatorsID);
Owen Andersonbac9ae22008-10-07 20:22:28 +000078
79 if (!StrongPHIElim) {
80 AU.addPreservedID(PHIEliminationID);
81 AU.addRequiredID(PHIEliminationID);
82 }
83
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084 AU.addRequiredID(TwoAddressInstructionPassID);
Lang Hamesd6a717c2009-11-03 23:52:08 +000085 AU.addPreserved<ProcessImplicitDefs>();
86 AU.addRequired<ProcessImplicitDefs>();
87 AU.addPreserved<SlotIndexes>();
88 AU.addRequiredTransitive<SlotIndexes>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000089 MachineFunctionPass::getAnalysisUsage(AU);
90}
91
92void LiveIntervals::releaseMemory() {
Owen Anderson348d1d82008-08-13 21:49:13 +000093 // Free the live intervals themselves.
Owen Anderson36bb2ba2008-08-13 22:08:30 +000094 for (DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.begin(),
Owen Anderson348d1d82008-08-13 21:49:13 +000095 E = r2iMap_.end(); I != E; ++I)
96 delete I->second;
97
Dan Gohmanf17a25c2007-07-18 16:29:46 +000098 r2iMap_.clear();
Evan Cheng95320812009-09-14 21:33:42 +000099 phiJoinCopies.clear();
Lang Hamesd2bd8622009-07-09 03:57:02 +0000100
Evan Cheng27344d42007-09-06 01:07:24 +0000101 // Release VNInfo memroy regions after all VNInfo objects are dtor'd.
102 VNInfoAllocator.Reset();
Evan Cheng95320812009-09-14 21:33:42 +0000103 while (!CloneMIs.empty()) {
104 MachineInstr *MI = CloneMIs.back();
105 CloneMIs.pop_back();
Evan Cheng4ce1a522008-07-19 00:37:25 +0000106 mf_->DeleteMachineInstr(MI);
107 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000108}
109
Owen Andersonf47fbec2008-05-28 20:54:50 +0000110/// runOnMachineFunction - Register allocate the whole function
111///
112bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
113 mf_ = &fn;
114 mri_ = &mf_->getRegInfo();
115 tm_ = &fn.getTarget();
116 tri_ = tm_->getRegisterInfo();
117 tii_ = tm_->getInstrInfo();
Dan Gohmane3427532008-07-25 00:02:30 +0000118 aa_ = &getAnalysis<AliasAnalysis>();
Owen Andersonf47fbec2008-05-28 20:54:50 +0000119 lv_ = &getAnalysis<LiveVariables>();
Lang Hamesd6a717c2009-11-03 23:52:08 +0000120 indexes_ = &getAnalysis<SlotIndexes>();
Owen Andersonf47fbec2008-05-28 20:54:50 +0000121 allocatableRegs_ = tri_->getAllocatableSet(fn);
122
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000123 computeIntervals();
Evan Cheng95320812009-09-14 21:33:42 +0000124 performEarlyCoalescing();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000125
126 numIntervals += getNumIntervals();
127
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000128 DEBUG(dump());
129 return true;
130}
131
132/// print - Implement the dump method.
Chris Lattner397f4562009-08-23 06:03:38 +0000133void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
Chris Lattnerd71b0b02009-08-23 03:41:05 +0000134 OS << "********** INTERVALS **********\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000135 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Chris Lattnerd71b0b02009-08-23 03:41:05 +0000136 I->second->print(OS, tri_);
137 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000138 }
139
Evan Cheng95320812009-09-14 21:33:42 +0000140 printInstrs(OS);
141}
142
143void LiveIntervals::printInstrs(raw_ostream &OS) const {
Chris Lattnerd71b0b02009-08-23 03:41:05 +0000144 OS << "********** MACHINEINSTRS **********\n";
145
Chris Lattner3f1d2c32009-07-21 21:12:58 +0000146 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
147 mbbi != mbbe; ++mbbi) {
Chris Lattnerd71b0b02009-08-23 03:41:05 +0000148 OS << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
Chris Lattner3f1d2c32009-07-21 21:12:58 +0000149 for (MachineBasicBlock::iterator mii = mbbi->begin(),
150 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattnerd71b0b02009-08-23 03:41:05 +0000151 OS << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner3f1d2c32009-07-21 21:12:58 +0000152 }
153 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000154}
155
Evan Cheng95320812009-09-14 21:33:42 +0000156void LiveIntervals::dumpInstrs() const {
157 printInstrs(errs());
158}
159
Evan Chengc4c75f52007-11-03 07:20:12 +0000160/// conflictsWithPhysRegDef - Returns true if the specified register
161/// is defined during the duration of the specified interval.
162bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
163 VirtRegMap &vrm, unsigned reg) {
164 for (LiveInterval::Ranges::const_iterator
165 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Lang Hamesd6a717c2009-11-03 23:52:08 +0000166 for (SlotIndex index = I->start.getBaseIndex(),
167 end = I->end.getPrevSlot().getBaseIndex().getNextIndex();
168 index != end;
169 index = index.getNextIndex()) {
Evan Chengc4c75f52007-11-03 07:20:12 +0000170 // skip deleted instructions
171 while (index != end && !getInstructionFromIndex(index))
Lang Hamesd6a717c2009-11-03 23:52:08 +0000172 index = index.getNextIndex();
Evan Chengc4c75f52007-11-03 07:20:12 +0000173 if (index == end) break;
174
175 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengf97496a2009-01-20 19:12:24 +0000176 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
177 if (tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Cheng58edd782007-11-15 08:13:29 +0000178 if (SrcReg == li.reg || DstReg == li.reg)
179 continue;
Evan Chengc4c75f52007-11-03 07:20:12 +0000180 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
181 MachineOperand& mop = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000182 if (!mop.isReg())
Evan Chengc4c75f52007-11-03 07:20:12 +0000183 continue;
184 unsigned PhysReg = mop.getReg();
Evan Cheng58edd782007-11-15 08:13:29 +0000185 if (PhysReg == 0 || PhysReg == li.reg)
Evan Chengc4c75f52007-11-03 07:20:12 +0000186 continue;
Dan Gohman1e57df32008-02-10 18:45:23 +0000187 if (TargetRegisterInfo::isVirtualRegister(PhysReg)) {
Evan Cheng58edd782007-11-15 08:13:29 +0000188 if (!vrm.hasPhys(PhysReg))
189 continue;
Evan Chengc4c75f52007-11-03 07:20:12 +0000190 PhysReg = vrm.getPhys(PhysReg);
Evan Cheng58edd782007-11-15 08:13:29 +0000191 }
Dan Gohman1e57df32008-02-10 18:45:23 +0000192 if (PhysReg && tri_->regsOverlap(PhysReg, reg))
Evan Chengc4c75f52007-11-03 07:20:12 +0000193 return true;
194 }
195 }
196 }
197
198 return false;
199}
200
Evan Cheng7a9b79c2009-01-07 02:08:57 +0000201/// conflictsWithPhysRegRef - Similar to conflictsWithPhysRegRef except
202/// it can check use as well.
203bool LiveIntervals::conflictsWithPhysRegRef(LiveInterval &li,
204 unsigned Reg, bool CheckUse,
205 SmallPtrSet<MachineInstr*,32> &JoinedCopies) {
206 for (LiveInterval::Ranges::const_iterator
207 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Lang Hamesd6a717c2009-11-03 23:52:08 +0000208 for (SlotIndex index = I->start.getBaseIndex(),
209 end = I->end.getPrevSlot().getBaseIndex().getNextIndex();
210 index != end;
211 index = index.getNextIndex()) {
Evan Cheng7a9b79c2009-01-07 02:08:57 +0000212 // Skip deleted instructions.
213 MachineInstr *MI = 0;
214 while (index != end) {
215 MI = getInstructionFromIndex(index);
216 if (MI)
217 break;
Lang Hamesd6a717c2009-11-03 23:52:08 +0000218 index = index.getNextIndex();
Evan Cheng7a9b79c2009-01-07 02:08:57 +0000219 }
220 if (index == end) break;
221
222 if (JoinedCopies.count(MI))
223 continue;
224 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
225 MachineOperand& MO = MI->getOperand(i);
226 if (!MO.isReg())
227 continue;
228 if (MO.isUse() && !CheckUse)
229 continue;
230 unsigned PhysReg = MO.getReg();
231 if (PhysReg == 0 || TargetRegisterInfo::isVirtualRegister(PhysReg))
232 continue;
233 if (tri_->isSubRegister(Reg, PhysReg))
234 return true;
235 }
236 }
237 }
238
239 return false;
240}
241
Daniel Dunbaref65e0c2009-09-15 20:31:12 +0000242#ifndef NDEBUG
Evan Cheng95320812009-09-14 21:33:42 +0000243static void printRegName(unsigned reg, const TargetRegisterInfo* tri_) {
Dan Gohman1e57df32008-02-10 18:45:23 +0000244 if (TargetRegisterInfo::isPhysicalRegister(reg))
Daniel Dunbarc6ebd382009-07-24 09:53:24 +0000245 errs() << tri_->getName(reg);
Evan Cheng1204d172007-08-13 23:45:17 +0000246 else
Daniel Dunbarc6ebd382009-07-24 09:53:24 +0000247 errs() << "%reg" << reg;
Evan Cheng1204d172007-08-13 23:45:17 +0000248}
Daniel Dunbaref65e0c2009-09-15 20:31:12 +0000249#endif
Evan Cheng1204d172007-08-13 23:45:17 +0000250
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000251void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
252 MachineBasicBlock::iterator mi,
Lang Hamesd6a717c2009-11-03 23:52:08 +0000253 SlotIndex MIIdx,
Lang Hamesd8f30992009-09-04 20:41:11 +0000254 MachineOperand& MO,
Evan Chengf1107fd2008-07-10 07:35:43 +0000255 unsigned MOIdx,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000256 LiveInterval &interval) {
Bill Wendling83c96ca2009-08-22 20:18:03 +0000257 DEBUG({
258 errs() << "\t\tregister: ";
Evan Cheng95320812009-09-14 21:33:42 +0000259 printRegName(interval.reg, tri_);
Bill Wendling83c96ca2009-08-22 20:18:03 +0000260 });
Evan Cheng70f68e92008-04-03 16:39:43 +0000261
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262 // Virtual registers may be defined multiple times (due to phi
263 // elimination and 2-addr elimination). Much of what we do only has to be
264 // done once for the vreg. We use an empty interval to detect the first
265 // time we see a vreg.
Evan Chengcb11cae2009-07-17 19:43:40 +0000266 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000267 if (interval.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000268 // Get the Idx of the defining instructions.
Lang Hamesd6a717c2009-11-03 23:52:08 +0000269 SlotIndex defIndex = MIIdx.getDefIndex();
Dale Johannesen13c4b632009-09-20 00:36:41 +0000270 // Earlyclobbers move back one, so that they overlap the live range
271 // of inputs.
Dale Johannesen94464072008-09-24 01:07:17 +0000272 if (MO.isEarlyClobber())
Lang Hamesd6a717c2009-11-03 23:52:08 +0000273 defIndex = MIIdx.getUseIndex();
Evan Cheng983b81d2007-08-29 20:45:00 +0000274 VNInfo *ValNo;
Evan Cheng7d2b9082008-02-15 18:24:29 +0000275 MachineInstr *CopyMI = NULL;
Evan Chengf97496a2009-01-20 19:12:24 +0000276 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Evan Cheng7d2b9082008-02-15 18:24:29 +0000277 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng909ab8b42008-04-09 20:57:25 +0000278 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Dan Gohman4cedb1c2009-04-08 00:15:30 +0000279 mi->getOpcode() == TargetInstrInfo::SUBREG_TO_REG ||
Evan Chengf97496a2009-01-20 19:12:24 +0000280 tii_->isMoveInstr(*mi, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Cheng7d2b9082008-02-15 18:24:29 +0000281 CopyMI = mi;
Evan Chenga9823a22008-12-19 20:58:01 +0000282 // Earlyclobbers move back one.
Lang Hames4eb8fc82009-06-17 21:01:20 +0000283 ValNo = interval.getNextValue(defIndex, CopyMI, true, VNInfoAllocator);
Evan Cheng983b81d2007-08-29 20:45:00 +0000284
285 assert(ValNo->id == 0 && "First value in interval is not 0?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286
287 // Loop over all of the blocks that the vreg is defined in. There are
288 // two cases we have to handle here. The most common case is a vreg
289 // whose lifetime is contained within a basic block. In this case there
290 // will be a single kill, in MBB, which comes after the definition.
291 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
292 // FIXME: what about dead vars?
Lang Hamesd6a717c2009-11-03 23:52:08 +0000293 SlotIndex killIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294 if (vi.Kills[0] != mi)
Lang Hamesd6a717c2009-11-03 23:52:08 +0000295 killIdx = getInstructionIndex(vi.Kills[0]).getDefIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000296 else
Lang Hamesd6a717c2009-11-03 23:52:08 +0000297 killIdx = defIndex.getStoreIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000298
299 // If the kill happens after the definition, we have an intra-block
300 // live range.
301 if (killIdx > defIndex) {
Jeffrey Yasskin02d392b2009-05-26 18:27:15 +0000302 assert(vi.AliveBlocks.empty() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000303 "Shouldn't be alive across any blocks!");
Evan Cheng983b81d2007-08-29 20:45:00 +0000304 LiveRange LR(defIndex, killIdx, ValNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000305 interval.addRange(LR);
Bill Wendling83c96ca2009-08-22 20:18:03 +0000306 DEBUG(errs() << " +" << LR << "\n");
Lang Hamesd8f30992009-09-04 20:41:11 +0000307 ValNo->addKill(killIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000308 return;
309 }
310 }
311
312 // The other case we handle is when a virtual register lives to the end
313 // of the defining block, potentially live across some blocks, then is
314 // live into some number of blocks, but gets killed. Start by adding a
315 // range that goes from this definition to the end of the defining block.
Lang Hamesd6a717c2009-11-03 23:52:08 +0000316 LiveRange NewLR(defIndex, getMBBEndIdx(mbb).getNextIndex().getLoadIndex(),
317 ValNo);
Bill Wendling83c96ca2009-08-22 20:18:03 +0000318 DEBUG(errs() << " +" << NewLR);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000319 interval.addRange(NewLR);
320
321 // Iterate over all of the blocks that the variable is completely
322 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
323 // live interval.
Jeffrey Yasskin02d392b2009-05-26 18:27:15 +0000324 for (SparseBitVector<>::iterator I = vi.AliveBlocks.begin(),
325 E = vi.AliveBlocks.end(); I != E; ++I) {
Lang Hamesd6a717c2009-11-03 23:52:08 +0000326 LiveRange LR(
327 getMBBStartIdx(mf_->getBlockNumbered(*I)),
328 getMBBEndIdx(mf_->getBlockNumbered(*I)).getNextIndex().getLoadIndex(),
329 ValNo);
Dan Gohmana48b1002008-11-13 16:31:27 +0000330 interval.addRange(LR);
Bill Wendling83c96ca2009-08-22 20:18:03 +0000331 DEBUG(errs() << " +" << LR);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000332 }
333
334 // Finally, this virtual register is live from the start of any killing
335 // block to the 'use' slot of the killing instruction.
336 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
337 MachineInstr *Kill = vi.Kills[i];
Lang Hamesd6a717c2009-11-03 23:52:08 +0000338 SlotIndex killIdx =
339 getInstructionIndex(Kill).getDefIndex();
Evan Chenga32393f2009-09-21 04:32:32 +0000340 LiveRange LR(getMBBStartIdx(Kill->getParent()), killIdx, ValNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000341 interval.addRange(LR);
Lang Hamesd8f30992009-09-04 20:41:11 +0000342 ValNo->addKill(killIdx);
Bill Wendling83c96ca2009-08-22 20:18:03 +0000343 DEBUG(errs() << " +" << LR);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344 }
345
346 } else {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347 // If this is the second time we see a virtual register definition, it
348 // must be due to phi elimination or two addr elimination. If this is
349 // the result of two address elimination, then the vreg is one of the
350 // def-and-use register operand.
Bob Wilsonaded9952009-04-09 17:16:43 +0000351 if (mi->isRegTiedToUseOperand(MOIdx)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000352 // If this is a two-address definition, then we have already processed
353 // the live range. The only problem is that we didn't realize there
354 // are actually two values in the live interval. Because of this we
355 // need to take the LiveRegion that defines this register and split it
356 // into two values.
Evan Cheng06701fc2008-01-10 08:22:10 +0000357 assert(interval.containsOneValue());
Lang Hamesd6a717c2009-11-03 23:52:08 +0000358 SlotIndex DefIndex = interval.getValNumInfo(0)->def.getDefIndex();
359 SlotIndex RedefIndex = MIIdx.getDefIndex();
Evan Cheng2682ea02009-03-23 08:01:15 +0000360 if (MO.isEarlyClobber())
Lang Hamesd6a717c2009-11-03 23:52:08 +0000361 RedefIndex = MIIdx.getUseIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000362
Lang Hames2a7b3b22009-09-12 03:34:03 +0000363 const LiveRange *OldLR =
Lang Hamesd6a717c2009-11-03 23:52:08 +0000364 interval.getLiveRangeContaining(RedefIndex.getUseIndex());
Evan Cheng983b81d2007-08-29 20:45:00 +0000365 VNInfo *OldValNo = OldLR->valno;
Evan Cheng816a7f32007-08-11 00:59:19 +0000366
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000367 // Delete the initial value, which should be short and continuous,
368 // because the 2-addr copy must be in the same MBB as the redef.
369 interval.removeRange(DefIndex, RedefIndex);
370
371 // Two-address vregs should always only be redefined once. This means
372 // that at this point, there should be exactly one value number in it.
373 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
374
375 // The new value number (#1) is defined by the instruction we claimed
376 // defined value #0.
Lang Hames87972832009-08-10 23:43:28 +0000377 VNInfo *ValNo = interval.getNextValue(OldValNo->def, OldValNo->getCopy(),
Lang Hames4eb8fc82009-06-17 21:01:20 +0000378 false, // update at *
Evan Cheng7d2b9082008-02-15 18:24:29 +0000379 VNInfoAllocator);
Lang Hames4eb8fc82009-06-17 21:01:20 +0000380 ValNo->setFlags(OldValNo->getFlags()); // * <- updating here
381
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000382 // Value#0 is now defined by the 2-addr instruction.
Evan Cheng7d2b9082008-02-15 18:24:29 +0000383 OldValNo->def = RedefIndex;
Lang Hames87972832009-08-10 23:43:28 +0000384 OldValNo->setCopy(0);
Evan Cheng2682ea02009-03-23 08:01:15 +0000385 if (MO.isEarlyClobber())
Lang Hames4eb8fc82009-06-17 21:01:20 +0000386 OldValNo->setHasRedefByEC(true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000387
388 // Add the new live interval which replaces the range for the input copy.
389 LiveRange LR(DefIndex, RedefIndex, ValNo);
Bill Wendling83c96ca2009-08-22 20:18:03 +0000390 DEBUG(errs() << " replace range with " << LR);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000391 interval.addRange(LR);
Lang Hamesd8f30992009-09-04 20:41:11 +0000392 ValNo->addKill(RedefIndex);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393
394 // If this redefinition is dead, we need to add a dummy unit live
395 // range covering the def slot.
Owen Anderson5b691fc2008-06-25 23:39:39 +0000396 if (MO.isDead())
Lang Hamesd6a717c2009-11-03 23:52:08 +0000397 interval.addRange(LiveRange(RedefIndex, RedefIndex.getStoreIndex(),
398 OldValNo));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399
Bill Wendling83c96ca2009-08-22 20:18:03 +0000400 DEBUG({
401 errs() << " RESULT: ";
402 interval.print(errs(), tri_);
403 });
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404 } else {
405 // Otherwise, this must be because of phi elimination. If this is the
406 // first redefinition of the vreg that we have seen, go back and change
407 // the live range in the PHI block to be a different value number.
408 if (interval.containsOneValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000409 // Remove the old range that we now know has an incorrect number.
Evan Cheng319802c2007-09-05 21:46:51 +0000410 VNInfo *VNI = interval.getValNumInfo(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000411 MachineInstr *Killer = vi.Kills[0];
Evan Cheng95320812009-09-14 21:33:42 +0000412 phiJoinCopies.push_back(Killer);
Lang Hamesd6a717c2009-11-03 23:52:08 +0000413 SlotIndex Start = getMBBStartIdx(Killer->getParent());
414 SlotIndex End = getInstructionIndex(Killer).getDefIndex();
Bill Wendling83c96ca2009-08-22 20:18:03 +0000415 DEBUG({
416 errs() << " Removing [" << Start << "," << End << "] from: ";
417 interval.print(errs(), tri_);
418 errs() << "\n";
419 });
Lang Hamesd2bd8622009-07-09 03:57:02 +0000420 interval.removeRange(Start, End);
421 assert(interval.ranges.size() == 1 &&
Evan Cheng95320812009-09-14 21:33:42 +0000422 "Newly discovered PHI interval has >1 ranges.");
Lang Hamesd8f30992009-09-04 20:41:11 +0000423 MachineBasicBlock *killMBB = getMBBFromIndex(interval.endIndex());
Lang Hamesd6a717c2009-11-03 23:52:08 +0000424 VNI->addKill(indexes_->getTerminatorGap(killMBB));
Lang Hames4eb8fc82009-06-17 21:01:20 +0000425 VNI->setHasPHIKill(true);
Bill Wendling83c96ca2009-08-22 20:18:03 +0000426 DEBUG({
427 errs() << " RESULT: ";
428 interval.print(errs(), tri_);
429 });
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000430
431 // Replace the interval with one of a NEW value number. Note that this
432 // value number isn't actually defined by an instruction, weird huh? :)
Lang Hames7c3765d2009-06-19 02:17:53 +0000433 LiveRange LR(Start, End,
Lang Hamesd6a717c2009-11-03 23:52:08 +0000434 interval.getNextValue(SlotIndex(getMBBStartIdx(mbb), true),
435 0, false, VNInfoAllocator));
Lang Hames4eb8fc82009-06-17 21:01:20 +0000436 LR.valno->setIsPHIDef(true);
Bill Wendling83c96ca2009-08-22 20:18:03 +0000437 DEBUG(errs() << " replace range with " << LR);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000438 interval.addRange(LR);
Lang Hamesd8f30992009-09-04 20:41:11 +0000439 LR.valno->addKill(End);
Bill Wendling83c96ca2009-08-22 20:18:03 +0000440 DEBUG({
441 errs() << " RESULT: ";
442 interval.print(errs(), tri_);
443 });
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000444 }
445
446 // In the case of PHI elimination, each variable definition is only
447 // live until the end of the block. We've already taken care of the
448 // rest of the live range.
Lang Hamesd6a717c2009-11-03 23:52:08 +0000449 SlotIndex defIndex = MIIdx.getDefIndex();
Evan Cheng2682ea02009-03-23 08:01:15 +0000450 if (MO.isEarlyClobber())
Lang Hamesd6a717c2009-11-03 23:52:08 +0000451 defIndex = MIIdx.getUseIndex();
Evan Cheng95320812009-09-14 21:33:42 +0000452
Evan Cheng983b81d2007-08-29 20:45:00 +0000453 VNInfo *ValNo;
Evan Cheng7d2b9082008-02-15 18:24:29 +0000454 MachineInstr *CopyMI = NULL;
Evan Chengf97496a2009-01-20 19:12:24 +0000455 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Evan Cheng7d2b9082008-02-15 18:24:29 +0000456 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng909ab8b42008-04-09 20:57:25 +0000457 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Dan Gohman4cedb1c2009-04-08 00:15:30 +0000458 mi->getOpcode() == TargetInstrInfo::SUBREG_TO_REG ||
Evan Chengf97496a2009-01-20 19:12:24 +0000459 tii_->isMoveInstr(*mi, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Cheng7d2b9082008-02-15 18:24:29 +0000460 CopyMI = mi;
Lang Hames4eb8fc82009-06-17 21:01:20 +0000461 ValNo = interval.getNextValue(defIndex, CopyMI, true, VNInfoAllocator);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000462
Lang Hamesd6a717c2009-11-03 23:52:08 +0000463 SlotIndex killIndex = getMBBEndIdx(mbb).getNextIndex().getLoadIndex();
Evan Cheng983b81d2007-08-29 20:45:00 +0000464 LiveRange LR(defIndex, killIndex, ValNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000465 interval.addRange(LR);
Lang Hamesd6a717c2009-11-03 23:52:08 +0000466 ValNo->addKill(indexes_->getTerminatorGap(mbb));
Lang Hames4eb8fc82009-06-17 21:01:20 +0000467 ValNo->setHasPHIKill(true);
Bill Wendling83c96ca2009-08-22 20:18:03 +0000468 DEBUG(errs() << " +" << LR);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000469 }
470 }
471
Bill Wendling83c96ca2009-08-22 20:18:03 +0000472 DEBUG(errs() << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000473}
474
475void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
476 MachineBasicBlock::iterator mi,
Lang Hamesd6a717c2009-11-03 23:52:08 +0000477 SlotIndex MIIdx,
Owen Anderson5b691fc2008-06-25 23:39:39 +0000478 MachineOperand& MO,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000479 LiveInterval &interval,
Evan Cheng7d2b9082008-02-15 18:24:29 +0000480 MachineInstr *CopyMI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000481 // A physical register cannot be live across basic block, so its
482 // lifetime must end somewhere in its defining basic block.
Bill Wendling83c96ca2009-08-22 20:18:03 +0000483 DEBUG({
484 errs() << "\t\tregister: ";
Evan Cheng95320812009-09-14 21:33:42 +0000485 printRegName(interval.reg, tri_);
Bill Wendling83c96ca2009-08-22 20:18:03 +0000486 });
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000487
Lang Hamesd6a717c2009-11-03 23:52:08 +0000488 SlotIndex baseIndex = MIIdx;
489 SlotIndex start = baseIndex.getDefIndex();
Dale Johannesen94464072008-09-24 01:07:17 +0000490 // Earlyclobbers move back one.
491 if (MO.isEarlyClobber())
Lang Hamesd6a717c2009-11-03 23:52:08 +0000492 start = MIIdx.getUseIndex();
493 SlotIndex end = start;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000494
495 // If it is not used after definition, it is considered dead at
496 // the instruction defining it. Hence its interval is:
497 // [defSlot(def), defSlot(def)+1)
Dale Johannesen13c4b632009-09-20 00:36:41 +0000498 // For earlyclobbers, the defSlot was pushed back one; the extra
499 // advance below compensates.
Owen Anderson5b691fc2008-06-25 23:39:39 +0000500 if (MO.isDead()) {
Bill Wendling83c96ca2009-08-22 20:18:03 +0000501 DEBUG(errs() << " dead");
Lang Hamesd6a717c2009-11-03 23:52:08 +0000502 end = start.getStoreIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000503 goto exit;
504 }
505
506 // If it is not dead on definition, it must be killed by a
507 // subsequent instruction. Hence its interval is:
508 // [defSlot(def), useSlot(kill)+1)
Lang Hamesd6a717c2009-11-03 23:52:08 +0000509 baseIndex = baseIndex.getNextIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000510 while (++mi != MBB->end()) {
Lang Hamesd6a717c2009-11-03 23:52:08 +0000511
512 if (getInstructionFromIndex(baseIndex) == 0)
513 baseIndex = indexes_->getNextNonNullIndex(baseIndex);
514
Evan Chengc7daf1f2008-03-05 00:59:57 +0000515 if (mi->killsRegister(interval.reg, tri_)) {
Bill Wendling83c96ca2009-08-22 20:18:03 +0000516 DEBUG(errs() << " killed");
Lang Hamesd6a717c2009-11-03 23:52:08 +0000517 end = baseIndex.getDefIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000518 goto exit;
Evan Cheng3be003c2009-04-27 20:42:46 +0000519 } else {
520 int DefIdx = mi->findRegisterDefOperandIdx(interval.reg, false, tri_);
521 if (DefIdx != -1) {
522 if (mi->isRegTiedToUseOperand(DefIdx)) {
523 // Two-address instruction.
Lang Hamesd6a717c2009-11-03 23:52:08 +0000524 end = baseIndex.getDefIndex();
525 assert(!mi->getOperand(DefIdx).isEarlyClobber() &&
526 "Two address instruction is an early clobber?");
Evan Cheng3be003c2009-04-27 20:42:46 +0000527 } else {
528 // Another instruction redefines the register before it is ever read.
529 // Then the register is essentially dead at the instruction that defines
530 // it. Hence its interval is:
531 // [defSlot(def), defSlot(def)+1)
Bill Wendling83c96ca2009-08-22 20:18:03 +0000532 DEBUG(errs() << " dead");
Lang Hamesd6a717c2009-11-03 23:52:08 +0000533 end = start.getStoreIndex();
Evan Cheng3be003c2009-04-27 20:42:46 +0000534 }
535 goto exit;
536 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000537 }
Owen Anderson4065ac92008-07-23 21:37:49 +0000538
Lang Hamesd6a717c2009-11-03 23:52:08 +0000539 baseIndex = baseIndex.getNextIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000540 }
541
542 // The only case we should have a dead physreg here without a killing or
543 // instruction where we know it's dead is if it is live-in to the function
Evan Cheng5431d9c2009-04-27 17:36:47 +0000544 // and never used. Another possible case is the implicit use of the
545 // physical register has been deleted by two-address pass.
Lang Hamesd6a717c2009-11-03 23:52:08 +0000546 end = start.getStoreIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000547
548exit:
549 assert(start < end && "did not find end of interval?");
550
551 // Already exists? Extend old live interval.
552 LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
Evan Chenga9823a22008-12-19 20:58:01 +0000553 bool Extend = OldLR != interval.end();
554 VNInfo *ValNo = Extend
Lang Hames4eb8fc82009-06-17 21:01:20 +0000555 ? OldLR->valno : interval.getNextValue(start, CopyMI, true, VNInfoAllocator);
Evan Chenga9823a22008-12-19 20:58:01 +0000556 if (MO.isEarlyClobber() && Extend)
Lang Hames4eb8fc82009-06-17 21:01:20 +0000557 ValNo->setHasRedefByEC(true);
Evan Cheng983b81d2007-08-29 20:45:00 +0000558 LiveRange LR(start, end, ValNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000559 interval.addRange(LR);
Lang Hamesd8f30992009-09-04 20:41:11 +0000560 LR.valno->addKill(end);
Bill Wendling83c96ca2009-08-22 20:18:03 +0000561 DEBUG(errs() << " +" << LR << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000562}
563
564void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
565 MachineBasicBlock::iterator MI,
Lang Hamesd6a717c2009-11-03 23:52:08 +0000566 SlotIndex MIIdx,
Evan Chengf1107fd2008-07-10 07:35:43 +0000567 MachineOperand& MO,
568 unsigned MOIdx) {
Owen Anderson5b691fc2008-06-25 23:39:39 +0000569 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Evan Chengf1107fd2008-07-10 07:35:43 +0000570 handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
Owen Anderson5b691fc2008-06-25 23:39:39 +0000571 getOrCreateInterval(MO.getReg()));
572 else if (allocatableRegs_[MO.getReg()]) {
Evan Cheng7d2b9082008-02-15 18:24:29 +0000573 MachineInstr *CopyMI = NULL;
Evan Chengf97496a2009-01-20 19:12:24 +0000574 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Evan Cheng7d2b9082008-02-15 18:24:29 +0000575 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng909ab8b42008-04-09 20:57:25 +0000576 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Dan Gohman4cedb1c2009-04-08 00:15:30 +0000577 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG ||
Evan Chengf97496a2009-01-20 19:12:24 +0000578 tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Cheng7d2b9082008-02-15 18:24:29 +0000579 CopyMI = MI;
Evan Cheng3be003c2009-04-27 20:42:46 +0000580 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
Owen Anderson5b691fc2008-06-25 23:39:39 +0000581 getOrCreateInterval(MO.getReg()), CopyMI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000582 // Def of a register also defines its sub-registers.
Owen Anderson5b691fc2008-06-25 23:39:39 +0000583 for (const unsigned* AS = tri_->getSubRegisters(MO.getReg()); *AS; ++AS)
Evan Chengc7daf1f2008-03-05 00:59:57 +0000584 // If MI also modifies the sub-register explicitly, avoid processing it
585 // more than once. Do not pass in TRI here so it checks for exact match.
586 if (!MI->modifiesRegister(*AS))
Evan Cheng3be003c2009-04-27 20:42:46 +0000587 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
Owen Anderson5b691fc2008-06-25 23:39:39 +0000588 getOrCreateInterval(*AS), 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000589 }
590}
591
592void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
Lang Hamesd6a717c2009-11-03 23:52:08 +0000593 SlotIndex MIIdx,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000594 LiveInterval &interval, bool isAlias) {
Bill Wendling83c96ca2009-08-22 20:18:03 +0000595 DEBUG({
596 errs() << "\t\tlivein register: ";
Evan Cheng95320812009-09-14 21:33:42 +0000597 printRegName(interval.reg, tri_);
Bill Wendling83c96ca2009-08-22 20:18:03 +0000598 });
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000599
600 // Look for kills, if it reaches a def before it's killed, then it shouldn't
601 // be considered a livein.
602 MachineBasicBlock::iterator mi = MBB->begin();
Lang Hamesd6a717c2009-11-03 23:52:08 +0000603 SlotIndex baseIndex = MIIdx;
604 SlotIndex start = baseIndex;
605 if (getInstructionFromIndex(baseIndex) == 0)
606 baseIndex = indexes_->getNextNonNullIndex(baseIndex);
607
608 SlotIndex end = baseIndex;
Evan Cheng1e16ae42009-03-05 03:34:26 +0000609 bool SeenDefUse = false;
Owen Andersonb2ae2692008-09-15 22:00:38 +0000610
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000611 while (mi != MBB->end()) {
Evan Chengc7daf1f2008-03-05 00:59:57 +0000612 if (mi->killsRegister(interval.reg, tri_)) {
Bill Wendling83c96ca2009-08-22 20:18:03 +0000613 DEBUG(errs() << " killed");
Lang Hamesd6a717c2009-11-03 23:52:08 +0000614 end = baseIndex.getDefIndex();
Evan Cheng1e16ae42009-03-05 03:34:26 +0000615 SeenDefUse = true;
Lang Hamescc664322009-06-18 22:01:47 +0000616 break;
Evan Chengc7daf1f2008-03-05 00:59:57 +0000617 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000618 // Another instruction redefines the register before it is ever read.
619 // Then the register is essentially dead at the instruction that defines
620 // it. Hence its interval is:
621 // [defSlot(def), defSlot(def)+1)
Bill Wendling83c96ca2009-08-22 20:18:03 +0000622 DEBUG(errs() << " dead");
Lang Hamesd6a717c2009-11-03 23:52:08 +0000623 end = start.getStoreIndex();
Evan Cheng1e16ae42009-03-05 03:34:26 +0000624 SeenDefUse = true;
Lang Hamescc664322009-06-18 22:01:47 +0000625 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000626 }
627
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628 ++mi;
Evan Cheng1e16ae42009-03-05 03:34:26 +0000629 if (mi != MBB->end()) {
Lang Hamesd6a717c2009-11-03 23:52:08 +0000630 baseIndex = indexes_->getNextNonNullIndex(baseIndex);
Evan Cheng1e16ae42009-03-05 03:34:26 +0000631 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632 }
633
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000634 // Live-in register might not be used at all.
Evan Cheng1e16ae42009-03-05 03:34:26 +0000635 if (!SeenDefUse) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000636 if (isAlias) {
Bill Wendling83c96ca2009-08-22 20:18:03 +0000637 DEBUG(errs() << " dead");
Lang Hamesd6a717c2009-11-03 23:52:08 +0000638 end = MIIdx.getStoreIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000639 } else {
Bill Wendling83c96ca2009-08-22 20:18:03 +0000640 DEBUG(errs() << " live through");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641 end = baseIndex;
642 }
643 }
644
Lang Hames7c3765d2009-06-19 02:17:53 +0000645 VNInfo *vni =
Lang Hamesd6a717c2009-11-03 23:52:08 +0000646 interval.getNextValue(SlotIndex(getMBBStartIdx(MBB), true),
Lang Hamesd8f30992009-09-04 20:41:11 +0000647 0, false, VNInfoAllocator);
Lang Hamescc664322009-06-18 22:01:47 +0000648 vni->setIsPHIDef(true);
649 LiveRange LR(start, end, vni);
Jakob Stoklund Olesend1332dc2009-11-07 01:58:40 +0000650
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000651 interval.addRange(LR);
Lang Hamesd8f30992009-09-04 20:41:11 +0000652 LR.valno->addKill(end);
Bill Wendling83c96ca2009-08-22 20:18:03 +0000653 DEBUG(errs() << " +" << LR << '\n');
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000654}
655
Jakob Stoklund Olesend1332dc2009-11-07 01:58:40 +0000656bool LiveIntervals::
657isSafeAndProfitableToCoalesce(LiveInterval &DstInt,
658 LiveInterval &SrcInt,
659 SmallVector<MachineInstr*,16> &IdentCopies,
660 SmallVector<MachineInstr*,16> &OtherCopies) {
Evan Cheng95320812009-09-14 21:33:42 +0000661 unsigned NumIdent = 0;
Dan Gohman04abe742009-09-25 22:26:13 +0000662 for (MachineRegisterInfo::def_iterator ri = mri_->def_begin(SrcInt.reg),
663 re = mri_->def_end(); ri != re; ++ri) {
Evan Cheng95320812009-09-14 21:33:42 +0000664 MachineInstr *MI = &*ri;
665 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
666 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Cheng6a48b002009-09-15 06:45:16 +0000667 return false;
Evan Cheng95320812009-09-14 21:33:42 +0000668 if (SrcReg != DstInt.reg) {
Jakob Stoklund Olesend1332dc2009-11-07 01:58:40 +0000669 // Non-identity copy - we cannot handle overlapping intervals
670 if (DstInt.liveAt(getInstructionIndex(MI)))
671 return false;
Evan Cheng95320812009-09-14 21:33:42 +0000672 OtherCopies.push_back(MI);
Evan Cheng95320812009-09-14 21:33:42 +0000673 } else {
674 IdentCopies.push_back(MI);
675 ++NumIdent;
676 }
677 }
678
Evan Cheng6a48b002009-09-15 06:45:16 +0000679 return IdentCopies.size() > OtherCopies.size();
Evan Cheng95320812009-09-14 21:33:42 +0000680}
681
682void LiveIntervals::performEarlyCoalescing() {
683 if (!EarlyCoalescing)
684 return;
685
686 /// Perform early coalescing: eliminate copies which feed into phi joins
687 /// and whose sources are defined by the phi joins.
688 for (unsigned i = 0, e = phiJoinCopies.size(); i != e; ++i) {
689 MachineInstr *Join = phiJoinCopies[i];
690 if (CoalescingLimit != -1 && (int)numCoalescing == CoalescingLimit)
691 break;
692
693 unsigned PHISrc, PHIDst, SrcSubReg, DstSubReg;
694 bool isMove= tii_->isMoveInstr(*Join, PHISrc, PHIDst, SrcSubReg, DstSubReg);
695#ifndef NDEBUG
696 assert(isMove && "PHI join instruction must be a move!");
697#else
698 isMove = isMove;
699#endif
700
701 LiveInterval &DstInt = getInterval(PHIDst);
702 LiveInterval &SrcInt = getInterval(PHISrc);
703 SmallVector<MachineInstr*, 16> IdentCopies;
704 SmallVector<MachineInstr*, 16> OtherCopies;
Jakob Stoklund Olesend1332dc2009-11-07 01:58:40 +0000705 if (!isSafeAndProfitableToCoalesce(DstInt, SrcInt,
706 IdentCopies, OtherCopies))
Evan Cheng95320812009-09-14 21:33:42 +0000707 continue;
708
709 DEBUG(errs() << "PHI Join: " << *Join);
710 assert(DstInt.containsOneValue() && "PHI join should have just one val#!");
Jakob Stoklund Olesend1332dc2009-11-07 01:58:40 +0000711 assert(std::distance(mri_->use_begin(PHISrc), mri_->use_end()) == 1 &&
712 "PHI join src should not be used elsewhere");
Evan Cheng95320812009-09-14 21:33:42 +0000713 VNInfo *VNI = DstInt.getValNumInfo(0);
Evan Cheng95320812009-09-14 21:33:42 +0000714
Evan Cheng6a48b002009-09-15 06:45:16 +0000715 // Change the non-identity copies to directly target the phi destination.
716 for (unsigned i = 0, e = OtherCopies.size(); i != e; ++i) {
717 MachineInstr *PHICopy = OtherCopies[i];
Lang Hamesd6a717c2009-11-03 23:52:08 +0000718 SlotIndex MIIndex = getInstructionIndex(PHICopy);
Jakob Stoklund Olesend1332dc2009-11-07 01:58:40 +0000719 DEBUG(errs() << "Moving: " << MIIndex << ' ' << *PHICopy);
Lang Hamesd6a717c2009-11-03 23:52:08 +0000720 SlotIndex DefIndex = MIIndex.getDefIndex();
Evan Cheng95320812009-09-14 21:33:42 +0000721 LiveRange *SLR = SrcInt.getLiveRangeContaining(DefIndex);
Lang Hamesd6a717c2009-11-03 23:52:08 +0000722 SlotIndex StartIndex = SLR->start;
723 SlotIndex EndIndex = SLR->end;
Evan Cheng95320812009-09-14 21:33:42 +0000724
725 // Delete val# defined by the now identity copy and add the range from
726 // beginning of the mbb to the end of the range.
727 SrcInt.removeValNo(SLR->valno);
Evan Cheng6a48b002009-09-15 06:45:16 +0000728 DEBUG(errs() << " added range [" << StartIndex << ','
729 << EndIndex << "] to reg" << DstInt.reg << '\n');
Jakob Stoklund Olesend1332dc2009-11-07 01:58:40 +0000730 assert (!DstInt.liveAt(StartIndex) && "Cannot coalesce when dst live!");
Evan Cheng6a48b002009-09-15 06:45:16 +0000731 VNInfo *NewVNI = DstInt.getNextValue(DefIndex, PHICopy, true,
732 VNInfoAllocator);
733 NewVNI->setHasPHIKill(true);
734 DstInt.addRange(LiveRange(StartIndex, EndIndex, NewVNI));
735 for (unsigned j = 0, ee = PHICopy->getNumOperands(); j != ee; ++j) {
736 MachineOperand &MO = PHICopy->getOperand(j);
737 if (!MO.isReg() || MO.getReg() != PHISrc)
738 continue;
739 MO.setReg(PHIDst);
Evan Cheng95320812009-09-14 21:33:42 +0000740 }
Evan Cheng6a48b002009-09-15 06:45:16 +0000741 }
742
743 // Now let's eliminate all the would-be identity copies.
744 for (unsigned i = 0, e = IdentCopies.size(); i != e; ++i) {
745 MachineInstr *PHICopy = IdentCopies[i];
746 DEBUG(errs() << "Coalescing: " << *PHICopy);
747
Lang Hamesd6a717c2009-11-03 23:52:08 +0000748 SlotIndex MIIndex = getInstructionIndex(PHICopy);
749 SlotIndex DefIndex = MIIndex.getDefIndex();
Evan Cheng6a48b002009-09-15 06:45:16 +0000750 LiveRange *SLR = SrcInt.getLiveRangeContaining(DefIndex);
Lang Hamesd6a717c2009-11-03 23:52:08 +0000751 SlotIndex StartIndex = SLR->start;
752 SlotIndex EndIndex = SLR->end;
Evan Cheng6a48b002009-09-15 06:45:16 +0000753
754 // Delete val# defined by the now identity copy and add the range from
755 // beginning of the mbb to the end of the range.
756 SrcInt.removeValNo(SLR->valno);
Evan Cheng95320812009-09-14 21:33:42 +0000757 RemoveMachineInstrFromMaps(PHICopy);
758 PHICopy->eraseFromParent();
Evan Cheng6a48b002009-09-15 06:45:16 +0000759 DEBUG(errs() << " added range [" << StartIndex << ','
760 << EndIndex << "] to reg" << DstInt.reg << '\n');
761 DstInt.addRange(LiveRange(StartIndex, EndIndex, VNI));
Evan Cheng95320812009-09-14 21:33:42 +0000762 }
Evan Cheng95320812009-09-14 21:33:42 +0000763
Evan Cheng6a48b002009-09-15 06:45:16 +0000764 // Remove the phi join and update the phi block liveness.
Lang Hamesd6a717c2009-11-03 23:52:08 +0000765 SlotIndex MIIndex = getInstructionIndex(Join);
766 SlotIndex UseIndex = MIIndex.getUseIndex();
767 SlotIndex DefIndex = MIIndex.getDefIndex();
Evan Cheng6a48b002009-09-15 06:45:16 +0000768 LiveRange *SLR = SrcInt.getLiveRangeContaining(UseIndex);
769 LiveRange *DLR = DstInt.getLiveRangeContaining(DefIndex);
770 DLR->valno->setCopy(0);
771 DLR->valno->setIsDefAccurate(false);
772 DstInt.addRange(LiveRange(SLR->start, SLR->end, DLR->valno));
773 SrcInt.removeRange(SLR->start, SLR->end);
774 assert(SrcInt.empty());
775 removeInterval(PHISrc);
776 RemoveMachineInstrFromMaps(Join);
777 Join->eraseFromParent();
Evan Cheng95320812009-09-14 21:33:42 +0000778
779 ++numCoalescing;
780 }
781}
782
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000783/// computeIntervals - computes the live intervals for virtual
784/// registers. for some ordering of the machine instructions [1,N] a
785/// live interval is an interval [i, j) where 1 <= i <= j < N for
786/// which a variable is live
Dale Johannesenbac3c812008-09-17 21:13:11 +0000787void LiveIntervals::computeIntervals() {
Daniel Dunbar005975c2009-07-25 00:23:56 +0000788 DEBUG(errs() << "********** COMPUTING LIVE INTERVALS **********\n"
Bill Wendling83c96ca2009-08-22 20:18:03 +0000789 << "********** Function: "
790 << ((Value*)mf_->getFunction())->getName() << '\n');
Evan Chengcb11cae2009-07-17 19:43:40 +0000791
792 SmallVector<unsigned, 8> UndefUses;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000793 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
794 MBBI != E; ++MBBI) {
795 MachineBasicBlock *MBB = MBBI;
Owen Andersonf9817732008-09-21 20:43:24 +0000796 // Track the index of the current machine instr.
Lang Hamesd6a717c2009-11-03 23:52:08 +0000797 SlotIndex MIIndex = getMBBStartIdx(MBB);
Daniel Dunbar005975c2009-07-25 00:23:56 +0000798 DEBUG(errs() << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000799
800 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
801
Dan Gohman3f7d94b2007-10-03 19:26:29 +0000802 // Create intervals for live-ins to this BB first.
803 for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
804 LE = MBB->livein_end(); LI != LE; ++LI) {
805 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
806 // Multiple live-ins can alias the same register.
Dan Gohman1e57df32008-02-10 18:45:23 +0000807 for (const unsigned* AS = tri_->getSubRegisters(*LI); *AS; ++AS)
Dan Gohman3f7d94b2007-10-03 19:26:29 +0000808 if (!hasInterval(*AS))
809 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
810 true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000811 }
812
Owen Andersonb2ae2692008-09-15 22:00:38 +0000813 // Skip over empty initial indices.
Lang Hamesd6a717c2009-11-03 23:52:08 +0000814 if (getInstructionFromIndex(MIIndex) == 0)
815 MIIndex = indexes_->getNextNonNullIndex(MIIndex);
Owen Andersonb2ae2692008-09-15 22:00:38 +0000816
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000817 for (; MI != miEnd; ++MI) {
Bill Wendling83c96ca2009-08-22 20:18:03 +0000818 DEBUG(errs() << MIIndex << "\t" << *MI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000819
820 // Handle defs.
821 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
822 MachineOperand &MO = MI->getOperand(i);
Evan Chengcb11cae2009-07-17 19:43:40 +0000823 if (!MO.isReg() || !MO.getReg())
824 continue;
825
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000826 // handle register defs - build intervals
Evan Chengcb11cae2009-07-17 19:43:40 +0000827 if (MO.isDef())
Evan Chengf1107fd2008-07-10 07:35:43 +0000828 handleRegisterDef(MBB, MI, MIIndex, MO, i);
Evan Chengcb11cae2009-07-17 19:43:40 +0000829 else if (MO.isUndef())
830 UndefUses.push_back(MO.getReg());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000831 }
Owen Anderson4065ac92008-07-23 21:37:49 +0000832
Lang Hamesd6a717c2009-11-03 23:52:08 +0000833 // Move to the next instr slot.
834 MIIndex = indexes_->getNextNonNullIndex(MIIndex);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000835 }
836 }
Evan Chengcb11cae2009-07-17 19:43:40 +0000837
838 // Create empty intervals for registers defined by implicit_def's (except
839 // for those implicit_def that define values which are liveout of their
840 // blocks.
841 for (unsigned i = 0, e = UndefUses.size(); i != e; ++i) {
842 unsigned UndefReg = UndefUses[i];
843 (void)getOrCreateInterval(UndefReg);
844 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000845}
846
Owen Anderson348d1d82008-08-13 21:49:13 +0000847LiveInterval* LiveIntervals::createInterval(unsigned reg) {
Evan Cheng87597222009-02-08 11:04:35 +0000848 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? HUGE_VALF : 0.0F;
Owen Anderson348d1d82008-08-13 21:49:13 +0000849 return new LiveInterval(reg, Weight);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000850}
Evan Cheng9b741602007-11-12 06:35:08 +0000851
Evan Cheng87597222009-02-08 11:04:35 +0000852/// dupInterval - Duplicate a live interval. The caller is responsible for
853/// managing the allocated memory.
854LiveInterval* LiveIntervals::dupInterval(LiveInterval *li) {
855 LiveInterval *NewLI = createInterval(li->reg);
Evan Chengd78907d2009-06-14 20:22:55 +0000856 NewLI->Copy(*li, mri_, getVNInfoAllocator());
Evan Cheng87597222009-02-08 11:04:35 +0000857 return NewLI;
858}
859
Evan Cheng7d2b9082008-02-15 18:24:29 +0000860/// getVNInfoSourceReg - Helper function that parses the specified VNInfo
861/// copy field and returns the source register that defines it.
862unsigned LiveIntervals::getVNInfoSourceReg(const VNInfo *VNI) const {
Lang Hames87972832009-08-10 23:43:28 +0000863 if (!VNI->getCopy())
Evan Cheng7d2b9082008-02-15 18:24:29 +0000864 return 0;
865
Lang Hames87972832009-08-10 23:43:28 +0000866 if (VNI->getCopy()->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
Evan Cheng7a9b79c2009-01-07 02:08:57 +0000867 // If it's extracting out of a physical register, return the sub-register.
Lang Hames87972832009-08-10 23:43:28 +0000868 unsigned Reg = VNI->getCopy()->getOperand(1).getReg();
Evan Cheng7a9b79c2009-01-07 02:08:57 +0000869 if (TargetRegisterInfo::isPhysicalRegister(Reg))
Lang Hames87972832009-08-10 23:43:28 +0000870 Reg = tri_->getSubReg(Reg, VNI->getCopy()->getOperand(2).getImm());
Evan Cheng7a9b79c2009-01-07 02:08:57 +0000871 return Reg;
Lang Hames87972832009-08-10 23:43:28 +0000872 } else if (VNI->getCopy()->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
873 VNI->getCopy()->getOpcode() == TargetInstrInfo::SUBREG_TO_REG)
874 return VNI->getCopy()->getOperand(2).getReg();
Evan Cheng7a9b79c2009-01-07 02:08:57 +0000875
Evan Chengf97496a2009-01-20 19:12:24 +0000876 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Lang Hames87972832009-08-10 23:43:28 +0000877 if (tii_->isMoveInstr(*VNI->getCopy(), SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Cheng7d2b9082008-02-15 18:24:29 +0000878 return SrcReg;
Edwin Törökbd448e32009-07-14 16:55:14 +0000879 llvm_unreachable("Unrecognized copy instruction!");
Evan Cheng7d2b9082008-02-15 18:24:29 +0000880 return 0;
881}
Evan Cheng9b741602007-11-12 06:35:08 +0000882
883//===----------------------------------------------------------------------===//
884// Register allocator hooks.
885//
886
Evan Chenga37ecfe2008-02-22 09:24:50 +0000887/// getReMatImplicitUse - If the remat definition MI has one (for now, we only
888/// allow one) virtual register operand, then its uses are implicitly using
889/// the register. Returns the virtual register.
890unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
891 MachineInstr *MI) const {
892 unsigned RegOp = 0;
893 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
894 MachineOperand &MO = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000895 if (!MO.isReg() || !MO.isUse())
Evan Chenga37ecfe2008-02-22 09:24:50 +0000896 continue;
897 unsigned Reg = MO.getReg();
898 if (Reg == 0 || Reg == li.reg)
899 continue;
Chris Lattnerbe5f2c62009-06-27 04:06:41 +0000900
901 if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
902 !allocatableRegs_[Reg])
903 continue;
Evan Chenga37ecfe2008-02-22 09:24:50 +0000904 // FIXME: For now, only remat MI with at most one register operand.
905 assert(!RegOp &&
906 "Can't rematerialize instruction with multiple register operand!");
907 RegOp = MO.getReg();
Dan Gohmane3427532008-07-25 00:02:30 +0000908#ifndef NDEBUG
Evan Chenga37ecfe2008-02-22 09:24:50 +0000909 break;
Dan Gohmane3427532008-07-25 00:02:30 +0000910#endif
Evan Chenga37ecfe2008-02-22 09:24:50 +0000911 }
912 return RegOp;
913}
914
915/// isValNoAvailableAt - Return true if the val# of the specified interval
916/// which reaches the given instruction also reaches the specified use index.
917bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
Lang Hamesd6a717c2009-11-03 23:52:08 +0000918 SlotIndex UseIdx) const {
919 SlotIndex Index = getInstructionIndex(MI);
Evan Chenga37ecfe2008-02-22 09:24:50 +0000920 VNInfo *ValNo = li.FindLiveRangeContaining(Index)->valno;
921 LiveInterval::const_iterator UI = li.FindLiveRangeContaining(UseIdx);
922 return UI != li.end() && UI->valno == ValNo;
923}
924
Evan Cheng9b741602007-11-12 06:35:08 +0000925/// isReMaterializable - Returns true if the definition MI of the specified
926/// val# of the specified interval is re-materializable.
927bool LiveIntervals::isReMaterializable(const LiveInterval &li,
Evan Chenge81fdb92007-12-06 00:01:56 +0000928 const VNInfo *ValNo, MachineInstr *MI,
Evan Chengc84ea132008-09-30 15:44:16 +0000929 SmallVectorImpl<LiveInterval*> &SpillIs,
Evan Chenge81fdb92007-12-06 00:01:56 +0000930 bool &isLoad) {
Evan Cheng9b741602007-11-12 06:35:08 +0000931 if (DisableReMat)
932 return false;
933
Dan Gohman0a4c09e2009-10-09 23:27:56 +0000934 if (!tii_->isTriviallyReMaterializable(MI, aa_))
935 return false;
Evan Chengc2855322008-02-23 01:44:27 +0000936
Dan Gohman0a4c09e2009-10-09 23:27:56 +0000937 // Target-specific code can mark an instruction as being rematerializable
938 // if it has one virtual reg use, though it had better be something like
939 // a PIC base register which is likely to be live everywhere.
Dan Gohmane3427532008-07-25 00:02:30 +0000940 unsigned ImpUse = getReMatImplicitUse(li, MI);
941 if (ImpUse) {
942 const LiveInterval &ImpLi = getInterval(ImpUse);
943 for (MachineRegisterInfo::use_iterator ri = mri_->use_begin(li.reg),
944 re = mri_->use_end(); ri != re; ++ri) {
945 MachineInstr *UseMI = &*ri;
Lang Hamesd6a717c2009-11-03 23:52:08 +0000946 SlotIndex UseIdx = getInstructionIndex(UseMI);
Dan Gohmane3427532008-07-25 00:02:30 +0000947 if (li.FindLiveRangeContaining(UseIdx)->valno != ValNo)
948 continue;
949 if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
950 return false;
951 }
Evan Chengc84ea132008-09-30 15:44:16 +0000952
953 // If a register operand of the re-materialized instruction is going to
954 // be spilled next, then it's not legal to re-materialize this instruction.
955 for (unsigned i = 0, e = SpillIs.size(); i != e; ++i)
956 if (ImpUse == SpillIs[i]->reg)
957 return false;
Dan Gohmane3427532008-07-25 00:02:30 +0000958 }
959 return true;
Evan Chenge81fdb92007-12-06 00:01:56 +0000960}
961
Evan Cheng9cd7ff02008-10-24 02:05:00 +0000962/// isReMaterializable - Returns true if the definition MI of the specified
963/// val# of the specified interval is re-materializable.
964bool LiveIntervals::isReMaterializable(const LiveInterval &li,
965 const VNInfo *ValNo, MachineInstr *MI) {
966 SmallVector<LiveInterval*, 4> Dummy1;
967 bool Dummy2;
968 return isReMaterializable(li, ValNo, MI, Dummy1, Dummy2);
969}
970
Evan Chenge81fdb92007-12-06 00:01:56 +0000971/// isReMaterializable - Returns true if every definition of MI of every
972/// val# of the specified interval is re-materializable.
Evan Chengc84ea132008-09-30 15:44:16 +0000973bool LiveIntervals::isReMaterializable(const LiveInterval &li,
974 SmallVectorImpl<LiveInterval*> &SpillIs,
975 bool &isLoad) {
Evan Chenge81fdb92007-12-06 00:01:56 +0000976 isLoad = false;
977 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
978 i != e; ++i) {
979 const VNInfo *VNI = *i;
Lang Hames4eb8fc82009-06-17 21:01:20 +0000980 if (VNI->isUnused())
Evan Chenge81fdb92007-12-06 00:01:56 +0000981 continue; // Dead val#.
982 // Is the def for the val# rematerializable?
Lang Hames4eb8fc82009-06-17 21:01:20 +0000983 if (!VNI->isDefAccurate())
Evan Chenge81fdb92007-12-06 00:01:56 +0000984 return false;
Lang Hames4eb8fc82009-06-17 21:01:20 +0000985 MachineInstr *ReMatDefMI = getInstructionFromIndex(VNI->def);
Evan Chenge81fdb92007-12-06 00:01:56 +0000986 bool DefIsLoad = false;
Evan Chenga37ecfe2008-02-22 09:24:50 +0000987 if (!ReMatDefMI ||
Evan Chengc84ea132008-09-30 15:44:16 +0000988 !isReMaterializable(li, VNI, ReMatDefMI, SpillIs, DefIsLoad))
Evan Chenge81fdb92007-12-06 00:01:56 +0000989 return false;
990 isLoad |= DefIsLoad;
Evan Cheng9b741602007-11-12 06:35:08 +0000991 }
992 return true;
993}
994
Evan Cheng70e40de2008-02-25 08:50:41 +0000995/// FilterFoldedOps - Filter out two-address use operands. Return
996/// true if it finds any issue with the operands that ought to prevent
997/// folding.
998static bool FilterFoldedOps(MachineInstr *MI,
999 SmallVector<unsigned, 2> &Ops,
1000 unsigned &MRInfo,
1001 SmallVector<unsigned, 2> &FoldOps) {
Evan Cheng70e40de2008-02-25 08:50:41 +00001002 MRInfo = 0;
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001003 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1004 unsigned OpIdx = Ops[i];
Evan Chenga37ecfe2008-02-22 09:24:50 +00001005 MachineOperand &MO = MI->getOperand(OpIdx);
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001006 // FIXME: fold subreg use.
Evan Chenga37ecfe2008-02-22 09:24:50 +00001007 if (MO.getSubReg())
Evan Cheng70e40de2008-02-25 08:50:41 +00001008 return true;
Evan Chenga37ecfe2008-02-22 09:24:50 +00001009 if (MO.isDef())
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001010 MRInfo |= (unsigned)VirtRegMap::isMod;
1011 else {
1012 // Filter out two-address use operand(s).
Evan Cheng48555e82009-03-19 20:30:06 +00001013 if (MI->isRegTiedToDefOperand(OpIdx)) {
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001014 MRInfo = VirtRegMap::isModRef;
1015 continue;
1016 }
1017 MRInfo |= (unsigned)VirtRegMap::isRef;
1018 }
1019 FoldOps.push_back(OpIdx);
Evan Chengff52f082007-12-01 02:07:52 +00001020 }
Evan Cheng70e40de2008-02-25 08:50:41 +00001021 return false;
1022}
1023
1024
1025/// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
1026/// slot / to reg or any rematerialized load into ith operand of specified
1027/// MI. If it is successul, MI is updated with the newly created MI and
1028/// returns true.
1029bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
1030 VirtRegMap &vrm, MachineInstr *DefMI,
Lang Hamesd6a717c2009-11-03 23:52:08 +00001031 SlotIndex InstrIdx,
Evan Cheng70e40de2008-02-25 08:50:41 +00001032 SmallVector<unsigned, 2> &Ops,
1033 bool isSS, int Slot, unsigned Reg) {
Evan Cheng70e40de2008-02-25 08:50:41 +00001034 // If it is an implicit def instruction, just delete it.
Evan Chengfdc17062008-03-15 00:19:36 +00001035 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Cheng70e40de2008-02-25 08:50:41 +00001036 RemoveMachineInstrFromMaps(MI);
1037 vrm.RemoveMachineInstrFromMaps(MI);
1038 MI->eraseFromParent();
1039 ++numFolds;
1040 return true;
1041 }
1042
1043 // Filter the list of operand indexes that are to be folded. Abort if
1044 // any operand will prevent folding.
1045 unsigned MRInfo = 0;
1046 SmallVector<unsigned, 2> FoldOps;
1047 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1048 return false;
Evan Chengff52f082007-12-01 02:07:52 +00001049
Evan Cheng4c7ab522008-03-31 23:19:51 +00001050 // The only time it's safe to fold into a two address instruction is when
1051 // it's folding reload and spill from / into a spill stack slot.
1052 if (DefMI && (MRInfo & VirtRegMap::isMod))
Evan Chengd0201932008-02-23 03:38:34 +00001053 return false;
1054
Evan Cheng3a15a4e2008-02-08 22:05:27 +00001055 MachineInstr *fmi = isSS ? tii_->foldMemoryOperand(*mf_, MI, FoldOps, Slot)
1056 : tii_->foldMemoryOperand(*mf_, MI, FoldOps, DefMI);
Evan Cheng9b741602007-11-12 06:35:08 +00001057 if (fmi) {
Evan Chengda872532008-02-27 03:04:06 +00001058 // Remember this instruction uses the spill slot.
1059 if (isSS) vrm.addSpillSlotUse(Slot, fmi);
1060
Evan Cheng9b741602007-11-12 06:35:08 +00001061 // Attempt to fold the memory reference into the instruction. If
1062 // we can do this, we don't need to insert spill code.
Evan Cheng9b741602007-11-12 06:35:08 +00001063 MachineBasicBlock &MBB = *MI->getParent();
Evan Chengefe93672008-01-10 08:24:38 +00001064 if (isSS && !mf_->getFrameInfo()->isImmutableObjectIndex(Slot))
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001065 vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
Evan Chengcecc8222007-11-17 00:40:40 +00001066 vrm.transferSpillPts(MI, fmi);
Evan Cheng96c61312007-11-29 01:06:25 +00001067 vrm.transferRestorePts(MI, fmi);
Evan Cheng1eeb2ef2008-03-11 21:34:46 +00001068 vrm.transferEmergencySpills(MI, fmi);
Lang Hamesd6a717c2009-11-03 23:52:08 +00001069 ReplaceMachineInstrInMaps(MI, fmi);
Evan Cheng9b741602007-11-12 06:35:08 +00001070 MI = MBB.insert(MBB.erase(MI), fmi);
Evan Cheng96c61312007-11-29 01:06:25 +00001071 ++numFolds;
Evan Cheng9b741602007-11-12 06:35:08 +00001072 return true;
1073 }
1074 return false;
1075}
1076
Evan Chengebcba1e2007-12-05 03:22:34 +00001077/// canFoldMemoryOperand - Returns true if the specified load / store
1078/// folding is possible.
1079bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI,
Evan Cheng70e40de2008-02-25 08:50:41 +00001080 SmallVector<unsigned, 2> &Ops,
Evan Cheng71f75b42008-04-01 21:37:32 +00001081 bool ReMat) const {
Evan Cheng70e40de2008-02-25 08:50:41 +00001082 // Filter the list of operand indexes that are to be folded. Abort if
1083 // any operand will prevent folding.
1084 unsigned MRInfo = 0;
Evan Chengebcba1e2007-12-05 03:22:34 +00001085 SmallVector<unsigned, 2> FoldOps;
Evan Cheng70e40de2008-02-25 08:50:41 +00001086 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1087 return false;
Evan Chengebcba1e2007-12-05 03:22:34 +00001088
Evan Cheng71f75b42008-04-01 21:37:32 +00001089 // It's only legal to remat for a use, not a def.
1090 if (ReMat && (MRInfo & VirtRegMap::isMod))
Evan Cheng70e40de2008-02-25 08:50:41 +00001091 return false;
Evan Chengebcba1e2007-12-05 03:22:34 +00001092
Evan Chenga37ecfe2008-02-22 09:24:50 +00001093 return tii_->canFoldMemoryOperand(MI, FoldOps);
1094}
1095
Evan Chengcecc8222007-11-17 00:40:40 +00001096bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
Lang Hamesd6a717c2009-11-03 23:52:08 +00001097 LiveInterval::Ranges::const_iterator itr = li.ranges.begin();
1098
1099 MachineBasicBlock *mbb = indexes_->getMBBCoveringRange(itr->start, itr->end);
1100
1101 if (mbb == 0)
1102 return false;
1103
1104 for (++itr; itr != li.ranges.end(); ++itr) {
1105 MachineBasicBlock *mbb2 =
1106 indexes_->getMBBCoveringRange(itr->start, itr->end);
1107
1108 if (mbb2 != mbb)
Evan Chengcecc8222007-11-17 00:40:40 +00001109 return false;
1110 }
Lang Hamesd6a717c2009-11-03 23:52:08 +00001111
Evan Chengcecc8222007-11-17 00:40:40 +00001112 return true;
1113}
1114
Evan Chenga37ecfe2008-02-22 09:24:50 +00001115/// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
1116/// interval on to-be re-materialized operands of MI) with new register.
1117void LiveIntervals::rewriteImplicitOps(const LiveInterval &li,
1118 MachineInstr *MI, unsigned NewVReg,
1119 VirtRegMap &vrm) {
1120 // There is an implicit use. That means one of the other operand is
1121 // being remat'ed and the remat'ed instruction has li.reg as an
1122 // use operand. Make sure we rewrite that as well.
1123 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1124 MachineOperand &MO = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +00001125 if (!MO.isReg())
Evan Chenga37ecfe2008-02-22 09:24:50 +00001126 continue;
1127 unsigned Reg = MO.getReg();
1128 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
1129 continue;
1130 if (!vrm.isReMaterialized(Reg))
1131 continue;
1132 MachineInstr *ReMatMI = vrm.getReMaterializedMI(Reg);
Evan Chengc7daf1f2008-03-05 00:59:57 +00001133 MachineOperand *UseMO = ReMatMI->findRegisterUseOperand(li.reg);
1134 if (UseMO)
1135 UseMO->setReg(NewVReg);
Evan Chenga37ecfe2008-02-22 09:24:50 +00001136 }
1137}
1138
Evan Cheng9b741602007-11-12 06:35:08 +00001139/// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
1140/// for addIntervalsForSpills to rewrite uses / defs for the given live range.
Evan Chengebcba1e2007-12-05 03:22:34 +00001141bool LiveIntervals::
Evan Chenga37ecfe2008-02-22 09:24:50 +00001142rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
Lang Hamesd6a717c2009-11-03 23:52:08 +00001143 bool TrySplit, SlotIndex index, SlotIndex end,
Lang Hamesd8f30992009-09-04 20:41:11 +00001144 MachineInstr *MI,
Evan Chengcecc8222007-11-17 00:40:40 +00001145 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Cheng9b741602007-11-12 06:35:08 +00001146 unsigned Slot, int LdSlot,
1147 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chenga37ecfe2008-02-22 09:24:50 +00001148 VirtRegMap &vrm,
Evan Cheng9b741602007-11-12 06:35:08 +00001149 const TargetRegisterClass* rc,
1150 SmallVector<int, 4> &ReMatIds,
Evan Cheng26d17df2007-12-11 02:09:15 +00001151 const MachineLoopInfo *loopInfo,
Evan Chengc7666af2008-02-23 00:33:04 +00001152 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
Owen Andersonfeab1a82008-08-13 22:28:50 +00001153 DenseMap<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng97c5f1f2009-05-03 18:32:42 +00001154 std::vector<LiveInterval*> &NewLIs) {
Evan Chengebcba1e2007-12-05 03:22:34 +00001155 bool CanFold = false;
Evan Cheng9b741602007-11-12 06:35:08 +00001156 RestartInstruction:
1157 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1158 MachineOperand& mop = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +00001159 if (!mop.isReg())
Evan Cheng9b741602007-11-12 06:35:08 +00001160 continue;
1161 unsigned Reg = mop.getReg();
1162 unsigned RegI = Reg;
Dan Gohman1e57df32008-02-10 18:45:23 +00001163 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
Evan Cheng9b741602007-11-12 06:35:08 +00001164 continue;
Evan Cheng9b741602007-11-12 06:35:08 +00001165 if (Reg != li.reg)
1166 continue;
1167
1168 bool TryFold = !DefIsReMat;
Evan Cheng35d47762007-11-29 23:02:50 +00001169 bool FoldSS = true; // Default behavior unless it's a remat.
Evan Cheng9b741602007-11-12 06:35:08 +00001170 int FoldSlot = Slot;
1171 if (DefIsReMat) {
1172 // If this is the rematerializable definition MI itself and
1173 // all of its uses are rematerialized, simply delete it.
Evan Chengcecc8222007-11-17 00:40:40 +00001174 if (MI == ReMatOrigDefMI && CanDelete) {
Bill Wendling83c96ca2009-08-22 20:18:03 +00001175 DEBUG(errs() << "\t\t\t\tErasing re-materlizable def: "
1176 << MI << '\n');
Evan Cheng9b741602007-11-12 06:35:08 +00001177 RemoveMachineInstrFromMaps(MI);
Evan Cheng91e32d02007-11-28 01:28:46 +00001178 vrm.RemoveMachineInstrFromMaps(MI);
Evan Cheng9b741602007-11-12 06:35:08 +00001179 MI->eraseFromParent();
1180 break;
1181 }
1182
1183 // If def for this use can't be rematerialized, then try folding.
Evan Cheng96c61312007-11-29 01:06:25 +00001184 // If def is rematerializable and it's a load, also try folding.
Evan Cheng35d47762007-11-29 23:02:50 +00001185 TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad));
Evan Cheng9b741602007-11-12 06:35:08 +00001186 if (isLoad) {
1187 // Try fold loads (from stack slot, constant pool, etc.) into uses.
1188 FoldSS = isLoadSS;
1189 FoldSlot = LdSlot;
1190 }
1191 }
1192
Evan Cheng9b741602007-11-12 06:35:08 +00001193 // Scan all of the operands of this instruction rewriting operands
1194 // to use NewVReg instead of li.reg as appropriate. We do this for
1195 // two reasons:
1196 //
1197 // 1. If the instr reads the same spilled vreg multiple times, we
1198 // want to reuse the NewVReg.
1199 // 2. If the instr is a two-addr instruction, we are required to
1200 // keep the src/dst regs pinned.
1201 //
1202 // Keep track of whether we replace a use and/or def so that we can
1203 // create the spill interval with the appropriate range.
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001204
Evan Chengcecc8222007-11-17 00:40:40 +00001205 HasUse = mop.isUse();
1206 HasDef = mop.isDef();
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001207 SmallVector<unsigned, 2> Ops;
1208 Ops.push_back(i);
Evan Cheng9b741602007-11-12 06:35:08 +00001209 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001210 const MachineOperand &MOj = MI->getOperand(j);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +00001211 if (!MOj.isReg())
Evan Cheng9b741602007-11-12 06:35:08 +00001212 continue;
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001213 unsigned RegJ = MOj.getReg();
Dan Gohman1e57df32008-02-10 18:45:23 +00001214 if (RegJ == 0 || TargetRegisterInfo::isPhysicalRegister(RegJ))
Evan Cheng9b741602007-11-12 06:35:08 +00001215 continue;
1216 if (RegJ == RegI) {
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001217 Ops.push_back(j);
Evan Chengcb11cae2009-07-17 19:43:40 +00001218 if (!MOj.isUndef()) {
1219 HasUse |= MOj.isUse();
1220 HasDef |= MOj.isDef();
1221 }
Evan Cheng9b741602007-11-12 06:35:08 +00001222 }
1223 }
1224
David Greenee269f3e2008-10-27 17:38:59 +00001225 // Create a new virtual register for the spill interval.
1226 // Create the new register now so we can map the fold instruction
1227 // to the new register so when it is unfolded we get the correct
1228 // answer.
1229 bool CreatedNewVReg = false;
1230 if (NewVReg == 0) {
1231 NewVReg = mri_->createVirtualRegister(rc);
1232 vrm.grow();
1233 CreatedNewVReg = true;
1234 }
1235
Evan Chengba221ca2008-06-06 07:54:39 +00001236 if (!TryFold)
1237 CanFold = false;
1238 else {
Evan Chengebcba1e2007-12-05 03:22:34 +00001239 // Do not fold load / store here if we are splitting. We'll find an
1240 // optimal point to insert a load / store later.
1241 if (!TrySplit) {
1242 if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
David Greenee269f3e2008-10-27 17:38:59 +00001243 Ops, FoldSS, FoldSlot, NewVReg)) {
Evan Chengebcba1e2007-12-05 03:22:34 +00001244 // Folding the load/store can completely change the instruction in
1245 // unpredictable ways, rescan it from the beginning.
David Greenee269f3e2008-10-27 17:38:59 +00001246
1247 if (FoldSS) {
1248 // We need to give the new vreg the same stack slot as the
1249 // spilled interval.
1250 vrm.assignVirt2StackSlot(NewVReg, FoldSlot);
1251 }
1252
Evan Chengebcba1e2007-12-05 03:22:34 +00001253 HasUse = false;
1254 HasDef = false;
1255 CanFold = false;
Evan Cheng97c5f1f2009-05-03 18:32:42 +00001256 if (isNotInMIMap(MI))
Evan Cheng909ab8b42008-04-09 20:57:25 +00001257 break;
Evan Chengebcba1e2007-12-05 03:22:34 +00001258 goto RestartInstruction;
1259 }
1260 } else {
Evan Chengba221ca2008-06-06 07:54:39 +00001261 // We'll try to fold it later if it's profitable.
Evan Cheng71f75b42008-04-01 21:37:32 +00001262 CanFold = canFoldMemoryOperand(MI, Ops, DefIsReMat);
Evan Chengebcba1e2007-12-05 03:22:34 +00001263 }
Evan Chengba221ca2008-06-06 07:54:39 +00001264 }
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001265
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001266 mop.setReg(NewVReg);
Evan Chenga37ecfe2008-02-22 09:24:50 +00001267 if (mop.isImplicit())
1268 rewriteImplicitOps(li, MI, NewVReg, vrm);
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001269
1270 // Reuse NewVReg for other reads.
Evan Chenga37ecfe2008-02-22 09:24:50 +00001271 for (unsigned j = 0, e = Ops.size(); j != e; ++j) {
1272 MachineOperand &mopj = MI->getOperand(Ops[j]);
1273 mopj.setReg(NewVReg);
1274 if (mopj.isImplicit())
1275 rewriteImplicitOps(li, MI, NewVReg, vrm);
1276 }
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001277
Evan Chengcecc8222007-11-17 00:40:40 +00001278 if (CreatedNewVReg) {
1279 if (DefIsReMat) {
Evan Cheng463a3e42009-07-16 09:20:10 +00001280 vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI);
Evan Chenga37ecfe2008-02-22 09:24:50 +00001281 if (ReMatIds[VNI->id] == VirtRegMap::MAX_STACK_SLOT) {
Evan Chengcecc8222007-11-17 00:40:40 +00001282 // Each valnum may have its own remat id.
Evan Chenga37ecfe2008-02-22 09:24:50 +00001283 ReMatIds[VNI->id] = vrm.assignVirtReMatId(NewVReg);
Evan Chengcecc8222007-11-17 00:40:40 +00001284 } else {
Evan Chenga37ecfe2008-02-22 09:24:50 +00001285 vrm.assignVirtReMatId(NewVReg, ReMatIds[VNI->id]);
Evan Chengcecc8222007-11-17 00:40:40 +00001286 }
1287 if (!CanDelete || (HasUse && HasDef)) {
1288 // If this is a two-addr instruction then its use operands are
1289 // rematerializable but its def is not. It should be assigned a
1290 // stack slot.
1291 vrm.assignVirt2StackSlot(NewVReg, Slot);
1292 }
Evan Cheng9b741602007-11-12 06:35:08 +00001293 } else {
Evan Cheng9b741602007-11-12 06:35:08 +00001294 vrm.assignVirt2StackSlot(NewVReg, Slot);
1295 }
Evan Cheng35d47762007-11-29 23:02:50 +00001296 } else if (HasUse && HasDef &&
1297 vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) {
1298 // If this interval hasn't been assigned a stack slot (because earlier
1299 // def is a deleted remat def), do it now.
1300 assert(Slot != VirtRegMap::NO_STACK_SLOT);
1301 vrm.assignVirt2StackSlot(NewVReg, Slot);
Evan Cheng9b741602007-11-12 06:35:08 +00001302 }
1303
Evan Chengc7666af2008-02-23 00:33:04 +00001304 // Re-matting an instruction with virtual register use. Add the
1305 // register as an implicit use on the use MI.
1306 if (DefIsReMat && ImpUse)
1307 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1308
Evan Cheng047e9d12009-04-21 22:46:52 +00001309 // Create a new register interval for this spill / remat.
Evan Cheng9b741602007-11-12 06:35:08 +00001310 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Chengcecc8222007-11-17 00:40:40 +00001311 if (CreatedNewVReg) {
1312 NewLIs.push_back(&nI);
Evan Cheng7b632362007-11-29 10:12:14 +00001313 MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg));
Evan Chengcecc8222007-11-17 00:40:40 +00001314 if (TrySplit)
1315 vrm.setIsSplitFromReg(NewVReg, li.reg);
1316 }
Evan Cheng9b741602007-11-12 06:35:08 +00001317
1318 if (HasUse) {
Evan Chengcecc8222007-11-17 00:40:40 +00001319 if (CreatedNewVReg) {
Lang Hamesd6a717c2009-11-03 23:52:08 +00001320 LiveRange LR(index.getLoadIndex(), index.getDefIndex(),
1321 nI.getNextValue(SlotIndex(), 0, false, VNInfoAllocator));
Bill Wendling83c96ca2009-08-22 20:18:03 +00001322 DEBUG(errs() << " +" << LR);
Evan Chengcecc8222007-11-17 00:40:40 +00001323 nI.addRange(LR);
1324 } else {
1325 // Extend the split live interval to this def / use.
Lang Hamesd6a717c2009-11-03 23:52:08 +00001326 SlotIndex End = index.getDefIndex();
Evan Chengcecc8222007-11-17 00:40:40 +00001327 LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
1328 nI.getValNumInfo(nI.getNumValNums()-1));
Bill Wendling83c96ca2009-08-22 20:18:03 +00001329 DEBUG(errs() << " +" << LR);
Evan Chengcecc8222007-11-17 00:40:40 +00001330 nI.addRange(LR);
1331 }
Evan Cheng9b741602007-11-12 06:35:08 +00001332 }
1333 if (HasDef) {
Lang Hamesd6a717c2009-11-03 23:52:08 +00001334 LiveRange LR(index.getDefIndex(), index.getStoreIndex(),
1335 nI.getNextValue(SlotIndex(), 0, false, VNInfoAllocator));
Bill Wendling83c96ca2009-08-22 20:18:03 +00001336 DEBUG(errs() << " +" << LR);
Evan Cheng9b741602007-11-12 06:35:08 +00001337 nI.addRange(LR);
1338 }
Evan Chengcecc8222007-11-17 00:40:40 +00001339
Bill Wendling83c96ca2009-08-22 20:18:03 +00001340 DEBUG({
1341 errs() << "\t\t\t\tAdded new interval: ";
1342 nI.print(errs(), tri_);
1343 errs() << '\n';
1344 });
Evan Cheng9b741602007-11-12 06:35:08 +00001345 }
Evan Chengebcba1e2007-12-05 03:22:34 +00001346 return CanFold;
Evan Cheng9b741602007-11-12 06:35:08 +00001347}
Evan Chengcecc8222007-11-17 00:40:40 +00001348bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
Evan Cheng96c61312007-11-29 01:06:25 +00001349 const VNInfo *VNI,
Lang Hamesd8f30992009-09-04 20:41:11 +00001350 MachineBasicBlock *MBB,
Lang Hamesd6a717c2009-11-03 23:52:08 +00001351 SlotIndex Idx) const {
1352 SlotIndex End = getMBBEndIdx(MBB);
Evan Cheng96c61312007-11-29 01:06:25 +00001353 for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
Lang Hamesd6a717c2009-11-03 23:52:08 +00001354 if (VNI->kills[j].isPHI())
Lang Hamesd2bd8622009-07-09 03:57:02 +00001355 continue;
1356
Lang Hamesd6a717c2009-11-03 23:52:08 +00001357 SlotIndex KillIdx = VNI->kills[j];
Evan Cheng96c61312007-11-29 01:06:25 +00001358 if (KillIdx > Idx && KillIdx < End)
1359 return true;
Evan Chengcecc8222007-11-17 00:40:40 +00001360 }
1361 return false;
1362}
1363
Evan Cheng44fccf22008-02-21 00:34:19 +00001364/// RewriteInfo - Keep track of machine instrs that will be rewritten
1365/// during spilling.
Dan Gohman089efff2008-05-13 00:00:25 +00001366namespace {
1367 struct RewriteInfo {
Lang Hamesd6a717c2009-11-03 23:52:08 +00001368 SlotIndex Index;
Dan Gohman089efff2008-05-13 00:00:25 +00001369 MachineInstr *MI;
1370 bool HasUse;
1371 bool HasDef;
Lang Hamesd6a717c2009-11-03 23:52:08 +00001372 RewriteInfo(SlotIndex i, MachineInstr *mi, bool u, bool d)
Dan Gohman089efff2008-05-13 00:00:25 +00001373 : Index(i), MI(mi), HasUse(u), HasDef(d) {}
1374 };
Evan Cheng44fccf22008-02-21 00:34:19 +00001375
Dan Gohman089efff2008-05-13 00:00:25 +00001376 struct RewriteInfoCompare {
1377 bool operator()(const RewriteInfo &LHS, const RewriteInfo &RHS) const {
1378 return LHS.Index < RHS.Index;
1379 }
1380 };
1381}
Evan Cheng44fccf22008-02-21 00:34:19 +00001382
Evan Cheng9b741602007-11-12 06:35:08 +00001383void LiveIntervals::
Evan Chengcecc8222007-11-17 00:40:40 +00001384rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
Evan Cheng9b741602007-11-12 06:35:08 +00001385 LiveInterval::Ranges::const_iterator &I,
Evan Chengcecc8222007-11-17 00:40:40 +00001386 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Cheng9b741602007-11-12 06:35:08 +00001387 unsigned Slot, int LdSlot,
1388 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chenga37ecfe2008-02-22 09:24:50 +00001389 VirtRegMap &vrm,
Evan Cheng9b741602007-11-12 06:35:08 +00001390 const TargetRegisterClass* rc,
1391 SmallVector<int, 4> &ReMatIds,
Evan Cheng26d17df2007-12-11 02:09:15 +00001392 const MachineLoopInfo *loopInfo,
Evan Chengcecc8222007-11-17 00:40:40 +00001393 BitVector &SpillMBBs,
Owen Andersonfeab1a82008-08-13 22:28:50 +00001394 DenseMap<unsigned, std::vector<SRInfo> > &SpillIdxes,
Evan Cheng96c61312007-11-29 01:06:25 +00001395 BitVector &RestoreMBBs,
Owen Andersonfeab1a82008-08-13 22:28:50 +00001396 DenseMap<unsigned, std::vector<SRInfo> > &RestoreIdxes,
1397 DenseMap<unsigned,unsigned> &MBBVRegsMap,
Evan Cheng97c5f1f2009-05-03 18:32:42 +00001398 std::vector<LiveInterval*> &NewLIs) {
Evan Chengebcba1e2007-12-05 03:22:34 +00001399 bool AllCanFold = true;
Evan Chengcecc8222007-11-17 00:40:40 +00001400 unsigned NewVReg = 0;
Lang Hamesd6a717c2009-11-03 23:52:08 +00001401 SlotIndex start = I->start.getBaseIndex();
1402 SlotIndex end = I->end.getPrevSlot().getBaseIndex().getNextIndex();
Evan Cheng9b741602007-11-12 06:35:08 +00001403
Evan Cheng44fccf22008-02-21 00:34:19 +00001404 // First collect all the def / use in this live range that will be rewritten.
Evan Cheng909ab8b42008-04-09 20:57:25 +00001405 // Make sure they are sorted according to instruction index.
Evan Cheng44fccf22008-02-21 00:34:19 +00001406 std::vector<RewriteInfo> RewriteMIs;
Evan Chenga37ecfe2008-02-22 09:24:50 +00001407 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1408 re = mri_->reg_end(); ri != re; ) {
Evan Cheng70f68e92008-04-03 16:39:43 +00001409 MachineInstr *MI = &*ri;
Evan Cheng44fccf22008-02-21 00:34:19 +00001410 MachineOperand &O = ri.getOperand();
1411 ++ri;
Evan Cheng8adc74e2008-03-31 07:53:30 +00001412 assert(!O.isImplicit() && "Spilling register that's used as implicit use?");
Lang Hamesd6a717c2009-11-03 23:52:08 +00001413 SlotIndex index = getInstructionIndex(MI);
Evan Cheng44fccf22008-02-21 00:34:19 +00001414 if (index < start || index >= end)
1415 continue;
Evan Chengcb11cae2009-07-17 19:43:40 +00001416
1417 if (O.isUndef())
Evan Chengc33577b2008-07-12 01:56:02 +00001418 // Must be defined by an implicit def. It should not be spilled. Note,
1419 // this is for correctness reason. e.g.
1420 // 8 %reg1024<def> = IMPLICIT_DEF
1421 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1422 // The live range [12, 14) are not part of the r1024 live interval since
1423 // it's defined by an implicit def. It will not conflicts with live
1424 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengc3c41c92008-07-12 02:22:07 +00001425 // easily see a situation where both registers are reloaded before
Evan Chengc33577b2008-07-12 01:56:02 +00001426 // the INSERT_SUBREG and both target registers that would overlap.
1427 continue;
Evan Cheng44fccf22008-02-21 00:34:19 +00001428 RewriteMIs.push_back(RewriteInfo(index, MI, O.isUse(), O.isDef()));
1429 }
1430 std::sort(RewriteMIs.begin(), RewriteMIs.end(), RewriteInfoCompare());
1431
Evan Chengc7666af2008-02-23 00:33:04 +00001432 unsigned ImpUse = DefIsReMat ? getReMatImplicitUse(li, ReMatDefMI) : 0;
Evan Cheng44fccf22008-02-21 00:34:19 +00001433 // Now rewrite the defs and uses.
1434 for (unsigned i = 0, e = RewriteMIs.size(); i != e; ) {
1435 RewriteInfo &rwi = RewriteMIs[i];
1436 ++i;
Lang Hamesd6a717c2009-11-03 23:52:08 +00001437 SlotIndex index = rwi.Index;
Evan Cheng44fccf22008-02-21 00:34:19 +00001438 bool MIHasUse = rwi.HasUse;
1439 bool MIHasDef = rwi.HasDef;
1440 MachineInstr *MI = rwi.MI;
1441 // If MI def and/or use the same register multiple times, then there
1442 // are multiple entries.
Evan Chengc7666af2008-02-23 00:33:04 +00001443 unsigned NumUses = MIHasUse;
Evan Cheng44fccf22008-02-21 00:34:19 +00001444 while (i != e && RewriteMIs[i].MI == MI) {
1445 assert(RewriteMIs[i].Index == index);
Evan Chengc7666af2008-02-23 00:33:04 +00001446 bool isUse = RewriteMIs[i].HasUse;
1447 if (isUse) ++NumUses;
1448 MIHasUse |= isUse;
Evan Cheng44fccf22008-02-21 00:34:19 +00001449 MIHasDef |= RewriteMIs[i].HasDef;
1450 ++i;
1451 }
Evan Chengcecc8222007-11-17 00:40:40 +00001452 MachineBasicBlock *MBB = MI->getParent();
Evan Chengc7666af2008-02-23 00:33:04 +00001453
Evan Cheng9c48ca72008-05-23 23:00:04 +00001454 if (ImpUse && MI != ReMatDefMI) {
Evan Chengc7666af2008-02-23 00:33:04 +00001455 // Re-matting an instruction with virtual register use. Update the
Evan Cheng8adc74e2008-03-31 07:53:30 +00001456 // register interval's spill weight to HUGE_VALF to prevent it from
1457 // being spilled.
Evan Chengc7666af2008-02-23 00:33:04 +00001458 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng8adc74e2008-03-31 07:53:30 +00001459 ImpLi.weight = HUGE_VALF;
Evan Chengc7666af2008-02-23 00:33:04 +00001460 }
1461
Evan Cheng44fccf22008-02-21 00:34:19 +00001462 unsigned MBBId = MBB->getNumber();
Evan Chengebcba1e2007-12-05 03:22:34 +00001463 unsigned ThisVReg = 0;
Evan Cheng1083a2f2007-12-03 09:58:48 +00001464 if (TrySplit) {
Owen Andersonfeab1a82008-08-13 22:28:50 +00001465 DenseMap<unsigned,unsigned>::iterator NVI = MBBVRegsMap.find(MBBId);
Evan Cheng7b632362007-11-29 10:12:14 +00001466 if (NVI != MBBVRegsMap.end()) {
Evan Chengebcba1e2007-12-05 03:22:34 +00001467 ThisVReg = NVI->second;
Evan Cheng7b632362007-11-29 10:12:14 +00001468 // One common case:
1469 // x = use
1470 // ...
1471 // ...
1472 // def = ...
1473 // = use
1474 // It's better to start a new interval to avoid artifically
1475 // extend the new interval.
Evan Cheng7b632362007-11-29 10:12:14 +00001476 if (MIHasDef && !MIHasUse) {
1477 MBBVRegsMap.erase(MBB->getNumber());
Evan Chengebcba1e2007-12-05 03:22:34 +00001478 ThisVReg = 0;
Evan Cheng7b632362007-11-29 10:12:14 +00001479 }
1480 }
Evan Cheng91e32d02007-11-28 01:28:46 +00001481 }
Evan Chengebcba1e2007-12-05 03:22:34 +00001482
1483 bool IsNew = ThisVReg == 0;
1484 if (IsNew) {
1485 // This ends the previous live interval. If all of its def / use
1486 // can be folded, give it a low spill weight.
1487 if (NewVReg && TrySplit && AllCanFold) {
1488 LiveInterval &nI = getOrCreateInterval(NewVReg);
1489 nI.weight /= 10.0F;
1490 }
1491 AllCanFold = true;
1492 }
1493 NewVReg = ThisVReg;
1494
Evan Chengcecc8222007-11-17 00:40:40 +00001495 bool HasDef = false;
1496 bool HasUse = false;
Evan Chenga37ecfe2008-02-22 09:24:50 +00001497 bool CanFold = rewriteInstructionForSpills(li, I->valno, TrySplit,
Evan Chengba221ca2008-06-06 07:54:39 +00001498 index, end, MI, ReMatOrigDefMI, ReMatDefMI,
1499 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
1500 CanDelete, vrm, rc, ReMatIds, loopInfo, NewVReg,
Evan Cheng97c5f1f2009-05-03 18:32:42 +00001501 ImpUse, HasDef, HasUse, MBBVRegsMap, NewLIs);
Evan Chengcecc8222007-11-17 00:40:40 +00001502 if (!HasDef && !HasUse)
1503 continue;
1504
Evan Chengebcba1e2007-12-05 03:22:34 +00001505 AllCanFold &= CanFold;
1506
Evan Chengcecc8222007-11-17 00:40:40 +00001507 // Update weight of spill interval.
1508 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng1083a2f2007-12-03 09:58:48 +00001509 if (!TrySplit) {
Evan Chengcecc8222007-11-17 00:40:40 +00001510 // The spill weight is now infinity as it cannot be spilled again.
1511 nI.weight = HUGE_VALF;
Evan Cheng96c61312007-11-29 01:06:25 +00001512 continue;
Evan Chengcecc8222007-11-17 00:40:40 +00001513 }
Evan Cheng96c61312007-11-29 01:06:25 +00001514
1515 // Keep track of the last def and first use in each MBB.
Evan Cheng96c61312007-11-29 01:06:25 +00001516 if (HasDef) {
1517 if (MI != ReMatOrigDefMI || !CanDelete) {
Evan Cheng96c61312007-11-29 01:06:25 +00001518 bool HasKill = false;
1519 if (!HasUse)
Lang Hamesd6a717c2009-11-03 23:52:08 +00001520 HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, index.getDefIndex());
Evan Cheng96c61312007-11-29 01:06:25 +00001521 else {
Evan Cheng7b632362007-11-29 10:12:14 +00001522 // If this is a two-address code, then this index starts a new VNInfo.
Lang Hamesd6a717c2009-11-03 23:52:08 +00001523 const VNInfo *VNI = li.findDefinedVNInfoForRegInt(index.getDefIndex());
Evan Cheng96c61312007-11-29 01:06:25 +00001524 if (VNI)
Lang Hamesd6a717c2009-11-03 23:52:08 +00001525 HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, index.getDefIndex());
Evan Cheng96c61312007-11-29 01:06:25 +00001526 }
Owen Andersonfeab1a82008-08-13 22:28:50 +00001527 DenseMap<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng999f9472007-12-01 04:42:39 +00001528 SpillIdxes.find(MBBId);
Evan Cheng96c61312007-11-29 01:06:25 +00001529 if (!HasKill) {
Evan Cheng7b632362007-11-29 10:12:14 +00001530 if (SII == SpillIdxes.end()) {
1531 std::vector<SRInfo> S;
1532 S.push_back(SRInfo(index, NewVReg, true));
1533 SpillIdxes.insert(std::make_pair(MBBId, S));
1534 } else if (SII->second.back().vreg != NewVReg) {
1535 SII->second.push_back(SRInfo(index, NewVReg, true));
Lang Hamesd8f30992009-09-04 20:41:11 +00001536 } else if (index > SII->second.back().index) {
Evan Cheng96c61312007-11-29 01:06:25 +00001537 // If there is an earlier def and this is a two-address
1538 // instruction, then it's not possible to fold the store (which
1539 // would also fold the load).
Evan Cheng7b632362007-11-29 10:12:14 +00001540 SRInfo &Info = SII->second.back();
1541 Info.index = index;
1542 Info.canFold = !HasUse;
Evan Cheng96c61312007-11-29 01:06:25 +00001543 }
1544 SpillMBBs.set(MBBId);
Evan Cheng999f9472007-12-01 04:42:39 +00001545 } else if (SII != SpillIdxes.end() &&
1546 SII->second.back().vreg == NewVReg &&
Lang Hamesd8f30992009-09-04 20:41:11 +00001547 index > SII->second.back().index) {
Evan Cheng999f9472007-12-01 04:42:39 +00001548 // There is an earlier def that's not killed (must be two-address).
1549 // The spill is no longer needed.
1550 SII->second.pop_back();
1551 if (SII->second.empty()) {
1552 SpillIdxes.erase(MBBId);
1553 SpillMBBs.reset(MBBId);
1554 }
Evan Cheng96c61312007-11-29 01:06:25 +00001555 }
1556 }
Evan Cheng96c61312007-11-29 01:06:25 +00001557 }
1558
1559 if (HasUse) {
Owen Andersonfeab1a82008-08-13 22:28:50 +00001560 DenseMap<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng96c61312007-11-29 01:06:25 +00001561 SpillIdxes.find(MBBId);
Evan Cheng7b632362007-11-29 10:12:14 +00001562 if (SII != SpillIdxes.end() &&
1563 SII->second.back().vreg == NewVReg &&
Lang Hamesd8f30992009-09-04 20:41:11 +00001564 index > SII->second.back().index)
Evan Cheng96c61312007-11-29 01:06:25 +00001565 // Use(s) following the last def, it's not safe to fold the spill.
Evan Cheng7b632362007-11-29 10:12:14 +00001566 SII->second.back().canFold = false;
Owen Andersonfeab1a82008-08-13 22:28:50 +00001567 DenseMap<unsigned, std::vector<SRInfo> >::iterator RII =
Evan Cheng96c61312007-11-29 01:06:25 +00001568 RestoreIdxes.find(MBBId);
Evan Cheng7b632362007-11-29 10:12:14 +00001569 if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg)
Evan Cheng96c61312007-11-29 01:06:25 +00001570 // If we are splitting live intervals, only fold if it's the first
1571 // use and there isn't another use later in the MBB.
Evan Cheng7b632362007-11-29 10:12:14 +00001572 RII->second.back().canFold = false;
Evan Cheng96c61312007-11-29 01:06:25 +00001573 else if (IsNew) {
1574 // Only need a reload if there isn't an earlier def / use.
Evan Cheng7b632362007-11-29 10:12:14 +00001575 if (RII == RestoreIdxes.end()) {
1576 std::vector<SRInfo> Infos;
1577 Infos.push_back(SRInfo(index, NewVReg, true));
1578 RestoreIdxes.insert(std::make_pair(MBBId, Infos));
1579 } else {
1580 RII->second.push_back(SRInfo(index, NewVReg, true));
1581 }
Evan Cheng96c61312007-11-29 01:06:25 +00001582 RestoreMBBs.set(MBBId);
1583 }
1584 }
1585
1586 // Update spill weight.
Evan Cheng26d17df2007-12-11 02:09:15 +00001587 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Chengf7b45f42008-06-21 06:45:54 +00001588 nI.weight += getSpillWeight(HasDef, HasUse, loopDepth);
Evan Cheng9b741602007-11-12 06:35:08 +00001589 }
Evan Chengebcba1e2007-12-05 03:22:34 +00001590
1591 if (NewVReg && TrySplit && AllCanFold) {
1592 // If all of its def / use can be folded, give it a low spill weight.
1593 LiveInterval &nI = getOrCreateInterval(NewVReg);
1594 nI.weight /= 10.0F;
1595 }
Evan Cheng9b741602007-11-12 06:35:08 +00001596}
1597
Lang Hamesd6a717c2009-11-03 23:52:08 +00001598bool LiveIntervals::alsoFoldARestore(int Id, SlotIndex index,
Lang Hamesd8f30992009-09-04 20:41:11 +00001599 unsigned vr, BitVector &RestoreMBBs,
Owen Andersonfeab1a82008-08-13 22:28:50 +00001600 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
Evan Cheng7b632362007-11-29 10:12:14 +00001601 if (!RestoreMBBs[Id])
1602 return false;
1603 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1604 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1605 if (Restores[i].index == index &&
1606 Restores[i].vreg == vr &&
1607 Restores[i].canFold)
1608 return true;
1609 return false;
1610}
1611
Lang Hamesd6a717c2009-11-03 23:52:08 +00001612void LiveIntervals::eraseRestoreInfo(int Id, SlotIndex index,
Lang Hamesd8f30992009-09-04 20:41:11 +00001613 unsigned vr, BitVector &RestoreMBBs,
Owen Andersonfeab1a82008-08-13 22:28:50 +00001614 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
Evan Cheng7b632362007-11-29 10:12:14 +00001615 if (!RestoreMBBs[Id])
1616 return;
1617 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1618 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1619 if (Restores[i].index == index && Restores[i].vreg)
Lang Hamesd6a717c2009-11-03 23:52:08 +00001620 Restores[i].index = SlotIndex();
Evan Cheng7b632362007-11-29 10:12:14 +00001621}
Evan Chengcecc8222007-11-17 00:40:40 +00001622
Evan Cheng7b88cbc2008-04-11 17:53:36 +00001623/// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
1624/// spilled and create empty intervals for their uses.
1625void
1626LiveIntervals::handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
1627 const TargetRegisterClass* rc,
1628 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng70f68e92008-04-03 16:39:43 +00001629 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1630 re = mri_->reg_end(); ri != re; ) {
Evan Cheng7b88cbc2008-04-11 17:53:36 +00001631 MachineOperand &O = ri.getOperand();
Evan Cheng70f68e92008-04-03 16:39:43 +00001632 MachineInstr *MI = &*ri;
1633 ++ri;
Evan Cheng7b88cbc2008-04-11 17:53:36 +00001634 if (O.isDef()) {
1635 assert(MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF &&
1636 "Register def was not rewritten?");
1637 RemoveMachineInstrFromMaps(MI);
1638 vrm.RemoveMachineInstrFromMaps(MI);
1639 MI->eraseFromParent();
1640 } else {
1641 // This must be an use of an implicit_def so it's not part of the live
1642 // interval. Create a new empty live interval for it.
1643 // FIXME: Can we simply erase some of the instructions? e.g. Stores?
1644 unsigned NewVReg = mri_->createVirtualRegister(rc);
1645 vrm.grow();
1646 vrm.setIsImplicitlyDefined(NewVReg);
1647 NewLIs.push_back(&getOrCreateInterval(NewVReg));
1648 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1649 MachineOperand &MO = MI->getOperand(i);
Evan Cheng9c73db12009-06-30 08:49:04 +00001650 if (MO.isReg() && MO.getReg() == li.reg) {
Evan Cheng7b88cbc2008-04-11 17:53:36 +00001651 MO.setReg(NewVReg);
Evan Cheng9c73db12009-06-30 08:49:04 +00001652 MO.setIsUndef();
Evan Cheng9c73db12009-06-30 08:49:04 +00001653 }
Evan Cheng7b88cbc2008-04-11 17:53:36 +00001654 }
1655 }
Evan Cheng70f68e92008-04-03 16:39:43 +00001656 }
1657}
1658
Evan Cheng9b741602007-11-12 06:35:08 +00001659std::vector<LiveInterval*> LiveIntervals::
Owen Anderson29042782008-08-18 18:05:32 +00001660addIntervalsForSpillsFast(const LiveInterval &li,
1661 const MachineLoopInfo *loopInfo,
Evan Cheng97c5f1f2009-05-03 18:32:42 +00001662 VirtRegMap &vrm) {
Owen Anderson06ab6d72008-08-18 23:41:04 +00001663 unsigned slot = vrm.assignVirt2StackSlot(li.reg);
Owen Anderson29042782008-08-18 18:05:32 +00001664
1665 std::vector<LiveInterval*> added;
1666
1667 assert(li.weight != HUGE_VALF &&
1668 "attempt to spill already spilled interval!");
1669
Bill Wendling83c96ca2009-08-22 20:18:03 +00001670 DEBUG({
1671 errs() << "\t\t\t\tadding intervals for spills for interval: ";
1672 li.dump();
1673 errs() << '\n';
1674 });
Owen Anderson29042782008-08-18 18:05:32 +00001675
1676 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
1677
Owen Anderson51dcfbe2008-08-19 22:12:11 +00001678 MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg);
1679 while (RI != mri_->reg_end()) {
1680 MachineInstr* MI = &*RI;
1681
1682 SmallVector<unsigned, 2> Indices;
1683 bool HasUse = false;
1684 bool HasDef = false;
1685
1686 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1687 MachineOperand& mop = MI->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +00001688 if (!mop.isReg() || mop.getReg() != li.reg) continue;
Owen Anderson51dcfbe2008-08-19 22:12:11 +00001689
1690 HasUse |= MI->getOperand(i).isUse();
1691 HasDef |= MI->getOperand(i).isDef();
1692
1693 Indices.push_back(i);
1694 }
1695
1696 if (!tryFoldMemoryOperand(MI, vrm, NULL, getInstructionIndex(MI),
1697 Indices, true, slot, li.reg)) {
1698 unsigned NewVReg = mri_->createVirtualRegister(rc);
Owen Anderson268000d2008-08-18 21:20:32 +00001699 vrm.grow();
Owen Anderson06ab6d72008-08-18 23:41:04 +00001700 vrm.assignVirt2StackSlot(NewVReg, slot);
1701
Owen Anderson51dcfbe2008-08-19 22:12:11 +00001702 // create a new register for this spill
1703 LiveInterval &nI = getOrCreateInterval(NewVReg);
Owen Anderson29042782008-08-18 18:05:32 +00001704
Owen Anderson51dcfbe2008-08-19 22:12:11 +00001705 // the spill weight is now infinity as it
1706 // cannot be spilled again
1707 nI.weight = HUGE_VALF;
1708
1709 // Rewrite register operands to use the new vreg.
1710 for (SmallVectorImpl<unsigned>::iterator I = Indices.begin(),
1711 E = Indices.end(); I != E; ++I) {
1712 MI->getOperand(*I).setReg(NewVReg);
1713
1714 if (MI->getOperand(*I).isUse())
1715 MI->getOperand(*I).setIsKill(true);
1716 }
1717
1718 // Fill in the new live interval.
Lang Hamesd6a717c2009-11-03 23:52:08 +00001719 SlotIndex index = getInstructionIndex(MI);
Owen Anderson51dcfbe2008-08-19 22:12:11 +00001720 if (HasUse) {
Lang Hamesd6a717c2009-11-03 23:52:08 +00001721 LiveRange LR(index.getLoadIndex(), index.getUseIndex(),
1722 nI.getNextValue(SlotIndex(), 0, false,
Lang Hamesd8f30992009-09-04 20:41:11 +00001723 getVNInfoAllocator()));
Bill Wendling83c96ca2009-08-22 20:18:03 +00001724 DEBUG(errs() << " +" << LR);
Owen Anderson51dcfbe2008-08-19 22:12:11 +00001725 nI.addRange(LR);
1726 vrm.addRestorePoint(NewVReg, MI);
1727 }
1728 if (HasDef) {
Lang Hamesd6a717c2009-11-03 23:52:08 +00001729 LiveRange LR(index.getDefIndex(), index.getStoreIndex(),
1730 nI.getNextValue(SlotIndex(), 0, false,
Lang Hamesd8f30992009-09-04 20:41:11 +00001731 getVNInfoAllocator()));
Bill Wendling83c96ca2009-08-22 20:18:03 +00001732 DEBUG(errs() << " +" << LR);
Owen Anderson51dcfbe2008-08-19 22:12:11 +00001733 nI.addRange(LR);
1734 vrm.addSpillPoint(NewVReg, true, MI);
1735 }
1736
Owen Anderson06ab6d72008-08-18 23:41:04 +00001737 added.push_back(&nI);
Owen Andersonfcfae3e2008-08-18 18:38:12 +00001738
Bill Wendling83c96ca2009-08-22 20:18:03 +00001739 DEBUG({
1740 errs() << "\t\t\t\tadded new interval: ";
1741 nI.dump();
1742 errs() << '\n';
1743 });
Owen Anderson51dcfbe2008-08-19 22:12:11 +00001744 }
Owen Anderson268000d2008-08-18 21:20:32 +00001745
Owen Anderson268000d2008-08-18 21:20:32 +00001746
Owen Anderson51dcfbe2008-08-19 22:12:11 +00001747 RI = mri_->reg_begin(li.reg);
Owen Anderson29042782008-08-18 18:05:32 +00001748 }
Owen Anderson29042782008-08-18 18:05:32 +00001749
1750 return added;
1751}
1752
1753std::vector<LiveInterval*> LiveIntervals::
Evan Chengcecc8222007-11-17 00:40:40 +00001754addIntervalsForSpills(const LiveInterval &li,
Evan Chengc84ea132008-09-30 15:44:16 +00001755 SmallVectorImpl<LiveInterval*> &SpillIs,
Evan Cheng97c5f1f2009-05-03 18:32:42 +00001756 const MachineLoopInfo *loopInfo, VirtRegMap &vrm) {
Owen Andersona9205692008-08-19 00:17:30 +00001757
1758 if (EnableFastSpilling)
Evan Cheng97c5f1f2009-05-03 18:32:42 +00001759 return addIntervalsForSpillsFast(li, loopInfo, vrm);
Owen Andersona9205692008-08-19 00:17:30 +00001760
Evan Cheng9b741602007-11-12 06:35:08 +00001761 assert(li.weight != HUGE_VALF &&
1762 "attempt to spill already spilled interval!");
1763
Bill Wendling83c96ca2009-08-22 20:18:03 +00001764 DEBUG({
1765 errs() << "\t\t\t\tadding intervals for spills for interval: ";
1766 li.print(errs(), tri_);
1767 errs() << '\n';
1768 });
Evan Cheng9b741602007-11-12 06:35:08 +00001769
Evan Cheng8a7cbc12008-12-05 17:00:16 +00001770 // Each bit specify whether a spill is required in the MBB.
Evan Chengcecc8222007-11-17 00:40:40 +00001771 BitVector SpillMBBs(mf_->getNumBlockIDs());
Owen Andersonfeab1a82008-08-13 22:28:50 +00001772 DenseMap<unsigned, std::vector<SRInfo> > SpillIdxes;
Evan Cheng96c61312007-11-29 01:06:25 +00001773 BitVector RestoreMBBs(mf_->getNumBlockIDs());
Owen Andersonfeab1a82008-08-13 22:28:50 +00001774 DenseMap<unsigned, std::vector<SRInfo> > RestoreIdxes;
1775 DenseMap<unsigned,unsigned> MBBVRegsMap;
Evan Cheng9b741602007-11-12 06:35:08 +00001776 std::vector<LiveInterval*> NewLIs;
Evan Chenga37ecfe2008-02-22 09:24:50 +00001777 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
Evan Cheng9b741602007-11-12 06:35:08 +00001778
1779 unsigned NumValNums = li.getNumValNums();
1780 SmallVector<MachineInstr*, 4> ReMatDefs;
1781 ReMatDefs.resize(NumValNums, NULL);
1782 SmallVector<MachineInstr*, 4> ReMatOrigDefs;
1783 ReMatOrigDefs.resize(NumValNums, NULL);
1784 SmallVector<int, 4> ReMatIds;
1785 ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
1786 BitVector ReMatDelete(NumValNums);
1787 unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
1788
Evan Chengcecc8222007-11-17 00:40:40 +00001789 // Spilling a split live interval. It cannot be split any further. Also,
1790 // it's also guaranteed to be a single val# / range interval.
1791 if (vrm.getPreSplitReg(li.reg)) {
1792 vrm.setIsSplitFromReg(li.reg, 0);
Evan Chengd9731042007-12-05 10:24:35 +00001793 // Unset the split kill marker on the last use.
Lang Hamesd6a717c2009-11-03 23:52:08 +00001794 SlotIndex KillIdx = vrm.getKillPoint(li.reg);
1795 if (KillIdx != SlotIndex()) {
Evan Chengd9731042007-12-05 10:24:35 +00001796 MachineInstr *KillMI = getInstructionFromIndex(KillIdx);
1797 assert(KillMI && "Last use disappeared?");
1798 int KillOp = KillMI->findRegisterUseOperandIdx(li.reg, true);
1799 assert(KillOp != -1 && "Last use disappeared?");
Chris Lattner7f2d3b82007-12-30 21:56:09 +00001800 KillMI->getOperand(KillOp).setIsKill(false);
Evan Chengd9731042007-12-05 10:24:35 +00001801 }
Evan Cheng6f522672007-12-05 09:51:10 +00001802 vrm.removeKillPoint(li.reg);
Evan Chengcecc8222007-11-17 00:40:40 +00001803 bool DefIsReMat = vrm.isReMaterialized(li.reg);
1804 Slot = vrm.getStackSlot(li.reg);
1805 assert(Slot != VirtRegMap::MAX_STACK_SLOT);
1806 MachineInstr *ReMatDefMI = DefIsReMat ?
1807 vrm.getReMaterializedMI(li.reg) : NULL;
1808 int LdSlot = 0;
1809 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1810 bool isLoad = isLoadSS ||
Dan Gohman5574cc72008-12-03 18:15:48 +00001811 (DefIsReMat && (ReMatDefMI->getDesc().canFoldAsLoad()));
Evan Chengcecc8222007-11-17 00:40:40 +00001812 bool IsFirstRange = true;
1813 for (LiveInterval::Ranges::const_iterator
1814 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1815 // If this is a split live interval with multiple ranges, it means there
1816 // are two-address instructions that re-defined the value. Only the
1817 // first def can be rematerialized!
1818 if (IsFirstRange) {
Evan Cheng35d47762007-11-29 23:02:50 +00001819 // Note ReMatOrigDefMI has already been deleted.
Evan Chengcecc8222007-11-17 00:40:40 +00001820 rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
1821 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chenga37ecfe2008-02-22 09:24:50 +00001822 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng96c61312007-11-29 01:06:25 +00001823 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng97c5f1f2009-05-03 18:32:42 +00001824 MBBVRegsMap, NewLIs);
Evan Chengcecc8222007-11-17 00:40:40 +00001825 } else {
1826 rewriteInstructionsForSpills(li, false, I, NULL, 0,
1827 Slot, 0, false, false, false,
Evan Chenga37ecfe2008-02-22 09:24:50 +00001828 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng96c61312007-11-29 01:06:25 +00001829 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng97c5f1f2009-05-03 18:32:42 +00001830 MBBVRegsMap, NewLIs);
Evan Chengcecc8222007-11-17 00:40:40 +00001831 }
1832 IsFirstRange = false;
1833 }
Evan Cheng70f68e92008-04-03 16:39:43 +00001834
Evan Cheng7b88cbc2008-04-11 17:53:36 +00001835 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Chengcecc8222007-11-17 00:40:40 +00001836 return NewLIs;
1837 }
1838
Evan Cheng95320812009-09-14 21:33:42 +00001839 bool TrySplit = !intervalIsInOneMBB(li);
Evan Cheng96c61312007-11-29 01:06:25 +00001840 if (TrySplit)
1841 ++numSplits;
Evan Cheng9b741602007-11-12 06:35:08 +00001842 bool NeedStackSlot = false;
1843 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1844 i != e; ++i) {
1845 const VNInfo *VNI = *i;
1846 unsigned VN = VNI->id;
Lang Hames4eb8fc82009-06-17 21:01:20 +00001847 if (VNI->isUnused())
Evan Cheng9b741602007-11-12 06:35:08 +00001848 continue; // Dead val#.
1849 // Is the def for the val# rematerializable?
Lang Hames4eb8fc82009-06-17 21:01:20 +00001850 MachineInstr *ReMatDefMI = VNI->isDefAccurate()
1851 ? getInstructionFromIndex(VNI->def) : 0;
Evan Chenge81fdb92007-12-06 00:01:56 +00001852 bool dummy;
Evan Chengc84ea132008-09-30 15:44:16 +00001853 if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, SpillIs, dummy)) {
Evan Cheng9b741602007-11-12 06:35:08 +00001854 // Remember how to remat the def of this val#.
Evan Chengcecc8222007-11-17 00:40:40 +00001855 ReMatOrigDefs[VN] = ReMatDefMI;
Dan Gohman8b3b5172008-07-17 23:49:46 +00001856 // Original def may be modified so we have to make a copy here.
Evan Cheng4ce1a522008-07-19 00:37:25 +00001857 MachineInstr *Clone = mf_->CloneMachineInstr(ReMatDefMI);
Evan Cheng95320812009-09-14 21:33:42 +00001858 CloneMIs.push_back(Clone);
Evan Cheng4ce1a522008-07-19 00:37:25 +00001859 ReMatDefs[VN] = Clone;
Evan Cheng9b741602007-11-12 06:35:08 +00001860
1861 bool CanDelete = true;
Lang Hames4eb8fc82009-06-17 21:01:20 +00001862 if (VNI->hasPHIKill()) {
Evan Cheng8b70e632007-11-29 09:49:23 +00001863 // A kill is a phi node, not all of its uses can be rematerialized.
Evan Cheng9b741602007-11-12 06:35:08 +00001864 // It must not be deleted.
Evan Cheng8b70e632007-11-29 09:49:23 +00001865 CanDelete = false;
1866 // Need a stack slot if there is any live range where uses cannot be
1867 // rematerialized.
1868 NeedStackSlot = true;
Evan Cheng9b741602007-11-12 06:35:08 +00001869 }
Evan Cheng9b741602007-11-12 06:35:08 +00001870 if (CanDelete)
1871 ReMatDelete.set(VN);
1872 } else {
1873 // Need a stack slot if there is any live range where uses cannot be
1874 // rematerialized.
1875 NeedStackSlot = true;
1876 }
1877 }
1878
1879 // One stack slot per live interval.
Owen Anderson5bfe6e82009-03-26 18:53:38 +00001880 if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0) {
1881 if (vrm.getStackSlot(li.reg) == VirtRegMap::NO_STACK_SLOT)
1882 Slot = vrm.assignVirt2StackSlot(li.reg);
1883
1884 // This case only occurs when the prealloc splitter has already assigned
1885 // a stack slot to this vreg.
1886 else
1887 Slot = vrm.getStackSlot(li.reg);
1888 }
Evan Cheng9b741602007-11-12 06:35:08 +00001889
1890 // Create new intervals and rewrite defs and uses.
1891 for (LiveInterval::Ranges::const_iterator
1892 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Evan Chengcecc8222007-11-17 00:40:40 +00001893 MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id];
1894 MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id];
1895 bool DefIsReMat = ReMatDefMI != NULL;
Evan Cheng9b741602007-11-12 06:35:08 +00001896 bool CanDelete = ReMatDelete[I->valno->id];
1897 int LdSlot = 0;
Evan Chengcecc8222007-11-17 00:40:40 +00001898 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
Evan Cheng9b741602007-11-12 06:35:08 +00001899 bool isLoad = isLoadSS ||
Dan Gohman5574cc72008-12-03 18:15:48 +00001900 (DefIsReMat && ReMatDefMI->getDesc().canFoldAsLoad());
Evan Chengcecc8222007-11-17 00:40:40 +00001901 rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
Evan Cheng96c61312007-11-29 01:06:25 +00001902 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chenga37ecfe2008-02-22 09:24:50 +00001903 CanDelete, vrm, rc, ReMatIds, loopInfo,
Evan Cheng96c61312007-11-29 01:06:25 +00001904 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Cheng97c5f1f2009-05-03 18:32:42 +00001905 MBBVRegsMap, NewLIs);
Evan Cheng9b741602007-11-12 06:35:08 +00001906 }
1907
Evan Cheng96c61312007-11-29 01:06:25 +00001908 // Insert spills / restores if we are splitting.
Evan Cheng70f68e92008-04-03 16:39:43 +00001909 if (!TrySplit) {
Evan Cheng7b88cbc2008-04-11 17:53:36 +00001910 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng7b632362007-11-29 10:12:14 +00001911 return NewLIs;
Evan Cheng70f68e92008-04-03 16:39:43 +00001912 }
Evan Cheng7b632362007-11-29 10:12:14 +00001913
Evan Chenged17a892007-12-05 08:16:32 +00001914 SmallPtrSet<LiveInterval*, 4> AddedKill;
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001915 SmallVector<unsigned, 2> Ops;
Evan Cheng7b632362007-11-29 10:12:14 +00001916 if (NeedStackSlot) {
1917 int Id = SpillMBBs.find_first();
1918 while (Id != -1) {
1919 std::vector<SRInfo> &spills = SpillIdxes[Id];
1920 for (unsigned i = 0, e = spills.size(); i != e; ++i) {
Lang Hamesd6a717c2009-11-03 23:52:08 +00001921 SlotIndex index = spills[i].index;
Evan Cheng7b632362007-11-29 10:12:14 +00001922 unsigned VReg = spills[i].vreg;
Evan Cheng3a46f222007-12-04 00:32:23 +00001923 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng96c61312007-11-29 01:06:25 +00001924 bool isReMat = vrm.isReMaterialized(VReg);
1925 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001926 bool CanFold = false;
1927 bool FoundUse = false;
1928 Ops.clear();
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001929 if (spills[i].canFold) {
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001930 CanFold = true;
Evan Cheng96c61312007-11-29 01:06:25 +00001931 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1932 MachineOperand &MO = MI->getOperand(j);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +00001933 if (!MO.isReg() || MO.getReg() != VReg)
Evan Cheng96c61312007-11-29 01:06:25 +00001934 continue;
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001935
1936 Ops.push_back(j);
1937 if (MO.isDef())
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001938 continue;
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001939 if (isReMat ||
1940 (!FoundUse && !alsoFoldARestore(Id, index, VReg,
1941 RestoreMBBs, RestoreIdxes))) {
1942 // MI has two-address uses of the same register. If the use
1943 // isn't the first and only use in the BB, then we can't fold
1944 // it. FIXME: Move this to rewriteInstructionsForSpills.
1945 CanFold = false;
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001946 break;
1947 }
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001948 FoundUse = true;
Evan Cheng96c61312007-11-29 01:06:25 +00001949 }
1950 }
1951 // Fold the store into the def if possible.
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001952 bool Folded = false;
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001953 if (CanFold && !Ops.empty()) {
1954 if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001955 Folded = true;
Sebastian Redl2aa4c4e2009-03-19 23:26:52 +00001956 if (FoundUse) {
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001957 // Also folded uses, do not issue a load.
1958 eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
Lang Hamesd6a717c2009-11-03 23:52:08 +00001959 nI.removeRange(index.getLoadIndex(), index.getDefIndex());
Evan Cheng550092f2007-12-05 09:05:34 +00001960 }
Lang Hamesd6a717c2009-11-03 23:52:08 +00001961 nI.removeRange(index.getDefIndex(), index.getStoreIndex());
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001962 }
Evan Cheng96c61312007-11-29 01:06:25 +00001963 }
1964
Evan Cheng909ab8b42008-04-09 20:57:25 +00001965 // Otherwise tell the spiller to issue a spill.
Evan Chenged17a892007-12-05 08:16:32 +00001966 if (!Folded) {
1967 LiveRange *LR = &nI.ranges[nI.ranges.size()-1];
Lang Hamesd6a717c2009-11-03 23:52:08 +00001968 bool isKill = LR->end == index.getStoreIndex();
Evan Cheng87dc7692008-05-20 08:10:37 +00001969 if (!MI->registerDefIsDead(nI.reg))
1970 // No need to spill a dead def.
1971 vrm.addSpillPoint(VReg, isKill, MI);
Evan Chenged17a892007-12-05 08:16:32 +00001972 if (isKill)
1973 AddedKill.insert(&nI);
1974 }
Evan Cheng96c61312007-11-29 01:06:25 +00001975 }
Evan Cheng7b632362007-11-29 10:12:14 +00001976 Id = SpillMBBs.find_next(Id);
Evan Cheng96c61312007-11-29 01:06:25 +00001977 }
Evan Cheng7b632362007-11-29 10:12:14 +00001978 }
Evan Cheng96c61312007-11-29 01:06:25 +00001979
Evan Cheng7b632362007-11-29 10:12:14 +00001980 int Id = RestoreMBBs.find_first();
1981 while (Id != -1) {
1982 std::vector<SRInfo> &restores = RestoreIdxes[Id];
1983 for (unsigned i = 0, e = restores.size(); i != e; ++i) {
Lang Hamesd6a717c2009-11-03 23:52:08 +00001984 SlotIndex index = restores[i].index;
1985 if (index == SlotIndex())
Evan Cheng7b632362007-11-29 10:12:14 +00001986 continue;
1987 unsigned VReg = restores[i].vreg;
Evan Cheng3a46f222007-12-04 00:32:23 +00001988 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Chengba221ca2008-06-06 07:54:39 +00001989 bool isReMat = vrm.isReMaterialized(VReg);
Evan Chengcecc8222007-11-17 00:40:40 +00001990 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001991 bool CanFold = false;
1992 Ops.clear();
Evan Cheng16ebb8c2007-11-30 21:23:43 +00001993 if (restores[i].canFold) {
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001994 CanFold = true;
Evan Chengcecc8222007-11-17 00:40:40 +00001995 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1996 MachineOperand &MO = MI->getOperand(j);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +00001997 if (!MO.isReg() || MO.getReg() != VReg)
Evan Chengcecc8222007-11-17 00:40:40 +00001998 continue;
Evan Chengfd0bd3c2007-12-02 08:30:39 +00001999
Evan Cheng96c61312007-11-29 01:06:25 +00002000 if (MO.isDef()) {
Evan Chengfd0bd3c2007-12-02 08:30:39 +00002001 // If this restore were to be folded, it would have been folded
2002 // already.
2003 CanFold = false;
Evan Chengcecc8222007-11-17 00:40:40 +00002004 break;
2005 }
Evan Chengfd0bd3c2007-12-02 08:30:39 +00002006 Ops.push_back(j);
Evan Chengcecc8222007-11-17 00:40:40 +00002007 }
2008 }
Evan Cheng96c61312007-11-29 01:06:25 +00002009
2010 // Fold the load into the use if possible.
Evan Cheng16ebb8c2007-11-30 21:23:43 +00002011 bool Folded = false;
Evan Chengfd0bd3c2007-12-02 08:30:39 +00002012 if (CanFold && !Ops.empty()) {
Evan Chengba221ca2008-06-06 07:54:39 +00002013 if (!isReMat)
Evan Chengfd0bd3c2007-12-02 08:30:39 +00002014 Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg);
2015 else {
Evan Cheng96c61312007-11-29 01:06:25 +00002016 MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg);
2017 int LdSlot = 0;
2018 bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
2019 // If the rematerializable def is a load, also try to fold it.
Dan Gohman5574cc72008-12-03 18:15:48 +00002020 if (isLoadSS || ReMatDefMI->getDesc().canFoldAsLoad())
Evan Chengfd0bd3c2007-12-02 08:30:39 +00002021 Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
2022 Ops, isLoadSS, LdSlot, VReg);
Evan Chengeb7a09b2008-12-05 17:41:31 +00002023 if (!Folded) {
2024 unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI);
2025 if (ImpUse) {
2026 // Re-matting an instruction with virtual register use. Add the
2027 // register as an implicit use on the use MI and update the register
2028 // interval's spill weight to HUGE_VALF to prevent it from being
2029 // spilled.
2030 LiveInterval &ImpLi = getInterval(ImpUse);
2031 ImpLi.weight = HUGE_VALF;
2032 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
2033 }
Evan Chenga37ecfe2008-02-22 09:24:50 +00002034 }
Evan Chengfd0bd3c2007-12-02 08:30:39 +00002035 }
Evan Cheng96c61312007-11-29 01:06:25 +00002036 }
2037 // If folding is not possible / failed, then tell the spiller to issue a
2038 // load / rematerialization for us.
Evan Cheng3a46f222007-12-04 00:32:23 +00002039 if (Folded)
Lang Hamesd6a717c2009-11-03 23:52:08 +00002040 nI.removeRange(index.getLoadIndex(), index.getDefIndex());
Evan Chenged17a892007-12-05 08:16:32 +00002041 else
Evan Cheng96c61312007-11-29 01:06:25 +00002042 vrm.addRestorePoint(VReg, MI);
Evan Chengcecc8222007-11-17 00:40:40 +00002043 }
Evan Cheng7b632362007-11-29 10:12:14 +00002044 Id = RestoreMBBs.find_next(Id);
Evan Chengcecc8222007-11-17 00:40:40 +00002045 }
2046
Evan Chenged17a892007-12-05 08:16:32 +00002047 // Finalize intervals: add kills, finalize spill weights, and filter out
2048 // dead intervals.
Evan Cheng3a46f222007-12-04 00:32:23 +00002049 std::vector<LiveInterval*> RetNewLIs;
2050 for (unsigned i = 0, e = NewLIs.size(); i != e; ++i) {
2051 LiveInterval *LI = NewLIs[i];
2052 if (!LI->empty()) {
Lang Hamesd6a717c2009-11-03 23:52:08 +00002053 LI->weight /= SlotIndex::NUM * getApproximateInstructionCount(*LI);
Evan Chenged17a892007-12-05 08:16:32 +00002054 if (!AddedKill.count(LI)) {
2055 LiveRange *LR = &LI->ranges[LI->ranges.size()-1];
Lang Hamesd6a717c2009-11-03 23:52:08 +00002056 SlotIndex LastUseIdx = LR->end.getBaseIndex();
Evan Chengd9731042007-12-05 10:24:35 +00002057 MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx);
Evan Chengc7daf1f2008-03-05 00:59:57 +00002058 int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg, false);
Evan Chenged17a892007-12-05 08:16:32 +00002059 assert(UseIdx != -1);
Evan Cheng48555e82009-03-19 20:30:06 +00002060 if (!LastUse->isRegTiedToDefOperand(UseIdx)) {
Evan Chenged17a892007-12-05 08:16:32 +00002061 LastUse->getOperand(UseIdx).setIsKill();
Evan Chengd9731042007-12-05 10:24:35 +00002062 vrm.addKillPoint(LI->reg, LastUseIdx);
Evan Cheng6f522672007-12-05 09:51:10 +00002063 }
Evan Chenged17a892007-12-05 08:16:32 +00002064 }
Evan Cheng3a46f222007-12-04 00:32:23 +00002065 RetNewLIs.push_back(LI);
2066 }
2067 }
Evan Chengcecc8222007-11-17 00:40:40 +00002068
Evan Cheng7b88cbc2008-04-11 17:53:36 +00002069 handleSpilledImpDefs(li, vrm, rc, RetNewLIs);
Evan Cheng3a46f222007-12-04 00:32:23 +00002070 return RetNewLIs;
Evan Cheng9b741602007-11-12 06:35:08 +00002071}
Evan Cheng14cc83f2008-03-11 07:19:34 +00002072
2073/// hasAllocatableSuperReg - Return true if the specified physical register has
2074/// any super register that's allocatable.
2075bool LiveIntervals::hasAllocatableSuperReg(unsigned Reg) const {
2076 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS)
2077 if (allocatableRegs_[*AS] && hasInterval(*AS))
2078 return true;
2079 return false;
2080}
2081
2082/// getRepresentativeReg - Find the largest super register of the specified
2083/// physical register.
2084unsigned LiveIntervals::getRepresentativeReg(unsigned Reg) const {
2085 // Find the largest super-register that is allocatable.
2086 unsigned BestReg = Reg;
2087 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS) {
2088 unsigned SuperReg = *AS;
2089 if (!hasAllocatableSuperReg(SuperReg) && hasInterval(SuperReg)) {
2090 BestReg = SuperReg;
2091 break;
2092 }
2093 }
2094 return BestReg;
2095}
2096
2097/// getNumConflictsWithPhysReg - Return the number of uses and defs of the
2098/// specified interval that conflicts with the specified physical register.
2099unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li,
2100 unsigned PhysReg) const {
2101 unsigned NumConflicts = 0;
2102 const LiveInterval &pli = getInterval(getRepresentativeReg(PhysReg));
2103 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
2104 E = mri_->reg_end(); I != E; ++I) {
2105 MachineOperand &O = I.getOperand();
2106 MachineInstr *MI = O.getParent();
Lang Hamesd6a717c2009-11-03 23:52:08 +00002107 SlotIndex Index = getInstructionIndex(MI);
Evan Cheng14cc83f2008-03-11 07:19:34 +00002108 if (pli.liveAt(Index))
2109 ++NumConflicts;
2110 }
2111 return NumConflicts;
2112}
2113
2114/// spillPhysRegAroundRegDefsUses - Spill the specified physical register
Evan Cheng973473b2009-03-23 18:24:37 +00002115/// around all defs and uses of the specified interval. Return true if it
2116/// was able to cut its interval.
2117bool LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
Evan Cheng14cc83f2008-03-11 07:19:34 +00002118 unsigned PhysReg, VirtRegMap &vrm) {
2119 unsigned SpillReg = getRepresentativeReg(PhysReg);
2120
2121 for (const unsigned *AS = tri_->getAliasSet(PhysReg); *AS; ++AS)
2122 // If there are registers which alias PhysReg, but which are not a
2123 // sub-register of the chosen representative super register. Assert
2124 // since we can't handle it yet.
Dan Gohman86a85d62009-04-13 15:22:29 +00002125 assert(*AS == SpillReg || !allocatableRegs_[*AS] || !hasInterval(*AS) ||
Evan Cheng14cc83f2008-03-11 07:19:34 +00002126 tri_->isSuperRegister(*AS, SpillReg));
2127
Evan Cheng973473b2009-03-23 18:24:37 +00002128 bool Cut = false;
Evan Cheng2f576c12009-10-20 01:31:09 +00002129 SmallVector<unsigned, 4> PRegs;
2130 if (hasInterval(SpillReg))
2131 PRegs.push_back(SpillReg);
2132 else {
2133 SmallSet<unsigned, 4> Added;
2134 for (const unsigned* AS = tri_->getSubRegisters(SpillReg); *AS; ++AS)
2135 if (Added.insert(*AS) && hasInterval(*AS)) {
2136 PRegs.push_back(*AS);
2137 for (const unsigned* ASS = tri_->getSubRegisters(*AS); *ASS; ++ASS)
2138 Added.insert(*ASS);
2139 }
2140 }
2141
Evan Cheng14cc83f2008-03-11 07:19:34 +00002142 SmallPtrSet<MachineInstr*, 8> SeenMIs;
2143 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
2144 E = mri_->reg_end(); I != E; ++I) {
2145 MachineOperand &O = I.getOperand();
2146 MachineInstr *MI = O.getParent();
2147 if (SeenMIs.count(MI))
2148 continue;
2149 SeenMIs.insert(MI);
Lang Hamesd6a717c2009-11-03 23:52:08 +00002150 SlotIndex Index = getInstructionIndex(MI);
Evan Cheng2f576c12009-10-20 01:31:09 +00002151 for (unsigned i = 0, e = PRegs.size(); i != e; ++i) {
2152 unsigned PReg = PRegs[i];
2153 LiveInterval &pli = getInterval(PReg);
2154 if (!pli.liveAt(Index))
2155 continue;
2156 vrm.addEmergencySpill(PReg, MI);
Lang Hamesd6a717c2009-11-03 23:52:08 +00002157 SlotIndex StartIdx = Index.getLoadIndex();
2158 SlotIndex EndIdx = Index.getNextIndex().getBaseIndex();
Evan Cheng973473b2009-03-23 18:24:37 +00002159 if (pli.isInOneLiveRange(StartIdx, EndIdx)) {
Evan Cheng548bc502009-01-29 02:20:59 +00002160 pli.removeRange(StartIdx, EndIdx);
Evan Cheng973473b2009-03-23 18:24:37 +00002161 Cut = true;
2162 } else {
Edwin Törökced9ff82009-07-11 13:10:19 +00002163 std::string msg;
2164 raw_string_ostream Msg(msg);
2165 Msg << "Ran out of registers during register allocation!";
Evan Cheng548bc502009-01-29 02:20:59 +00002166 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
Edwin Törökced9ff82009-07-11 13:10:19 +00002167 Msg << "\nPlease check your inline asm statement for invalid "
Evan Cheng2f576c12009-10-20 01:31:09 +00002168 << "constraints:\n";
Edwin Törökced9ff82009-07-11 13:10:19 +00002169 MI->print(Msg, tm_);
Evan Cheng548bc502009-01-29 02:20:59 +00002170 }
Edwin Törökced9ff82009-07-11 13:10:19 +00002171 llvm_report_error(Msg.str());
Evan Cheng548bc502009-01-29 02:20:59 +00002172 }
Evan Cheng2f576c12009-10-20 01:31:09 +00002173 for (const unsigned* AS = tri_->getSubRegisters(PReg); *AS; ++AS) {
Evan Cheng14cc83f2008-03-11 07:19:34 +00002174 if (!hasInterval(*AS))
2175 continue;
2176 LiveInterval &spli = getInterval(*AS);
2177 if (spli.liveAt(Index))
Lang Hamesd6a717c2009-11-03 23:52:08 +00002178 spli.removeRange(Index.getLoadIndex(),
2179 Index.getNextIndex().getBaseIndex());
Evan Cheng14cc83f2008-03-11 07:19:34 +00002180 }
2181 }
2182 }
Evan Cheng973473b2009-03-23 18:24:37 +00002183 return Cut;
Evan Cheng14cc83f2008-03-11 07:19:34 +00002184}
Owen Anderson7399f222008-06-05 17:15:43 +00002185
2186LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
Lang Hamesd2bd8622009-07-09 03:57:02 +00002187 MachineInstr* startInst) {
Owen Anderson7399f222008-06-05 17:15:43 +00002188 LiveInterval& Interval = getOrCreateInterval(reg);
2189 VNInfo* VN = Interval.getNextValue(
Lang Hamesd6a717c2009-11-03 23:52:08 +00002190 SlotIndex(getInstructionIndex(startInst).getDefIndex()),
Lang Hamesd8f30992009-09-04 20:41:11 +00002191 startInst, true, getVNInfoAllocator());
Lang Hames4eb8fc82009-06-17 21:01:20 +00002192 VN->setHasPHIKill(true);
Lang Hamesd6a717c2009-11-03 23:52:08 +00002193 VN->kills.push_back(indexes_->getTerminatorGap(startInst->getParent()));
Lang Hamesd8f30992009-09-04 20:41:11 +00002194 LiveRange LR(
Lang Hamesd6a717c2009-11-03 23:52:08 +00002195 SlotIndex(getInstructionIndex(startInst).getDefIndex()),
2196 getMBBEndIdx(startInst->getParent()).getNextIndex().getBaseIndex(), VN);
Owen Anderson7399f222008-06-05 17:15:43 +00002197 Interval.addRange(LR);
2198
2199 return LR;
2200}
David Greene180b5e72009-08-03 21:55:09 +00002201