blob: c414ded1a41372901afb7272ce24c73d227013ca [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
Jakob Stoklund Olesen4281e202012-01-07 07:39:47 +000018#define DEBUG_TYPE "regalloc"
Chris Lattner3c3fe462005-09-21 04:19:09 +000019#include "llvm/CodeGen/LiveIntervalAnalysis.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000020#include "LiveRangeCalc.h"
21#include "llvm/ADT/DenseSet.h"
22#include "llvm/ADT/STLExtras.h"
Dan Gohman6d69ba82008-07-25 00:02:30 +000023#include "llvm/Analysis/AliasAnalysis.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000024#include "llvm/CodeGen/LiveVariables.h"
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +000025#include "llvm/CodeGen/MachineDominators.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000026#include "llvm/CodeGen/MachineInstr.h"
Chris Lattner84bc5422007-12-31 04:13:23 +000027#include "llvm/CodeGen/MachineRegisterInfo.h"
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000028#include "llvm/CodeGen/Passes.h"
Jakob Stoklund Olesen1ead68d2012-11-28 19:13:06 +000029#include "llvm/CodeGen/VirtRegMap.h"
Jakob Stoklund Olesen3dfa38a2012-07-27 20:58:46 +000030#include "llvm/Support/CommandLine.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000031#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000032#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/raw_ostream.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000034#include "llvm/Target/TargetInstrInfo.h"
35#include "llvm/Target/TargetMachine.h"
36#include "llvm/Target/TargetRegisterInfo.h"
37#include "llvm/Value.h"
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000038#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000039#include <cmath>
Chandler Carruthd04a8d42012-12-03 16:50:05 +000040#include <limits>
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000041using namespace llvm;
42
Jakob Stoklund Olesen3dfa38a2012-07-27 20:58:46 +000043// Switch to the new experimental algorithm for computing live intervals.
44static cl::opt<bool>
45NewLiveIntervals("new-live-intervals", cl::Hidden,
46 cl::desc("Use new algorithm forcomputing live intervals"));
47
Devang Patel19974732007-05-03 01:11:54 +000048char LiveIntervals::ID = 0;
Jakob Stoklund Olesendcc44362012-08-03 22:12:54 +000049char &llvm::LiveIntervalsID = LiveIntervals::ID;
Owen Anderson2ab36d32010-10-12 19:48:12 +000050INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
51 "Live Interval Analysis", false, false)
Andrew Trick8dd26252012-02-10 04:10:36 +000052INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
Owen Anderson2ab36d32010-10-12 19:48:12 +000053INITIALIZE_PASS_DEPENDENCY(LiveVariables)
Andrew Trick8dd26252012-02-10 04:10:36 +000054INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
Owen Anderson2ab36d32010-10-12 19:48:12 +000055INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
Owen Anderson2ab36d32010-10-12 19:48:12 +000056INITIALIZE_PASS_END(LiveIntervals, "liveintervals",
Owen Andersonce665bd2010-10-07 22:25:06 +000057 "Live Interval Analysis", false, false)
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000058
Chris Lattnerf7da2c72006-08-24 22:43:55 +000059void LiveIntervals::getAnalysisUsage(AnalysisUsage &AU) const {
Dan Gohman845012e2009-07-31 23:37:33 +000060 AU.setPreservesCFG();
Dan Gohman6d69ba82008-07-25 00:02:30 +000061 AU.addRequired<AliasAnalysis>();
62 AU.addPreserved<AliasAnalysis>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000063 AU.addRequired<LiveVariables>();
Evan Cheng148341c2010-08-17 21:00:37 +000064 AU.addPreserved<LiveVariables>();
Andrew Trickd35576b2012-02-13 20:44:42 +000065 AU.addPreservedID(MachineLoopInfoID);
Jakob Stoklund Olesenc4118452012-06-20 23:31:34 +000066 AU.addRequiredTransitiveID(MachineDominatorsID);
Bill Wendling67d65bb2008-01-04 20:54:55 +000067 AU.addPreservedID(MachineDominatorsID);
Lang Hames233a60e2009-11-03 23:52:08 +000068 AU.addPreserved<SlotIndexes>();
69 AU.addRequiredTransitive<SlotIndexes>();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +000070 MachineFunctionPass::getAnalysisUsage(AU);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +000071}
72
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +000073LiveIntervals::LiveIntervals() : MachineFunctionPass(ID),
74 DomTree(0), LRCalc(0) {
75 initializeLiveIntervalsPass(*PassRegistry::getPassRegistry());
76}
77
78LiveIntervals::~LiveIntervals() {
79 delete LRCalc;
80}
81
Chris Lattnerf7da2c72006-08-24 22:43:55 +000082void LiveIntervals::releaseMemory() {
Owen Anderson03857b22008-08-13 21:49:13 +000083 // Free the live intervals themselves.
Jakob Stoklund Olesen7fa67842012-06-22 20:37:52 +000084 for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
85 delete VirtRegIntervals[TargetRegisterInfo::index2VirtReg(i)];
86 VirtRegIntervals.clear();
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +000087 RegMaskSlots.clear();
88 RegMaskBits.clear();
Jakob Stoklund Olesen34e85d02012-02-10 01:26:29 +000089 RegMaskBlocks.clear();
Lang Hamesffd13262009-07-09 03:57:02 +000090
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +000091 for (unsigned i = 0, e = RegUnitIntervals.size(); i != e; ++i)
92 delete RegUnitIntervals[i];
93 RegUnitIntervals.clear();
94
Benjamin Kramerce9a20b2010-06-26 11:30:59 +000095 // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
96 VNInfoAllocator.Reset();
Alkis Evlogimenos08cec002004-01-31 19:59:32 +000097}
98
Owen Anderson80b3ce62008-05-28 20:54:50 +000099/// runOnMachineFunction - Register allocate the whole function
100///
101bool LiveIntervals::runOnMachineFunction(MachineFunction &fn) {
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000102 MF = &fn;
103 MRI = &MF->getRegInfo();
104 TM = &fn.getTarget();
105 TRI = TM->getRegisterInfo();
106 TII = TM->getInstrInfo();
107 AA = &getAnalysis<AliasAnalysis>();
108 LV = &getAnalysis<LiveVariables>();
109 Indexes = &getAnalysis<SlotIndexes>();
Jakob Stoklund Olesenc4118452012-06-20 23:31:34 +0000110 DomTree = &getAnalysis<MachineDominatorTree>();
111 if (!LRCalc)
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000112 LRCalc = new LiveRangeCalc();
Owen Anderson80b3ce62008-05-28 20:54:50 +0000113
Jakob Stoklund Olesen3dfa38a2012-07-27 20:58:46 +0000114 // Allocate space for all virtual registers.
115 VirtRegIntervals.resize(MRI->getNumVirtRegs());
116
117 if (NewLiveIntervals) {
118 // This is the new way of computing live intervals.
119 // It is independent of LiveVariables, and it can run at any time.
Jakob Stoklund Olesenc16bf792012-07-27 21:56:39 +0000120 computeVirtRegs();
121 computeRegMasks();
Jakob Stoklund Olesen3dfa38a2012-07-27 20:58:46 +0000122 } else {
123 // This is the old way of computing live intervals.
124 // It depends on LiveVariables.
125 computeIntervals();
126 }
Jakob Stoklund Olesenc4118452012-06-20 23:31:34 +0000127 computeLiveInRegUnits();
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000128
Chris Lattner70ca3582004-09-30 15:59:17 +0000129 DEBUG(dump());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000130 return true;
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000131}
132
Chris Lattner70ca3582004-09-30 15:59:17 +0000133/// print - Implement the dump method.
Chris Lattner45cfe542009-08-23 06:03:38 +0000134void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
Chris Lattner705e07f2009-08-23 03:41:05 +0000135 OS << "********** INTERVALS **********\n";
Jakob Stoklund Olesenf658af52012-02-14 23:46:21 +0000136
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000137 // Dump the regunits.
138 for (unsigned i = 0, e = RegUnitIntervals.size(); i != e; ++i)
139 if (LiveInterval *LI = RegUnitIntervals[i])
140 OS << PrintRegUnit(i, TRI) << " = " << *LI << '\n';
141
Jakob Stoklund Olesenf658af52012-02-14 23:46:21 +0000142 // Dump the virtregs.
Jakob Stoklund Olesen7fa67842012-06-22 20:37:52 +0000143 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
144 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
145 if (hasInterval(Reg))
146 OS << PrintReg(Reg) << " = " << getInterval(Reg) << '\n';
147 }
Chris Lattner70ca3582004-09-30 15:59:17 +0000148
Jakob Stoklund Olesen722c9a72012-11-09 19:18:49 +0000149 OS << "RegMasks:";
150 for (unsigned i = 0, e = RegMaskSlots.size(); i != e; ++i)
151 OS << ' ' << RegMaskSlots[i];
152 OS << '\n';
153
Evan Cheng752195e2009-09-14 21:33:42 +0000154 printInstrs(OS);
155}
156
157void LiveIntervals::printInstrs(raw_ostream &OS) const {
Chris Lattner705e07f2009-08-23 03:41:05 +0000158 OS << "********** MACHINEINSTRS **********\n";
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000159 MF->print(OS, Indexes);
Chris Lattner70ca3582004-09-30 15:59:17 +0000160}
161
Manman Renb720be62012-09-11 22:23:19 +0000162#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Evan Cheng752195e2009-09-14 21:33:42 +0000163void LiveIntervals::dumpInstrs() const {
David Greene8a342292010-01-04 22:49:02 +0000164 printInstrs(dbgs());
Evan Cheng752195e2009-09-14 21:33:42 +0000165}
Manman Ren77e300e2012-09-06 19:06:06 +0000166#endif
Evan Cheng752195e2009-09-14 21:33:42 +0000167
Evan Chengafff40a2010-05-04 20:26:52 +0000168static
Evan Cheng37499432010-05-05 18:27:40 +0000169bool MultipleDefsBySameMI(const MachineInstr &MI, unsigned MOIdx) {
Evan Chengafff40a2010-05-04 20:26:52 +0000170 unsigned Reg = MI.getOperand(MOIdx).getReg();
171 for (unsigned i = MOIdx+1, e = MI.getNumOperands(); i < e; ++i) {
172 const MachineOperand &MO = MI.getOperand(i);
173 if (!MO.isReg())
174 continue;
175 if (MO.getReg() == Reg && MO.isDef()) {
176 assert(MI.getOperand(MOIdx).getSubReg() != MO.getSubReg() &&
177 MI.getOperand(MOIdx).getSubReg() &&
Jakob Stoklund Olesened2185e2010-07-06 23:26:25 +0000178 (MO.getSubReg() || MO.isImplicit()));
Evan Chengafff40a2010-05-04 20:26:52 +0000179 return true;
180 }
181 }
182 return false;
183}
184
Evan Cheng37499432010-05-05 18:27:40 +0000185/// isPartialRedef - Return true if the specified def at the specific index is
186/// partially re-defining the specified live interval. A common case of this is
Jakob Stoklund Olesen1b293202010-08-12 20:01:23 +0000187/// a definition of the sub-register.
Evan Cheng37499432010-05-05 18:27:40 +0000188bool LiveIntervals::isPartialRedef(SlotIndex MIIdx, MachineOperand &MO,
189 LiveInterval &interval) {
190 if (!MO.getSubReg() || MO.isEarlyClobber())
191 return false;
192
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000193 SlotIndex RedefIndex = MIIdx.getRegSlot();
Evan Cheng37499432010-05-05 18:27:40 +0000194 const LiveRange *OldLR =
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000195 interval.getLiveRangeContaining(RedefIndex.getRegSlot(true));
Lang Hames6e2968c2010-09-25 12:04:16 +0000196 MachineInstr *DefMI = getInstructionFromIndex(OldLR->valno->def);
197 if (DefMI != 0) {
Evan Cheng37499432010-05-05 18:27:40 +0000198 return DefMI->findRegisterDefOperandIdx(interval.reg) != -1;
199 }
200 return false;
201}
202
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000203void LiveIntervals::handleVirtualRegisterDef(MachineBasicBlock *mbb,
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000204 MachineBasicBlock::iterator mi,
Lang Hames233a60e2009-11-03 23:52:08 +0000205 SlotIndex MIIdx,
Lang Hames86511252009-09-04 20:41:11 +0000206 MachineOperand& MO,
Evan Chengef0732d2008-07-10 07:35:43 +0000207 unsigned MOIdx,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000208 LiveInterval &interval) {
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000209 DEBUG(dbgs() << "\t\tregister: " << PrintReg(interval.reg, TRI));
Evan Cheng419852c2008-04-03 16:39:43 +0000210
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000211 // Virtual registers may be defined multiple times (due to phi
212 // elimination and 2-addr elimination). Much of what we do only has to be
213 // done once for the vreg. We use an empty interval to detect the first
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000214 // time we see a vreg.
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000215 LiveVariables::VarInfo& vi = LV->getVarInfo(interval.reg);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000216 if (interval.empty()) {
217 // Get the Idx of the defining instructions.
Jakob Stoklund Olesend14614e2011-11-13 22:05:42 +0000218 SlotIndex defIndex = MIIdx.getRegSlot(MO.isEarlyClobber());
Jakob Stoklund Olesen63e6a482010-05-21 16:32:16 +0000219
Jakob Stoklund Olesen92b7df02012-03-04 19:19:10 +0000220 // Make sure the first definition is not a partial redefinition.
221 assert(!MO.readsReg() && "First def cannot also read virtual register "
222 "missing <undef> flag?");
Jakob Stoklund Olesen63e6a482010-05-21 16:32:16 +0000223
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +0000224 VNInfo *ValNo = interval.getNextValue(defIndex, VNInfoAllocator);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000225 assert(ValNo->id == 0 && "First value in interval is not 0?");
Chris Lattner7ac2d312004-07-24 02:59:07 +0000226
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000227 // Loop over all of the blocks that the vreg is defined in. There are
228 // two cases we have to handle here. The most common case is a vreg
229 // whose lifetime is contained within a basic block. In this case there
230 // will be a single kill, in MBB, which comes after the definition.
231 if (vi.Kills.size() == 1 && vi.Kills[0]->getParent() == mbb) {
232 // FIXME: what about dead vars?
Lang Hames233a60e2009-11-03 23:52:08 +0000233 SlotIndex killIdx;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000234 if (vi.Kills[0] != mi)
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000235 killIdx = getInstructionIndex(vi.Kills[0]).getRegSlot();
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000236 else
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000237 killIdx = defIndex.getDeadSlot();
Chris Lattner6097d132004-07-19 02:15:56 +0000238
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000239 // If the kill happens after the definition, we have an intra-block
240 // live range.
241 if (killIdx > defIndex) {
Jeffrey Yasskin493a3d02009-05-26 18:27:15 +0000242 assert(vi.AliveBlocks.empty() &&
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000243 "Shouldn't be alive across any blocks!");
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000244 LiveRange LR(defIndex, killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000245 interval.addRange(LR);
David Greene8a342292010-01-04 22:49:02 +0000246 DEBUG(dbgs() << " +" << LR << "\n");
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000247 return;
248 }
Alkis Evlogimenosdd2cc652003-12-18 08:48:48 +0000249 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000250
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000251 // The other case we handle is when a virtual register lives to the end
252 // of the defining block, potentially live across some blocks, then is
253 // live into some number of blocks, but gets killed. Start by adding a
254 // range that goes from this definition to the end of the defining block.
Lang Hames74ab5ee2009-12-22 00:11:50 +0000255 LiveRange NewLR(defIndex, getMBBEndIdx(mbb), ValNo);
David Greene8a342292010-01-04 22:49:02 +0000256 DEBUG(dbgs() << " +" << NewLR);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000257 interval.addRange(NewLR);
258
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000259 bool PHIJoin = LV->isPHIJoin(interval.reg);
Jakob Stoklund Olesendcfe5f32010-02-23 22:43:58 +0000260
261 if (PHIJoin) {
Jakob Stoklund Olesenfa8becb2012-06-19 22:50:53 +0000262 // A phi join register is killed at the end of the MBB and revived as a
263 // new valno in the killing blocks.
Jakob Stoklund Olesendcfe5f32010-02-23 22:43:58 +0000264 assert(vi.AliveBlocks.empty() && "Phi join can't pass through blocks");
265 DEBUG(dbgs() << " phi-join");
Jakob Stoklund Olesendcfe5f32010-02-23 22:43:58 +0000266 } else {
267 // Iterate over all of the blocks that the variable is completely
268 // live in, adding [insrtIndex(begin), instrIndex(end)+4) to the
269 // live interval.
270 for (SparseBitVector<>::iterator I = vi.AliveBlocks.begin(),
271 E = vi.AliveBlocks.end(); I != E; ++I) {
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000272 MachineBasicBlock *aliveBlock = MF->getBlockNumbered(*I);
Jakob Stoklund Olesenfa8becb2012-06-19 22:50:53 +0000273 LiveRange LR(getMBBStartIdx(aliveBlock), getMBBEndIdx(aliveBlock),
274 ValNo);
Jakob Stoklund Olesendcfe5f32010-02-23 22:43:58 +0000275 interval.addRange(LR);
276 DEBUG(dbgs() << " +" << LR);
277 }
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000278 }
279
280 // Finally, this virtual register is live from the start of any killing
281 // block to the 'use' slot of the killing instruction.
282 for (unsigned i = 0, e = vi.Kills.size(); i != e; ++i) {
283 MachineInstr *Kill = vi.Kills[i];
Jakob Stoklund Olesendcfe5f32010-02-23 22:43:58 +0000284 SlotIndex Start = getMBBStartIdx(Kill->getParent());
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000285 SlotIndex killIdx = getInstructionIndex(Kill).getRegSlot();
Jakob Stoklund Olesendcfe5f32010-02-23 22:43:58 +0000286
287 // Create interval with one of a NEW value number. Note that this value
288 // number isn't actually defined by an instruction, weird huh? :)
289 if (PHIJoin) {
Lang Hames6e2968c2010-09-25 12:04:16 +0000290 assert(getInstructionFromIndex(Start) == 0 &&
291 "PHI def index points at actual instruction.");
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +0000292 ValNo = interval.getNextValue(Start, VNInfoAllocator);
Jakob Stoklund Olesendcfe5f32010-02-23 22:43:58 +0000293 }
294 LiveRange LR(Start, killIdx, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000295 interval.addRange(LR);
David Greene8a342292010-01-04 22:49:02 +0000296 DEBUG(dbgs() << " +" << LR);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000297 }
298
299 } else {
Evan Cheng37499432010-05-05 18:27:40 +0000300 if (MultipleDefsBySameMI(*mi, MOIdx))
Nick Lewycky761fd4c2010-05-20 03:30:09 +0000301 // Multiple defs of the same virtual register by the same instruction.
302 // e.g. %reg1031:5<def>, %reg1031:6<def> = VLD1q16 %reg1024<kill>, ...
Evan Chengafff40a2010-05-04 20:26:52 +0000303 // This is likely due to elimination of REG_SEQUENCE instructions. Return
304 // here since there is nothing to do.
305 return;
306
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000307 // If this is the second time we see a virtual register definition, it
308 // must be due to phi elimination or two addr elimination. If this is
Evan Chengbf105c82006-11-03 03:04:46 +0000309 // the result of two address elimination, then the vreg is one of the
310 // def-and-use register operand.
Evan Cheng37499432010-05-05 18:27:40 +0000311
312 // It may also be partial redef like this:
Jakob Stoklund Olesen1b293202010-08-12 20:01:23 +0000313 // 80 %reg1041:6<def> = VSHRNv4i16 %reg1034<kill>, 12, pred:14, pred:%reg0
314 // 120 %reg1041:5<def> = VSHRNv4i16 %reg1039<kill>, 12, pred:14, pred:%reg0
Evan Cheng37499432010-05-05 18:27:40 +0000315 bool PartReDef = isPartialRedef(MIIdx, MO, interval);
316 if (PartReDef || mi->isRegTiedToUseOperand(MOIdx)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000317 // If this is a two-address definition, then we have already processed
318 // the live range. The only problem is that we didn't realize there
319 // are actually two values in the live interval. Because of this we
320 // need to take the LiveRegion that defines this register and split it
321 // into two values.
Jakob Stoklund Olesend14614e2011-11-13 22:05:42 +0000322 SlotIndex RedefIndex = MIIdx.getRegSlot(MO.isEarlyClobber());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000323
Lang Hames35f291d2009-09-12 03:34:03 +0000324 const LiveRange *OldLR =
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000325 interval.getLiveRangeContaining(RedefIndex.getRegSlot(true));
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000326 VNInfo *OldValNo = OldLR->valno;
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000327 SlotIndex DefIndex = OldValNo->def.getRegSlot();
Evan Cheng4f8ff162007-08-11 00:59:19 +0000328
Jakob Stoklund Olesenc66d0f22010-06-16 21:29:40 +0000329 // Delete the previous value, which should be short and continuous,
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000330 // because the 2-addr copy must be in the same MBB as the redef.
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000331 interval.removeRange(DefIndex, RedefIndex);
Alkis Evlogimenos70651572004-08-04 09:46:56 +0000332
Chris Lattner91725b72006-08-31 05:54:43 +0000333 // The new value number (#1) is defined by the instruction we claimed
334 // defined value #0.
Lang Hames6e2968c2010-09-25 12:04:16 +0000335 VNInfo *ValNo = interval.createValueCopy(OldValNo, VNInfoAllocator);
Lang Hames857c4e02009-06-17 21:01:20 +0000336
Chris Lattner91725b72006-08-31 05:54:43 +0000337 // Value#0 is now defined by the 2-addr instruction.
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +0000338 OldValNo->def = RedefIndex;
Jakob Stoklund Olesen1b293202010-08-12 20:01:23 +0000339
Chris Lattnerbe4f88a2006-08-22 18:19:46 +0000340 // Add the new live interval which replaces the range for the input copy.
341 LiveRange LR(DefIndex, RedefIndex, ValNo);
David Greene8a342292010-01-04 22:49:02 +0000342 DEBUG(dbgs() << " replace range with " << LR);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000343 interval.addRange(LR);
344
345 // If this redefinition is dead, we need to add a dummy unit live
346 // range covering the def slot.
Owen Anderson6b098de2008-06-25 23:39:39 +0000347 if (MO.isDead())
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000348 interval.addRange(LiveRange(RedefIndex, RedefIndex.getDeadSlot(),
Lang Hames233a60e2009-11-03 23:52:08 +0000349 OldValNo));
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000350
Jakob Stoklund Olesenb77ec7d2012-06-05 22:51:54 +0000351 DEBUG(dbgs() << " RESULT: " << interval);
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000352 } else if (LV->isPHIJoin(interval.reg)) {
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000353 // In the case of PHI elimination, each variable definition is only
354 // live until the end of the block. We've already taken care of the
355 // rest of the live range.
Jakob Stoklund Olesendcfe5f32010-02-23 22:43:58 +0000356
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000357 SlotIndex defIndex = MIIdx.getRegSlot();
Evan Chengfb112882009-03-23 08:01:15 +0000358 if (MO.isEarlyClobber())
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000359 defIndex = MIIdx.getRegSlot(true);
Evan Cheng752195e2009-09-14 21:33:42 +0000360
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +0000361 VNInfo *ValNo = interval.getNextValue(defIndex, VNInfoAllocator);
Jakob Stoklund Olesen1b293202010-08-12 20:01:23 +0000362
Lang Hames74ab5ee2009-12-22 00:11:50 +0000363 SlotIndex killIndex = getMBBEndIdx(mbb);
Evan Cheng7ecb38b2007-08-29 20:45:00 +0000364 LiveRange LR(defIndex, killIndex, ValNo);
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000365 interval.addRange(LR);
Jakob Stoklund Olesendcfe5f32010-02-23 22:43:58 +0000366 DEBUG(dbgs() << " phi-join +" << LR);
Evan Cheng37499432010-05-05 18:27:40 +0000367 } else {
368 llvm_unreachable("Multiply defined register");
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000369 }
370 }
371
David Greene8a342292010-01-04 22:49:02 +0000372 DEBUG(dbgs() << '\n');
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000373}
374
Chris Lattnerf35fef72004-07-23 21:24:19 +0000375void LiveIntervals::handleRegisterDef(MachineBasicBlock *MBB,
376 MachineBasicBlock::iterator MI,
Lang Hames233a60e2009-11-03 23:52:08 +0000377 SlotIndex MIIdx,
Evan Chengef0732d2008-07-10 07:35:43 +0000378 MachineOperand& MO,
379 unsigned MOIdx) {
Owen Anderson6b098de2008-06-25 23:39:39 +0000380 if (TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Evan Chengef0732d2008-07-10 07:35:43 +0000381 handleVirtualRegisterDef(MBB, MI, MIIdx, MO, MOIdx,
Owen Anderson6b098de2008-06-25 23:39:39 +0000382 getOrCreateInterval(MO.getReg()));
Evan Chengb371f452007-02-19 21:49:54 +0000383}
384
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000385/// computeIntervals - computes the live intervals for virtual
Alkis Evlogimenos4d46e1e2004-01-31 14:37:41 +0000386/// registers. for some ordering of the machine instructions [1,N] a
Alkis Evlogimenos08cec002004-01-31 19:59:32 +0000387/// live interval is an interval [i, j) where 1 <= i <= j < N for
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000388/// which a variable is live
Jakob Stoklund Olesen1b293202010-08-12 20:01:23 +0000389void LiveIntervals::computeIntervals() {
David Greene8a342292010-01-04 22:49:02 +0000390 DEBUG(dbgs() << "********** COMPUTING LIVE INTERVALS **********\n"
David Blaikie986d76d2012-08-22 17:18:53 +0000391 << "********** Function: " << MF->getName() << '\n');
Evan Chengd129d732009-07-17 19:43:40 +0000392
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000393 RegMaskBlocks.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesen34e85d02012-02-10 01:26:29 +0000394
Evan Chengd129d732009-07-17 19:43:40 +0000395 SmallVector<unsigned, 8> UndefUses;
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000396 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
Chris Lattner428b92e2006-09-15 03:57:23 +0000397 MBBI != E; ++MBBI) {
398 MachineBasicBlock *MBB = MBBI;
Jakob Stoklund Olesen34e85d02012-02-10 01:26:29 +0000399 RegMaskBlocks[MBB->getNumber()].first = RegMaskSlots.size();
400
Evan Cheng00a99a32010-02-06 09:07:11 +0000401 if (MBB->empty())
402 continue;
403
Owen Anderson134eb732008-09-21 20:43:24 +0000404 // Track the index of the current machine instr.
Lang Hames233a60e2009-11-03 23:52:08 +0000405 SlotIndex MIIndex = getMBBStartIdx(MBB);
Bob Wilsonad98f792010-05-03 21:38:11 +0000406 DEBUG(dbgs() << "BB#" << MBB->getNumber()
407 << ":\t\t# derived from " << MBB->getName() << "\n");
Alkis Evlogimenos6b4edba2003-12-21 20:19:10 +0000408
Owen Anderson99500ae2008-09-15 22:00:38 +0000409 // Skip over empty initial indices.
Lang Hames233a60e2009-11-03 23:52:08 +0000410 if (getInstructionFromIndex(MIIndex) == 0)
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000411 MIIndex = Indexes->getNextNonNullIndex(MIIndex);
Jakob Stoklund Olesen1b293202010-08-12 20:01:23 +0000412
Dale Johannesen1caedd02010-01-22 22:38:21 +0000413 for (MachineBasicBlock::iterator MI = MBB->begin(), miEnd = MBB->end();
414 MI != miEnd; ++MI) {
David Greene8a342292010-01-04 22:49:02 +0000415 DEBUG(dbgs() << MIIndex << "\t" << *MI);
Chris Lattner518bb532010-02-09 19:54:29 +0000416 if (MI->isDebugValue())
Dale Johannesen1caedd02010-01-22 22:38:21 +0000417 continue;
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000418 assert(Indexes->getInstructionFromIndex(MIIndex) == MI &&
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000419 "Lost SlotIndex synchronization");
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000420
Evan Cheng438f7bc2006-11-10 08:43:01 +0000421 // Handle defs.
Chris Lattner428b92e2006-09-15 03:57:23 +0000422 for (int i = MI->getNumOperands() - 1; i >= 0; --i) {
423 MachineOperand &MO = MI->getOperand(i);
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000424
425 // Collect register masks.
426 if (MO.isRegMask()) {
427 RegMaskSlots.push_back(MIIndex.getRegSlot());
428 RegMaskBits.push_back(MO.getRegMask());
429 continue;
430 }
431
Jakob Stoklund Olesen27b76692012-06-22 18:20:50 +0000432 if (!MO.isReg() || !TargetRegisterInfo::isVirtualRegister(MO.getReg()))
Evan Chengd129d732009-07-17 19:43:40 +0000433 continue;
434
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000435 // handle register defs - build intervals
Evan Chengd129d732009-07-17 19:43:40 +0000436 if (MO.isDef())
Evan Chengef0732d2008-07-10 07:35:43 +0000437 handleRegisterDef(MBB, MI, MIIndex, MO, i);
Evan Chengd129d732009-07-17 19:43:40 +0000438 else if (MO.isUndef())
439 UndefUses.push_back(MO.getReg());
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000440 }
Jakob Stoklund Olesen1b293202010-08-12 20:01:23 +0000441
Lang Hames233a60e2009-11-03 23:52:08 +0000442 // Move to the next instr slot.
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000443 MIIndex = Indexes->getNextNonNullIndex(MIIndex);
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000444 }
Jakob Stoklund Olesen34e85d02012-02-10 01:26:29 +0000445
446 // Compute the number of register mask instructions in this block.
447 std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB->getNumber()];
Dmitri Gribenko2de05722012-09-10 21:26:47 +0000448 RMB.second = RegMaskSlots.size() - RMB.first;
Alkis Evlogimenos1a8ea012004-08-04 09:46:26 +0000449 }
Evan Chengd129d732009-07-17 19:43:40 +0000450
451 // Create empty intervals for registers defined by implicit_def's (except
452 // for those implicit_def that define values which are liveout of their
453 // blocks.
454 for (unsigned i = 0, e = UndefUses.size(); i != e; ++i) {
455 unsigned UndefReg = UndefUses[i];
456 (void)getOrCreateInterval(UndefReg);
457 }
Alkis Evlogimenosff0cbe12003-11-20 03:32:25 +0000458}
Alkis Evlogimenosb27ef242003-12-05 10:38:28 +0000459
Owen Anderson03857b22008-08-13 21:49:13 +0000460LiveInterval* LiveIntervals::createInterval(unsigned reg) {
Evan Cheng0a1fcce2009-02-08 11:04:35 +0000461 float Weight = TargetRegisterInfo::isPhysicalRegister(reg) ? HUGE_VALF : 0.0F;
Owen Anderson03857b22008-08-13 21:49:13 +0000462 return new LiveInterval(reg, Weight);
Alkis Evlogimenos9a8b4902004-04-09 18:07:57 +0000463}
Evan Chengf2fbca62007-11-12 06:35:08 +0000464
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000465
Jakob Stoklund Olesen3dfa38a2012-07-27 20:58:46 +0000466/// computeVirtRegInterval - Compute the live interval of a virtual register,
467/// based on defs and uses.
468void LiveIntervals::computeVirtRegInterval(LiveInterval *LI) {
469 assert(LRCalc && "LRCalc not initialized.");
470 assert(LI->empty() && "Should only compute empty intervals.");
471 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
472 LRCalc->createDeadDefs(LI);
473 LRCalc->extendToUses(LI);
474}
475
Jakob Stoklund Olesenc16bf792012-07-27 21:56:39 +0000476void LiveIntervals::computeVirtRegs() {
477 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
478 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
479 if (MRI->reg_nodbg_empty(Reg))
480 continue;
481 LiveInterval *LI = createInterval(Reg);
482 VirtRegIntervals[Reg] = LI;
483 computeVirtRegInterval(LI);
484 }
485}
486
487void LiveIntervals::computeRegMasks() {
488 RegMaskBlocks.resize(MF->getNumBlockIDs());
489
490 // Find all instructions with regmask operands.
491 for (MachineFunction::iterator MBBI = MF->begin(), E = MF->end();
492 MBBI != E; ++MBBI) {
493 MachineBasicBlock *MBB = MBBI;
494 std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB->getNumber()];
495 RMB.first = RegMaskSlots.size();
496 for (MachineBasicBlock::iterator MI = MBB->begin(), ME = MBB->end();
497 MI != ME; ++MI)
498 for (MIOperands MO(MI); MO.isValid(); ++MO) {
499 if (!MO->isRegMask())
500 continue;
501 RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
502 RegMaskBits.push_back(MO->getRegMask());
503 }
504 // Compute the number of register mask instructions in this block.
Dmitri Gribenko2de05722012-09-10 21:26:47 +0000505 RMB.second = RegMaskSlots.size() - RMB.first;
Jakob Stoklund Olesenc16bf792012-07-27 21:56:39 +0000506 }
507}
Jakob Stoklund Olesen3dfa38a2012-07-27 20:58:46 +0000508
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000509//===----------------------------------------------------------------------===//
510// Register Unit Liveness
511//===----------------------------------------------------------------------===//
512//
513// Fixed interference typically comes from ABI boundaries: Function arguments
514// and return values are passed in fixed registers, and so are exception
515// pointers entering landing pads. Certain instructions require values to be
516// present in specific registers. That is also represented through fixed
517// interference.
518//
519
520/// computeRegUnitInterval - Compute the live interval of a register unit, based
521/// on the uses and defs of aliasing registers. The interval should be empty,
522/// or contain only dead phi-defs from ABI blocks.
523void LiveIntervals::computeRegUnitInterval(LiveInterval *LI) {
524 unsigned Unit = LI->reg;
525
526 assert(LRCalc && "LRCalc not initialized.");
527 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
528
529 // The physregs aliasing Unit are the roots and their super-registers.
530 // Create all values as dead defs before extending to uses. Note that roots
531 // may share super-registers. That's OK because createDeadDefs() is
532 // idempotent. It is very rare for a register unit to have multiple roots, so
533 // uniquing super-registers is probably not worthwhile.
534 for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
535 unsigned Root = *Roots;
536 if (!MRI->reg_empty(Root))
537 LRCalc->createDeadDefs(LI, Root);
538 for (MCSuperRegIterator Supers(Root, TRI); Supers.isValid(); ++Supers) {
539 if (!MRI->reg_empty(*Supers))
540 LRCalc->createDeadDefs(LI, *Supers);
541 }
542 }
543
544 // Now extend LI to reach all uses.
545 // Ignore uses of reserved registers. We only track defs of those.
546 for (MCRegUnitRootIterator Roots(Unit, TRI); Roots.isValid(); ++Roots) {
547 unsigned Root = *Roots;
Jakob Stoklund Olesen79004762012-10-15 22:14:34 +0000548 if (!MRI->isReserved(Root) && !MRI->reg_empty(Root))
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000549 LRCalc->extendToUses(LI, Root);
550 for (MCSuperRegIterator Supers(Root, TRI); Supers.isValid(); ++Supers) {
551 unsigned Reg = *Supers;
Jakob Stoklund Olesen79004762012-10-15 22:14:34 +0000552 if (!MRI->isReserved(Reg) && !MRI->reg_empty(Reg))
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000553 LRCalc->extendToUses(LI, Reg);
554 }
555 }
556}
557
558
559/// computeLiveInRegUnits - Precompute the live ranges of any register units
560/// that are live-in to an ABI block somewhere. Register values can appear
561/// without a corresponding def when entering the entry block or a landing pad.
562///
563void LiveIntervals::computeLiveInRegUnits() {
564 RegUnitIntervals.resize(TRI->getNumRegUnits());
565 DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
566
567 // Keep track of the intervals allocated.
568 SmallVector<LiveInterval*, 8> NewIntvs;
569
570 // Check all basic blocks for live-ins.
571 for (MachineFunction::const_iterator MFI = MF->begin(), MFE = MF->end();
572 MFI != MFE; ++MFI) {
573 const MachineBasicBlock *MBB = MFI;
574
575 // We only care about ABI blocks: Entry + landing pads.
576 if ((MFI != MF->begin() && !MBB->isLandingPad()) || MBB->livein_empty())
577 continue;
578
579 // Create phi-defs at Begin for all live-in registers.
580 SlotIndex Begin = Indexes->getMBBStartIdx(MBB);
581 DEBUG(dbgs() << Begin << "\tBB#" << MBB->getNumber());
582 for (MachineBasicBlock::livein_iterator LII = MBB->livein_begin(),
583 LIE = MBB->livein_end(); LII != LIE; ++LII) {
584 for (MCRegUnitIterator Units(*LII, TRI); Units.isValid(); ++Units) {
585 unsigned Unit = *Units;
586 LiveInterval *Intv = RegUnitIntervals[Unit];
587 if (!Intv) {
588 Intv = RegUnitIntervals[Unit] = new LiveInterval(Unit, HUGE_VALF);
589 NewIntvs.push_back(Intv);
590 }
591 VNInfo *VNI = Intv->createDeadDef(Begin, getVNInfoAllocator());
Matt Beaumont-Gay05b46f02012-06-05 23:00:03 +0000592 (void)VNI;
Jakob Stoklund Olesen34c6f982012-06-05 22:02:15 +0000593 DEBUG(dbgs() << ' ' << PrintRegUnit(Unit, TRI) << '#' << VNI->id);
594 }
595 }
596 DEBUG(dbgs() << '\n');
597 }
598 DEBUG(dbgs() << "Created " << NewIntvs.size() << " new intervals.\n");
599
600 // Compute the 'normal' part of the intervals.
601 for (unsigned i = 0, e = NewIntvs.size(); i != e; ++i)
602 computeRegUnitInterval(NewIntvs[i]);
603}
604
605
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000606/// shrinkToUses - After removing some uses of a register, shrink its live
607/// range to just the remaining uses. This method does not compute reaching
608/// defs for new uses, and it doesn't remove dead defs.
Jakob Stoklund Olesen6a3dbd32011-03-17 20:37:07 +0000609bool LiveIntervals::shrinkToUses(LiveInterval *li,
Jakob Stoklund Olesen0d8ccaa2011-03-07 23:29:10 +0000610 SmallVectorImpl<MachineInstr*> *dead) {
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000611 DEBUG(dbgs() << "Shrink: " << *li << '\n');
612 assert(TargetRegisterInfo::isVirtualRegister(li->reg)
Lang Hames567cdba2012-01-03 20:05:57 +0000613 && "Can only shrink virtual registers");
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000614 // Find all the values used, including PHI kills.
615 SmallVector<std::pair<SlotIndex, VNInfo*>, 16> WorkList;
616
Jakob Stoklund Olesen031432f2011-09-15 15:24:16 +0000617 // Blocks that have already been added to WorkList as live-out.
618 SmallPtrSet<MachineBasicBlock*, 16> LiveOut;
619
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000620 // Visit all instructions reading li->reg.
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000621 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(li->reg);
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000622 MachineInstr *UseMI = I.skipInstruction();) {
623 if (UseMI->isDebugValue() || !UseMI->readsVirtualRegister(li->reg))
624 continue;
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000625 SlotIndex Idx = getInstructionIndex(UseMI).getRegSlot();
Jakob Stoklund Olesen97769fc2012-05-20 02:54:52 +0000626 LiveRangeQuery LRQ(*li, Idx);
627 VNInfo *VNI = LRQ.valueIn();
Jakob Stoklund Olesen9ef931e2011-03-18 03:06:04 +0000628 if (!VNI) {
629 // This shouldn't happen: readsVirtualRegister returns true, but there is
630 // no live value. It is likely caused by a target getting <undef> flags
631 // wrong.
632 DEBUG(dbgs() << Idx << '\t' << *UseMI
633 << "Warning: Instr claims to read non-existent value in "
634 << *li << '\n');
635 continue;
636 }
Jakob Stoklund Olesenf054e192011-11-14 18:45:38 +0000637 // Special case: An early-clobber tied operand reads and writes the
Jakob Stoklund Olesen97769fc2012-05-20 02:54:52 +0000638 // register one slot early.
639 if (VNInfo *DefVNI = LRQ.valueDefined())
640 Idx = DefVNI->def;
641
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000642 WorkList.push_back(std::make_pair(Idx, VNI));
643 }
644
645 // Create a new live interval with only minimal live segments per def.
646 LiveInterval NewLI(li->reg, 0);
647 for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
648 I != E; ++I) {
649 VNInfo *VNI = *I;
650 if (VNI->isUnused())
651 continue;
Jakob Stoklund Olesen1f81e312011-11-13 22:42:13 +0000652 NewLI.addRange(LiveRange(VNI->def, VNI->def.getDeadSlot(), VNI));
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000653 }
654
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000655 // Keep track of the PHIs that are in use.
656 SmallPtrSet<VNInfo*, 8> UsedPHIs;
657
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000658 // Extend intervals to reach all uses in WorkList.
659 while (!WorkList.empty()) {
660 SlotIndex Idx = WorkList.back().first;
661 VNInfo *VNI = WorkList.back().second;
662 WorkList.pop_back();
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000663 const MachineBasicBlock *MBB = getMBBFromIndex(Idx.getPrevSlot());
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000664 SlotIndex BlockStart = getMBBStartIdx(MBB);
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000665
666 // Extend the live range for VNI to be live at Idx.
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000667 if (VNInfo *ExtVNI = NewLI.extendInBlock(BlockStart, Idx)) {
Nick Lewycky4b11a702011-03-02 01:43:30 +0000668 (void)ExtVNI;
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000669 assert(ExtVNI == VNI && "Unexpected existing value number");
670 // Is this a PHIDef we haven't seen before?
Jakob Stoklund Olesenc29d9b32011-03-03 00:20:51 +0000671 if (!VNI->isPHIDef() || VNI->def != BlockStart || !UsedPHIs.insert(VNI))
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000672 continue;
673 // The PHI is live, make sure the predecessors are live-out.
674 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
675 PE = MBB->pred_end(); PI != PE; ++PI) {
Jakob Stoklund Olesen031432f2011-09-15 15:24:16 +0000676 if (!LiveOut.insert(*PI))
677 continue;
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000678 SlotIndex Stop = getMBBEndIdx(*PI);
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000679 // A predecessor is not required to have a live-out value for a PHI.
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000680 if (VNInfo *PVNI = li->getVNInfoBefore(Stop))
Jakob Stoklund Olesene0ab2452011-03-02 00:33:03 +0000681 WorkList.push_back(std::make_pair(Stop, PVNI));
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000682 }
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000683 continue;
684 }
685
686 // VNI is live-in to MBB.
687 DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000688 NewLI.addRange(LiveRange(BlockStart, Idx, VNI));
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000689
690 // Make sure VNI is live-out from the predecessors.
691 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(),
692 PE = MBB->pred_end(); PI != PE; ++PI) {
Jakob Stoklund Olesen031432f2011-09-15 15:24:16 +0000693 if (!LiveOut.insert(*PI))
694 continue;
Jakob Stoklund Olesen6c9cc212011-11-13 23:53:25 +0000695 SlotIndex Stop = getMBBEndIdx(*PI);
696 assert(li->getVNInfoBefore(Stop) == VNI &&
697 "Wrong value out of predecessor");
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000698 WorkList.push_back(std::make_pair(Stop, VNI));
699 }
700 }
701
702 // Handle dead values.
Jakob Stoklund Olesen6a3dbd32011-03-17 20:37:07 +0000703 bool CanSeparate = false;
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000704 for (LiveInterval::vni_iterator I = li->vni_begin(), E = li->vni_end();
705 I != E; ++I) {
706 VNInfo *VNI = *I;
707 if (VNI->isUnused())
708 continue;
709 LiveInterval::iterator LII = NewLI.FindLiveRangeContaining(VNI->def);
710 assert(LII != NewLI.end() && "Missing live range for PHI");
Jakob Stoklund Olesen1f81e312011-11-13 22:42:13 +0000711 if (LII->end != VNI->def.getDeadSlot())
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000712 continue;
Jakob Stoklund Olesena4d34732011-03-02 00:33:01 +0000713 if (VNI->isPHIDef()) {
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000714 // This is a dead PHI. Remove it.
Jakob Stoklund Olesenb2beac22012-08-03 20:59:32 +0000715 VNI->markUnused();
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000716 NewLI.removeRange(*LII);
Jakob Stoklund Olesen6a3dbd32011-03-17 20:37:07 +0000717 DEBUG(dbgs() << "Dead PHI at " << VNI->def << " may separate interval\n");
718 CanSeparate = true;
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000719 } else {
720 // This is a dead def. Make sure the instruction knows.
721 MachineInstr *MI = getInstructionFromIndex(VNI->def);
722 assert(MI && "No instruction defining live value");
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000723 MI->addRegisterDead(li->reg, TRI);
Jakob Stoklund Olesen0d8ccaa2011-03-07 23:29:10 +0000724 if (dead && MI->allDefsAreDead()) {
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +0000725 DEBUG(dbgs() << "All defs dead: " << VNI->def << '\t' << *MI);
Jakob Stoklund Olesen0d8ccaa2011-03-07 23:29:10 +0000726 dead->push_back(MI);
727 }
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000728 }
729 }
730
731 // Move the trimmed ranges back.
732 li->ranges.swap(NewLI.ranges);
Jakob Stoklund Olesenc46570d2011-03-16 22:56:08 +0000733 DEBUG(dbgs() << "Shrunk: " << *li << '\n');
Jakob Stoklund Olesen6a3dbd32011-03-17 20:37:07 +0000734 return CanSeparate;
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000735}
736
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000737void LiveIntervals::extendToIndices(LiveInterval *LI,
738 ArrayRef<SlotIndex> Indices) {
739 assert(LRCalc && "LRCalc not initialized.");
740 LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
741 for (unsigned i = 0, e = Indices.size(); i != e; ++i)
742 LRCalc->extend(LI, Indices[i]);
743}
744
745void LiveIntervals::pruneValue(LiveInterval *LI, SlotIndex Kill,
746 SmallVectorImpl<SlotIndex> *EndPoints) {
747 LiveRangeQuery LRQ(*LI, Kill);
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000748 VNInfo *VNI = LRQ.valueOut();
749 if (!VNI)
750 return;
751
752 MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
753 SlotIndex MBBStart, MBBEnd;
754 tie(MBBStart, MBBEnd) = Indexes->getMBBRange(KillMBB);
755
756 // If VNI isn't live out from KillMBB, the value is trivially pruned.
757 if (LRQ.endPoint() < MBBEnd) {
758 LI->removeRange(Kill, LRQ.endPoint());
759 if (EndPoints) EndPoints->push_back(LRQ.endPoint());
760 return;
761 }
762
763 // VNI is live out of KillMBB.
764 LI->removeRange(Kill, MBBEnd);
765 if (EndPoints) EndPoints->push_back(MBBEnd);
766
Jakob Stoklund Olesenaf896902012-10-13 16:15:31 +0000767 // Find all blocks that are reachable from KillMBB without leaving VNI's live
768 // range. It is possible that KillMBB itself is reachable, so start a DFS
769 // from each successor.
770 typedef SmallPtrSet<MachineBasicBlock*, 9> VisitedTy;
771 VisitedTy Visited;
772 for (MachineBasicBlock::succ_iterator
773 SuccI = KillMBB->succ_begin(), SuccE = KillMBB->succ_end();
774 SuccI != SuccE; ++SuccI) {
775 for (df_ext_iterator<MachineBasicBlock*, VisitedTy>
776 I = df_ext_begin(*SuccI, Visited), E = df_ext_end(*SuccI, Visited);
777 I != E;) {
778 MachineBasicBlock *MBB = *I;
779
780 // Check if VNI is live in to MBB.
781 tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
782 LiveRangeQuery LRQ(*LI, MBBStart);
783 if (LRQ.valueIn() != VNI) {
784 // This block isn't part of the VNI live range. Prune the search.
785 I.skipChildren();
786 continue;
787 }
788
789 // Prune the search if VNI is killed in MBB.
790 if (LRQ.endPoint() < MBBEnd) {
791 LI->removeRange(MBBStart, LRQ.endPoint());
792 if (EndPoints) EndPoints->push_back(LRQ.endPoint());
793 I.skipChildren();
794 continue;
795 }
796
797 // VNI is live through MBB.
798 LI->removeRange(MBBStart, MBBEnd);
799 if (EndPoints) EndPoints->push_back(MBBEnd);
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000800 ++I;
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000801 }
Jakob Stoklund Olesen87f78642012-09-17 23:03:25 +0000802 }
803}
Jakob Stoklund Olesen11513e52011-02-08 00:03:05 +0000804
Evan Chengf2fbca62007-11-12 06:35:08 +0000805//===----------------------------------------------------------------------===//
806// Register allocator hooks.
807//
808
Jakob Stoklund Olesene617ccb2012-09-06 18:15:18 +0000809void LiveIntervals::addKillFlags(const VirtRegMap *VRM) {
810 // Keep track of regunit ranges.
811 SmallVector<std::pair<LiveInterval*, LiveInterval::iterator>, 8> RU;
812
Jakob Stoklund Olesen12a7be92012-06-20 23:23:59 +0000813 for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
814 unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000815 if (MRI->reg_nodbg_empty(Reg))
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +0000816 continue;
Jakob Stoklund Olesen12a7be92012-06-20 23:23:59 +0000817 LiveInterval *LI = &getInterval(Reg);
Jakob Stoklund Olesene617ccb2012-09-06 18:15:18 +0000818 if (LI->empty())
819 continue;
820
821 // Find the regunit intervals for the assigned register. They may overlap
822 // the virtual register live range, cancelling any kills.
823 RU.clear();
824 for (MCRegUnitIterator Units(VRM->getPhys(Reg), TRI); Units.isValid();
825 ++Units) {
826 LiveInterval *RUInt = &getRegUnit(*Units);
827 if (RUInt->empty())
828 continue;
829 RU.push_back(std::make_pair(RUInt, RUInt->find(LI->begin()->end)));
830 }
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +0000831
832 // Every instruction that kills Reg corresponds to a live range end point.
833 for (LiveInterval::iterator RI = LI->begin(), RE = LI->end(); RI != RE;
834 ++RI) {
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000835 // A block index indicates an MBB edge.
836 if (RI->end.isBlock())
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +0000837 continue;
838 MachineInstr *MI = getInstructionFromIndex(RI->end);
839 if (!MI)
840 continue;
Jakob Stoklund Olesene617ccb2012-09-06 18:15:18 +0000841
842 // Check if any of the reguints are live beyond the end of RI. That could
843 // happen when a physreg is defined as a copy of a virtreg:
844 //
845 // %EAX = COPY %vreg5
846 // FOO %vreg5 <--- MI, cancel kill because %EAX is live.
847 // BAR %EAX<kill>
848 //
849 // There should be no kill flag on FOO when %vreg5 is rewritten as %EAX.
850 bool CancelKill = false;
851 for (unsigned u = 0, e = RU.size(); u != e; ++u) {
852 LiveInterval *RInt = RU[u].first;
853 LiveInterval::iterator &I = RU[u].second;
854 if (I == RInt->end())
855 continue;
856 I = RInt->advanceTo(I, RI->end);
857 if (I == RInt->end() || I->start >= RI->end)
858 continue;
859 // I is overlapping RI.
860 CancelKill = true;
861 break;
862 }
863 if (CancelKill)
864 MI->clearRegisterKills(Reg, NULL);
865 else
866 MI->addRegisterKilled(Reg, NULL);
Jakob Stoklund Olesen8a61da82011-02-08 21:13:03 +0000867 }
868 }
869}
870
Jakob Stoklund Olesenebf27502012-02-10 01:23:55 +0000871MachineBasicBlock*
872LiveIntervals::intervalIsInOneMBB(const LiveInterval &LI) const {
873 // A local live range must be fully contained inside the block, meaning it is
874 // defined and killed at instructions, not at block boundaries. It is not
875 // live in or or out of any block.
876 //
877 // It is technically possible to have a PHI-defined live range identical to a
878 // single block, but we are going to return false in that case.
Lang Hames233a60e2009-11-03 23:52:08 +0000879
Jakob Stoklund Olesenebf27502012-02-10 01:23:55 +0000880 SlotIndex Start = LI.beginIndex();
881 if (Start.isBlock())
882 return NULL;
Lang Hames233a60e2009-11-03 23:52:08 +0000883
Jakob Stoklund Olesenebf27502012-02-10 01:23:55 +0000884 SlotIndex Stop = LI.endIndex();
885 if (Stop.isBlock())
886 return NULL;
Lang Hames233a60e2009-11-03 23:52:08 +0000887
Jakob Stoklund Olesenebf27502012-02-10 01:23:55 +0000888 // getMBBFromIndex doesn't need to search the MBB table when both indexes
889 // belong to proper instructions.
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000890 MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
891 MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
Jakob Stoklund Olesenebf27502012-02-10 01:23:55 +0000892 return MBB1 == MBB2 ? MBB1 : NULL;
Evan Cheng81a03822007-11-17 00:40:40 +0000893}
894
Jakob Stoklund Olesen0ab71032012-08-03 20:10:24 +0000895bool
896LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
897 for (LiveInterval::const_vni_iterator I = LI.vni_begin(), E = LI.vni_end();
898 I != E; ++I) {
899 const VNInfo *PHI = *I;
900 if (PHI->isUnused() || !PHI->isPHIDef())
901 continue;
902 const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
903 // Conservatively return true instead of scanning huge predecessor lists.
904 if (PHIMBB->pred_size() > 100)
905 return true;
906 for (MachineBasicBlock::const_pred_iterator
907 PI = PHIMBB->pred_begin(), PE = PHIMBB->pred_end(); PI != PE; ++PI)
908 if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(*PI)))
909 return true;
910 }
911 return false;
912}
913
Jakob Stoklund Olesene5d90412010-03-01 20:59:38 +0000914float
915LiveIntervals::getSpillWeight(bool isDef, bool isUse, unsigned loopDepth) {
916 // Limit the loop depth ridiculousness.
917 if (loopDepth > 200)
918 loopDepth = 200;
919
920 // The loop depth is used to roughly estimate the number of times the
921 // instruction is executed. Something like 10^d is simple, but will quickly
922 // overflow a float. This expression behaves like 10^d for small d, but is
923 // more tempered for large d. At d=200 we get 6.7e33 which leaves a bit of
924 // headroom before overflow.
NAKAMURA Takumidc5198b2011-03-31 12:11:33 +0000925 // By the way, powf() might be unavailable here. For consistency,
926 // We may take pow(double,double).
927 float lc = std::pow(1 + (100.0 / (loopDepth + 10)), (double)loopDepth);
Jakob Stoklund Olesene5d90412010-03-01 20:59:38 +0000928
929 return (isDef + isUse) * lc;
930}
931
Owen Andersonc4dc1322008-06-05 17:15:43 +0000932LiveRange LiveIntervals::addLiveRangeToEndOfBlock(unsigned reg,
Lang Hamesffd13262009-07-09 03:57:02 +0000933 MachineInstr* startInst) {
Owen Andersonc4dc1322008-06-05 17:15:43 +0000934 LiveInterval& Interval = getOrCreateInterval(reg);
935 VNInfo* VN = Interval.getNextValue(
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000936 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
Jakob Stoklund Olesen3b1088a2012-02-04 05:20:49 +0000937 getVNInfoAllocator());
Lang Hames86511252009-09-04 20:41:11 +0000938 LiveRange LR(
Jakob Stoklund Olesen2debd482011-11-13 20:45:27 +0000939 SlotIndex(getInstructionIndex(startInst).getRegSlot()),
Lang Hames74ab5ee2009-12-22 00:11:50 +0000940 getMBBEndIdx(startInst->getParent()), VN);
Owen Andersonc4dc1322008-06-05 17:15:43 +0000941 Interval.addRange(LR);
Jakob Stoklund Olesen1b293202010-08-12 20:01:23 +0000942
Owen Andersonc4dc1322008-06-05 17:15:43 +0000943 return LR;
944}
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000945
946
947//===----------------------------------------------------------------------===//
948// Register mask functions
949//===----------------------------------------------------------------------===//
950
951bool LiveIntervals::checkRegMaskInterference(LiveInterval &LI,
952 BitVector &UsableRegs) {
953 if (LI.empty())
954 return false;
Jakob Stoklund Olesen9f10ac62012-02-10 01:31:31 +0000955 LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
956
957 // Use a smaller arrays for local live ranges.
958 ArrayRef<SlotIndex> Slots;
959 ArrayRef<const uint32_t*> Bits;
960 if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
961 Slots = getRegMaskSlotsInBlock(MBB->getNumber());
962 Bits = getRegMaskBitsInBlock(MBB->getNumber());
963 } else {
964 Slots = getRegMaskSlots();
965 Bits = getRegMaskBits();
966 }
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000967
968 // We are going to enumerate all the register mask slots contained in LI.
969 // Start with a binary search of RegMaskSlots to find a starting point.
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000970 ArrayRef<SlotIndex>::iterator SlotI =
971 std::lower_bound(Slots.begin(), Slots.end(), LiveI->start);
972 ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
973
974 // No slots in range, LI begins after the last call.
975 if (SlotI == SlotE)
976 return false;
977
978 bool Found = false;
979 for (;;) {
980 assert(*SlotI >= LiveI->start);
981 // Loop over all slots overlapping this segment.
982 while (*SlotI < LiveI->end) {
983 // *SlotI overlaps LI. Collect mask bits.
984 if (!Found) {
985 // This is the first overlap. Initialize UsableRegs to all ones.
986 UsableRegs.clear();
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +0000987 UsableRegs.resize(TRI->getNumRegs(), true);
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000988 Found = true;
989 }
990 // Remove usable registers clobbered by this mask.
Jakob Stoklund Olesen9f10ac62012-02-10 01:31:31 +0000991 UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
Jakob Stoklund Olesen3fd3a842012-02-08 17:33:45 +0000992 if (++SlotI == SlotE)
993 return Found;
994 }
995 // *SlotI is beyond the current LI segment.
996 LiveI = LI.advanceTo(LiveI, *SlotI);
997 if (LiveI == LiveE)
998 return Found;
999 // Advance SlotI until it overlaps.
1000 while (*SlotI < LiveI->start)
1001 if (++SlotI == SlotE)
1002 return Found;
1003 }
1004}
Lang Hames3dc7c512012-02-17 18:44:18 +00001005
1006//===----------------------------------------------------------------------===//
1007// IntervalUpdate class.
1008//===----------------------------------------------------------------------===//
1009
Lang Hamesfd6d3212012-02-21 00:00:36 +00001010// HMEditor is a toolkit used by handleMove to trim or extend live intervals.
Lang Hames3dc7c512012-02-17 18:44:18 +00001011class LiveIntervals::HMEditor {
1012private:
Lang Hamesecb50622012-02-17 23:43:40 +00001013 LiveIntervals& LIS;
1014 const MachineRegisterInfo& MRI;
1015 const TargetRegisterInfo& TRI;
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001016 SlotIndex OldIdx;
Lang Hamesecb50622012-02-17 23:43:40 +00001017 SlotIndex NewIdx;
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001018 SmallPtrSet<LiveInterval*, 8> Updated;
Andrew Trick27c28ce2012-10-16 00:22:51 +00001019 bool UpdateFlags;
Lang Hames6aceab12012-02-19 07:13:05 +00001020
Lang Hames3dc7c512012-02-17 18:44:18 +00001021public:
Lang Hamesecb50622012-02-17 23:43:40 +00001022 HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001023 const TargetRegisterInfo& TRI,
Andrew Trick27c28ce2012-10-16 00:22:51 +00001024 SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
1025 : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
1026 UpdateFlags(UpdateFlags) {}
1027
1028 // FIXME: UpdateFlags is a workaround that creates live intervals for all
1029 // physregs, even those that aren't needed for regalloc, in order to update
1030 // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
1031 // flags, and postRA passes will use a live register utility instead.
1032 LiveInterval *getRegUnitLI(unsigned Unit) {
1033 if (UpdateFlags)
1034 return &LIS.getRegUnit(Unit);
1035 return LIS.getCachedRegUnit(Unit);
1036 }
Lang Hames3dc7c512012-02-17 18:44:18 +00001037
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001038 /// Update all live ranges touched by MI, assuming a move from OldIdx to
1039 /// NewIdx.
1040 void updateAllRanges(MachineInstr *MI) {
1041 DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": " << *MI);
1042 bool hasRegMask = false;
1043 for (MIOperands MO(MI); MO.isValid(); ++MO) {
1044 if (MO->isRegMask())
1045 hasRegMask = true;
1046 if (!MO->isReg())
Lang Hames4586d252012-02-21 22:29:38 +00001047 continue;
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001048 // Aggressively clear all kill flags.
1049 // They are reinserted by VirtRegRewriter.
1050 if (MO->isUse())
1051 MO->setIsKill(false);
1052
1053 unsigned Reg = MO->getReg();
1054 if (!Reg)
1055 continue;
1056 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1057 updateRange(LIS.getInterval(Reg));
1058 continue;
1059 }
1060
1061 // For physregs, only update the regunits that actually have a
1062 // precomputed live range.
1063 for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
Andrew Trick27c28ce2012-10-16 00:22:51 +00001064 if (LiveInterval *LI = getRegUnitLI(*Units))
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001065 updateRange(*LI);
Lang Hames4586d252012-02-21 22:29:38 +00001066 }
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001067 if (hasRegMask)
1068 updateRegMaskSlots();
Lang Hames6aceab12012-02-19 07:13:05 +00001069 }
1070
Lang Hames55fed622012-02-19 03:00:30 +00001071private:
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001072 /// Update a single live range, assuming an instruction has been moved from
1073 /// OldIdx to NewIdx.
1074 void updateRange(LiveInterval &LI) {
1075 if (!Updated.insert(&LI))
1076 return;
1077 DEBUG({
1078 dbgs() << " ";
1079 if (TargetRegisterInfo::isVirtualRegister(LI.reg))
1080 dbgs() << PrintReg(LI.reg);
Jakob Stoklund Olesenbf833f02012-06-19 23:50:18 +00001081 else
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001082 dbgs() << PrintRegUnit(LI.reg, &TRI);
1083 dbgs() << ":\t" << LI << '\n';
1084 });
1085 if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
1086 handleMoveDown(LI);
1087 else
1088 handleMoveUp(LI);
1089 DEBUG(dbgs() << " -->\t" << LI << '\n');
1090 LI.verify();
Lang Hames3dc7c512012-02-17 18:44:18 +00001091 }
1092
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001093 /// Update LI to reflect an instruction has been moved downwards from OldIdx
1094 /// to NewIdx.
1095 ///
1096 /// 1. Live def at OldIdx:
1097 /// Move def to NewIdx, assert endpoint after NewIdx.
1098 ///
1099 /// 2. Live def at OldIdx, killed at NewIdx:
1100 /// Change to dead def at NewIdx.
1101 /// (Happens when bundling def+kill together).
1102 ///
1103 /// 3. Dead def at OldIdx:
1104 /// Move def to NewIdx, possibly across another live value.
1105 ///
1106 /// 4. Def at OldIdx AND at NewIdx:
1107 /// Remove live range [OldIdx;NewIdx) and value defined at OldIdx.
1108 /// (Happens when bundling multiple defs together).
1109 ///
1110 /// 5. Value read at OldIdx, killed before NewIdx:
1111 /// Extend kill to NewIdx.
1112 ///
1113 void handleMoveDown(LiveInterval &LI) {
1114 // First look for a kill at OldIdx.
1115 LiveInterval::iterator I = LI.find(OldIdx.getBaseIndex());
1116 LiveInterval::iterator E = LI.end();
1117 // Is LI even live at OldIdx?
1118 if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
1119 return;
Lang Hames6aceab12012-02-19 07:13:05 +00001120
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001121 // Handle a live-in value.
1122 if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
1123 bool isKill = SlotIndex::isSameInstr(OldIdx, I->end);
1124 // If the live-in value already extends to NewIdx, there is nothing to do.
1125 if (!SlotIndex::isEarlierInstr(I->end, NewIdx))
1126 return;
1127 // Aggressively remove all kill flags from the old kill point.
1128 // Kill flags shouldn't be used while live intervals exist, they will be
1129 // reinserted by VirtRegRewriter.
1130 if (MachineInstr *KillMI = LIS.getInstructionFromIndex(I->end))
1131 for (MIBundleOperands MO(KillMI); MO.isValid(); ++MO)
1132 if (MO->isReg() && MO->isUse())
1133 MO->setIsKill(false);
1134 // Adjust I->end to reach NewIdx. This may temporarily make LI invalid by
1135 // overlapping ranges. Case 5 above.
1136 I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
1137 // If this was a kill, there may also be a def. Otherwise we're done.
1138 if (!isKill)
1139 return;
1140 ++I;
Lang Hames6aceab12012-02-19 07:13:05 +00001141 }
1142
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001143 // Check for a def at OldIdx.
1144 if (I == E || !SlotIndex::isSameInstr(OldIdx, I->start))
1145 return;
1146 // We have a def at OldIdx.
1147 VNInfo *DefVNI = I->valno;
1148 assert(DefVNI->def == I->start && "Inconsistent def");
1149 DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
1150 // If the defined value extends beyond NewIdx, just move the def down.
1151 // This is case 1 above.
1152 if (SlotIndex::isEarlierInstr(NewIdx, I->end)) {
1153 I->start = DefVNI->def;
1154 return;
1155 }
1156 // The remaining possibilities are now:
1157 // 2. Live def at OldIdx, killed at NewIdx: isSameInstr(I->end, NewIdx).
1158 // 3. Dead def at OldIdx: I->end = OldIdx.getDeadSlot().
1159 // In either case, it is possible that there is an existing def at NewIdx.
1160 assert((I->end == OldIdx.getDeadSlot() ||
1161 SlotIndex::isSameInstr(I->end, NewIdx)) &&
1162 "Cannot move def below kill");
1163 LiveInterval::iterator NewI = LI.advanceTo(I, NewIdx.getRegSlot());
1164 if (NewI != E && SlotIndex::isSameInstr(NewI->start, NewIdx)) {
1165 // There is an existing def at NewIdx, case 4 above. The def at OldIdx is
1166 // coalesced into that value.
1167 assert(NewI->valno != DefVNI && "Multiple defs of value?");
1168 LI.removeValNo(DefVNI);
1169 return;
1170 }
1171 // There was no existing def at NewIdx. Turn *I into a dead def at NewIdx.
1172 // If the def at OldIdx was dead, we allow it to be moved across other LI
1173 // values. The new range should be placed immediately before NewI, move any
1174 // intermediate ranges up.
1175 assert(NewI != I && "Inconsistent iterators");
1176 std::copy(llvm::next(I), NewI, I);
1177 *llvm::prior(NewI) = LiveRange(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
1178 }
1179
1180 /// Update LI to reflect an instruction has been moved upwards from OldIdx
1181 /// to NewIdx.
1182 ///
1183 /// 1. Live def at OldIdx:
1184 /// Hoist def to NewIdx.
1185 ///
1186 /// 2. Dead def at OldIdx:
1187 /// Hoist def+end to NewIdx, possibly move across other values.
1188 ///
1189 /// 3. Dead def at OldIdx AND existing def at NewIdx:
1190 /// Remove value defined at OldIdx, coalescing it with existing value.
1191 ///
1192 /// 4. Live def at OldIdx AND existing def at NewIdx:
1193 /// Remove value defined at NewIdx, hoist OldIdx def to NewIdx.
1194 /// (Happens when bundling multiple defs together).
1195 ///
1196 /// 5. Value killed at OldIdx:
1197 /// Hoist kill to NewIdx, then scan for last kill between NewIdx and
1198 /// OldIdx.
1199 ///
1200 void handleMoveUp(LiveInterval &LI) {
1201 // First look for a kill at OldIdx.
1202 LiveInterval::iterator I = LI.find(OldIdx.getBaseIndex());
1203 LiveInterval::iterator E = LI.end();
1204 // Is LI even live at OldIdx?
1205 if (I == E || SlotIndex::isEarlierInstr(OldIdx, I->start))
1206 return;
1207
1208 // Handle a live-in value.
1209 if (!SlotIndex::isSameInstr(I->start, OldIdx)) {
1210 // If the live-in value isn't killed here, there is nothing to do.
1211 if (!SlotIndex::isSameInstr(OldIdx, I->end))
1212 return;
1213 // Adjust I->end to end at NewIdx. If we are hoisting a kill above
1214 // another use, we need to search for that use. Case 5 above.
1215 I->end = NewIdx.getRegSlot(I->end.isEarlyClobber());
1216 ++I;
1217 // If OldIdx also defines a value, there couldn't have been another use.
1218 if (I == E || !SlotIndex::isSameInstr(I->start, OldIdx)) {
1219 // No def, search for the new kill.
1220 // This can never be an early clobber kill since there is no def.
1221 llvm::prior(I)->end = findLastUseBefore(LI.reg).getRegSlot();
1222 return;
Lang Hames6aceab12012-02-19 07:13:05 +00001223 }
1224 }
1225
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001226 // Now deal with the def at OldIdx.
1227 assert(I != E && SlotIndex::isSameInstr(I->start, OldIdx) && "No def?");
1228 VNInfo *DefVNI = I->valno;
1229 assert(DefVNI->def == I->start && "Inconsistent def");
1230 DefVNI->def = NewIdx.getRegSlot(I->start.isEarlyClobber());
1231
1232 // Check for an existing def at NewIdx.
1233 LiveInterval::iterator NewI = LI.find(NewIdx.getRegSlot());
1234 if (SlotIndex::isSameInstr(NewI->start, NewIdx)) {
1235 assert(NewI->valno != DefVNI && "Same value defined more than once?");
1236 // There is an existing def at NewIdx.
1237 if (I->end.isDead()) {
1238 // Case 3: Remove the dead def at OldIdx.
1239 LI.removeValNo(DefVNI);
1240 return;
1241 }
1242 // Case 4: Replace def at NewIdx with live def at OldIdx.
1243 I->start = DefVNI->def;
1244 LI.removeValNo(NewI->valno);
1245 return;
Lang Hames6aceab12012-02-19 07:13:05 +00001246 }
1247
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001248 // There is no existing def at NewIdx. Hoist DefVNI.
1249 if (!I->end.isDead()) {
1250 // Leave the end point of a live def.
1251 I->start = DefVNI->def;
1252 return;
1253 }
1254
1255 // DefVNI is a dead def. It may have been moved across other values in LI,
1256 // so move I up to NewI. Slide [NewI;I) down one position.
1257 std::copy_backward(NewI, I, llvm::next(I));
1258 *NewI = LiveRange(DefVNI->def, NewIdx.getDeadSlot(), DefVNI);
Lang Hames6aceab12012-02-19 07:13:05 +00001259 }
1260
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001261 void updateRegMaskSlots() {
Lang Hamesecb50622012-02-17 23:43:40 +00001262 SmallVectorImpl<SlotIndex>::iterator RI =
1263 std::lower_bound(LIS.RegMaskSlots.begin(), LIS.RegMaskSlots.end(),
1264 OldIdx);
Jakob Stoklund Olesen722c9a72012-11-09 19:18:49 +00001265 assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
1266 "No RegMask at OldIdx.");
1267 *RI = NewIdx.getRegSlot();
1268 assert((RI == LIS.RegMaskSlots.begin() ||
1269 SlotIndex::isEarlierInstr(*llvm::prior(RI), *RI)) &&
1270 "Cannot move regmask instruction above another call");
1271 assert((llvm::next(RI) == LIS.RegMaskSlots.end() ||
1272 SlotIndex::isEarlierInstr(*RI, *llvm::next(RI))) &&
1273 "Cannot move regmask instruction below another call");
Lang Hamesfbc8dd32012-02-17 21:29:41 +00001274 }
Lang Hames55fed622012-02-19 03:00:30 +00001275
1276 // Return the last use of reg between NewIdx and OldIdx.
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001277 SlotIndex findLastUseBefore(unsigned Reg) {
Lang Hames55fed622012-02-19 03:00:30 +00001278 SlotIndex LastUse = NewIdx;
Lang Hames6d742cc2012-09-12 06:56:16 +00001279
1280 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
1281 for (MachineRegisterInfo::use_nodbg_iterator
1282 UI = MRI.use_nodbg_begin(Reg),
1283 UE = MRI.use_nodbg_end();
1284 UI != UE; UI.skipInstruction()) {
1285 const MachineInstr* MI = &*UI;
1286 SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
1287 if (InstSlot > LastUse && InstSlot < OldIdx)
1288 LastUse = InstSlot;
1289 }
1290 } else {
1291 MachineInstr* MI = LIS.getSlotIndexes()->getInstructionFromIndex(NewIdx);
1292 MachineBasicBlock::iterator MII(MI);
1293 ++MII;
1294 MachineBasicBlock* MBB = MI->getParent();
Andrew Trick30fe61a2012-12-01 01:22:41 +00001295 for (; MII != MBB->end(); ++MII){
1296 if (MII->isDebugValue())
1297 continue;
1298 if (LIS.getInstructionIndex(MII) < OldIdx)
1299 break;
Lang Hames6d742cc2012-09-12 06:56:16 +00001300 for (MachineInstr::mop_iterator MOI = MII->operands_begin(),
1301 MOE = MII->operands_end();
1302 MOI != MOE; ++MOI) {
1303 const MachineOperand& mop = *MOI;
1304 if (!mop.isReg() || mop.getReg() == 0 ||
1305 TargetRegisterInfo::isVirtualRegister(mop.getReg()))
1306 continue;
1307
1308 if (TRI.hasRegUnit(mop.getReg(), Reg))
1309 LastUse = LIS.getInstructionIndex(MII);
1310 }
1311 }
Lang Hames55fed622012-02-19 03:00:30 +00001312 }
1313 return LastUse;
1314 }
Lang Hames3dc7c512012-02-17 18:44:18 +00001315};
1316
Andrew Trick27c28ce2012-10-16 00:22:51 +00001317void LiveIntervals::handleMove(MachineInstr* MI, bool UpdateFlags) {
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001318 assert(!MI->isBundled() && "Can't handle bundled instructions yet.");
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +00001319 SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1320 Indexes->removeMachineInstrFromMaps(MI);
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001321 SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
Lang Hamesecb50622012-02-17 23:43:40 +00001322 assert(getMBBStartIdx(MI->getParent()) <= OldIndex &&
1323 OldIndex < getMBBEndIdx(MI->getParent()) &&
Lang Hames3dc7c512012-02-17 18:44:18 +00001324 "Cannot handle moves across basic block boundaries.");
Lang Hames3dc7c512012-02-17 18:44:18 +00001325
Andrew Trick27c28ce2012-10-16 00:22:51 +00001326 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001327 HME.updateAllRanges(MI);
Lang Hames4586d252012-02-21 22:29:38 +00001328}
1329
Jakob Stoklund Olesenfa8becb2012-06-19 22:50:53 +00001330void LiveIntervals::handleMoveIntoBundle(MachineInstr* MI,
Andrew Trick27c28ce2012-10-16 00:22:51 +00001331 MachineInstr* BundleStart,
1332 bool UpdateFlags) {
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001333 SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
Jakob Stoklund Olesen15f1d8c2012-06-04 22:39:14 +00001334 SlotIndex NewIndex = Indexes->getInstructionIndex(BundleStart);
Andrew Trick27c28ce2012-10-16 00:22:51 +00001335 HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
Jakob Stoklund Olesenad5e9692012-10-12 21:31:57 +00001336 HME.updateAllRanges(MI);
Lang Hames3dc7c512012-02-17 18:44:18 +00001337}