blob: 854fb4d7f6d85f398ec1ea4dcb21adc031c800ed [file] [log] [blame]
Chris Lattnera3b8b5c2004-07-23 17:56:30 +00001//===-- LiveIntervalAnalysis.cpp - Live Interval Analysis -----------------===//
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the LiveInterval analysis pass which is used
11// by the Linear Scan Register allocator. This pass linearizes the
12// basic blocks of the function in DFS order and uses the
13// LiveVariables pass to conservatively compute live intervals for
14// each virtual and physical register.
15//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "liveintervals"
Chris Lattner3c3fe462005-09-21 04:19:09 +000019#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Misha Brukman08a6c762004-09-03 18:25:53 +000020#include "VirtRegMap.h"
Chris Lattner015959e2004-05-01 21:24:39 +000021#include "llvm/Value.h"
Dan Gohman6d69ba82008-07-25 00:02:30 +000022#include "llvm/Analysis/AliasAnalysis.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000023#include "llvm/CodeGen/LiveVariables.h"
24#include "llvm/CodeGen/MachineFrameInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000025#include "llvm/CodeGen/MachineInstr.h"
Evan Cheng2578ba22009-07-01 01:59:31 +000026#include "llvm/CodeGen/MachineInstrBuilder.h"
Evan Cheng22f07ff2007-12-11 02:09:15 +000027#include "llvm/CodeGen/MachineLoopInfo.h"
Dan Gohmanc76909a2009-09-25 20:36:54 +000028#include "llvm/CodeGen/MachineMemOperand.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000029#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000030#include "llvm/CodeGen/Passes.h"
Lang Hames233a60e2009-11-03 23:52:08 +000031#include "llvm/CodeGen/ProcessImplicitDefs.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000032#include "llvm/Target/TargetRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000033#include "llvm/Target/TargetInstrInfo.h"
34#include "llvm/Target/TargetMachine.h"
Owen Anderson95dad832008-10-07 20:22:28 +000035#include "llvm/Target/TargetOptions.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000036#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000038#include "llvm/Support/ErrorHandling.h"
39#include "llvm/Support/raw_ostream.h"
Evan Cheng2578ba22009-07-01 01:59:31 +000040#include "llvm/ADT/DepthFirstIterator.h"
41#include "llvm/ADT/SmallSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000042#include "llvm/ADT/Statistic.h"
43#include "llvm/ADT/STLExtras.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000044#include <algorithm>
Lang Hamesf41538d2009-06-02 16:53:25 +000045#include <limits>
Jeff Cohen97af7512006-12-02 02:22:01 +000046#include <cmath>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000047using namespace llvm;
48
Dan Gohman844731a2008-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 Cheng81a03822007-11-17 00:40:40 +000052
Owen Andersonae339ba2008-08-19 00:17:30 +000053static cl::opt<bool> EnableFastSpilling("fast-spill",
54 cl::init(false), cl::Hidden);
55
Evan Cheng752195e2009-09-14 21:33:42 +000056static cl::opt<bool> EarlyCoalescing("early-coalescing", cl::init(false));
57
58static cl::opt<int> CoalescingLimit("early-coalescing-limit",
59 cl::init(-1), cl::Hidden);
60
61STATISTIC(numIntervals , "Number of original intervals");
62STATISTIC(numFolds , "Number of loads/stores folded into instructions");
63STATISTIC(numSplits , "Number of intervals split");
64STATISTIC(numCoalescing, "Number of early coalescing performed");
Chris Lattnercd3245a2006-12-19 22:41:21 +000065
Devang Patel19974732007-05-03 01:11:54 +000066char LiveIntervals::ID = 0;
Dan Gohman844731a2008-05-13 00:00:25 +000067static RegisterPass<LiveIntervals> X("liveintervals", "Live Interval Analysis");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000068
Chris Lattnerf7da2c72006-08-24 22:43:55 +000069void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000070 AU.setPreservesCFG();
Dan Gohman6d69ba82008-07-25 00:02:30 +000071 AU.addRequired<AliasAnalysis>();
72 AU.addPreserved<AliasAnalysis>();
David Greene25133302007-06-08 17:18:56 +000073 AU.addPreserved<LiveVariables>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000074 AU.addRequired<LiveVariables>();
Bill Wendling67d65bb2008-01-04 20:54:55 +000075 AU.addPreservedID(MachineLoopInfoID);
76 AU.addPreservedID(MachineDominatorsID);
Owen Anderson95dad832008-10-07 20:22:28 +000077
78 if (!StrongPHIElim) {
79 AU.addPreservedID(PHIEliminationID);
80 AU.addRequiredID(PHIEliminationID);
81 }
82
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000083 AU.addRequiredID(TwoAddressInstructionPassID);
Lang Hames233a60e2009-11-03 23:52:08 +000084 AU.addPreserved<ProcessImplicitDefs>();
85 AU.addRequired<ProcessImplicitDefs>();
86 AU.addPreserved<SlotIndexes>();
87 AU.addRequiredTransitive<SlotIndexes>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000088 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000089}
90
Chris Lattnerf7da2c72006-08-24 22:43:55 +000091void LiveIntervals::releaseMemory() {
Owen Anderson03857b22008-08-13 21:49:13 +000092 // Free the live intervals themselves.
Owen Anderson20e28392008-08-13 22:08:30 +000093 for (DenseMap<unsigned, LiveInterval*>::iterator I = r2iMap_.begin(),
Owen Anderson03857b22008-08-13 21:49:13 +000094 E = r2iMap_.end(); I != E; ++I)
95 delete I->second;
96
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000097 r2iMap_.clear();
Evan Cheng752195e2009-09-14 21:33:42 +000098 phiJoinCopies.clear();
Lang Hamesffd13262009-07-09 03:57:02 +000099
Evan Chengdd199d22007-09-06 01:07:24 +0000100 // Release VNInfo memroy regions after all VNInfo objects are dtor'd.
101 VNInfoAllocator.Reset();
Evan Cheng752195e2009-09-14 21:33:42 +0000102 while (!CloneMIs.empty()) {
103 MachineInstr *MI = CloneMIs.back();
104 CloneMIs.pop_back();
Evan Cheng1ed99222008-07-19 00:37:25 +0000105 mf_->DeleteMachineInstr(MI);
106 }
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000107}
108
Owen Anderson80b3ce62008-05-28 20:54:50 +0000109/// runOnMachineFunction - Register allocate the whole function
110///
111bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
112 mf_ = &fn;
113 mri_ = &mf_->getRegInfo();
114 tm_ = &fn.getTarget();
115 tri_ = tm_->getRegisterInfo();
116 tii_ = tm_->getInstrInfo();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000117 aa_ = &getAnalysis<AliasAnalysis>();
Owen Anderson80b3ce62008-05-28 20:54:50 +0000118 lv_ = &getAnalysis<LiveVariables>();
Lang Hames233a60e2009-11-03 23:52:08 +0000119 indexes_ = &getAnalysis<SlotIndexes>();
Owen Anderson80b3ce62008-05-28 20:54:50 +0000120 allocatableRegs_ = tri_->getAllocatableSet(fn);
121
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000122 computeIntervals();
Evan Cheng752195e2009-09-14 21:33:42 +0000123 performEarlyCoalescing();
Alkis Evlogimenos843b1602004-02-15 10:24:21 +0000124
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000125 numIntervals += getNumIntervals();
126
Chris Lattner70ca3582004-09-30 15:59:17 +0000127 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000128 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000129}
130
Chris Lattner70ca3582004-09-30 15:59:17 +0000131/// print - Implement the dump method.
Chris Lattner45cfe542009-08-23 06:03:38 +0000132void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
Chris Lattner705e07f2009-08-23 03:41:05 +0000133 OS << "********** INTERVALS **********\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000134 for (const_iterator I = begin(), E = end(); I != E; ++I) {
Chris Lattner705e07f2009-08-23 03:41:05 +0000135 I->second->print(OS, tri_);
136 OS << "\n";
Chris Lattner8e7a7092005-07-27 23:03:38 +0000137 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000138
Evan Cheng752195e2009-09-14 21:33:42 +0000139 printInstrs(OS);
140}
141
142void LiveIntervals::printInstrs(raw_ostream &OS) const {
Chris Lattner705e07f2009-08-23 03:41:05 +0000143 OS << "********** MACHINEINSTRS **********\n";
144
Chris Lattner3380d5c2009-07-21 21:12:58 +0000145 for (MachineFunction::iterator mbbi = mf_->begin(), mbbe = mf_->end();
146 mbbi != mbbe; ++mbbi) {
Chris Lattner705e07f2009-08-23 03:41:05 +0000147 OS << ((Value*)mbbi->getBasicBlock())->getName() << ":\n";
Chris Lattner3380d5c2009-07-21 21:12:58 +0000148 for (MachineBasicBlock::iterator mii = mbbi->begin(),
149 mie = mbbi->end(); mii != mie; ++mii) {
Chris Lattner705e07f2009-08-23 03:41:05 +0000150 OS << getInstructionIndex(mii) << '\t' << *mii;
Chris Lattner3380d5c2009-07-21 21:12:58 +0000151 }
152 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000153}
154
Evan Cheng752195e2009-09-14 21:33:42 +0000155void LiveIntervals::dumpInstrs() const {
156 printInstrs(errs());
157}
158
Evan Chengc92da382007-11-03 07:20:12 +0000159/// conflictsWithPhysRegDef - Returns true if the specified register
160/// is defined during the duration of the specified interval.
161bool LiveIntervals::conflictsWithPhysRegDef(const LiveInterval &li,
162 VirtRegMap &vrm, unsigned reg) {
163 for (LiveInterval::Ranges::const_iterator
164 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Lang Hames233a60e2009-11-03 23:52:08 +0000165 for (SlotIndex index = I->start.getBaseIndex(),
166 end = I->end.getPrevSlot().getBaseIndex().getNextIndex();
167 index != end;
168 index = index.getNextIndex()) {
Evan Chengc92da382007-11-03 07:20:12 +0000169 // skip deleted instructions
170 while (index != end && !getInstructionFromIndex(index))
Lang Hames233a60e2009-11-03 23:52:08 +0000171 index = index.getNextIndex();
Evan Chengc92da382007-11-03 07:20:12 +0000172 if (index == end) break;
173
174 MachineInstr *MI = getInstructionFromIndex(index);
Evan Cheng04ee5a12009-01-20 19:12:24 +0000175 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
176 if (tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Cheng5d446262007-11-15 08:13:29 +0000177 if (SrcReg == li.reg || DstReg == li.reg)
178 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000179 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
180 MachineOperand& mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000181 if (!mop.isReg())
Evan Chengc92da382007-11-03 07:20:12 +0000182 continue;
183 unsigned PhysReg = mop.getReg();
Evan Cheng5d446262007-11-15 08:13:29 +0000184 if (PhysReg == 0 || PhysReg == li.reg)
Evan Chengc92da382007-11-03 07:20:12 +0000185 continue;
Dan Gohman6f0d0242008-02-10 18:45:23 +0000186 if (TargetRegisterInfo::isVirtualRegister(PhysReg)) {
Evan Cheng5d446262007-11-15 08:13:29 +0000187 if (!vrm.hasPhys(PhysReg))
188 continue;
Evan Chengc92da382007-11-03 07:20:12 +0000189 PhysReg = vrm.getPhys(PhysReg);
Evan Cheng5d446262007-11-15 08:13:29 +0000190 }
Dan Gohman6f0d0242008-02-10 18:45:23 +0000191 if (PhysReg && tri_->regsOverlap(PhysReg, reg))
Evan Chengc92da382007-11-03 07:20:12 +0000192 return true;
193 }
194 }
195 }
196
197 return false;
198}
199
Evan Cheng8f90b6e2009-01-07 02:08:57 +0000200/// conflictsWithPhysRegRef - Similar to conflictsWithPhysRegRef except
201/// it can check use as well.
202bool LiveIntervals::conflictsWithPhysRegRef(LiveInterval &li,
203 unsigned Reg, bool CheckUse,
204 SmallPtrSet<MachineInstr*,32> &JoinedCopies) {
205 for (LiveInterval::Ranges::const_iterator
206 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Lang Hames233a60e2009-11-03 23:52:08 +0000207 for (SlotIndex index = I->start.getBaseIndex(),
208 end = I->end.getPrevSlot().getBaseIndex().getNextIndex();
209 index != end;
210 index = index.getNextIndex()) {
Evan Cheng8f90b6e2009-01-07 02:08:57 +0000211 // Skip deleted instructions.
212 MachineInstr *MI = 0;
213 while (index != end) {
214 MI = getInstructionFromIndex(index);
215 if (MI)
216 break;
Lang Hames233a60e2009-11-03 23:52:08 +0000217 index = index.getNextIndex();
Evan Cheng8f90b6e2009-01-07 02:08:57 +0000218 }
219 if (index == end) break;
220
221 if (JoinedCopies.count(MI))
222 continue;
223 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
224 MachineOperand& MO = MI->getOperand(i);
225 if (!MO.isReg())
226 continue;
227 if (MO.isUse() && !CheckUse)
228 continue;
229 unsigned PhysReg = MO.getReg();
230 if (PhysReg == 0 || TargetRegisterInfo::isVirtualRegister(PhysReg))
231 continue;
232 if (tri_->isSubRegister(Reg, PhysReg))
233 return true;
234 }
235 }
236 }
237
238 return false;
239}
240
Daniel Dunbar504f9a62009-09-15 20:31:12 +0000241#ifndef NDEBUG
Evan Cheng752195e2009-09-14 21:33:42 +0000242static void printRegName(unsigned reg, const TargetRegisterInfo* tri_) {
Dan Gohman6f0d0242008-02-10 18:45:23 +0000243 if (TargetRegisterInfo::isPhysicalRegister(reg))
Daniel Dunbar3f0e8302009-07-24 09:53:24 +0000244 errs() << tri_->getName(reg);
Evan Cheng549f27d32007-08-13 23:45:17 +0000245 else
Daniel Dunbar3f0e8302009-07-24 09:53:24 +0000246 errs() << "%reg" << reg;
Evan Cheng549f27d32007-08-13 23:45:17 +0000247}
Daniel Dunbar504f9a62009-09-15 20:31:12 +0000248#endif
Evan Cheng549f27d32007-08-13 23:45:17 +0000249
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000250void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000251 MachineBasicBlock::iterator mi,
Lang Hames233a60e2009-11-03 23:52:08 +0000252 SlotIndex MIIdx,
Lang Hames86511252009-09-04 20:41:11 +0000253 MachineOperand& MO,
Evan Chengef0732d2008-07-10 07:35:43 +0000254 unsigned MOIdx,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000255 LiveInterval &interval) {
Bill Wendling8e6179f2009-08-22 20:18:03 +0000256 DEBUG({
257 errs() << "\t\tregister: ";
Evan Cheng752195e2009-09-14 21:33:42 +0000258 printRegName(interval.reg, tri_);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000259 });
Evan Cheng419852c2008-04-03 16:39:43 +0000260
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000261 // Virtual registers may be defined multiple times (due to phi
262 // elimination and 2-addr elimination). Much of what we do only has to be
263 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000264 // time we see a vreg.
Evan Chengd129d732009-07-17 19:43:40 +0000265 LiveVariables::VarInfo& vi = lv_->getVarInfo(interval.reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000266 if (interval.empty()) {
267 // Get the Idx of the defining instructions.
Lang Hames233a60e2009-11-03 23:52:08 +0000268 SlotIndex defIndex = MIIdx.getDefIndex();
Dale Johannesen39faac22009-09-20 00:36:41 +0000269 // Earlyclobbers move back one, so that they overlap the live range
270 // of inputs.
Dale Johannesen86b49f82008-09-24 01:07:17 +0000271 if (MO.isEarlyClobber())
Lang Hames233a60e2009-11-03 23:52:08 +0000272 defIndex = MIIdx.getUseIndex();
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000273 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000274 MachineInstr *CopyMI = NULL;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000275 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000276 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000277 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Dan Gohman97121ba2009-04-08 00:15:30 +0000278 mi->getOpcode() == TargetInstrInfo::SUBREG_TO_REG ||
Evan Cheng04ee5a12009-01-20 19:12:24 +0000279 tii_->isMoveInstr(*mi, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000280 CopyMI = mi;
Evan Cheng5379f412008-12-19 20:58:01 +0000281 // Earlyclobbers move back one.
Lang Hames857c4e02009-06-17 21:01:20 +0000282 ValNo = interval.getNextValue(defIndex, CopyMI, true, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000283
284 assert(ValNo->id == 0 && "First value in interval is not 0?");
Chris Lattner7ac2d312004-07-24 02:59:07 +0000285
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000286 // Loop over all of the blocks that the vreg is defined in. There are
287 // two cases we have to handle here. The most common case is a vreg
288 // whose lifetime is contained within a basic block. In this case there
289 // will be a single kill, in MBB, which comes after the definition.
290 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
291 // FIXME: what about dead vars?
Lang Hames233a60e2009-11-03 23:52:08 +0000292 SlotIndex killIdx;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000293 if (vi.Kills[0] != mi)
Lang Hames233a60e2009-11-03 23:52:08 +0000294 killIdx = getInstructionIndex(vi.Kills[0]).getDefIndex();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000295 else
Lang Hames233a60e2009-11-03 23:52:08 +0000296 killIdx = defIndex.getStoreIndex();
Chris Lattner6097d132004-07-19 02:15:56 +0000297
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000298 // If the kill happens after the definition, we have an intra-block
299 // live range.
300 if (killIdx > defIndex) {
Jeffrey Yasskin493a3d02009-05-26 18:27:15 +0000301 assert(vi.AliveBlocks.empty() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000302 "Shouldn't be alive across any blocks!");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000303 LiveRange LR(defIndex, killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000304 interval.addRange(LR);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000305 DEBUG(errs() << " +" << LR << "\n");
Lang Hames86511252009-09-04 20:41:11 +0000306 ValNo->addKill(killIdx);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000307 return;
308 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000309 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000310
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000311 // The other case we handle is when a virtual register lives to the end
312 // of the defining block, potentially live across some blocks, then is
313 // live into some number of blocks, but gets killed. Start by adding a
314 // range that goes from this definition to the end of the defining block.
Lang Hames233a60e2009-11-03 23:52:08 +0000315 LiveRange NewLR(defIndex, getMBBEndIdx(mbb).getNextIndex().getLoadIndex(),
316 ValNo);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000317 DEBUG(errs() << " +" << NewLR);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000318 interval.addRange(NewLR);
319
320 // Iterate over all of the blocks that the variable is completely
321 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
322 // live interval.
Jeffrey Yasskin493a3d02009-05-26 18:27:15 +0000323 for (SparseBitVector<>::iterator I = vi.AliveBlocks.begin(),
324 E = vi.AliveBlocks.end(); I != E; ++I) {
Lang Hames233a60e2009-11-03 23:52:08 +0000325 LiveRange LR(
326 getMBBStartIdx(mf_->getBlockNumbered(*I)),
327 getMBBEndIdx(mf_->getBlockNumbered(*I)).getNextIndex().getLoadIndex(),
328 ValNo);
Dan Gohman4a829ec2008-11-13 16:31:27 +0000329 interval.addRange(LR);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000330 DEBUG(errs() << " +" << LR);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000331 }
332
333 // Finally, this virtual register is live from the start of any killing
334 // block to the 'use' slot of the killing instruction.
335 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
336 MachineInstr *Kill = vi.Kills[i];
Lang Hames233a60e2009-11-03 23:52:08 +0000337 SlotIndex killIdx =
338 getInstructionIndex(Kill).getDefIndex();
Evan Chengb0f59732009-09-21 04:32:32 +0000339 LiveRange LR(getMBBStartIdx(Kill->getParent()), killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000340 interval.addRange(LR);
Lang Hames86511252009-09-04 20:41:11 +0000341 ValNo->addKill(killIdx);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000342 DEBUG(errs() << " +" << LR);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000343 }
344
345 } else {
346 // If this is the second time we see a virtual register definition, it
347 // must be due to phi elimination or two addr elimination. If this is
Evan Chengbf105c82006-11-03 03:04:46 +0000348 // the result of two address elimination, then the vreg is one of the
349 // def-and-use register operand.
Bob Wilsond9df5012009-04-09 17:16:43 +0000350 if (mi->isRegTiedToUseOperand(MOIdx)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000351 // If this is a two-address definition, then we have already processed
352 // the live range. The only problem is that we didn't realize there
353 // are actually two values in the live interval. Because of this we
354 // need to take the LiveRegion that defines this register and split it
355 // into two values.
Evan Chenga07cec92008-01-10 08:22:10 +0000356 assert(interval.containsOneValue());
Lang Hames233a60e2009-11-03 23:52:08 +0000357 SlotIndex DefIndex = interval.getValNumInfo(0)->def.getDefIndex();
358 SlotIndex RedefIndex = MIIdx.getDefIndex();
Evan Chengfb112882009-03-23 08:01:15 +0000359 if (MO.isEarlyClobber())
Lang Hames233a60e2009-11-03 23:52:08 +0000360 RedefIndex = MIIdx.getUseIndex();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000361
Lang Hames35f291d2009-09-12 03:34:03 +0000362 const LiveRange *OldLR =
Lang Hames233a60e2009-11-03 23:52:08 +0000363 interval.getLiveRangeContaining(RedefIndex.getUseIndex());
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000364 VNInfo *OldValNo = OldLR->valno;
Evan Cheng4f8ff162007-08-11 00:59:19 +0000365
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000366 // Delete the initial value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000367 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000368 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000369
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000370 // Two-address vregs should always only be redefined once. This means
371 // that at this point, there should be exactly one value number in it.
372 assert(interval.containsOneValue() && "Unexpected 2-addr liveint!");
373
Chris Lattner91725b72006-08-31 05:54:43 +0000374 // The new value number (#1) is defined by the instruction we claimed
375 // defined value #0.
Lang Hames52c1afc2009-08-10 23:43:28 +0000376 VNInfo *ValNo = interval.getNextValue(OldValNo->def, OldValNo->getCopy(),
Lang Hames857c4e02009-06-17 21:01:20 +0000377 false, // update at *
Evan Chengc8d044e2008-02-15 18:24:29 +0000378 VNInfoAllocator);
Lang Hames857c4e02009-06-17 21:01:20 +0000379 ValNo->setFlags(OldValNo->getFlags()); // * <- updating here
380
Chris Lattner91725b72006-08-31 05:54:43 +0000381 // Value#0 is now defined by the 2-addr instruction.
Evan Chengc8d044e2008-02-15 18:24:29 +0000382 OldValNo->def = RedefIndex;
Lang Hames52c1afc2009-08-10 23:43:28 +0000383 OldValNo->setCopy(0);
Evan Chengfb112882009-03-23 08:01:15 +0000384 if (MO.isEarlyClobber())
Lang Hames857c4e02009-06-17 21:01:20 +0000385 OldValNo->setHasRedefByEC(true);
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000386
387 // Add the new live interval which replaces the range for the input copy.
388 LiveRange LR(DefIndex, RedefIndex, ValNo);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000389 DEBUG(errs() << " replace range with " << LR);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000390 interval.addRange(LR);
Lang Hames86511252009-09-04 20:41:11 +0000391 ValNo->addKill(RedefIndex);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000392
393 // If this redefinition is dead, we need to add a dummy unit live
394 // range covering the def slot.
Owen Anderson6b098de2008-06-25 23:39:39 +0000395 if (MO.isDead())
Lang Hames233a60e2009-11-03 23:52:08 +0000396 interval.addRange(LiveRange(RedefIndex, RedefIndex.getStoreIndex(),
397 OldValNo));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000398
Bill Wendling8e6179f2009-08-22 20:18:03 +0000399 DEBUG({
400 errs() << " RESULT: ";
401 interval.print(errs(), tri_);
402 });
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000403 } else {
404 // Otherwise, this must be because of phi elimination. If this is the
405 // first redefinition of the vreg that we have seen, go back and change
406 // the live range in the PHI block to be a different value number.
407 if (interval.containsOneValue()) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000408 // Remove the old range that we now know has an incorrect number.
Evan Chengf3bb2e62007-09-05 21:46:51 +0000409 VNInfo *VNI = interval.getValNumInfo(0);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000410 MachineInstr *Killer = vi.Kills[0];
Evan Cheng752195e2009-09-14 21:33:42 +0000411 phiJoinCopies.push_back(Killer);
Lang Hames233a60e2009-11-03 23:52:08 +0000412 SlotIndex Start = getMBBStartIdx(Killer->getParent());
413 SlotIndex End = getInstructionIndex(Killer).getDefIndex();
Bill Wendling8e6179f2009-08-22 20:18:03 +0000414 DEBUG({
415 errs() << " Removing [" << Start << "," << End << "] from: ";
416 interval.print(errs(), tri_);
417 errs() << "\n";
418 });
Lang Hamesffd13262009-07-09 03:57:02 +0000419 interval.removeRange(Start, End);
420 assert(interval.ranges.size() == 1 &&
Evan Cheng752195e2009-09-14 21:33:42 +0000421 "Newly discovered PHI interval has >1 ranges.");
Lang Hames86511252009-09-04 20:41:11 +0000422 MachineBasicBlock *killMBB = getMBBFromIndex(interval.endIndex());
Lang Hames233a60e2009-11-03 23:52:08 +0000423 VNI->addKill(indexes_->getTerminatorGap(killMBB));
Lang Hames857c4e02009-06-17 21:01:20 +0000424 VNI->setHasPHIKill(true);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000425 DEBUG({
426 errs() << " RESULT: ";
427 interval.print(errs(), tri_);
428 });
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000429
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000430 // Replace the interval with one of a NEW value number. Note that this
431 // value number isn't actually defined by an instruction, weird huh? :)
Lang Hames10382fb2009-06-19 02:17:53 +0000432 LiveRange LR(Start, End,
Lang Hames233a60e2009-11-03 23:52:08 +0000433 interval.getNextValue(SlotIndex(getMBBStartIdx(mbb), true),
434 0, false, VNInfoAllocator));
Lang Hames857c4e02009-06-17 21:01:20 +0000435 LR.valno->setIsPHIDef(true);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000436 DEBUG(errs() << " replace range with " << LR);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000437 interval.addRange(LR);
Lang Hames86511252009-09-04 20:41:11 +0000438 LR.valno->addKill(End);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000439 DEBUG({
440 errs() << " RESULT: ";
441 interval.print(errs(), tri_);
442 });
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000443 }
444
445 // In the case of PHI elimination, each variable definition is only
446 // live until the end of the block. We've already taken care of the
447 // rest of the live range.
Lang Hames233a60e2009-11-03 23:52:08 +0000448 SlotIndex defIndex = MIIdx.getDefIndex();
Evan Chengfb112882009-03-23 08:01:15 +0000449 if (MO.isEarlyClobber())
Lang Hames233a60e2009-11-03 23:52:08 +0000450 defIndex = MIIdx.getUseIndex();
Evan Cheng752195e2009-09-14 21:33:42 +0000451
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000452 VNInfo *ValNo;
Evan Chengc8d044e2008-02-15 18:24:29 +0000453 MachineInstr *CopyMI = NULL;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000454 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000455 if (mi->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000456 mi->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Dan Gohman97121ba2009-04-08 00:15:30 +0000457 mi->getOpcode() == TargetInstrInfo::SUBREG_TO_REG ||
Evan Cheng04ee5a12009-01-20 19:12:24 +0000458 tii_->isMoveInstr(*mi, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000459 CopyMI = mi;
Lang Hames857c4e02009-06-17 21:01:20 +0000460 ValNo = interval.getNextValue(defIndex, CopyMI, true, VNInfoAllocator);
Chris Lattner91725b72006-08-31 05:54:43 +0000461
Lang Hames233a60e2009-11-03 23:52:08 +0000462 SlotIndex killIndex = getMBBEndIdx(mbb).getNextIndex().getLoadIndex();
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000463 LiveRange LR(defIndex, killIndex, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000464 interval.addRange(LR);
Lang Hames233a60e2009-11-03 23:52:08 +0000465 ValNo->addKill(indexes_->getTerminatorGap(mbb));
Lang Hames857c4e02009-06-17 21:01:20 +0000466 ValNo->setHasPHIKill(true);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000467 DEBUG(errs() << " +" << LR);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000468 }
469 }
470
Bill Wendling8e6179f2009-08-22 20:18:03 +0000471 DEBUG(errs() << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000472}
473
Chris Lattnerf35fef72004-07-23 21:24:19 +0000474void LiveIntervals::handlePhysicalRegisterDef(MachineBasicBlock *MBB,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000475 MachineBasicBlock::iterator mi,
Lang Hames233a60e2009-11-03 23:52:08 +0000476 SlotIndex MIIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000477 MachineOperand& MO,
Chris Lattner91725b72006-08-31 05:54:43 +0000478 LiveInterval &interval,
Evan Chengc8d044e2008-02-15 18:24:29 +0000479 MachineInstr *CopyMI) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000480 // A physical register cannot be live across basic block, so its
481 // lifetime must end somewhere in its defining basic block.
Bill Wendling8e6179f2009-08-22 20:18:03 +0000482 DEBUG({
483 errs() << "\t\tregister: ";
Evan Cheng752195e2009-09-14 21:33:42 +0000484 printRegName(interval.reg, tri_);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000485 });
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000486
Lang Hames233a60e2009-11-03 23:52:08 +0000487 SlotIndex baseIndex = MIIdx;
488 SlotIndex start = baseIndex.getDefIndex();
Dale Johannesen86b49f82008-09-24 01:07:17 +0000489 // Earlyclobbers move back one.
490 if (MO.isEarlyClobber())
Lang Hames233a60e2009-11-03 23:52:08 +0000491 start = MIIdx.getUseIndex();
492 SlotIndex end = start;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000493
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000494 // If it is not used after definition, it is considered dead at
495 // the instruction defining it. Hence its interval is:
496 // [defSlot(def), defSlot(def)+1)
Dale Johannesen39faac22009-09-20 00:36:41 +0000497 // For earlyclobbers, the defSlot was pushed back one; the extra
498 // advance below compensates.
Owen Anderson6b098de2008-06-25 23:39:39 +0000499 if (MO.isDead()) {
Bill Wendling8e6179f2009-08-22 20:18:03 +0000500 DEBUG(errs() << " dead");
Lang Hames233a60e2009-11-03 23:52:08 +0000501 end = start.getStoreIndex();
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000502 goto exit;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000503 }
504
505 // If it is not dead on definition, it must be killed by a
506 // subsequent instruction. Hence its interval is:
507 // [defSlot(def), useSlot(kill)+1)
Lang Hames233a60e2009-11-03 23:52:08 +0000508 baseIndex = baseIndex.getNextIndex();
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000509 while (++mi != MBB->end()) {
Lang Hames233a60e2009-11-03 23:52:08 +0000510
511 if (getInstructionFromIndex(baseIndex) == 0)
512 baseIndex = indexes_->getNextNonNullIndex(baseIndex);
513
Evan Cheng6130f662008-03-05 00:59:57 +0000514 if (mi->killsRegister(interval.reg, tri_)) {
Bill Wendling8e6179f2009-08-22 20:18:03 +0000515 DEBUG(errs() << " killed");
Lang Hames233a60e2009-11-03 23:52:08 +0000516 end = baseIndex.getDefIndex();
Chris Lattnerab4b66d2005-08-23 22:51:41 +0000517 goto exit;
Evan Chengc45288e2009-04-27 20:42:46 +0000518 } else {
519 int DefIdx = mi->findRegisterDefOperandIdx(interval.reg, false, tri_);
520 if (DefIdx != -1) {
521 if (mi->isRegTiedToUseOperand(DefIdx)) {
522 // Two-address instruction.
Lang Hames233a60e2009-11-03 23:52:08 +0000523 end = baseIndex.getDefIndex();
524 assert(!mi->getOperand(DefIdx).isEarlyClobber() &&
525 "Two address instruction is an early clobber?");
Evan Chengc45288e2009-04-27 20:42:46 +0000526 } else {
527 // Another instruction redefines the register before it is ever read.
528 // Then the register is essentially dead at the instruction that defines
529 // it. Hence its interval is:
530 // [defSlot(def), defSlot(def)+1)
Bill Wendling8e6179f2009-08-22 20:18:03 +0000531 DEBUG(errs() << " dead");
Lang Hames233a60e2009-11-03 23:52:08 +0000532 end = start.getStoreIndex();
Evan Chengc45288e2009-04-27 20:42:46 +0000533 }
534 goto exit;
535 }
Alkis Evlogimenosaf254732004-01-13 22:26:14 +0000536 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000537
Lang Hames233a60e2009-11-03 23:52:08 +0000538 baseIndex = baseIndex.getNextIndex();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000539 }
Chris Lattner5ab6f5f2005-09-02 00:20:32 +0000540
541 // The only case we should have a dead physreg here without a killing or
542 // instruction where we know it's dead is if it is live-in to the function
Evan Chengd521bc92009-04-27 17:36:47 +0000543 // and never used. Another possible case is the implicit use of the
544 // physical register has been deleted by two-address pass.
Lang Hames233a60e2009-11-03 23:52:08 +0000545 end = start.getStoreIndex();
Alkis Evlogimenos02ba13c2004-01-31 23:13:30 +0000546
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000547exit:
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000548 assert(start < end && "did not find end of interval?");
Chris Lattnerf768bba2005-03-09 23:05:19 +0000549
Evan Cheng24a3cc42007-04-25 07:30:23 +0000550 // Already exists? Extend old live interval.
551 LiveInterval::iterator OldLR = interval.FindLiveRangeContaining(start);
Evan Cheng5379f412008-12-19 20:58:01 +0000552 bool Extend = OldLR != interval.end();
553 VNInfo *ValNo = Extend
Lang Hames857c4e02009-06-17 21:01:20 +0000554 ? OldLR->valno : interval.getNextValue(start, CopyMI, true, VNInfoAllocator);
Evan Cheng5379f412008-12-19 20:58:01 +0000555 if (MO.isEarlyClobber() && Extend)
Lang Hames857c4e02009-06-17 21:01:20 +0000556 ValNo->setHasRedefByEC(true);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000557 LiveRange LR(start, end, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000558 interval.addRange(LR);
Lang Hames86511252009-09-04 20:41:11 +0000559 LR.valno->addKill(end);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000560 DEBUG(errs() << " +" << LR << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000561}
562
Chris Lattnerf35fef72004-07-23 21:24:19 +0000563void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
564 MachineBasicBlock::iterator MI,
Lang Hames233a60e2009-11-03 23:52:08 +0000565 SlotIndex MIIdx,
Evan Chengef0732d2008-07-10 07:35:43 +0000566 MachineOperand& MO,
567 unsigned MOIdx) {
Owen Anderson6b098de2008-06-25 23:39:39 +0000568 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Evan Chengef0732d2008-07-10 07:35:43 +0000569 handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000570 getOrCreateInterval(MO.getReg()));
571 else if (allocatableRegs_[MO.getReg()]) {
Evan Chengc8d044e2008-02-15 18:24:29 +0000572 MachineInstr *CopyMI = NULL;
Evan Cheng04ee5a12009-01-20 19:12:24 +0000573 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Evan Chengc8d044e2008-02-15 18:24:29 +0000574 if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG ||
Evan Cheng7e073ba2008-04-09 20:57:25 +0000575 MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
Dan Gohman97121ba2009-04-08 00:15:30 +0000576 MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG ||
Evan Cheng04ee5a12009-01-20 19:12:24 +0000577 tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000578 CopyMI = MI;
Evan Chengc45288e2009-04-27 20:42:46 +0000579 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
Owen Anderson6b098de2008-06-25 23:39:39 +0000580 getOrCreateInterval(MO.getReg()), CopyMI);
Evan Cheng24a3cc42007-04-25 07:30:23 +0000581 // Def of a register also defines its sub-registers.
Owen Anderson6b098de2008-06-25 23:39:39 +0000582 for (const unsigned* AS = tri_->getSubRegisters(MO.getReg()); *AS; ++AS)
Evan Cheng6130f662008-03-05 00:59:57 +0000583 // If MI also modifies the sub-register explicitly, avoid processing it
584 // more than once. Do not pass in TRI here so it checks for exact match.
585 if (!MI->modifiesRegister(*AS))
Evan Chengc45288e2009-04-27 20:42:46 +0000586 handlePhysicalRegisterDef(MBB, MI, MIIdx, MO,
Owen Anderson6b098de2008-06-25 23:39:39 +0000587 getOrCreateInterval(*AS), 0);
Chris Lattnerf35fef72004-07-23 21:24:19 +0000588 }
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000589}
590
Evan Chengb371f452007-02-19 21:49:54 +0000591void LiveIntervals::handleLiveInRegister(MachineBasicBlock *MBB,
Lang Hames233a60e2009-11-03 23:52:08 +0000592 SlotIndex MIIdx,
Evan Cheng24a3cc42007-04-25 07:30:23 +0000593 LiveInterval &interval, bool isAlias) {
Bill Wendling8e6179f2009-08-22 20:18:03 +0000594 DEBUG({
595 errs() << "\t\tlivein register: ";
Evan Cheng752195e2009-09-14 21:33:42 +0000596 printRegName(interval.reg, tri_);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000597 });
Evan Chengb371f452007-02-19 21:49:54 +0000598
599 // Look for kills, if it reaches a def before it's killed, then it shouldn't
600 // be considered a livein.
601 MachineBasicBlock::iterator mi = MBB->begin();
Lang Hames233a60e2009-11-03 23:52:08 +0000602 SlotIndex baseIndex = MIIdx;
603 SlotIndex start = baseIndex;
604 if (getInstructionFromIndex(baseIndex) == 0)
605 baseIndex = indexes_->getNextNonNullIndex(baseIndex);
606
607 SlotIndex end = baseIndex;
Evan Cheng0076c612009-03-05 03:34:26 +0000608 bool SeenDefUse = false;
Owen Anderson99500ae2008-09-15 22:00:38 +0000609
Evan Chengb371f452007-02-19 21:49:54 +0000610 while (mi != MBB->end()) {
Evan Cheng6130f662008-03-05 00:59:57 +0000611 if (mi->killsRegister(interval.reg, tri_)) {
Bill Wendling8e6179f2009-08-22 20:18:03 +0000612 DEBUG(errs() << " killed");
Lang Hames233a60e2009-11-03 23:52:08 +0000613 end = baseIndex.getDefIndex();
Evan Cheng0076c612009-03-05 03:34:26 +0000614 SeenDefUse = true;
Lang Hamesd21c3162009-06-18 22:01:47 +0000615 break;
Evan Cheng6130f662008-03-05 00:59:57 +0000616 } else if (mi->modifiesRegister(interval.reg, tri_)) {
Evan Chengb371f452007-02-19 21:49:54 +0000617 // Another instruction redefines the register before it is ever read.
618 // Then the register is essentially dead at the instruction that defines
619 // it. Hence its interval is:
620 // [defSlot(def), defSlot(def)+1)
Bill Wendling8e6179f2009-08-22 20:18:03 +0000621 DEBUG(errs() << " dead");
Lang Hames233a60e2009-11-03 23:52:08 +0000622 end = start.getStoreIndex();
Evan Cheng0076c612009-03-05 03:34:26 +0000623 SeenDefUse = true;
Lang Hamesd21c3162009-06-18 22:01:47 +0000624 break;
Evan Chengb371f452007-02-19 21:49:54 +0000625 }
626
Evan Chengb371f452007-02-19 21:49:54 +0000627 ++mi;
Evan Cheng0076c612009-03-05 03:34:26 +0000628 if (mi != MBB->end()) {
Lang Hames233a60e2009-11-03 23:52:08 +0000629 baseIndex = indexes_->getNextNonNullIndex(baseIndex);
Evan Cheng0076c612009-03-05 03:34:26 +0000630 }
Evan Chengb371f452007-02-19 21:49:54 +0000631 }
632
Evan Cheng75611fb2007-06-27 01:16:36 +0000633 // Live-in register might not be used at all.
Evan Cheng0076c612009-03-05 03:34:26 +0000634 if (!SeenDefUse) {
Evan Cheng292da942007-06-27 18:47:28 +0000635 if (isAlias) {
Bill Wendling8e6179f2009-08-22 20:18:03 +0000636 DEBUG(errs() << " dead");
Lang Hames233a60e2009-11-03 23:52:08 +0000637 end = MIIdx.getStoreIndex();
Evan Cheng292da942007-06-27 18:47:28 +0000638 } else {
Bill Wendling8e6179f2009-08-22 20:18:03 +0000639 DEBUG(errs() << " live through");
Evan Cheng292da942007-06-27 18:47:28 +0000640 end = baseIndex;
641 }
Evan Cheng24a3cc42007-04-25 07:30:23 +0000642 }
643
Lang Hames10382fb2009-06-19 02:17:53 +0000644 VNInfo *vni =
Lang Hames233a60e2009-11-03 23:52:08 +0000645 interval.getNextValue(SlotIndex(getMBBStartIdx(MBB), true),
Lang Hames86511252009-09-04 20:41:11 +0000646 0, false, VNInfoAllocator);
Lang Hamesd21c3162009-06-18 22:01:47 +0000647 vni->setIsPHIDef(true);
648 LiveRange LR(start, end, vni);
Jakob Stoklund Olesen3de23e62009-11-07 01:58:40 +0000649
Jim Laskey9b25b8c2007-02-21 22:41:17 +0000650 interval.addRange(LR);
Lang Hames86511252009-09-04 20:41:11 +0000651 LR.valno->addKill(end);
Bill Wendling8e6179f2009-08-22 20:18:03 +0000652 DEBUG(errs() << " +" << LR << '\n');
Evan Chengb371f452007-02-19 21:49:54 +0000653}
654
Jakob Stoklund Olesen3de23e62009-11-07 01:58:40 +0000655bool LiveIntervals::
656isSafeAndProfitableToCoalesce(LiveInterval &DstInt,
657 LiveInterval &SrcInt,
658 SmallVector<MachineInstr*,16> &IdentCopies,
659 SmallVector<MachineInstr*,16> &OtherCopies) {
Evan Cheng752195e2009-09-14 21:33:42 +0000660 unsigned NumIdent = 0;
Dan Gohman2bf06492009-09-25 22:26:13 +0000661 for (MachineRegisterInfo::def_iterator ri = mri_->def_begin(SrcInt.reg),
662 re = mri_->def_end(); ri != re; ++ri) {
Evan Cheng752195e2009-09-14 21:33:42 +0000663 MachineInstr *MI = &*ri;
664 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
665 if (!tii_->isMoveInstr(*MI, SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Cheng3f855492009-09-15 06:45:16 +0000666 return false;
Evan Cheng752195e2009-09-14 21:33:42 +0000667 if (SrcReg != DstInt.reg) {
Jakob Stoklund Olesen3de23e62009-11-07 01:58:40 +0000668 // Non-identity copy - we cannot handle overlapping intervals
669 if (DstInt.liveAt(getInstructionIndex(MI)))
670 return false;
Evan Cheng752195e2009-09-14 21:33:42 +0000671 OtherCopies.push_back(MI);
Evan Cheng752195e2009-09-14 21:33:42 +0000672 } else {
673 IdentCopies.push_back(MI);
674 ++NumIdent;
675 }
676 }
677
Evan Cheng3f855492009-09-15 06:45:16 +0000678 return IdentCopies.size() > OtherCopies.size();
Evan Cheng752195e2009-09-14 21:33:42 +0000679}
680
681void LiveIntervals::performEarlyCoalescing() {
682 if (!EarlyCoalescing)
683 return;
684
685 /// Perform early coalescing: eliminate copies which feed into phi joins
686 /// and whose sources are defined by the phi joins.
687 for (unsigned i = 0, e = phiJoinCopies.size(); i != e; ++i) {
688 MachineInstr *Join = phiJoinCopies[i];
689 if (CoalescingLimit != -1 && (int)numCoalescing == CoalescingLimit)
690 break;
691
692 unsigned PHISrc, PHIDst, SrcSubReg, DstSubReg;
693 bool isMove= tii_->isMoveInstr(*Join, PHISrc, PHIDst, SrcSubReg, DstSubReg);
694#ifndef NDEBUG
695 assert(isMove && "PHI join instruction must be a move!");
696#else
697 isMove = isMove;
698#endif
699
700 LiveInterval &DstInt = getInterval(PHIDst);
701 LiveInterval &SrcInt = getInterval(PHISrc);
702 SmallVector<MachineInstr*, 16> IdentCopies;
703 SmallVector<MachineInstr*, 16> OtherCopies;
Jakob Stoklund Olesen3de23e62009-11-07 01:58:40 +0000704 if (!isSafeAndProfitableToCoalesce(DstInt, SrcInt,
705 IdentCopies, OtherCopies))
Evan Cheng752195e2009-09-14 21:33:42 +0000706 continue;
707
708 DEBUG(errs() << "PHI Join: " << *Join);
709 assert(DstInt.containsOneValue() && "PHI join should have just one val#!");
Jakob Stoklund Olesen3de23e62009-11-07 01:58:40 +0000710 assert(std::distance(mri_->use_begin(PHISrc), mri_->use_end()) == 1 &&
711 "PHI join src should not be used elsewhere");
Evan Cheng752195e2009-09-14 21:33:42 +0000712 VNInfo *VNI = DstInt.getValNumInfo(0);
Evan Cheng752195e2009-09-14 21:33:42 +0000713
Evan Cheng3f855492009-09-15 06:45:16 +0000714 // Change the non-identity copies to directly target the phi destination.
715 for (unsigned i = 0, e = OtherCopies.size(); i != e; ++i) {
716 MachineInstr *PHICopy = OtherCopies[i];
Lang Hames233a60e2009-11-03 23:52:08 +0000717 SlotIndex MIIndex = getInstructionIndex(PHICopy);
Jakob Stoklund Olesen3de23e62009-11-07 01:58:40 +0000718 DEBUG(errs() << "Moving: " << MIIndex << ' ' << *PHICopy);
Lang Hames233a60e2009-11-03 23:52:08 +0000719 SlotIndex DefIndex = MIIndex.getDefIndex();
Evan Cheng752195e2009-09-14 21:33:42 +0000720 LiveRange *SLR = SrcInt.getLiveRangeContaining(DefIndex);
Lang Hames233a60e2009-11-03 23:52:08 +0000721 SlotIndex StartIndex = SLR->start;
722 SlotIndex EndIndex = SLR->end;
Evan Cheng752195e2009-09-14 21:33:42 +0000723
724 // Delete val# defined by the now identity copy and add the range from
725 // beginning of the mbb to the end of the range.
726 SrcInt.removeValNo(SLR->valno);
Evan Cheng3f855492009-09-15 06:45:16 +0000727 DEBUG(errs() << " added range [" << StartIndex << ','
728 << EndIndex << "] to reg" << DstInt.reg << '\n');
Jakob Stoklund Olesen3de23e62009-11-07 01:58:40 +0000729 assert (!DstInt.liveAt(StartIndex) && "Cannot coalesce when dst live!");
Evan Cheng3f855492009-09-15 06:45:16 +0000730 VNInfo *NewVNI = DstInt.getNextValue(DefIndex, PHICopy, true,
731 VNInfoAllocator);
732 NewVNI->setHasPHIKill(true);
733 DstInt.addRange(LiveRange(StartIndex, EndIndex, NewVNI));
734 for (unsigned j = 0, ee = PHICopy->getNumOperands(); j != ee; ++j) {
735 MachineOperand &MO = PHICopy->getOperand(j);
736 if (!MO.isReg() || MO.getReg() != PHISrc)
737 continue;
738 MO.setReg(PHIDst);
Evan Cheng752195e2009-09-14 21:33:42 +0000739 }
Evan Cheng3f855492009-09-15 06:45:16 +0000740 }
741
742 // Now let's eliminate all the would-be identity copies.
743 for (unsigned i = 0, e = IdentCopies.size(); i != e; ++i) {
744 MachineInstr *PHICopy = IdentCopies[i];
745 DEBUG(errs() << "Coalescing: " << *PHICopy);
746
Lang Hames233a60e2009-11-03 23:52:08 +0000747 SlotIndex MIIndex = getInstructionIndex(PHICopy);
748 SlotIndex DefIndex = MIIndex.getDefIndex();
Evan Cheng3f855492009-09-15 06:45:16 +0000749 LiveRange *SLR = SrcInt.getLiveRangeContaining(DefIndex);
Lang Hames233a60e2009-11-03 23:52:08 +0000750 SlotIndex StartIndex = SLR->start;
751 SlotIndex EndIndex = SLR->end;
Evan Cheng3f855492009-09-15 06:45:16 +0000752
753 // Delete val# defined by the now identity copy and add the range from
754 // beginning of the mbb to the end of the range.
755 SrcInt.removeValNo(SLR->valno);
Evan Cheng752195e2009-09-14 21:33:42 +0000756 RemoveMachineInstrFromMaps(PHICopy);
757 PHICopy->eraseFromParent();
Evan Cheng3f855492009-09-15 06:45:16 +0000758 DEBUG(errs() << " added range [" << StartIndex << ','
759 << EndIndex << "] to reg" << DstInt.reg << '\n');
760 DstInt.addRange(LiveRange(StartIndex, EndIndex, VNI));
Evan Cheng752195e2009-09-14 21:33:42 +0000761 }
Evan Cheng752195e2009-09-14 21:33:42 +0000762
Evan Cheng3f855492009-09-15 06:45:16 +0000763 // Remove the phi join and update the phi block liveness.
Lang Hames233a60e2009-11-03 23:52:08 +0000764 SlotIndex MIIndex = getInstructionIndex(Join);
765 SlotIndex UseIndex = MIIndex.getUseIndex();
766 SlotIndex DefIndex = MIIndex.getDefIndex();
Evan Cheng3f855492009-09-15 06:45:16 +0000767 LiveRange *SLR = SrcInt.getLiveRangeContaining(UseIndex);
768 LiveRange *DLR = DstInt.getLiveRangeContaining(DefIndex);
769 DLR->valno->setCopy(0);
770 DLR->valno->setIsDefAccurate(false);
771 DstInt.addRange(LiveRange(SLR->start, SLR->end, DLR->valno));
772 SrcInt.removeRange(SLR->start, SLR->end);
773 assert(SrcInt.empty());
774 removeInterval(PHISrc);
775 RemoveMachineInstrFromMaps(Join);
776 Join->eraseFromParent();
Evan Cheng752195e2009-09-14 21:33:42 +0000777
778 ++numCoalescing;
779 }
780}
781
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000782/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000783/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000784/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000785/// which a variable is live
Dale Johannesen91aac102008-09-17 21:13:11 +0000786void LiveIntervals::computeIntervals() {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000787 DEBUG(errs() << "********** COMPUTING LIVE INTERVALS **********\n"
Bill Wendling8e6179f2009-08-22 20:18:03 +0000788 << "********** Function: "
789 << ((Value*)mf_->getFunction())->getName() << '\n');
Evan Chengd129d732009-07-17 19:43:40 +0000790
791 SmallVector<unsigned, 8> UndefUses;
Chris Lattner428b92e2006-09-15 03:57:23 +0000792 for (MachineFunction::iterator MBBI = mf_->begin(), E = mf_->end();
793 MBBI != E; ++MBBI) {
794 MachineBasicBlock *MBB = MBBI;
Owen Anderson134eb732008-09-21 20:43:24 +0000795 // Track the index of the current machine instr.
Lang Hames233a60e2009-11-03 23:52:08 +0000796 SlotIndex MIIndex = getMBBStartIdx(MBB);
Daniel Dunbarce63ffb2009-07-25 00:23:56 +0000797 DEBUG(errs() << ((Value*)MBB->getBasicBlock())->getName() << ":\n");
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000798
Chris Lattner428b92e2006-09-15 03:57:23 +0000799 MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
Evan Cheng0c9f92e2007-02-13 01:30:55 +0000800
Dan Gohmancb406c22007-10-03 19:26:29 +0000801 // Create intervals for live-ins to this BB first.
802 for (MachineBasicBlock::const_livein_iterator LI = MBB->livein_begin(),
803 LE = MBB->livein_end(); LI != LE; ++LI) {
804 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*LI));
805 // Multiple live-ins can alias the same register.
Dan Gohman6f0d0242008-02-10 18:45:23 +0000806 for (const unsigned* AS = tri_->getSubRegisters(*LI); *AS; ++AS)
Dan Gohmancb406c22007-10-03 19:26:29 +0000807 if (!hasInterval(*AS))
808 handleLiveInRegister(MBB, MIIndex, getOrCreateInterval(*AS),
809 true);
Chris Lattnerdffb2e82006-09-04 18:27:40 +0000810 }
811
Owen Anderson99500ae2008-09-15 22:00:38 +0000812 // Skip over empty initial indices.
Lang Hames233a60e2009-11-03 23:52:08 +0000813 if (getInstructionFromIndex(MIIndex) == 0)
814 MIIndex = indexes_->getNextNonNullIndex(MIIndex);
Owen Anderson99500ae2008-09-15 22:00:38 +0000815
Chris Lattner428b92e2006-09-15 03:57:23 +0000816 for (; MI != miEnd; ++MI) {
Bill Wendling8e6179f2009-08-22 20:18:03 +0000817 DEBUG(errs() << MIIndex << "\t" << *MI);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000818
Evan Cheng438f7bc2006-11-10 08:43:01 +0000819 // Handle defs.
Chris Lattner428b92e2006-09-15 03:57:23 +0000820 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
821 MachineOperand &MO = MI->getOperand(i);
Evan Chengd129d732009-07-17 19:43:40 +0000822 if (!MO.isReg() || !MO.getReg())
823 continue;
824
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000825 // handle register defs - build intervals
Evan Chengd129d732009-07-17 19:43:40 +0000826 if (MO.isDef())
Evan Chengef0732d2008-07-10 07:35:43 +0000827 handleRegisterDef(MBB, MI, MIIndex, MO, i);
Evan Chengd129d732009-07-17 19:43:40 +0000828 else if (MO.isUndef())
829 UndefUses.push_back(MO.getReg());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000830 }
Owen Anderson7fbad272008-07-23 21:37:49 +0000831
Lang Hames233a60e2009-11-03 23:52:08 +0000832 // Move to the next instr slot.
833 MIIndex = indexes_->getNextNonNullIndex(MIIndex);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000834 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000835 }
Evan Chengd129d732009-07-17 19:43:40 +0000836
837 // Create empty intervals for registers defined by implicit_def's (except
838 // for those implicit_def that define values which are liveout of their
839 // blocks.
840 for (unsigned i = 0, e = UndefUses.size(); i != e; ++i) {
841 unsigned UndefReg = UndefUses[i];
842 (void)getOrCreateInterval(UndefReg);
843 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000844}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000845
Owen Anderson03857b22008-08-13 21:49:13 +0000846LiveInterval* LiveIntervals::createInterval(unsigned reg) {
Evan Cheng0a1fcce2009-02-08 11:04:35 +0000847 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? HUGE_VALF : 0.0F;
Owen Anderson03857b22008-08-13 21:49:13 +0000848 return new LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000849}
Evan Chengf2fbca62007-11-12 06:35:08 +0000850
Evan Cheng0a1fcce2009-02-08 11:04:35 +0000851/// dupInterval - Duplicate a live interval. The caller is responsible for
852/// managing the allocated memory.
853LiveInterval* LiveIntervals::dupInterval(LiveInterval *li) {
854 LiveInterval *NewLI = createInterval(li->reg);
Evan Cheng90f95f82009-06-14 20:22:55 +0000855 NewLI->Copy(*li, mri_, getVNInfoAllocator());
Evan Cheng0a1fcce2009-02-08 11:04:35 +0000856 return NewLI;
857}
858
Evan Chengc8d044e2008-02-15 18:24:29 +0000859/// getVNInfoSourceReg - Helper function that parses the specified VNInfo
860/// copy field and returns the source register that defines it.
861unsigned LiveIntervals::getVNInfoSourceReg(const VNInfo *VNI) const {
Lang Hames52c1afc2009-08-10 23:43:28 +0000862 if (!VNI->getCopy())
Evan Chengc8d044e2008-02-15 18:24:29 +0000863 return 0;
864
Lang Hames52c1afc2009-08-10 23:43:28 +0000865 if (VNI->getCopy()->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) {
Evan Cheng8f90b6e2009-01-07 02:08:57 +0000866 // If it's extracting out of a physical register, return the sub-register.
Lang Hames52c1afc2009-08-10 23:43:28 +0000867 unsigned Reg = VNI->getCopy()->getOperand(1).getReg();
Evan Cheng8f90b6e2009-01-07 02:08:57 +0000868 if (TargetRegisterInfo::isPhysicalRegister(Reg))
Lang Hames52c1afc2009-08-10 23:43:28 +0000869 Reg = tri_->getSubReg(Reg, VNI->getCopy()->getOperand(2).getImm());
Evan Cheng8f90b6e2009-01-07 02:08:57 +0000870 return Reg;
Lang Hames52c1afc2009-08-10 23:43:28 +0000871 } else if (VNI->getCopy()->getOpcode() == TargetInstrInfo::INSERT_SUBREG ||
872 VNI->getCopy()->getOpcode() == TargetInstrInfo::SUBREG_TO_REG)
873 return VNI->getCopy()->getOperand(2).getReg();
Evan Cheng8f90b6e2009-01-07 02:08:57 +0000874
Evan Cheng04ee5a12009-01-20 19:12:24 +0000875 unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
Lang Hames52c1afc2009-08-10 23:43:28 +0000876 if (tii_->isMoveInstr(*VNI->getCopy(), SrcReg, DstReg, SrcSubReg, DstSubReg))
Evan Chengc8d044e2008-02-15 18:24:29 +0000877 return SrcReg;
Torok Edwinc23197a2009-07-14 16:55:14 +0000878 llvm_unreachable("Unrecognized copy instruction!");
Evan Chengc8d044e2008-02-15 18:24:29 +0000879 return 0;
880}
Evan Chengf2fbca62007-11-12 06:35:08 +0000881
882//===----------------------------------------------------------------------===//
883// Register allocator hooks.
884//
885
Evan Chengd70dbb52008-02-22 09:24:50 +0000886/// getReMatImplicitUse - If the remat definition MI has one (for now, we only
887/// allow one) virtual register operand, then its uses are implicitly using
888/// the register. Returns the virtual register.
889unsigned LiveIntervals::getReMatImplicitUse(const LiveInterval &li,
890 MachineInstr *MI) const {
891 unsigned RegOp = 0;
892 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
893 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000894 if (!MO.isReg() || !MO.isUse())
Evan Chengd70dbb52008-02-22 09:24:50 +0000895 continue;
896 unsigned Reg = MO.getReg();
897 if (Reg == 0 || Reg == li.reg)
898 continue;
Chris Lattner1873d0c2009-06-27 04:06:41 +0000899
900 if (TargetRegisterInfo::isPhysicalRegister(Reg) &&
901 !allocatableRegs_[Reg])
902 continue;
Evan Chengd70dbb52008-02-22 09:24:50 +0000903 // FIXME: For now, only remat MI with at most one register operand.
904 assert(!RegOp &&
905 "Can't rematerialize instruction with multiple register operand!");
906 RegOp = MO.getReg();
Dan Gohman6d69ba82008-07-25 00:02:30 +0000907#ifndef NDEBUG
Evan Chengd70dbb52008-02-22 09:24:50 +0000908 break;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000909#endif
Evan Chengd70dbb52008-02-22 09:24:50 +0000910 }
911 return RegOp;
912}
913
914/// isValNoAvailableAt - Return true if the val# of the specified interval
915/// which reaches the given instruction also reaches the specified use index.
916bool LiveIntervals::isValNoAvailableAt(const LiveInterval &li, MachineInstr *MI,
Lang Hames233a60e2009-11-03 23:52:08 +0000917 SlotIndex UseIdx) const {
918 SlotIndex Index = getInstructionIndex(MI);
Evan Chengd70dbb52008-02-22 09:24:50 +0000919 VNInfo *ValNo = li.FindLiveRangeContaining(Index)->valno;
920 LiveInterval::const_iterator UI = li.FindLiveRangeContaining(UseIdx);
921 return UI != li.end() && UI->valno == ValNo;
922}
923
Evan Chengf2fbca62007-11-12 06:35:08 +0000924/// isReMaterializable - Returns true if the definition MI of the specified
925/// val# of the specified interval is re-materializable.
926bool LiveIntervals::isReMaterializable(const LiveInterval &li,
Evan Cheng5ef3a042007-12-06 00:01:56 +0000927 const VNInfo *ValNo, MachineInstr *MI,
Evan Chengdc377862008-09-30 15:44:16 +0000928 SmallVectorImpl<LiveInterval*> &SpillIs,
Evan Cheng5ef3a042007-12-06 00:01:56 +0000929 bool &isLoad) {
Evan Chengf2fbca62007-11-12 06:35:08 +0000930 if (DisableReMat)
931 return false;
932
Dan Gohmana70dca12009-10-09 23:27:56 +0000933 if (!tii_->isTriviallyReMaterializable(MI, aa_))
934 return false;
Evan Chengdd3465e2008-02-23 01:44:27 +0000935
Dan Gohmana70dca12009-10-09 23:27:56 +0000936 // Target-specific code can mark an instruction as being rematerializable
937 // if it has one virtual reg use, though it had better be something like
938 // a PIC base register which is likely to be live everywhere.
Dan Gohman6d69ba82008-07-25 00:02:30 +0000939 unsigned ImpUse = getReMatImplicitUse(li, MI);
940 if (ImpUse) {
941 const LiveInterval &ImpLi = getInterval(ImpUse);
942 for (MachineRegisterInfo::use_iterator ri = mri_->use_begin(li.reg),
943 re = mri_->use_end(); ri != re; ++ri) {
944 MachineInstr *UseMI = &*ri;
Lang Hames233a60e2009-11-03 23:52:08 +0000945 SlotIndex UseIdx = getInstructionIndex(UseMI);
Dan Gohman6d69ba82008-07-25 00:02:30 +0000946 if (li.FindLiveRangeContaining(UseIdx)->valno != ValNo)
947 continue;
948 if (!isValNoAvailableAt(ImpLi, MI, UseIdx))
949 return false;
950 }
Evan Chengdc377862008-09-30 15:44:16 +0000951
952 // If a register operand of the re-materialized instruction is going to
953 // be spilled next, then it's not legal to re-materialize this instruction.
954 for (unsigned i = 0, e = SpillIs.size(); i != e; ++i)
955 if (ImpUse == SpillIs[i]->reg)
956 return false;
Dan Gohman6d69ba82008-07-25 00:02:30 +0000957 }
958 return true;
Evan Cheng5ef3a042007-12-06 00:01:56 +0000959}
960
Evan Cheng06587492008-10-24 02:05:00 +0000961/// isReMaterializable - Returns true if the definition MI of the specified
962/// val# of the specified interval is re-materializable.
963bool LiveIntervals::isReMaterializable(const LiveInterval &li,
964 const VNInfo *ValNo, MachineInstr *MI) {
965 SmallVector<LiveInterval*, 4> Dummy1;
966 bool Dummy2;
967 return isReMaterializable(li, ValNo, MI, Dummy1, Dummy2);
968}
969
Evan Cheng5ef3a042007-12-06 00:01:56 +0000970/// isReMaterializable - Returns true if every definition of MI of every
971/// val# of the specified interval is re-materializable.
Evan Chengdc377862008-09-30 15:44:16 +0000972bool LiveIntervals::isReMaterializable(const LiveInterval &li,
973 SmallVectorImpl<LiveInterval*> &SpillIs,
974 bool &isLoad) {
Evan Cheng5ef3a042007-12-06 00:01:56 +0000975 isLoad = false;
976 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
977 i != e; ++i) {
978 const VNInfo *VNI = *i;
Lang Hames857c4e02009-06-17 21:01:20 +0000979 if (VNI->isUnused())
Evan Cheng5ef3a042007-12-06 00:01:56 +0000980 continue; // Dead val#.
981 // Is the def for the val# rematerializable?
Lang Hames857c4e02009-06-17 21:01:20 +0000982 if (!VNI->isDefAccurate())
Evan Cheng5ef3a042007-12-06 00:01:56 +0000983 return false;
Lang Hames857c4e02009-06-17 21:01:20 +0000984 MachineInstr *ReMatDefMI = getInstructionFromIndex(VNI->def);
Evan Cheng5ef3a042007-12-06 00:01:56 +0000985 bool DefIsLoad = false;
Evan Chengd70dbb52008-02-22 09:24:50 +0000986 if (!ReMatDefMI ||
Evan Chengdc377862008-09-30 15:44:16 +0000987 !isReMaterializable(li, VNI, ReMatDefMI, SpillIs, DefIsLoad))
Evan Cheng5ef3a042007-12-06 00:01:56 +0000988 return false;
989 isLoad |= DefIsLoad;
Evan Chengf2fbca62007-11-12 06:35:08 +0000990 }
991 return true;
992}
993
Evan Cheng79a0c1e2008-02-25 08:50:41 +0000994/// FilterFoldedOps - Filter out two-address use operands. Return
995/// true if it finds any issue with the operands that ought to prevent
996/// folding.
997static bool FilterFoldedOps(MachineInstr *MI,
998 SmallVector<unsigned, 2> &Ops,
999 unsigned &MRInfo,
1000 SmallVector<unsigned, 2> &FoldOps) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001001 MRInfo = 0;
Evan Chengaee4af62007-12-02 08:30:39 +00001002 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1003 unsigned OpIdx = Ops[i];
Evan Chengd70dbb52008-02-22 09:24:50 +00001004 MachineOperand &MO = MI->getOperand(OpIdx);
Evan Chengaee4af62007-12-02 08:30:39 +00001005 // FIXME: fold subreg use.
Evan Chengd70dbb52008-02-22 09:24:50 +00001006 if (MO.getSubReg())
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001007 return true;
Evan Chengd70dbb52008-02-22 09:24:50 +00001008 if (MO.isDef())
Evan Chengaee4af62007-12-02 08:30:39 +00001009 MRInfo |= (unsigned)VirtRegMap::isMod;
1010 else {
1011 // Filter out two-address use operand(s).
Evan Chenga24752f2009-03-19 20:30:06 +00001012 if (MI->isRegTiedToDefOperand(OpIdx)) {
Evan Chengaee4af62007-12-02 08:30:39 +00001013 MRInfo = VirtRegMap::isModRef;
1014 continue;
1015 }
1016 MRInfo |= (unsigned)VirtRegMap::isRef;
1017 }
1018 FoldOps.push_back(OpIdx);
Evan Chenge62f97c2007-12-01 02:07:52 +00001019 }
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001020 return false;
1021}
1022
1023
1024/// tryFoldMemoryOperand - Attempts to fold either a spill / restore from
1025/// slot / to reg or any rematerialized load into ith operand of specified
1026/// MI. If it is successul, MI is updated with the newly created MI and
1027/// returns true.
1028bool LiveIntervals::tryFoldMemoryOperand(MachineInstr* &MI,
1029 VirtRegMap &vrm, MachineInstr *DefMI,
Lang Hames233a60e2009-11-03 23:52:08 +00001030 SlotIndex InstrIdx,
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001031 SmallVector<unsigned, 2> &Ops,
1032 bool isSS, int Slot, unsigned Reg) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001033 // If it is an implicit def instruction, just delete it.
Evan Cheng20ccded2008-03-15 00:19:36 +00001034 if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001035 RemoveMachineInstrFromMaps(MI);
1036 vrm.RemoveMachineInstrFromMaps(MI);
1037 MI->eraseFromParent();
1038 ++numFolds;
1039 return true;
1040 }
1041
1042 // Filter the list of operand indexes that are to be folded. Abort if
1043 // any operand will prevent folding.
1044 unsigned MRInfo = 0;
1045 SmallVector<unsigned, 2> FoldOps;
1046 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1047 return false;
Evan Chenge62f97c2007-12-01 02:07:52 +00001048
Evan Cheng427f4c12008-03-31 23:19:51 +00001049 // The only time it's safe to fold into a two address instruction is when
1050 // it's folding reload and spill from / into a spill stack slot.
1051 if (DefMI && (MRInfo & VirtRegMap::isMod))
Evan Cheng249ded32008-02-23 03:38:34 +00001052 return false;
1053
Evan Chengf2f8c2a2008-02-08 22:05:27 +00001054 MachineInstr *fmi = isSS ? tii_->foldMemoryOperand(*mf_, MI, FoldOps, Slot)
1055 : tii_->foldMemoryOperand(*mf_, MI, FoldOps, DefMI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001056 if (fmi) {
Evan Chengd3653122008-02-27 03:04:06 +00001057 // Remember this instruction uses the spill slot.
1058 if (isSS) vrm.addSpillSlotUse(Slot, fmi);
1059
Evan Chengf2fbca62007-11-12 06:35:08 +00001060 // Attempt to fold the memory reference into the instruction. If
1061 // we can do this, we don't need to insert spill code.
Evan Chengf2fbca62007-11-12 06:35:08 +00001062 MachineBasicBlock &MBB = *MI->getParent();
Evan Cheng84802932008-01-10 08:24:38 +00001063 if (isSS && !mf_->getFrameInfo()->isImmutableObjectIndex(Slot))
Evan Chengaee4af62007-12-02 08:30:39 +00001064 vrm.virtFolded(Reg, MI, fmi, (VirtRegMap::ModRef)MRInfo);
Evan Cheng81a03822007-11-17 00:40:40 +00001065 vrm.transferSpillPts(MI, fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001066 vrm.transferRestorePts(MI, fmi);
Evan Chengc1f53c72008-03-11 21:34:46 +00001067 vrm.transferEmergencySpills(MI, fmi);
Lang Hames233a60e2009-11-03 23:52:08 +00001068 ReplaceMachineInstrInMaps(MI, fmi);
Evan Chengf2fbca62007-11-12 06:35:08 +00001069 MI = MBB.insert(MBB.erase(MI), fmi);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001070 ++numFolds;
Evan Chengf2fbca62007-11-12 06:35:08 +00001071 return true;
1072 }
1073 return false;
1074}
1075
Evan Cheng018f9b02007-12-05 03:22:34 +00001076/// canFoldMemoryOperand - Returns true if the specified load / store
1077/// folding is possible.
1078bool LiveIntervals::canFoldMemoryOperand(MachineInstr *MI,
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001079 SmallVector<unsigned, 2> &Ops,
Evan Cheng3c75ba82008-04-01 21:37:32 +00001080 bool ReMat) const {
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001081 // Filter the list of operand indexes that are to be folded. Abort if
1082 // any operand will prevent folding.
1083 unsigned MRInfo = 0;
Evan Cheng018f9b02007-12-05 03:22:34 +00001084 SmallVector<unsigned, 2> FoldOps;
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001085 if (FilterFoldedOps(MI, Ops, MRInfo, FoldOps))
1086 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001087
Evan Cheng3c75ba82008-04-01 21:37:32 +00001088 // It's only legal to remat for a use, not a def.
1089 if (ReMat && (MRInfo & VirtRegMap::isMod))
Evan Cheng79a0c1e2008-02-25 08:50:41 +00001090 return false;
Evan Cheng018f9b02007-12-05 03:22:34 +00001091
Evan Chengd70dbb52008-02-22 09:24:50 +00001092 return tii_->canFoldMemoryOperand(MI, FoldOps);
1093}
1094
Evan Cheng81a03822007-11-17 00:40:40 +00001095bool LiveIntervals::intervalIsInOneMBB(const LiveInterval &li) const {
Lang Hames233a60e2009-11-03 23:52:08 +00001096 LiveInterval::Ranges::const_iterator itr = li.ranges.begin();
1097
1098 MachineBasicBlock *mbb = indexes_->getMBBCoveringRange(itr->start, itr->end);
1099
1100 if (mbb == 0)
1101 return false;
1102
1103 for (++itr; itr != li.ranges.end(); ++itr) {
1104 MachineBasicBlock *mbb2 =
1105 indexes_->getMBBCoveringRange(itr->start, itr->end);
1106
1107 if (mbb2 != mbb)
Evan Cheng81a03822007-11-17 00:40:40 +00001108 return false;
1109 }
Lang Hames233a60e2009-11-03 23:52:08 +00001110
Evan Cheng81a03822007-11-17 00:40:40 +00001111 return true;
1112}
1113
Evan Chengd70dbb52008-02-22 09:24:50 +00001114/// rewriteImplicitOps - Rewrite implicit use operands of MI (i.e. uses of
1115/// interval on to-be re-materialized operands of MI) with new register.
1116void LiveIntervals::rewriteImplicitOps(const LiveInterval &li,
1117 MachineInstr *MI, unsigned NewVReg,
1118 VirtRegMap &vrm) {
1119 // There is an implicit use. That means one of the other operand is
1120 // being remat'ed and the remat'ed instruction has li.reg as an
1121 // use operand. Make sure we rewrite that as well.
1122 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1123 MachineOperand &MO = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001124 if (!MO.isReg())
Evan Chengd70dbb52008-02-22 09:24:50 +00001125 continue;
1126 unsigned Reg = MO.getReg();
1127 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
1128 continue;
1129 if (!vrm.isReMaterialized(Reg))
1130 continue;
1131 MachineInstr *ReMatMI = vrm.getReMaterializedMI(Reg);
Evan Cheng6130f662008-03-05 00:59:57 +00001132 MachineOperand *UseMO = ReMatMI->findRegisterUseOperand(li.reg);
1133 if (UseMO)
1134 UseMO->setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001135 }
1136}
1137
Evan Chengf2fbca62007-11-12 06:35:08 +00001138/// rewriteInstructionForSpills, rewriteInstructionsForSpills - Helper functions
1139/// for addIntervalsForSpills to rewrite uses / defs for the given live range.
Evan Cheng018f9b02007-12-05 03:22:34 +00001140bool LiveIntervals::
Evan Chengd70dbb52008-02-22 09:24:50 +00001141rewriteInstructionForSpills(const LiveInterval &li, const VNInfo *VNI,
Lang Hames233a60e2009-11-03 23:52:08 +00001142 bool TrySplit, SlotIndex index, SlotIndex end,
Lang Hames86511252009-09-04 20:41:11 +00001143 MachineInstr *MI,
Evan Cheng81a03822007-11-17 00:40:40 +00001144 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001145 unsigned Slot, int LdSlot,
1146 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001147 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001148 const TargetRegisterClass* rc,
1149 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001150 const MachineLoopInfo *loopInfo,
Evan Cheng313d4b82008-02-23 00:33:04 +00001151 unsigned &NewVReg, unsigned ImpUse, bool &HasDef, bool &HasUse,
Owen Anderson28998312008-08-13 22:28:50 +00001152 DenseMap<unsigned,unsigned> &MBBVRegsMap,
Evan Chengc781a242009-05-03 18:32:42 +00001153 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001154 bool CanFold = false;
Evan Chengf2fbca62007-11-12 06:35:08 +00001155 RestartInstruction:
1156 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1157 MachineOperand& mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001158 if (!mop.isReg())
Evan Chengf2fbca62007-11-12 06:35:08 +00001159 continue;
1160 unsigned Reg = mop.getReg();
1161 unsigned RegI = Reg;
Dan Gohman6f0d0242008-02-10 18:45:23 +00001162 if (Reg == 0 || TargetRegisterInfo::isPhysicalRegister(Reg))
Evan Chengf2fbca62007-11-12 06:35:08 +00001163 continue;
Evan Chengf2fbca62007-11-12 06:35:08 +00001164 if (Reg != li.reg)
1165 continue;
1166
1167 bool TryFold = !DefIsReMat;
Evan Chengcb3c3302007-11-29 23:02:50 +00001168 bool FoldSS = true; // Default behavior unless it's a remat.
Evan Chengf2fbca62007-11-12 06:35:08 +00001169 int FoldSlot = Slot;
1170 if (DefIsReMat) {
1171 // If this is the rematerializable definition MI itself and
1172 // all of its uses are rematerialized, simply delete it.
Evan Cheng81a03822007-11-17 00:40:40 +00001173 if (MI == ReMatOrigDefMI && CanDelete) {
Bill Wendling8e6179f2009-08-22 20:18:03 +00001174 DEBUG(errs() << "\t\t\t\tErasing re-materlizable def: "
1175 << MI << '\n');
Evan Chengf2fbca62007-11-12 06:35:08 +00001176 RemoveMachineInstrFromMaps(MI);
Evan Chengcada2452007-11-28 01:28:46 +00001177 vrm.RemoveMachineInstrFromMaps(MI);
Evan Chengf2fbca62007-11-12 06:35:08 +00001178 MI->eraseFromParent();
1179 break;
1180 }
1181
1182 // If def for this use can't be rematerialized, then try folding.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001183 // If def is rematerializable and it's a load, also try folding.
Evan Chengcb3c3302007-11-29 23:02:50 +00001184 TryFold = !ReMatDefMI || (ReMatDefMI && (MI == ReMatOrigDefMI || isLoad));
Evan Chengf2fbca62007-11-12 06:35:08 +00001185 if (isLoad) {
1186 // Try fold loads (from stack slot, constant pool, etc.) into uses.
1187 FoldSS = isLoadSS;
1188 FoldSlot = LdSlot;
1189 }
1190 }
1191
Evan Chengf2fbca62007-11-12 06:35:08 +00001192 // Scan all of the operands of this instruction rewriting operands
1193 // to use NewVReg instead of li.reg as appropriate. We do this for
1194 // two reasons:
1195 //
1196 // 1. If the instr reads the same spilled vreg multiple times, we
1197 // want to reuse the NewVReg.
1198 // 2. If the instr is a two-addr instruction, we are required to
1199 // keep the src/dst regs pinned.
1200 //
1201 // Keep track of whether we replace a use and/or def so that we can
1202 // create the spill interval with the appropriate range.
Evan Chengcddbb832007-11-30 21:23:43 +00001203
Evan Cheng81a03822007-11-17 00:40:40 +00001204 HasUse = mop.isUse();
1205 HasDef = mop.isDef();
Evan Chengaee4af62007-12-02 08:30:39 +00001206 SmallVector<unsigned, 2> Ops;
1207 Ops.push_back(i);
Evan Chengf2fbca62007-11-12 06:35:08 +00001208 for (unsigned j = i+1, e = MI->getNumOperands(); j != e; ++j) {
Evan Chengaee4af62007-12-02 08:30:39 +00001209 const MachineOperand &MOj = MI->getOperand(j);
Dan Gohmand735b802008-10-03 15:45:36 +00001210 if (!MOj.isReg())
Evan Chengf2fbca62007-11-12 06:35:08 +00001211 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001212 unsigned RegJ = MOj.getReg();
Dan Gohman6f0d0242008-02-10 18:45:23 +00001213 if (RegJ == 0 || TargetRegisterInfo::isPhysicalRegister(RegJ))
Evan Chengf2fbca62007-11-12 06:35:08 +00001214 continue;
1215 if (RegJ == RegI) {
Evan Chengaee4af62007-12-02 08:30:39 +00001216 Ops.push_back(j);
Evan Chengd129d732009-07-17 19:43:40 +00001217 if (!MOj.isUndef()) {
1218 HasUse |= MOj.isUse();
1219 HasDef |= MOj.isDef();
1220 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001221 }
1222 }
1223
David Greene26b86a02008-10-27 17:38:59 +00001224 // Create a new virtual register for the spill interval.
1225 // Create the new register now so we can map the fold instruction
1226 // to the new register so when it is unfolded we get the correct
1227 // answer.
1228 bool CreatedNewVReg = false;
1229 if (NewVReg == 0) {
1230 NewVReg = mri_->createVirtualRegister(rc);
1231 vrm.grow();
1232 CreatedNewVReg = true;
1233 }
1234
Evan Cheng9c3c2212008-06-06 07:54:39 +00001235 if (!TryFold)
1236 CanFold = false;
1237 else {
Evan Cheng018f9b02007-12-05 03:22:34 +00001238 // Do not fold load / store here if we are splitting. We'll find an
1239 // optimal point to insert a load / store later.
1240 if (!TrySplit) {
1241 if (tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
David Greene26b86a02008-10-27 17:38:59 +00001242 Ops, FoldSS, FoldSlot, NewVReg)) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001243 // Folding the load/store can completely change the instruction in
1244 // unpredictable ways, rescan it from the beginning.
David Greene26b86a02008-10-27 17:38:59 +00001245
1246 if (FoldSS) {
1247 // We need to give the new vreg the same stack slot as the
1248 // spilled interval.
1249 vrm.assignVirt2StackSlot(NewVReg, FoldSlot);
1250 }
1251
Evan Cheng018f9b02007-12-05 03:22:34 +00001252 HasUse = false;
1253 HasDef = false;
1254 CanFold = false;
Evan Chengc781a242009-05-03 18:32:42 +00001255 if (isNotInMIMap(MI))
Evan Cheng7e073ba2008-04-09 20:57:25 +00001256 break;
Evan Cheng018f9b02007-12-05 03:22:34 +00001257 goto RestartInstruction;
1258 }
1259 } else {
Evan Cheng9c3c2212008-06-06 07:54:39 +00001260 // We'll try to fold it later if it's profitable.
Evan Cheng3c75ba82008-04-01 21:37:32 +00001261 CanFold = canFoldMemoryOperand(MI, Ops, DefIsReMat);
Evan Cheng018f9b02007-12-05 03:22:34 +00001262 }
Evan Cheng9c3c2212008-06-06 07:54:39 +00001263 }
Evan Chengcddbb832007-11-30 21:23:43 +00001264
Evan Chengcddbb832007-11-30 21:23:43 +00001265 mop.setReg(NewVReg);
Evan Chengd70dbb52008-02-22 09:24:50 +00001266 if (mop.isImplicit())
1267 rewriteImplicitOps(li, MI, NewVReg, vrm);
Evan Chengcddbb832007-11-30 21:23:43 +00001268
1269 // Reuse NewVReg for other reads.
Evan Chengd70dbb52008-02-22 09:24:50 +00001270 for (unsigned j = 0, e = Ops.size(); j != e; ++j) {
1271 MachineOperand &mopj = MI->getOperand(Ops[j]);
1272 mopj.setReg(NewVReg);
1273 if (mopj.isImplicit())
1274 rewriteImplicitOps(li, MI, NewVReg, vrm);
1275 }
Evan Chengcddbb832007-11-30 21:23:43 +00001276
Evan Cheng81a03822007-11-17 00:40:40 +00001277 if (CreatedNewVReg) {
1278 if (DefIsReMat) {
Evan Cheng37844532009-07-16 09:20:10 +00001279 vrm.setVirtIsReMaterialized(NewVReg, ReMatDefMI);
Evan Chengd70dbb52008-02-22 09:24:50 +00001280 if (ReMatIds[VNI->id] == VirtRegMap::MAX_STACK_SLOT) {
Evan Cheng81a03822007-11-17 00:40:40 +00001281 // Each valnum may have its own remat id.
Evan Chengd70dbb52008-02-22 09:24:50 +00001282 ReMatIds[VNI->id] = vrm.assignVirtReMatId(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001283 } else {
Evan Chengd70dbb52008-02-22 09:24:50 +00001284 vrm.assignVirtReMatId(NewVReg, ReMatIds[VNI->id]);
Evan Cheng81a03822007-11-17 00:40:40 +00001285 }
1286 if (!CanDelete || (HasUse && HasDef)) {
1287 // If this is a two-addr instruction then its use operands are
1288 // rematerializable but its def is not. It should be assigned a
1289 // stack slot.
1290 vrm.assignVirt2StackSlot(NewVReg, Slot);
1291 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001292 } else {
Evan Chengf2fbca62007-11-12 06:35:08 +00001293 vrm.assignVirt2StackSlot(NewVReg, Slot);
1294 }
Evan Chengcb3c3302007-11-29 23:02:50 +00001295 } else if (HasUse && HasDef &&
1296 vrm.getStackSlot(NewVReg) == VirtRegMap::NO_STACK_SLOT) {
1297 // If this interval hasn't been assigned a stack slot (because earlier
1298 // def is a deleted remat def), do it now.
1299 assert(Slot != VirtRegMap::NO_STACK_SLOT);
1300 vrm.assignVirt2StackSlot(NewVReg, Slot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001301 }
1302
Evan Cheng313d4b82008-02-23 00:33:04 +00001303 // Re-matting an instruction with virtual register use. Add the
1304 // register as an implicit use on the use MI.
1305 if (DefIsReMat && ImpUse)
1306 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
1307
Evan Cheng5b69eba2009-04-21 22:46:52 +00001308 // Create a new register interval for this spill / remat.
Evan Chengf2fbca62007-11-12 06:35:08 +00001309 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001310 if (CreatedNewVReg) {
1311 NewLIs.push_back(&nI);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001312 MBBVRegsMap.insert(std::make_pair(MI->getParent()->getNumber(), NewVReg));
Evan Cheng81a03822007-11-17 00:40:40 +00001313 if (TrySplit)
1314 vrm.setIsSplitFromReg(NewVReg, li.reg);
1315 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001316
1317 if (HasUse) {
Evan Cheng81a03822007-11-17 00:40:40 +00001318 if (CreatedNewVReg) {
Lang Hames233a60e2009-11-03 23:52:08 +00001319 LiveRange LR(index.getLoadIndex(), index.getDefIndex(),
1320 nI.getNextValue(SlotIndex(), 0, false, VNInfoAllocator));
Bill Wendling8e6179f2009-08-22 20:18:03 +00001321 DEBUG(errs() << " +" << LR);
Evan Cheng81a03822007-11-17 00:40:40 +00001322 nI.addRange(LR);
1323 } else {
1324 // Extend the split live interval to this def / use.
Lang Hames233a60e2009-11-03 23:52:08 +00001325 SlotIndex End = index.getDefIndex();
Evan Cheng81a03822007-11-17 00:40:40 +00001326 LiveRange LR(nI.ranges[nI.ranges.size()-1].end, End,
1327 nI.getValNumInfo(nI.getNumValNums()-1));
Bill Wendling8e6179f2009-08-22 20:18:03 +00001328 DEBUG(errs() << " +" << LR);
Evan Cheng81a03822007-11-17 00:40:40 +00001329 nI.addRange(LR);
1330 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001331 }
1332 if (HasDef) {
Lang Hames233a60e2009-11-03 23:52:08 +00001333 LiveRange LR(index.getDefIndex(), index.getStoreIndex(),
1334 nI.getNextValue(SlotIndex(), 0, false, VNInfoAllocator));
Bill Wendling8e6179f2009-08-22 20:18:03 +00001335 DEBUG(errs() << " +" << LR);
Evan Chengf2fbca62007-11-12 06:35:08 +00001336 nI.addRange(LR);
1337 }
Evan Cheng81a03822007-11-17 00:40:40 +00001338
Bill Wendling8e6179f2009-08-22 20:18:03 +00001339 DEBUG({
1340 errs() << "\t\t\t\tAdded new interval: ";
1341 nI.print(errs(), tri_);
1342 errs() << '\n';
1343 });
Evan Chengf2fbca62007-11-12 06:35:08 +00001344 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001345 return CanFold;
Evan Chengf2fbca62007-11-12 06:35:08 +00001346}
Evan Cheng81a03822007-11-17 00:40:40 +00001347bool LiveIntervals::anyKillInMBBAfterIdx(const LiveInterval &li,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001348 const VNInfo *VNI,
Lang Hames86511252009-09-04 20:41:11 +00001349 MachineBasicBlock *MBB,
Lang Hames233a60e2009-11-03 23:52:08 +00001350 SlotIndex Idx) const {
1351 SlotIndex End = getMBBEndIdx(MBB);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001352 for (unsigned j = 0, ee = VNI->kills.size(); j != ee; ++j) {
Lang Hames233a60e2009-11-03 23:52:08 +00001353 if (VNI->kills[j].isPHI())
Lang Hamesffd13262009-07-09 03:57:02 +00001354 continue;
1355
Lang Hames233a60e2009-11-03 23:52:08 +00001356 SlotIndex KillIdx = VNI->kills[j];
Evan Cheng0cbb1162007-11-29 01:06:25 +00001357 if (KillIdx > Idx && KillIdx < End)
1358 return true;
Evan Cheng81a03822007-11-17 00:40:40 +00001359 }
1360 return false;
1361}
1362
Evan Cheng063284c2008-02-21 00:34:19 +00001363/// RewriteInfo - Keep track of machine instrs that will be rewritten
1364/// during spilling.
Dan Gohman844731a2008-05-13 00:00:25 +00001365namespace {
1366 struct RewriteInfo {
Lang Hames233a60e2009-11-03 23:52:08 +00001367 SlotIndex Index;
Dan Gohman844731a2008-05-13 00:00:25 +00001368 MachineInstr *MI;
1369 bool HasUse;
1370 bool HasDef;
Lang Hames233a60e2009-11-03 23:52:08 +00001371 RewriteInfo(SlotIndex i, MachineInstr *mi, bool u, bool d)
Dan Gohman844731a2008-05-13 00:00:25 +00001372 : Index(i), MI(mi), HasUse(u), HasDef(d) {}
1373 };
Evan Cheng063284c2008-02-21 00:34:19 +00001374
Dan Gohman844731a2008-05-13 00:00:25 +00001375 struct RewriteInfoCompare {
1376 bool operator()(const RewriteInfo &LHS, const RewriteInfo &RHS) const {
1377 return LHS.Index < RHS.Index;
1378 }
1379 };
1380}
Evan Cheng063284c2008-02-21 00:34:19 +00001381
Evan Chengf2fbca62007-11-12 06:35:08 +00001382void LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001383rewriteInstructionsForSpills(const LiveInterval &li, bool TrySplit,
Evan Chengf2fbca62007-11-12 06:35:08 +00001384 LiveInterval::Ranges::const_iterator &I,
Evan Cheng81a03822007-11-17 00:40:40 +00001385 MachineInstr *ReMatOrigDefMI, MachineInstr *ReMatDefMI,
Evan Chengf2fbca62007-11-12 06:35:08 +00001386 unsigned Slot, int LdSlot,
1387 bool isLoad, bool isLoadSS, bool DefIsReMat, bool CanDelete,
Evan Chengd70dbb52008-02-22 09:24:50 +00001388 VirtRegMap &vrm,
Evan Chengf2fbca62007-11-12 06:35:08 +00001389 const TargetRegisterClass* rc,
1390 SmallVector<int, 4> &ReMatIds,
Evan Cheng22f07ff2007-12-11 02:09:15 +00001391 const MachineLoopInfo *loopInfo,
Evan Cheng81a03822007-11-17 00:40:40 +00001392 BitVector &SpillMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001393 DenseMap<unsigned, std::vector<SRInfo> > &SpillIdxes,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001394 BitVector &RestoreMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001395 DenseMap<unsigned, std::vector<SRInfo> > &RestoreIdxes,
1396 DenseMap<unsigned,unsigned> &MBBVRegsMap,
Evan Chengc781a242009-05-03 18:32:42 +00001397 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001398 bool AllCanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001399 unsigned NewVReg = 0;
Lang Hames233a60e2009-11-03 23:52:08 +00001400 SlotIndex start = I->start.getBaseIndex();
1401 SlotIndex end = I->end.getPrevSlot().getBaseIndex().getNextIndex();
Evan Chengf2fbca62007-11-12 06:35:08 +00001402
Evan Cheng063284c2008-02-21 00:34:19 +00001403 // First collect all the def / use in this live range that will be rewritten.
Evan Cheng7e073ba2008-04-09 20:57:25 +00001404 // Make sure they are sorted according to instruction index.
Evan Cheng063284c2008-02-21 00:34:19 +00001405 std::vector<RewriteInfo> RewriteMIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001406 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1407 re = mri_->reg_end(); ri != re; ) {
Evan Cheng419852c2008-04-03 16:39:43 +00001408 MachineInstr *MI = &*ri;
Evan Cheng063284c2008-02-21 00:34:19 +00001409 MachineOperand &O = ri.getOperand();
1410 ++ri;
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001411 assert(!O.isImplicit() && "Spilling register that's used as implicit use?");
Lang Hames233a60e2009-11-03 23:52:08 +00001412 SlotIndex index = getInstructionIndex(MI);
Evan Cheng063284c2008-02-21 00:34:19 +00001413 if (index < start || index >= end)
1414 continue;
Evan Chengd129d732009-07-17 19:43:40 +00001415
1416 if (O.isUndef())
Evan Cheng79a796c2008-07-12 01:56:02 +00001417 // Must be defined by an implicit def. It should not be spilled. Note,
1418 // this is for correctness reason. e.g.
1419 // 8 %reg1024<def> = IMPLICIT_DEF
1420 // 12 %reg1024<def> = INSERT_SUBREG %reg1024<kill>, %reg1025, 2
1421 // The live range [12, 14) are not part of the r1024 live interval since
1422 // it's defined by an implicit def. It will not conflicts with live
1423 // interval of r1025. Now suppose both registers are spilled, you can
Evan Chengb9890ae2008-07-12 02:22:07 +00001424 // easily see a situation where both registers are reloaded before
Evan Cheng79a796c2008-07-12 01:56:02 +00001425 // the INSERT_SUBREG and both target registers that would overlap.
1426 continue;
Evan Cheng063284c2008-02-21 00:34:19 +00001427 RewriteMIs.push_back(RewriteInfo(index, MI, O.isUse(), O.isDef()));
1428 }
1429 std::sort(RewriteMIs.begin(), RewriteMIs.end(), RewriteInfoCompare());
1430
Evan Cheng313d4b82008-02-23 00:33:04 +00001431 unsigned ImpUse = DefIsReMat ? getReMatImplicitUse(li, ReMatDefMI) : 0;
Evan Cheng063284c2008-02-21 00:34:19 +00001432 // Now rewrite the defs and uses.
1433 for (unsigned i = 0, e = RewriteMIs.size(); i != e; ) {
1434 RewriteInfo &rwi = RewriteMIs[i];
1435 ++i;
Lang Hames233a60e2009-11-03 23:52:08 +00001436 SlotIndex index = rwi.Index;
Evan Cheng063284c2008-02-21 00:34:19 +00001437 bool MIHasUse = rwi.HasUse;
1438 bool MIHasDef = rwi.HasDef;
1439 MachineInstr *MI = rwi.MI;
1440 // If MI def and/or use the same register multiple times, then there
1441 // are multiple entries.
Evan Cheng313d4b82008-02-23 00:33:04 +00001442 unsigned NumUses = MIHasUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001443 while (i != e && RewriteMIs[i].MI == MI) {
1444 assert(RewriteMIs[i].Index == index);
Evan Cheng313d4b82008-02-23 00:33:04 +00001445 bool isUse = RewriteMIs[i].HasUse;
1446 if (isUse) ++NumUses;
1447 MIHasUse |= isUse;
Evan Cheng063284c2008-02-21 00:34:19 +00001448 MIHasDef |= RewriteMIs[i].HasDef;
1449 ++i;
1450 }
Evan Cheng81a03822007-11-17 00:40:40 +00001451 MachineBasicBlock *MBB = MI->getParent();
Evan Cheng313d4b82008-02-23 00:33:04 +00001452
Evan Cheng0a891ed2008-05-23 23:00:04 +00001453 if (ImpUse && MI != ReMatDefMI) {
Evan Cheng313d4b82008-02-23 00:33:04 +00001454 // Re-matting an instruction with virtual register use. Update the
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001455 // register interval's spill weight to HUGE_VALF to prevent it from
1456 // being spilled.
Evan Cheng313d4b82008-02-23 00:33:04 +00001457 LiveInterval &ImpLi = getInterval(ImpUse);
Evan Cheng24d2f8a2008-03-31 07:53:30 +00001458 ImpLi.weight = HUGE_VALF;
Evan Cheng313d4b82008-02-23 00:33:04 +00001459 }
1460
Evan Cheng063284c2008-02-21 00:34:19 +00001461 unsigned MBBId = MBB->getNumber();
Evan Cheng018f9b02007-12-05 03:22:34 +00001462 unsigned ThisVReg = 0;
Evan Cheng70306f82007-12-03 09:58:48 +00001463 if (TrySplit) {
Owen Anderson28998312008-08-13 22:28:50 +00001464 DenseMap<unsigned,unsigned>::iterator NVI = MBBVRegsMap.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001465 if (NVI != MBBVRegsMap.end()) {
Evan Cheng018f9b02007-12-05 03:22:34 +00001466 ThisVReg = NVI->second;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001467 // One common case:
1468 // x = use
1469 // ...
1470 // ...
1471 // def = ...
1472 // = use
1473 // It's better to start a new interval to avoid artifically
1474 // extend the new interval.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001475 if (MIHasDef && !MIHasUse) {
1476 MBBVRegsMap.erase(MBB->getNumber());
Evan Cheng018f9b02007-12-05 03:22:34 +00001477 ThisVReg = 0;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001478 }
1479 }
Evan Chengcada2452007-11-28 01:28:46 +00001480 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001481
1482 bool IsNew = ThisVReg == 0;
1483 if (IsNew) {
1484 // This ends the previous live interval. If all of its def / use
1485 // can be folded, give it a low spill weight.
1486 if (NewVReg && TrySplit && AllCanFold) {
1487 LiveInterval &nI = getOrCreateInterval(NewVReg);
1488 nI.weight /= 10.0F;
1489 }
1490 AllCanFold = true;
1491 }
1492 NewVReg = ThisVReg;
1493
Evan Cheng81a03822007-11-17 00:40:40 +00001494 bool HasDef = false;
1495 bool HasUse = false;
Evan Chengd70dbb52008-02-22 09:24:50 +00001496 bool CanFold = rewriteInstructionForSpills(li, I->valno, TrySplit,
Evan Cheng9c3c2212008-06-06 07:54:39 +00001497 index, end, MI, ReMatOrigDefMI, ReMatDefMI,
1498 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
1499 CanDelete, vrm, rc, ReMatIds, loopInfo, NewVReg,
Evan Chengc781a242009-05-03 18:32:42 +00001500 ImpUse, HasDef, HasUse, MBBVRegsMap, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001501 if (!HasDef && !HasUse)
1502 continue;
1503
Evan Cheng018f9b02007-12-05 03:22:34 +00001504 AllCanFold &= CanFold;
1505
Evan Cheng81a03822007-11-17 00:40:40 +00001506 // Update weight of spill interval.
1507 LiveInterval &nI = getOrCreateInterval(NewVReg);
Evan Cheng70306f82007-12-03 09:58:48 +00001508 if (!TrySplit) {
Evan Cheng81a03822007-11-17 00:40:40 +00001509 // The spill weight is now infinity as it cannot be spilled again.
1510 nI.weight = HUGE_VALF;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001511 continue;
Evan Cheng81a03822007-11-17 00:40:40 +00001512 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001513
1514 // Keep track of the last def and first use in each MBB.
Evan Cheng0cbb1162007-11-29 01:06:25 +00001515 if (HasDef) {
1516 if (MI != ReMatOrigDefMI || !CanDelete) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001517 bool HasKill = false;
1518 if (!HasUse)
Lang Hames233a60e2009-11-03 23:52:08 +00001519 HasKill = anyKillInMBBAfterIdx(li, I->valno, MBB, index.getDefIndex());
Evan Cheng0cbb1162007-11-29 01:06:25 +00001520 else {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001521 // If this is a two-address code, then this index starts a new VNInfo.
Lang Hames233a60e2009-11-03 23:52:08 +00001522 const VNInfo *VNI = li.findDefinedVNInfoForRegInt(index.getDefIndex());
Evan Cheng0cbb1162007-11-29 01:06:25 +00001523 if (VNI)
Lang Hames233a60e2009-11-03 23:52:08 +00001524 HasKill = anyKillInMBBAfterIdx(li, VNI, MBB, index.getDefIndex());
Evan Cheng0cbb1162007-11-29 01:06:25 +00001525 }
Owen Anderson28998312008-08-13 22:28:50 +00001526 DenseMap<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Chenge3110d02007-12-01 04:42:39 +00001527 SpillIdxes.find(MBBId);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001528 if (!HasKill) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001529 if (SII == SpillIdxes.end()) {
1530 std::vector<SRInfo> S;
1531 S.push_back(SRInfo(index, NewVReg, true));
1532 SpillIdxes.insert(std::make_pair(MBBId, S));
1533 } else if (SII->second.back().vreg != NewVReg) {
1534 SII->second.push_back(SRInfo(index, NewVReg, true));
Lang Hames86511252009-09-04 20:41:11 +00001535 } else if (index > SII->second.back().index) {
Evan Cheng0cbb1162007-11-29 01:06:25 +00001536 // If there is an earlier def and this is a two-address
1537 // instruction, then it's not possible to fold the store (which
1538 // would also fold the load).
Evan Cheng1953d0c2007-11-29 10:12:14 +00001539 SRInfo &Info = SII->second.back();
1540 Info.index = index;
1541 Info.canFold = !HasUse;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001542 }
1543 SpillMBBs.set(MBBId);
Evan Chenge3110d02007-12-01 04:42:39 +00001544 } else if (SII != SpillIdxes.end() &&
1545 SII->second.back().vreg == NewVReg &&
Lang Hames86511252009-09-04 20:41:11 +00001546 index > SII->second.back().index) {
Evan Chenge3110d02007-12-01 04:42:39 +00001547 // There is an earlier def that's not killed (must be two-address).
1548 // The spill is no longer needed.
1549 SII->second.pop_back();
1550 if (SII->second.empty()) {
1551 SpillIdxes.erase(MBBId);
1552 SpillMBBs.reset(MBBId);
1553 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001554 }
1555 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001556 }
1557
1558 if (HasUse) {
Owen Anderson28998312008-08-13 22:28:50 +00001559 DenseMap<unsigned, std::vector<SRInfo> >::iterator SII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001560 SpillIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001561 if (SII != SpillIdxes.end() &&
1562 SII->second.back().vreg == NewVReg &&
Lang Hames86511252009-09-04 20:41:11 +00001563 index > SII->second.back().index)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001564 // Use(s) following the last def, it's not safe to fold the spill.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001565 SII->second.back().canFold = false;
Owen Anderson28998312008-08-13 22:28:50 +00001566 DenseMap<unsigned, std::vector<SRInfo> >::iterator RII =
Evan Cheng0cbb1162007-11-29 01:06:25 +00001567 RestoreIdxes.find(MBBId);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001568 if (RII != RestoreIdxes.end() && RII->second.back().vreg == NewVReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001569 // If we are splitting live intervals, only fold if it's the first
1570 // use and there isn't another use later in the MBB.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001571 RII->second.back().canFold = false;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001572 else if (IsNew) {
1573 // Only need a reload if there isn't an earlier def / use.
Evan Cheng1953d0c2007-11-29 10:12:14 +00001574 if (RII == RestoreIdxes.end()) {
1575 std::vector<SRInfo> Infos;
1576 Infos.push_back(SRInfo(index, NewVReg, true));
1577 RestoreIdxes.insert(std::make_pair(MBBId, Infos));
1578 } else {
1579 RII->second.push_back(SRInfo(index, NewVReg, true));
1580 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001581 RestoreMBBs.set(MBBId);
1582 }
1583 }
1584
1585 // Update spill weight.
Evan Cheng22f07ff2007-12-11 02:09:15 +00001586 unsigned loopDepth = loopInfo->getLoopDepth(MBB);
Evan Chengc3417602008-06-21 06:45:54 +00001587 nI.weight += getSpillWeight(HasDef, HasUse, loopDepth);
Evan Chengf2fbca62007-11-12 06:35:08 +00001588 }
Evan Cheng018f9b02007-12-05 03:22:34 +00001589
1590 if (NewVReg && TrySplit && AllCanFold) {
1591 // If all of its def / use can be folded, give it a low spill weight.
1592 LiveInterval &nI = getOrCreateInterval(NewVReg);
1593 nI.weight /= 10.0F;
1594 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001595}
1596
Lang Hames233a60e2009-11-03 23:52:08 +00001597bool LiveIntervals::alsoFoldARestore(int Id, SlotIndex index,
Lang Hames86511252009-09-04 20:41:11 +00001598 unsigned vr, BitVector &RestoreMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001599 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001600 if (!RestoreMBBs[Id])
1601 return false;
1602 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1603 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1604 if (Restores[i].index == index &&
1605 Restores[i].vreg == vr &&
1606 Restores[i].canFold)
1607 return true;
1608 return false;
1609}
1610
Lang Hames233a60e2009-11-03 23:52:08 +00001611void LiveIntervals::eraseRestoreInfo(int Id, SlotIndex index,
Lang Hames86511252009-09-04 20:41:11 +00001612 unsigned vr, BitVector &RestoreMBBs,
Owen Anderson28998312008-08-13 22:28:50 +00001613 DenseMap<unsigned,std::vector<SRInfo> > &RestoreIdxes) {
Evan Cheng1953d0c2007-11-29 10:12:14 +00001614 if (!RestoreMBBs[Id])
1615 return;
1616 std::vector<SRInfo> &Restores = RestoreIdxes[Id];
1617 for (unsigned i = 0, e = Restores.size(); i != e; ++i)
1618 if (Restores[i].index == index && Restores[i].vreg)
Lang Hames233a60e2009-11-03 23:52:08 +00001619 Restores[i].index = SlotIndex();
Evan Cheng1953d0c2007-11-29 10:12:14 +00001620}
Evan Cheng81a03822007-11-17 00:40:40 +00001621
Evan Cheng4cce6b42008-04-11 17:53:36 +00001622/// handleSpilledImpDefs - Remove IMPLICIT_DEF instructions which are being
1623/// spilled and create empty intervals for their uses.
1624void
1625LiveIntervals::handleSpilledImpDefs(const LiveInterval &li, VirtRegMap &vrm,
1626 const TargetRegisterClass* rc,
1627 std::vector<LiveInterval*> &NewLIs) {
Evan Cheng419852c2008-04-03 16:39:43 +00001628 for (MachineRegisterInfo::reg_iterator ri = mri_->reg_begin(li.reg),
1629 re = mri_->reg_end(); ri != re; ) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001630 MachineOperand &O = ri.getOperand();
Evan Cheng419852c2008-04-03 16:39:43 +00001631 MachineInstr *MI = &*ri;
1632 ++ri;
Evan Cheng4cce6b42008-04-11 17:53:36 +00001633 if (O.isDef()) {
1634 assert(MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF &&
1635 "Register def was not rewritten?");
1636 RemoveMachineInstrFromMaps(MI);
1637 vrm.RemoveMachineInstrFromMaps(MI);
1638 MI->eraseFromParent();
1639 } else {
1640 // This must be an use of an implicit_def so it's not part of the live
1641 // interval. Create a new empty live interval for it.
1642 // FIXME: Can we simply erase some of the instructions? e.g. Stores?
1643 unsigned NewVReg = mri_->createVirtualRegister(rc);
1644 vrm.grow();
1645 vrm.setIsImplicitlyDefined(NewVReg);
1646 NewLIs.push_back(&getOrCreateInterval(NewVReg));
1647 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
1648 MachineOperand &MO = MI->getOperand(i);
Evan Cheng4784f1f2009-06-30 08:49:04 +00001649 if (MO.isReg() && MO.getReg() == li.reg) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001650 MO.setReg(NewVReg);
Evan Cheng4784f1f2009-06-30 08:49:04 +00001651 MO.setIsUndef();
Evan Cheng4784f1f2009-06-30 08:49:04 +00001652 }
Evan Cheng4cce6b42008-04-11 17:53:36 +00001653 }
1654 }
Evan Cheng419852c2008-04-03 16:39:43 +00001655 }
1656}
1657
Evan Chengf2fbca62007-11-12 06:35:08 +00001658std::vector<LiveInterval*> LiveIntervals::
Owen Andersond6664312008-08-18 18:05:32 +00001659addIntervalsForSpillsFast(const LiveInterval &li,
1660 const MachineLoopInfo *loopInfo,
Evan Chengc781a242009-05-03 18:32:42 +00001661 VirtRegMap &vrm) {
Owen Anderson17197312008-08-18 23:41:04 +00001662 unsigned slot = vrm.assignVirt2StackSlot(li.reg);
Owen Andersond6664312008-08-18 18:05:32 +00001663
1664 std::vector<LiveInterval*> added;
1665
1666 assert(li.weight != HUGE_VALF &&
1667 "attempt to spill already spilled interval!");
1668
Bill Wendling8e6179f2009-08-22 20:18:03 +00001669 DEBUG({
1670 errs() << "\t\t\t\tadding intervals for spills for interval: ";
1671 li.dump();
1672 errs() << '\n';
1673 });
Owen Andersond6664312008-08-18 18:05:32 +00001674
1675 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
1676
Owen Andersona41e47a2008-08-19 22:12:11 +00001677 MachineRegisterInfo::reg_iterator RI = mri_->reg_begin(li.reg);
1678 while (RI != mri_->reg_end()) {
1679 MachineInstr* MI = &*RI;
1680
1681 SmallVector<unsigned, 2> Indices;
1682 bool HasUse = false;
1683 bool HasDef = false;
1684
1685 for (unsigned i = 0; i != MI->getNumOperands(); ++i) {
1686 MachineOperand& mop = MI->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +00001687 if (!mop.isReg() || mop.getReg() != li.reg) continue;
Owen Andersona41e47a2008-08-19 22:12:11 +00001688
1689 HasUse |= MI->getOperand(i).isUse();
1690 HasDef |= MI->getOperand(i).isDef();
1691
1692 Indices.push_back(i);
1693 }
1694
1695 if (!tryFoldMemoryOperand(MI, vrm, NULL, getInstructionIndex(MI),
1696 Indices, true, slot, li.reg)) {
1697 unsigned NewVReg = mri_->createVirtualRegister(rc);
Owen Anderson9a032932008-08-18 21:20:32 +00001698 vrm.grow();
Owen Anderson17197312008-08-18 23:41:04 +00001699 vrm.assignVirt2StackSlot(NewVReg, slot);
1700
Owen Andersona41e47a2008-08-19 22:12:11 +00001701 // create a new register for this spill
1702 LiveInterval &nI = getOrCreateInterval(NewVReg);
Owen Andersond6664312008-08-18 18:05:32 +00001703
Owen Andersona41e47a2008-08-19 22:12:11 +00001704 // the spill weight is now infinity as it
1705 // cannot be spilled again
1706 nI.weight = HUGE_VALF;
1707
1708 // Rewrite register operands to use the new vreg.
1709 for (SmallVectorImpl<unsigned>::iterator I = Indices.begin(),
1710 E = Indices.end(); I != E; ++I) {
1711 MI->getOperand(*I).setReg(NewVReg);
1712
1713 if (MI->getOperand(*I).isUse())
1714 MI->getOperand(*I).setIsKill(true);
1715 }
1716
1717 // Fill in the new live interval.
Lang Hames233a60e2009-11-03 23:52:08 +00001718 SlotIndex index = getInstructionIndex(MI);
Owen Andersona41e47a2008-08-19 22:12:11 +00001719 if (HasUse) {
Lang Hames233a60e2009-11-03 23:52:08 +00001720 LiveRange LR(index.getLoadIndex(), index.getUseIndex(),
1721 nI.getNextValue(SlotIndex(), 0, false,
Lang Hames86511252009-09-04 20:41:11 +00001722 getVNInfoAllocator()));
Bill Wendling8e6179f2009-08-22 20:18:03 +00001723 DEBUG(errs() << " +" << LR);
Owen Andersona41e47a2008-08-19 22:12:11 +00001724 nI.addRange(LR);
1725 vrm.addRestorePoint(NewVReg, MI);
1726 }
1727 if (HasDef) {
Lang Hames233a60e2009-11-03 23:52:08 +00001728 LiveRange LR(index.getDefIndex(), index.getStoreIndex(),
1729 nI.getNextValue(SlotIndex(), 0, false,
Lang Hames86511252009-09-04 20:41:11 +00001730 getVNInfoAllocator()));
Bill Wendling8e6179f2009-08-22 20:18:03 +00001731 DEBUG(errs() << " +" << LR);
Owen Andersona41e47a2008-08-19 22:12:11 +00001732 nI.addRange(LR);
1733 vrm.addSpillPoint(NewVReg, true, MI);
1734 }
1735
Owen Anderson17197312008-08-18 23:41:04 +00001736 added.push_back(&nI);
Owen Anderson8dc2cbe2008-08-18 18:38:12 +00001737
Bill Wendling8e6179f2009-08-22 20:18:03 +00001738 DEBUG({
1739 errs() << "\t\t\t\tadded new interval: ";
1740 nI.dump();
1741 errs() << '\n';
1742 });
Owen Andersona41e47a2008-08-19 22:12:11 +00001743 }
Owen Anderson9a032932008-08-18 21:20:32 +00001744
Owen Anderson9a032932008-08-18 21:20:32 +00001745
Owen Andersona41e47a2008-08-19 22:12:11 +00001746 RI = mri_->reg_begin(li.reg);
Owen Andersond6664312008-08-18 18:05:32 +00001747 }
Owen Andersond6664312008-08-18 18:05:32 +00001748
1749 return added;
1750}
1751
1752std::vector<LiveInterval*> LiveIntervals::
Evan Cheng81a03822007-11-17 00:40:40 +00001753addIntervalsForSpills(const LiveInterval &li,
Evan Chengdc377862008-09-30 15:44:16 +00001754 SmallVectorImpl<LiveInterval*> &SpillIs,
Evan Chengc781a242009-05-03 18:32:42 +00001755 const MachineLoopInfo *loopInfo, VirtRegMap &vrm) {
Owen Andersonae339ba2008-08-19 00:17:30 +00001756
1757 if (EnableFastSpilling)
Evan Chengc781a242009-05-03 18:32:42 +00001758 return addIntervalsForSpillsFast(li, loopInfo, vrm);
Owen Andersonae339ba2008-08-19 00:17:30 +00001759
Evan Chengf2fbca62007-11-12 06:35:08 +00001760 assert(li.weight != HUGE_VALF &&
1761 "attempt to spill already spilled interval!");
1762
Bill Wendling8e6179f2009-08-22 20:18:03 +00001763 DEBUG({
1764 errs() << "\t\t\t\tadding intervals for spills for interval: ";
1765 li.print(errs(), tri_);
1766 errs() << '\n';
1767 });
Evan Chengf2fbca62007-11-12 06:35:08 +00001768
Evan Cheng72eeb942008-12-05 17:00:16 +00001769 // Each bit specify whether a spill is required in the MBB.
Evan Cheng81a03822007-11-17 00:40:40 +00001770 BitVector SpillMBBs(mf_->getNumBlockIDs());
Owen Anderson28998312008-08-13 22:28:50 +00001771 DenseMap<unsigned, std::vector<SRInfo> > SpillIdxes;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001772 BitVector RestoreMBBs(mf_->getNumBlockIDs());
Owen Anderson28998312008-08-13 22:28:50 +00001773 DenseMap<unsigned, std::vector<SRInfo> > RestoreIdxes;
1774 DenseMap<unsigned,unsigned> MBBVRegsMap;
Evan Chengf2fbca62007-11-12 06:35:08 +00001775 std::vector<LiveInterval*> NewLIs;
Evan Chengd70dbb52008-02-22 09:24:50 +00001776 const TargetRegisterClass* rc = mri_->getRegClass(li.reg);
Evan Chengf2fbca62007-11-12 06:35:08 +00001777
1778 unsigned NumValNums = li.getNumValNums();
1779 SmallVector<MachineInstr*, 4> ReMatDefs;
1780 ReMatDefs.resize(NumValNums, NULL);
1781 SmallVector<MachineInstr*, 4> ReMatOrigDefs;
1782 ReMatOrigDefs.resize(NumValNums, NULL);
1783 SmallVector<int, 4> ReMatIds;
1784 ReMatIds.resize(NumValNums, VirtRegMap::MAX_STACK_SLOT);
1785 BitVector ReMatDelete(NumValNums);
1786 unsigned Slot = VirtRegMap::MAX_STACK_SLOT;
1787
Evan Cheng81a03822007-11-17 00:40:40 +00001788 // Spilling a split live interval. It cannot be split any further. Also,
1789 // it's also guaranteed to be a single val# / range interval.
1790 if (vrm.getPreSplitReg(li.reg)) {
1791 vrm.setIsSplitFromReg(li.reg, 0);
Evan Chengd120ffd2007-12-05 10:24:35 +00001792 // Unset the split kill marker on the last use.
Lang Hames233a60e2009-11-03 23:52:08 +00001793 SlotIndex KillIdx = vrm.getKillPoint(li.reg);
1794 if (KillIdx != SlotIndex()) {
Evan Chengd120ffd2007-12-05 10:24:35 +00001795 MachineInstr *KillMI = getInstructionFromIndex(KillIdx);
1796 assert(KillMI && "Last use disappeared?");
1797 int KillOp = KillMI->findRegisterUseOperandIdx(li.reg, true);
1798 assert(KillOp != -1 && "Last use disappeared?");
Chris Lattnerf7382302007-12-30 21:56:09 +00001799 KillMI->getOperand(KillOp).setIsKill(false);
Evan Chengd120ffd2007-12-05 10:24:35 +00001800 }
Evan Chengadf85902007-12-05 09:51:10 +00001801 vrm.removeKillPoint(li.reg);
Evan Cheng81a03822007-11-17 00:40:40 +00001802 bool DefIsReMat = vrm.isReMaterialized(li.reg);
1803 Slot = vrm.getStackSlot(li.reg);
1804 assert(Slot != VirtRegMap::MAX_STACK_SLOT);
1805 MachineInstr *ReMatDefMI = DefIsReMat ?
1806 vrm.getReMaterializedMI(li.reg) : NULL;
1807 int LdSlot = 0;
1808 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
1809 bool isLoad = isLoadSS ||
Dan Gohman15511cf2008-12-03 18:15:48 +00001810 (DefIsReMat && (ReMatDefMI->getDesc().canFoldAsLoad()));
Evan Cheng81a03822007-11-17 00:40:40 +00001811 bool IsFirstRange = true;
1812 for (LiveInterval::Ranges::const_iterator
1813 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
1814 // If this is a split live interval with multiple ranges, it means there
1815 // are two-address instructions that re-defined the value. Only the
1816 // first def can be rematerialized!
1817 if (IsFirstRange) {
Evan Chengcb3c3302007-11-29 23:02:50 +00001818 // Note ReMatOrigDefMI has already been deleted.
Evan Cheng81a03822007-11-17 00:40:40 +00001819 rewriteInstructionsForSpills(li, false, I, NULL, ReMatDefMI,
1820 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001821 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001822 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Chengc781a242009-05-03 18:32:42 +00001823 MBBVRegsMap, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001824 } else {
1825 rewriteInstructionsForSpills(li, false, I, NULL, 0,
1826 Slot, 0, false, false, false,
Evan Chengd70dbb52008-02-22 09:24:50 +00001827 false, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001828 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Chengc781a242009-05-03 18:32:42 +00001829 MBBVRegsMap, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001830 }
1831 IsFirstRange = false;
1832 }
Evan Cheng419852c2008-04-03 16:39:43 +00001833
Evan Cheng4cce6b42008-04-11 17:53:36 +00001834 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng81a03822007-11-17 00:40:40 +00001835 return NewLIs;
1836 }
1837
Evan Cheng752195e2009-09-14 21:33:42 +00001838 bool TrySplit = !intervalIsInOneMBB(li);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001839 if (TrySplit)
1840 ++numSplits;
Evan Chengf2fbca62007-11-12 06:35:08 +00001841 bool NeedStackSlot = false;
1842 for (LiveInterval::const_vni_iterator i = li.vni_begin(), e = li.vni_end();
1843 i != e; ++i) {
1844 const VNInfo *VNI = *i;
1845 unsigned VN = VNI->id;
Lang Hames857c4e02009-06-17 21:01:20 +00001846 if (VNI->isUnused())
Evan Chengf2fbca62007-11-12 06:35:08 +00001847 continue; // Dead val#.
1848 // Is the def for the val# rematerializable?
Lang Hames857c4e02009-06-17 21:01:20 +00001849 MachineInstr *ReMatDefMI = VNI->isDefAccurate()
1850 ? getInstructionFromIndex(VNI->def) : 0;
Evan Cheng5ef3a042007-12-06 00:01:56 +00001851 bool dummy;
Evan Chengdc377862008-09-30 15:44:16 +00001852 if (ReMatDefMI && isReMaterializable(li, VNI, ReMatDefMI, SpillIs, dummy)) {
Evan Chengf2fbca62007-11-12 06:35:08 +00001853 // Remember how to remat the def of this val#.
Evan Cheng81a03822007-11-17 00:40:40 +00001854 ReMatOrigDefs[VN] = ReMatDefMI;
Dan Gohman2c3f7ae2008-07-17 23:49:46 +00001855 // Original def may be modified so we have to make a copy here.
Evan Cheng1ed99222008-07-19 00:37:25 +00001856 MachineInstr *Clone = mf_->CloneMachineInstr(ReMatDefMI);
Evan Cheng752195e2009-09-14 21:33:42 +00001857 CloneMIs.push_back(Clone);
Evan Cheng1ed99222008-07-19 00:37:25 +00001858 ReMatDefs[VN] = Clone;
Evan Chengf2fbca62007-11-12 06:35:08 +00001859
1860 bool CanDelete = true;
Lang Hames857c4e02009-06-17 21:01:20 +00001861 if (VNI->hasPHIKill()) {
Evan Chengc3fc7d92007-11-29 09:49:23 +00001862 // A kill is a phi node, not all of its uses can be rematerialized.
Evan Chengf2fbca62007-11-12 06:35:08 +00001863 // It must not be deleted.
Evan Chengc3fc7d92007-11-29 09:49:23 +00001864 CanDelete = false;
1865 // Need a stack slot if there is any live range where uses cannot be
1866 // rematerialized.
1867 NeedStackSlot = true;
Evan Chengf2fbca62007-11-12 06:35:08 +00001868 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001869 if (CanDelete)
1870 ReMatDelete.set(VN);
1871 } else {
1872 // Need a stack slot if there is any live range where uses cannot be
1873 // rematerialized.
1874 NeedStackSlot = true;
1875 }
1876 }
1877
1878 // One stack slot per live interval.
Owen Andersonb98bbb72009-03-26 18:53:38 +00001879 if (NeedStackSlot && vrm.getPreSplitReg(li.reg) == 0) {
1880 if (vrm.getStackSlot(li.reg) == VirtRegMap::NO_STACK_SLOT)
1881 Slot = vrm.assignVirt2StackSlot(li.reg);
1882
1883 // This case only occurs when the prealloc splitter has already assigned
1884 // a stack slot to this vreg.
1885 else
1886 Slot = vrm.getStackSlot(li.reg);
1887 }
Evan Chengf2fbca62007-11-12 06:35:08 +00001888
1889 // Create new intervals and rewrite defs and uses.
1890 for (LiveInterval::Ranges::const_iterator
1891 I = li.ranges.begin(), E = li.ranges.end(); I != E; ++I) {
Evan Cheng81a03822007-11-17 00:40:40 +00001892 MachineInstr *ReMatDefMI = ReMatDefs[I->valno->id];
1893 MachineInstr *ReMatOrigDefMI = ReMatOrigDefs[I->valno->id];
1894 bool DefIsReMat = ReMatDefMI != NULL;
Evan Chengf2fbca62007-11-12 06:35:08 +00001895 bool CanDelete = ReMatDelete[I->valno->id];
1896 int LdSlot = 0;
Evan Cheng81a03822007-11-17 00:40:40 +00001897 bool isLoadSS = DefIsReMat && tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
Evan Chengf2fbca62007-11-12 06:35:08 +00001898 bool isLoad = isLoadSS ||
Dan Gohman15511cf2008-12-03 18:15:48 +00001899 (DefIsReMat && ReMatDefMI->getDesc().canFoldAsLoad());
Evan Cheng81a03822007-11-17 00:40:40 +00001900 rewriteInstructionsForSpills(li, TrySplit, I, ReMatOrigDefMI, ReMatDefMI,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001901 Slot, LdSlot, isLoad, isLoadSS, DefIsReMat,
Evan Chengd70dbb52008-02-22 09:24:50 +00001902 CanDelete, vrm, rc, ReMatIds, loopInfo,
Evan Cheng0cbb1162007-11-29 01:06:25 +00001903 SpillMBBs, SpillIdxes, RestoreMBBs, RestoreIdxes,
Evan Chengc781a242009-05-03 18:32:42 +00001904 MBBVRegsMap, NewLIs);
Evan Chengf2fbca62007-11-12 06:35:08 +00001905 }
1906
Evan Cheng0cbb1162007-11-29 01:06:25 +00001907 // Insert spills / restores if we are splitting.
Evan Cheng419852c2008-04-03 16:39:43 +00001908 if (!TrySplit) {
Evan Cheng4cce6b42008-04-11 17:53:36 +00001909 handleSpilledImpDefs(li, vrm, rc, NewLIs);
Evan Cheng1953d0c2007-11-29 10:12:14 +00001910 return NewLIs;
Evan Cheng419852c2008-04-03 16:39:43 +00001911 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001912
Evan Chengb50bb8c2007-12-05 08:16:32 +00001913 SmallPtrSet<LiveInterval*, 4> AddedKill;
Evan Chengaee4af62007-12-02 08:30:39 +00001914 SmallVector<unsigned, 2> Ops;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001915 if (NeedStackSlot) {
1916 int Id = SpillMBBs.find_first();
1917 while (Id != -1) {
1918 std::vector<SRInfo> &spills = SpillIdxes[Id];
1919 for (unsigned i = 0, e = spills.size(); i != e; ++i) {
Lang Hames233a60e2009-11-03 23:52:08 +00001920 SlotIndex index = spills[i].index;
Evan Cheng1953d0c2007-11-29 10:12:14 +00001921 unsigned VReg = spills[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001922 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001923 bool isReMat = vrm.isReMaterialized(VReg);
1924 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001925 bool CanFold = false;
1926 bool FoundUse = false;
1927 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001928 if (spills[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001929 CanFold = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001930 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1931 MachineOperand &MO = MI->getOperand(j);
Dan Gohmand735b802008-10-03 15:45:36 +00001932 if (!MO.isReg() || MO.getReg() != VReg)
Evan Cheng0cbb1162007-11-29 01:06:25 +00001933 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001934
1935 Ops.push_back(j);
1936 if (MO.isDef())
Evan Chengcddbb832007-11-30 21:23:43 +00001937 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001938 if (isReMat ||
1939 (!FoundUse && !alsoFoldARestore(Id, index, VReg,
1940 RestoreMBBs, RestoreIdxes))) {
1941 // MI has two-address uses of the same register. If the use
1942 // isn't the first and only use in the BB, then we can't fold
1943 // it. FIXME: Move this to rewriteInstructionsForSpills.
1944 CanFold = false;
Evan Chengcddbb832007-11-30 21:23:43 +00001945 break;
1946 }
Evan Chengaee4af62007-12-02 08:30:39 +00001947 FoundUse = true;
Evan Cheng0cbb1162007-11-29 01:06:25 +00001948 }
1949 }
1950 // Fold the store into the def if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00001951 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00001952 if (CanFold && !Ops.empty()) {
1953 if (tryFoldMemoryOperand(MI, vrm, NULL, index, Ops, true, Slot,VReg)){
Evan Chengcddbb832007-11-30 21:23:43 +00001954 Folded = true;
Sebastian Redl48fe6352009-03-19 23:26:52 +00001955 if (FoundUse) {
Evan Chengaee4af62007-12-02 08:30:39 +00001956 // Also folded uses, do not issue a load.
1957 eraseRestoreInfo(Id, index, VReg, RestoreMBBs, RestoreIdxes);
Lang Hames233a60e2009-11-03 23:52:08 +00001958 nI.removeRange(index.getLoadIndex(), index.getDefIndex());
Evan Chengf38d14f2007-12-05 09:05:34 +00001959 }
Lang Hames233a60e2009-11-03 23:52:08 +00001960 nI.removeRange(index.getDefIndex(), index.getStoreIndex());
Evan Chengcddbb832007-11-30 21:23:43 +00001961 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001962 }
1963
Evan Cheng7e073ba2008-04-09 20:57:25 +00001964 // Otherwise tell the spiller to issue a spill.
Evan Chengb50bb8c2007-12-05 08:16:32 +00001965 if (!Folded) {
1966 LiveRange *LR = &nI.ranges[nI.ranges.size()-1];
Lang Hames233a60e2009-11-03 23:52:08 +00001967 bool isKill = LR->end == index.getStoreIndex();
Evan Chengb0a6f622008-05-20 08:10:37 +00001968 if (!MI->registerDefIsDead(nI.reg))
1969 // No need to spill a dead def.
1970 vrm.addSpillPoint(VReg, isKill, MI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00001971 if (isKill)
1972 AddedKill.insert(&nI);
1973 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001974 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001975 Id = SpillMBBs.find_next(Id);
Evan Cheng0cbb1162007-11-29 01:06:25 +00001976 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00001977 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00001978
Evan Cheng1953d0c2007-11-29 10:12:14 +00001979 int Id = RestoreMBBs.find_first();
1980 while (Id != -1) {
1981 std::vector<SRInfo> &restores = RestoreIdxes[Id];
1982 for (unsigned i = 0, e = restores.size(); i != e; ++i) {
Lang Hames233a60e2009-11-03 23:52:08 +00001983 SlotIndex index = restores[i].index;
1984 if (index == SlotIndex())
Evan Cheng1953d0c2007-11-29 10:12:14 +00001985 continue;
1986 unsigned VReg = restores[i].vreg;
Evan Cheng597d10d2007-12-04 00:32:23 +00001987 LiveInterval &nI = getOrCreateInterval(VReg);
Evan Cheng9c3c2212008-06-06 07:54:39 +00001988 bool isReMat = vrm.isReMaterialized(VReg);
Evan Cheng81a03822007-11-17 00:40:40 +00001989 MachineInstr *MI = getInstructionFromIndex(index);
Evan Chengaee4af62007-12-02 08:30:39 +00001990 bool CanFold = false;
1991 Ops.clear();
Evan Chengcddbb832007-11-30 21:23:43 +00001992 if (restores[i].canFold) {
Evan Chengaee4af62007-12-02 08:30:39 +00001993 CanFold = true;
Evan Cheng81a03822007-11-17 00:40:40 +00001994 for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
1995 MachineOperand &MO = MI->getOperand(j);
Dan Gohmand735b802008-10-03 15:45:36 +00001996 if (!MO.isReg() || MO.getReg() != VReg)
Evan Cheng81a03822007-11-17 00:40:40 +00001997 continue;
Evan Chengaee4af62007-12-02 08:30:39 +00001998
Evan Cheng0cbb1162007-11-29 01:06:25 +00001999 if (MO.isDef()) {
Evan Chengaee4af62007-12-02 08:30:39 +00002000 // If this restore were to be folded, it would have been folded
2001 // already.
2002 CanFold = false;
Evan Cheng81a03822007-11-17 00:40:40 +00002003 break;
2004 }
Evan Chengaee4af62007-12-02 08:30:39 +00002005 Ops.push_back(j);
Evan Cheng81a03822007-11-17 00:40:40 +00002006 }
2007 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002008
2009 // Fold the load into the use if possible.
Evan Chengcddbb832007-11-30 21:23:43 +00002010 bool Folded = false;
Evan Chengaee4af62007-12-02 08:30:39 +00002011 if (CanFold && !Ops.empty()) {
Evan Cheng9c3c2212008-06-06 07:54:39 +00002012 if (!isReMat)
Evan Chengaee4af62007-12-02 08:30:39 +00002013 Folded = tryFoldMemoryOperand(MI, vrm, NULL,index,Ops,true,Slot,VReg);
2014 else {
Evan Cheng0cbb1162007-11-29 01:06:25 +00002015 MachineInstr *ReMatDefMI = vrm.getReMaterializedMI(VReg);
2016 int LdSlot = 0;
2017 bool isLoadSS = tii_->isLoadFromStackSlot(ReMatDefMI, LdSlot);
2018 // If the rematerializable def is a load, also try to fold it.
Dan Gohman15511cf2008-12-03 18:15:48 +00002019 if (isLoadSS || ReMatDefMI->getDesc().canFoldAsLoad())
Evan Chengaee4af62007-12-02 08:30:39 +00002020 Folded = tryFoldMemoryOperand(MI, vrm, ReMatDefMI, index,
2021 Ops, isLoadSS, LdSlot, VReg);
Evan Cheng650d7f32008-12-05 17:41:31 +00002022 if (!Folded) {
2023 unsigned ImpUse = getReMatImplicitUse(li, ReMatDefMI);
2024 if (ImpUse) {
2025 // Re-matting an instruction with virtual register use. Add the
2026 // register as an implicit use on the use MI and update the register
2027 // interval's spill weight to HUGE_VALF to prevent it from being
2028 // spilled.
2029 LiveInterval &ImpLi = getInterval(ImpUse);
2030 ImpLi.weight = HUGE_VALF;
2031 MI->addOperand(MachineOperand::CreateReg(ImpUse, false, true));
2032 }
Evan Chengd70dbb52008-02-22 09:24:50 +00002033 }
Evan Chengaee4af62007-12-02 08:30:39 +00002034 }
Evan Cheng0cbb1162007-11-29 01:06:25 +00002035 }
2036 // If folding is not possible / failed, then tell the spiller to issue a
2037 // load / rematerialization for us.
Evan Cheng597d10d2007-12-04 00:32:23 +00002038 if (Folded)
Lang Hames233a60e2009-11-03 23:52:08 +00002039 nI.removeRange(index.getLoadIndex(), index.getDefIndex());
Evan Chengb50bb8c2007-12-05 08:16:32 +00002040 else
Evan Cheng0cbb1162007-11-29 01:06:25 +00002041 vrm.addRestorePoint(VReg, MI);
Evan Cheng81a03822007-11-17 00:40:40 +00002042 }
Evan Cheng1953d0c2007-11-29 10:12:14 +00002043 Id = RestoreMBBs.find_next(Id);
Evan Cheng81a03822007-11-17 00:40:40 +00002044 }
2045
Evan Chengb50bb8c2007-12-05 08:16:32 +00002046 // Finalize intervals: add kills, finalize spill weights, and filter out
2047 // dead intervals.
Evan Cheng597d10d2007-12-04 00:32:23 +00002048 std::vector<LiveInterval*> RetNewLIs;
2049 for (unsigned i = 0, e = NewLIs.size(); i != e; ++i) {
2050 LiveInterval *LI = NewLIs[i];
2051 if (!LI->empty()) {
Lang Hames233a60e2009-11-03 23:52:08 +00002052 LI->weight /= SlotIndex::NUM * getApproximateInstructionCount(*LI);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002053 if (!AddedKill.count(LI)) {
2054 LiveRange *LR = &LI->ranges[LI->ranges.size()-1];
Lang Hames233a60e2009-11-03 23:52:08 +00002055 SlotIndex LastUseIdx = LR->end.getBaseIndex();
Evan Chengd120ffd2007-12-05 10:24:35 +00002056 MachineInstr *LastUse = getInstructionFromIndex(LastUseIdx);
Evan Cheng6130f662008-03-05 00:59:57 +00002057 int UseIdx = LastUse->findRegisterUseOperandIdx(LI->reg, false);
Evan Chengb50bb8c2007-12-05 08:16:32 +00002058 assert(UseIdx != -1);
Evan Chenga24752f2009-03-19 20:30:06 +00002059 if (!LastUse->isRegTiedToDefOperand(UseIdx)) {
Evan Chengb50bb8c2007-12-05 08:16:32 +00002060 LastUse->getOperand(UseIdx).setIsKill();
Evan Chengd120ffd2007-12-05 10:24:35 +00002061 vrm.addKillPoint(LI->reg, LastUseIdx);
Evan Chengadf85902007-12-05 09:51:10 +00002062 }
Evan Chengb50bb8c2007-12-05 08:16:32 +00002063 }
Evan Cheng597d10d2007-12-04 00:32:23 +00002064 RetNewLIs.push_back(LI);
2065 }
2066 }
Evan Cheng81a03822007-11-17 00:40:40 +00002067
Evan Cheng4cce6b42008-04-11 17:53:36 +00002068 handleSpilledImpDefs(li, vrm, rc, RetNewLIs);
Evan Cheng597d10d2007-12-04 00:32:23 +00002069 return RetNewLIs;
Evan Chengf2fbca62007-11-12 06:35:08 +00002070}
Evan Cheng676dd7c2008-03-11 07:19:34 +00002071
2072/// hasAllocatableSuperReg - Return true if the specified physical register has
2073/// any super register that's allocatable.
2074bool LiveIntervals::hasAllocatableSuperReg(unsigned Reg) const {
2075 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS)
2076 if (allocatableRegs_[*AS] && hasInterval(*AS))
2077 return true;
2078 return false;
2079}
2080
2081/// getRepresentativeReg - Find the largest super register of the specified
2082/// physical register.
2083unsigned LiveIntervals::getRepresentativeReg(unsigned Reg) const {
2084 // Find the largest super-register that is allocatable.
2085 unsigned BestReg = Reg;
2086 for (const unsigned* AS = tri_->getSuperRegisters(Reg); *AS; ++AS) {
2087 unsigned SuperReg = *AS;
2088 if (!hasAllocatableSuperReg(SuperReg) && hasInterval(SuperReg)) {
2089 BestReg = SuperReg;
2090 break;
2091 }
2092 }
2093 return BestReg;
2094}
2095
2096/// getNumConflictsWithPhysReg - Return the number of uses and defs of the
2097/// specified interval that conflicts with the specified physical register.
2098unsigned LiveIntervals::getNumConflictsWithPhysReg(const LiveInterval &li,
2099 unsigned PhysReg) const {
2100 unsigned NumConflicts = 0;
2101 const LiveInterval &pli = getInterval(getRepresentativeReg(PhysReg));
2102 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
2103 E = mri_->reg_end(); I != E; ++I) {
2104 MachineOperand &O = I.getOperand();
2105 MachineInstr *MI = O.getParent();
Lang Hames233a60e2009-11-03 23:52:08 +00002106 SlotIndex Index = getInstructionIndex(MI);
Evan Cheng676dd7c2008-03-11 07:19:34 +00002107 if (pli.liveAt(Index))
2108 ++NumConflicts;
2109 }
2110 return NumConflicts;
2111}
2112
2113/// spillPhysRegAroundRegDefsUses - Spill the specified physical register
Evan Cheng2824a652009-03-23 18:24:37 +00002114/// around all defs and uses of the specified interval. Return true if it
2115/// was able to cut its interval.
2116bool LiveIntervals::spillPhysRegAroundRegDefsUses(const LiveInterval &li,
Evan Cheng676dd7c2008-03-11 07:19:34 +00002117 unsigned PhysReg, VirtRegMap &vrm) {
2118 unsigned SpillReg = getRepresentativeReg(PhysReg);
2119
2120 for (const unsigned *AS = tri_->getAliasSet(PhysReg); *AS; ++AS)
2121 // If there are registers which alias PhysReg, but which are not a
2122 // sub-register of the chosen representative super register. Assert
2123 // since we can't handle it yet.
Dan Gohman70f2f652009-04-13 15:22:29 +00002124 assert(*AS == SpillReg || !allocatableRegs_[*AS] || !hasInterval(*AS) ||
Evan Cheng676dd7c2008-03-11 07:19:34 +00002125 tri_->isSuperRegister(*AS, SpillReg));
2126
Evan Cheng2824a652009-03-23 18:24:37 +00002127 bool Cut = false;
Evan Cheng0222a8c2009-10-20 01:31:09 +00002128 SmallVector<unsigned, 4> PRegs;
2129 if (hasInterval(SpillReg))
2130 PRegs.push_back(SpillReg);
2131 else {
2132 SmallSet<unsigned, 4> Added;
2133 for (const unsigned* AS = tri_->getSubRegisters(SpillReg); *AS; ++AS)
2134 if (Added.insert(*AS) && hasInterval(*AS)) {
2135 PRegs.push_back(*AS);
2136 for (const unsigned* ASS = tri_->getSubRegisters(*AS); *ASS; ++ASS)
2137 Added.insert(*ASS);
2138 }
2139 }
2140
Evan Cheng676dd7c2008-03-11 07:19:34 +00002141 SmallPtrSet<MachineInstr*, 8> SeenMIs;
2142 for (MachineRegisterInfo::reg_iterator I = mri_->reg_begin(li.reg),
2143 E = mri_->reg_end(); I != E; ++I) {
2144 MachineOperand &O = I.getOperand();
2145 MachineInstr *MI = O.getParent();
2146 if (SeenMIs.count(MI))
2147 continue;
2148 SeenMIs.insert(MI);
Lang Hames233a60e2009-11-03 23:52:08 +00002149 SlotIndex Index = getInstructionIndex(MI);
Evan Cheng0222a8c2009-10-20 01:31:09 +00002150 for (unsigned i = 0, e = PRegs.size(); i != e; ++i) {
2151 unsigned PReg = PRegs[i];
2152 LiveInterval &pli = getInterval(PReg);
2153 if (!pli.liveAt(Index))
2154 continue;
2155 vrm.addEmergencySpill(PReg, MI);
Lang Hames233a60e2009-11-03 23:52:08 +00002156 SlotIndex StartIdx = Index.getLoadIndex();
2157 SlotIndex EndIdx = Index.getNextIndex().getBaseIndex();
Evan Cheng2824a652009-03-23 18:24:37 +00002158 if (pli.isInOneLiveRange(StartIdx, EndIdx)) {
Evan Cheng5a3c6a82009-01-29 02:20:59 +00002159 pli.removeRange(StartIdx, EndIdx);
Evan Cheng2824a652009-03-23 18:24:37 +00002160 Cut = true;
2161 } else {
Torok Edwin7d696d82009-07-11 13:10:19 +00002162 std::string msg;
2163 raw_string_ostream Msg(msg);
2164 Msg << "Ran out of registers during register allocation!";
Evan Cheng5a3c6a82009-01-29 02:20:59 +00002165 if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
Torok Edwin7d696d82009-07-11 13:10:19 +00002166 Msg << "\nPlease check your inline asm statement for invalid "
Evan Cheng0222a8c2009-10-20 01:31:09 +00002167 << "constraints:\n";
Torok Edwin7d696d82009-07-11 13:10:19 +00002168 MI->print(Msg, tm_);
Evan Cheng5a3c6a82009-01-29 02:20:59 +00002169 }
Torok Edwin7d696d82009-07-11 13:10:19 +00002170 llvm_report_error(Msg.str());
Evan Cheng5a3c6a82009-01-29 02:20:59 +00002171 }
Evan Cheng0222a8c2009-10-20 01:31:09 +00002172 for (const unsigned* AS = tri_->getSubRegisters(PReg); *AS; ++AS) {
Evan Cheng676dd7c2008-03-11 07:19:34 +00002173 if (!hasInterval(*AS))
2174 continue;
2175 LiveInterval &spli = getInterval(*AS);
2176 if (spli.liveAt(Index))
Lang Hames233a60e2009-11-03 23:52:08 +00002177 spli.removeRange(Index.getLoadIndex(),
2178 Index.getNextIndex().getBaseIndex());
Evan Cheng676dd7c2008-03-11 07:19:34 +00002179 }
2180 }
2181 }
Evan Cheng2824a652009-03-23 18:24:37 +00002182 return Cut;
Evan Cheng676dd7c2008-03-11 07:19:34 +00002183}
Owen Andersonc4dc1322008-06-05 17:15:43 +00002184
2185LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
Lang Hamesffd13262009-07-09 03:57:02 +00002186 MachineInstr* startInst) {
Owen Andersonc4dc1322008-06-05 17:15:43 +00002187 LiveInterval& Interval = getOrCreateInterval(reg);
2188 VNInfo* VN = Interval.getNextValue(
Lang Hames233a60e2009-11-03 23:52:08 +00002189 SlotIndex(getInstructionIndex(startInst).getDefIndex()),
Lang Hames86511252009-09-04 20:41:11 +00002190 startInst, true, getVNInfoAllocator());
Lang Hames857c4e02009-06-17 21:01:20 +00002191 VN->setHasPHIKill(true);
Lang Hames233a60e2009-11-03 23:52:08 +00002192 VN->kills.push_back(indexes_->getTerminatorGap(startInst->getParent()));
Lang Hames86511252009-09-04 20:41:11 +00002193 LiveRange LR(
Lang Hames233a60e2009-11-03 23:52:08 +00002194 SlotIndex(getInstructionIndex(startInst).getDefIndex()),
2195 getMBBEndIdx(startInst->getParent()).getNextIndex().getBaseIndex(), VN);
Owen Andersonc4dc1322008-06-05 17:15:43 +00002196 Interval.addRange(LR);
2197
2198 return LR;
2199}
David Greeneb5257662009-08-03 21:55:09 +00002200